blob: ce8aa048b6c69e68604470e82559dd3744ecfd74 [file] [log] [blame]
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001/**
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
Andy Huang30e2c242012-01-06 18:14:30 -080017package com.android.mail.compose;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080018
Mindy Pereira326c6602012-01-04 15:32:42 -080019import android.app.ActionBar;
Andy Huang5c5fd572012-04-08 18:19:29 -070020import android.app.ActionBar.OnNavigationListener;
21import android.app.Activity;
Mindy Pereira82cc5662012-01-09 17:29:30 -080022import android.app.ActivityManager;
23import android.app.AlertDialog;
24import android.app.Dialog;
Tony Mantler2558b502013-07-09 10:53:34 -070025import android.app.DialogFragment;
Mindy Pereirab199d172012-08-13 11:04:03 -070026import android.app.Fragment;
Mindy Pereirab199d172012-08-13 11:04:03 -070027import android.app.FragmentTransaction;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -070028import android.app.LoaderManager;
Andrew Sapperstein05089f32013-10-01 17:00:03 -070029import android.content.ClipData;
Mindy Pereira6349a042012-01-04 11:25:01 -080030import android.content.ContentResolver;
Mindy Pereira82cc5662012-01-09 17:29:30 -080031import android.content.ContentValues;
Mindy Pereira6349a042012-01-04 11:25:01 -080032import android.content.Context;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -070033import android.content.CursorLoader;
Mindy Pereira82cc5662012-01-09 17:29:30 -080034import android.content.DialogInterface;
Mindy Pereira6349a042012-01-04 11:25:01 -080035import android.content.Intent;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -070036import android.content.Loader;
Mindy Pereira82cc5662012-01-09 17:29:30 -080037import android.content.pm.ActivityInfo;
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -070038import android.content.res.Resources;
Mindy Pereira7ed1c112012-01-18 10:59:25 -080039import android.database.Cursor;
Mindy Pereira6349a042012-01-04 11:25:01 -080040import android.net.Uri;
Andrew Sapperstein05089f32013-10-01 17:00:03 -070041import android.os.Build;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080042import android.os.Bundle;
Mindy Pereira82cc5662012-01-09 17:29:30 -080043import android.os.Handler;
44import android.os.HandlerThread;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -070045import android.os.ParcelFileDescriptor;
Alice Yang1ebc2db2013-03-14 21:21:44 -070046import android.os.Parcelable;
Mindy Pereira82cc5662012-01-09 17:29:30 -080047import android.provider.BaseColumns;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080048import android.text.Editable;
Mindy Pereira82cc5662012-01-09 17:29:30 -080049import android.text.Html;
mindyped9c2f02012-10-12 10:02:08 -070050import android.text.SpannableString;
Mindy Pereira82cc5662012-01-09 17:29:30 -080051import android.text.Spanned;
Paul Westbrookc1827622012-01-06 11:27:12 -080052import android.text.TextUtils;
Mindy Pereira82cc5662012-01-09 17:29:30 -080053import android.text.TextWatcher;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080054import android.text.util.Rfc822Token;
Mindy Pereirac17d0732011-12-29 10:46:19 -080055import android.text.util.Rfc822Tokenizer;
Mindy Pereira3cd4f402012-07-17 11:16:18 -070056import android.view.Gravity;
mindyp62d3ec72012-08-24 13:04:09 -070057import android.view.KeyEvent;
Mindy Pereira326c6602012-01-04 15:32:42 -080058import android.view.LayoutInflater;
Mindy Pereirab47f3e22011-12-13 14:25:04 -080059import android.view.Menu;
60import android.view.MenuInflater;
61import android.view.MenuItem;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080062import android.view.View;
63import android.view.View.OnClickListener;
Andy Huang5c5fd572012-04-08 18:19:29 -070064import android.view.ViewGroup;
Paul Westbrookb4931c62013-01-14 17:51:18 -080065import android.view.inputmethod.BaseInputConnection;
mindyp62d3ec72012-08-24 13:04:09 -070066import android.view.inputmethod.EditorInfo;
Mindy Pereira326c6602012-01-04 15:32:42 -080067import android.widget.ArrayAdapter;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080068import android.widget.Button;
Mindy Pereira433b1982012-04-03 11:53:07 -070069import android.widget.EditText;
Mindy Pereira6349a042012-01-04 11:25:01 -080070import android.widget.TextView;
Mindy Pereira013194c2012-01-06 15:09:33 -080071import android.widget.Toast;
Mindy Pereira7b56a612011-12-14 12:32:28 -080072
Mindy Pereirac17d0732011-12-29 10:46:19 -080073import com.android.common.Rfc822Validator;
Tony Mantler9f324232013-08-08 14:24:30 -070074import com.android.common.contacts.DataUsageStatUpdater;
Andy Huang5c5fd572012-04-08 18:19:29 -070075import com.android.ex.chips.RecipientEditTextView;
Scott Kennedy5680ec22013-01-07 13:15:20 -080076import com.android.mail.MailIntentService;
Andy Huang5c5fd572012-04-08 18:19:29 -070077import com.android.mail.R;
Andy Huang761522c2013-08-08 13:09:11 -070078import com.android.mail.analytics.Analytics;
Alice Yang1ebc2db2013-03-14 21:21:44 -070079import com.android.mail.browse.MessageHeaderView;
mindyp40882432012-09-06 11:07:40 -070080import com.android.mail.compose.AttachmentsView.AttachmentAddedOrDeletedListener;
Mindy Pereira9932dee2012-01-10 16:09:50 -080081import com.android.mail.compose.AttachmentsView.AttachmentFailureException;
Mindy Pereira5a85e2b2012-01-11 09:53:32 -080082import com.android.mail.compose.FromAddressSpinner.OnAccountChangedListener;
Andy Huang30e2c242012-01-06 18:14:30 -080083import com.android.mail.compose.QuotedTextView.RespondInlineListener;
Mindy Pereira33fe9082012-01-09 16:24:30 -080084import com.android.mail.providers.Account;
Andy Huang30e2c242012-01-06 18:14:30 -080085import com.android.mail.providers.Address;
86import com.android.mail.providers.Attachment;
Scott Kennedy5680ec22013-01-07 13:15:20 -080087import com.android.mail.providers.Folder;
Mindy Pereira47d0e652012-07-23 09:45:07 -070088import com.android.mail.providers.MailAppProvider;
Mindy Pereira3ce64e72012-01-13 14:29:45 -080089import com.android.mail.providers.Message;
Mindy Pereira82cc5662012-01-09 17:29:30 -080090import com.android.mail.providers.MessageModification;
Mindy Pereira92551d02012-04-05 11:31:12 -070091import com.android.mail.providers.ReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -080092import com.android.mail.providers.Settings;
Andy Huang30e2c242012-01-06 18:14:30 -080093import com.android.mail.providers.UIProvider;
Mindy Pereira3ca5bad2012-04-16 11:02:42 -070094import com.android.mail.providers.UIProvider.AccountCapabilities;
Mindy Pereira12575862012-03-21 16:30:54 -070095import com.android.mail.providers.UIProvider.DraftType;
Alice Yang1ebc2db2013-03-14 21:21:44 -070096import com.android.mail.ui.AttachmentTile.AttachmentPreview;
Paul Westbrook83e6b572013-02-05 16:22:42 -080097import com.android.mail.ui.FeedbackEnabledActivity;
Mindy Pereirafa20c1a2012-07-23 13:00:02 -070098import com.android.mail.ui.MailActivity;
Mindy Pereirab199d172012-08-13 11:04:03 -070099import com.android.mail.ui.WaitFragment;
Paul Westbrook92227f62012-03-20 10:32:51 -0700100import com.android.mail.utils.AccountUtils;
Mark Wei434f2942012-08-24 11:54:02 -0700101import com.android.mail.utils.AttachmentUtils;
mindypfebd2262012-11-13 17:45:09 -0800102import com.android.mail.utils.ContentProviderTask;
Paul Westbrookb334c902012-06-25 11:42:46 -0700103import com.android.mail.utils.LogTag;
Andy Huang30e2c242012-01-06 18:14:30 -0800104import com.android.mail.utils.LogUtils;
Andy Huang30e2c242012-01-06 18:14:30 -0800105import com.android.mail.utils.Utils;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800106import com.google.common.annotations.VisibleForTesting;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800107import com.google.common.collect.Lists;
Mindy Pereira4a27ea92012-01-05 15:55:25 -0800108import com.google.common.collect.Sets;
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800109
Paul Westbrook3c7f94d2012-10-23 14:13:00 -0700110import java.io.FileNotFoundException;
111import java.io.IOException;
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700112import java.io.UnsupportedEncodingException;
113import java.net.URLDecoder;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800114import java.util.ArrayList;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700115import java.util.Arrays;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800116import java.util.Collection;
Mindy Pereira75f66632012-01-11 11:42:02 -0800117import java.util.HashMap;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800118import java.util.HashSet;
119import java.util.List;
Paul Westbrook1c078cf2012-03-20 16:18:51 -0700120import java.util.Map.Entry;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700121import java.util.Set;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800122import java.util.concurrent.ConcurrentHashMap;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800123
124public class ComposeActivity extends Activity implements OnClickListener, OnNavigationListener,
Tony Mantler2558b502013-07-09 10:53:34 -0700125 RespondInlineListener, TextWatcher,
Alice Yanga990a712013-03-13 18:37:00 -0700126 AttachmentAddedOrDeletedListener, OnAccountChangedListener,
127 LoaderManager.LoaderCallbacks<Cursor>, TextView.OnEditorActionListener,
128 FeedbackEnabledActivity {
Mindy Pereira6349a042012-01-04 11:25:01 -0800129 // Identifiers for which type of composition this is
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700130 public static final int COMPOSE = -1;
131 public static final int REPLY = 0;
132 public static final int REPLY_ALL = 1;
133 public static final int FORWARD = 2;
134 public static final int EDIT_DRAFT = 3;
Mindy Pereira6349a042012-01-04 11:25:01 -0800135
136 // Integer extra holding one of the above compose action
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700137 protected static final String EXTRA_ACTION = "action";
Mindy Pereira6349a042012-01-04 11:25:01 -0800138
Mindy Pereira326689d2012-05-17 10:14:14 -0700139 private static final String EXTRA_SHOW_CC = "showCc";
140 private static final String EXTRA_SHOW_BCC = "showBcc";
mindyp1623f9b2012-11-21 12:41:16 -0800141 private static final String EXTRA_RESPONDED_INLINE = "respondedInline";
mindyp1d7e9142012-11-21 13:54:30 -0800142 private static final String EXTRA_SAVE_ENABLED = "saveEnabled";
Mindy Pereiraa34c9a02012-04-17 14:10:53 -0700143
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700144 private static final String UTF8_ENCODING_NAME = "UTF-8";
145
146 private static final String MAIL_TO = "mailto";
147
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700148 private static final String EXTRA_SUBJECT = "subject";
149
150 private static final String EXTRA_BODY = "body";
151
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700152 /**
153 * Expected to be html formatted text.
154 */
155 private static final String EXTRA_QUOTED_TEXT = "quotedText";
156
mindypd27b6ea2012-10-05 09:43:49 -0700157 protected static final String EXTRA_FROM_ACCOUNT_STRING = "fromAccountString";
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700158
Mark Wei62066e42012-09-13 12:07:02 -0700159 private static final String EXTRA_ATTACHMENT_PREVIEWS = "attachmentPreviews";
160
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700161 // Extra that we can get passed from other activities
Tony Mantler184ec732013-10-24 13:13:49 -0700162 @VisibleForTesting
163 protected static final String EXTRA_TO = "to";
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700164 private static final String EXTRA_CC = "cc";
165 private static final String EXTRA_BCC = "bcc";
166
Scott Kennedy60847252013-08-15 15:55:42 -0700167 /**
168 * An optional extra containing a {@link ContentValues} of values to be added to
169 * {@link SendOrSaveMessage#mValues}.
170 */
171 public static final String EXTRA_VALUES = "extra-values";
172
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700173 // List of all the fields
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700174 static final String[] ALL_EXTRAS = { EXTRA_SUBJECT, EXTRA_BODY, EXTRA_TO, EXTRA_CC, EXTRA_BCC,
175 EXTRA_QUOTED_TEXT };
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700176
Mindy Pereira82cc5662012-01-09 17:29:30 -0800177 private static SendOrSaveCallback sTestSendOrSaveCallback = null;
178 // Map containing information about requests to create new messages, and the id of the
179 // messages that were the result of those requests.
180 //
181 // This map is used when the activity that initiated the save a of a new message, is killed
182 // before the save has completed (and when we know the id of the newly created message). When
183 // a save is completed, the service that is running in the background, will update the map
184 //
185 // When a new ComposeActivity instance is created, it will attempt to use the information in
186 // the previously instantiated map. If ComposeActivity.onCreate() is called, with a bundle
187 // (restoring data from a previous instance), and the map hasn't been created, we will attempt
188 // to populate the map with data stored in shared preferences.
Andy Huang1f8f4dd2012-10-25 21:35:35 -0700189 // FIXME: values in this map are never read.
Mindy Pereira82cc5662012-01-09 17:29:30 -0800190 private static ConcurrentHashMap<Integer, Long> sRequestMessageIdMap = null;
Mindy Pereira6349a042012-01-04 11:25:01 -0800191 /**
192 * Notifies the {@code Activity} that the caller is an Email
193 * {@code Activity}, so that the back behavior may be modified accordingly.
194 *
195 * @see #onAppUpPressed
196 */
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700197 public static final String EXTRA_FROM_EMAIL_TASK = "fromemail";
Mindy Pereira6349a042012-01-04 11:25:01 -0800198
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700199 public static final String EXTRA_ATTACHMENTS = "attachments";
Paul Westbrookf97588b2012-03-20 11:11:37 -0700200
Scott Kennedy5680ec22013-01-07 13:15:20 -0800201 /** If set, we will clear notifications for this folder. */
202 public static final String EXTRA_NOTIFICATION_FOLDER = "extra-notification-folder";
203
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800204 // If this is a reply/forward then this extra will hold the original message
Mindy Pereira36bbcae2012-04-25 09:27:04 -0700205 private static final String EXTRA_IN_REFERENCE_TO_MESSAGE = "in-reference-to-message";
Mindy Pereirab18e5a92012-07-10 11:47:21 -0700206 // If this is a reply/forward then this extra will hold a uri we must query
207 // to get the original message.
208 protected static final String EXTRA_IN_REFERENCE_TO_MESSAGE_URI = "in-reference-to-message-uri";
Mark Wei434f2942012-08-24 11:54:02 -0700209 // If this is an action to edit an existing draft message, this extra will hold the
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700210 // draft message
211 private static final String ORIGINAL_DRAFT_MESSAGE = "original-draft-message";
Mindy Pereira4a27ea92012-01-05 15:55:25 -0800212 private static final String END_TOKEN = ", ";
Paul Westbrookb334c902012-06-25 11:42:46 -0700213 private static final String LOG_TAG = LogTag.getLogTag();
Mindy Pereira013194c2012-01-06 15:09:33 -0800214 // Request numbers for activities we start
215 private static final int RESULT_PICK_ATTACHMENT = 1;
216 private static final int RESULT_CREATE_ACCOUNT = 2;
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700217 // TODO(mindyp) set mime-type for auto send?
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700218 public static final String AUTO_SEND_ACTION = "com.android.mail.action.AUTO_SEND";
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700219
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700220 private static final String EXTRA_SELECTED_REPLY_FROM_ACCOUNT = "replyFromAccount";
221 private static final String EXTRA_REQUEST_ID = "requestId";
222 private static final String EXTRA_FOCUS_SELECTION_START = "focusSelectionStart";
Paul Westbrook176a1992013-07-22 13:57:19 -0700223 private static final String EXTRA_FOCUS_SELECTION_END = "focusSelectionEnd";
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700224 private static final String EXTRA_MESSAGE = "extraMessage";
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700225 private static final int REFERENCE_MESSAGE_LOADER = 0;
Mindy Pereirab199d172012-08-13 11:04:03 -0700226 private static final int LOADER_ACCOUNT_CURSOR = 1;
Alice Yanga990a712013-03-13 18:37:00 -0700227 private static final int INIT_DRAFT_USING_REFERENCE_MESSAGE = 2;
Mindy Pereira47d0e652012-07-23 09:45:07 -0700228 private static final String EXTRA_SELECTED_ACCOUNT = "selectedAccount";
Mindy Pereirab199d172012-08-13 11:04:03 -0700229 private static final String TAG_WAIT = "wait-fragment";
Andrew Sapperstein5cb71802013-10-01 18:31:20 -0700230 private static final String MIME_TYPE_ALL = "*/*";
Mindy Pereira2db7d4a2012-08-15 11:00:02 -0700231 private static final String MIME_TYPE_PHOTO = "image/*";
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800232
Andy Huang9f855d62013-05-30 17:15:03 -0700233 private static final String KEY_INNER_SAVED_STATE = "compose_state";
234
Mindy Pereira82cc5662012-01-09 17:29:30 -0800235 /**
236 * A single thread for running tasks in the background.
237 */
238 private Handler mSendSaveTaskHandler = null;
Mindy Pereirac17d0732011-12-29 10:46:19 -0800239 private RecipientEditTextView mTo;
240 private RecipientEditTextView mCc;
241 private RecipientEditTextView mBcc;
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800242 private Button mCcBccButton;
243 private CcBccView mCcBccView;
Mindy Pereira7b56a612011-12-14 12:32:28 -0800244 private AttachmentsView mAttachmentsView;
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700245 protected Account mAccount;
Tony Mantler59e69092013-08-14 11:05:00 -0700246 protected ReplyFromAccount mReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -0800247 private Settings mCachedSettings;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800248 private Rfc822Validator mValidator;
Mindy Pereira6349a042012-01-04 11:25:01 -0800249 private TextView mSubject;
250
Mindy Pereira326c6602012-01-04 15:32:42 -0800251 private ComposeModeAdapter mComposeModeAdapter;
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700252 protected int mComposeMode = -1;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800253 private boolean mForward;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800254 private QuotedTextView mQuotedTextView;
Tony Mantler59e69092013-08-14 11:05:00 -0700255 protected EditText mBodyView;
Mindy Pereira1a95a572012-01-05 12:21:29 -0800256 private View mFromStatic;
Mindy Pereira2eb17322012-03-07 10:07:34 -0800257 private TextView mFromStaticText;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800258 private View mFromSpinnerWrapper;
Mindy Pereira1883b342012-06-20 08:34:56 -0700259 @VisibleForTesting
260 protected FromAddressSpinner mFromSpinner;
Mindy Pereira013194c2012-01-06 15:09:33 -0800261 private boolean mAddingAttachment;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800262 private boolean mAttachmentsChanged;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800263 private boolean mTextChanged;
264 private boolean mReplyFromChanged;
265 private MenuItem mSave;
Mindy Pereirab3112a22012-06-20 12:10:03 -0700266 @VisibleForTesting
267 protected Message mRefMessage;
Mindy Pereira7ed1c112012-01-18 10:59:25 -0800268 private long mDraftId = UIProvider.INVALID_MESSAGE_ID;
269 private Message mDraft;
mindyp44a63392012-11-05 12:05:16 -0800270 private ReplyFromAccount mDraftAccount;
Mindy Pereira7ed1c112012-01-18 10:59:25 -0800271 private Object mDraftLock = new Object();
Andrew Sapperstein6aea7862013-10-24 19:59:51 -0700272 private View mAddAttachmentsButton;
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800273
Mindy Pereira326c6602012-01-04 15:32:42 -0800274 /**
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700275 * Boolean indicating whether ComposeActivity was launched from a Gmail controlled view.
276 */
277 private boolean mLaunchedFromEmail = false;
Mindy Pereiracbfb75a2012-06-25 14:52:23 -0700278 private RecipientTextWatcher mToListener;
279 private RecipientTextWatcher mCcListener;
280 private RecipientTextWatcher mBccListener;
Mindy Pereirab18e5a92012-07-10 11:47:21 -0700281 private Uri mRefMessageUri;
Alice Yanga990a712013-03-13 18:37:00 -0700282 private boolean mShowQuotedText = false;
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700283 protected Bundle mInnerSavedState;
Scott Kennedy60847252013-08-15 15:55:42 -0700284 private ContentValues mExtraValues = null;
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700285
mindyp1623f9b2012-11-21 12:41:16 -0800286 // Array of the outstanding send or save tasks. Access is synchronized
287 // with the object itself
288 /* package for testing */
289 @VisibleForTesting
290 public ArrayList<SendOrSaveTask> mActiveTasks = Lists.newArrayList();
291 // FIXME: this variable is never read. related to sRequestMessageIdMap.
292 private int mRequestId;
293 private String mSignature;
294 private Account[] mAccounts;
295 private boolean mRespondedInline;
Andy Huangdc97bf42013-08-15 16:52:45 -0700296 private boolean mPerformedSendOrDiscard = false;
mindyp1623f9b2012-11-21 12:41:16 -0800297
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700298 /**
Mindy Pereira326c6602012-01-04 15:32:42 -0800299 * Can be called from a non-UI thread.
300 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800301 public static void editDraft(Context launcher, Account account, Message message) {
Scott Kennedy60847252013-08-15 15:55:42 -0700302 launch(launcher, account, message, EDIT_DRAFT, null, null, null, null,
303 null /* extraValues */);
Mindy Pereira326c6602012-01-04 15:32:42 -0800304 }
305
Mindy Pereira6349a042012-01-04 11:25:01 -0800306 /**
307 * Can be called from a non-UI thread.
308 */
Mindy Pereira33fe9082012-01-09 16:24:30 -0800309 public static void compose(Context launcher, Account account) {
Scott Kennedy60847252013-08-15 15:55:42 -0700310 launch(launcher, account, null, COMPOSE, null, null, null, null, null /* extraValues */);
Mindy Pereira6349a042012-01-04 11:25:01 -0800311 }
312
313 /**
314 * Can be called from a non-UI thread.
315 */
Andrew Sapperstein3de76ec2013-07-16 12:08:15 -0700316 public static void composeToAddress(Context launcher, Account account, String toAddress) {
Scott Kennedy60847252013-08-15 15:55:42 -0700317 launch(launcher, account, null, COMPOSE, toAddress, null, null, null,
318 null /* extraValues */);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700319 }
320
321 /**
322 * Can be called from a non-UI thread.
323 */
324 public static void composeWithQuotedText(Context launcher, Account account,
Scott Kennedy60847252013-08-15 15:55:42 -0700325 String quotedText, String subject, final ContentValues extraValues) {
326 launch(launcher, account, null, COMPOSE, null, null, quotedText, subject, extraValues);
Andrew Sapperstein3de76ec2013-07-16 12:08:15 -0700327 }
328
329 /**
330 * Can be called from a non-UI thread.
331 */
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700332 public static void composeWithExtraValues(Context launcher, Account account,
333 String subject, final ContentValues extraValues) {
334 launch(launcher, account, null, COMPOSE, null, null, null, subject, extraValues);
335 }
336
337 /**
338 * Can be called from a non-UI thread.
339 */
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -0800340 public static Intent createReplyIntent(final Context launcher, final Account account,
341 final Uri messageUri, final boolean isReplyAll) {
342 return createActionIntent(launcher, account, messageUri, isReplyAll ? REPLY_ALL : REPLY);
343 }
344
345 /**
346 * Can be called from a non-UI thread.
347 */
348 public static Intent createForwardIntent(final Context launcher, final Account account,
349 final Uri messageUri) {
350 return createActionIntent(launcher, account, messageUri, FORWARD);
351 }
352
353 private static Intent createActionIntent(final Context launcher, final Account account,
354 final Uri messageUri, final int action) {
355 final Intent intent = new Intent(launcher, ComposeActivity.class);
356
Paul Westbrook6d2442b2013-07-17 17:51:51 -0700357 updateActionIntent(account, messageUri, action, intent);
358
359 return intent;
360 }
361
362 @VisibleForTesting
363 static Intent updateActionIntent(Account account, Uri messageUri, int action, Intent intent) {
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -0800364 intent.putExtra(EXTRA_FROM_EMAIL_TASK, true);
365 intent.putExtra(EXTRA_ACTION, action);
366 intent.putExtra(Utils.EXTRA_ACCOUNT, account);
367 intent.putExtra(EXTRA_IN_REFERENCE_TO_MESSAGE_URI, messageUri);
368
369 return intent;
370 }
371
372 /**
373 * Can be called from a non-UI thread.
374 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800375 public static void reply(Context launcher, Account account, Message message) {
Scott Kennedy60847252013-08-15 15:55:42 -0700376 launch(launcher, account, message, REPLY, null, null, null, null, null /* extraValues */);
Mindy Pereira6349a042012-01-04 11:25:01 -0800377 }
378
379 /**
380 * Can be called from a non-UI thread.
381 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800382 public static void replyAll(Context launcher, Account account, Message message) {
Scott Kennedy60847252013-08-15 15:55:42 -0700383 launch(launcher, account, message, REPLY_ALL, null, null, null, null,
384 null /* extraValues */);
Mindy Pereira6349a042012-01-04 11:25:01 -0800385 }
386
387 /**
388 * Can be called from a non-UI thread.
389 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800390 public static void forward(Context launcher, Account account, Message message) {
Scott Kennedy60847252013-08-15 15:55:42 -0700391 launch(launcher, account, message, FORWARD, null, null, null, null, null /* extraValues */);
Mindy Pereira6349a042012-01-04 11:25:01 -0800392 }
393
Alice Yang1ebc2db2013-03-14 21:21:44 -0700394 public static void reportRenderingFeedback(Context launcher, Account account, Message message,
395 String body) {
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700396 launch(launcher, account, message, FORWARD,
Scott Kennedy60847252013-08-15 15:55:42 -0700397 "android-gmail-readability@google.com", body, null, null, null /* extraValues */);
Alice Yang1ebc2db2013-03-14 21:21:44 -0700398 }
399
400 private static void launch(Context launcher, Account account, Message message, int action,
Scott Kennedy60847252013-08-15 15:55:42 -0700401 String toAddress, String body, String quotedText, String subject,
402 final ContentValues extraValues) {
Mindy Pereira6349a042012-01-04 11:25:01 -0800403 Intent intent = new Intent(launcher, ComposeActivity.class);
404 intent.putExtra(EXTRA_FROM_EMAIL_TASK, true);
405 intent.putExtra(EXTRA_ACTION, action);
406 intent.putExtra(Utils.EXTRA_ACCOUNT, account);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700407 if (action == EDIT_DRAFT) {
408 intent.putExtra(ORIGINAL_DRAFT_MESSAGE, message);
409 } else {
410 intent.putExtra(EXTRA_IN_REFERENCE_TO_MESSAGE, message);
411 }
Alice Yang1ebc2db2013-03-14 21:21:44 -0700412 if (toAddress != null) {
413 intent.putExtra(EXTRA_TO, toAddress);
414 }
415 if (body != null) {
416 intent.putExtra(EXTRA_BODY, body);
417 }
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700418 if (quotedText != null) {
419 intent.putExtra(EXTRA_QUOTED_TEXT, quotedText);
420 }
421 if (subject != null) {
422 intent.putExtra(EXTRA_SUBJECT, subject);
423 }
Scott Kennedy60847252013-08-15 15:55:42 -0700424 if (extraValues != null) {
425 LogUtils.d(LOG_TAG, "Launching with extraValues: %s", extraValues.toString());
426 intent.putExtra(EXTRA_VALUES, extraValues);
427 }
Mindy Pereira6349a042012-01-04 11:25:01 -0800428 launcher.startActivity(intent);
429 }
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800430
Andy Huang0a2a3462013-12-20 15:56:13 -0800431 public static void composeMailto(Context launcher, Account account, Uri mailto) {
432 final Intent intent = new Intent(Intent.ACTION_VIEW, mailto, launcher,
433 ComposeActivity.class);
434 intent.putExtra(EXTRA_FROM_EMAIL_TASK, true);
435 intent.putExtra(Utils.EXTRA_ACCOUNT, account);
436 launcher.startActivity(intent);
437 }
438
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800439 @Override
Scott Kennedyd9063902013-08-02 22:14:37 -0700440 protected void onCreate(Bundle savedInstanceState) {
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800441 super.onCreate(savedInstanceState);
Mindy Pereira3528d362012-01-05 14:39:44 -0800442 setContentView(R.layout.compose);
Andy Huang9f855d62013-05-30 17:15:03 -0700443 mInnerSavedState = (savedInstanceState != null) ?
444 savedInstanceState.getBundle(KEY_INNER_SAVED_STATE) : null;
Mindy Pereirab199d172012-08-13 11:04:03 -0700445 checkValidAccounts();
446 }
447
448 private void finishCreate() {
Andy Huang9f855d62013-05-30 17:15:03 -0700449 final Bundle savedState = mInnerSavedState;
Mindy Pereira3528d362012-01-05 14:39:44 -0800450 findViews();
Mindy Pereira818143e2012-01-11 13:59:49 -0800451 Intent intent = getIntent();
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700452 Message message;
Mark Wei62066e42012-09-13 12:07:02 -0700453 ArrayList<AttachmentPreview> previews;
Alice Yanga990a712013-03-13 18:37:00 -0700454 mShowQuotedText = false;
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700455 CharSequence quotedText = null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700456 int action;
Mindy Pereira47d0e652012-07-23 09:45:07 -0700457 // Check for any of the possibly supplied accounts.;
458 Account account = null;
Andy Huang9f855d62013-05-30 17:15:03 -0700459 if (hadSavedInstanceStateMessage(savedState)) {
460 action = savedState.getInt(EXTRA_ACTION, COMPOSE);
461 account = savedState.getParcelable(Utils.EXTRA_ACCOUNT);
462 message = (Message) savedState.getParcelable(EXTRA_MESSAGE);
Mark Wei62066e42012-09-13 12:07:02 -0700463
Andy Huang9f855d62013-05-30 17:15:03 -0700464 previews = savedState.getParcelableArrayList(EXTRA_ATTACHMENT_PREVIEWS);
465 mRefMessage = (Message) savedState.getParcelable(EXTRA_IN_REFERENCE_TO_MESSAGE);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700466 quotedText = savedState.getCharSequence(EXTRA_QUOTED_TEXT);
Scott Kennedy44d44812013-08-19 14:18:31 -0700467
468 mExtraValues = savedState.getParcelable(EXTRA_VALUES);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700469 } else {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700470 account = obtainAccount(intent);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700471 action = intent.getIntExtra(EXTRA_ACTION, COMPOSE);
472 // Initialize the message from the message in the intent
473 message = (Message) intent.getParcelableExtra(ORIGINAL_DRAFT_MESSAGE);
Mark Wei62066e42012-09-13 12:07:02 -0700474 previews = intent.getParcelableArrayListExtra(EXTRA_ATTACHMENT_PREVIEWS);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700475 mRefMessage = (Message) intent.getParcelableExtra(EXTRA_IN_REFERENCE_TO_MESSAGE);
Mindy Pereirab18e5a92012-07-10 11:47:21 -0700476 mRefMessageUri = (Uri) intent.getParcelableExtra(EXTRA_IN_REFERENCE_TO_MESSAGE_URI);
Andy Huang4fe0af82013-08-20 17:24:51 -0700477
478 if (Analytics.isLoggable()) {
479 if (intent.getBooleanExtra(Utils.EXTRA_FROM_NOTIFICATION, false)) {
480 Analytics.getInstance().sendEvent(
481 "notification_action", "compose", getActionString(action), 0);
482 }
483 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700484 }
Mark Wei62066e42012-09-13 12:07:02 -0700485 mAttachmentsView.setAttachmentPreviews(previews);
Paul Westbrook92227f62012-03-20 10:32:51 -0700486
487 setAccount(account);
Mindy Pereira818143e2012-01-11 13:59:49 -0800488 if (mAccount == null) {
489 return;
490 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700491
Scott Kennedyfe853d32013-06-19 11:47:35 -0700492 initRecipients();
493
Scott Kennedy5680ec22013-01-07 13:15:20 -0800494 // Clear the notification and mark the conversation as seen, if necessary
495 final Folder notificationFolder =
496 intent.getParcelableExtra(EXTRA_NOTIFICATION_FOLDER);
497 if (notificationFolder != null) {
498 final Intent clearNotifIntent =
499 new Intent(MailIntentService.ACTION_CLEAR_NEW_MAIL_NOTIFICATIONS);
Scott Kennedyd5edd2d2012-12-05 11:11:32 -0800500 clearNotifIntent.setPackage(getPackageName());
Scott Kennedy48cfe462013-04-10 11:32:02 -0700501 clearNotifIntent.putExtra(Utils.EXTRA_ACCOUNT, account);
502 clearNotifIntent.putExtra(Utils.EXTRA_FOLDER, notificationFolder);
Scott Kennedy5680ec22013-01-07 13:15:20 -0800503
504 startService(clearNotifIntent);
505 }
506
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700507 if (intent.getBooleanExtra(EXTRA_FROM_EMAIL_TASK, false)) {
508 mLaunchedFromEmail = true;
509 } else if (Intent.ACTION_SEND.equals(intent.getAction())) {
510 final Uri dataUri = intent.getData();
511 if (dataUri != null) {
512 final String dataScheme = intent.getData().getScheme();
513 final String accountScheme = mAccount.composeIntentUri.getScheme();
514 mLaunchedFromEmail = TextUtils.equals(dataScheme, accountScheme);
515 }
516 }
517
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700518 if (mRefMessageUri != null) {
Alice Yanga990a712013-03-13 18:37:00 -0700519 mShowQuotedText = true;
520 mComposeMode = action;
521 getLoaderManager().initLoader(INIT_DRAFT_USING_REFERENCE_MESSAGE, null, this);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700522 return;
523 } else if (message != null && action != EDIT_DRAFT) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700524 initFromDraftMessage(message);
525 initQuotedTextFromRefMessage(mRefMessage, action);
Andy Huang9f855d62013-05-30 17:15:03 -0700526 showCcBcc(savedState);
Alice Yanga990a712013-03-13 18:37:00 -0700527 mShowQuotedText = message.appendRefMessageContent;
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700528 // if we should be showing quoted text but mRefMessage is null
529 // and we have some quotedText, display that
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700530 if (mShowQuotedText && mRefMessage == null) {
531 if (quotedText != null) {
532 initQuotedText(quotedText, false /* shouldQuoteText */);
533 } else if (mExtraValues != null) {
534 initExtraValues(mExtraValues);
535 return;
536 }
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700537 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700538 } else if (action == EDIT_DRAFT) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700539 initFromDraftMessage(message);
Scott Kennedy8960f0a2012-11-07 15:35:50 -0800540 boolean showBcc = !TextUtils.isEmpty(message.getBcc());
541 boolean showCc = showBcc || !TextUtils.isEmpty(message.getCc());
Mindy Pereiraef388302012-06-18 19:07:44 -0700542 mCcBccView.show(false, showCc, showBcc);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700543 // Update the action to the draft type of the previous draft
544 switch (message.draftType) {
545 case UIProvider.DraftType.REPLY:
546 action = REPLY;
547 break;
548 case UIProvider.DraftType.REPLY_ALL:
549 action = REPLY_ALL;
550 break;
551 case UIProvider.DraftType.FORWARD:
552 action = FORWARD;
553 break;
554 case UIProvider.DraftType.COMPOSE:
555 default:
556 action = COMPOSE;
557 break;
558 }
Alice Yanga990a712013-03-13 18:37:00 -0700559 LogUtils.d(LOG_TAG, "Previous draft had action type: %d", action);
560
561 mShowQuotedText = message.appendRefMessageContent;
562 if (message.refMessageUri != null) {
563 // If we're editing an existing draft that was in reference to an existing message,
564 // still need to load that original message since we might need to refer to the
565 // original sender and recipients if user switches "reply <-> reply-all".
566 mRefMessageUri = message.refMessageUri;
567 mComposeMode = action;
568 getLoaderManager().initLoader(REFERENCE_MESSAGE_LOADER, null, this);
569 return;
570 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700571 } else if ((action == REPLY || action == REPLY_ALL || action == FORWARD)) {
572 if (mRefMessage != null) {
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -0800573 initFromRefMessage(action);
Alice Yanga990a712013-03-13 18:37:00 -0700574 mShowQuotedText = true;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700575 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700576 } else {
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700577 if (initFromExtras(intent)) {
578 return;
579 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700580 }
Alice Yanga990a712013-03-13 18:37:00 -0700581
582 mComposeMode = action;
Andy Huang9f855d62013-05-30 17:15:03 -0700583 finishSetup(action, intent, savedState);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700584 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700585
Mindy Pereirab199d172012-08-13 11:04:03 -0700586 private void checkValidAccounts() {
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700587 final Account[] allAccounts = AccountUtils.getAccounts(this);
588 if (allAccounts == null || allAccounts.length == 0) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700589 final Intent noAccountIntent = MailAppProvider.getNoAccountIntent(this);
590 if (noAccountIntent != null) {
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700591 mAccounts = null;
Mindy Pereirab199d172012-08-13 11:04:03 -0700592 startActivityForResult(noAccountIntent, RESULT_CREATE_ACCOUNT);
593 }
594 } else {
mindyp26d4d2d2012-09-18 17:30:32 -0700595 // If none of the accounts are syncing, setup a watcher.
Mindy Pereirab199d172012-08-13 11:04:03 -0700596 boolean anySyncing = false;
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700597 for (Account a : allAccounts) {
Paul Westbrookdfa1dec2012-09-26 16:27:28 -0700598 if (a.isAccountReady()) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700599 anySyncing = true;
600 break;
601 }
602 }
603 if (!anySyncing) {
604 // There are accounts, but none are sync'd, which is just like having no accounts.
605 mAccounts = null;
606 getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, null, this);
607 return;
608 }
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700609 mAccounts = AccountUtils.getSyncingAccounts(this);
Mindy Pereirab199d172012-08-13 11:04:03 -0700610 finishCreate();
611 }
612 }
613
Mindy Pereira47d0e652012-07-23 09:45:07 -0700614 private Account obtainAccount(Intent intent) {
615 Account account = null;
616 Object accountExtra = null;
617 if (intent != null && intent.getExtras() != null) {
618 accountExtra = intent.getExtras().get(Utils.EXTRA_ACCOUNT);
619 if (accountExtra instanceof Account) {
620 return (Account) accountExtra;
mindyp7ae042e2012-08-27 13:27:37 -0700621 } else if (accountExtra instanceof String) {
622 // This is the Account attached to the widget compose intent.
623 account = Account.newinstance((String)accountExtra);
624 if (account != null) {
625 return account;
626 }
Mindy Pereira47d0e652012-07-23 09:45:07 -0700627 }
mindyp5ee9dc42013-01-08 09:54:54 -0800628 accountExtra = intent.hasExtra(Utils.EXTRA_ACCOUNT) ?
629 intent.getStringExtra(Utils.EXTRA_ACCOUNT) :
630 intent.getStringExtra(EXTRA_SELECTED_ACCOUNT);
Mindy Pereira47d0e652012-07-23 09:45:07 -0700631 }
632 if (account == null) {
mindyp06174462012-10-12 09:11:27 -0700633 MailAppProvider provider = MailAppProvider.getInstance();
634 String lastAccountUri = provider.getLastSentFromAccount();
635 if (TextUtils.isEmpty(lastAccountUri)) {
636 lastAccountUri = provider.getLastViewedAccount();
637 }
Mindy Pereira47d0e652012-07-23 09:45:07 -0700638 if (!TextUtils.isEmpty(lastAccountUri)) {
639 accountExtra = Uri.parse(lastAccountUri);
640 }
641 }
Mindy Pereirab199d172012-08-13 11:04:03 -0700642 if (mAccounts != null && mAccounts.length > 0) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700643 if (accountExtra instanceof String && !TextUtils.isEmpty((String) accountExtra)) {
644 // For backwards compatibility, we need to check account
645 // names.
Mindy Pereirab199d172012-08-13 11:04:03 -0700646 for (Account a : mAccounts) {
Tony Mantler79b11562013-10-09 15:31:50 -0700647 if (a.getEmailAddress().equals(accountExtra)) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700648 account = a;
649 }
650 }
651 } else if (accountExtra instanceof Uri) {
652 // The uri of the last viewed account is what is stored in
653 // the current code base.
Mindy Pereirab199d172012-08-13 11:04:03 -0700654 for (Account a : mAccounts) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700655 if (a.uri.equals(accountExtra)) {
656 account = a;
657 }
658 }
Mindy Pereirab199d172012-08-13 11:04:03 -0700659 }
660 if (account == null) {
661 account = mAccounts[0];
Mindy Pereira47d0e652012-07-23 09:45:07 -0700662 }
663 }
664 return account;
665 }
666
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700667 protected void finishSetup(int action, Intent intent, Bundle savedInstanceState) {
mindyp34a3c562012-11-06 15:12:15 -0800668 setFocus(action);
Mindy Pereiraf7fc6c32012-06-19 15:18:33 -0700669 // Don't bother with the intent if we have procured a message from the
670 // intent already.
671 if (!hadSavedInstanceStateMessage(savedInstanceState)) {
672 initAttachmentsFromIntent(intent);
673 }
Alice Yanga990a712013-03-13 18:37:00 -0700674 initActionBar();
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700675 initFromSpinner(savedInstanceState != null ? savedInstanceState : intent.getExtras(),
676 action);
mindypd4a48662012-11-08 17:13:49 -0800677
678 // If this is a draft message, the draft account is whatever account was
679 // used to open the draft message in Compose.
680 if (mDraft != null) {
681 mDraftAccount = mReplyFromAccount;
682 }
683
Mindy Pereira75f66632012-01-11 11:42:02 -0800684 initChangeListeners();
Mindy Pereira326689d2012-05-17 10:14:14 -0700685 updateHideOrShowCcBcc();
Alice Yanga990a712013-03-13 18:37:00 -0700686 updateHideOrShowQuotedText(mShowQuotedText);
mindyp1623f9b2012-11-21 12:41:16 -0800687
Andy Huang9f855d62013-05-30 17:15:03 -0700688 mRespondedInline = mInnerSavedState != null ?
689 mInnerSavedState.getBoolean(EXTRA_RESPONDED_INLINE) : false;
mindyp1623f9b2012-11-21 12:41:16 -0800690 if (mRespondedInline) {
691 mQuotedTextView.setVisibility(View.GONE);
692 }
Mindy Pereira71c9e562012-05-17 11:01:02 -0700693 }
694
Scott Kennedyff8553f2013-04-05 20:57:44 -0700695 private static boolean hadSavedInstanceStateMessage(final Bundle savedInstanceState) {
Mindy Pereiraf7fc6c32012-06-19 15:18:33 -0700696 return savedInstanceState != null && savedInstanceState.containsKey(EXTRA_MESSAGE);
697 }
698
Mindy Pereira71c9e562012-05-17 11:01:02 -0700699 private void updateHideOrShowQuotedText(boolean showQuotedText) {
700 mQuotedTextView.updateCheckedState(showQuotedText);
mindyp40882432012-09-06 11:07:40 -0700701 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
Mindy Pereira433b1982012-04-03 11:53:07 -0700702 }
703
704 private void setFocus(int action) {
705 if (action == EDIT_DRAFT) {
706 int type = mDraft.draftType;
707 switch (type) {
708 case UIProvider.DraftType.COMPOSE:
709 case UIProvider.DraftType.FORWARD:
710 action = COMPOSE;
711 break;
712 case UIProvider.DraftType.REPLY:
713 case UIProvider.DraftType.REPLY_ALL:
714 default:
715 action = REPLY;
716 break;
717 }
718 }
719 switch (action) {
720 case FORWARD:
721 case COMPOSE:
mindyp27083062012-11-15 09:02:01 -0800722 if (TextUtils.isEmpty(mTo.getText())) {
723 mTo.requestFocus();
724 break;
725 }
Scott Kennedyff8553f2013-04-05 20:57:44 -0700726 //$FALL-THROUGH$
Mindy Pereira433b1982012-04-03 11:53:07 -0700727 case REPLY:
728 case REPLY_ALL:
729 default:
730 focusBody();
731 break;
732 }
733 }
734
735 /**
736 * Focus the body of the message.
737 */
738 public void focusBody() {
739 mBodyView.requestFocus();
740 int length = mBodyView.getText().length();
741
742 int signatureStartPos = getSignatureStartPosition(
743 mSignature, mBodyView.getText().toString());
744 if (signatureStartPos > -1) {
745 // In case the user deleted the newlines...
746 mBodyView.setSelection(signatureStartPos);
mindyp8743cfc2012-09-18 13:29:08 -0700747 } else if (length >= 0) {
Mindy Pereira433b1982012-04-03 11:53:07 -0700748 // Move cursor to the end.
749 mBodyView.setSelection(length);
750 }
Mindy Pereira1a95a572012-01-05 12:21:29 -0800751 }
752
753 @Override
Andy Huang761522c2013-08-08 13:09:11 -0700754 protected void onStart() {
755 super.onStart();
756
757 Analytics.getInstance().activityStart(this);
758 }
759
760 @Override
761 protected void onStop() {
762 super.onStop();
763
764 Analytics.getInstance().activityStop(this);
765 }
766
767 @Override
Mindy Pereira1a95a572012-01-05 12:21:29 -0800768 protected void onResume() {
769 super.onResume();
770 // Update the from spinner as other accounts
771 // may now be available.
Mindy Pereira818143e2012-01-11 13:59:49 -0800772 if (mFromSpinner != null && mAccount != null) {
Paul Westbrookc97ec3e2013-07-12 18:17:19 -0700773 mFromSpinner.initialize(mComposeMode, mAccount, mAccounts, mRefMessage);
Mindy Pereira818143e2012-01-11 13:59:49 -0800774 }
Mindy Pereira1a95a572012-01-05 12:21:29 -0800775 }
776
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800777 @Override
778 protected void onPause() {
779 super.onPause();
780
Mindy Pereiraa2148332012-07-02 13:54:14 -0700781 // When the user exits the compose view, see if this draft needs saving.
Yorke Lee3d7048e2012-09-19 14:19:25 -0700782 // Don't save unnecessary drafts if we are only changing the orientation.
783 if (!isChangingConfigurations()) {
Mindy Pereiraa2148332012-07-02 13:54:14 -0700784 saveIfNeeded();
Andy Huangdc97bf42013-08-15 16:52:45 -0700785
Andy Huange003b4c2013-08-16 10:32:05 -0700786 if (isFinishing() && !mPerformedSendOrDiscard && !isBlank()) {
Andy Huangdc97bf42013-08-15 16:52:45 -0700787 // log saving upon backing out of activity. (we avoid logging every sendOrSave()
788 // because that method can be invoked many times in a single compose session.)
789 logSendOrSave(true /* save */);
790 }
Mindy Pereiraa2148332012-07-02 13:54:14 -0700791 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800792 }
793
794 @Override
795 protected final void onActivityResult(int request, int result, Intent data) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700796 if (request == RESULT_PICK_ATTACHMENT && result == RESULT_OK) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800797 addAttachmentAndUpdateView(data);
Mindy Pereirab199d172012-08-13 11:04:03 -0700798 mAddingAttachment = false;
799 } else if (request == RESULT_CREATE_ACCOUNT) {
Alice Yanga990a712013-03-13 18:37:00 -0700800 // We were waiting for the user to create an account
Mindy Pereirab199d172012-08-13 11:04:03 -0700801 if (result != RESULT_OK) {
802 finish();
803 } else {
804 // Watch for accounts to show up!
805 // restart the loader to get the updated list of accounts
806 getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, null, this);
807 showWaitFragment(null);
808 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800809 }
810 }
811
812 @Override
Scott Kennedyd9063902013-08-02 22:14:37 -0700813 protected final void onRestoreInstanceState(Bundle savedInstanceState) {
Yorke Lee7bec2b92013-04-26 08:31:42 -0700814 final boolean hasAccounts = mAccounts != null && mAccounts.length > 0;
815 if (hasAccounts) {
816 clearChangeListeners();
817 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700818 super.onRestoreInstanceState(savedInstanceState);
Andy Huang9f855d62013-05-30 17:15:03 -0700819 if (mInnerSavedState != null) {
820 if (mInnerSavedState.containsKey(EXTRA_FOCUS_SELECTION_START)) {
821 int selectionStart = mInnerSavedState.getInt(EXTRA_FOCUS_SELECTION_START);
822 int selectionEnd = mInnerSavedState.getInt(EXTRA_FOCUS_SELECTION_END);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700823 // There should be a focus and it should be an EditText since we
824 // only save these extras if these conditions are true.
825 EditText focusEditText = (EditText) getCurrentFocus();
826 final int length = focusEditText.getText().length();
827 if (selectionStart < length && selectionEnd < length) {
828 focusEditText.setSelection(selectionStart, selectionEnd);
829 }
830 }
831 }
Yorke Lee7bec2b92013-04-26 08:31:42 -0700832 if (hasAccounts) {
833 initChangeListeners();
834 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700835 }
836
837 @Override
Scott Kennedyd9063902013-08-02 22:14:37 -0700838 protected final void onSaveInstanceState(Bundle state) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800839 super.onSaveInstanceState(state);
Andy Huang9f855d62013-05-30 17:15:03 -0700840 final Bundle inner = new Bundle();
841 saveState(inner);
842 state.putBundle(KEY_INNER_SAVED_STATE, inner);
843 }
844
845 private void saveState(Bundle state) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700846 // We have no accounts so there is nothing to compose, and therefore, nothing to save.
847 if (mAccounts == null || mAccounts.length == 0) {
848 return;
849 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700850 // The framework is happy to save and restore the selection but only if it also saves and
851 // restores the contents of the edit text. That's a lot of text to put in a bundle so we do
852 // this manually.
853 View focus = getCurrentFocus();
854 if (focus != null && focus instanceof EditText) {
855 EditText focusEditText = (EditText) focus;
856 state.putInt(EXTRA_FOCUS_SELECTION_START, focusEditText.getSelectionStart());
857 state.putInt(EXTRA_FOCUS_SELECTION_END, focusEditText.getSelectionEnd());
858 }
Paul Westbrook6273e962012-04-23 10:44:15 -0700859
860 final List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
Paul Westbrook151f1ad2012-04-24 09:13:00 -0700861 final int selectedPos = mFromSpinner.getSelectedItemPosition();
Mindy Pereirad90f7ac2012-06-27 10:31:06 -0700862 final ReplyFromAccount selectedReplyFromAccount = (replyFromAccounts != null
863 && replyFromAccounts.size() > 0 && replyFromAccounts.size() > selectedPos) ?
864 replyFromAccounts.get(selectedPos) : null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700865 if (selectedReplyFromAccount != null) {
866 state.putString(EXTRA_SELECTED_REPLY_FROM_ACCOUNT, selectedReplyFromAccount.serialize()
867 .toString());
868 state.putParcelable(Utils.EXTRA_ACCOUNT, selectedReplyFromAccount.account);
869 } else {
870 state.putParcelable(Utils.EXTRA_ACCOUNT, mAccount);
871 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800872
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700873 if (mDraftId == UIProvider.INVALID_MESSAGE_ID && mRequestId !=0) {
874 // We don't have a draft id, and we have a request id,
875 // save the request id.
876 state.putInt(EXTRA_REQUEST_ID, mRequestId);
877 }
878
879 // We want to restore the current mode after a pause
880 // or rotation.
881 int mode = getMode();
882 state.putInt(EXTRA_ACTION, mode);
883
mindype7b76aa2012-11-14 16:19:13 -0800884 final Message message = createMessage(selectedReplyFromAccount, mode);
Andy Huang1f8f4dd2012-10-25 21:35:35 -0700885 if (mDraft != null) {
mindype7b76aa2012-11-14 16:19:13 -0800886 message.id = mDraft.id;
887 message.serverId = mDraft.serverId;
888 message.uri = mDraft.uri;
Andy Huang1f8f4dd2012-10-25 21:35:35 -0700889 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700890 state.putParcelable(EXTRA_MESSAGE, message);
891
892 if (mRefMessage != null) {
893 state.putParcelable(EXTRA_IN_REFERENCE_TO_MESSAGE, mRefMessage);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700894 } else if (message.appendRefMessageContent) {
895 // If we have no ref message but should be appending
896 // ref message content, we have orphaned quoted text. Save it.
897 state.putCharSequence(EXTRA_QUOTED_TEXT, mQuotedTextView.getQuotedTextIfIncluded());
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700898 }
Mindy Pereira326689d2012-05-17 10:14:14 -0700899 state.putBoolean(EXTRA_SHOW_CC, mCcBccView.isCcVisible());
900 state.putBoolean(EXTRA_SHOW_BCC, mCcBccView.isBccVisible());
mindyp1623f9b2012-11-21 12:41:16 -0800901 state.putBoolean(EXTRA_RESPONDED_INLINE, mRespondedInline);
mindyp816b3f02012-12-11 08:25:04 -0800902 state.putBoolean(EXTRA_SAVE_ENABLED, mSave != null && mSave.isEnabled());
Mark Wei62066e42012-09-13 12:07:02 -0700903 state.putParcelableArrayList(
904 EXTRA_ATTACHMENT_PREVIEWS, mAttachmentsView.getAttachmentPreviews());
Scott Kennedy44d44812013-08-19 14:18:31 -0700905
906 state.putParcelable(EXTRA_VALUES, mExtraValues);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700907 }
908
909 private int getMode() {
910 int mode = ComposeActivity.COMPOSE;
911 ActionBar actionBar = getActionBar();
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700912 if (actionBar != null
913 && actionBar.getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700914 mode = actionBar.getSelectedNavigationIndex();
915 }
916 return mode;
917 }
918
919 private Message createMessage(ReplyFromAccount selectedReplyFromAccount, int mode) {
920 Message message = new Message();
921 message.id = UIProvider.INVALID_MESSAGE_ID;
Andy Huangd47877e2012-08-09 19:31:24 -0700922 message.serverId = null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700923 message.uri = null;
924 message.conversationUri = null;
925 message.subject = mSubject.getText().toString();
926 message.snippet = null;
Scott Kennedy8960f0a2012-11-07 15:35:50 -0800927 message.setTo(formatSenders(mTo.getText().toString()));
928 message.setCc(formatSenders(mCc.getText().toString()));
929 message.setBcc(formatSenders(mBcc.getText().toString()));
930 message.setReplyTo(null);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700931 message.dateReceivedMs = 0;
Paul Westbrookb4931c62013-01-14 17:51:18 -0800932 final String htmlBody = Html.toHtml(removeComposingSpans(mBodyView.getText()));
933 final StringBuilder fullBody = new StringBuilder(htmlBody);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700934 message.bodyHtml = fullBody.toString();
935 message.bodyText = mBodyView.getText().toString();
936 message.embedsExternalResources = false;
Alice Yanga990a712013-03-13 18:37:00 -0700937 message.refMessageUri = mRefMessage != null ? mRefMessage.uri : null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700938 message.appendRefMessageContent = mQuotedTextView.getQuotedTextIfIncluded() != null;
939 ArrayList<Attachment> attachments = mAttachmentsView.getAttachments();
940 message.hasAttachments = attachments != null && attachments.size() > 0;
941 message.attachmentListUri = null;
942 message.messageFlags = 0;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700943 message.alwaysShowImages = false;
944 message.attachmentsJson = Attachment.toJSONArray(attachments);
945 CharSequence quotedText = mQuotedTextView.getQuotedText();
946 message.quotedTextOffset = !TextUtils.isEmpty(quotedText) ? QuotedTextView
947 .getQuotedTextOffset(quotedText.toString()) : -1;
948 message.accountUri = null;
Tony Mantlerbb036ff72013-10-18 14:03:43 -0700949 final String email = selectedReplyFromAccount != null ? selectedReplyFromAccount.address
950 : mAccount != null ? mAccount.getEmailAddress() : null;
951 // TODO: this behavior is wrong. Pull the name from selectedReplyFromAccount.name
952 final String senderName = mAccount != null ? mAccount.getSenderName() : null;
953 final Address address = new Address(senderName, email);
954 message.setFrom(address.pack());
Andy Huang1f8f4dd2012-10-25 21:35:35 -0700955 message.draftType = getDraftType(mode);
mindype7b76aa2012-11-14 16:19:13 -0800956 return message;
Andy Huang1f8f4dd2012-10-25 21:35:35 -0700957 }
958
Scott Kennedyff8553f2013-04-05 20:57:44 -0700959 private static String formatSenders(final String string) {
Mindy Pereira3c911582012-08-09 16:59:09 -0700960 if (!TextUtils.isEmpty(string) && string.charAt(string.length() - 1) == ',') {
961 return string.substring(0, string.length() - 1);
962 }
963 return string;
964 }
965
Mindy Pereira818143e2012-01-11 13:59:49 -0800966 @VisibleForTesting
967 void setAccount(Account account) {
Mindy Pereirabb5217e2012-04-17 11:08:29 -0700968 if (account == null) {
969 return;
970 }
Mindy Pereira23e9fde2012-03-20 15:08:24 -0700971 if (!account.equals(mAccount)) {
972 mAccount = account;
Paul Westbrookb1f573c2012-04-06 11:38:28 -0700973 mCachedSettings = mAccount.settings;
974 appendSignature();
Mindy Pereira23e9fde2012-03-20 15:08:24 -0700975 }
Mindy Pereirafa20c1a2012-07-23 13:00:02 -0700976 if (mAccount != null) {
Tony Mantler79b11562013-10-09 15:31:50 -0700977 MailActivity.setNfcMessage(mAccount.getEmailAddress());
Mindy Pereirafa20c1a2012-07-23 13:00:02 -0700978 }
Mindy Pereira818143e2012-01-11 13:59:49 -0800979 }
980
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700981 private void initFromSpinner(Bundle bundle, int action) {
982 if (action == EDIT_DRAFT && mDraft.draftType == UIProvider.DraftType.COMPOSE) {
Mindy Pereira62de1b12012-04-06 12:17:56 -0700983 action = COMPOSE;
984 }
Paul Westbrookc97ec3e2013-07-12 18:17:19 -0700985 mFromSpinner.initialize(action, mAccount, mAccounts, mRefMessage);
986
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700987 if (bundle != null) {
988 if (bundle.containsKey(EXTRA_SELECTED_REPLY_FROM_ACCOUNT)) {
989 mReplyFromAccount = ReplyFromAccount.deserialize(mAccount,
990 bundle.getString(EXTRA_SELECTED_REPLY_FROM_ACCOUNT));
991 } else if (bundle.containsKey(EXTRA_FROM_ACCOUNT_STRING)) {
Paul Westbrookc97ec3e2013-07-12 18:17:19 -0700992 final String accountString = bundle.getString(EXTRA_FROM_ACCOUNT_STRING);
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700993 mReplyFromAccount = mFromSpinner.getMatchingReplyFromAccount(accountString);
994 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700995 }
996 if (mReplyFromAccount == null) {
997 if (mDraft != null) {
998 mReplyFromAccount = getReplyFromAccountFromDraft(mAccount, mDraft);
999 } else if (mRefMessage != null) {
1000 mReplyFromAccount = getReplyFromAccountForReply(mAccount, mRefMessage);
1001 }
Mindy Pereira62de1b12012-04-06 12:17:56 -07001002 }
1003 if (mReplyFromAccount == null) {
Andy Huang238aa472012-10-30 17:45:17 -07001004 mReplyFromAccount = getDefaultReplyFromAccount(mAccount);
Mindy Pereira62de1b12012-04-06 12:17:56 -07001005 }
Mindy Pereira9a42bb42012-04-18 15:21:33 -07001006
Mindy Pereira62de1b12012-04-06 12:17:56 -07001007 mFromSpinner.setCurrentAccount(mReplyFromAccount);
Mindy Pereira9a42bb42012-04-18 15:21:33 -07001008
Mindy Pereira62de1b12012-04-06 12:17:56 -07001009 if (mFromSpinner.getCount() > 1) {
Mindy Pereiraa83e7082012-03-30 08:53:11 -07001010 // If there is only 1 account, just show that account.
1011 // Otherwise, give the user the ability to choose which account to
Mindy Pereira62de1b12012-04-06 12:17:56 -07001012 // send mail from / save drafts to.
1013 mFromStatic.setVisibility(View.GONE);
Tony Mantlerbb036ff72013-10-18 14:03:43 -07001014 // TODO: do we want name or address here?
Paul Westbrookc97ec3e2013-07-12 18:17:19 -07001015 mFromStaticText.setText(mReplyFromAccount.name);
Mindy Pereira62de1b12012-04-06 12:17:56 -07001016 mFromSpinnerWrapper.setVisibility(View.VISIBLE);
Mindy Pereiraa83e7082012-03-30 08:53:11 -07001017 } else {
1018 mFromStatic.setVisibility(View.VISIBLE);
Tony Mantlerbb036ff72013-10-18 14:03:43 -07001019 // TODO: do we want name or address here?
Paul Westbrookc97ec3e2013-07-12 18:17:19 -07001020 mFromStaticText.setText(mReplyFromAccount.name);
Mindy Pereiraa83e7082012-03-30 08:53:11 -07001021 mFromSpinnerWrapper.setVisibility(View.GONE);
Mindy Pereiraa83e7082012-03-30 08:53:11 -07001022 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001023 }
1024
Mindy Pereira62de1b12012-04-06 12:17:56 -07001025 private ReplyFromAccount getReplyFromAccountForReply(Account account, Message refMessage) {
1026 if (refMessage.accountUri != null) {
1027 // This must be from combined inbox.
1028 List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
1029 for (ReplyFromAccount from : replyFromAccounts) {
1030 if (from.account.uri.equals(refMessage.accountUri)) {
1031 return from;
1032 }
1033 }
1034 return null;
1035 } else {
1036 return getReplyFromAccount(account, refMessage);
1037 }
1038 }
1039
1040 /**
Tony Mantler9016a5e2013-07-19 11:54:17 -07001041 * Given an account and the message we're replying to,
Mindy Pereira62de1b12012-04-06 12:17:56 -07001042 * return who the message should be sent from.
1043 * @param account Account in which the message arrived.
Tony Mantler9016a5e2013-07-19 11:54:17 -07001044 * @param refMessage Message to analyze for account selection
Mindy Pereira62de1b12012-04-06 12:17:56 -07001045 * @return the address from which to reply.
1046 */
1047 public ReplyFromAccount getReplyFromAccount(Account account, Message refMessage) {
1048 // First see if we are supposed to use the default address or
1049 // the address it was sentTo.
Mindy Pereira326689d2012-05-17 10:14:14 -07001050 if (mCachedSettings.forceReplyFromDefault) {
Mindy Pereira62de1b12012-04-06 12:17:56 -07001051 return getDefaultReplyFromAccount(account);
1052 } else {
Mindy Pereira89bae572012-06-18 11:34:36 -07001053 // If we aren't explicitly told which account to look for, look at
Mindy Pereira62de1b12012-04-06 12:17:56 -07001054 // all the message recipients and find one that matches
1055 // a custom from or account.
1056 List<String> allRecipients = new ArrayList<String>();
Tony Mantler9016a5e2013-07-19 11:54:17 -07001057 allRecipients.addAll(Arrays.asList(refMessage.getToAddressesUnescaped()));
1058 allRecipients.addAll(Arrays.asList(refMessage.getCcAddressesUnescaped()));
Mindy Pereira62de1b12012-04-06 12:17:56 -07001059 return getMatchingRecipient(account, allRecipients);
1060 }
1061 }
1062
1063 /**
1064 * Compare all the recipients of an email to the current account and all
1065 * custom addresses associated with that account. Return the match if there
1066 * is one, or the default account if there isn't.
1067 */
1068 protected ReplyFromAccount getMatchingRecipient(Account account, List<String> sentTo) {
1069 // Tokenize the list and place in a hashmap.
1070 ReplyFromAccount matchingReplyFrom = null;
1071 Rfc822Token[] tokens;
1072 HashSet<String> recipientsMap = new HashSet<String>();
1073 for (String address : sentTo) {
1074 tokens = Rfc822Tokenizer.tokenize(address);
1075 for (int i = 0; i < tokens.length; i++) {
1076 recipientsMap.add(tokens[i].getAddress());
1077 }
1078 }
1079
1080 int matchingAddressCount = 0;
1081 List<ReplyFromAccount> customFroms;
Andy Huang16174812012-08-16 16:40:35 -07001082 customFroms = account.getReplyFroms();
1083 if (customFroms != null) {
1084 for (ReplyFromAccount entry : customFroms) {
1085 if (recipientsMap.contains(entry.address)) {
1086 matchingReplyFrom = entry;
1087 matchingAddressCount++;
Mindy Pereira62de1b12012-04-06 12:17:56 -07001088 }
1089 }
Mindy Pereira62de1b12012-04-06 12:17:56 -07001090 }
1091 if (matchingAddressCount > 1) {
1092 matchingReplyFrom = getDefaultReplyFromAccount(account);
1093 }
1094 return matchingReplyFrom;
1095 }
1096
Scott Kennedyff8553f2013-04-05 20:57:44 -07001097 private static ReplyFromAccount getDefaultReplyFromAccount(final Account account) {
1098 for (final ReplyFromAccount from : account.getReplyFroms()) {
Mindy Pereira62de1b12012-04-06 12:17:56 -07001099 if (from.isDefault) {
1100 return from;
1101 }
1102 }
Tony Mantler79b11562013-10-09 15:31:50 -07001103 return new ReplyFromAccount(account, account.uri, account.getEmailAddress(), account.name,
1104 account.getEmailAddress(), true, false);
Mindy Pereira62de1b12012-04-06 12:17:56 -07001105 }
1106
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001107 private ReplyFromAccount getReplyFromAccountFromDraft(Account account, Message msg) {
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001108 String sender = msg.getFrom();
Mindy Pereira62de1b12012-04-06 12:17:56 -07001109 ReplyFromAccount replyFromAccount = null;
1110 List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
Tony Mantler79b11562013-10-09 15:31:50 -07001111 if (TextUtils.equals(account.getEmailAddress(), sender)) {
1112 replyFromAccount = new ReplyFromAccount(mAccount, mAccount.uri,
1113 mAccount.getEmailAddress(), mAccount.name, mAccount.getEmailAddress(),
1114 true, false);
Mindy Pereira62de1b12012-04-06 12:17:56 -07001115 } else {
1116 for (ReplyFromAccount fromAccount : replyFromAccounts) {
Tony Mantler79b11562013-10-09 15:31:50 -07001117 if (TextUtils.equals(fromAccount.address, sender)) {
Mindy Pereira62de1b12012-04-06 12:17:56 -07001118 replyFromAccount = fromAccount;
1119 break;
1120 }
1121 }
1122 }
1123 return replyFromAccount;
1124 }
1125
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001126 private void findViews() {
Mindy Pereirab199d172012-08-13 11:04:03 -07001127 findViewById(R.id.compose).setVisibility(View.VISIBLE);
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001128 mCcBccButton = (Button) findViewById(R.id.add_cc_bcc);
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001129 if (mCcBccButton != null) {
1130 mCcBccButton.setOnClickListener(this);
1131 }
1132 mCcBccView = (CcBccView) findViewById(R.id.cc_bcc_wrapper);
Mindy Pereira7b56a612011-12-14 12:32:28 -08001133 mAttachmentsView = (AttachmentsView)findViewById(R.id.attachments);
Andrew Sapperstein6aea7862013-10-24 19:59:51 -07001134 mAddAttachmentsButton = findViewById(R.id.add_attachment);
1135 if (mAddAttachmentsButton != null) {
1136 mAddAttachmentsButton.setOnClickListener(this);
mindypcd0b0b92012-08-23 14:33:17 -07001137 }
Mindy Pereira818143e2012-01-11 13:59:49 -08001138 mTo = (RecipientEditTextView) findViewById(R.id.to);
Scott Kennedy41500392013-04-24 18:46:36 -07001139 mTo.setTokenizer(new Rfc822Tokenizer());
Mindy Pereira818143e2012-01-11 13:59:49 -08001140 mCc = (RecipientEditTextView) findViewById(R.id.cc);
Scott Kennedy41500392013-04-24 18:46:36 -07001141 mCc.setTokenizer(new Rfc822Tokenizer());
Mindy Pereira818143e2012-01-11 13:59:49 -08001142 mBcc = (RecipientEditTextView) findViewById(R.id.bcc);
Scott Kennedy41500392013-04-24 18:46:36 -07001143 mBcc.setTokenizer(new Rfc822Tokenizer());
Mindy Pereira82cc5662012-01-09 17:29:30 -08001144 // TODO: add special chips text change watchers before adding
1145 // this as a text changed watcher to the to, cc, bcc fields.
Mindy Pereira6349a042012-01-04 11:25:01 -08001146 mSubject = (TextView) findViewById(R.id.subject);
mindyp62d3ec72012-08-24 13:04:09 -07001147 mSubject.setOnEditorActionListener(this);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001148 mQuotedTextView = (QuotedTextView) findViewById(R.id.quoted_text_view);
1149 mQuotedTextView.setRespondInlineListener(this);
Mindy Pereira433b1982012-04-03 11:53:07 -07001150 mBodyView = (EditText) findViewById(R.id.body);
Mindy Pereira1a95a572012-01-05 12:21:29 -08001151 mFromStatic = findViewById(R.id.static_from_content);
Mindy Pereira2eb17322012-03-07 10:07:34 -08001152 mFromStaticText = (TextView) findViewById(R.id.from_account_name);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001153 mFromSpinnerWrapper = findViewById(R.id.spinner_from_content);
Mindy Pereira5a85e2b2012-01-11 09:53:32 -08001154 mFromSpinner = (FromAddressSpinner) findViewById(R.id.from_picker);
Mindy Pereira6349a042012-01-04 11:25:01 -08001155 }
1156
mindyp62d3ec72012-08-24 13:04:09 -07001157 @Override
1158 public boolean onEditorAction(TextView view, int action, KeyEvent keyEvent) {
1159 if (action == EditorInfo.IME_ACTION_DONE) {
1160 focusBody();
1161 return true;
1162 }
1163 return false;
1164 }
1165
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001166 protected TextView getBody() {
1167 return mBodyView;
1168 }
1169
1170 @VisibleForTesting
Andy Huang0a2a3462013-12-20 15:56:13 -08001171 public String getBodyHtml() {
1172 return Html.toHtml(removeComposingSpans(mBodyView.getText()));
1173 }
1174
1175 @VisibleForTesting
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001176 public Account getFromAccount() {
1177 return mReplyFromAccount != null && mReplyFromAccount.account != null ?
1178 mReplyFromAccount.account : mAccount;
1179 }
1180
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07001181 private void clearChangeListeners() {
1182 mSubject.removeTextChangedListener(this);
1183 mBodyView.removeTextChangedListener(this);
1184 mTo.removeTextChangedListener(mToListener);
1185 mCc.removeTextChangedListener(mCcListener);
1186 mBcc.removeTextChangedListener(mBccListener);
1187 mFromSpinner.setOnAccountChangedListener(null);
1188 mAttachmentsView.setAttachmentChangesListener(null);
1189 }
1190
Mindy Pereira75f66632012-01-11 11:42:02 -08001191 // Now that the message has been initialized from any existing draft or
1192 // ref message data, set up listeners for any changes that occur to the
1193 // message.
1194 private void initChangeListeners() {
mindyp1d7e9142012-11-21 13:54:30 -08001195 // Make sure we only add text changed listeners once!
1196 clearChangeListeners();
Mindy Pereira75f66632012-01-11 11:42:02 -08001197 mSubject.addTextChangedListener(this);
1198 mBodyView.addTextChangedListener(this);
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07001199 if (mToListener == null) {
1200 mToListener = new RecipientTextWatcher(mTo, this);
1201 }
1202 mTo.addTextChangedListener(mToListener);
1203 if (mCcListener == null) {
1204 mCcListener = new RecipientTextWatcher(mCc, this);
1205 }
1206 mCc.addTextChangedListener(mCcListener);
1207 if (mBccListener == null) {
1208 mBccListener = new RecipientTextWatcher(mBcc, this);
1209 }
1210 mBcc.addTextChangedListener(mBccListener);
Mindy Pereira75f66632012-01-11 11:42:02 -08001211 mFromSpinner.setOnAccountChangedListener(this);
Mindy Pereira818143e2012-01-11 13:59:49 -08001212 mAttachmentsView.setAttachmentChangesListener(this);
Mindy Pereira75f66632012-01-11 11:42:02 -08001213 }
1214
Alice Yanga990a712013-03-13 18:37:00 -07001215 private void initActionBar() {
1216 LogUtils.d(LOG_TAG, "initializing action bar in ComposeActivity");
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001217 ActionBar actionBar = getActionBar();
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001218 if (actionBar == null) {
1219 return;
1220 }
Alice Yanga990a712013-03-13 18:37:00 -07001221 if (mComposeMode == ComposeActivity.COMPOSE) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001222 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1223 actionBar.setTitle(R.string.compose);
Mindy Pereira326c6602012-01-04 15:32:42 -08001224 } else {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001225 actionBar.setTitle(null);
Mindy Pereira326c6602012-01-04 15:32:42 -08001226 if (mComposeModeAdapter == null) {
1227 mComposeModeAdapter = new ComposeModeAdapter(this);
1228 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001229 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
1230 actionBar.setListNavigationCallbacks(mComposeModeAdapter, this);
Alice Yanga990a712013-03-13 18:37:00 -07001231 switch (mComposeMode) {
Mindy Pereira326c6602012-01-04 15:32:42 -08001232 case ComposeActivity.REPLY:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001233 actionBar.setSelectedNavigationItem(0);
Mindy Pereira326c6602012-01-04 15:32:42 -08001234 break;
1235 case ComposeActivity.REPLY_ALL:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001236 actionBar.setSelectedNavigationItem(1);
Mindy Pereira326c6602012-01-04 15:32:42 -08001237 break;
1238 case ComposeActivity.FORWARD:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001239 actionBar.setSelectedNavigationItem(2);
Mindy Pereira326c6602012-01-04 15:32:42 -08001240 break;
1241 }
1242 }
Mindy Pereirafbe40192012-03-20 10:40:45 -07001243 actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME,
1244 ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME);
1245 actionBar.setHomeButtonEnabled(true);
Mindy Pereira326c6602012-01-04 15:32:42 -08001246 }
1247
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08001248 private void initFromRefMessage(int action) {
1249 setFieldsFromRefMessage(action);
Alice Yang1ebc2db2013-03-14 21:21:44 -07001250
1251 // Check if To: address and email body needs to be prefilled based on extras.
1252 // This is used for reporting rendering feedback.
1253 if (MessageHeaderView.ENABLE_REPORT_RENDERING_PROBLEM) {
1254 Intent intent = getIntent();
1255 if (intent.getExtras() != null) {
1256 String toAddresses = intent.getStringExtra(EXTRA_TO);
1257 if (toAddresses != null) {
1258 addToAddresses(Arrays.asList(TextUtils.split(toAddresses, ",")));
1259 }
1260 String body = intent.getStringExtra(EXTRA_BODY);
1261 if (body != null) {
1262 setBody(body, false /* withSignature */);
1263 }
1264 }
1265 }
1266
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07001267 if (mRefMessage != null) {
1268 // CC field only gets populated when doing REPLY_ALL.
1269 // BCC never gets auto-populated, unless the user is editing
1270 // a draft with one.
Mindy Pereira29a717e2012-07-25 18:05:48 -07001271 if (!TextUtils.isEmpty(mCc.getText()) && action == REPLY_ALL) {
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07001272 mCcBccView.show(false, true, false);
1273 }
1274 }
1275 updateHideOrShowCcBcc();
1276 }
1277
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08001278 private void setFieldsFromRefMessage(int action) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001279 setSubject(mRefMessage, action);
1280 // Setup recipients
1281 if (action == FORWARD) {
1282 mForward = true;
Mindy Pereira6349a042012-01-04 11:25:01 -08001283 }
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08001284 initRecipientsFromRefMessage(mRefMessage, action);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001285 initQuotedTextFromRefMessage(mRefMessage, action);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001286 if (action == ComposeActivity.FORWARD || mAttachmentsChanged) {
1287 initAttachments(mRefMessage);
1288 }
Mindy Pereirac17d0732011-12-29 10:46:19 -08001289 }
1290
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001291 private void initFromDraftMessage(Message message) {
Andy Huang1f8f4dd2012-10-25 21:35:35 -07001292 LogUtils.d(LOG_TAG, "Intializing draft from previous draft message: %s", message);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001293
1294 mDraft = message;
1295 mDraftId = message.id;
1296 mSubject.setText(message.subject);
1297 mForward = message.draftType == UIProvider.DraftType.FORWARD;
Tony Mantler9016a5e2013-07-19 11:54:17 -07001298 final List<String> toAddresses = Arrays.asList(message.getToAddressesUnescaped());
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001299 addToAddresses(toAddresses);
Tony Mantler9016a5e2013-07-19 11:54:17 -07001300 addCcAddresses(Arrays.asList(message.getCcAddressesUnescaped()), toAddresses);
1301 addBccAddresses(Arrays.asList(message.getBccAddressesUnescaped()));
Mindy Pereira2421dc82012-03-27 13:32:31 -07001302 if (message.hasAttachments) {
1303 List<Attachment> attachments = message.getAttachments();
1304 for (Attachment a : attachments) {
Andy Huang5c5fd572012-04-08 18:19:29 -07001305 addAttachmentAndUpdateView(a);
Mindy Pereira2421dc82012-03-27 13:32:31 -07001306 }
1307 }
Mindy Pereiracc8e7db2012-05-30 12:57:42 -07001308 int quotedTextIndex = message.appendRefMessageContent ?
Mindy Pereira002ff522012-05-30 10:31:26 -07001309 message.quotedTextOffset : -1;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001310 // Set the body
Mindy Pereira002ff522012-05-30 10:31:26 -07001311 CharSequence quotedText = null;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001312 if (!TextUtils.isEmpty(message.bodyHtml)) {
Mindy Pereira752222d2012-07-19 09:58:53 -07001313 CharSequence htmlText = "";
Mindy Pereira002ff522012-05-30 10:31:26 -07001314 if (quotedTextIndex > -1) {
Mindy Pereira752222d2012-07-19 09:58:53 -07001315 // Find the offset in the htmltext of the actual quoted text and strip it out.
1316 quotedTextIndex = QuotedTextView.findQuotedTextIndex(message.bodyHtml);
1317 if (quotedTextIndex > -1) {
mindypc59dd822012-11-13 10:56:21 -08001318 htmlText = Utils.convertHtmlToPlainText(message.bodyHtml.substring(0,
1319 quotedTextIndex));
Mindy Pereira752222d2012-07-19 09:58:53 -07001320 quotedText = message.bodyHtml.subSequence(quotedTextIndex,
1321 message.bodyHtml.length());
1322 }
Mindy Pereira1a6e9382012-08-14 15:51:22 -07001323 } else {
mindypc59dd822012-11-13 10:56:21 -08001324 htmlText = Utils.convertHtmlToPlainText(message.bodyHtml);
Mindy Pereira002ff522012-05-30 10:31:26 -07001325 }
1326 mBodyView.setText(htmlText);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001327 } else {
Mindy Pereira752222d2012-07-19 09:58:53 -07001328 final String body = message.bodyText;
1329 final CharSequence bodyText = !TextUtils.isEmpty(body) ?
1330 (quotedTextIndex > -1 ?
1331 message.bodyText.substring(0, quotedTextIndex) : message.bodyText)
1332 : "";
Mindy Pereira002ff522012-05-30 10:31:26 -07001333 if (quotedTextIndex > -1) {
Mindy Pereira752222d2012-07-19 09:58:53 -07001334 quotedText = !TextUtils.isEmpty(body) ? message.bodyText.substring(quotedTextIndex)
1335 : null;
Mindy Pereira002ff522012-05-30 10:31:26 -07001336 }
1337 mBodyView.setText(bodyText);
1338 }
1339 if (quotedTextIndex > -1 && quotedText != null) {
Mindy Pereira39713232012-05-30 11:48:41 -07001340 mQuotedTextView.setQuotedTextFromDraft(quotedText, mForward);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001341 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001342 }
1343
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001344 /**
1345 * Fill all the widgets with the content found in the Intent Extra, if any.
1346 * Also apply the same style to all widgets. Note: if initFromExtras is
1347 * called as a result of switching between reply, reply all, and forward per
1348 * the latest revision of Gmail, and the user has already made changes to
1349 * attachments on a previous incarnation of the message (as a reply, reply
1350 * all, or forward), the original attachments from the message will not be
1351 * re-instantiated. The user's changes will be respected. This follows the
1352 * web gmail interaction.
Andrew Sapperstein746d8612013-08-26 15:56:32 -07001353 * @return {@code true} if the activity should not call {@link #finishSetup}.
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001354 */
Andrew Sapperstein746d8612013-08-26 15:56:32 -07001355 public boolean initFromExtras(Intent intent) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001356 // If we were invoked with a SENDTO intent, the value
1357 // should take precedence
1358 final Uri dataUri = intent.getData();
1359 if (dataUri != null) {
1360 if (MAIL_TO.equals(dataUri.getScheme())) {
1361 initFromMailTo(dataUri.toString());
1362 } else {
Mindy Pereira0b4f28e2012-03-28 14:12:21 -07001363 if (!mAccount.composeIntentUri.equals(dataUri)) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001364 String toText = dataUri.getSchemeSpecificPart();
1365 if (toText != null) {
1366 mTo.setText("");
Mindy Pereiradbe89962012-04-13 09:42:38 -07001367 addToAddresses(Arrays.asList(TextUtils.split(toText, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001368 }
1369 }
1370 }
1371 }
1372
1373 String[] extraStrings = intent.getStringArrayExtra(Intent.EXTRA_EMAIL);
1374 if (extraStrings != null) {
1375 addToAddresses(Arrays.asList(extraStrings));
1376 }
1377 extraStrings = intent.getStringArrayExtra(Intent.EXTRA_CC);
1378 if (extraStrings != null) {
1379 addCcAddresses(Arrays.asList(extraStrings), null);
1380 }
1381 extraStrings = intent.getStringArrayExtra(Intent.EXTRA_BCC);
1382 if (extraStrings != null) {
1383 addBccAddresses(Arrays.asList(extraStrings));
1384 }
1385
1386 String extraString = intent.getStringExtra(Intent.EXTRA_SUBJECT);
1387 if (extraString != null) {
1388 mSubject.setText(extraString);
1389 }
1390
1391 for (String extra : ALL_EXTRAS) {
1392 if (intent.hasExtra(extra)) {
1393 String value = intent.getStringExtra(extra);
1394 if (EXTRA_TO.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001395 addToAddresses(Arrays.asList(TextUtils.split(value, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001396 } else if (EXTRA_CC.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001397 addCcAddresses(Arrays.asList(TextUtils.split(value, ",")), null);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001398 } else if (EXTRA_BCC.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001399 addBccAddresses(Arrays.asList(TextUtils.split(value, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001400 } else if (EXTRA_SUBJECT.equals(extra)) {
1401 mSubject.setText(value);
1402 } else if (EXTRA_BODY.equals(extra)) {
1403 setBody(value, true /* with signature */);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001404 } else if (EXTRA_QUOTED_TEXT.equals(extra)) {
1405 initQuotedText(value, true /* shouldQuoteText */);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001406 }
1407 }
1408 }
1409
1410 Bundle extras = intent.getExtras();
1411 if (extras != null) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001412 CharSequence text = extras.getCharSequence(Intent.EXTRA_TEXT);
1413 if (text != null) {
1414 setBody(text, true /* with signature */);
1415 }
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001416
1417 // TODO - support EXTRA_HTML_TEXT
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001418 }
Andrew Sapperstein746d8612013-08-26 15:56:32 -07001419
1420 mExtraValues = intent.getParcelableExtra(EXTRA_VALUES);
1421 if (mExtraValues != null) {
1422 LogUtils.d(LOG_TAG, "Launched with extra values: %s", mExtraValues.toString());
1423 initExtraValues(mExtraValues);
1424 return true;
1425 }
1426
1427 return false;
1428 }
1429
1430 protected void initExtraValues(ContentValues extraValues) {
1431 // DO NOTHING - Gmail will override
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001432 }
1433
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001434
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001435 @VisibleForTesting
1436 protected String decodeEmailInUri(String s) throws UnsupportedEncodingException {
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001437 // TODO: handle the case where there are spaces in the display name as
1438 // well as the email such as "Guy with spaces <guy+with+spaces@gmail.com>"
1439 // as they could be encoded ambiguously.
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001440 // Since URLDecode.decode changes + into ' ', and + is a valid
1441 // email character, we need to find/ replace these ourselves before
1442 // decoding.
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001443 try {
Yorke Lee7dd05b12013-04-25 10:04:43 -07001444 return URLDecoder.decode(replacePlus(s), UTF8_ENCODING_NAME);
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001445 } catch (IllegalArgumentException e) {
1446 if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
1447 LogUtils.e(LOG_TAG, "%s while decoding '%s'", e.getMessage(), s);
1448 } else {
1449 LogUtils.e(LOG_TAG, e, "Exception while decoding mailto address");
1450 }
1451 return null;
1452 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001453 }
1454
1455 /**
Yorke Lee7dd05b12013-04-25 10:04:43 -07001456 * Replaces all occurrences of '+' with "%2B", to prevent URLDecode.decode from
1457 * changing '+' into ' '
1458 *
1459 * @param toReplace Input string
1460 * @return The string with all "+" characters replaced with "%2B"
1461 */
Scott Kennedy3b965d72013-06-25 14:36:55 -07001462 private static String replacePlus(String toReplace) {
Yorke Lee7dd05b12013-04-25 10:04:43 -07001463 return toReplace.replace("+", "%2B");
1464 }
1465
1466 /**
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001467 * Initialize the compose view from a String representing a mailTo uri.
1468 * @param mailToString The uri as a string.
1469 */
1470 public void initFromMailTo(String mailToString) {
1471 // We need to disguise this string as a URI in order to parse it
1472 // TODO: Remove this hack when http://b/issue?id=1445295 gets fixed
1473 Uri uri = Uri.parse("foo://" + mailToString);
1474 int index = mailToString.indexOf("?");
1475 int length = "mailto".length() + 1;
1476 String to;
1477 try {
1478 // Extract the recipient after mailto:
1479 if (index == -1) {
1480 to = decodeEmailInUri(mailToString.substring(length));
1481 } else {
1482 to = decodeEmailInUri(mailToString.substring(length, index));
1483 }
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001484 if (!TextUtils.isEmpty(to)) {
1485 addToAddresses(Arrays.asList(TextUtils.split(to, ",")));
1486 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001487 } catch (UnsupportedEncodingException e) {
1488 if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
1489 LogUtils.e(LOG_TAG, "%s while decoding '%s'", e.getMessage(), mailToString);
1490 } else {
1491 LogUtils.e(LOG_TAG, e, "Exception while decoding mailto address");
1492 }
1493 }
1494
1495 List<String> cc = uri.getQueryParameters("cc");
1496 addCcAddresses(Arrays.asList(cc.toArray(new String[cc.size()])), null);
1497
1498 List<String> otherTo = uri.getQueryParameters("to");
1499 addToAddresses(Arrays.asList(otherTo.toArray(new String[otherTo.size()])));
1500
1501 List<String> bcc = uri.getQueryParameters("bcc");
1502 addBccAddresses(Arrays.asList(bcc.toArray(new String[bcc.size()])));
1503
1504 List<String> subject = uri.getQueryParameters("subject");
1505 if (subject.size() > 0) {
1506 try {
Yorke Lee7dd05b12013-04-25 10:04:43 -07001507 mSubject.setText(URLDecoder.decode(replacePlus(subject.get(0)),
1508 UTF8_ENCODING_NAME));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001509 } catch (UnsupportedEncodingException e) {
1510 LogUtils.e(LOG_TAG, "%s while decoding subject '%s'",
1511 e.getMessage(), subject);
1512 }
1513 }
1514
1515 List<String> body = uri.getQueryParameters("body");
1516 if (body.size() > 0) {
1517 try {
Yorke Lee7dd05b12013-04-25 10:04:43 -07001518 setBody(URLDecoder.decode(replacePlus(body.get(0)), UTF8_ENCODING_NAME),
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001519 true /* with signature */);
1520 } catch (UnsupportedEncodingException e) {
1521 LogUtils.e(LOG_TAG, "%s while decoding body '%s'", e.getMessage(), body);
1522 }
1523 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001524 }
1525
Mindy Pereirabddd6f32012-06-20 12:10:03 -07001526 @VisibleForTesting
1527 protected void initAttachments(Message refMessage) {
Mark Wei434f2942012-08-24 11:54:02 -07001528 addAttachments(refMessage.getAttachments());
1529 }
1530
1531 public long addAttachments(List<Attachment> attachments) {
1532 long size = 0;
1533 AttachmentFailureException error = null;
1534 for (Attachment a : attachments) {
1535 try {
1536 size += mAttachmentsView.addAttachment(mAccount, a);
1537 } catch (AttachmentFailureException e) {
1538 error = e;
1539 }
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001540 }
Mark Wei434f2942012-08-24 11:54:02 -07001541 if (error != null) {
1542 LogUtils.e(LOG_TAG, error, "Error adding attachment");
1543 if (attachments.size() > 1) {
1544 showAttachmentTooBigToast(R.string.too_large_to_attach_multiple);
1545 } else {
1546 showAttachmentTooBigToast(error.getErrorRes());
1547 }
1548 }
1549 return size;
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001550 }
1551
1552 /**
1553 * When an attachment is too large to be added to a message, show a toast.
1554 * This method also updates the position of the toast so that it is shown
1555 * clearly above they keyboard if it happens to be open.
1556 */
Mark Wei434f2942012-08-24 11:54:02 -07001557 private void showAttachmentTooBigToast(int errorRes) {
1558 String maxSize = AttachmentUtils.convertToHumanReadableSize(
1559 getApplicationContext(), mAccount.settings.getMaxAttachmentSize());
1560 showErrorToast(getString(errorRes, maxSize));
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001561 }
1562
Mark Wei434f2942012-08-24 11:54:02 -07001563 private void showErrorToast(String message) {
1564 Toast t = Toast.makeText(this, message, Toast.LENGTH_LONG);
1565 t.setText(message);
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001566 t.setGravity(Gravity.CENTER_HORIZONTAL, 0,
1567 getResources().getDimensionPixelSize(R.dimen.attachment_toast_yoffset));
1568 t.show();
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001569 }
1570
Paul Westbrookf97588b2012-03-20 11:11:37 -07001571 private void initAttachmentsFromIntent(Intent intent) {
Paul Westbrook03ee9712012-04-02 09:51:51 -07001572 Bundle extras = intent.getExtras();
1573 if (extras == null) {
1574 extras = Bundle.EMPTY;
1575 }
Paul Westbrookf97588b2012-03-20 11:11:37 -07001576 final String action = intent.getAction();
1577 if (!mAttachmentsChanged) {
1578 long totalSize = 0;
1579 if (extras.containsKey(EXTRA_ATTACHMENTS)) {
1580 String[] uris = (String[]) extras.getSerializable(EXTRA_ATTACHMENTS);
1581 for (String uriString : uris) {
1582 final Uri uri = Uri.parse(uriString);
1583 long size = 0;
1584 try {
Andy Huange003b4c2013-08-16 10:32:05 -07001585 final Attachment a = mAttachmentsView.generateLocalAttachment(uri);
1586 size = mAttachmentsView.addAttachment(mAccount, a);
1587
1588 Analytics.getInstance().sendEvent("send_intent_attachment",
1589 Utils.normalizeMimeType(a.getContentType()), null, size);
1590
Paul Westbrookf97588b2012-03-20 11:11:37 -07001591 } catch (AttachmentFailureException e) {
Paul Westbrookf97588b2012-03-20 11:11:37 -07001592 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Mark Wei434f2942012-08-24 11:54:02 -07001593 showAttachmentTooBigToast(e.getErrorRes());
Paul Westbrookf97588b2012-03-20 11:11:37 -07001594 }
1595 totalSize += size;
1596 }
1597 }
mindyp9a9e8d62012-10-03 12:24:07 -07001598 if (extras.containsKey(Intent.EXTRA_STREAM)) {
1599 if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
1600 ArrayList<Parcelable> uris = extras
1601 .getParcelableArrayList(Intent.EXTRA_STREAM);
1602 ArrayList<Attachment> attachments = new ArrayList<Attachment>();
1603 for (Parcelable uri : uris) {
1604 try {
Andy Huange003b4c2013-08-16 10:32:05 -07001605 final Attachment a = mAttachmentsView.generateLocalAttachment(
1606 (Uri) uri);
1607 attachments.add(a);
1608
1609 Analytics.getInstance().sendEvent("send_intent_attachment",
1610 Utils.normalizeMimeType(a.getContentType()), null, a.size);
1611
mindyp9a9e8d62012-10-03 12:24:07 -07001612 } catch (AttachmentFailureException e) {
1613 LogUtils.e(LOG_TAG, e, "Error adding attachment");
1614 String maxSize = AttachmentUtils.convertToHumanReadableSize(
1615 getApplicationContext(),
1616 mAccount.settings.getMaxAttachmentSize());
1617 showErrorToast(getString
1618 (R.string.generic_attachment_problem, maxSize));
1619 }
1620 }
1621 totalSize += addAttachments(attachments);
1622 } else {
1623 final Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
1624 long size = 0;
Paul Westbrookf97588b2012-03-20 11:11:37 -07001625 try {
Andy Huange003b4c2013-08-16 10:32:05 -07001626 final Attachment a = mAttachmentsView.generateLocalAttachment(uri);
1627 size = mAttachmentsView.addAttachment(mAccount, a);
1628
1629 Analytics.getInstance().sendEvent("send_intent_attachment",
1630 Utils.normalizeMimeType(a.getContentType()), null, size);
1631
Paul Westbrookf97588b2012-03-20 11:11:37 -07001632 } catch (AttachmentFailureException e) {
Paul Westbrookf97588b2012-03-20 11:11:37 -07001633 LogUtils.e(LOG_TAG, e, "Error adding attachment");
mindyp9a9e8d62012-10-03 12:24:07 -07001634 showAttachmentTooBigToast(e.getErrorRes());
Paul Westbrookf97588b2012-03-20 11:11:37 -07001635 }
mindyp9a9e8d62012-10-03 12:24:07 -07001636 totalSize += size;
Paul Westbrookf97588b2012-03-20 11:11:37 -07001637 }
1638 }
1639
1640 if (totalSize > 0) {
1641 mAttachmentsChanged = true;
1642 updateSaveUi();
Andy Huange003b4c2013-08-16 10:32:05 -07001643
1644 Analytics.getInstance().sendEvent("send_intent_with_attachments",
1645 Integer.toString(getAttachments().size()), null, totalSize);
Paul Westbrookf97588b2012-03-20 11:11:37 -07001646 }
1647 }
1648 }
1649
Andrew Sapperstein746d8612013-08-26 15:56:32 -07001650 protected void initQuotedText(CharSequence quotedText, boolean shouldQuoteText) {
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001651 mQuotedTextView.setQuotedTextFromHtml(quotedText, shouldQuoteText);
1652 mShowQuotedText = true;
1653 }
Paul Westbrookf97588b2012-03-20 11:11:37 -07001654
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001655 private void initQuotedTextFromRefMessage(Message refMessage, int action) {
1656 if (mRefMessage != null && (action == REPLY || action == REPLY_ALL || action == FORWARD)) {
Mindy Pereira9932dee2012-01-10 16:09:50 -08001657 mQuotedTextView.setQuotedText(action, refMessage, action != FORWARD);
1658 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001659 }
1660
1661 private void updateHideOrShowCcBcc() {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001662 // Its possible there is a menu item OR a button.
Mindy Pereira326689d2012-05-17 10:14:14 -07001663 boolean ccVisible = mCcBccView.isCcVisible();
1664 boolean bccVisible = mCcBccView.isBccVisible();
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001665 if (mCcBccButton != null) {
Mindy Pereira326689d2012-05-17 10:14:14 -07001666 if (!ccVisible || !bccVisible) {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001667 mCcBccButton.setVisibility(View.VISIBLE);
Mindy Pereira326689d2012-05-17 10:14:14 -07001668 mCcBccButton.setText(getString(!ccVisible ? R.string.add_cc_label
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001669 : R.string.add_bcc_label));
1670 } else {
mindypcd0b0b92012-08-23 14:33:17 -07001671 mCcBccButton.setVisibility(View.INVISIBLE);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001672 }
1673 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001674 }
1675
Mindy Pereiraa34c9a02012-04-17 14:10:53 -07001676 private void showCcBcc(Bundle state) {
Mindy Pereira326689d2012-05-17 10:14:14 -07001677 if (state != null && state.containsKey(EXTRA_SHOW_CC)) {
1678 boolean showCc = state.getBoolean(EXTRA_SHOW_CC);
1679 boolean showBcc = state.getBoolean(EXTRA_SHOW_BCC);
1680 if (showCc || showBcc) {
1681 mCcBccView.show(false, showCc, showBcc);
Mindy Pereira6faeedf2012-04-18 16:11:39 -07001682 }
Mindy Pereiraa34c9a02012-04-17 14:10:53 -07001683 }
1684 }
1685
Mindy Pereira013194c2012-01-06 15:09:33 -08001686 /**
1687 * Add attachment and update the compose area appropriately.
1688 * @param data
1689 */
1690 public void addAttachmentAndUpdateView(Intent data) {
Andrew Sapperstein05089f32013-10-01 17:00:03 -07001691 if (data == null) {
1692 return;
1693 }
1694
1695 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
1696 final ClipData clipData = data.getClipData();
1697 if (clipData != null) {
1698 for (int i = 0, size = clipData.getItemCount(); i < size; i++) {
1699 addAttachmentAndUpdateView(clipData.getItemAt(i).getUri());
1700 }
1701 return;
1702 }
1703 }
1704
1705 addAttachmentAndUpdateView(data.getData());
Mindy Pereira2421dc82012-03-27 13:32:31 -07001706 }
1707
Andy Huang5c5fd572012-04-08 18:19:29 -07001708 public void addAttachmentAndUpdateView(Uri contentUri) {
1709 if (contentUri == null) {
Mindy Pereira2421dc82012-03-27 13:32:31 -07001710 return;
1711 }
Mindy Pereira013194c2012-01-06 15:09:33 -08001712 try {
Andy Huang5c5fd572012-04-08 18:19:29 -07001713 addAttachmentAndUpdateView(mAttachmentsView.generateLocalAttachment(contentUri));
1714 } catch (AttachmentFailureException e) {
Andy Huang5c5fd572012-04-08 18:19:29 -07001715 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Mark Wei434f2942012-08-24 11:54:02 -07001716 showErrorToast(getResources().getString(
1717 e.getErrorRes(),
1718 AttachmentUtils.convertToHumanReadableSize(
1719 getApplicationContext(), mAccount.settings.getMaxAttachmentSize())));
Andy Huang5c5fd572012-04-08 18:19:29 -07001720 }
1721 }
1722
1723 public void addAttachmentAndUpdateView(Attachment attachment) {
1724 try {
Mark Wei434f2942012-08-24 11:54:02 -07001725 long size = mAttachmentsView.addAttachment(mAccount, attachment);
Mindy Pereira9932dee2012-01-10 16:09:50 -08001726 if (size > 0) {
1727 mAttachmentsChanged = true;
1728 updateSaveUi();
Mindy Pereira013194c2012-01-06 15:09:33 -08001729 }
Mindy Pereira9932dee2012-01-10 16:09:50 -08001730 } catch (AttachmentFailureException e) {
Mindy Pereira9932dee2012-01-10 16:09:50 -08001731 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Mark Wei434f2942012-08-24 11:54:02 -07001732 showAttachmentTooBigToast(e.getErrorRes());
Mindy Pereira013194c2012-01-06 15:09:33 -08001733 }
1734 }
1735
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08001736 void initRecipientsFromRefMessage(Message refMessage, int action) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001737 // Don't populate the address if this is a forward.
1738 if (action == ComposeActivity.FORWARD) {
1739 return;
1740 }
Scott Kennedyff8553f2013-04-05 20:57:44 -07001741 initReplyRecipients(refMessage, action);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001742 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001743
Paul Westbrook6d2442b2013-07-17 17:51:51 -07001744 // TODO: This should be private. This method shouldn't be used by ComposeActivityTests, as
1745 // it doesn't setup the state of the activity correctly
Mindy Pereira818143e2012-01-11 13:59:49 -08001746 @VisibleForTesting
Scott Kennedyff8553f2013-04-05 20:57:44 -07001747 void initReplyRecipients(final Message refMessage, final int action) {
Tony Mantler9016a5e2013-07-19 11:54:17 -07001748 String[] sentToAddresses = refMessage.getToAddressesUnescaped();
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001749 final Collection<String> toAddresses;
Tony Mantler89de9eb2013-07-25 11:43:58 -07001750 final String[] replyToAddresses = refMessage.getReplyToAddressesUnescaped();
1751 String replyToAddress = replyToAddresses.length > 0 ? replyToAddresses[0] : null;
1752 final String[] fromAddresses = refMessage.getFromAddressesUnescaped();
1753 final String fromAddress = fromAddresses.length > 0 ? fromAddresses[0] : null;
1754
mindyp65b06f52012-11-21 10:35:08 -08001755 // If there is no reply to address, the reply to address is the sender.
Tony Mantler89de9eb2013-07-25 11:43:58 -07001756 if (TextUtils.isEmpty(replyToAddress)) {
1757 replyToAddress = fromAddress;
mindyp65b06f52012-11-21 10:35:08 -08001758 }
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001759
1760 // If this is a reply, the Cc list is empty. If this is a reply-all, the
1761 // Cc list is the union of the To and Cc recipients of the original
1762 // message, excluding the current user's email address and any addresses
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001763 // already on the To list.
1764 if (action == ComposeActivity.REPLY) {
Tony Mantler89de9eb2013-07-25 11:43:58 -07001765 toAddresses = initToRecipients(fromAddress, replyToAddress, sentToAddresses);
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001766 addToAddresses(toAddresses);
1767 } else if (action == ComposeActivity.REPLY_ALL) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001768 final Set<String> ccAddresses = Sets.newHashSet();
Tony Mantler89de9eb2013-07-25 11:43:58 -07001769 toAddresses = initToRecipients(fromAddress, replyToAddress, sentToAddresses);
Mindy Pereira154386a2012-01-11 13:02:33 -08001770 addToAddresses(toAddresses);
Scott Kennedyff8553f2013-04-05 20:57:44 -07001771 addRecipients(ccAddresses, sentToAddresses);
Tony Mantler9016a5e2013-07-19 11:54:17 -07001772 addRecipients(ccAddresses, refMessage.getCcAddressesUnescaped());
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001773 addCcAddresses(ccAddresses, toAddresses);
1774 }
1775 }
1776
1777 private void addToAddresses(Collection<String> addresses) {
1778 addAddressesToList(addresses, mTo);
1779 }
1780
1781 private void addCcAddresses(Collection<String> addresses, Collection<String> toAddresses) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001782 addCcAddressesToList(tokenizeAddressList(addresses),
1783 toAddresses != null ? tokenizeAddressList(toAddresses) : null, mCc);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001784 }
1785
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001786 private void addBccAddresses(Collection<String> addresses) {
1787 addAddressesToList(addresses, mBcc);
1788 }
1789
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001790 @VisibleForTesting
1791 protected void addCcAddressesToList(List<Rfc822Token[]> addresses,
1792 List<Rfc822Token[]> compareToList, RecipientEditTextView list) {
1793 String address;
1794
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001795 if (compareToList == null) {
1796 for (Rfc822Token[] tokens : addresses) {
1797 for (int i = 0; i < tokens.length; i++) {
1798 address = tokens[i].toString();
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001799 list.append(address + END_TOKEN);
1800 }
1801 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001802 } else {
1803 HashSet<String> compareTo = convertToHashSet(compareToList);
1804 for (Rfc822Token[] tokens : addresses) {
1805 for (int i = 0; i < tokens.length; i++) {
1806 address = tokens[i].toString();
1807 // Check if this is a duplicate:
1808 if (!compareTo.contains(tokens[i].getAddress())) {
1809 // Get the address here
1810 list.append(address + END_TOKEN);
1811 }
1812 }
1813 }
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001814 }
1815 }
1816
Scott Kennedyff8553f2013-04-05 20:57:44 -07001817 private static HashSet<String> convertToHashSet(final List<Rfc822Token[]> list) {
1818 final HashSet<String> hash = new HashSet<String>();
1819 for (final Rfc822Token[] tokens : list) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001820 for (int i = 0; i < tokens.length; i++) {
1821 hash.add(tokens[i].getAddress());
1822 }
1823 }
1824 return hash;
1825 }
1826
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001827 protected List<Rfc822Token[]> tokenizeAddressList(Collection<String> addresses) {
1828 @VisibleForTesting
1829 List<Rfc822Token[]> tokenized = new ArrayList<Rfc822Token[]>();
1830
1831 for (String address: addresses) {
1832 tokenized.add(Rfc822Tokenizer.tokenize(address));
1833 }
1834 return tokenized;
1835 }
1836
1837 @VisibleForTesting
1838 void addAddressesToList(Collection<String> addresses, RecipientEditTextView list) {
1839 for (String address : addresses) {
1840 addAddressToList(address, list);
1841 }
1842 }
1843
Scott Kennedyff8553f2013-04-05 20:57:44 -07001844 private static void addAddressToList(final String address, final RecipientEditTextView list) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001845 if (address == null || list == null)
1846 return;
1847
Scott Kennedyff8553f2013-04-05 20:57:44 -07001848 final Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(address);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001849
1850 for (int i = 0; i < tokens.length; i++) {
1851 list.append(tokens[i] + END_TOKEN);
1852 }
1853 }
1854
1855 @VisibleForTesting
Scott Kennedyff8553f2013-04-05 20:57:44 -07001856 protected Collection<String> initToRecipients(final String fullSenderAddress,
1857 final String replyToAddress, final String[] inToAddresses) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001858 // The To recipient is the reply-to address specified in the original
1859 // message, unless it is:
1860 // the current user OR a custom from of the current user, in which case
1861 // it's the To recipient list of the original message.
1862 // OR missing, in which case use the sender of the original message
1863 Set<String> toAddresses = Sets.newHashSet();
mindyp65b06f52012-11-21 10:35:08 -08001864 if (!TextUtils.isEmpty(replyToAddress) && !recipientMatchesThisAccount(replyToAddress)) {
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001865 toAddresses.add(replyToAddress);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001866 } else {
mindyp65b06f52012-11-21 10:35:08 -08001867 // In this case, the user is replying to a message in which their
1868 // current account or one of their custom from addresses is the only
1869 // recipient and they sent the original message.
1870 if (inToAddresses.length == 1 && recipientMatchesThisAccount(fullSenderAddress)
1871 && recipientMatchesThisAccount(inToAddresses[0])) {
1872 toAddresses.add(inToAddresses[0]);
1873 return toAddresses;
1874 }
1875 // This happens if the user replies to a message they originally
1876 // wrote. In this case, "reply" really means "re-send," so we
1877 // target the original recipients. This works as expected even
1878 // if the user sent the original message to themselves.
1879 for (String address : inToAddresses) {
1880 if (!recipientMatchesThisAccount(address)) {
1881 toAddresses.add(address);
mindypfe8557b2012-11-05 12:05:16 -08001882 }
Mindy Pereira1469b4e2012-06-19 19:18:54 -07001883 }
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001884 }
1885 return toAddresses;
1886 }
1887
Scott Kennedyff8553f2013-04-05 20:57:44 -07001888 private void addRecipients(final Set<String> recipients, final String[] addresses) {
1889 for (final String email : addresses) {
Mindy Pereiracecc54a2012-07-31 09:38:11 -07001890 // Do not add this account, or any of its custom from addresses, to
1891 // the list of recipients.
Mindy Pereira4a20b702012-01-05 16:24:24 -08001892 final String recipientAddress = Address.getEmailAddress(email).getAddress();
mindyp5ee5d692012-11-19 16:02:16 -08001893 if (!recipientMatchesThisAccount(recipientAddress)) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001894 recipients.add(email.replace("\"\"", ""));
1895 }
1896 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001897 }
1898
Mindy Pereiracecc54a2012-07-31 09:38:11 -07001899 /**
1900 * A recipient matches this account if it has the same address as the
1901 * currently selected account OR one of the custom from addresses associated
1902 * with the currently selected account.
Mindy Pereiracecc54a2012-07-31 09:38:11 -07001903 * @param recipientAddress address we are comparing with the currently selected account
1904 * @return
1905 */
mindyp5ee5d692012-11-19 16:02:16 -08001906 protected boolean recipientMatchesThisAccount(String recipientAddress) {
1907 return ReplyFromAccount.matchesAccountOrCustomFrom(mAccount, recipientAddress,
mindypfe8557b2012-11-05 12:05:16 -08001908 mAccount.getReplyFroms());
Mindy Pereiracecc54a2012-07-31 09:38:11 -07001909 }
1910
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001911 /**
1912 * Returns a formatted subject string with the appropriate prefix for the action type.
1913 * E.g., "FWD: " is prepended if action is {@link ComposeActivity#FORWARD}.
1914 */
1915 public static String buildFormattedSubject(Resources res, String subject, int action) {
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001916 String prefix;
1917 String correctedSubject = null;
1918 if (action == ComposeActivity.COMPOSE) {
1919 prefix = "";
1920 } else if (action == ComposeActivity.FORWARD) {
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001921 prefix = res.getString(R.string.forward_subject_label);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001922 } else {
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001923 prefix = res.getString(R.string.reply_subject_label);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001924 }
1925
1926 // Don't duplicate the prefix
Mindy Pereirac7a36992012-07-30 14:00:37 -07001927 if (!TextUtils.isEmpty(subject)
1928 && subject.toLowerCase().startsWith(prefix.toLowerCase())) {
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001929 correctedSubject = subject;
1930 } else {
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001931 correctedSubject = String.format(
1932 res.getString(R.string.formatted_subject), prefix, subject);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001933 }
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001934
1935 return correctedSubject;
1936 }
1937
1938 private void setSubject(Message refMessage, int action) {
1939 mSubject.setText(buildFormattedSubject(getResources(), refMessage.subject, action));
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001940 }
1941
Mindy Pereira818143e2012-01-11 13:59:49 -08001942 private void initRecipients() {
1943 setupRecipients(mTo);
1944 setupRecipients(mCc);
1945 setupRecipients(mBcc);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001946 }
1947
Mindy Pereira818143e2012-01-11 13:59:49 -08001948 private void setupRecipients(RecipientEditTextView view) {
Paul Westbrook679a8cc2012-02-21 16:37:58 -08001949 view.setAdapter(new RecipientAdapter(this, mAccount));
Mindy Pereira82cc5662012-01-09 17:29:30 -08001950 if (mValidator == null) {
Tony Mantler79b11562013-10-09 15:31:50 -07001951 final String accountName = mAccount.getEmailAddress();
Mindy Pereira33fe9082012-01-09 16:24:30 -08001952 int offset = accountName.indexOf("@") + 1;
1953 String account = accountName;
Tony Mantler79b11562013-10-09 15:31:50 -07001954 if (offset > 0) {
1955 account = account.substring(offset);
Mindy Pereirac17d0732011-12-29 10:46:19 -08001956 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001957 mValidator = new Rfc822Validator(account);
Mindy Pereirac17d0732011-12-29 10:46:19 -08001958 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001959 view.setValidator(mValidator);
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001960 }
1961
1962 @Override
1963 public void onClick(View v) {
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07001964 final int id = v.getId();
1965 if (id == R.id.add_cc_bcc) {
1966 // Verify that cc/ bcc aren't showing.
1967 // Animate in cc/bcc.
1968 showCcBccViews();
Andrew Sapperstein6aea7862013-10-24 19:59:51 -07001969 } else if (id == R.id.add_attachment) {
1970 doAttach(Utils.isRunningKitkatOrLater() ? MIME_TYPE_ALL : MIME_TYPE_PHOTO);
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001971 }
1972 }
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001973
1974 @Override
1975 public boolean onCreateOptionsMenu(Menu menu) {
Tony Mantler5b8799a2013-10-31 10:43:03 -07001976 final boolean superCreated = super.onCreateOptionsMenu(menu);
Mindy Pereirab199d172012-08-13 11:04:03 -07001977 // Don't render any menu items when there are no accounts.
1978 if (mAccounts == null || mAccounts.length == 0) {
Tony Mantler5b8799a2013-10-31 10:43:03 -07001979 return superCreated;
Mindy Pereirab199d172012-08-13 11:04:03 -07001980 }
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001981 MenuInflater inflater = getMenuInflater();
1982 inflater.inflate(R.menu.compose_menu, menu);
mindyp1d7e9142012-11-21 13:54:30 -08001983
1984 /*
1985 * Start save in the correct enabled state.
1986 * 1) If a user launches compose from within gmail, save is disabled
1987 * until they add something, at which point, save is enabled, auto save
1988 * on exit; if the user empties everything, save is disabled, exiting does not
1989 * auto-save
1990 * 2) if a user replies/ reply all/ forwards from within gmail, save is
1991 * disabled until they change something, at which point, save is
1992 * enabled, auto save on exit; if the user empties everything, save is
1993 * disabled, exiting does not auto-save.
1994 * 3) If a user launches compose from another application and something
1995 * gets populated (attachments, recipients, body, subject, etc), save is
1996 * enabled, auto save on exit; if the user empties everything, save is
1997 * disabled, exiting does not auto-save
1998 */
Mindy Pereira82cc5662012-01-09 17:29:30 -08001999 mSave = menu.findItem(R.id.save);
mindyp1d7e9142012-11-21 13:54:30 -08002000 String action = getIntent() != null ? getIntent().getAction() : null;
Andy Huang9f855d62013-05-30 17:15:03 -07002001 enableSave(mInnerSavedState != null ?
2002 mInnerSavedState.getBoolean(EXTRA_SAVE_ENABLED)
mindyp1d7e9142012-11-21 13:54:30 -08002003 : (Intent.ACTION_SEND.equals(action)
2004 || Intent.ACTION_SEND_MULTIPLE.equals(action)
2005 || Intent.ACTION_SENDTO.equals(action)
2006 || shouldSave()));
2007
Mindy Pereira3ca5bad2012-04-16 11:02:42 -07002008 MenuItem helpItem = menu.findItem(R.id.help_info_menu_item);
2009 MenuItem sendFeedbackItem = menu.findItem(R.id.feedback_menu_item);
2010 if (helpItem != null) {
2011 helpItem.setVisible(mAccount != null
2012 && mAccount.supportsCapability(AccountCapabilities.HELP_CONTENT));
2013 }
2014 if (sendFeedbackItem != null) {
2015 sendFeedbackItem.setVisible(mAccount != null
2016 && mAccount.supportsCapability(AccountCapabilities.SEND_FEEDBACK));
2017 }
Andrew Sapperstein5cb71802013-10-01 18:31:20 -07002018
Andrew Sapperstein8809f9f2013-10-11 16:13:35 -07002019 // Show attach picture on pre-K devices.
2020 menu.findItem(R.id.add_photo_attachment).setVisible(!Utils.isRunningKitkatOrLater());
Andrew Sapperstein5cb71802013-10-01 18:31:20 -07002021
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002022 return true;
2023 }
2024
2025 @Override
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08002026 public boolean onPrepareOptionsMenu(Menu menu) {
2027 MenuItem ccBcc = menu.findItem(R.id.add_cc_bcc);
Mindy Pereira818143e2012-01-11 13:59:49 -08002028 if (ccBcc != null && mCc != null) {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08002029 // Its possible there is a menu item OR a button.
2030 boolean ccFieldVisible = mCc.isShown();
2031 boolean bccFieldVisible = mBcc.isShown();
2032 if (!ccFieldVisible || !bccFieldVisible) {
2033 ccBcc.setVisible(true);
2034 ccBcc.setTitle(getString(!ccFieldVisible ? R.string.add_cc_label
2035 : R.string.add_bcc_label));
2036 } else {
2037 ccBcc.setVisible(false);
2038 }
2039 }
2040 return true;
2041 }
2042
2043 @Override
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002044 public boolean onOptionsItemSelected(MenuItem item) {
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002045 final int id = item.getItemId();
Andy Huangdc97bf42013-08-15 16:52:45 -07002046
2047 Analytics.getInstance().sendMenuItemEvent(Analytics.EVENT_CATEGORY_MENU_ITEM, id, null, 0);
2048
Mindy Pereira75f66632012-01-11 11:42:02 -08002049 boolean handled = true;
Andrew Sapperstein5cb71802013-10-01 18:31:20 -07002050 if (id == R.id.add_file_attachment) {
2051 doAttach(MIME_TYPE_ALL);
2052 } else if (id == R.id.add_photo_attachment) {
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002053 doAttach(MIME_TYPE_PHOTO);
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002054 } else if (id == R.id.add_cc_bcc) {
2055 showCcBccViews();
2056 } else if (id == R.id.save) {
2057 doSave(true);
2058 } else if (id == R.id.send) {
2059 doSend();
2060 } else if (id == R.id.discard) {
2061 doDiscard();
2062 } else if (id == R.id.settings) {
2063 Utils.showSettings(this, mAccount);
2064 } else if (id == android.R.id.home) {
2065 onAppUpPressed();
2066 } else if (id == R.id.help_info_menu_item) {
2067 Utils.showHelp(this, mAccount, getString(R.string.compose_help_context));
2068 } else if (id == R.id.feedback_menu_item) {
2069 Utils.sendFeedback(this, mAccount, false);
2070 } else {
2071 handled = false;
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002072 }
2073 return !handled ? super.onOptionsItemSelected(item) : handled;
2074 }
Mindy Pereira326c6602012-01-04 15:32:42 -08002075
Mindy Pereirab199d172012-08-13 11:04:03 -07002076 @Override
2077 public void onBackPressed() {
2078 // If we are showing the wait fragment, just exit.
2079 if (getWaitFragment() != null) {
2080 finish();
2081 } else {
2082 super.onBackPressed();
2083 }
2084 }
2085
Vikram Aggarwal1672ff82012-09-21 10:15:22 -07002086 /**
2087 * Carries out the "up" action in the action bar.
2088 */
Paul Westbrookdaecb4b2012-05-31 10:21:26 -07002089 private void onAppUpPressed() {
2090 if (mLaunchedFromEmail) {
2091 // If this was started from Gmail, simply treat app up as the system back button, so
2092 // that the last view is restored.
2093 onBackPressed();
2094 return;
2095 }
2096
2097 // Fire the main activity to ensure it launches the "top" screen of mail.
2098 // Since the main Activity is singleTask, it should revive that task if it was already
2099 // started.
Vikram Aggarwal0c3c2052012-09-21 11:06:28 -07002100 final Intent mailIntent = Utils.createViewInboxIntent(mAccount);
Paul Westbrookdaecb4b2012-05-31 10:21:26 -07002101 mailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |
2102 Intent.FLAG_ACTIVITY_TASK_ON_HOME);
2103 startActivity(mailIntent);
2104 finish();
2105 }
2106
Mindy Pereira33fe9082012-01-09 16:24:30 -08002107 private void doSend() {
Mark Weidd19b632012-10-19 13:59:28 -07002108 sendOrSaveWithSanityChecks(false, true, false, false);
Andy Huangdc97bf42013-08-15 16:52:45 -07002109 logSendOrSave(false /* save */);
2110 mPerformedSendOrDiscard = true;
Mindy Pereira33fe9082012-01-09 16:24:30 -08002111 }
2112
Mindy Pereira48e31b02012-05-30 13:12:24 -07002113 private void doSave(boolean showToast) {
Mark Weidd19b632012-10-19 13:59:28 -07002114 sendOrSaveWithSanityChecks(true, showToast, false, false);
Mindy Pereira48e31b02012-05-30 13:12:24 -07002115 }
2116
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002117 @VisibleForTesting
2118 public interface SendOrSaveCallback {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002119 public void initializeSendOrSave(SendOrSaveTask sendOrSaveTask);
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002120 public void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage, Message message);
2121 public Message getMessage();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002122 public void sendOrSaveFinished(SendOrSaveTask sendOrSaveTask, boolean success);
2123 }
2124
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002125 @VisibleForTesting
2126 public static class SendOrSaveTask implements Runnable {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002127 private final Context mContext;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002128 @VisibleForTesting
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002129 public final SendOrSaveCallback mSendOrSaveCallback;
2130 @VisibleForTesting
2131 public final SendOrSaveMessage mSendOrSaveMessage;
mindyp44a63392012-11-05 12:05:16 -08002132 private ReplyFromAccount mExistingDraftAccount;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002133
2134 public SendOrSaveTask(Context context, SendOrSaveMessage message,
mindyp44a63392012-11-05 12:05:16 -08002135 SendOrSaveCallback callback, ReplyFromAccount draftAccount) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002136 mContext = context;
2137 mSendOrSaveCallback = callback;
2138 mSendOrSaveMessage = message;
mindyp44a63392012-11-05 12:05:16 -08002139 mExistingDraftAccount = draftAccount;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002140 }
2141
2142 @Override
2143 public void run() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002144 final SendOrSaveMessage sendOrSaveMessage = mSendOrSaveMessage;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002145
Mindy Pereira92551d02012-04-05 11:31:12 -07002146 final ReplyFromAccount selectedAccount = sendOrSaveMessage.mAccount;
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002147 Message message = mSendOrSaveCallback.getMessage();
2148 long messageId = message != null ? message.id : UIProvider.INVALID_MESSAGE_ID;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002149 // If a previous draft has been saved, in an account that is different
2150 // than what the user wants to send from, remove the old draft, and treat this
2151 // as a new message
mindyp44a63392012-11-05 12:05:16 -08002152 if (mExistingDraftAccount != null
2153 && !selectedAccount.account.uri.equals(mExistingDraftAccount.account.uri)) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002154 if (messageId != UIProvider.INVALID_MESSAGE_ID) {
2155 ContentResolver resolver = mContext.getContentResolver();
2156 ContentValues values = new ContentValues();
2157 values.put(BaseColumns._ID, messageId);
mindypfebd2262012-11-13 17:45:09 -08002158 if (mExistingDraftAccount.account.expungeMessageUri != null) {
2159 new ContentProviderTask.UpdateTask()
2160 .run(resolver, mExistingDraftAccount.account.expungeMessageUri,
2161 values, null, null);
Mindy Pereiracfb7f332012-02-28 10:23:43 -08002162 } else {
2163 // TODO(mindyp) delete the conversation.
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002164 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002165 // reset messageId to 0, so a new message will be created
2166 messageId = UIProvider.INVALID_MESSAGE_ID;
2167 }
2168 }
2169
2170 final long messageIdToSave = messageId;
Scott Kennedyff8553f2013-04-05 20:57:44 -07002171 sendOrSaveMessage(messageIdToSave, sendOrSaveMessage, selectedAccount);
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002172
2173 if (!sendOrSaveMessage.mSave) {
Tony Mantler9f324232013-08-08 14:24:30 -07002174 incrementRecipientsTimesContacted(mContext,
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002175 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.TO));
Tony Mantler9f324232013-08-08 14:24:30 -07002176 incrementRecipientsTimesContacted(mContext,
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002177 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.CC));
Tony Mantler9f324232013-08-08 14:24:30 -07002178 incrementRecipientsTimesContacted(mContext,
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002179 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.BCC));
2180 }
2181 mSendOrSaveCallback.sendOrSaveFinished(SendOrSaveTask.this, true);
2182 }
2183
Tony Mantler9f324232013-08-08 14:24:30 -07002184 private static void incrementRecipientsTimesContacted(final Context context,
2185 final String addressString) {
2186 if (TextUtils.isEmpty(addressString)) {
2187 return;
2188 }
2189 final Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(addressString);
2190 final ArrayList<String> recipients = new ArrayList<String>(tokens.length);
2191 for (int i = 0; i < tokens.length;i++) {
2192 recipients.add(tokens[i].getAddress());
2193 }
2194 final DataUsageStatUpdater statsUpdater = new DataUsageStatUpdater(context);
2195 statsUpdater.updateWithAddress(recipients);
2196 }
2197
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002198 /**
2199 * Send or Save a message.
2200 */
Scott Kennedyff8553f2013-04-05 20:57:44 -07002201 private void sendOrSaveMessage(final long messageIdToSave,
2202 final SendOrSaveMessage sendOrSaveMessage, final ReplyFromAccount selectedAccount) {
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002203 final ContentResolver resolver = mContext.getContentResolver();
2204 final boolean updateExistingMessage = messageIdToSave != UIProvider.INVALID_MESSAGE_ID;
2205
2206 final String accountMethod = sendOrSaveMessage.mSave ?
2207 UIProvider.AccountCallMethods.SAVE_MESSAGE :
2208 UIProvider.AccountCallMethods.SEND_MESSAGE;
2209
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002210 try {
2211 if (updateExistingMessage) {
2212 sendOrSaveMessage.mValues.put(BaseColumns._ID, messageIdToSave);
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002213
Paul Westbrook013a23c2013-02-22 10:37:41 -08002214 callAccountSendSaveMethod(resolver,
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002215 selectedAccount.account, accountMethod, sendOrSaveMessage);
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002216 } else {
Paul Westbrook013a23c2013-02-22 10:37:41 -08002217 Uri messageUri = null;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002218 final Bundle result = callAccountSendSaveMethod(resolver,
2219 selectedAccount.account, accountMethod, sendOrSaveMessage);
2220 if (result != null) {
2221 // If a non-null value was returned, then the provider handled the call
2222 // method
2223 messageUri = result.getParcelable(UIProvider.MessageColumns.URI);
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002224 }
2225 if (sendOrSaveMessage.mSave && messageUri != null) {
2226 final Cursor messageCursor = resolver.query(messageUri,
2227 UIProvider.MESSAGE_PROJECTION, null, null, null);
2228 if (messageCursor != null) {
2229 try {
2230 if (messageCursor.moveToFirst()) {
2231 // Broadcast notification that a new message has
2232 // been allocated
2233 mSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage,
2234 new Message(messageCursor));
2235 }
2236 } finally {
2237 messageCursor.close();
Paul Westbrookba558482012-03-19 11:00:24 -07002238 }
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002239 }
2240 }
2241 }
2242 } finally {
2243 // Close any opened file descriptors
2244 closeOpenedAttachmentFds(sendOrSaveMessage);
2245 }
2246 }
2247
Scott Kennedyff8553f2013-04-05 20:57:44 -07002248 private static void closeOpenedAttachmentFds(final SendOrSaveMessage sendOrSaveMessage) {
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002249 final Bundle openedFds = sendOrSaveMessage.attachmentFds();
2250 if (openedFds != null) {
2251 final Set<String> keys = openedFds.keySet();
Scott Kennedyff8553f2013-04-05 20:57:44 -07002252 for (final String key : keys) {
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002253 final ParcelFileDescriptor fd = openedFds.getParcelable(key);
2254 if (fd != null) {
2255 try {
2256 fd.close();
2257 } catch (IOException e) {
2258 // Do nothing
Paul Westbrookba558482012-03-19 11:00:24 -07002259 }
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002260 }
2261 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002262 }
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002263 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002264
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002265 /**
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07002266 * Use the {@link ContentResolver#call} method to send or save the message.
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002267 *
2268 * If this was successful, this method will return an non-null Bundle instance
2269 */
Scott Kennedyff8553f2013-04-05 20:57:44 -07002270 private static Bundle callAccountSendSaveMethod(final ContentResolver resolver,
2271 final Account account, final String method,
2272 final SendOrSaveMessage sendOrSaveMessage) {
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002273 // Copy all of the values from the content values to the bundle
2274 final Bundle methodExtras = new Bundle(sendOrSaveMessage.mValues.size());
2275 final Set<Entry<String, Object>> valueSet = sendOrSaveMessage.mValues.valueSet();
2276
2277 for (Entry<String, Object> entry : valueSet) {
2278 final Object entryValue = entry.getValue();
2279 final String key = entry.getKey();
2280 if (entryValue instanceof String) {
2281 methodExtras.putString(key, (String)entryValue);
2282 } else if (entryValue instanceof Boolean) {
2283 methodExtras.putBoolean(key, (Boolean)entryValue);
2284 } else if (entryValue instanceof Integer) {
2285 methodExtras.putInt(key, (Integer)entryValue);
2286 } else if (entryValue instanceof Long) {
2287 methodExtras.putLong(key, (Long)entryValue);
2288 } else {
2289 LogUtils.wtf(LOG_TAG, "Unexpected object type: %s",
2290 entryValue.getClass().getName());
2291 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002292 }
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002293
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002294 // If the SendOrSaveMessage has some opened fds, add them to the bundle
2295 final Bundle fdMap = sendOrSaveMessage.attachmentFds();
2296 if (fdMap != null) {
2297 methodExtras.putParcelable(
2298 UIProvider.SendOrSaveMethodParamKeys.OPENED_FD_MAP, fdMap);
2299 }
2300
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002301 return resolver.call(account.uri, method, account.uri.toString(), methodExtras);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002302 }
2303 }
2304
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002305 @VisibleForTesting
2306 public static class SendOrSaveMessage {
Mindy Pereira92551d02012-04-05 11:31:12 -07002307 final ReplyFromAccount mAccount;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002308 final ContentValues mValues;
Mindy Pereira3ce64e72012-01-13 14:29:45 -08002309 final String mRefMessageId;
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002310 @VisibleForTesting
2311 public final boolean mSave;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002312 final int mRequestId;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002313 private final Bundle mAttachmentFds;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002314
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002315 public SendOrSaveMessage(Context context, ReplyFromAccount account, ContentValues values,
2316 String refMessageId, List<Attachment> attachments, boolean save) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002317 mAccount = account;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002318 mValues = values;
2319 mRefMessageId = refMessageId;
2320 mSave = save;
2321 mRequestId = mValues.hashCode() ^ hashCode();
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002322
2323 mAttachmentFds = initializeAttachmentFds(context, attachments);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002324 }
2325
2326 int requestId() {
2327 return mRequestId;
2328 }
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002329
2330 Bundle attachmentFds() {
2331 return mAttachmentFds;
2332 }
2333
2334 /**
2335 * Opens {@link ParcelFileDescriptor} for each of the attachments. This method must be
2336 * called before the ComposeActivity finishes.
2337 * Note: The caller is responsible for closing these file descriptors.
2338 */
Scott Kennedyff8553f2013-04-05 20:57:44 -07002339 private static Bundle initializeAttachmentFds(final Context context,
2340 final List<Attachment> attachments) {
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002341 if (attachments == null || attachments.size() == 0) {
2342 return null;
2343 }
2344
2345 final Bundle result = new Bundle(attachments.size());
2346 final ContentResolver resolver = context.getContentResolver();
2347
2348 for (Attachment attachment : attachments) {
2349 if (attachment == null || Utils.isEmpty(attachment.contentUri)) {
2350 continue;
2351 }
2352
2353 ParcelFileDescriptor fileDescriptor;
2354 try {
2355 fileDescriptor = resolver.openFileDescriptor(attachment.contentUri, "r");
2356 } catch (FileNotFoundException e) {
2357 LogUtils.e(LOG_TAG, e, "Exception attempting to open attachment");
2358 fileDescriptor = null;
Paul Westbrookc537fd42013-02-20 11:10:03 -08002359 } catch (SecurityException e) {
2360 // We have encountered a security exception when attempting to open the file
2361 // specified by the content uri. If the attachment has been cached, this
2362 // isn't a problem, as even through the original permission may have been
2363 // revoked, we have cached the file. This will happen when saving/sending
2364 // a previously saved draft.
2365 // TODO(markwei): Expose whether the attachment has been cached through the
2366 // attachment object. This would allow us to limit when the log is made, as
2367 // if the attachment has been cached, this really isn't an error
2368 LogUtils.e(LOG_TAG, e, "Security Exception attempting to open attachment");
2369 // Just set the file descriptor to null, as the underlying provider needs
2370 // to handle the file descriptor not being set.
2371 fileDescriptor = null;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002372 }
2373
2374 if (fileDescriptor != null) {
2375 result.putParcelable(attachment.contentUri.toString(), fileDescriptor);
2376 }
2377 }
2378
2379 return result;
2380 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002381 }
2382
2383 /**
2384 * Get the to recipients.
2385 */
2386 public String[] getToAddresses() {
2387 return getAddressesFromList(mTo);
2388 }
2389
2390 /**
2391 * Get the cc recipients.
2392 */
2393 public String[] getCcAddresses() {
2394 return getAddressesFromList(mCc);
2395 }
2396
2397 /**
2398 * Get the bcc recipients.
2399 */
2400 public String[] getBccAddresses() {
2401 return getAddressesFromList(mBcc);
2402 }
2403
2404 public String[] getAddressesFromList(RecipientEditTextView list) {
2405 if (list == null) {
2406 return new String[0];
2407 }
2408 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(list.getText());
2409 int count = tokens.length;
2410 String[] result = new String[count];
2411 for (int i = 0; i < count; i++) {
2412 result[i] = tokens[i].toString();
2413 }
2414 return result;
2415 }
2416
2417 /**
2418 * Check for invalid email addresses.
2419 * @param to String array of email addresses to check.
2420 * @param wrongEmailsOut Emails addresses that were invalid.
2421 */
Scott Kennedyff8553f2013-04-05 20:57:44 -07002422 public void checkInvalidEmails(final String[] to, final List<String> wrongEmailsOut) {
Mindy Pereirae5f20bf2012-06-25 14:20:40 -07002423 if (mValidator == null) {
2424 return;
2425 }
Scott Kennedyff8553f2013-04-05 20:57:44 -07002426 for (final String email : to) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002427 if (!mValidator.isValid(email)) {
2428 wrongEmailsOut.add(email);
2429 }
2430 }
2431 }
2432
Tony Mantler2558b502013-07-09 10:53:34 -07002433 public static class RecipientErrorDialogFragment extends DialogFragment {
Paul Westbrookf0ea4842013-08-13 16:41:18 -07002434 // Public no-args constructor needed for fragment re-instantiation
2435 public RecipientErrorDialogFragment() {}
2436
Tony Mantler2558b502013-07-09 10:53:34 -07002437 public static RecipientErrorDialogFragment newInstance(final String message) {
2438 final RecipientErrorDialogFragment frag = new RecipientErrorDialogFragment();
2439 final Bundle args = new Bundle(1);
2440 args.putString("message", message);
2441 frag.setArguments(args);
2442 return frag;
2443 }
2444
2445 @Override
2446 public Dialog onCreateDialog(Bundle savedInstanceState) {
2447 final String message = getArguments().getString("message");
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07002448 return new AlertDialog.Builder(getActivity())
2449 .setMessage(message)
Tony Mantler2558b502013-07-09 10:53:34 -07002450 .setPositiveButton(
2451 R.string.ok, new Dialog.OnClickListener() {
2452 @Override
2453 public void onClick(DialogInterface dialog, int which) {
2454 ((ComposeActivity)getActivity()).finishRecipientErrorDialog();
2455 }
2456 }).create();
2457 }
2458 }
2459
2460 private void finishRecipientErrorDialog() {
2461 // after the user dismisses the recipient error
2462 // dialog we want to make sure to refocus the
2463 // recipient to field so they can fix the issue
2464 // easily
2465 if (mTo != null) {
2466 mTo.requestFocus();
2467 }
2468 }
2469
Mindy Pereira82cc5662012-01-09 17:29:30 -08002470 /**
2471 * Show an error because the user has entered an invalid recipient.
2472 * @param message
2473 */
Tony Mantler2558b502013-07-09 10:53:34 -07002474 private void showRecipientErrorDialog(final String message) {
2475 final DialogFragment frag = RecipientErrorDialogFragment.newInstance(message);
2476 frag.show(getFragmentManager(), "recipient error");
Mindy Pereira82cc5662012-01-09 17:29:30 -08002477 }
2478
2479 /**
2480 * Update the state of the UI based on whether or not the current draft
2481 * needs to be saved and the message is not empty.
2482 */
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002483 public void updateSaveUi() {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002484 if (mSave != null) {
2485 mSave.setEnabled((shouldSave() && !isBlank()));
2486 }
2487 }
2488
2489 /**
2490 * Returns true if we need to save the current draft.
2491 */
2492 private boolean shouldSave() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002493 synchronized (mDraftLock) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002494 // The message should only be saved if:
2495 // It hasn't been sent AND
2496 // Some text has been added to the message OR
2497 // an attachment has been added or removed
Mindy Pereiraa2148332012-07-02 13:54:14 -07002498 // AND there is actually something in the draft to save.
Andy Huangd47877e2012-08-09 19:31:24 -07002499 return (mTextChanged || mAttachmentsChanged || mReplyFromChanged)
Mindy Pereiraa2148332012-07-02 13:54:14 -07002500 && !isBlank();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002501 }
2502 }
2503
2504 /**
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002505 * Check if all fields are blank.
Mindy Pereira82cc5662012-01-09 17:29:30 -08002506 * @return boolean
2507 */
2508 public boolean isBlank() {
Alice Yanga49b6842013-08-23 10:36:18 -07002509 // Need to check for null since isBlank() can be called from onPause()
2510 // before findViews() is called
2511 if (mSubject == null || mBodyView == null || mTo == null || mCc == null ||
2512 mAttachmentsView == null) {
2513 LogUtils.w(LOG_TAG, "null views in isBlank check");
2514 return true;
2515 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002516 return mSubject.getText().length() == 0
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002517 && (mBodyView.getText().length() == 0 || getSignatureStartPosition(mSignature,
2518 mBodyView.getText().toString()) == 0)
2519 && mTo.length() == 0
2520 && mCc.length() == 0 && mBcc.length() == 0
2521 && mAttachmentsView.getAttachments().size() == 0;
2522 }
2523
2524 @VisibleForTesting
2525 protected int getSignatureStartPosition(String signature, String bodyText) {
2526 int startPos = -1;
2527
2528 if (TextUtils.isEmpty(signature) || TextUtils.isEmpty(bodyText)) {
2529 return startPos;
2530 }
2531
2532 int bodyLength = bodyText.length();
2533 int signatureLength = signature.length();
2534 String printableVersion = convertToPrintableSignature(signature);
2535 int printableLength = printableVersion.length();
2536
2537 if (bodyLength >= printableLength
2538 && bodyText.substring(bodyLength - printableLength)
2539 .equals(printableVersion)) {
2540 startPos = bodyLength - printableLength;
2541 } else if (bodyLength >= signatureLength
2542 && bodyText.substring(bodyLength - signatureLength)
2543 .equals(signature)) {
2544 startPos = bodyLength - signatureLength;
2545 }
2546 return startPos;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002547 }
2548
2549 /**
2550 * Allows any changes made by the user to be ignored. Called when the user
2551 * decides to discard a draft.
2552 */
2553 private void discardChanges() {
2554 mTextChanged = false;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002555 mAttachmentsChanged = false;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002556 mReplyFromChanged = false;
2557 }
2558
2559 /**
Mindy Pereira181df782012-03-01 13:32:44 -08002560 * @param save
2561 * @param showToast
2562 * @return Whether the send or save succeeded.
2563 */
2564 protected boolean sendOrSaveWithSanityChecks(final boolean save, final boolean showToast,
Mark Weidd19b632012-10-19 13:59:28 -07002565 final boolean orientationChanged, final boolean autoSend) {
Mark Wei009b3712012-10-18 18:07:50 -07002566 if (mAccounts == null || mAccount == null) {
2567 Toast.makeText(this, R.string.send_failed, Toast.LENGTH_SHORT).show();
Mark Weidd19b632012-10-19 13:59:28 -07002568 if (autoSend) {
2569 finish();
2570 }
Mark Wei009b3712012-10-18 18:07:50 -07002571 return false;
2572 }
2573
Scott Kennedyff8553f2013-04-05 20:57:44 -07002574 final String[] to, cc, bcc;
Mindy Pereira181df782012-03-01 13:32:44 -08002575 if (orientationChanged) {
2576 to = cc = bcc = new String[0];
2577 } else {
2578 to = getToAddresses();
2579 cc = getCcAddresses();
2580 bcc = getBccAddresses();
2581 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002582
Mindy Pereira181df782012-03-01 13:32:44 -08002583 // Don't let the user send to nobody (but it's okay to save a message
2584 // with no recipients)
2585 if (!save && (to.length == 0 && cc.length == 0 && bcc.length == 0)) {
2586 showRecipientErrorDialog(getString(R.string.recipient_needed));
2587 return false;
2588 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002589
Mindy Pereira181df782012-03-01 13:32:44 -08002590 List<String> wrongEmails = new ArrayList<String>();
2591 if (!save) {
2592 checkInvalidEmails(to, wrongEmails);
2593 checkInvalidEmails(cc, wrongEmails);
2594 checkInvalidEmails(bcc, wrongEmails);
2595 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002596
Mindy Pereira181df782012-03-01 13:32:44 -08002597 // Don't let the user send an email with invalid recipients
2598 if (wrongEmails.size() > 0) {
2599 String errorText = String.format(getString(R.string.invalid_recipient),
2600 wrongEmails.get(0));
2601 showRecipientErrorDialog(errorText);
2602 return false;
2603 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002604
Mindy Pereira181df782012-03-01 13:32:44 -08002605 // Show a warning before sending only if there are no attachments.
2606 if (!save) {
2607 if (mAttachmentsView.getAttachments().isEmpty() && showEmptyTextWarnings()) {
2608 boolean warnAboutEmptySubject = isSubjectEmpty();
Tony Mantler2558b502013-07-09 10:53:34 -07002609 boolean emptyBody = TextUtils.getTrimmedLength(mBodyView.getEditableText()) == 0;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002610
Mindy Pereira181df782012-03-01 13:32:44 -08002611 // A warning about an empty body may not be warranted when
2612 // forwarding mails, since a common use case is to forward
2613 // quoted text and not append any more text.
2614 boolean warnAboutEmptyBody = emptyBody && (!mForward || isBodyEmpty());
Mindy Pereira82cc5662012-01-09 17:29:30 -08002615
Mindy Pereira181df782012-03-01 13:32:44 -08002616 // When we bring up a dialog warning the user about a send,
2617 // assume that they accept sending the message. If they do not,
2618 // the dialog listener is required to enable sending again.
2619 if (warnAboutEmptySubject) {
Tony Mantler2558b502013-07-09 10:53:34 -07002620 showSendConfirmDialog(R.string.confirm_send_message_with_no_subject, save,
2621 showToast);
Mindy Pereira181df782012-03-01 13:32:44 -08002622 return true;
2623 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002624
Mindy Pereira181df782012-03-01 13:32:44 -08002625 if (warnAboutEmptyBody) {
Tony Mantler2558b502013-07-09 10:53:34 -07002626 showSendConfirmDialog(R.string.confirm_send_message_with_no_body, save,
2627 showToast);
Mindy Pereira181df782012-03-01 13:32:44 -08002628 return true;
2629 }
2630 }
2631 // Ask for confirmation to send (if always required)
2632 if (showSendConfirmation()) {
Tony Mantler2558b502013-07-09 10:53:34 -07002633 showSendConfirmDialog(R.string.confirm_send_message, save, showToast);
Mindy Pereira181df782012-03-01 13:32:44 -08002634 return true;
2635 }
2636 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002637
Tony Mantler2558b502013-07-09 10:53:34 -07002638 sendOrSave(save, showToast);
Mindy Pereira181df782012-03-01 13:32:44 -08002639 return true;
2640 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002641
Mindy Pereira181df782012-03-01 13:32:44 -08002642 /**
2643 * Returns a boolean indicating whether warnings should be shown for empty
2644 * subject and body fields
Andy Huang5c5fd572012-04-08 18:19:29 -07002645 *
Mindy Pereira181df782012-03-01 13:32:44 -08002646 * @return True if a warning should be shown for empty text fields
2647 */
2648 protected boolean showEmptyTextWarnings() {
2649 return mAttachmentsView.getAttachments().size() == 0;
2650 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002651
Mindy Pereira181df782012-03-01 13:32:44 -08002652 /**
2653 * Returns a boolean indicating whether the user should confirm each send
2654 *
2655 * @return True if a warning should be on each send
2656 */
2657 protected boolean showSendConfirmation() {
2658 return mCachedSettings != null ? mCachedSettings.confirmSend : false;
2659 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002660
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07002661 public static class SendConfirmDialogFragment extends DialogFragment
2662 implements DialogInterface.OnClickListener {
2663
2664 private boolean mSave;
2665 private boolean mShowToast;
2666
Paul Westbrookf0ea4842013-08-13 16:41:18 -07002667 // Public no-args constructor needed for fragment re-instantiation
2668 public SendConfirmDialogFragment() {}
2669
Tony Mantler2558b502013-07-09 10:53:34 -07002670 public static SendConfirmDialogFragment newInstance(final int messageId,
2671 final boolean save, final boolean showToast) {
2672 final SendConfirmDialogFragment frag = new SendConfirmDialogFragment();
2673 final Bundle args = new Bundle(3);
2674 args.putInt("messageId", messageId);
2675 args.putBoolean("save", save);
2676 args.putBoolean("showToast", showToast);
2677 frag.setArguments(args);
2678 return frag;
Mindy Pereira181df782012-03-01 13:32:44 -08002679 }
Tony Mantler2558b502013-07-09 10:53:34 -07002680
2681 @Override
2682 public Dialog onCreateDialog(Bundle savedInstanceState) {
2683 final int messageId = getArguments().getInt("messageId");
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07002684 mSave = getArguments().getBoolean("save");
2685 mShowToast = getArguments().getBoolean("showToast");
2686
2687 final int confirmTextId = (messageId == R.string.confirm_send_message) ?
2688 R.string.ok : R.string.send;
Tony Mantler2558b502013-07-09 10:53:34 -07002689
2690 return new AlertDialog.Builder(getActivity())
2691 .setMessage(messageId)
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07002692 .setPositiveButton(confirmTextId, this)
Paul Westbrook7d1c5c42013-10-01 23:40:04 -07002693 .setNegativeButton(R.string.cancel, null)
Tony Mantler2558b502013-07-09 10:53:34 -07002694 .create();
2695 }
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07002696
2697 @Override
2698 public void onClick(DialogInterface dialog, int which) {
2699 if (which == DialogInterface.BUTTON_POSITIVE) {
2700 ((ComposeActivity) getActivity()).finishSendConfirmDialog(mSave, mShowToast);
2701 }
2702 }
Tony Mantler2558b502013-07-09 10:53:34 -07002703 }
2704
2705 private void finishSendConfirmDialog(final boolean save, final boolean showToast) {
2706 sendOrSave(save, showToast);
2707 }
2708
2709 private void showSendConfirmDialog(final int messageId, final boolean save,
2710 final boolean showToast) {
2711 final DialogFragment frag = SendConfirmDialogFragment.newInstance(messageId, save,
2712 showToast);
2713 frag.show(getFragmentManager(), "send confirm");
Mindy Pereira181df782012-03-01 13:32:44 -08002714 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002715
Mindy Pereira181df782012-03-01 13:32:44 -08002716 /**
2717 * Returns whether the ComposeArea believes there is any text in the body of
2718 * the composition. TODO: When ComposeArea controls the Body as well, add
2719 * that here.
2720 */
2721 public boolean isBodyEmpty() {
2722 return !mQuotedTextView.isTextIncluded();
2723 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002724
Mindy Pereira181df782012-03-01 13:32:44 -08002725 /**
2726 * Test to see if the subject is empty.
2727 *
2728 * @return boolean.
2729 */
2730 // TODO: this will likely go away when composeArea.focus() is implemented
2731 // after all the widget control is moved over.
2732 public boolean isSubjectEmpty() {
2733 return TextUtils.getTrimmedLength(mSubject.getText()) == 0;
2734 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002735
Andy Huang0a2a3462013-12-20 15:56:13 -08002736 @VisibleForTesting
2737 public String getSubject() {
2738 return mSubject.getText().toString();
2739 }
2740
Mindy Pereira181df782012-03-01 13:32:44 -08002741 /* package */
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002742 static int sendOrSaveInternal(Context context, ReplyFromAccount replyFromAccount,
Paul Westbrook05b92b82012-04-20 13:29:37 -07002743 Message message, final Message refMessage, Spanned body, final CharSequence quotedText,
mindyp44a63392012-11-05 12:05:16 -08002744 SendOrSaveCallback callback, Handler handler, boolean save, int composeMode,
Scott Kennedy60847252013-08-15 15:55:42 -07002745 ReplyFromAccount draftAccount, final ContentValues extraValues) {
Paul Westbrookb4931c62013-01-14 17:51:18 -08002746 final ContentValues values = new ContentValues();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002747
Paul Westbrookb4931c62013-01-14 17:51:18 -08002748 final String refMessageId = refMessage != null ? refMessage.uri.toString() : "";
Mindy Pereirac2031972012-04-03 09:38:35 -07002749
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002750 MessageModification.putToAddresses(values, message.getToAddresses());
2751 MessageModification.putCcAddresses(values, message.getCcAddresses());
2752 MessageModification.putBccAddresses(values, message.getBccAddresses());
Mindy Pereira82cc5662012-01-09 17:29:30 -08002753
Scott Kennedy8960f0a2012-11-07 15:35:50 -08002754 MessageModification.putCustomFromAddress(values, message.getFrom());
Mindy Pereira92551d02012-04-05 11:31:12 -07002755
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002756 MessageModification.putSubject(values, message.subject);
Paul Westbrookb4931c62013-01-14 17:51:18 -08002757 // Make sure to remove only the composing spans from the Spannable before saving.
2758 final String htmlBody = Html.toHtml(removeComposingSpans(body));
Paul Westbrook05b92b82012-04-20 13:29:37 -07002759
Mindy Pereira29ef1b82012-01-13 11:26:21 -08002760 boolean includeQuotedText = !TextUtils.isEmpty(quotedText);
2761 StringBuilder fullBody = new StringBuilder(htmlBody);
2762 if (includeQuotedText) {
Mindy Pereirae8caf122012-03-20 15:23:31 -07002763 // HTML gets converted to text for now
2764 final String text = quotedText.toString();
2765 if (QuotedTextView.containsQuotedText(text)) {
2766 int pos = QuotedTextView.getQuotedTextOffset(text);
Paul Westbrook55271cf2012-04-20 16:25:02 -07002767 final int quoteStartPos = fullBody.length() + pos;
2768 fullBody.append(text);
2769 MessageModification.putQuoteStartPos(values, quoteStartPos);
Mindy Pereira12575862012-03-21 16:30:54 -07002770 MessageModification.putForward(values, composeMode == ComposeActivity.FORWARD);
Mindy Pereirae8caf122012-03-20 15:23:31 -07002771 MessageModification.putAppendRefMessageContent(values, includeQuotedText);
Mindy Pereira29ef1b82012-01-13 11:26:21 -08002772 } else {
Mindy Pereirae8caf122012-03-20 15:23:31 -07002773 LogUtils.w(LOG_TAG, "Couldn't find quoted text");
2774 // This shouldn't happen, but just use what we have,
2775 // and don't do server-side expansion
2776 fullBody.append(text);
Mindy Pereira29ef1b82012-01-13 11:26:21 -08002777 }
2778 }
Mindy Pereira002ff522012-05-30 10:31:26 -07002779 int draftType = getDraftType(composeMode);
Mindy Pereira12575862012-03-21 16:30:54 -07002780 MessageModification.putDraftType(values, draftType);
Mindy Pereirac6f1e2a2012-04-04 10:33:45 -07002781 if (refMessage != null) {
2782 if (!TextUtils.isEmpty(refMessage.bodyHtml)) {
2783 MessageModification.putBodyHtml(values, fullBody.toString());
2784 }
2785 if (!TextUtils.isEmpty(refMessage.bodyText)) {
mindypc59dd822012-11-13 10:56:21 -08002786 MessageModification.putBody(values,
2787 Utils.convertHtmlToPlainText(fullBody.toString()).toString());
Mindy Pereirac6f1e2a2012-04-04 10:33:45 -07002788 }
2789 } else {
Mindy Pereirac2031972012-04-03 09:38:35 -07002790 MessageModification.putBodyHtml(values, fullBody.toString());
mindypc59dd822012-11-13 10:56:21 -08002791 MessageModification.putBody(values, Utils.convertHtmlToPlainText(fullBody.toString())
2792 .toString());
Mindy Pereirac2031972012-04-03 09:38:35 -07002793 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002794 MessageModification.putAttachments(values, message.getAttachments());
Mindy Pereira12575862012-03-21 16:30:54 -07002795 if (!TextUtils.isEmpty(refMessageId)) {
2796 MessageModification.putRefMessageId(values, refMessageId);
2797 }
Scott Kennedy60847252013-08-15 15:55:42 -07002798 if (extraValues != null) {
2799 values.putAll(extraValues);
2800 }
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002801 SendOrSaveMessage sendOrSaveMessage = new SendOrSaveMessage(context, replyFromAccount,
2802 values, refMessageId, message.getAttachments(), save);
mindyp44a63392012-11-05 12:05:16 -08002803 SendOrSaveTask sendOrSaveTask = new SendOrSaveTask(context, sendOrSaveMessage, callback,
2804 draftAccount);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002805
Mindy Pereira181df782012-03-01 13:32:44 -08002806 callback.initializeSendOrSave(sendOrSaveTask);
Mindy Pereira181df782012-03-01 13:32:44 -08002807 // Do the send/save action on the specified handler to avoid possible
2808 // ANRs
2809 handler.post(sendOrSaveTask);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002810
Mindy Pereira181df782012-03-01 13:32:44 -08002811 return sendOrSaveMessage.requestId();
2812 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002813
Paul Westbrookb4931c62013-01-14 17:51:18 -08002814 /**
2815 * Removes any composing spans from the specified string. This will create a new
2816 * SpannableString instance, as to not modify the behavior of the EditText view.
2817 */
2818 private static SpannableString removeComposingSpans(Spanned body) {
2819 final SpannableString messageBody = new SpannableString(body);
2820 BaseInputConnection.removeComposingSpans(messageBody);
2821 return messageBody;
2822 }
2823
Mindy Pereira002ff522012-05-30 10:31:26 -07002824 private static int getDraftType(int mode) {
2825 int draftType = -1;
2826 switch (mode) {
2827 case ComposeActivity.COMPOSE:
2828 draftType = DraftType.COMPOSE;
2829 break;
2830 case ComposeActivity.REPLY:
2831 draftType = DraftType.REPLY;
2832 break;
2833 case ComposeActivity.REPLY_ALL:
2834 draftType = DraftType.REPLY_ALL;
2835 break;
2836 case ComposeActivity.FORWARD:
2837 draftType = DraftType.FORWARD;
2838 break;
2839 }
2840 return draftType;
2841 }
2842
Tony Mantler2558b502013-07-09 10:53:34 -07002843 private void sendOrSave(final boolean save, final boolean showToast) {
Mindy Pereira181df782012-03-01 13:32:44 -08002844 // Check if user is a monkey. Monkeys can compose and hit send
2845 // button but are not allowed to send anything off the device.
Paul Westbrook3ae824c2012-04-06 13:29:39 -07002846 if (ActivityManager.isUserAMonkey()) {
Mindy Pereira181df782012-03-01 13:32:44 -08002847 return;
2848 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002849
Tony Mantler2558b502013-07-09 10:53:34 -07002850 final Spanned body = mBodyView.getEditableText();
2851
Mindy Pereira181df782012-03-01 13:32:44 -08002852 SendOrSaveCallback callback = new SendOrSaveCallback() {
Andy Huang1f8f4dd2012-10-25 21:35:35 -07002853 // FIXME: unused
Mindy Pereira82cc5662012-01-09 17:29:30 -08002854 private int mRestoredRequestId;
2855
Marc Blank0bbc8582012-04-23 15:07:57 -07002856 @Override
Mindy Pereira82cc5662012-01-09 17:29:30 -08002857 public void initializeSendOrSave(SendOrSaveTask sendOrSaveTask) {
Mindy Pereira181df782012-03-01 13:32:44 -08002858 synchronized (mActiveTasks) {
2859 int numTasks = mActiveTasks.size();
2860 if (numTasks == 0) {
2861 // Start service so we won't be killed if this app is
2862 // put in the background.
2863 startService(new Intent(ComposeActivity.this, EmptyService.class));
2864 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002865
Mindy Pereira181df782012-03-01 13:32:44 -08002866 mActiveTasks.add(sendOrSaveTask);
2867 }
2868 if (sTestSendOrSaveCallback != null) {
2869 sTestSendOrSaveCallback.initializeSendOrSave(sendOrSaveTask);
2870 }
2871 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002872
Marc Blank0bbc8582012-04-23 15:07:57 -07002873 @Override
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002874 public void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage,
2875 Message message) {
Mindy Pereira181df782012-03-01 13:32:44 -08002876 synchronized (mDraftLock) {
mindyp44a63392012-11-05 12:05:16 -08002877 mDraftAccount = sendOrSaveMessage.mAccount;
Mindy Pereira181df782012-03-01 13:32:44 -08002878 mDraftId = message.id;
2879 mDraft = message;
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002880 if (sRequestMessageIdMap != null) {
2881 sRequestMessageIdMap.put(sendOrSaveMessage.requestId(), mDraftId);
2882 }
Mindy Pereira181df782012-03-01 13:32:44 -08002883 // Cache request message map, in case the process is killed
2884 saveRequestMap();
2885 }
2886 if (sTestSendOrSaveCallback != null) {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002887 sTestSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage, message);
Mindy Pereira181df782012-03-01 13:32:44 -08002888 }
2889 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002890
Marc Blank0bbc8582012-04-23 15:07:57 -07002891 @Override
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002892 public Message getMessage() {
2893 synchronized (mDraftLock) {
2894 return mDraft;
2895 }
2896 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002897
Marc Blank0bbc8582012-04-23 15:07:57 -07002898 @Override
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002899 public void sendOrSaveFinished(SendOrSaveTask task, boolean success) {
Mindy Pereira47d0e652012-07-23 09:45:07 -07002900 // Update the last sent from account.
2901 if (mAccount != null) {
2902 MailAppProvider.getInstance().setLastSentFromAccount(mAccount.uri.toString());
2903 }
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002904 if (success) {
2905 // Successfully sent or saved so reset change markers
2906 discardChanges();
2907 } else {
2908 // A failure happened with saving/sending the draft
2909 // TODO(pwestbro): add a better string that should be used
2910 // when failing to send or save
2911 Toast.makeText(ComposeActivity.this, R.string.send_failed, Toast.LENGTH_SHORT)
2912 .show();
2913 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002914
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002915 int numTasks;
2916 synchronized (mActiveTasks) {
2917 // Remove the task from the list of active tasks
2918 mActiveTasks.remove(task);
2919 numTasks = mActiveTasks.size();
2920 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002921
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002922 if (numTasks == 0) {
2923 // Stop service so we can be killed.
2924 stopService(new Intent(ComposeActivity.this, EmptyService.class));
2925 }
2926 if (sTestSendOrSaveCallback != null) {
2927 sTestSendOrSaveCallback.sendOrSaveFinished(task, success);
2928 }
2929 }
Mindy Pereira181df782012-03-01 13:32:44 -08002930 };
Mindy Pereira82cc5662012-01-09 17:29:30 -08002931
Tony Mantler1e05a1e2013-08-12 16:44:26 -07002932 setAccount(mReplyFromAccount.account);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002933
Mindy Pereira181df782012-03-01 13:32:44 -08002934 if (mSendSaveTaskHandler == null) {
2935 HandlerThread handlerThread = new HandlerThread("Send Message Task Thread");
2936 handlerThread.start();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002937
Mindy Pereira181df782012-03-01 13:32:44 -08002938 mSendSaveTaskHandler = new Handler(handlerThread.getLooper());
2939 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002940
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002941 Message msg = createMessage(mReplyFromAccount, getMode());
Paul Westbrook05b92b82012-04-20 13:29:37 -07002942 mRequestId = sendOrSaveInternal(this, mReplyFromAccount, msg, mRefMessage, body,
2943 mQuotedTextView.getQuotedTextIfIncluded(), callback,
Scott Kennedy60847252013-08-15 15:55:42 -07002944 mSendSaveTaskHandler, save, mComposeMode, mDraftAccount, mExtraValues);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002945
Mindy Pereira181df782012-03-01 13:32:44 -08002946 // Don't display the toast if the user is just changing the orientation,
2947 // but we still need to save the draft to the cursor because this is how we restore
2948 // the attachments when the configuration change completes.
2949 if (showToast && (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) {
2950 Toast.makeText(this, save ? R.string.message_saved : R.string.sending_message,
2951 Toast.LENGTH_LONG).show();
2952 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002953
Mindy Pereira181df782012-03-01 13:32:44 -08002954 // Need to update variables here because the send or save completes
2955 // asynchronously even though the toast shows right away.
2956 discardChanges();
2957 updateSaveUi();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002958
Mindy Pereira181df782012-03-01 13:32:44 -08002959 // If we are sending, finish the activity
2960 if (!save) {
2961 finish();
2962 }
2963 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002964
Mindy Pereira181df782012-03-01 13:32:44 -08002965 /**
2966 * Save the state of the request messageid map. This allows for the Gmail
2967 * process to be killed, but and still allow for ComposeActivity instances
2968 * to be recreated correctly.
2969 */
2970 private void saveRequestMap() {
2971 // TODO: store the request map in user preferences.
2972 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002973
Mindy Pereira2db7d4a2012-08-15 11:00:02 -07002974 private void doAttach(String type) {
Mindy Pereira013194c2012-01-06 15:09:33 -08002975 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2976 i.addCategory(Intent.CATEGORY_OPENABLE);
Paul Westbrookd6a9a3f2012-04-26 18:47:23 -07002977 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
Andrew Sapperstein05089f32013-10-01 17:00:03 -07002978 i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
Mindy Pereira2db7d4a2012-08-15 11:00:02 -07002979 i.setType(type);
Mindy Pereira013194c2012-01-06 15:09:33 -08002980 mAddingAttachment = true;
Mindy Pereira181df782012-03-01 13:32:44 -08002981 startActivityForResult(Intent.createChooser(i, getText(R.string.select_attachment_type)),
2982 RESULT_PICK_ATTACHMENT);
Mindy Pereira013194c2012-01-06 15:09:33 -08002983 }
2984
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08002985 private void showCcBccViews() {
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08002986 mCcBccView.show(true, true, true);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08002987 if (mCcBccButton != null) {
mindypcd0b0b92012-08-23 14:33:17 -07002988 mCcBccButton.setVisibility(View.INVISIBLE);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08002989 }
2990 }
2991
Andy Huang4fe0af82013-08-20 17:24:51 -07002992 private static String getActionString(int action) {
Andy Huangdc97bf42013-08-15 16:52:45 -07002993 final String msgType;
Andy Huang4fe0af82013-08-20 17:24:51 -07002994 switch (action) {
Andy Huangdc97bf42013-08-15 16:52:45 -07002995 case COMPOSE:
2996 msgType = "new_message";
2997 break;
2998 case REPLY:
2999 msgType = "reply";
3000 break;
3001 case REPLY_ALL:
3002 msgType = "reply_all";
3003 break;
3004 case FORWARD:
3005 msgType = "forward";
3006 break;
3007 default:
3008 msgType = "unknown";
3009 break;
3010 }
Andy Huang4fe0af82013-08-20 17:24:51 -07003011 return msgType;
3012 }
3013
3014 private void logSendOrSave(boolean save) {
3015 if (!Analytics.isLoggable() || mAttachmentsView == null) {
3016 return;
3017 }
3018
3019 final String category = (save) ? "message_save" : "message_send";
3020 final int attachmentCount = getAttachments().size();
3021 final String msgType = getActionString(mComposeMode);
Andy Huangdc97bf42013-08-15 16:52:45 -07003022 final String label;
3023 final long value;
3024 if (mComposeMode == COMPOSE) {
3025 label = Integer.toString(attachmentCount);
3026 value = attachmentCount;
3027 } else {
3028 label = null;
3029 value = 0;
3030 }
3031 Analytics.getInstance().sendEvent(category, msgType, label, value);
3032 }
3033
Mindy Pereira326c6602012-01-04 15:32:42 -08003034 @Override
3035 public boolean onNavigationItemSelected(int position, long itemId) {
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08003036 int initialComposeMode = mComposeMode;
Mindy Pereira326c6602012-01-04 15:32:42 -08003037 if (position == ComposeActivity.REPLY) {
3038 mComposeMode = ComposeActivity.REPLY;
3039 } else if (position == ComposeActivity.REPLY_ALL) {
3040 mComposeMode = ComposeActivity.REPLY_ALL;
3041 } else if (position == ComposeActivity.FORWARD) {
3042 mComposeMode = ComposeActivity.FORWARD;
3043 }
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07003044 clearChangeListeners();
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08003045 if (initialComposeMode != mComposeMode) {
Mindy Pereira154386a2012-01-11 13:02:33 -08003046 resetMessageForModeChange();
mindyp68c0bfc2012-12-04 10:29:48 -08003047 if (mRefMessage != null) {
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08003048 setFieldsFromRefMessage(mComposeMode);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07003049 }
Mindy Pereiraef388302012-06-18 19:07:44 -07003050 boolean showCc = false;
3051 boolean showBcc = false;
3052 if (mDraft != null) {
3053 // Following desktop behavior, if the user has added a BCC
3054 // field to a draft, we show it regardless of compose mode.
Scott Kennedy8960f0a2012-11-07 15:35:50 -08003055 showBcc = !TextUtils.isEmpty(mDraft.getBcc());
Mindy Pereiraef388302012-06-18 19:07:44 -07003056 // Use the draft to determine what to populate.
3057 // If the Bcc field is showing, show the Cc field whether it is populated or not.
Scott Kennedy8960f0a2012-11-07 15:35:50 -08003058 showCc = showBcc
3059 || (!TextUtils.isEmpty(mDraft.getCc()) && mComposeMode == REPLY_ALL);
mindyp68c0bfc2012-12-04 10:29:48 -08003060 }
3061 if (mRefMessage != null) {
mindyp9b1ac572012-09-27 14:12:00 -07003062 showCc = !TextUtils.isEmpty(mCc.getText());
mindyp68c0bfc2012-12-04 10:29:48 -08003063 showBcc = !TextUtils.isEmpty(mBcc.getText());
Mindy Pereiraef388302012-06-18 19:07:44 -07003064 }
3065 mCcBccView.show(false, showCc, showBcc);
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08003066 }
Mindy Pereiraef388302012-06-18 19:07:44 -07003067 updateHideOrShowCcBcc();
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07003068 initChangeListeners();
Mindy Pereira326c6602012-01-04 15:32:42 -08003069 return true;
3070 }
3071
Mindy Pereirab3112a22012-06-20 12:10:03 -07003072 @VisibleForTesting
3073 protected void resetMessageForModeChange() {
Mindy Pereira154386a2012-01-11 13:02:33 -08003074 // When switching between reply, reply all, forward,
3075 // follow the behavior of webview.
3076 // The contents of the following fields are cleared
3077 // so that they can be populated directly from the
3078 // ref message:
3079 // 1) Any recipient fields
3080 // 2) The subject
3081 mTo.setText("");
3082 mCc.setText("");
3083 mBcc.setText("");
3084 // Any edits to the subject are replaced with the original subject.
3085 mSubject.setText("");
3086
3087 // Any changes to the contents of the following fields are kept:
3088 // 1) Body
3089 // 2) Attachments
3090 // If the user made changes to attachments, keep their changes.
3091 if (!mAttachmentsChanged) {
3092 mAttachmentsView.deleteAllAttachments();
3093 }
3094 }
3095
Mindy Pereira326c6602012-01-04 15:32:42 -08003096 private class ComposeModeAdapter extends ArrayAdapter<String> {
3097
3098 private LayoutInflater mInflater;
3099
3100 public ComposeModeAdapter(Context context) {
3101 super(context, R.layout.compose_mode_item, R.id.mode, getResources()
3102 .getStringArray(R.array.compose_modes));
3103 }
3104
3105 private LayoutInflater getInflater() {
3106 if (mInflater == null) {
3107 mInflater = LayoutInflater.from(getContext());
3108 }
3109 return mInflater;
3110 }
3111
3112 @Override
3113 public View getView(int position, View convertView, ViewGroup parent) {
3114 if (convertView == null) {
3115 convertView = getInflater().inflate(R.layout.compose_mode_display_item, null);
3116 }
3117 ((TextView) convertView.findViewById(R.id.mode)).setText(getItem(position));
3118 return super.getView(position, convertView, parent);
3119 }
3120 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003121
3122 @Override
3123 public void onRespondInline(String text) {
3124 appendToBody(text, false);
mindyp40882432012-09-06 11:07:40 -07003125 mQuotedTextView.setUpperDividerVisible(false);
mindyp1623f9b2012-11-21 12:41:16 -08003126 mRespondedInline = true;
mindyp09dd3732012-12-17 08:37:52 -08003127 if (!mBodyView.hasFocus()) {
mindyp8654d4f2012-12-17 09:01:37 -08003128 mBodyView.requestFocus();
mindyp09dd3732012-12-17 08:37:52 -08003129 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003130 }
3131
3132 /**
3133 * Append text to the body of the message. If there is no existing body
3134 * text, just sets the body to text.
3135 *
3136 * @param text
3137 * @param withSignature True to append a signature.
3138 */
3139 public void appendToBody(CharSequence text, boolean withSignature) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003140 Editable bodyText = mBodyView.getEditableText();
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003141 if (bodyText != null && bodyText.length() > 0) {
3142 bodyText.append(text);
3143 } else {
3144 setBody(text, withSignature);
3145 }
3146 }
3147
3148 /**
3149 * Set the body of the message.
Mindy Pereirabdf7a402012-03-01 15:23:26 -08003150 *
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003151 * @param text
3152 * @param withSignature True to append a signature.
3153 */
3154 public void setBody(CharSequence text, boolean withSignature) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003155 mBodyView.setText(text);
Mindy Pereirabdf7a402012-03-01 15:23:26 -08003156 if (withSignature) {
3157 appendSignature();
3158 }
3159 }
3160
3161 private void appendSignature() {
Mindy Pereirab13917c2012-03-29 08:08:19 -07003162 String newSignature = mCachedSettings != null ? mCachedSettings.signature : null;
Mindy Pereira433b1982012-04-03 11:53:07 -07003163 boolean hasFocus = mBodyView.hasFocus();
mindyp27083062012-11-15 09:02:01 -08003164 int signaturePos = getSignatureStartPosition(mSignature, mBodyView.getText().toString());
3165 if (!TextUtils.equals(newSignature, mSignature) || signaturePos < 0) {
Mindy Pereirab13917c2012-03-29 08:08:19 -07003166 mSignature = newSignature;
mindyp27083062012-11-15 09:02:01 -08003167 if (!TextUtils.isEmpty(mSignature)) {
Mindy Pereirab13917c2012-03-29 08:08:19 -07003168 // Appending a signature does not count as changing text.
3169 mBodyView.removeTextChangedListener(this);
3170 mBodyView.append(convertToPrintableSignature(mSignature));
3171 mBodyView.addTextChangedListener(this);
3172 }
Mindy Pereira433b1982012-04-03 11:53:07 -07003173 if (hasFocus) {
3174 focusBody();
3175 }
Mindy Pereirabdf7a402012-03-01 15:23:26 -08003176 }
3177 }
3178
3179 private String convertToPrintableSignature(String signature) {
3180 String signatureResource = getResources().getString(R.string.signature);
3181 if (signature == null) {
3182 signature = "";
3183 }
3184 return String.format(signatureResource, signature);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003185 }
Mindy Pereira1a95a572012-01-05 12:21:29 -08003186
Mindy Pereira5a85e2b2012-01-11 09:53:32 -08003187 @Override
3188 public void onAccountChanged() {
Mindy Pereira92551d02012-04-05 11:31:12 -07003189 mReplyFromAccount = mFromSpinner.getCurrentAccount();
3190 if (!mAccount.equals(mReplyFromAccount.account)) {
mindypf432dbc2012-11-12 16:00:44 -08003191 // Clear a signature, if there was one.
3192 mBodyView.removeTextChangedListener(this);
3193 String oldSignature = mSignature;
3194 String bodyText = getBody().getText().toString();
3195 if (!TextUtils.isEmpty(oldSignature)) {
3196 int pos = getSignatureStartPosition(oldSignature, bodyText);
3197 if (pos > -1) {
3198 mBodyView.setText(bodyText.substring(0, pos));
3199 }
3200 }
Paul Westbrookb1f573c2012-04-06 11:38:28 -07003201 setAccount(mReplyFromAccount.account);
mindypf432dbc2012-11-12 16:00:44 -08003202 mBodyView.addTextChangedListener(this);
Mindy Pereira181df782012-03-01 13:32:44 -08003203 // TODO: handle discarding attachments when switching accounts.
3204 // Only enable save for this draft if there is any other content
3205 // in the message.
3206 if (!isBlank()) {
3207 enableSave(true);
3208 }
3209 mReplyFromChanged = true;
3210 initRecipients();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003211 }
Mindy Pereira1a95a572012-01-05 12:21:29 -08003212 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003213
3214 public void enableSave(boolean enabled) {
3215 if (mSave != null) {
3216 mSave.setEnabled(enabled);
3217 }
3218 }
3219
Tony Mantler2558b502013-07-09 10:53:34 -07003220 public static class DiscardConfirmDialogFragment extends DialogFragment {
Paul Westbrookf0ea4842013-08-13 16:41:18 -07003221 // Public no-args constructor needed for fragment re-instantiation
3222 public DiscardConfirmDialogFragment() {}
3223
Tony Mantler2558b502013-07-09 10:53:34 -07003224 @Override
3225 public Dialog onCreateDialog(Bundle savedInstanceState) {
3226 return new AlertDialog.Builder(getActivity())
3227 .setMessage(R.string.confirm_discard_text)
3228 .setPositiveButton(R.string.discard,
3229 new DialogInterface.OnClickListener() {
3230 @Override
3231 public void onClick(DialogInterface dialog, int which) {
3232 ((ComposeActivity)getActivity()).doDiscardWithoutConfirmation();
3233 }
3234 })
Tony Mantler2b215b72013-07-31 10:20:46 -07003235 .setNegativeButton(R.string.cancel, null)
Tony Mantler2558b502013-07-09 10:53:34 -07003236 .create();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003237 }
3238 }
3239
Mindy Pereiraefe3d252012-03-01 14:20:44 -08003240 private void doDiscard() {
Tony Mantler2558b502013-07-09 10:53:34 -07003241 final DialogFragment frag = new DiscardConfirmDialogFragment();
3242 frag.show(getFragmentManager(), "discard confirm");
Mindy Pereiraefe3d252012-03-01 14:20:44 -08003243 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003244 /**
3245 * Effectively discard the current message.
3246 *
3247 * This method is either invoked from the menu or from the dialog
3248 * once the user has confirmed that they want to discard the message.
Mindy Pereira82cc5662012-01-09 17:29:30 -08003249 */
Tony Mantler2558b502013-07-09 10:53:34 -07003250 private void doDiscardWithoutConfirmation() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003251 synchronized (mDraftLock) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08003252 if (mDraftId != UIProvider.INVALID_MESSAGE_ID) {
3253 ContentValues values = new ContentValues();
Paul Westbrookb7050e62012-03-20 12:59:44 -07003254 values.put(BaseColumns._ID, mDraftId);
Marc Blank78ea8e22012-08-04 11:14:06 -07003255 if (!mAccount.expungeMessageUri.equals(Uri.EMPTY)) {
Mindy Pereiracfb7f332012-02-28 10:23:43 -08003256 getContentResolver().update(mAccount.expungeMessageUri, values, null, null);
3257 } else {
Marc Blank0bbc8582012-04-23 15:07:57 -07003258 getContentResolver().delete(mDraft.uri, null, null);
Mindy Pereiracfb7f332012-02-28 10:23:43 -08003259 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003260 // This is not strictly necessary (since we should not try to
3261 // save the draft after calling this) but it ensures that if we
3262 // do save again for some reason we make a new draft rather than
3263 // trying to resave an expunged draft.
3264 mDraftId = UIProvider.INVALID_MESSAGE_ID;
3265 }
3266 }
3267
Tony Mantler2558b502013-07-09 10:53:34 -07003268 // Display a toast to let the user know
3269 Toast.makeText(this, R.string.message_discarded, Toast.LENGTH_SHORT).show();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003270
3271 // This prevents the draft from being saved in onPause().
3272 discardChanges();
Andy Huangdc97bf42013-08-15 16:52:45 -07003273 mPerformedSendOrDiscard = true;
Mindy Pereira82cc5662012-01-09 17:29:30 -08003274 finish();
3275 }
3276
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003277 private void saveIfNeeded() {
3278 if (mAccount == null) {
3279 // We have not chosen an account yet so there's no way that we can save. This is ok,
3280 // though, since we are saving our state before AccountsActivity is activated. Thus, the
3281 // user has not interacted with us yet and there is no real state to save.
3282 return;
3283 }
3284
3285 if (shouldSave()) {
Mindy Pereira48e31b02012-05-30 13:12:24 -07003286 doSave(!mAddingAttachment /* show toast */);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003287 }
3288 }
3289
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003290 @Override
3291 public void onAttachmentDeleted() {
3292 mAttachmentsChanged = true;
mindyp40882432012-09-06 11:07:40 -07003293 // If we are showing any attachments, make sure we have an upper
3294 // divider.
3295 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003296 updateSaveUi();
3297 }
Mindy Pereira75f66632012-01-11 11:42:02 -08003298
mindyp40882432012-09-06 11:07:40 -07003299 @Override
3300 public void onAttachmentAdded() {
3301 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
3302 mAttachmentsView.focusLastAttachment();
3303 }
Mindy Pereira75f66632012-01-11 11:42:02 -08003304
3305 /**
3306 * This is called any time one of our text fields changes.
3307 */
Marc Blank0bbc8582012-04-23 15:07:57 -07003308 @Override
Mindy Pereira75f66632012-01-11 11:42:02 -08003309 public void afterTextChanged(Editable s) {
3310 mTextChanged = true;
3311 updateSaveUi();
3312 }
3313
3314 @Override
3315 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3316 // Do nothing.
3317 }
3318
Marc Blank0bbc8582012-04-23 15:07:57 -07003319 @Override
Mindy Pereira75f66632012-01-11 11:42:02 -08003320 public void onTextChanged(CharSequence s, int start, int before, int count) {
3321 // Do nothing.
3322 }
3323
3324
3325 // There is a big difference between the text associated with an address changing
3326 // to add the display name or to format properly and a recipient being added or deleted.
3327 // Make sure we only notify of changes when a recipient has been added or deleted.
3328 private class RecipientTextWatcher implements TextWatcher {
3329 private HashMap<String, Integer> mContent = new HashMap<String, Integer>();
3330
3331 private RecipientEditTextView mView;
3332
3333 private TextWatcher mListener;
3334
3335 public RecipientTextWatcher(RecipientEditTextView view, TextWatcher listener) {
3336 mView = view;
3337 mListener = listener;
3338 }
3339
3340 @Override
3341 public void afterTextChanged(Editable s) {
3342 if (hasChanged()) {
3343 mListener.afterTextChanged(s);
3344 }
3345 }
3346
3347 private boolean hasChanged() {
3348 String[] currRecips = tokenizeRecips(getAddressesFromList(mView));
3349 int totalCount = currRecips.length;
3350 int totalPrevCount = 0;
3351 for (Entry<String, Integer> entry : mContent.entrySet()) {
3352 totalPrevCount += entry.getValue();
3353 }
3354 if (totalCount != totalPrevCount) {
3355 return true;
3356 }
3357
3358 for (String recip : currRecips) {
3359 if (!mContent.containsKey(recip)) {
3360 return true;
3361 } else {
3362 int count = mContent.get(recip) - 1;
3363 if (count < 0) {
3364 return true;
3365 } else {
3366 mContent.put(recip, count);
3367 }
3368 }
3369 }
3370 return false;
3371 }
3372
3373 private String[] tokenizeRecips(String[] recips) {
3374 // Tokenize them all and put them in the list.
3375 String[] recipAddresses = new String[recips.length];
3376 for (int i = 0; i < recips.length; i++) {
3377 recipAddresses[i] = Rfc822Tokenizer.tokenize(recips[i])[0].getAddress();
3378 }
3379 return recipAddresses;
3380 }
3381
3382 @Override
3383 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3384 String[] recips = tokenizeRecips(getAddressesFromList(mView));
3385 for (String recip : recips) {
3386 if (!mContent.containsKey(recip)) {
3387 mContent.put(recip, 1);
3388 } else {
3389 mContent.put(recip, (mContent.get(recip)) + 1);
3390 }
3391 }
3392 }
3393
3394 @Override
3395 public void onTextChanged(CharSequence s, int start, int before, int count) {
3396 // Do nothing.
3397 }
3398 }
Mindy Pereirae011b1d2012-06-18 13:45:26 -07003399
3400 public static void registerTestSendOrSaveCallback(SendOrSaveCallback testCallback) {
3401 if (sTestSendOrSaveCallback != null && testCallback != null) {
3402 throw new IllegalStateException("Attempting to register more than one test callback");
3403 }
3404 sTestSendOrSaveCallback = testCallback;
3405 }
Mindy Pereirabddd6f32012-06-20 12:10:03 -07003406
3407 @VisibleForTesting
3408 protected ArrayList<Attachment> getAttachments() {
3409 return mAttachmentsView.getAttachments();
3410 }
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003411
3412 @Override
3413 public Loader<Cursor> onCreateLoader(int id, Bundle args) {
3414 switch (id) {
Alice Yanga990a712013-03-13 18:37:00 -07003415 case INIT_DRAFT_USING_REFERENCE_MESSAGE:
3416 return new CursorLoader(this, mRefMessageUri, UIProvider.MESSAGE_PROJECTION, null,
3417 null, null);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003418 case REFERENCE_MESSAGE_LOADER:
3419 return new CursorLoader(this, mRefMessageUri, UIProvider.MESSAGE_PROJECTION, null,
3420 null, null);
Mindy Pereirab199d172012-08-13 11:04:03 -07003421 case LOADER_ACCOUNT_CURSOR:
3422 return new CursorLoader(this, MailAppProvider.getAccountsUri(),
3423 UIProvider.ACCOUNTS_PROJECTION, null, null, null);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003424 }
3425 return null;
3426 }
3427
3428 @Override
3429 public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Mindy Pereirab199d172012-08-13 11:04:03 -07003430 int id = loader.getId();
3431 switch (id) {
Alice Yanga990a712013-03-13 18:37:00 -07003432 case INIT_DRAFT_USING_REFERENCE_MESSAGE:
Mindy Pereirab199d172012-08-13 11:04:03 -07003433 if (data != null && data.moveToFirst()) {
3434 mRefMessage = new Message(data);
Mindy Pereirab199d172012-08-13 11:04:03 -07003435 Intent intent = getIntent();
Alice Yanga990a712013-03-13 18:37:00 -07003436 initFromRefMessage(mComposeMode);
3437 finishSetup(mComposeMode, intent, null);
3438 if (mComposeMode != FORWARD) {
Mindy Pereirab199d172012-08-13 11:04:03 -07003439 String to = intent.getStringExtra(EXTRA_TO);
3440 if (!TextUtils.isEmpty(to)) {
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08003441 mRefMessage.setTo(null);
3442 mRefMessage.setFrom(null);
Mindy Pereirab199d172012-08-13 11:04:03 -07003443 clearChangeListeners();
3444 mTo.append(to);
3445 initChangeListeners();
3446 }
3447 }
3448 } else {
3449 finish();
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003450 }
Mindy Pereirab199d172012-08-13 11:04:03 -07003451 break;
Alice Yanga990a712013-03-13 18:37:00 -07003452 case REFERENCE_MESSAGE_LOADER:
3453 // Only populate mRefMessage and leave other fields untouched.
3454 if (data != null && data.moveToFirst()) {
3455 mRefMessage = new Message(data);
3456 }
Andy Huang9f855d62013-05-30 17:15:03 -07003457 finishSetup(mComposeMode, getIntent(), mInnerSavedState);
Alice Yanga990a712013-03-13 18:37:00 -07003458 break;
Mindy Pereirab199d172012-08-13 11:04:03 -07003459 case LOADER_ACCOUNT_CURSOR:
3460 if (data != null && data.moveToFirst()) {
3461 // there are accounts now!
3462 Account account;
Paul Westbrookfaa742f2012-11-01 09:50:16 -07003463 final ArrayList<Account> accounts = new ArrayList<Account>();
3464 final ArrayList<Account> initializedAccounts = new ArrayList<Account>();
Mindy Pereirab199d172012-08-13 11:04:03 -07003465 do {
3466 account = new Account(data);
Paul Westbrookdfa1dec2012-09-26 16:27:28 -07003467 if (account.isAccountReady()) {
Mindy Pereirab199d172012-08-13 11:04:03 -07003468 initializedAccounts.add(account);
3469 }
3470 accounts.add(account);
3471 } while (data.moveToNext());
3472 if (initializedAccounts.size() > 0) {
3473 findViewById(R.id.wait).setVisibility(View.GONE);
3474 getLoaderManager().destroyLoader(LOADER_ACCOUNT_CURSOR);
3475 findViewById(R.id.compose).setVisibility(View.VISIBLE);
Paul Westbrookfaa742f2012-11-01 09:50:16 -07003476 mAccounts = initializedAccounts.toArray(
3477 new Account[initializedAccounts.size()]);
3478
Mindy Pereirab199d172012-08-13 11:04:03 -07003479 finishCreate();
3480 invalidateOptionsMenu();
3481 } else {
3482 // Show "waiting"
3483 account = accounts.size() > 0 ? accounts.get(0) : null;
3484 showWaitFragment(account);
3485 }
3486 }
3487 break;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003488 }
3489 }
3490
Mindy Pereirab199d172012-08-13 11:04:03 -07003491 private void showWaitFragment(Account account) {
3492 WaitFragment fragment = getWaitFragment();
3493 if (fragment != null) {
3494 fragment.updateAccount(account);
3495 } else {
3496 findViewById(R.id.wait).setVisibility(View.VISIBLE);
3497 replaceFragment(WaitFragment.newInstance(account, true),
3498 FragmentTransaction.TRANSIT_FRAGMENT_OPEN, TAG_WAIT);
3499 }
3500 }
3501
3502 private WaitFragment getWaitFragment() {
3503 return (WaitFragment) getFragmentManager().findFragmentByTag(TAG_WAIT);
3504 }
3505
3506 private int replaceFragment(Fragment fragment, int transition, String tag) {
3507 FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
Mindy Pereirab199d172012-08-13 11:04:03 -07003508 fragmentTransaction.setTransition(transition);
3509 fragmentTransaction.replace(R.id.wait, fragment, tag);
3510 final int transactionId = fragmentTransaction.commitAllowingStateLoss();
3511 return transactionId;
3512 }
3513
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003514 @Override
3515 public void onLoaderReset(Loader<Cursor> arg0) {
3516 // Do nothing.
3517 }
Paul Westbrook83e6b572013-02-05 16:22:42 -08003518
3519 @Override
3520 public Context getActivityContext() {
3521 return this;
3522 }
Andy Huang1f8f4dd2012-10-25 21:35:35 -07003523}