blob: fa281ce79ba307db319c6d3cabfc8b3b4880e431 [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
Tony Mantler581edd42014-02-18 15:41:22 -080019import android.annotation.SuppressLint;
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -070020import android.annotation.TargetApi;
Andy Huang5c5fd572012-04-08 18:19:29 -070021import 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;
Jin Caoadae7a32014-09-09 18:16:25 -070030import android.content.ClipDescription;
Mindy Pereira6349a042012-01-04 11:25:01 -080031import android.content.ContentResolver;
Mindy Pereira82cc5662012-01-09 17:29:30 -080032import android.content.ContentValues;
Mindy Pereira6349a042012-01-04 11:25:01 -080033import android.content.Context;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -070034import android.content.CursorLoader;
Mindy Pereira82cc5662012-01-09 17:29:30 -080035import android.content.DialogInterface;
Mindy Pereira6349a042012-01-04 11:25:01 -080036import android.content.Intent;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -070037import android.content.Loader;
Mindy Pereira82cc5662012-01-09 17:29:30 -080038import android.content.pm.ActivityInfo;
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -070039import android.content.res.Resources;
Mindy Pereira7ed1c112012-01-18 10:59:25 -080040import android.database.Cursor;
Jin Cao36e23872014-07-29 13:41:12 -070041import android.graphics.Rect;
Mindy Pereira6349a042012-01-04 11:25:01 -080042import android.net.Uri;
Alan Lau15490232014-03-06 14:53:14 -080043import android.os.AsyncTask;
Andrew Sapperstein05089f32013-10-01 17:00:03 -070044import android.os.Build;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080045import android.os.Bundle;
Jin Caoadea2c82014-08-28 12:25:52 -070046import android.os.Environment;
Mindy Pereira82cc5662012-01-09 17:29:30 -080047import android.os.Handler;
48import android.os.HandlerThread;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -070049import android.os.ParcelFileDescriptor;
Mindy Pereira82cc5662012-01-09 17:29:30 -080050import android.provider.BaseColumns;
Alan Lau439aa5d2014-05-27 17:57:13 -070051import android.support.v4.app.RemoteInput;
Andrew Sapperstein52882ff2014-07-27 12:30:18 -070052import android.support.v7.app.ActionBar;
53import android.support.v7.app.ActionBarActivity;
Andrew Sapperstein734718a2014-09-15 17:29:13 -070054import android.support.v7.view.ActionMode;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080055import android.text.Editable;
Mindy Pereira82cc5662012-01-09 17:29:30 -080056import android.text.Html;
Andy Huangff017272014-06-18 00:27:35 -070057import android.text.SpanWatcher;
mindyped9c2f02012-10-12 10:02:08 -070058import android.text.SpannableString;
Mindy Pereira82cc5662012-01-09 17:29:30 -080059import android.text.Spanned;
Paul Westbrookc1827622012-01-06 11:27:12 -080060import android.text.TextUtils;
Mindy Pereira82cc5662012-01-09 17:29:30 -080061import android.text.TextWatcher;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080062import android.text.util.Rfc822Token;
Mindy Pereirac17d0732011-12-29 10:46:19 -080063import android.text.util.Rfc822Tokenizer;
Mindy Pereira3cd4f402012-07-17 11:16:18 -070064import android.view.Gravity;
mindyp62d3ec72012-08-24 13:04:09 -070065import android.view.KeyEvent;
Mindy Pereira326c6602012-01-04 15:32:42 -080066import android.view.LayoutInflater;
Mindy Pereirab47f3e22011-12-13 14:25:04 -080067import android.view.Menu;
68import android.view.MenuInflater;
69import android.view.MenuItem;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080070import android.view.View;
71import android.view.View.OnClickListener;
Andy Huang5c5fd572012-04-08 18:19:29 -070072import android.view.ViewGroup;
Andrew Sapperstein734718a2014-09-15 17:29:13 -070073import android.view.Window;
Paul Westbrookb4931c62013-01-14 17:51:18 -080074import android.view.inputmethod.BaseInputConnection;
mindyp62d3ec72012-08-24 13:04:09 -070075import android.view.inputmethod.EditorInfo;
Mindy Pereira326c6602012-01-04 15:32:42 -080076import android.widget.ArrayAdapter;
Mindy Pereira433b1982012-04-03 11:53:07 -070077import android.widget.EditText;
Jin Cao36e23872014-07-29 13:41:12 -070078import android.widget.ScrollView;
Mindy Pereira6349a042012-01-04 11:25:01 -080079import android.widget.TextView;
Mindy Pereira013194c2012-01-06 15:09:33 -080080import android.widget.Toast;
Mindy Pereira7b56a612011-12-14 12:32:28 -080081
Mindy Pereirac17d0732011-12-29 10:46:19 -080082import com.android.common.Rfc822Validator;
Tony Mantler9f324232013-08-08 14:24:30 -070083import com.android.common.contacts.DataUsageStatUpdater;
Tony Mantler821e5782014-01-06 15:33:43 -080084import com.android.emailcommon.mail.Address;
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -070085import com.android.ex.chips.BaseRecipientAdapter;
86import com.android.ex.chips.DropdownChipLayouter;
Andy Huang5c5fd572012-04-08 18:19:29 -070087import com.android.ex.chips.RecipientEditTextView;
Scott Kennedy5680ec22013-01-07 13:15:20 -080088import com.android.mail.MailIntentService;
Andy Huang5c5fd572012-04-08 18:19:29 -070089import com.android.mail.R;
Andy Huang761522c2013-08-08 13:09:11 -070090import com.android.mail.analytics.Analytics;
Alice Yang1ebc2db2013-03-14 21:21:44 -070091import com.android.mail.browse.MessageHeaderView;
mindyp40882432012-09-06 11:07:40 -070092import com.android.mail.compose.AttachmentsView.AttachmentAddedOrDeletedListener;
Mindy Pereira9932dee2012-01-10 16:09:50 -080093import com.android.mail.compose.AttachmentsView.AttachmentFailureException;
Mindy Pereira5a85e2b2012-01-11 09:53:32 -080094import com.android.mail.compose.FromAddressSpinner.OnAccountChangedListener;
Andy Huang30e2c242012-01-06 18:14:30 -080095import com.android.mail.compose.QuotedTextView.RespondInlineListener;
Mindy Pereira33fe9082012-01-09 16:24:30 -080096import com.android.mail.providers.Account;
Andy Huang30e2c242012-01-06 18:14:30 -080097import com.android.mail.providers.Attachment;
Scott Kennedy5680ec22013-01-07 13:15:20 -080098import com.android.mail.providers.Folder;
Mindy Pereira47d0e652012-07-23 09:45:07 -070099import com.android.mail.providers.MailAppProvider;
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800100import com.android.mail.providers.Message;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800101import com.android.mail.providers.MessageModification;
Mindy Pereira92551d02012-04-05 11:31:12 -0700102import com.android.mail.providers.ReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -0800103import com.android.mail.providers.Settings;
Andy Huang30e2c242012-01-06 18:14:30 -0800104import com.android.mail.providers.UIProvider;
Mindy Pereira3ca5bad2012-04-16 11:02:42 -0700105import com.android.mail.providers.UIProvider.AccountCapabilities;
Mindy Pereira12575862012-03-21 16:30:54 -0700106import com.android.mail.providers.UIProvider.DraftType;
Alice Yang1ebc2db2013-03-14 21:21:44 -0700107import com.android.mail.ui.AttachmentTile.AttachmentPreview;
Mindy Pereirafa20c1a2012-07-23 13:00:02 -0700108import com.android.mail.ui.MailActivity;
Mindy Pereirab199d172012-08-13 11:04:03 -0700109import com.android.mail.ui.WaitFragment;
Paul Westbrook92227f62012-03-20 10:32:51 -0700110import com.android.mail.utils.AccountUtils;
Mark Wei434f2942012-08-24 11:54:02 -0700111import com.android.mail.utils.AttachmentUtils;
mindypfebd2262012-11-13 17:45:09 -0800112import com.android.mail.utils.ContentProviderTask;
Jin Cao77b4c2c2014-05-20 13:55:53 -0700113import com.android.mail.utils.HtmlUtils;
Paul Westbrookb334c902012-06-25 11:42:46 -0700114import com.android.mail.utils.LogTag;
Andy Huang30e2c242012-01-06 18:14:30 -0800115import com.android.mail.utils.LogUtils;
Alan Lau15490232014-03-06 14:53:14 -0800116import com.android.mail.utils.NotificationActionUtils;
Andy Huang30e2c242012-01-06 18:14:30 -0800117import com.android.mail.utils.Utils;
Andy Huang9ed742c2014-06-18 02:34:50 -0700118import com.google.android.mail.common.html.parser.HtmlTree;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800119import com.google.common.annotations.VisibleForTesting;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800120import com.google.common.collect.Lists;
Mindy Pereira4a27ea92012-01-05 15:55:25 -0800121import com.google.common.collect.Sets;
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800122
Jin Caoadea2c82014-08-28 12:25:52 -0700123import java.io.File;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -0700124import java.io.FileNotFoundException;
125import java.io.IOException;
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700126import java.io.UnsupportedEncodingException;
127import java.net.URLDecoder;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800128import java.util.ArrayList;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700129import java.util.Arrays;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800130import java.util.Collection;
Mindy Pereira75f66632012-01-11 11:42:02 -0800131import java.util.HashMap;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800132import java.util.HashSet;
133import java.util.List;
Paul Westbrook1c078cf2012-03-20 16:18:51 -0700134import java.util.Map.Entry;
Jin Cao31bb3d62014-09-11 14:01:43 -0700135import java.util.Random;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700136import java.util.Set;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800137import java.util.concurrent.ConcurrentHashMap;
Jin Caoaff451f2014-09-09 14:32:04 -0700138import java.util.concurrent.atomic.AtomicInteger;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800139
Andrew Sapperstein52882ff2014-07-27 12:30:18 -0700140public class ComposeActivity extends ActionBarActivity
141 implements OnClickListener, ActionBar.OnNavigationListener,
Tony Mantler2558b502013-07-09 10:53:34 -0700142 RespondInlineListener, TextWatcher,
Alice Yanga990a712013-03-13 18:37:00 -0700143 AttachmentAddedOrDeletedListener, OnAccountChangedListener,
Andrew Sappersteinffd61552014-05-14 15:04:23 -0700144 LoaderManager.LoaderCallbacks<Cursor>, TextView.OnEditorActionListener,
Jin Caoc5c550a2014-07-29 11:53:17 -0700145 RecipientEditTextView.RecipientEntryItemClickedListener, View.OnFocusChangeListener {
Scott Kennedya0287a82014-04-07 14:30:13 -0700146 /**
147 * An {@link Intent} action that launches {@link ComposeActivity}, but is handled as if the
148 * {@link Activity} were launched with no special action.
149 */
150 private static final String ACTION_LAUNCH_COMPOSE =
151 "com.android.mail.intent.action.LAUNCH_COMPOSE";
152
Mindy Pereira6349a042012-01-04 11:25:01 -0800153 // Identifiers for which type of composition this is
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700154 public static final int COMPOSE = -1;
155 public static final int REPLY = 0;
156 public static final int REPLY_ALL = 1;
157 public static final int FORWARD = 2;
158 public static final int EDIT_DRAFT = 3;
Mindy Pereira6349a042012-01-04 11:25:01 -0800159
160 // Integer extra holding one of the above compose action
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700161 protected static final String EXTRA_ACTION = "action";
Mindy Pereira6349a042012-01-04 11:25:01 -0800162
Mindy Pereira326689d2012-05-17 10:14:14 -0700163 private static final String EXTRA_SHOW_CC = "showCc";
164 private static final String EXTRA_SHOW_BCC = "showBcc";
mindyp1623f9b2012-11-21 12:41:16 -0800165 private static final String EXTRA_RESPONDED_INLINE = "respondedInline";
mindyp1d7e9142012-11-21 13:54:30 -0800166 private static final String EXTRA_SAVE_ENABLED = "saveEnabled";
Mindy Pereiraa34c9a02012-04-17 14:10:53 -0700167
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700168 private static final String UTF8_ENCODING_NAME = "UTF-8";
169
170 private static final String MAIL_TO = "mailto";
171
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700172 private static final String EXTRA_SUBJECT = "subject";
173
174 private static final String EXTRA_BODY = "body";
Jin Cao1fdbe1f2014-08-19 13:51:26 -0700175 private static final String EXTRA_TEXT_CHANGED ="extraTextChanged";
176
177 private static final String EXTRA_SKIP_PARSING_BODY = "extraSkipParsingBody";
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700178
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700179 /**
180 * Expected to be html formatted text.
181 */
182 private static final String EXTRA_QUOTED_TEXT = "quotedText";
183
mindypd27b6ea2012-10-05 09:43:49 -0700184 protected static final String EXTRA_FROM_ACCOUNT_STRING = "fromAccountString";
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700185
Mark Wei62066e42012-09-13 12:07:02 -0700186 private static final String EXTRA_ATTACHMENT_PREVIEWS = "attachmentPreviews";
187
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700188 // Extra that we can get passed from other activities
Tony Mantler184ec732013-10-24 13:13:49 -0700189 @VisibleForTesting
190 protected static final String EXTRA_TO = "to";
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700191 private static final String EXTRA_CC = "cc";
192 private static final String EXTRA_BCC = "bcc";
193
Scott Kennedy60847252013-08-15 15:55:42 -0700194 /**
195 * An optional extra containing a {@link ContentValues} of values to be added to
196 * {@link SendOrSaveMessage#mValues}.
197 */
198 public static final String EXTRA_VALUES = "extra-values";
199
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700200 // List of all the fields
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700201 static final String[] ALL_EXTRAS = { EXTRA_SUBJECT, EXTRA_BODY, EXTRA_TO, EXTRA_CC, EXTRA_BCC,
202 EXTRA_QUOTED_TEXT };
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700203
Alan Lau439aa5d2014-05-27 17:57:13 -0700204 private static final String LEGACY_WEAR_EXTRA = "com.google.android.wearable.extras";
205
Andrew Sapperstein09da9422014-05-30 09:48:08 -0700206 /**
207 * Constant value for the threshold to use for auto-complete suggestions
208 * for the to/cc/bcc fields.
209 */
210 private static final int COMPLETION_THRESHOLD = 1;
211
Mindy Pereira82cc5662012-01-09 17:29:30 -0800212 private static SendOrSaveCallback sTestSendOrSaveCallback = null;
213 // Map containing information about requests to create new messages, and the id of the
214 // messages that were the result of those requests.
215 //
216 // This map is used when the activity that initiated the save a of a new message, is killed
217 // before the save has completed (and when we know the id of the newly created message). When
218 // a save is completed, the service that is running in the background, will update the map
219 //
220 // When a new ComposeActivity instance is created, it will attempt to use the information in
221 // the previously instantiated map. If ComposeActivity.onCreate() is called, with a bundle
222 // (restoring data from a previous instance), and the map hasn't been created, we will attempt
223 // to populate the map with data stored in shared preferences.
Jin Cao31bb3d62014-09-11 14:01:43 -0700224 private static final ConcurrentHashMap<Integer, Long> sRequestMessageIdMap =
225 new ConcurrentHashMap<Integer, Long>(10);
226 private static final Random sRandom = new Random(System.currentTimeMillis());
227
Mindy Pereira6349a042012-01-04 11:25:01 -0800228 /**
229 * Notifies the {@code Activity} that the caller is an Email
230 * {@code Activity}, so that the back behavior may be modified accordingly.
231 *
232 * @see #onAppUpPressed
233 */
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700234 public static final String EXTRA_FROM_EMAIL_TASK = "fromemail";
Mindy Pereira6349a042012-01-04 11:25:01 -0800235
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700236 public static final String EXTRA_ATTACHMENTS = "attachments";
Paul Westbrookf97588b2012-03-20 11:11:37 -0700237
Scott Kennedy5680ec22013-01-07 13:15:20 -0800238 /** If set, we will clear notifications for this folder. */
239 public static final String EXTRA_NOTIFICATION_FOLDER = "extra-notification-folder";
Alan Laue806c942014-06-06 16:19:15 -0700240 public static final String EXTRA_NOTIFICATION_CONVERSATION = "extra-notification-conversation";
Scott Kennedy5680ec22013-01-07 13:15:20 -0800241
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800242 // If this is a reply/forward then this extra will hold the original message
Mindy Pereira36bbcae2012-04-25 09:27:04 -0700243 private static final String EXTRA_IN_REFERENCE_TO_MESSAGE = "in-reference-to-message";
Mindy Pereirab18e5a92012-07-10 11:47:21 -0700244 // If this is a reply/forward then this extra will hold a uri we must query
245 // to get the original message.
246 protected static final String EXTRA_IN_REFERENCE_TO_MESSAGE_URI = "in-reference-to-message-uri";
Mark Wei434f2942012-08-24 11:54:02 -0700247 // If this is an action to edit an existing draft message, this extra will hold the
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700248 // draft message
249 private static final String ORIGINAL_DRAFT_MESSAGE = "original-draft-message";
Mindy Pereira4a27ea92012-01-05 15:55:25 -0800250 private static final String END_TOKEN = ", ";
Paul Westbrookb334c902012-06-25 11:42:46 -0700251 private static final String LOG_TAG = LogTag.getLogTag();
Mindy Pereira013194c2012-01-06 15:09:33 -0800252 // Request numbers for activities we start
253 private static final int RESULT_PICK_ATTACHMENT = 1;
254 private static final int RESULT_CREATE_ACCOUNT = 2;
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700255 // TODO(mindyp) set mime-type for auto send?
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700256 public static final String AUTO_SEND_ACTION = "com.android.mail.action.AUTO_SEND";
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700257
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700258 private static final String EXTRA_SELECTED_REPLY_FROM_ACCOUNT = "replyFromAccount";
259 private static final String EXTRA_REQUEST_ID = "requestId";
260 private static final String EXTRA_FOCUS_SELECTION_START = "focusSelectionStart";
Paul Westbrook176a1992013-07-22 13:57:19 -0700261 private static final String EXTRA_FOCUS_SELECTION_END = "focusSelectionEnd";
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700262 private static final String EXTRA_MESSAGE = "extraMessage";
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700263 private static final int REFERENCE_MESSAGE_LOADER = 0;
Mindy Pereirab199d172012-08-13 11:04:03 -0700264 private static final int LOADER_ACCOUNT_CURSOR = 1;
Alice Yanga990a712013-03-13 18:37:00 -0700265 private static final int INIT_DRAFT_USING_REFERENCE_MESSAGE = 2;
Mindy Pereira47d0e652012-07-23 09:45:07 -0700266 private static final String EXTRA_SELECTED_ACCOUNT = "selectedAccount";
Mindy Pereirab199d172012-08-13 11:04:03 -0700267 private static final String TAG_WAIT = "wait-fragment";
Andrew Sapperstein5cb71802013-10-01 18:31:20 -0700268 private static final String MIME_TYPE_ALL = "*/*";
Mindy Pereira2db7d4a2012-08-15 11:00:02 -0700269 private static final String MIME_TYPE_PHOTO = "image/*";
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800270
Andy Huang9f855d62013-05-30 17:15:03 -0700271 private static final String KEY_INNER_SAVED_STATE = "compose_state";
272
Jin Caoadea2c82014-08-28 12:25:52 -0700273 // A single thread for running tasks in the background.
274 private static final Handler SEND_SAVE_TASK_HANDLER;
Jin Caoaff451f2014-09-09 14:32:04 -0700275 @VisibleForTesting
276 public static final AtomicInteger PENDING_SEND_OR_SAVE_TASKS_NUM = new AtomicInteger(0);
277
Jin Caoadea2c82014-08-28 12:25:52 -0700278 // String representing the uri of the data directory (used for attachment uri checking).
279 private static final String DATA_DIRECTORY_ROOT;
Jin Cao24ed2942014-09-02 10:21:37 -0700280 private static final String ALTERNATE_DATA_DIRECTORY_ROOT;
Jin Caoadea2c82014-08-28 12:25:52 -0700281
282 // Static initializations
Jin Cao5134be52014-05-06 19:18:38 -0700283 static {
284 HandlerThread handlerThread = new HandlerThread("Send Message Task Thread");
285 handlerThread.start();
Jin Cao5134be52014-05-06 19:18:38 -0700286 SEND_SAVE_TASK_HANDLER = new Handler(handlerThread.getLooper());
Jin Caoadea2c82014-08-28 12:25:52 -0700287
288 DATA_DIRECTORY_ROOT = Environment.getDataDirectory().toString();
Jin Cao24ed2942014-09-02 10:21:37 -0700289 ALTERNATE_DATA_DIRECTORY_ROOT = DATA_DIRECTORY_ROOT + DATA_DIRECTORY_ROOT;
Jin Cao5134be52014-05-06 19:18:38 -0700290 }
291
Jin Caocfba4bb2014-10-07 19:29:15 -0700292 private final Rect mRect = new Rect();
293
Jin Cao36e23872014-07-29 13:41:12 -0700294 private ScrollView mScrollView;
Mindy Pereirac17d0732011-12-29 10:46:19 -0800295 private RecipientEditTextView mTo;
296 private RecipientEditTextView mCc;
297 private RecipientEditTextView mBcc;
Jin Cao9d358a12014-07-24 12:15:38 -0700298 private View mCcBccButton;
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800299 private CcBccView mCcBccView;
Mindy Pereira7b56a612011-12-14 12:32:28 -0800300 private AttachmentsView mAttachmentsView;
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700301 protected Account mAccount;
Tony Mantler59e69092013-08-14 11:05:00 -0700302 protected ReplyFromAccount mReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -0800303 private Settings mCachedSettings;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800304 private Rfc822Validator mValidator;
Mindy Pereira6349a042012-01-04 11:25:01 -0800305 private TextView mSubject;
306
Mindy Pereira326c6602012-01-04 15:32:42 -0800307 private ComposeModeAdapter mComposeModeAdapter;
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700308 protected int mComposeMode = -1;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800309 private boolean mForward;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800310 private QuotedTextView mQuotedTextView;
Tony Mantler59e69092013-08-14 11:05:00 -0700311 protected EditText mBodyView;
Mindy Pereira1a95a572012-01-05 12:21:29 -0800312 private View mFromStatic;
Mindy Pereira2eb17322012-03-07 10:07:34 -0800313 private TextView mFromStaticText;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800314 private View mFromSpinnerWrapper;
Mindy Pereira1883b342012-06-20 08:34:56 -0700315 @VisibleForTesting
316 protected FromAddressSpinner mFromSpinner;
Andy Huang5f082212014-06-11 22:19:21 -0700317 protected boolean mAddingAttachment;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800318 private boolean mAttachmentsChanged;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800319 private boolean mTextChanged;
320 private boolean mReplyFromChanged;
321 private MenuItem mSave;
Mindy Pereirab3112a22012-06-20 12:10:03 -0700322 @VisibleForTesting
323 protected Message mRefMessage;
Mindy Pereira7ed1c112012-01-18 10:59:25 -0800324 private long mDraftId = UIProvider.INVALID_MESSAGE_ID;
325 private Message mDraft;
mindyp44a63392012-11-05 12:05:16 -0800326 private ReplyFromAccount mDraftAccount;
Tony Mantler581edd42014-02-18 15:41:22 -0800327 private final Object mDraftLock = new Object();
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800328
Mindy Pereira326c6602012-01-04 15:32:42 -0800329 /**
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700330 * Boolean indicating whether ComposeActivity was launched from a Gmail controlled view.
331 */
332 private boolean mLaunchedFromEmail = false;
Mindy Pereiracbfb75a2012-06-25 14:52:23 -0700333 private RecipientTextWatcher mToListener;
334 private RecipientTextWatcher mCcListener;
335 private RecipientTextWatcher mBccListener;
Mindy Pereirab18e5a92012-07-10 11:47:21 -0700336 private Uri mRefMessageUri;
Alice Yanga990a712013-03-13 18:37:00 -0700337 private boolean mShowQuotedText = false;
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700338 protected Bundle mInnerSavedState;
Scott Kennedy60847252013-08-15 15:55:42 -0700339 private ContentValues mExtraValues = null;
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700340
Jin Cao31bb3d62014-09-11 14:01:43 -0700341 // This is used to track pending requests, refer to sRequestMessageIdMap
mindyp1623f9b2012-11-21 12:41:16 -0800342 private int mRequestId;
343 private String mSignature;
344 private Account[] mAccounts;
345 private boolean mRespondedInline;
Andy Huangdc97bf42013-08-15 16:52:45 -0700346 private boolean mPerformedSendOrDiscard = false;
mindyp1623f9b2012-11-21 12:41:16 -0800347
Jin Cao23ab6ea2014-09-24 15:28:18 -0700348 // OnKeyListener solely used for intercepting CTRL+ENTER event for SEND.
349 private final View.OnKeyListener mKeyListenerForSendShortcut = new View.OnKeyListener() {
350 @Override
351 public boolean onKey(View v, int keyCode, KeyEvent event) {
352 if (event.hasModifiers(KeyEvent.META_CTRL_ON) &&
353 keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
354 doSend();
355 return true;
356 }
357 return false;
358 }
359 };
360
Andy Huang9ed742c2014-06-18 02:34:50 -0700361 private final HtmlTree.ConverterFactory mSpanConverterFactory =
362 new HtmlTree.ConverterFactory() {
363 @Override
364 public HtmlTree.Converter<Spanned> createInstance() {
365 return getSpanConverter();
366 }
367 };
368
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700369 /**
Mindy Pereira326c6602012-01-04 15:32:42 -0800370 * Can be called from a non-UI thread.
371 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800372 public static void editDraft(Context launcher, Account account, Message message) {
Scott Kennedy60847252013-08-15 15:55:42 -0700373 launch(launcher, account, message, EDIT_DRAFT, null, null, null, null,
374 null /* extraValues */);
Mindy Pereira326c6602012-01-04 15:32:42 -0800375 }
376
Mindy Pereira6349a042012-01-04 11:25:01 -0800377 /**
378 * Can be called from a non-UI thread.
379 */
Mindy Pereira33fe9082012-01-09 16:24:30 -0800380 public static void compose(Context launcher, Account account) {
Scott Kennedy60847252013-08-15 15:55:42 -0700381 launch(launcher, account, null, COMPOSE, null, null, null, null, null /* extraValues */);
Mindy Pereira6349a042012-01-04 11:25:01 -0800382 }
383
384 /**
385 * Can be called from a non-UI thread.
386 */
Andrew Sapperstein3de76ec2013-07-16 12:08:15 -0700387 public static void composeToAddress(Context launcher, Account account, String toAddress) {
Scott Kennedy60847252013-08-15 15:55:42 -0700388 launch(launcher, account, null, COMPOSE, toAddress, null, null, null,
389 null /* extraValues */);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700390 }
391
392 /**
393 * Can be called from a non-UI thread.
394 */
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700395 public static void composeWithExtraValues(Context launcher, Account account,
396 String subject, final ContentValues extraValues) {
397 launch(launcher, account, null, COMPOSE, null, null, null, subject, extraValues);
398 }
399
400 /**
401 * Can be called from a non-UI thread.
402 */
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -0800403 public static Intent createReplyIntent(final Context launcher, final Account account,
404 final Uri messageUri, final boolean isReplyAll) {
405 return createActionIntent(launcher, account, messageUri, isReplyAll ? REPLY_ALL : REPLY);
406 }
407
408 /**
409 * Can be called from a non-UI thread.
410 */
411 public static Intent createForwardIntent(final Context launcher, final Account account,
412 final Uri messageUri) {
413 return createActionIntent(launcher, account, messageUri, FORWARD);
414 }
415
Scott Kennedya0287a82014-04-07 14:30:13 -0700416 private static Intent createActionIntent(final Context context, final Account account,
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -0800417 final Uri messageUri, final int action) {
Scott Kennedya0287a82014-04-07 14:30:13 -0700418 final Intent intent = new Intent(ACTION_LAUNCH_COMPOSE);
419 intent.setPackage(context.getPackageName());
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -0800420
Paul Westbrook6d2442b2013-07-17 17:51:51 -0700421 updateActionIntent(account, messageUri, action, intent);
422
423 return intent;
424 }
425
426 @VisibleForTesting
427 static Intent updateActionIntent(Account account, Uri messageUri, int action, Intent intent) {
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -0800428 intent.putExtra(EXTRA_FROM_EMAIL_TASK, true);
429 intent.putExtra(EXTRA_ACTION, action);
430 intent.putExtra(Utils.EXTRA_ACCOUNT, account);
431 intent.putExtra(EXTRA_IN_REFERENCE_TO_MESSAGE_URI, messageUri);
432
433 return intent;
434 }
435
436 /**
437 * Can be called from a non-UI thread.
438 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800439 public static void reply(Context launcher, Account account, Message message) {
Scott Kennedy60847252013-08-15 15:55:42 -0700440 launch(launcher, account, message, REPLY, null, null, null, null, null /* extraValues */);
Mindy Pereira6349a042012-01-04 11:25:01 -0800441 }
442
443 /**
444 * Can be called from a non-UI thread.
445 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800446 public static void replyAll(Context launcher, Account account, Message message) {
Scott Kennedy60847252013-08-15 15:55:42 -0700447 launch(launcher, account, message, REPLY_ALL, null, null, null, null,
448 null /* extraValues */);
Mindy Pereira6349a042012-01-04 11:25:01 -0800449 }
450
451 /**
452 * Can be called from a non-UI thread.
453 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800454 public static void forward(Context launcher, Account account, Message message) {
Scott Kennedy60847252013-08-15 15:55:42 -0700455 launch(launcher, account, message, FORWARD, null, null, null, null, null /* extraValues */);
Mindy Pereira6349a042012-01-04 11:25:01 -0800456 }
457
Alice Yang1ebc2db2013-03-14 21:21:44 -0700458 public static void reportRenderingFeedback(Context launcher, Account account, Message message,
459 String body) {
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700460 launch(launcher, account, message, FORWARD,
Scott Kennedy60847252013-08-15 15:55:42 -0700461 "android-gmail-readability@google.com", body, null, null, null /* extraValues */);
Alice Yang1ebc2db2013-03-14 21:21:44 -0700462 }
463
Scott Kennedya0287a82014-04-07 14:30:13 -0700464 private static void launch(Context context, Account account, Message message, int action,
Scott Kennedy60847252013-08-15 15:55:42 -0700465 String toAddress, String body, String quotedText, String subject,
466 final ContentValues extraValues) {
Scott Kennedya0287a82014-04-07 14:30:13 -0700467 Intent intent = new Intent(ACTION_LAUNCH_COMPOSE);
468 intent.setPackage(context.getPackageName());
Mindy Pereira6349a042012-01-04 11:25:01 -0800469 intent.putExtra(EXTRA_FROM_EMAIL_TASK, true);
470 intent.putExtra(EXTRA_ACTION, action);
471 intent.putExtra(Utils.EXTRA_ACCOUNT, account);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700472 if (action == EDIT_DRAFT) {
473 intent.putExtra(ORIGINAL_DRAFT_MESSAGE, message);
474 } else {
475 intent.putExtra(EXTRA_IN_REFERENCE_TO_MESSAGE, message);
476 }
Alice Yang1ebc2db2013-03-14 21:21:44 -0700477 if (toAddress != null) {
478 intent.putExtra(EXTRA_TO, toAddress);
479 }
480 if (body != null) {
481 intent.putExtra(EXTRA_BODY, body);
482 }
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700483 if (quotedText != null) {
484 intent.putExtra(EXTRA_QUOTED_TEXT, quotedText);
485 }
486 if (subject != null) {
487 intent.putExtra(EXTRA_SUBJECT, subject);
488 }
Scott Kennedy60847252013-08-15 15:55:42 -0700489 if (extraValues != null) {
490 LogUtils.d(LOG_TAG, "Launching with extraValues: %s", extraValues.toString());
491 intent.putExtra(EXTRA_VALUES, extraValues);
492 }
Andy Huange0f03202014-06-13 17:34:49 -0700493 if (action == COMPOSE) {
494 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
495 } else if (message != null) {
James Lemieuxcb1018a2014-06-18 11:09:18 -0700496 intent.setData(Utils.normalizeUri(message.uri));
Andy Huange0f03202014-06-13 17:34:49 -0700497 }
Scott Kennedya0287a82014-04-07 14:30:13 -0700498 context.startActivity(intent);
Mindy Pereira6349a042012-01-04 11:25:01 -0800499 }
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800500
Scott Kennedya0287a82014-04-07 14:30:13 -0700501 public static void composeMailto(Context context, Account account, Uri mailto) {
502 final Intent intent = new Intent(Intent.ACTION_VIEW, mailto);
503 intent.setPackage(context.getPackageName());
Andy Huang0a2a3462013-12-20 15:56:13 -0800504 intent.putExtra(EXTRA_FROM_EMAIL_TASK, true);
505 intent.putExtra(Utils.EXTRA_ACCOUNT, account);
Andy Huange0f03202014-06-13 17:34:49 -0700506 if (mailto != null) {
James Lemieuxcb1018a2014-06-18 11:09:18 -0700507 intent.setData(Utils.normalizeUri(mailto));
Andy Huange0f03202014-06-13 17:34:49 -0700508 }
Scott Kennedya0287a82014-04-07 14:30:13 -0700509 context.startActivity(intent);
Andy Huang0a2a3462013-12-20 15:56:13 -0800510 }
511
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800512 @Override
Scott Kennedyd9063902013-08-02 22:14:37 -0700513 protected void onCreate(Bundle savedInstanceState) {
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800514 super.onCreate(savedInstanceState);
Mindy Pereira3528d362012-01-05 14:39:44 -0800515 setContentView(R.layout.compose);
Andrew Sapperstein52882ff2014-07-27 12:30:18 -0700516 final ActionBar actionBar = getSupportActionBar();
Paul Westbrook4def3bf2014-07-01 00:38:17 -0700517 if (actionBar != null) {
518 // Hide the app icon.
Paul Westbrook5043cc22014-06-28 05:04:21 -0700519 actionBar.setIcon(null);
Paul Westbrook4def3bf2014-07-01 00:38:17 -0700520 actionBar.setDisplayUseLogoEnabled(false);
Paul Westbrook5043cc22014-06-28 05:04:21 -0700521 }
522
Andy Huang9f855d62013-05-30 17:15:03 -0700523 mInnerSavedState = (savedInstanceState != null) ?
524 savedInstanceState.getBundle(KEY_INNER_SAVED_STATE) : null;
Mindy Pereirab199d172012-08-13 11:04:03 -0700525 checkValidAccounts();
526 }
527
528 private void finishCreate() {
Andy Huang9f855d62013-05-30 17:15:03 -0700529 final Bundle savedState = mInnerSavedState;
Mindy Pereira3528d362012-01-05 14:39:44 -0800530 findViews();
Tony Mantler581edd42014-02-18 15:41:22 -0800531 final Intent intent = getIntent();
532 final Message message;
533 final ArrayList<AttachmentPreview> previews;
Alice Yanga990a712013-03-13 18:37:00 -0700534 mShowQuotedText = false;
Tony Mantler581edd42014-02-18 15:41:22 -0800535 final CharSequence quotedText;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700536 int action;
Mindy Pereira47d0e652012-07-23 09:45:07 -0700537 // Check for any of the possibly supplied accounts.;
Tony Mantler581edd42014-02-18 15:41:22 -0800538 final Account account;
Andy Huang9f855d62013-05-30 17:15:03 -0700539 if (hadSavedInstanceStateMessage(savedState)) {
540 action = savedState.getInt(EXTRA_ACTION, COMPOSE);
541 account = savedState.getParcelable(Utils.EXTRA_ACCOUNT);
Tony Mantler581edd42014-02-18 15:41:22 -0800542 message = savedState.getParcelable(EXTRA_MESSAGE);
Mark Wei62066e42012-09-13 12:07:02 -0700543
Andy Huang9f855d62013-05-30 17:15:03 -0700544 previews = savedState.getParcelableArrayList(EXTRA_ATTACHMENT_PREVIEWS);
Tony Mantler581edd42014-02-18 15:41:22 -0800545 mRefMessage = savedState.getParcelable(EXTRA_IN_REFERENCE_TO_MESSAGE);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700546 quotedText = savedState.getCharSequence(EXTRA_QUOTED_TEXT);
Scott Kennedy44d44812013-08-19 14:18:31 -0700547
548 mExtraValues = savedState.getParcelable(EXTRA_VALUES);
Jin Cao31bb3d62014-09-11 14:01:43 -0700549
550 // Get the draft id from the request id if there is one.
551 if (savedState.containsKey(EXTRA_REQUEST_ID)) {
552 final int requestId = savedState.getInt(EXTRA_REQUEST_ID);
553 if (sRequestMessageIdMap.containsKey(requestId)) {
554 synchronized (mDraftLock) {
555 mDraftId = sRequestMessageIdMap.get(requestId);
556 }
557 }
558 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700559 } else {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700560 account = obtainAccount(intent);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700561 action = intent.getIntExtra(EXTRA_ACTION, COMPOSE);
562 // Initialize the message from the message in the intent
Tony Mantler581edd42014-02-18 15:41:22 -0800563 message = intent.getParcelableExtra(ORIGINAL_DRAFT_MESSAGE);
Mark Wei62066e42012-09-13 12:07:02 -0700564 previews = intent.getParcelableArrayListExtra(EXTRA_ATTACHMENT_PREVIEWS);
Tony Mantler581edd42014-02-18 15:41:22 -0800565 mRefMessage = intent.getParcelableExtra(EXTRA_IN_REFERENCE_TO_MESSAGE);
566 mRefMessageUri = intent.getParcelableExtra(EXTRA_IN_REFERENCE_TO_MESSAGE_URI);
567 quotedText = null;
Andy Huang4fe0af82013-08-20 17:24:51 -0700568
569 if (Analytics.isLoggable()) {
570 if (intent.getBooleanExtra(Utils.EXTRA_FROM_NOTIFICATION, false)) {
571 Analytics.getInstance().sendEvent(
572 "notification_action", "compose", getActionString(action), 0);
573 }
574 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700575 }
Mark Wei62066e42012-09-13 12:07:02 -0700576 mAttachmentsView.setAttachmentPreviews(previews);
Paul Westbrook92227f62012-03-20 10:32:51 -0700577
578 setAccount(account);
Mindy Pereira818143e2012-01-11 13:59:49 -0800579 if (mAccount == null) {
580 return;
581 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700582
Scott Kennedyfe853d32013-06-19 11:47:35 -0700583 initRecipients();
584
Scott Kennedy5680ec22013-01-07 13:15:20 -0800585 // Clear the notification and mark the conversation as seen, if necessary
586 final Folder notificationFolder =
587 intent.getParcelableExtra(EXTRA_NOTIFICATION_FOLDER);
Scott Kennedy5680ec22013-01-07 13:15:20 -0800588
Alan Laue806c942014-06-06 16:19:15 -0700589 if (notificationFolder != null) {
590 final Uri conversationUri = intent.getParcelableExtra(EXTRA_NOTIFICATION_CONVERSATION);
591 Intent actionIntent;
592 if (conversationUri != null) {
593 actionIntent = new Intent(MailIntentService.ACTION_RESEND_NOTIFICATIONS_WEAR);
594 actionIntent.putExtra(Utils.EXTRA_CONVERSATION, conversationUri);
595 } else {
596 actionIntent = new Intent(MailIntentService.ACTION_CLEAR_NEW_MAIL_NOTIFICATIONS);
597 actionIntent.setData(Utils.appendVersionQueryParameter(this,
598 notificationFolder.folderUri.fullUri));
599 }
600 actionIntent.setPackage(getPackageName());
601 actionIntent.putExtra(Utils.EXTRA_ACCOUNT, account);
602 actionIntent.putExtra(Utils.EXTRA_FOLDER, notificationFolder);
603
604 startService(actionIntent);
Scott Kennedy5680ec22013-01-07 13:15:20 -0800605 }
606
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700607 if (intent.getBooleanExtra(EXTRA_FROM_EMAIL_TASK, false)) {
608 mLaunchedFromEmail = true;
609 } else if (Intent.ACTION_SEND.equals(intent.getAction())) {
610 final Uri dataUri = intent.getData();
611 if (dataUri != null) {
612 final String dataScheme = intent.getData().getScheme();
613 final String accountScheme = mAccount.composeIntentUri.getScheme();
614 mLaunchedFromEmail = TextUtils.equals(dataScheme, accountScheme);
615 }
616 }
617
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700618 if (mRefMessageUri != null) {
Alice Yanga990a712013-03-13 18:37:00 -0700619 mShowQuotedText = true;
620 mComposeMode = action;
Alan Lau15490232014-03-06 14:53:14 -0800621
622 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
Alan Lau575255c2014-05-16 11:44:27 -0700623 Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
Alan Lau439aa5d2014-05-27 17:57:13 -0700624 String wearReply = null;
Alan Lau575255c2014-05-16 11:44:27 -0700625 if (remoteInput != null) {
Alan Lau439aa5d2014-05-27 17:57:13 -0700626 LogUtils.d(LOG_TAG, "Got remote input from new api");
627 CharSequence input = remoteInput.getCharSequence(
Alan Lau575255c2014-05-16 11:44:27 -0700628 NotificationActionUtils.WEAR_REPLY_INPUT);
Alan Lau439aa5d2014-05-27 17:57:13 -0700629 if (input != null) {
630 wearReply = input.toString();
Alan Lau15490232014-03-06 14:53:14 -0800631 }
Alan Lau575255c2014-05-16 11:44:27 -0700632 } else {
Alan Lau439aa5d2014-05-27 17:57:13 -0700633 // TODO: remove after legacy code has been removed.
634 LogUtils.d(LOG_TAG,
635 "No remote input from new api, falling back to compatibility mode");
636 ClipData clipData = intent.getClipData();
637 if (clipData != null
638 && LEGACY_WEAR_EXTRA.equals(clipData.getDescription().getLabel())) {
639 Bundle extras = clipData.getItemAt(0).getIntent().getExtras();
640 if (extras != null) {
641 wearReply = extras.getString(NotificationActionUtils.WEAR_REPLY_INPUT);
642 }
643 }
644 }
645
646 if (!TextUtils.isEmpty(wearReply)) {
647 createWearReplyTask(this, mRefMessageUri, UIProvider.MESSAGE_PROJECTION,
648 mComposeMode, wearReply).execute();
649 finish();
650 return;
651 } else {
652 LogUtils.w(LOG_TAG, "remote input string is null");
Alan Lau15490232014-03-06 14:53:14 -0800653 }
654 }
655
Alice Yanga990a712013-03-13 18:37:00 -0700656 getLoaderManager().initLoader(INIT_DRAFT_USING_REFERENCE_MESSAGE, null, this);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700657 return;
658 } else if (message != null && action != EDIT_DRAFT) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700659 initFromDraftMessage(message);
660 initQuotedTextFromRefMessage(mRefMessage, action);
Alice Yanga990a712013-03-13 18:37:00 -0700661 mShowQuotedText = message.appendRefMessageContent;
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700662 // if we should be showing quoted text but mRefMessage is null
663 // and we have some quotedText, display that
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700664 if (mShowQuotedText && mRefMessage == null) {
665 if (quotedText != null) {
666 initQuotedText(quotedText, false /* shouldQuoteText */);
667 } else if (mExtraValues != null) {
668 initExtraValues(mExtraValues);
669 return;
670 }
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700671 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700672 } else if (action == EDIT_DRAFT) {
Tony Mantler581edd42014-02-18 15:41:22 -0800673 if (message == null) {
674 throw new IllegalStateException("Message must not be null to edit draft");
675 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700676 initFromDraftMessage(message);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700677 // Update the action to the draft type of the previous draft
678 switch (message.draftType) {
679 case UIProvider.DraftType.REPLY:
680 action = REPLY;
681 break;
682 case UIProvider.DraftType.REPLY_ALL:
683 action = REPLY_ALL;
684 break;
685 case UIProvider.DraftType.FORWARD:
686 action = FORWARD;
687 break;
688 case UIProvider.DraftType.COMPOSE:
689 default:
690 action = COMPOSE;
691 break;
692 }
Alice Yanga990a712013-03-13 18:37:00 -0700693 LogUtils.d(LOG_TAG, "Previous draft had action type: %d", action);
694
695 mShowQuotedText = message.appendRefMessageContent;
696 if (message.refMessageUri != null) {
697 // If we're editing an existing draft that was in reference to an existing message,
698 // still need to load that original message since we might need to refer to the
699 // original sender and recipients if user switches "reply <-> reply-all".
700 mRefMessageUri = message.refMessageUri;
701 mComposeMode = action;
702 getLoaderManager().initLoader(REFERENCE_MESSAGE_LOADER, null, this);
703 return;
704 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700705 } else if ((action == REPLY || action == REPLY_ALL || action == FORWARD)) {
706 if (mRefMessage != null) {
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -0800707 initFromRefMessage(action);
Alice Yanga990a712013-03-13 18:37:00 -0700708 mShowQuotedText = true;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700709 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700710 } else {
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700711 if (initFromExtras(intent)) {
712 return;
713 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700714 }
Alice Yanga990a712013-03-13 18:37:00 -0700715
716 mComposeMode = action;
Andy Huang9f855d62013-05-30 17:15:03 -0700717 finishSetup(action, intent, savedState);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700718 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700719
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -0700720 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
Alan Lau15490232014-03-06 14:53:14 -0800721 private static AsyncTask<Void, Void, Message> createWearReplyTask(
722 final ComposeActivity composeActivity,
723 final Uri refMessageUri, final String[] projection, final int action,
724 final String wearReply) {
725 return new AsyncTask<Void, Void, Message>() {
726 private Intent mEmptyServiceIntent = new Intent(composeActivity, EmptyService.class);
727
728 @Override
729 protected void onPreExecute() {
730 // Start service so we won't be killed if this app is put in the background.
731 composeActivity.startService(mEmptyServiceIntent);
732 }
733
734 @Override
735 protected Message doInBackground(Void... params) {
736 Cursor cursor = composeActivity.getContentResolver()
737 .query(refMessageUri, projection, null, null, null, null);
738 if (cursor != null) {
739 try {
740 cursor.moveToFirst();
741 return new Message(cursor);
742 } finally {
743 cursor.close();
744 }
745 }
746 return null;
747 }
748
749 @Override
750 protected void onPostExecute(Message message) {
751 composeActivity.stopService(mEmptyServiceIntent);
752
753 composeActivity.mRefMessage = message;
754 composeActivity.initFromRefMessage(action);
755 composeActivity.setBody(wearReply, false);
756 composeActivity.finishSetup(action, composeActivity.getIntent(), null);
757 composeActivity.sendOrSaveWithSanityChecks(false /* save */, true /* show toast */,
758 false /* orientationChanged */, true /* autoSend */);
759 }
760 };
761 }
762
Mindy Pereirab199d172012-08-13 11:04:03 -0700763 private void checkValidAccounts() {
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700764 final Account[] allAccounts = AccountUtils.getAccounts(this);
765 if (allAccounts == null || allAccounts.length == 0) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700766 final Intent noAccountIntent = MailAppProvider.getNoAccountIntent(this);
767 if (noAccountIntent != null) {
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700768 mAccounts = null;
Mindy Pereirab199d172012-08-13 11:04:03 -0700769 startActivityForResult(noAccountIntent, RESULT_CREATE_ACCOUNT);
770 }
771 } else {
mindyp26d4d2d2012-09-18 17:30:32 -0700772 // If none of the accounts are syncing, setup a watcher.
Mindy Pereirab199d172012-08-13 11:04:03 -0700773 boolean anySyncing = false;
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700774 for (Account a : allAccounts) {
Paul Westbrookdfa1dec2012-09-26 16:27:28 -0700775 if (a.isAccountReady()) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700776 anySyncing = true;
777 break;
778 }
779 }
780 if (!anySyncing) {
781 // There are accounts, but none are sync'd, which is just like having no accounts.
782 mAccounts = null;
783 getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, null, this);
784 return;
785 }
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700786 mAccounts = AccountUtils.getSyncingAccounts(this);
Mindy Pereirab199d172012-08-13 11:04:03 -0700787 finishCreate();
788 }
789 }
790
Mindy Pereira47d0e652012-07-23 09:45:07 -0700791 private Account obtainAccount(Intent intent) {
792 Account account = null;
793 Object accountExtra = null;
794 if (intent != null && intent.getExtras() != null) {
795 accountExtra = intent.getExtras().get(Utils.EXTRA_ACCOUNT);
796 if (accountExtra instanceof Account) {
797 return (Account) accountExtra;
mindyp7ae042e2012-08-27 13:27:37 -0700798 } else if (accountExtra instanceof String) {
799 // This is the Account attached to the widget compose intent.
Tony Mantler26a20752014-02-28 16:44:24 -0800800 account = Account.newInstance((String) accountExtra);
mindyp7ae042e2012-08-27 13:27:37 -0700801 if (account != null) {
802 return account;
803 }
Mindy Pereira47d0e652012-07-23 09:45:07 -0700804 }
mindyp5ee9dc42013-01-08 09:54:54 -0800805 accountExtra = intent.hasExtra(Utils.EXTRA_ACCOUNT) ?
806 intent.getStringExtra(Utils.EXTRA_ACCOUNT) :
807 intent.getStringExtra(EXTRA_SELECTED_ACCOUNT);
Mindy Pereira47d0e652012-07-23 09:45:07 -0700808 }
Tony Mantler581edd42014-02-18 15:41:22 -0800809
810 MailAppProvider provider = MailAppProvider.getInstance();
811 String lastAccountUri = provider.getLastSentFromAccount();
812 if (TextUtils.isEmpty(lastAccountUri)) {
813 lastAccountUri = provider.getLastViewedAccount();
Mindy Pereira47d0e652012-07-23 09:45:07 -0700814 }
Tony Mantler581edd42014-02-18 15:41:22 -0800815 if (!TextUtils.isEmpty(lastAccountUri)) {
816 accountExtra = Uri.parse(lastAccountUri);
817 }
818
Mindy Pereirab199d172012-08-13 11:04:03 -0700819 if (mAccounts != null && mAccounts.length > 0) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700820 if (accountExtra instanceof String && !TextUtils.isEmpty((String) accountExtra)) {
821 // For backwards compatibility, we need to check account
822 // names.
Mindy Pereirab199d172012-08-13 11:04:03 -0700823 for (Account a : mAccounts) {
Tony Mantler79b11562013-10-09 15:31:50 -0700824 if (a.getEmailAddress().equals(accountExtra)) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700825 account = a;
826 }
827 }
828 } else if (accountExtra instanceof Uri) {
829 // The uri of the last viewed account is what is stored in
830 // the current code base.
Mindy Pereirab199d172012-08-13 11:04:03 -0700831 for (Account a : mAccounts) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700832 if (a.uri.equals(accountExtra)) {
833 account = a;
834 }
835 }
Mindy Pereirab199d172012-08-13 11:04:03 -0700836 }
837 if (account == null) {
838 account = mAccounts[0];
Mindy Pereira47d0e652012-07-23 09:45:07 -0700839 }
840 }
841 return account;
842 }
843
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700844 protected void finishSetup(int action, Intent intent, Bundle savedInstanceState) {
mindyp34a3c562012-11-06 15:12:15 -0800845 setFocus(action);
Mindy Pereiraf7fc6c32012-06-19 15:18:33 -0700846 // Don't bother with the intent if we have procured a message from the
847 // intent already.
848 if (!hadSavedInstanceStateMessage(savedInstanceState)) {
849 initAttachmentsFromIntent(intent);
850 }
Alice Yanga990a712013-03-13 18:37:00 -0700851 initActionBar();
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700852 initFromSpinner(savedInstanceState != null ? savedInstanceState : intent.getExtras(),
853 action);
mindypd4a48662012-11-08 17:13:49 -0800854
855 // If this is a draft message, the draft account is whatever account was
856 // used to open the draft message in Compose.
857 if (mDraft != null) {
858 mDraftAccount = mReplyFromAccount;
859 }
860
Mindy Pereira75f66632012-01-11 11:42:02 -0800861 initChangeListeners();
Jin Cao32973b42014-05-06 16:12:11 -0700862
863 // These two should be identical since we check CC and BCC the same way
864 boolean showCc = !TextUtils.isEmpty(mCc.getText()) || (savedInstanceState != null &&
865 savedInstanceState.getBoolean(EXTRA_SHOW_CC));
866 boolean showBcc = !TextUtils.isEmpty(mBcc.getText()) || (savedInstanceState != null &&
867 savedInstanceState.getBoolean(EXTRA_SHOW_BCC));
868 mCcBccView.show(false /* animate */, showCc, showBcc);
Mindy Pereira326689d2012-05-17 10:14:14 -0700869 updateHideOrShowCcBcc();
Alice Yanga990a712013-03-13 18:37:00 -0700870 updateHideOrShowQuotedText(mShowQuotedText);
mindyp1623f9b2012-11-21 12:41:16 -0800871
Tony Mantler581edd42014-02-18 15:41:22 -0800872 mRespondedInline = mInnerSavedState != null &&
873 mInnerSavedState.getBoolean(EXTRA_RESPONDED_INLINE);
mindyp1623f9b2012-11-21 12:41:16 -0800874 if (mRespondedInline) {
875 mQuotedTextView.setVisibility(View.GONE);
876 }
Jin Cao1fdbe1f2014-08-19 13:51:26 -0700877
878 mTextChanged = (savedInstanceState != null) ?
879 savedInstanceState.getBoolean(EXTRA_TEXT_CHANGED) : false;
Mindy Pereira71c9e562012-05-17 11:01:02 -0700880 }
881
Scott Kennedyff8553f2013-04-05 20:57:44 -0700882 private static boolean hadSavedInstanceStateMessage(final Bundle savedInstanceState) {
Mindy Pereiraf7fc6c32012-06-19 15:18:33 -0700883 return savedInstanceState != null && savedInstanceState.containsKey(EXTRA_MESSAGE);
884 }
885
Mindy Pereira71c9e562012-05-17 11:01:02 -0700886 private void updateHideOrShowQuotedText(boolean showQuotedText) {
887 mQuotedTextView.updateCheckedState(showQuotedText);
mindyp40882432012-09-06 11:07:40 -0700888 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
Mindy Pereira433b1982012-04-03 11:53:07 -0700889 }
890
891 private void setFocus(int action) {
892 if (action == EDIT_DRAFT) {
893 int type = mDraft.draftType;
894 switch (type) {
895 case UIProvider.DraftType.COMPOSE:
896 case UIProvider.DraftType.FORWARD:
897 action = COMPOSE;
898 break;
899 case UIProvider.DraftType.REPLY:
900 case UIProvider.DraftType.REPLY_ALL:
901 default:
902 action = REPLY;
903 break;
904 }
905 }
906 switch (action) {
907 case FORWARD:
908 case COMPOSE:
mindyp27083062012-11-15 09:02:01 -0800909 if (TextUtils.isEmpty(mTo.getText())) {
910 mTo.requestFocus();
911 break;
912 }
Scott Kennedyff8553f2013-04-05 20:57:44 -0700913 //$FALL-THROUGH$
Mindy Pereira433b1982012-04-03 11:53:07 -0700914 case REPLY:
915 case REPLY_ALL:
916 default:
917 focusBody();
918 break;
919 }
920 }
921
922 /**
923 * Focus the body of the message.
924 */
Tony Mantler6a7ac782014-02-19 15:22:02 -0800925 private void focusBody() {
Mindy Pereira433b1982012-04-03 11:53:07 -0700926 mBodyView.requestFocus();
Tony Mantler6a7ac782014-02-19 15:22:02 -0800927 resetBodySelection();
928 }
Mindy Pereira433b1982012-04-03 11:53:07 -0700929
Tony Mantler6a7ac782014-02-19 15:22:02 -0800930 private void resetBodySelection() {
931 int length = mBodyView.getText().length();
Mindy Pereira433b1982012-04-03 11:53:07 -0700932 int signatureStartPos = getSignatureStartPosition(
933 mSignature, mBodyView.getText().toString());
934 if (signatureStartPos > -1) {
935 // In case the user deleted the newlines...
936 mBodyView.setSelection(signatureStartPos);
mindyp8743cfc2012-09-18 13:29:08 -0700937 } else if (length >= 0) {
Mindy Pereira433b1982012-04-03 11:53:07 -0700938 // Move cursor to the end.
939 mBodyView.setSelection(length);
940 }
Mindy Pereira1a95a572012-01-05 12:21:29 -0800941 }
942
943 @Override
Andy Huang761522c2013-08-08 13:09:11 -0700944 protected void onStart() {
945 super.onStart();
946
947 Analytics.getInstance().activityStart(this);
948 }
949
950 @Override
951 protected void onStop() {
952 super.onStop();
953
954 Analytics.getInstance().activityStop(this);
955 }
956
957 @Override
Mindy Pereira1a95a572012-01-05 12:21:29 -0800958 protected void onResume() {
959 super.onResume();
960 // Update the from spinner as other accounts
961 // may now be available.
Mindy Pereira818143e2012-01-11 13:59:49 -0800962 if (mFromSpinner != null && mAccount != null) {
Andrew Sappersteina01ddca2014-03-04 10:59:56 -0800963 mFromSpinner.initialize(mComposeMode, mAccount, mAccounts, mRefMessage);
Mindy Pereira818143e2012-01-11 13:59:49 -0800964 }
Mindy Pereira1a95a572012-01-05 12:21:29 -0800965 }
966
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800967 @Override
968 protected void onPause() {
969 super.onPause();
970
Mindy Pereiraa2148332012-07-02 13:54:14 -0700971 // When the user exits the compose view, see if this draft needs saving.
Yorke Lee3d7048e2012-09-19 14:19:25 -0700972 // Don't save unnecessary drafts if we are only changing the orientation.
973 if (!isChangingConfigurations()) {
Mindy Pereiraa2148332012-07-02 13:54:14 -0700974 saveIfNeeded();
Andy Huangdc97bf42013-08-15 16:52:45 -0700975
Andy Huange003b4c2013-08-16 10:32:05 -0700976 if (isFinishing() && !mPerformedSendOrDiscard && !isBlank()) {
Andy Huangdc97bf42013-08-15 16:52:45 -0700977 // log saving upon backing out of activity. (we avoid logging every sendOrSave()
978 // because that method can be invoked many times in a single compose session.)
979 logSendOrSave(true /* save */);
980 }
Mindy Pereiraa2148332012-07-02 13:54:14 -0700981 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800982 }
983
984 @Override
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -0700985 protected void onActivityResult(int request, int result, Intent data) {
Andy Huang5f082212014-06-11 22:19:21 -0700986 if (request == RESULT_PICK_ATTACHMENT) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700987 mAddingAttachment = false;
Andy Huang5f082212014-06-11 22:19:21 -0700988 if (result == RESULT_OK) {
989 addAttachmentAndUpdateView(data);
990 }
Mindy Pereirab199d172012-08-13 11:04:03 -0700991 } else if (request == RESULT_CREATE_ACCOUNT) {
Alice Yanga990a712013-03-13 18:37:00 -0700992 // We were waiting for the user to create an account
Mindy Pereirab199d172012-08-13 11:04:03 -0700993 if (result != RESULT_OK) {
994 finish();
995 } else {
996 // Watch for accounts to show up!
997 // restart the loader to get the updated list of accounts
998 getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, null, this);
999 showWaitFragment(null);
1000 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001001 }
1002 }
1003
1004 @Override
Scott Kennedyd9063902013-08-02 22:14:37 -07001005 protected final void onRestoreInstanceState(Bundle savedInstanceState) {
Yorke Lee7bec2b92013-04-26 08:31:42 -07001006 final boolean hasAccounts = mAccounts != null && mAccounts.length > 0;
1007 if (hasAccounts) {
1008 clearChangeListeners();
1009 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001010 super.onRestoreInstanceState(savedInstanceState);
Andy Huang9f855d62013-05-30 17:15:03 -07001011 if (mInnerSavedState != null) {
1012 if (mInnerSavedState.containsKey(EXTRA_FOCUS_SELECTION_START)) {
1013 int selectionStart = mInnerSavedState.getInt(EXTRA_FOCUS_SELECTION_START);
1014 int selectionEnd = mInnerSavedState.getInt(EXTRA_FOCUS_SELECTION_END);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001015 // There should be a focus and it should be an EditText since we
1016 // only save these extras if these conditions are true.
1017 EditText focusEditText = (EditText) getCurrentFocus();
1018 final int length = focusEditText.getText().length();
1019 if (selectionStart < length && selectionEnd < length) {
1020 focusEditText.setSelection(selectionStart, selectionEnd);
1021 }
1022 }
1023 }
Yorke Lee7bec2b92013-04-26 08:31:42 -07001024 if (hasAccounts) {
1025 initChangeListeners();
1026 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001027 }
1028
1029 @Override
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07001030 protected void onSaveInstanceState(Bundle state) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001031 super.onSaveInstanceState(state);
Andy Huang9f855d62013-05-30 17:15:03 -07001032 final Bundle inner = new Bundle();
1033 saveState(inner);
1034 state.putBundle(KEY_INNER_SAVED_STATE, inner);
1035 }
1036
1037 private void saveState(Bundle state) {
Mindy Pereirab199d172012-08-13 11:04:03 -07001038 // We have no accounts so there is nothing to compose, and therefore, nothing to save.
1039 if (mAccounts == null || mAccounts.length == 0) {
1040 return;
1041 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001042 // The framework is happy to save and restore the selection but only if it also saves and
1043 // restores the contents of the edit text. That's a lot of text to put in a bundle so we do
1044 // this manually.
1045 View focus = getCurrentFocus();
1046 if (focus != null && focus instanceof EditText) {
1047 EditText focusEditText = (EditText) focus;
1048 state.putInt(EXTRA_FOCUS_SELECTION_START, focusEditText.getSelectionStart());
1049 state.putInt(EXTRA_FOCUS_SELECTION_END, focusEditText.getSelectionEnd());
1050 }
Paul Westbrook6273e962012-04-23 10:44:15 -07001051
1052 final List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
Paul Westbrook151f1ad2012-04-24 09:13:00 -07001053 final int selectedPos = mFromSpinner.getSelectedItemPosition();
Mindy Pereirad90f7ac2012-06-27 10:31:06 -07001054 final ReplyFromAccount selectedReplyFromAccount = (replyFromAccounts != null
1055 && replyFromAccounts.size() > 0 && replyFromAccounts.size() > selectedPos) ?
1056 replyFromAccounts.get(selectedPos) : null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001057 if (selectedReplyFromAccount != null) {
1058 state.putString(EXTRA_SELECTED_REPLY_FROM_ACCOUNT, selectedReplyFromAccount.serialize()
1059 .toString());
1060 state.putParcelable(Utils.EXTRA_ACCOUNT, selectedReplyFromAccount.account);
1061 } else {
1062 state.putParcelable(Utils.EXTRA_ACCOUNT, mAccount);
1063 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001064
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001065 if (mDraftId == UIProvider.INVALID_MESSAGE_ID && mRequestId !=0) {
1066 // We don't have a draft id, and we have a request id,
1067 // save the request id.
1068 state.putInt(EXTRA_REQUEST_ID, mRequestId);
1069 }
1070
1071 // We want to restore the current mode after a pause
1072 // or rotation.
1073 int mode = getMode();
1074 state.putInt(EXTRA_ACTION, mode);
1075
Jin Cao77b4c2c2014-05-20 13:55:53 -07001076 final Message message = createMessage(selectedReplyFromAccount, mRefMessage, mode,
1077 removeComposingSpans(mBodyView.getText()));
Andy Huang1f8f4dd2012-10-25 21:35:35 -07001078 if (mDraft != null) {
mindype7b76aa2012-11-14 16:19:13 -08001079 message.id = mDraft.id;
1080 message.serverId = mDraft.serverId;
1081 message.uri = mDraft.uri;
Andy Huang1f8f4dd2012-10-25 21:35:35 -07001082 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001083 state.putParcelable(EXTRA_MESSAGE, message);
1084
1085 if (mRefMessage != null) {
1086 state.putParcelable(EXTRA_IN_REFERENCE_TO_MESSAGE, mRefMessage);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001087 } else if (message.appendRefMessageContent) {
1088 // If we have no ref message but should be appending
1089 // ref message content, we have orphaned quoted text. Save it.
1090 state.putCharSequence(EXTRA_QUOTED_TEXT, mQuotedTextView.getQuotedTextIfIncluded());
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001091 }
Mindy Pereira326689d2012-05-17 10:14:14 -07001092 state.putBoolean(EXTRA_SHOW_CC, mCcBccView.isCcVisible());
1093 state.putBoolean(EXTRA_SHOW_BCC, mCcBccView.isBccVisible());
mindyp1623f9b2012-11-21 12:41:16 -08001094 state.putBoolean(EXTRA_RESPONDED_INLINE, mRespondedInline);
mindyp816b3f02012-12-11 08:25:04 -08001095 state.putBoolean(EXTRA_SAVE_ENABLED, mSave != null && mSave.isEnabled());
Mark Wei62066e42012-09-13 12:07:02 -07001096 state.putParcelableArrayList(
1097 EXTRA_ATTACHMENT_PREVIEWS, mAttachmentsView.getAttachmentPreviews());
Scott Kennedy44d44812013-08-19 14:18:31 -07001098
1099 state.putParcelable(EXTRA_VALUES, mExtraValues);
Jin Cao1fdbe1f2014-08-19 13:51:26 -07001100
1101 state.putBoolean(EXTRA_TEXT_CHANGED, mTextChanged);
1102 // On configuration changes, we don't actually need to parse the body html ourselves because
1103 // the framework can correctly restore the body EditText to its exact original state.
1104 state.putBoolean(EXTRA_SKIP_PARSING_BODY, isChangingConfigurations());
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001105 }
1106
1107 private int getMode() {
1108 int mode = ComposeActivity.COMPOSE;
Andrew Sapperstein52882ff2014-07-27 12:30:18 -07001109 final ActionBar actionBar = getSupportActionBar();
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001110 if (actionBar != null
1111 && actionBar.getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001112 mode = actionBar.getSelectedNavigationIndex();
1113 }
1114 return mode;
1115 }
1116
Jin Cao77b4c2c2014-05-20 13:55:53 -07001117 /**
1118 * This function might be called from a background thread, so be sure to move everything that
1119 * can potentially modify the UI to the main thread (e.g. removeComposingSpans for body).
1120 */
Anthony Lee2a3cc132014-04-22 14:15:25 -07001121 private Message createMessage(ReplyFromAccount selectedReplyFromAccount, Message refMessage,
Jin Cao77b4c2c2014-05-20 13:55:53 -07001122 int mode, Spanned body) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001123 Message message = new Message();
1124 message.id = UIProvider.INVALID_MESSAGE_ID;
Andy Huangd47877e2012-08-09 19:31:24 -07001125 message.serverId = null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001126 message.uri = null;
1127 message.conversationUri = null;
1128 message.subject = mSubject.getText().toString();
1129 message.snippet = null;
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001130 message.setTo(formatSenders(mTo.getText().toString()));
1131 message.setCc(formatSenders(mCc.getText().toString()));
1132 message.setBcc(formatSenders(mBcc.getText().toString()));
1133 message.setReplyTo(null);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001134 message.dateReceivedMs = 0;
Jin Cao77b4c2c2014-05-20 13:55:53 -07001135 message.bodyHtml = spannedBodyToHtml(body, true);
Jin Cao7800d292014-08-24 11:31:15 -07001136 message.bodyText = body.toString();
Jin Cao0a8e8222014-10-02 11:27:52 -07001137 // Fallback to use the text version if html conversion fails for whatever the reason.
Jin Caoefd62cb2014-10-02 17:50:07 -07001138 final String htmlInPlainText = Utils.convertHtmlToPlainText(message.bodyHtml);
1139 if (!TextUtils.isEmpty(message.bodyText) && TextUtils.isEmpty(htmlInPlainText)) {
1140 LogUtils.w(LOG_TAG, "FAILED HTML CONVERSION: from %d to %d", message.bodyText.length(),
1141 htmlInPlainText.length());
1142 Analytics.getInstance().sendEvent("errors", "failed_html_conversion", null, 0);
Jin Cao0a8e8222014-10-02 11:27:52 -07001143 message.bodyHtml = "<p>" + message.bodyText + "</p>";
1144 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001145 message.embedsExternalResources = false;
Alice Yanga990a712013-03-13 18:37:00 -07001146 message.refMessageUri = mRefMessage != null ? mRefMessage.uri : null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001147 message.appendRefMessageContent = mQuotedTextView.getQuotedTextIfIncluded() != null;
1148 ArrayList<Attachment> attachments = mAttachmentsView.getAttachments();
1149 message.hasAttachments = attachments != null && attachments.size() > 0;
1150 message.attachmentListUri = null;
1151 message.messageFlags = 0;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001152 message.alwaysShowImages = false;
1153 message.attachmentsJson = Attachment.toJSONArray(attachments);
1154 CharSequence quotedText = mQuotedTextView.getQuotedText();
Anthony Lee2a3cc132014-04-22 14:15:25 -07001155 message.quotedTextOffset = -1; // Just a default value.
1156 if (refMessage != null && !TextUtils.isEmpty(quotedText)) {
1157 if (!TextUtils.isEmpty(refMessage.bodyHtml)) {
1158 // We want the index to point to just the quoted text and not the
1159 // "On December 25, 2014..." part of it.
1160 message.quotedTextOffset =
1161 QuotedTextView.getQuotedTextOffset(quotedText.toString());
1162 } else if (!TextUtils.isEmpty(refMessage.bodyText)) {
1163 // We want to point to the entire quoted text.
1164 message.quotedTextOffset = QuotedTextView.findQuotedTextIndex(quotedText);
1165 }
1166 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001167 message.accountUri = null;
Greg Bullock14fd3042014-08-12 09:21:15 +02001168 message.setFrom(computeFromForAccount(selectedReplyFromAccount));
1169 message.draftType = getDraftType(mode);
1170 return message;
1171 }
1172
1173 protected String computeFromForAccount(ReplyFromAccount selectedReplyFromAccount) {
Tony Mantlerbb036ff72013-10-18 14:03:43 -07001174 final String email = selectedReplyFromAccount != null ? selectedReplyFromAccount.address
1175 : mAccount != null ? mAccount.getEmailAddress() : null;
Tony Mantlerf441d142013-10-22 11:46:00 -07001176 final String senderName = selectedReplyFromAccount != null ? selectedReplyFromAccount.name
1177 : mAccount != null ? mAccount.getSenderName() : null;
Tony Mantler821e5782014-01-06 15:33:43 -08001178 final Address address = new Address(email, senderName);
Greg Bullock14fd3042014-08-12 09:21:15 +02001179 return address.toHeader();
Andy Huang1f8f4dd2012-10-25 21:35:35 -07001180 }
1181
Scott Kennedyff8553f2013-04-05 20:57:44 -07001182 private static String formatSenders(final String string) {
Mindy Pereira3c911582012-08-09 16:59:09 -07001183 if (!TextUtils.isEmpty(string) && string.charAt(string.length() - 1) == ',') {
1184 return string.substring(0, string.length() - 1);
1185 }
1186 return string;
1187 }
1188
Mindy Pereira818143e2012-01-11 13:59:49 -08001189 @VisibleForTesting
Andy Huang91ede362014-01-21 19:16:00 -08001190 protected void setAccount(Account account) {
Mindy Pereirabb5217e2012-04-17 11:08:29 -07001191 if (account == null) {
1192 return;
1193 }
Mindy Pereira23e9fde2012-03-20 15:08:24 -07001194 if (!account.equals(mAccount)) {
1195 mAccount = account;
Paul Westbrookb1f573c2012-04-06 11:38:28 -07001196 mCachedSettings = mAccount.settings;
1197 appendSignature();
Mindy Pereira23e9fde2012-03-20 15:08:24 -07001198 }
Mindy Pereirafa20c1a2012-07-23 13:00:02 -07001199 if (mAccount != null) {
Tony Mantler79b11562013-10-09 15:31:50 -07001200 MailActivity.setNfcMessage(mAccount.getEmailAddress());
Mindy Pereirafa20c1a2012-07-23 13:00:02 -07001201 }
Mindy Pereira818143e2012-01-11 13:59:49 -08001202 }
1203
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001204 private void initFromSpinner(Bundle bundle, int action) {
1205 if (action == EDIT_DRAFT && mDraft.draftType == UIProvider.DraftType.COMPOSE) {
Mindy Pereira62de1b12012-04-06 12:17:56 -07001206 action = COMPOSE;
1207 }
Andrew Sappersteina01ddca2014-03-04 10:59:56 -08001208 mFromSpinner.initialize(action, mAccount, mAccounts, mRefMessage);
Paul Westbrookc97ec3e2013-07-12 18:17:19 -07001209
Mindy Pereira9a42bb42012-04-18 15:21:33 -07001210 if (bundle != null) {
1211 if (bundle.containsKey(EXTRA_SELECTED_REPLY_FROM_ACCOUNT)) {
1212 mReplyFromAccount = ReplyFromAccount.deserialize(mAccount,
1213 bundle.getString(EXTRA_SELECTED_REPLY_FROM_ACCOUNT));
1214 } else if (bundle.containsKey(EXTRA_FROM_ACCOUNT_STRING)) {
Paul Westbrookc97ec3e2013-07-12 18:17:19 -07001215 final String accountString = bundle.getString(EXTRA_FROM_ACCOUNT_STRING);
Mindy Pereira9a42bb42012-04-18 15:21:33 -07001216 mReplyFromAccount = mFromSpinner.getMatchingReplyFromAccount(accountString);
1217 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001218 }
1219 if (mReplyFromAccount == null) {
1220 if (mDraft != null) {
Jin Cao24c892d2014-09-29 11:06:03 -07001221 mReplyFromAccount = getReplyFromAccountFromDraft(mDraft);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001222 } else if (mRefMessage != null) {
1223 mReplyFromAccount = getReplyFromAccountForReply(mAccount, mRefMessage);
1224 }
Mindy Pereira62de1b12012-04-06 12:17:56 -07001225 }
1226 if (mReplyFromAccount == null) {
Andy Huang238aa472012-10-30 17:45:17 -07001227 mReplyFromAccount = getDefaultReplyFromAccount(mAccount);
Mindy Pereira62de1b12012-04-06 12:17:56 -07001228 }
Mindy Pereira9a42bb42012-04-18 15:21:33 -07001229
Mindy Pereira62de1b12012-04-06 12:17:56 -07001230 mFromSpinner.setCurrentAccount(mReplyFromAccount);
Mindy Pereira9a42bb42012-04-18 15:21:33 -07001231
Mindy Pereira62de1b12012-04-06 12:17:56 -07001232 if (mFromSpinner.getCount() > 1) {
Mindy Pereiraa83e7082012-03-30 08:53:11 -07001233 // If there is only 1 account, just show that account.
1234 // Otherwise, give the user the ability to choose which account to
Mindy Pereira62de1b12012-04-06 12:17:56 -07001235 // send mail from / save drafts to.
1236 mFromStatic.setVisibility(View.GONE);
Andy Huangca4676f2014-01-16 13:22:20 -08001237 mFromStaticText.setText(mReplyFromAccount.address);
Mindy Pereira62de1b12012-04-06 12:17:56 -07001238 mFromSpinnerWrapper.setVisibility(View.VISIBLE);
Mindy Pereiraa83e7082012-03-30 08:53:11 -07001239 } else {
1240 mFromStatic.setVisibility(View.VISIBLE);
Andy Huangca4676f2014-01-16 13:22:20 -08001241 mFromStaticText.setText(mReplyFromAccount.address);
Mindy Pereiraa83e7082012-03-30 08:53:11 -07001242 mFromSpinnerWrapper.setVisibility(View.GONE);
Mindy Pereiraa83e7082012-03-30 08:53:11 -07001243 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001244 }
1245
Mindy Pereira62de1b12012-04-06 12:17:56 -07001246 private ReplyFromAccount getReplyFromAccountForReply(Account account, Message refMessage) {
1247 if (refMessage.accountUri != null) {
1248 // This must be from combined inbox.
1249 List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
1250 for (ReplyFromAccount from : replyFromAccounts) {
1251 if (from.account.uri.equals(refMessage.accountUri)) {
1252 return from;
1253 }
1254 }
1255 return null;
1256 } else {
1257 return getReplyFromAccount(account, refMessage);
1258 }
1259 }
1260
1261 /**
Tony Mantler9016a5e2013-07-19 11:54:17 -07001262 * Given an account and the message we're replying to,
Mindy Pereira62de1b12012-04-06 12:17:56 -07001263 * return who the message should be sent from.
1264 * @param account Account in which the message arrived.
Tony Mantler9016a5e2013-07-19 11:54:17 -07001265 * @param refMessage Message to analyze for account selection
Mindy Pereira62de1b12012-04-06 12:17:56 -07001266 * @return the address from which to reply.
1267 */
1268 public ReplyFromAccount getReplyFromAccount(Account account, Message refMessage) {
1269 // First see if we are supposed to use the default address or
1270 // the address it was sentTo.
Mindy Pereira326689d2012-05-17 10:14:14 -07001271 if (mCachedSettings.forceReplyFromDefault) {
Mindy Pereira62de1b12012-04-06 12:17:56 -07001272 return getDefaultReplyFromAccount(account);
1273 } else {
Mindy Pereira89bae572012-06-18 11:34:36 -07001274 // If we aren't explicitly told which account to look for, look at
Mindy Pereira62de1b12012-04-06 12:17:56 -07001275 // all the message recipients and find one that matches
1276 // a custom from or account.
1277 List<String> allRecipients = new ArrayList<String>();
Tony Mantler9016a5e2013-07-19 11:54:17 -07001278 allRecipients.addAll(Arrays.asList(refMessage.getToAddressesUnescaped()));
1279 allRecipients.addAll(Arrays.asList(refMessage.getCcAddressesUnescaped()));
Mindy Pereira62de1b12012-04-06 12:17:56 -07001280 return getMatchingRecipient(account, allRecipients);
1281 }
1282 }
1283
1284 /**
1285 * Compare all the recipients of an email to the current account and all
1286 * custom addresses associated with that account. Return the match if there
1287 * is one, or the default account if there isn't.
1288 */
1289 protected ReplyFromAccount getMatchingRecipient(Account account, List<String> sentTo) {
1290 // Tokenize the list and place in a hashmap.
1291 ReplyFromAccount matchingReplyFrom = null;
1292 Rfc822Token[] tokens;
1293 HashSet<String> recipientsMap = new HashSet<String>();
1294 for (String address : sentTo) {
1295 tokens = Rfc822Tokenizer.tokenize(address);
Tony Mantler581edd42014-02-18 15:41:22 -08001296 for (final Rfc822Token token : tokens) {
1297 recipientsMap.add(token.getAddress());
Mindy Pereira62de1b12012-04-06 12:17:56 -07001298 }
1299 }
1300
1301 int matchingAddressCount = 0;
1302 List<ReplyFromAccount> customFroms;
Andy Huang16174812012-08-16 16:40:35 -07001303 customFroms = account.getReplyFroms();
1304 if (customFroms != null) {
1305 for (ReplyFromAccount entry : customFroms) {
1306 if (recipientsMap.contains(entry.address)) {
1307 matchingReplyFrom = entry;
1308 matchingAddressCount++;
Mindy Pereira62de1b12012-04-06 12:17:56 -07001309 }
1310 }
Mindy Pereira62de1b12012-04-06 12:17:56 -07001311 }
1312 if (matchingAddressCount > 1) {
1313 matchingReplyFrom = getDefaultReplyFromAccount(account);
1314 }
1315 return matchingReplyFrom;
1316 }
1317
Scott Kennedyff8553f2013-04-05 20:57:44 -07001318 private static ReplyFromAccount getDefaultReplyFromAccount(final Account account) {
1319 for (final ReplyFromAccount from : account.getReplyFroms()) {
Mindy Pereira62de1b12012-04-06 12:17:56 -07001320 if (from.isDefault) {
1321 return from;
1322 }
1323 }
Tony Mantlerf441d142013-10-22 11:46:00 -07001324 return new ReplyFromAccount(account, account.uri, account.getEmailAddress(),
1325 account.getSenderName(), account.getEmailAddress(), true, false);
Mindy Pereira62de1b12012-04-06 12:17:56 -07001326 }
1327
Jin Cao24c892d2014-09-29 11:06:03 -07001328 private ReplyFromAccount getReplyFromAccountFromDraft(final Message msg) {
Tony Mantlerf441d142013-10-22 11:46:00 -07001329 final Address[] draftFroms = Address.parse(msg.getFrom());
1330 final String sender = draftFroms.length > 0 ? draftFroms[0].getAddress() : "";
Mindy Pereira62de1b12012-04-06 12:17:56 -07001331 ReplyFromAccount replyFromAccount = null;
Jin Cao24c892d2014-09-29 11:06:03 -07001332 // Do not try to check against the "default" account because the default might be an alias.
1333 for (ReplyFromAccount fromAccount : mFromSpinner.getReplyFromAccounts()) {
1334 if (TextUtils.equals(fromAccount.address, sender)) {
1335 replyFromAccount = fromAccount;
1336 break;
Mindy Pereira62de1b12012-04-06 12:17:56 -07001337 }
1338 }
1339 return replyFromAccount;
1340 }
1341
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001342 private void findViews() {
Jin Cao36e23872014-07-29 13:41:12 -07001343 mScrollView = (ScrollView) findViewById(R.id.compose);
1344 mScrollView.setVisibility(View.VISIBLE);
Jin Cao9d358a12014-07-24 12:15:38 -07001345 mCcBccButton = findViewById(R.id.add_cc_bcc);
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001346 if (mCcBccButton != null) {
1347 mCcBccButton.setOnClickListener(this);
1348 }
1349 mCcBccView = (CcBccView) findViewById(R.id.cc_bcc_wrapper);
Mindy Pereira7b56a612011-12-14 12:32:28 -08001350 mAttachmentsView = (AttachmentsView)findViewById(R.id.attachments);
Mindy Pereira818143e2012-01-11 13:59:49 -08001351 mTo = (RecipientEditTextView) findViewById(R.id.to);
Jin Cao23ab6ea2014-09-24 15:28:18 -07001352 mTo.setOnKeyListener(mKeyListenerForSendShortcut);
Andrew Sapperstein09da9422014-05-30 09:48:08 -07001353 initializeRecipientEditTextView(mTo);
Jin Cao15f09d72014-08-08 13:27:34 -07001354 mTo.setAlternatePopupAnchor(findViewById(R.id.compose_to_dropdown_anchor));
Mindy Pereira818143e2012-01-11 13:59:49 -08001355 mCc = (RecipientEditTextView) findViewById(R.id.cc);
Jin Cao23ab6ea2014-09-24 15:28:18 -07001356 mCc.setOnKeyListener(mKeyListenerForSendShortcut);
Andrew Sapperstein09da9422014-05-30 09:48:08 -07001357 initializeRecipientEditTextView(mCc);
Mindy Pereira818143e2012-01-11 13:59:49 -08001358 mBcc = (RecipientEditTextView) findViewById(R.id.bcc);
Jin Cao23ab6ea2014-09-24 15:28:18 -07001359 mBcc.setOnKeyListener(mKeyListenerForSendShortcut);
Andrew Sapperstein09da9422014-05-30 09:48:08 -07001360 initializeRecipientEditTextView(mBcc);
Mindy Pereira82cc5662012-01-09 17:29:30 -08001361 // TODO: add special chips text change watchers before adding
1362 // this as a text changed watcher to the to, cc, bcc fields.
Mindy Pereira6349a042012-01-04 11:25:01 -08001363 mSubject = (TextView) findViewById(R.id.subject);
Jin Cao23ab6ea2014-09-24 15:28:18 -07001364 mSubject.setOnKeyListener(mKeyListenerForSendShortcut);
mindyp62d3ec72012-08-24 13:04:09 -07001365 mSubject.setOnEditorActionListener(this);
Jin Caoc5c550a2014-07-29 11:53:17 -07001366 mSubject.setOnFocusChangeListener(this);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001367 mQuotedTextView = (QuotedTextView) findViewById(R.id.quoted_text_view);
1368 mQuotedTextView.setRespondInlineListener(this);
Mindy Pereira433b1982012-04-03 11:53:07 -07001369 mBodyView = (EditText) findViewById(R.id.body);
Jin Cao23ab6ea2014-09-24 15:28:18 -07001370 mBodyView.setOnKeyListener(mKeyListenerForSendShortcut);
Jin Caoc5c550a2014-07-29 11:53:17 -07001371 mBodyView.setOnFocusChangeListener(this);
Mindy Pereira1a95a572012-01-05 12:21:29 -08001372 mFromStatic = findViewById(R.id.static_from_content);
Mindy Pereira2eb17322012-03-07 10:07:34 -08001373 mFromStaticText = (TextView) findViewById(R.id.from_account_name);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001374 mFromSpinnerWrapper = findViewById(R.id.spinner_from_content);
Mindy Pereira5a85e2b2012-01-11 09:53:32 -08001375 mFromSpinner = (FromAddressSpinner) findViewById(R.id.from_picker);
Jin Cao95b8a7b2014-09-02 16:45:42 -07001376
1377 // Bottom placeholder to forward click events to the body
1378 findViewById(R.id.composearea_tap_trap_bottom).setOnClickListener(new OnClickListener() {
1379 @Override
1380 public void onClick(View v) {
1381 mBodyView.requestFocus();
1382 mBodyView.setSelection(mBodyView.getText().length());
1383 }
1384 });
Mindy Pereira6349a042012-01-04 11:25:01 -08001385 }
1386
Andrew Sapperstein09da9422014-05-30 09:48:08 -07001387 private void initializeRecipientEditTextView(RecipientEditTextView view) {
1388 view.setTokenizer(new Rfc822Tokenizer());
1389 view.setThreshold(COMPLETION_THRESHOLD);
1390 }
1391
mindyp62d3ec72012-08-24 13:04:09 -07001392 @Override
1393 public boolean onEditorAction(TextView view, int action, KeyEvent keyEvent) {
1394 if (action == EditorInfo.IME_ACTION_DONE) {
1395 focusBody();
1396 return true;
1397 }
1398 return false;
1399 }
1400
Andy Huang91ede362014-01-21 19:16:00 -08001401 /**
1402 * Convert the body text (in {@link Spanned} form) to ready-to-send HTML format as a plain
1403 * String.
1404 *
1405 * @param body the body text including fancy style spans
Jin Cao77b4c2c2014-05-20 13:55:53 -07001406 * @param removedComposing whether the function already removed composingSpans. Necessary
1407 * because we cannot call removeComposingSpans from a background thread.
Andy Huang91ede362014-01-21 19:16:00 -08001408 * @return HTML formatted body that's suitable for sending or saving
1409 */
Jin Cao77b4c2c2014-05-20 13:55:53 -07001410 private String spannedBodyToHtml(Spanned body, boolean removedComposing) {
1411 if (!removedComposing) {
1412 body = removeComposingSpans(body);
1413 }
1414 final HtmlifyBeginResult r = onHtmlifyBegin(body);
Andy Huang91ede362014-01-21 19:16:00 -08001415 return onHtmlifyEnd(Html.toHtml(r.result), r.extras);
1416 }
1417
1418 /**
1419 * A hook for subclasses to convert custom spans in the body text prior to system HTML
1420 * conversion. That HTML conversion is lossy, so anything above and beyond its capability
1421 * has to be handled here.
1422 *
1423 * @param body
1424 * @return a copy of the body text with custom spans replaced with HTML
1425 */
1426 protected HtmlifyBeginResult onHtmlifyBegin(Spanned body) {
1427 return new HtmlifyBeginResult(body, null /* extras */);
1428 }
1429
1430 protected String onHtmlifyEnd(String html, Object extras) {
1431 return html;
1432 }
1433
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001434 protected TextView getBody() {
1435 return mBodyView;
1436 }
1437
1438 @VisibleForTesting
Andy Huang0a2a3462013-12-20 15:56:13 -08001439 public String getBodyHtml() {
Jin Cao77b4c2c2014-05-20 13:55:53 -07001440 return spannedBodyToHtml(mBodyView.getText(), false);
Andy Huang0a2a3462013-12-20 15:56:13 -08001441 }
1442
1443 @VisibleForTesting
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001444 public Account getFromAccount() {
1445 return mReplyFromAccount != null && mReplyFromAccount.account != null ?
1446 mReplyFromAccount.account : mAccount;
1447 }
1448
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07001449 private void clearChangeListeners() {
1450 mSubject.removeTextChangedListener(this);
1451 mBodyView.removeTextChangedListener(this);
1452 mTo.removeTextChangedListener(mToListener);
1453 mCc.removeTextChangedListener(mCcListener);
1454 mBcc.removeTextChangedListener(mBccListener);
1455 mFromSpinner.setOnAccountChangedListener(null);
1456 mAttachmentsView.setAttachmentChangesListener(null);
1457 }
1458
Mindy Pereira75f66632012-01-11 11:42:02 -08001459 // Now that the message has been initialized from any existing draft or
1460 // ref message data, set up listeners for any changes that occur to the
1461 // message.
1462 private void initChangeListeners() {
mindyp1d7e9142012-11-21 13:54:30 -08001463 // Make sure we only add text changed listeners once!
1464 clearChangeListeners();
Mindy Pereira75f66632012-01-11 11:42:02 -08001465 mSubject.addTextChangedListener(this);
1466 mBodyView.addTextChangedListener(this);
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07001467 if (mToListener == null) {
1468 mToListener = new RecipientTextWatcher(mTo, this);
1469 }
1470 mTo.addTextChangedListener(mToListener);
1471 if (mCcListener == null) {
1472 mCcListener = new RecipientTextWatcher(mCc, this);
1473 }
1474 mCc.addTextChangedListener(mCcListener);
1475 if (mBccListener == null) {
1476 mBccListener = new RecipientTextWatcher(mBcc, this);
1477 }
1478 mBcc.addTextChangedListener(mBccListener);
Mindy Pereira75f66632012-01-11 11:42:02 -08001479 mFromSpinner.setOnAccountChangedListener(this);
Mindy Pereira818143e2012-01-11 13:59:49 -08001480 mAttachmentsView.setAttachmentChangesListener(this);
Mindy Pereira75f66632012-01-11 11:42:02 -08001481 }
1482
Alice Yanga990a712013-03-13 18:37:00 -07001483 private void initActionBar() {
1484 LogUtils.d(LOG_TAG, "initializing action bar in ComposeActivity");
Andrew Sapperstein52882ff2014-07-27 12:30:18 -07001485 final ActionBar actionBar = getSupportActionBar();
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001486 if (actionBar == null) {
1487 return;
1488 }
Alice Yanga990a712013-03-13 18:37:00 -07001489 if (mComposeMode == ComposeActivity.COMPOSE) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001490 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
Jin Caof0a0b4c2014-08-20 15:35:50 -07001491 actionBar.setTitle(R.string.compose_title);
Mindy Pereira326c6602012-01-04 15:32:42 -08001492 } else {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001493 actionBar.setTitle(null);
Mindy Pereira326c6602012-01-04 15:32:42 -08001494 if (mComposeModeAdapter == null) {
Jin Caof7461632014-08-11 15:21:43 -07001495 mComposeModeAdapter = new ComposeModeAdapter(actionBar.getThemedContext());
Mindy Pereira326c6602012-01-04 15:32:42 -08001496 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001497 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
1498 actionBar.setListNavigationCallbacks(mComposeModeAdapter, this);
Alice Yanga990a712013-03-13 18:37:00 -07001499 switch (mComposeMode) {
Mindy Pereira326c6602012-01-04 15:32:42 -08001500 case ComposeActivity.REPLY:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001501 actionBar.setSelectedNavigationItem(0);
Mindy Pereira326c6602012-01-04 15:32:42 -08001502 break;
1503 case ComposeActivity.REPLY_ALL:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001504 actionBar.setSelectedNavigationItem(1);
Mindy Pereira326c6602012-01-04 15:32:42 -08001505 break;
1506 case ComposeActivity.FORWARD:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001507 actionBar.setSelectedNavigationItem(2);
Mindy Pereira326c6602012-01-04 15:32:42 -08001508 break;
1509 }
1510 }
Paul Westbrook4def3bf2014-07-01 00:38:17 -07001511 actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP,
1512 ActionBar.DISPLAY_HOME_AS_UP);
Mindy Pereirafbe40192012-03-20 10:40:45 -07001513 actionBar.setHomeButtonEnabled(true);
Mindy Pereira326c6602012-01-04 15:32:42 -08001514 }
1515
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08001516 private void initFromRefMessage(int action) {
1517 setFieldsFromRefMessage(action);
Alice Yang1ebc2db2013-03-14 21:21:44 -07001518
1519 // Check if To: address and email body needs to be prefilled based on extras.
1520 // This is used for reporting rendering feedback.
1521 if (MessageHeaderView.ENABLE_REPORT_RENDERING_PROBLEM) {
1522 Intent intent = getIntent();
1523 if (intent.getExtras() != null) {
1524 String toAddresses = intent.getStringExtra(EXTRA_TO);
1525 if (toAddresses != null) {
1526 addToAddresses(Arrays.asList(TextUtils.split(toAddresses, ",")));
1527 }
1528 String body = intent.getStringExtra(EXTRA_BODY);
1529 if (body != null) {
1530 setBody(body, false /* withSignature */);
1531 }
1532 }
1533 }
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07001534 }
1535
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08001536 private void setFieldsFromRefMessage(int action) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001537 setSubject(mRefMessage, action);
1538 // Setup recipients
1539 if (action == FORWARD) {
1540 mForward = true;
Mindy Pereira6349a042012-01-04 11:25:01 -08001541 }
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08001542 initRecipientsFromRefMessage(mRefMessage, action);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001543 initQuotedTextFromRefMessage(mRefMessage, action);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001544 if (action == ComposeActivity.FORWARD || mAttachmentsChanged) {
1545 initAttachments(mRefMessage);
1546 }
Mindy Pereirac17d0732011-12-29 10:46:19 -08001547 }
1548
Andy Huang9ed742c2014-06-18 02:34:50 -07001549 protected HtmlTree.Converter<Spanned> getSpanConverter() {
1550 return new HtmlUtils.SpannedConverter();
1551 }
1552
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001553 private void initFromDraftMessage(Message message) {
Jin Cao31bb3d62014-09-11 14:01:43 -07001554 LogUtils.d(LOG_TAG, "Initializing draft from previous draft message: %s", message);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001555
Jin Cao31bb3d62014-09-11 14:01:43 -07001556 synchronized (mDraftLock) {
1557 // Draft id might already be set by the request to id map, if so we don't need to set it
1558 if (mDraftId == UIProvider.INVALID_MESSAGE_ID) {
1559 mDraftId = message.id;
1560 } else {
1561 message.id = mDraftId;
1562 }
1563 mDraft = message;
1564 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001565 mSubject.setText(message.subject);
1566 mForward = message.draftType == UIProvider.DraftType.FORWARD;
Jin Cao1fdbe1f2014-08-19 13:51:26 -07001567
Tony Mantler9016a5e2013-07-19 11:54:17 -07001568 final List<String> toAddresses = Arrays.asList(message.getToAddressesUnescaped());
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001569 addToAddresses(toAddresses);
Tony Mantler9016a5e2013-07-19 11:54:17 -07001570 addCcAddresses(Arrays.asList(message.getCcAddressesUnescaped()), toAddresses);
1571 addBccAddresses(Arrays.asList(message.getBccAddressesUnescaped()));
Mindy Pereira2421dc82012-03-27 13:32:31 -07001572 if (message.hasAttachments) {
1573 List<Attachment> attachments = message.getAttachments();
1574 for (Attachment a : attachments) {
Andy Huang5c5fd572012-04-08 18:19:29 -07001575 addAttachmentAndUpdateView(a);
Mindy Pereira2421dc82012-03-27 13:32:31 -07001576 }
1577 }
Jin Cao1fdbe1f2014-08-19 13:51:26 -07001578
1579 // If we don't need to re-populate the body, and the quoted text will be restored from
1580 // ref message. So we can skip rest of this code.
1581 if (mInnerSavedState != null && mInnerSavedState.getBoolean(EXTRA_SKIP_PARSING_BODY)) {
1582 LogUtils.i(LOG_TAG, "Skipping manually populating body and quoted text from draft.");
1583 return;
1584 }
1585
Anthony Lee2a3cc132014-04-22 14:15:25 -07001586 int quotedTextIndex = message.appendRefMessageContent ? message.quotedTextOffset : -1;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001587 // Set the body
Mindy Pereira002ff522012-05-30 10:31:26 -07001588 CharSequence quotedText = null;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001589 if (!TextUtils.isEmpty(message.bodyHtml)) {
Jin Cao32f453b2014-07-22 14:21:15 -07001590 String body = message.bodyHtml;
Mindy Pereira002ff522012-05-30 10:31:26 -07001591 if (quotedTextIndex > -1) {
Anthony Lee2a3cc132014-04-22 14:15:25 -07001592 // Find the offset in the html text of the actual quoted text and strip it out.
1593 // Note that the actual quotedTextOffset in the message has not changed as
1594 // this different offset is used only for display purposes. They point to different
1595 // parts of the original message. Please see the comments in QuoteTextView
1596 // to see the differences.
Mindy Pereira752222d2012-07-19 09:58:53 -07001597 quotedTextIndex = QuotedTextView.findQuotedTextIndex(message.bodyHtml);
1598 if (quotedTextIndex > -1) {
Jin Cao32f453b2014-07-22 14:21:15 -07001599 body = message.bodyHtml.substring(0, quotedTextIndex);
Mindy Pereira752222d2012-07-19 09:58:53 -07001600 quotedText = message.bodyHtml.subSequence(quotedTextIndex,
1601 message.bodyHtml.length());
1602 }
Mindy Pereira002ff522012-05-30 10:31:26 -07001603 }
Jin Cao32f453b2014-07-22 14:21:15 -07001604 new HtmlToSpannedTask().execute(body);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001605 } else {
Mindy Pereira752222d2012-07-19 09:58:53 -07001606 final String body = message.bodyText;
Anthony Lee2a3cc132014-04-22 14:15:25 -07001607 final CharSequence bodyText;
1608 if (TextUtils.isEmpty(body)) {
1609 bodyText = "";
1610 quotedText = null;
1611 } else {
1612 if (quotedTextIndex > body.length()) {
1613 // Sanity check to guarantee that we will not over index the String.
1614 // If this happens there is a bigger problem. This should never happen hence
1615 // the wtf logging.
1616 quotedTextIndex = -1;
1617 LogUtils.wtf(LOG_TAG, "quotedTextIndex (%d) > body.length() (%d)",
1618 quotedTextIndex, body.length());
1619 }
1620 bodyText = quotedTextIndex > -1 ? body.substring(0, quotedTextIndex) : body;
1621 if (quotedTextIndex > -1) {
1622 quotedText = body.substring(quotedTextIndex);
1623 }
Mindy Pereira002ff522012-05-30 10:31:26 -07001624 }
Jin Cao738cafe2014-09-02 16:10:29 -07001625 setBody(bodyText, false);
Mindy Pereira002ff522012-05-30 10:31:26 -07001626 }
1627 if (quotedTextIndex > -1 && quotedText != null) {
Mindy Pereira39713232012-05-30 11:48:41 -07001628 mQuotedTextView.setQuotedTextFromDraft(quotedText, mForward);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001629 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001630 }
1631
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001632 /**
1633 * Fill all the widgets with the content found in the Intent Extra, if any.
1634 * Also apply the same style to all widgets. Note: if initFromExtras is
1635 * called as a result of switching between reply, reply all, and forward per
1636 * the latest revision of Gmail, and the user has already made changes to
1637 * attachments on a previous incarnation of the message (as a reply, reply
1638 * all, or forward), the original attachments from the message will not be
1639 * re-instantiated. The user's changes will be respected. This follows the
1640 * web gmail interaction.
Andrew Sapperstein746d8612013-08-26 15:56:32 -07001641 * @return {@code true} if the activity should not call {@link #finishSetup}.
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001642 */
Andrew Sapperstein746d8612013-08-26 15:56:32 -07001643 public boolean initFromExtras(Intent intent) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001644 // If we were invoked with a SENDTO intent, the value
1645 // should take precedence
1646 final Uri dataUri = intent.getData();
1647 if (dataUri != null) {
1648 if (MAIL_TO.equals(dataUri.getScheme())) {
1649 initFromMailTo(dataUri.toString());
1650 } else {
Mindy Pereira0b4f28e2012-03-28 14:12:21 -07001651 if (!mAccount.composeIntentUri.equals(dataUri)) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001652 String toText = dataUri.getSchemeSpecificPart();
1653 if (toText != null) {
1654 mTo.setText("");
Mindy Pereiradbe89962012-04-13 09:42:38 -07001655 addToAddresses(Arrays.asList(TextUtils.split(toText, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001656 }
1657 }
1658 }
1659 }
1660
1661 String[] extraStrings = intent.getStringArrayExtra(Intent.EXTRA_EMAIL);
1662 if (extraStrings != null) {
1663 addToAddresses(Arrays.asList(extraStrings));
1664 }
1665 extraStrings = intent.getStringArrayExtra(Intent.EXTRA_CC);
1666 if (extraStrings != null) {
1667 addCcAddresses(Arrays.asList(extraStrings), null);
1668 }
1669 extraStrings = intent.getStringArrayExtra(Intent.EXTRA_BCC);
1670 if (extraStrings != null) {
1671 addBccAddresses(Arrays.asList(extraStrings));
1672 }
1673
1674 String extraString = intent.getStringExtra(Intent.EXTRA_SUBJECT);
1675 if (extraString != null) {
1676 mSubject.setText(extraString);
1677 }
1678
1679 for (String extra : ALL_EXTRAS) {
1680 if (intent.hasExtra(extra)) {
1681 String value = intent.getStringExtra(extra);
1682 if (EXTRA_TO.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001683 addToAddresses(Arrays.asList(TextUtils.split(value, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001684 } else if (EXTRA_CC.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001685 addCcAddresses(Arrays.asList(TextUtils.split(value, ",")), null);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001686 } else if (EXTRA_BCC.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001687 addBccAddresses(Arrays.asList(TextUtils.split(value, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001688 } else if (EXTRA_SUBJECT.equals(extra)) {
1689 mSubject.setText(value);
1690 } else if (EXTRA_BODY.equals(extra)) {
1691 setBody(value, true /* with signature */);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001692 } else if (EXTRA_QUOTED_TEXT.equals(extra)) {
1693 initQuotedText(value, true /* shouldQuoteText */);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001694 }
1695 }
1696 }
1697
1698 Bundle extras = intent.getExtras();
1699 if (extras != null) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001700 CharSequence text = extras.getCharSequence(Intent.EXTRA_TEXT);
Jin Caoa8f34ff2014-07-24 14:43:57 -07001701 setBody((text != null) ? text : "", true /* with signature */);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001702
1703 // TODO - support EXTRA_HTML_TEXT
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001704 }
Andrew Sapperstein746d8612013-08-26 15:56:32 -07001705
1706 mExtraValues = intent.getParcelableExtra(EXTRA_VALUES);
1707 if (mExtraValues != null) {
1708 LogUtils.d(LOG_TAG, "Launched with extra values: %s", mExtraValues.toString());
1709 initExtraValues(mExtraValues);
1710 return true;
1711 }
1712
1713 return false;
1714 }
1715
1716 protected void initExtraValues(ContentValues extraValues) {
1717 // DO NOTHING - Gmail will override
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001718 }
1719
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001720
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001721 @VisibleForTesting
1722 protected String decodeEmailInUri(String s) throws UnsupportedEncodingException {
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001723 // TODO: handle the case where there are spaces in the display name as
1724 // well as the email such as "Guy with spaces <guy+with+spaces@gmail.com>"
1725 // as they could be encoded ambiguously.
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001726 // Since URLDecode.decode changes + into ' ', and + is a valid
1727 // email character, we need to find/ replace these ourselves before
1728 // decoding.
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001729 try {
Yorke Lee7dd05b12013-04-25 10:04:43 -07001730 return URLDecoder.decode(replacePlus(s), UTF8_ENCODING_NAME);
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001731 } catch (IllegalArgumentException e) {
1732 if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
1733 LogUtils.e(LOG_TAG, "%s while decoding '%s'", e.getMessage(), s);
1734 } else {
1735 LogUtils.e(LOG_TAG, e, "Exception while decoding mailto address");
1736 }
1737 return null;
1738 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001739 }
1740
1741 /**
Yorke Lee7dd05b12013-04-25 10:04:43 -07001742 * Replaces all occurrences of '+' with "%2B", to prevent URLDecode.decode from
1743 * changing '+' into ' '
1744 *
1745 * @param toReplace Input string
1746 * @return The string with all "+" characters replaced with "%2B"
1747 */
Scott Kennedy3b965d72013-06-25 14:36:55 -07001748 private static String replacePlus(String toReplace) {
Yorke Lee7dd05b12013-04-25 10:04:43 -07001749 return toReplace.replace("+", "%2B");
1750 }
1751
1752 /**
Jin Caod67d7e32014-03-26 16:49:48 -07001753 * Replaces all occurrences of '%' with "%25", to prevent URLDecode.decode from
1754 * crashing on decoded '%' symbols
1755 *
1756 * @param toReplace Input string
1757 * @return The string with all "%" characters replaced with "%25"
1758 */
1759 private static String replacePercent(String toReplace) {
1760 return toReplace.replace("%", "%25");
1761 }
1762
1763 /**
1764 * Helper function to encapsulate encoding/decoding string from Uri.getQueryParameters
1765 * @param content Input string
1766 * @return The string that's properly escaped to be shown in mail subject/content
1767 */
1768 private static String decodeContentFromQueryParam(String content) {
1769 try {
1770 return URLDecoder.decode(replacePlus(replacePercent(content)), UTF8_ENCODING_NAME);
1771 } catch (UnsupportedEncodingException e) {
1772 LogUtils.e(LOG_TAG, "%s while decoding '%s'", e.getMessage(), content);
1773 return ""; // Default to empty string so setText/setBody has same behavior as before.
1774 }
1775 }
1776
1777 /**
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001778 * Initialize the compose view from a String representing a mailTo uri.
1779 * @param mailToString The uri as a string.
1780 */
1781 public void initFromMailTo(String mailToString) {
1782 // We need to disguise this string as a URI in order to parse it
1783 // TODO: Remove this hack when http://b/issue?id=1445295 gets fixed
1784 Uri uri = Uri.parse("foo://" + mailToString);
1785 int index = mailToString.indexOf("?");
1786 int length = "mailto".length() + 1;
1787 String to;
1788 try {
1789 // Extract the recipient after mailto:
1790 if (index == -1) {
1791 to = decodeEmailInUri(mailToString.substring(length));
1792 } else {
1793 to = decodeEmailInUri(mailToString.substring(length, index));
1794 }
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001795 if (!TextUtils.isEmpty(to)) {
1796 addToAddresses(Arrays.asList(TextUtils.split(to, ",")));
1797 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001798 } catch (UnsupportedEncodingException e) {
1799 if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
1800 LogUtils.e(LOG_TAG, "%s while decoding '%s'", e.getMessage(), mailToString);
1801 } else {
1802 LogUtils.e(LOG_TAG, e, "Exception while decoding mailto address");
1803 }
1804 }
1805
1806 List<String> cc = uri.getQueryParameters("cc");
1807 addCcAddresses(Arrays.asList(cc.toArray(new String[cc.size()])), null);
1808
1809 List<String> otherTo = uri.getQueryParameters("to");
1810 addToAddresses(Arrays.asList(otherTo.toArray(new String[otherTo.size()])));
1811
1812 List<String> bcc = uri.getQueryParameters("bcc");
1813 addBccAddresses(Arrays.asList(bcc.toArray(new String[bcc.size()])));
1814
Jin Caod67d7e32014-03-26 16:49:48 -07001815 // NOTE: Uri.getQueryParameters already decodes % encoded characters
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001816 List<String> subject = uri.getQueryParameters("subject");
1817 if (subject.size() > 0) {
Jin Caod67d7e32014-03-26 16:49:48 -07001818 mSubject.setText(decodeContentFromQueryParam(subject.get(0)));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001819 }
1820
1821 List<String> body = uri.getQueryParameters("body");
1822 if (body.size() > 0) {
Jin Caod67d7e32014-03-26 16:49:48 -07001823 setBody(decodeContentFromQueryParam(body.get(0)), true /* with signature */);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001824 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001825 }
1826
Mindy Pereirabddd6f32012-06-20 12:10:03 -07001827 @VisibleForTesting
1828 protected void initAttachments(Message refMessage) {
Mark Wei434f2942012-08-24 11:54:02 -07001829 addAttachments(refMessage.getAttachments());
1830 }
1831
1832 public long addAttachments(List<Attachment> attachments) {
1833 long size = 0;
1834 AttachmentFailureException error = null;
1835 for (Attachment a : attachments) {
1836 try {
1837 size += mAttachmentsView.addAttachment(mAccount, a);
1838 } catch (AttachmentFailureException e) {
1839 error = e;
1840 }
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001841 }
Mark Wei434f2942012-08-24 11:54:02 -07001842 if (error != null) {
1843 LogUtils.e(LOG_TAG, error, "Error adding attachment");
1844 if (attachments.size() > 1) {
1845 showAttachmentTooBigToast(R.string.too_large_to_attach_multiple);
1846 } else {
1847 showAttachmentTooBigToast(error.getErrorRes());
1848 }
1849 }
1850 return size;
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001851 }
1852
1853 /**
1854 * When an attachment is too large to be added to a message, show a toast.
1855 * This method also updates the position of the toast so that it is shown
1856 * clearly above they keyboard if it happens to be open.
1857 */
Mark Wei434f2942012-08-24 11:54:02 -07001858 private void showAttachmentTooBigToast(int errorRes) {
1859 String maxSize = AttachmentUtils.convertToHumanReadableSize(
1860 getApplicationContext(), mAccount.settings.getMaxAttachmentSize());
1861 showErrorToast(getString(errorRes, maxSize));
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001862 }
1863
Mark Wei434f2942012-08-24 11:54:02 -07001864 private void showErrorToast(String message) {
1865 Toast t = Toast.makeText(this, message, Toast.LENGTH_LONG);
1866 t.setText(message);
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001867 t.setGravity(Gravity.CENTER_HORIZONTAL, 0,
1868 getResources().getDimensionPixelSize(R.dimen.attachment_toast_yoffset));
1869 t.show();
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001870 }
1871
Paul Westbrookf97588b2012-03-20 11:11:37 -07001872 private void initAttachmentsFromIntent(Intent intent) {
Paul Westbrook03ee9712012-04-02 09:51:51 -07001873 Bundle extras = intent.getExtras();
1874 if (extras == null) {
1875 extras = Bundle.EMPTY;
1876 }
Paul Westbrookf97588b2012-03-20 11:11:37 -07001877 final String action = intent.getAction();
1878 if (!mAttachmentsChanged) {
1879 long totalSize = 0;
1880 if (extras.containsKey(EXTRA_ATTACHMENTS)) {
Jin Caoadea2c82014-08-28 12:25:52 -07001881 final String[] uris = (String[]) extras.getSerializable(EXTRA_ATTACHMENTS);
1882 final ArrayList<Uri> parsedUris = Lists.newArrayListWithCapacity(uris.length);
1883 for (String uri : uris) {
1884 parsedUris.add(Uri.parse(uri));
Paul Westbrookf97588b2012-03-20 11:11:37 -07001885 }
Jin Caoadea2c82014-08-28 12:25:52 -07001886 totalSize += handleAttachmentUrisFromIntent(parsedUris);
Paul Westbrookf97588b2012-03-20 11:11:37 -07001887 }
mindyp9a9e8d62012-10-03 12:24:07 -07001888 if (extras.containsKey(Intent.EXTRA_STREAM)) {
1889 if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
Andy Huang91ede362014-01-21 19:16:00 -08001890 final ArrayList<Uri> uris = extras
mindyp9a9e8d62012-10-03 12:24:07 -07001891 .getParcelableArrayList(Intent.EXTRA_STREAM);
Jin Caoadea2c82014-08-28 12:25:52 -07001892 totalSize += handleAttachmentUrisFromIntent(uris);
mindyp9a9e8d62012-10-03 12:24:07 -07001893 } else {
Tony Mantler581edd42014-02-18 15:41:22 -08001894 final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
Jin Caoadea2c82014-08-28 12:25:52 -07001895 final ArrayList<Uri> uris = Lists.newArrayList(uri);
1896 totalSize += handleAttachmentUrisFromIntent(uris);
Paul Westbrookf97588b2012-03-20 11:11:37 -07001897 }
1898 }
1899
1900 if (totalSize > 0) {
1901 mAttachmentsChanged = true;
1902 updateSaveUi();
Andy Huange003b4c2013-08-16 10:32:05 -07001903
1904 Analytics.getInstance().sendEvent("send_intent_with_attachments",
1905 Integer.toString(getAttachments().size()), null, totalSize);
Paul Westbrookf97588b2012-03-20 11:11:37 -07001906 }
1907 }
1908 }
1909
Jin Caoadea2c82014-08-28 12:25:52 -07001910 /**
1911 * Helper function to handle a list of uris to attach.
1912 * @return the total size of all successfully attached files.
1913 */
1914 private long handleAttachmentUrisFromIntent(List<Uri> uris) {
1915 ArrayList<Attachment> attachments = Lists.newArrayList();
1916 for (Uri uri : uris) {
1917 try {
1918 if (uri != null) {
1919 if ("file".equals(uri.getScheme())) {
1920 final File f = new File(uri.getPath());
Jin Cao24ed2942014-09-02 10:21:37 -07001921 // We should not be attaching any files from the data directory UNLESS
1922 // the data directory is part of the calling process.
1923 final String filePath = f.getCanonicalPath();
1924 if (filePath.startsWith(DATA_DIRECTORY_ROOT)) {
1925 final String callingPackage = getCallingPackage();
1926 if (callingPackage == null) {
1927 showErrorToast(getString(R.string.attachment_permission_denied));
1928 continue;
1929 }
1930
1931 // So it looks like the data directory are usually /data/data, but
1932 // DATA_DIRECTORY_ROOT is only /data.. so let's check for both
1933 final String pathWithoutRoot;
1934 // We add 1 to the length for the additional / before the package name.
1935 if (filePath.startsWith(ALTERNATE_DATA_DIRECTORY_ROOT)) {
1936 pathWithoutRoot = filePath.substring(
1937 ALTERNATE_DATA_DIRECTORY_ROOT.length() + 1);
1938 } else {
1939 pathWithoutRoot = filePath.substring(
1940 DATA_DIRECTORY_ROOT.length() + 1);
1941 }
1942
1943 // If we are trying to access a data package that's not part of the
1944 // calling package, show error toast and ignore this attachment.
1945 if (!pathWithoutRoot.startsWith(callingPackage)) {
1946 showErrorToast(getString(R.string.attachment_permission_denied));
1947 continue;
1948 }
Jin Caoadea2c82014-08-28 12:25:52 -07001949 }
1950 }
1951 if (!handleSpecialAttachmentUri(uri)) {
1952 final Attachment a = mAttachmentsView.generateLocalAttachment(uri);
1953 attachments.add(a);
1954
1955 Analytics.getInstance().sendEvent("send_intent_attachment",
1956 Utils.normalizeMimeType(a.getContentType()), null, a.size);
1957 }
1958 }
1959 } catch (AttachmentFailureException e) {
1960 LogUtils.e(LOG_TAG, e, "Error adding attachment");
1961 showAttachmentTooBigToast(e.getErrorRes());
1962 } catch (IOException | SecurityException e) {
Jin Cao24ed2942014-09-02 10:21:37 -07001963 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Jin Caoadea2c82014-08-28 12:25:52 -07001964 showErrorToast(getString(R.string.attachment_permission_denied));
1965 }
1966 }
1967 return addAttachments(attachments);
1968 }
1969
Andrew Sapperstein746d8612013-08-26 15:56:32 -07001970 protected void initQuotedText(CharSequence quotedText, boolean shouldQuoteText) {
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001971 mQuotedTextView.setQuotedTextFromHtml(quotedText, shouldQuoteText);
1972 mShowQuotedText = true;
1973 }
Paul Westbrookf97588b2012-03-20 11:11:37 -07001974
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001975 private void initQuotedTextFromRefMessage(Message refMessage, int action) {
1976 if (mRefMessage != null && (action == REPLY || action == REPLY_ALL || action == FORWARD)) {
Mindy Pereira9932dee2012-01-10 16:09:50 -08001977 mQuotedTextView.setQuotedText(action, refMessage, action != FORWARD);
1978 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001979 }
1980
1981 private void updateHideOrShowCcBcc() {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001982 // Its possible there is a menu item OR a button.
Mindy Pereira326689d2012-05-17 10:14:14 -07001983 boolean ccVisible = mCcBccView.isCcVisible();
1984 boolean bccVisible = mCcBccView.isBccVisible();
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001985 if (mCcBccButton != null) {
Mindy Pereira326689d2012-05-17 10:14:14 -07001986 if (!ccVisible || !bccVisible) {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001987 mCcBccButton.setVisibility(View.VISIBLE);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001988 } else {
Jin Cao9d358a12014-07-24 12:15:38 -07001989 mCcBccButton.setVisibility(View.GONE);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001990 }
1991 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001992 }
1993
Mindy Pereira013194c2012-01-06 15:09:33 -08001994 /**
1995 * Add attachment and update the compose area appropriately.
Mindy Pereira013194c2012-01-06 15:09:33 -08001996 */
Andrew Sapperstein865ae9c2014-02-10 18:23:48 -08001997 private void addAttachmentAndUpdateView(Intent data) {
Andrew Sapperstein05089f32013-10-01 17:00:03 -07001998 if (data == null) {
1999 return;
2000 }
2001
2002 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
2003 final ClipData clipData = data.getClipData();
2004 if (clipData != null) {
2005 for (int i = 0, size = clipData.getItemCount(); i < size; i++) {
2006 addAttachmentAndUpdateView(clipData.getItemAt(i).getUri());
2007 }
2008 return;
2009 }
2010 }
2011
2012 addAttachmentAndUpdateView(data.getData());
Mindy Pereira2421dc82012-03-27 13:32:31 -07002013 }
2014
Andrew Sapperstein865ae9c2014-02-10 18:23:48 -08002015 private void addAttachmentAndUpdateView(Uri contentUri) {
Andy Huang5c5fd572012-04-08 18:19:29 -07002016 if (contentUri == null) {
Mindy Pereira2421dc82012-03-27 13:32:31 -07002017 return;
2018 }
Mindy Pereira013194c2012-01-06 15:09:33 -08002019 try {
Andy Huang91ede362014-01-21 19:16:00 -08002020
2021 if (handleSpecialAttachmentUri(contentUri)) {
2022 return;
2023 }
2024
Andy Huang5c5fd572012-04-08 18:19:29 -07002025 addAttachmentAndUpdateView(mAttachmentsView.generateLocalAttachment(contentUri));
2026 } catch (AttachmentFailureException e) {
Andy Huang5c5fd572012-04-08 18:19:29 -07002027 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Mark Wei434f2942012-08-24 11:54:02 -07002028 showErrorToast(getResources().getString(
2029 e.getErrorRes(),
2030 AttachmentUtils.convertToHumanReadableSize(
2031 getApplicationContext(), mAccount.settings.getMaxAttachmentSize())));
Andy Huang5c5fd572012-04-08 18:19:29 -07002032 }
2033 }
2034
Andy Huang91ede362014-01-21 19:16:00 -08002035 /**
2036 * Allow subclasses to implement custom handling of attachments.
2037 *
2038 * @param contentUri a passed-in URI from a pick intent
2039 * @return true iff handled
2040 */
2041 protected boolean handleSpecialAttachmentUri(final Uri contentUri) {
2042 return false;
2043 }
2044
Andrew Sapperstein865ae9c2014-02-10 18:23:48 -08002045 private void addAttachmentAndUpdateView(Attachment attachment) {
Andy Huang5c5fd572012-04-08 18:19:29 -07002046 try {
Mark Wei434f2942012-08-24 11:54:02 -07002047 long size = mAttachmentsView.addAttachment(mAccount, attachment);
Mindy Pereira9932dee2012-01-10 16:09:50 -08002048 if (size > 0) {
2049 mAttachmentsChanged = true;
2050 updateSaveUi();
Mindy Pereira013194c2012-01-06 15:09:33 -08002051 }
Mindy Pereira9932dee2012-01-10 16:09:50 -08002052 } catch (AttachmentFailureException e) {
Mindy Pereira9932dee2012-01-10 16:09:50 -08002053 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Mark Wei434f2942012-08-24 11:54:02 -07002054 showAttachmentTooBigToast(e.getErrorRes());
Mindy Pereira013194c2012-01-06 15:09:33 -08002055 }
2056 }
2057
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08002058 void initRecipientsFromRefMessage(Message refMessage, int action) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002059 // Don't populate the address if this is a forward.
2060 if (action == ComposeActivity.FORWARD) {
2061 return;
2062 }
Scott Kennedyff8553f2013-04-05 20:57:44 -07002063 initReplyRecipients(refMessage, action);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002064 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002065
Paul Westbrook6d2442b2013-07-17 17:51:51 -07002066 // TODO: This should be private. This method shouldn't be used by ComposeActivityTests, as
2067 // it doesn't setup the state of the activity correctly
Mindy Pereira818143e2012-01-11 13:59:49 -08002068 @VisibleForTesting
Scott Kennedyff8553f2013-04-05 20:57:44 -07002069 void initReplyRecipients(final Message refMessage, final int action) {
Tony Mantler9016a5e2013-07-19 11:54:17 -07002070 String[] sentToAddresses = refMessage.getToAddressesUnescaped();
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08002071 final Collection<String> toAddresses;
Tony Mantler89de9eb2013-07-25 11:43:58 -07002072 final String[] fromAddresses = refMessage.getFromAddressesUnescaped();
2073 final String fromAddress = fromAddresses.length > 0 ? fromAddresses[0] : null;
Andy Huange2af8872014-01-16 12:36:27 -08002074 final String[] replyToAddresses = getReplyToAddresses(
2075 refMessage.getReplyToAddressesUnescaped(), fromAddress);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002076
2077 // If this is a reply, the Cc list is empty. If this is a reply-all, the
2078 // Cc list is the union of the To and Cc recipients of the original
2079 // message, excluding the current user's email address and any addresses
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08002080 // already on the To list.
2081 if (action == ComposeActivity.REPLY) {
Tony Mantler24f116f2014-01-16 10:20:50 -08002082 toAddresses = initToRecipients(fromAddress, replyToAddresses, sentToAddresses);
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08002083 addToAddresses(toAddresses);
2084 } else if (action == ComposeActivity.REPLY_ALL) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002085 final Set<String> ccAddresses = Sets.newHashSet();
Tony Mantler24f116f2014-01-16 10:20:50 -08002086 toAddresses = initToRecipients(fromAddress, replyToAddresses, sentToAddresses);
Mindy Pereira154386a2012-01-11 13:02:33 -08002087 addToAddresses(toAddresses);
Scott Kennedyff8553f2013-04-05 20:57:44 -07002088 addRecipients(ccAddresses, sentToAddresses);
Tony Mantler9016a5e2013-07-19 11:54:17 -07002089 addRecipients(ccAddresses, refMessage.getCcAddressesUnescaped());
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002090 addCcAddresses(ccAddresses, toAddresses);
2091 }
2092 }
2093
Andy Huange2af8872014-01-16 12:36:27 -08002094 // If there is no reply to address, the reply to address is the sender.
2095 private static String[] getReplyToAddresses(String[] replyTo, String from) {
2096 boolean hasReplyTo = false;
2097 for (final String replyToAddress : replyTo) {
2098 if (!TextUtils.isEmpty(replyToAddress)) {
2099 hasReplyTo = true;
2100 }
2101 }
2102 return hasReplyTo ? replyTo : new String[] {from};
2103 }
2104
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002105 private void addToAddresses(Collection<String> addresses) {
2106 addAddressesToList(addresses, mTo);
2107 }
2108
2109 private void addCcAddresses(Collection<String> addresses, Collection<String> toAddresses) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07002110 addCcAddressesToList(tokenizeAddressList(addresses),
2111 toAddresses != null ? tokenizeAddressList(toAddresses) : null, mCc);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002112 }
2113
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07002114 private void addBccAddresses(Collection<String> addresses) {
2115 addAddressesToList(addresses, mBcc);
2116 }
2117
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002118 @VisibleForTesting
2119 protected void addCcAddressesToList(List<Rfc822Token[]> addresses,
2120 List<Rfc822Token[]> compareToList, RecipientEditTextView list) {
2121 String address;
2122
Mindy Pereira8eca57a2012-03-20 16:42:34 -07002123 if (compareToList == null) {
Tony Mantler581edd42014-02-18 15:41:22 -08002124 for (final Rfc822Token[] tokens : addresses) {
2125 for (final Rfc822Token token : tokens) {
2126 address = token.toString();
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002127 list.append(address + END_TOKEN);
2128 }
2129 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07002130 } else {
2131 HashSet<String> compareTo = convertToHashSet(compareToList);
Tony Mantler581edd42014-02-18 15:41:22 -08002132 for (final Rfc822Token[] tokens : addresses) {
2133 for (final Rfc822Token token : tokens) {
2134 address = token.toString();
Mindy Pereira8eca57a2012-03-20 16:42:34 -07002135 // Check if this is a duplicate:
Tony Mantler581edd42014-02-18 15:41:22 -08002136 if (!compareTo.contains(token.getAddress())) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07002137 // Get the address here
2138 list.append(address + END_TOKEN);
2139 }
2140 }
2141 }
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002142 }
2143 }
2144
Scott Kennedyff8553f2013-04-05 20:57:44 -07002145 private static HashSet<String> convertToHashSet(final List<Rfc822Token[]> list) {
2146 final HashSet<String> hash = new HashSet<String>();
2147 for (final Rfc822Token[] tokens : list) {
Tony Mantler581edd42014-02-18 15:41:22 -08002148 for (final Rfc822Token token : tokens) {
2149 hash.add(token.getAddress());
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002150 }
2151 }
2152 return hash;
2153 }
2154
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002155 protected List<Rfc822Token[]> tokenizeAddressList(Collection<String> addresses) {
2156 @VisibleForTesting
2157 List<Rfc822Token[]> tokenized = new ArrayList<Rfc822Token[]>();
2158
2159 for (String address: addresses) {
2160 tokenized.add(Rfc822Tokenizer.tokenize(address));
2161 }
2162 return tokenized;
2163 }
2164
2165 @VisibleForTesting
2166 void addAddressesToList(Collection<String> addresses, RecipientEditTextView list) {
2167 for (String address : addresses) {
2168 addAddressToList(address, list);
2169 }
2170 }
2171
Scott Kennedyff8553f2013-04-05 20:57:44 -07002172 private static void addAddressToList(final String address, final RecipientEditTextView list) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002173 if (address == null || list == null)
2174 return;
2175
Scott Kennedyff8553f2013-04-05 20:57:44 -07002176 final Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(address);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002177
Tony Mantler581edd42014-02-18 15:41:22 -08002178 for (final Rfc822Token token : tokens) {
2179 list.append(token + END_TOKEN);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002180 }
2181 }
2182
2183 @VisibleForTesting
Scott Kennedyff8553f2013-04-05 20:57:44 -07002184 protected Collection<String> initToRecipients(final String fullSenderAddress,
Tony Mantler24f116f2014-01-16 10:20:50 -08002185 final String[] replyToAddresses, final String[] inToAddresses) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002186 // The To recipient is the reply-to address specified in the original
2187 // message, unless it is:
2188 // the current user OR a custom from of the current user, in which case
2189 // it's the To recipient list of the original message.
2190 // OR missing, in which case use the sender of the original message
2191 Set<String> toAddresses = Sets.newHashSet();
Tony Mantler24f116f2014-01-16 10:20:50 -08002192 for (final String replyToAddress : replyToAddresses) {
2193 if (!TextUtils.isEmpty(replyToAddress)
2194 && !recipientMatchesThisAccount(replyToAddress)) {
2195 toAddresses.add(replyToAddress);
2196 }
2197 }
2198 if (toAddresses.size() == 0) {
mindyp65b06f52012-11-21 10:35:08 -08002199 // In this case, the user is replying to a message in which their
Tony Mantler24f116f2014-01-16 10:20:50 -08002200 // current account or some of their custom from addresses are the only
2201 // recipients and they sent the original message.
mindyp65b06f52012-11-21 10:35:08 -08002202 if (inToAddresses.length == 1 && recipientMatchesThisAccount(fullSenderAddress)
2203 && recipientMatchesThisAccount(inToAddresses[0])) {
2204 toAddresses.add(inToAddresses[0]);
2205 return toAddresses;
2206 }
2207 // This happens if the user replies to a message they originally
2208 // wrote. In this case, "reply" really means "re-send," so we
2209 // target the original recipients. This works as expected even
2210 // if the user sent the original message to themselves.
2211 for (String address : inToAddresses) {
2212 if (!recipientMatchesThisAccount(address)) {
2213 toAddresses.add(address);
mindypfe8557b2012-11-05 12:05:16 -08002214 }
Mindy Pereira1469b4e2012-06-19 19:18:54 -07002215 }
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002216 }
2217 return toAddresses;
2218 }
2219
Scott Kennedyff8553f2013-04-05 20:57:44 -07002220 private void addRecipients(final Set<String> recipients, final String[] addresses) {
2221 for (final String email : addresses) {
Mindy Pereiracecc54a2012-07-31 09:38:11 -07002222 // Do not add this account, or any of its custom from addresses, to
2223 // the list of recipients.
Mindy Pereira4a20b702012-01-05 16:24:24 -08002224 final String recipientAddress = Address.getEmailAddress(email).getAddress();
mindyp5ee5d692012-11-19 16:02:16 -08002225 if (!recipientMatchesThisAccount(recipientAddress)) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002226 recipients.add(email.replace("\"\"", ""));
2227 }
2228 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002229 }
2230
Mindy Pereiracecc54a2012-07-31 09:38:11 -07002231 /**
2232 * A recipient matches this account if it has the same address as the
2233 * currently selected account OR one of the custom from addresses associated
2234 * with the currently selected account.
Mindy Pereiracecc54a2012-07-31 09:38:11 -07002235 * @param recipientAddress address we are comparing with the currently selected account
Mindy Pereiracecc54a2012-07-31 09:38:11 -07002236 */
mindyp5ee5d692012-11-19 16:02:16 -08002237 protected boolean recipientMatchesThisAccount(String recipientAddress) {
2238 return ReplyFromAccount.matchesAccountOrCustomFrom(mAccount, recipientAddress,
mindypfe8557b2012-11-05 12:05:16 -08002239 mAccount.getReplyFroms());
Mindy Pereiracecc54a2012-07-31 09:38:11 -07002240 }
2241
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07002242 /**
2243 * Returns a formatted subject string with the appropriate prefix for the action type.
2244 * E.g., "FWD: " is prepended if action is {@link ComposeActivity#FORWARD}.
2245 */
Andrew Sapperstein7e04f142014-06-11 13:43:07 -07002246 public static String buildFormattedSubject(Resources res, String subject, int action) {
Tony Mantler41c3a252014-06-30 11:00:43 -07002247 final String prefix;
2248 final String correctedSubject;
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002249 if (action == ComposeActivity.COMPOSE) {
2250 prefix = "";
2251 } else if (action == ComposeActivity.FORWARD) {
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07002252 prefix = res.getString(R.string.forward_subject_label);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002253 } else {
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07002254 prefix = res.getString(R.string.reply_subject_label);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002255 }
2256
Tony Mantler41c3a252014-06-30 11:00:43 -07002257 if (TextUtils.isEmpty(subject)) {
2258 correctedSubject = prefix;
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002259 } else {
Tony Mantler41c3a252014-06-30 11:00:43 -07002260 // Don't duplicate the prefix
2261 if (subject.toLowerCase().startsWith(prefix.toLowerCase())) {
2262 correctedSubject = subject;
2263 } else {
2264 correctedSubject = String.format(
2265 res.getString(R.string.formatted_subject), prefix, subject);
2266 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002267 }
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07002268
2269 return correctedSubject;
2270 }
2271
2272 private void setSubject(Message refMessage, int action) {
2273 mSubject.setText(buildFormattedSubject(getResources(), refMessage.subject, action));
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002274 }
2275
Mindy Pereira818143e2012-01-11 13:59:49 -08002276 private void initRecipients() {
2277 setupRecipients(mTo);
2278 setupRecipients(mCc);
2279 setupRecipients(mBcc);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002280 }
2281
Mindy Pereira818143e2012-01-11 13:59:49 -08002282 private void setupRecipients(RecipientEditTextView view) {
Andrew Sapperstein9afa8222014-06-23 16:19:23 -07002283 final DropdownChipLayouter layouter = getDropdownChipLayouter();
2284 if (layouter != null) {
2285 view.setDropdownChipLayouter(layouter);
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07002286 }
Andrew Sapperstein9afa8222014-06-23 16:19:23 -07002287 view.setAdapter(getRecipientAdapter());
Andrew Sappersteinffd61552014-05-14 15:04:23 -07002288 view.setRecipientEntryItemClickedListener(this);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002289 if (mValidator == null) {
Tony Mantler79b11562013-10-09 15:31:50 -07002290 final String accountName = mAccount.getEmailAddress();
Mindy Pereira33fe9082012-01-09 16:24:30 -08002291 int offset = accountName.indexOf("@") + 1;
2292 String account = accountName;
Tony Mantler79b11562013-10-09 15:31:50 -07002293 if (offset > 0) {
2294 account = account.substring(offset);
Mindy Pereirac17d0732011-12-29 10:46:19 -08002295 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002296 mValidator = new Rfc822Validator(account);
Mindy Pereirac17d0732011-12-29 10:46:19 -08002297 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002298 view.setValidator(mValidator);
Mindy Pereira8e9305e2011-12-13 14:25:04 -08002299 }
2300
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07002301 /**
2302 * Derived classes should override if they wish to provide their own autocomplete behavior.
2303 */
2304 public BaseRecipientAdapter getRecipientAdapter() {
2305 return new RecipientAdapter(this, mAccount);
2306 }
2307
2308 /**
2309 * Derived classes should override this to provide their own dropdown behavior.
2310 * If the result is null, the default {@link com.android.ex.chips.DropdownChipLayouter}
2311 * is used.
2312 */
2313 public DropdownChipLayouter getDropdownChipLayouter() {
2314 return null;
2315 }
2316
Mindy Pereira8e9305e2011-12-13 14:25:04 -08002317 @Override
2318 public void onClick(View v) {
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002319 final int id = v.getId();
2320 if (id == R.id.add_cc_bcc) {
2321 // Verify that cc/ bcc aren't showing.
2322 // Animate in cc/bcc.
2323 showCcBccViews();
Mindy Pereira8e9305e2011-12-13 14:25:04 -08002324 }
2325 }
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002326
2327 @Override
Jin Caoc5c550a2014-07-29 11:53:17 -07002328 public void onFocusChange (View v, boolean hasFocus) {
2329 final int id = v.getId();
2330 if (hasFocus && (id == R.id.subject || id == R.id.body)) {
2331 // Collapse cc/bcc iff both are empty
2332 final boolean showCcBccFields = !TextUtils.isEmpty(mCc.getText()) ||
2333 !TextUtils.isEmpty(mBcc.getText());
2334 mCcBccView.show(false /* animate */, showCcBccFields, showCcBccFields);
Jin Cao36e23872014-07-29 13:41:12 -07002335 mCcBccButton.setVisibility(showCcBccFields ? View.GONE : View.VISIBLE);
2336
2337 // On phones autoscroll down so that Cc aligns to the top if we are showing cc/bcc.
2338 if (getResources().getBoolean(R.bool.auto_scroll_cc) && showCcBccFields) {
2339 final int[] coords = new int[2];
2340 mCc.getLocationOnScreen(coords);
2341
2342 // Subtract status bar and action bar height from y-coord.
Jin Caocfba4bb2014-10-07 19:29:15 -07002343 getWindow().getDecorView().getWindowVisibleDisplayFrame(mRect);
2344 final int deltaY = coords[1] - getSupportActionBar().getHeight() - mRect.top;
Jin Cao36e23872014-07-29 13:41:12 -07002345
2346 // Only scroll down
2347 if (deltaY > 0) {
2348 mScrollView.smoothScrollBy(0, deltaY);
2349 }
2350 }
Jin Caoc5c550a2014-07-29 11:53:17 -07002351 }
2352 }
2353
2354 @Override
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002355 public boolean onCreateOptionsMenu(Menu menu) {
Tony Mantler5b8799a2013-10-31 10:43:03 -07002356 final boolean superCreated = super.onCreateOptionsMenu(menu);
Mindy Pereirab199d172012-08-13 11:04:03 -07002357 // Don't render any menu items when there are no accounts.
2358 if (mAccounts == null || mAccounts.length == 0) {
Tony Mantler5b8799a2013-10-31 10:43:03 -07002359 return superCreated;
Mindy Pereirab199d172012-08-13 11:04:03 -07002360 }
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002361 MenuInflater inflater = getMenuInflater();
2362 inflater.inflate(R.menu.compose_menu, menu);
mindyp1d7e9142012-11-21 13:54:30 -08002363
2364 /*
2365 * Start save in the correct enabled state.
2366 * 1) If a user launches compose from within gmail, save is disabled
2367 * until they add something, at which point, save is enabled, auto save
2368 * on exit; if the user empties everything, save is disabled, exiting does not
2369 * auto-save
2370 * 2) if a user replies/ reply all/ forwards from within gmail, save is
2371 * disabled until they change something, at which point, save is
2372 * enabled, auto save on exit; if the user empties everything, save is
2373 * disabled, exiting does not auto-save.
2374 * 3) If a user launches compose from another application and something
2375 * gets populated (attachments, recipients, body, subject, etc), save is
2376 * enabled, auto save on exit; if the user empties everything, save is
2377 * disabled, exiting does not auto-save
2378 */
Mindy Pereira82cc5662012-01-09 17:29:30 -08002379 mSave = menu.findItem(R.id.save);
mindyp1d7e9142012-11-21 13:54:30 -08002380 String action = getIntent() != null ? getIntent().getAction() : null;
Andy Huang9f855d62013-05-30 17:15:03 -07002381 enableSave(mInnerSavedState != null ?
2382 mInnerSavedState.getBoolean(EXTRA_SAVE_ENABLED)
mindyp1d7e9142012-11-21 13:54:30 -08002383 : (Intent.ACTION_SEND.equals(action)
2384 || Intent.ACTION_SEND_MULTIPLE.equals(action)
2385 || Intent.ACTION_SENDTO.equals(action)
Jin Caoe0037922014-09-16 10:23:50 -07002386 || isDraftDirty()));
mindyp1d7e9142012-11-21 13:54:30 -08002387
Greg Bullockd47a7042014-08-13 16:02:59 +02002388 final MenuItem helpItem = menu.findItem(R.id.help_info_menu_item);
2389 final MenuItem sendFeedbackItem = menu.findItem(R.id.feedback_menu_item);
2390 final MenuItem attachFromServiceItem = menu.findItem(R.id.attach_from_service_stub1);
Mindy Pereira3ca5bad2012-04-16 11:02:42 -07002391 if (helpItem != null) {
2392 helpItem.setVisible(mAccount != null
2393 && mAccount.supportsCapability(AccountCapabilities.HELP_CONTENT));
2394 }
2395 if (sendFeedbackItem != null) {
2396 sendFeedbackItem.setVisible(mAccount != null
2397 && mAccount.supportsCapability(AccountCapabilities.SEND_FEEDBACK));
2398 }
Greg Bullockd47a7042014-08-13 16:02:59 +02002399 if (attachFromServiceItem != null) {
2400 attachFromServiceItem.setVisible(shouldEnableAttachFromServiceMenu(mAccount));
2401 }
Andrew Sapperstein5cb71802013-10-01 18:31:20 -07002402
Andrew Sapperstein8809f9f2013-10-11 16:13:35 -07002403 // Show attach picture on pre-K devices.
2404 menu.findItem(R.id.add_photo_attachment).setVisible(!Utils.isRunningKitkatOrLater());
Andrew Sapperstein5cb71802013-10-01 18:31:20 -07002405
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002406 return true;
2407 }
2408
2409 @Override
2410 public boolean onOptionsItemSelected(MenuItem item) {
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002411 final int id = item.getItemId();
Andy Huangdc97bf42013-08-15 16:52:45 -07002412
Andy Huangf8c59b02014-03-19 20:00:53 -07002413 Analytics.getInstance().sendMenuItemEvent(Analytics.EVENT_CATEGORY_MENU_ITEM, id,
2414 "compose", 0);
Andy Huangdc97bf42013-08-15 16:52:45 -07002415
Mindy Pereira75f66632012-01-11 11:42:02 -08002416 boolean handled = true;
Andrew Sapperstein5cb71802013-10-01 18:31:20 -07002417 if (id == R.id.add_file_attachment) {
2418 doAttach(MIME_TYPE_ALL);
2419 } else if (id == R.id.add_photo_attachment) {
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002420 doAttach(MIME_TYPE_PHOTO);
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002421 } else if (id == R.id.save) {
2422 doSave(true);
2423 } else if (id == R.id.send) {
2424 doSend();
2425 } else if (id == R.id.discard) {
2426 doDiscard();
2427 } else if (id == R.id.settings) {
2428 Utils.showSettings(this, mAccount);
2429 } else if (id == android.R.id.home) {
2430 onAppUpPressed();
2431 } else if (id == R.id.help_info_menu_item) {
2432 Utils.showHelp(this, mAccount, getString(R.string.compose_help_context));
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002433 } else {
2434 handled = false;
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002435 }
Tony Mantler581edd42014-02-18 15:41:22 -08002436 return handled || super.onOptionsItemSelected(item);
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002437 }
Mindy Pereira326c6602012-01-04 15:32:42 -08002438
Mindy Pereirab199d172012-08-13 11:04:03 -07002439 @Override
2440 public void onBackPressed() {
2441 // If we are showing the wait fragment, just exit.
2442 if (getWaitFragment() != null) {
2443 finish();
2444 } else {
2445 super.onBackPressed();
2446 }
2447 }
2448
Vikram Aggarwal1672ff82012-09-21 10:15:22 -07002449 /**
2450 * Carries out the "up" action in the action bar.
2451 */
Paul Westbrookdaecb4b2012-05-31 10:21:26 -07002452 private void onAppUpPressed() {
2453 if (mLaunchedFromEmail) {
2454 // If this was started from Gmail, simply treat app up as the system back button, so
2455 // that the last view is restored.
2456 onBackPressed();
2457 return;
2458 }
2459
2460 // Fire the main activity to ensure it launches the "top" screen of mail.
2461 // Since the main Activity is singleTask, it should revive that task if it was already
2462 // started.
Vikram Aggarwal0c3c2052012-09-21 11:06:28 -07002463 final Intent mailIntent = Utils.createViewInboxIntent(mAccount);
Paul Westbrookdaecb4b2012-05-31 10:21:26 -07002464 mailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |
2465 Intent.FLAG_ACTIVITY_TASK_ON_HOME);
2466 startActivity(mailIntent);
2467 finish();
2468 }
2469
Mindy Pereira33fe9082012-01-09 16:24:30 -08002470 private void doSend() {
Mark Weidd19b632012-10-19 13:59:28 -07002471 sendOrSaveWithSanityChecks(false, true, false, false);
Andy Huangdc97bf42013-08-15 16:52:45 -07002472 logSendOrSave(false /* save */);
2473 mPerformedSendOrDiscard = true;
Mindy Pereira33fe9082012-01-09 16:24:30 -08002474 }
2475
Mindy Pereira48e31b02012-05-30 13:12:24 -07002476 private void doSave(boolean showToast) {
Mark Weidd19b632012-10-19 13:59:28 -07002477 sendOrSaveWithSanityChecks(true, showToast, false, false);
Mindy Pereira48e31b02012-05-30 13:12:24 -07002478 }
2479
Andrew Sappersteinffd61552014-05-14 15:04:23 -07002480 @Override
2481 public void onRecipientEntryItemClicked(int charactersTyped, int position) {
2482 // Send analytics of characters typed and position in dropdown selected.
2483 Analytics.getInstance().sendEvent(
Andrew Sapperstein9afa8222014-06-23 16:19:23 -07002484 "suggest_click", Integer.toString(charactersTyped), Integer.toString(position), 0);
Andrew Sappersteinffd61552014-05-14 15:04:23 -07002485 }
2486
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002487 @VisibleForTesting
2488 public interface SendOrSaveCallback {
Jin Caoaff451f2014-09-09 14:32:04 -07002489 void initializeSendOrSave();
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07002490 void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage, Message message);
Jin Cao31bb3d62014-09-11 14:01:43 -07002491 long getMessageId();
Jin Caoaff451f2014-09-09 14:32:04 -07002492 void sendOrSaveFinished(SendOrSaveMessage message, boolean success);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002493 }
2494
Jin Caoaff451f2014-09-09 14:32:04 -07002495 private void runSendOrSaveProviderCalls(SendOrSaveMessage sendOrSaveMessage,
Jin Cao31bb3d62014-09-11 14:01:43 -07002496 SendOrSaveCallback callback, ReplyFromAccount currReplyFromAccount,
2497 ReplyFromAccount originalReplyFromAccount) {
2498 long messageId = callback.getMessageId();
Jin Caoaff451f2014-09-09 14:32:04 -07002499 // If a previous draft has been saved, in an account that is different
2500 // than what the user wants to send from, remove the old draft, and treat this
2501 // as a new message
Jin Cao31bb3d62014-09-11 14:01:43 -07002502 if (originalReplyFromAccount != null
2503 && !currReplyFromAccount.account.uri.equals(originalReplyFromAccount.account.uri)) {
Jin Caoaff451f2014-09-09 14:32:04 -07002504 if (messageId != UIProvider.INVALID_MESSAGE_ID) {
2505 ContentResolver resolver = getContentResolver();
2506 ContentValues values = new ContentValues();
2507 values.put(BaseColumns._ID, messageId);
Jin Cao31bb3d62014-09-11 14:01:43 -07002508 if (originalReplyFromAccount.account.expungeMessageUri != null) {
Jin Caoaff451f2014-09-09 14:32:04 -07002509 new ContentProviderTask.UpdateTask()
Jin Cao31bb3d62014-09-11 14:01:43 -07002510 .run(resolver, originalReplyFromAccount.account.expungeMessageUri,
Jin Caoaff451f2014-09-09 14:32:04 -07002511 values, null, null);
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002512 } else {
Jin Caoaff451f2014-09-09 14:32:04 -07002513 // TODO(mindyp) delete the conversation.
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002514 }
Jin Caoaff451f2014-09-09 14:32:04 -07002515 // reset messageId to 0, so a new message will be created
2516 messageId = UIProvider.INVALID_MESSAGE_ID;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002517 }
2518 }
2519
Jin Caoaff451f2014-09-09 14:32:04 -07002520 final long messageIdToSave = messageId;
Jin Cao31bb3d62014-09-11 14:01:43 -07002521 sendOrSaveMessage(callback, messageIdToSave, sendOrSaveMessage, currReplyFromAccount);
Jin Caoaff451f2014-09-09 14:32:04 -07002522
2523 if (!sendOrSaveMessage.mSave) {
2524 incrementRecipientsTimesContacted(
2525 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.TO),
2526 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.CC),
2527 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.BCC));
2528 }
2529 callback.sendOrSaveFinished(sendOrSaveMessage, true);
2530 }
2531
2532 private void incrementRecipientsTimesContacted(
2533 final String toAddresses, final String ccAddresses, final String bccAddresses) {
2534 final List<String> recipients = Lists.newArrayList();
2535 addAddressesToRecipientList(recipients, toAddresses);
2536 addAddressesToRecipientList(recipients, ccAddresses);
2537 addAddressesToRecipientList(recipients, bccAddresses);
2538 incrementRecipientsTimesContacted(recipients);
2539 }
2540
2541 private void addAddressesToRecipientList(
2542 final List<String> recipients, final String addressString) {
2543 if (recipients == null) {
2544 throw new IllegalArgumentException("recipientList cannot be null");
2545 }
2546 if (TextUtils.isEmpty(addressString)) {
2547 return;
2548 }
2549 final Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(addressString);
2550 for (final Rfc822Token token : tokens) {
2551 recipients.add(token.getAddress());
2552 }
2553 }
2554
2555 /**
2556 * Send or Save a message.
2557 */
2558 private void sendOrSaveMessage(SendOrSaveCallback callback, final long messageIdToSave,
2559 final SendOrSaveMessage sendOrSaveMessage, final ReplyFromAccount selectedAccount) {
2560 final ContentResolver resolver = getContentResolver();
2561 final boolean updateExistingMessage = messageIdToSave != UIProvider.INVALID_MESSAGE_ID;
2562
2563 final String accountMethod = sendOrSaveMessage.mSave ?
2564 UIProvider.AccountCallMethods.SAVE_MESSAGE :
2565 UIProvider.AccountCallMethods.SEND_MESSAGE;
2566
2567 try {
2568 if (updateExistingMessage) {
2569 sendOrSaveMessage.mValues.put(BaseColumns._ID, messageIdToSave);
2570
2571 callAccountSendSaveMethod(resolver,
2572 selectedAccount.account, accountMethod, sendOrSaveMessage);
2573 } else {
2574 Uri messageUri = null;
2575 final Bundle result = callAccountSendSaveMethod(resolver,
2576 selectedAccount.account, accountMethod, sendOrSaveMessage);
2577 if (result != null) {
2578 // If a non-null value was returned, then the provider handled the call
2579 // method
2580 messageUri = result.getParcelable(UIProvider.MessageColumns.URI);
2581 }
2582 if (sendOrSaveMessage.mSave && messageUri != null) {
2583 final Cursor messageCursor = resolver.query(messageUri,
2584 UIProvider.MESSAGE_PROJECTION, null, null, null);
2585 if (messageCursor != null) {
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002586 try {
Jin Caoaff451f2014-09-09 14:32:04 -07002587 if (messageCursor.moveToFirst()) {
2588 // Broadcast notification that a new message has
2589 // been allocated
2590 callback.notifyMessageIdAllocated(sendOrSaveMessage,
2591 new Message(messageCursor));
2592 }
2593 } finally {
2594 messageCursor.close();
Paul Westbrookba558482012-03-19 11:00:24 -07002595 }
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002596 }
2597 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002598 }
Jin Caoaff451f2014-09-09 14:32:04 -07002599 } finally {
2600 // Close any opened file descriptors
2601 closeOpenedAttachmentFds(sendOrSaveMessage);
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002602 }
Jin Caoaff451f2014-09-09 14:32:04 -07002603 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002604
Jin Caoaff451f2014-09-09 14:32:04 -07002605 private static void closeOpenedAttachmentFds(final SendOrSaveMessage sendOrSaveMessage) {
2606 final Bundle openedFds = sendOrSaveMessage.attachmentFds();
2607 if (openedFds != null) {
2608 final Set<String> keys = openedFds.keySet();
2609 for (final String key : keys) {
2610 final ParcelFileDescriptor fd = openedFds.getParcelable(key);
2611 if (fd != null) {
2612 try {
2613 fd.close();
2614 } catch (IOException e) {
2615 // Do nothing
2616 }
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002617 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002618 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002619 }
2620 }
2621
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07002622 /**
Jin Caoaff451f2014-09-09 14:32:04 -07002623 * Use the {@link ContentResolver#call} method to send or save the message.
2624 *
2625 * If this was successful, this method will return an non-null Bundle instance
2626 */
2627 private static Bundle callAccountSendSaveMethod(final ContentResolver resolver,
2628 final Account account, final String method,
2629 final SendOrSaveMessage sendOrSaveMessage) {
2630 // Copy all of the values from the content values to the bundle
2631 final Bundle methodExtras = new Bundle(sendOrSaveMessage.mValues.size());
2632 final Set<Entry<String, Object>> valueSet = sendOrSaveMessage.mValues.valueSet();
2633
2634 for (Entry<String, Object> entry : valueSet) {
2635 final Object entryValue = entry.getValue();
2636 final String key = entry.getKey();
2637 if (entryValue instanceof String) {
2638 methodExtras.putString(key, (String)entryValue);
2639 } else if (entryValue instanceof Boolean) {
2640 methodExtras.putBoolean(key, (Boolean)entryValue);
2641 } else if (entryValue instanceof Integer) {
2642 methodExtras.putInt(key, (Integer)entryValue);
2643 } else if (entryValue instanceof Long) {
2644 methodExtras.putLong(key, (Long)entryValue);
2645 } else {
2646 LogUtils.wtf(LOG_TAG, "Unexpected object type: %s",
2647 entryValue.getClass().getName());
2648 }
2649 }
2650
2651 // If the SendOrSaveMessage has some opened fds, add them to the bundle
2652 final Bundle fdMap = sendOrSaveMessage.attachmentFds();
2653 if (fdMap != null) {
2654 methodExtras.putParcelable(
2655 UIProvider.SendOrSaveMethodParamKeys.OPENED_FD_MAP, fdMap);
2656 }
2657
2658 return resolver.call(account.uri, method, account.uri.toString(), methodExtras);
2659 }
2660
2661 /**
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07002662 * Reports recipients that have been contacted in order to improve auto-complete
2663 * suggestions. Default behavior updates usage statistics in ContactsProvider.
2664 * @param recipients addresses
2665 */
2666 protected void incrementRecipientsTimesContacted(List<String> recipients) {
2667 final DataUsageStatUpdater statsUpdater = new DataUsageStatUpdater(this);
2668 statsUpdater.updateWithAddress(recipients);
2669 }
2670
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002671 @VisibleForTesting
2672 public static class SendOrSaveMessage {
Jin Cao31bb3d62014-09-11 14:01:43 -07002673 final int mRequestId;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002674 final ContentValues mValues;
Mindy Pereira3ce64e72012-01-13 14:29:45 -08002675 final String mRefMessageId;
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002676 @VisibleForTesting
2677 public final boolean mSave;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002678 private final Bundle mAttachmentFds;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002679
Jin Cao31bb3d62014-09-11 14:01:43 -07002680 public SendOrSaveMessage(Context context, int requestId, ContentValues values,
Jin Caoadae7a32014-09-09 18:16:25 -07002681 String refMessageId, List<Attachment> attachments, Bundle optionalAttachmentFds,
2682 boolean save) {
Jin Cao31bb3d62014-09-11 14:01:43 -07002683 mRequestId = requestId;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002684 mValues = values;
2685 mRefMessageId = refMessageId;
2686 mSave = save;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002687
Jin Caoadae7a32014-09-09 18:16:25 -07002688 // If the attachments are already open for us (pre-JB), then don't open them again
2689 if (optionalAttachmentFds != null) {
2690 mAttachmentFds = optionalAttachmentFds;
2691 } else {
2692 mAttachmentFds = initializeAttachmentFds(context, attachments);
2693 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002694 }
2695
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002696 Bundle attachmentFds() {
2697 return mAttachmentFds;
2698 }
Jin Caoadae7a32014-09-09 18:16:25 -07002699 }
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002700
Jin Caoadae7a32014-09-09 18:16:25 -07002701 /**
2702 * Opens {@link ParcelFileDescriptor} for each of the attachments. This method must be
2703 * called before the ComposeActivity finishes.
2704 * Note: The caller is responsible for closing these file descriptors.
2705 */
2706 private static Bundle initializeAttachmentFds(final Context context,
2707 final List<Attachment> attachments) {
2708 if (attachments == null || attachments.size() == 0) {
2709 return null;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002710 }
Jin Caoadae7a32014-09-09 18:16:25 -07002711
2712 final Bundle result = new Bundle(attachments.size());
2713 final ContentResolver resolver = context.getContentResolver();
2714
2715 for (Attachment attachment : attachments) {
2716 if (attachment == null || Utils.isEmpty(attachment.contentUri)) {
2717 continue;
2718 }
2719
2720 ParcelFileDescriptor fileDescriptor;
2721 try {
2722 fileDescriptor = resolver.openFileDescriptor(attachment.contentUri, "r");
2723 } catch (FileNotFoundException e) {
2724 LogUtils.e(LOG_TAG, e, "Exception attempting to open attachment");
2725 fileDescriptor = null;
2726 } catch (SecurityException e) {
2727 // We have encountered a security exception when attempting to open the file
2728 // specified by the content uri. If the attachment has been cached, this
2729 // isn't a problem, as even through the original permission may have been
2730 // revoked, we have cached the file. This will happen when saving/sending
2731 // a previously saved draft.
2732 // TODO(markwei): Expose whether the attachment has been cached through the
2733 // attachment object. This would allow us to limit when the log is made, as
2734 // if the attachment has been cached, this really isn't an error
2735 LogUtils.e(LOG_TAG, e, "Security Exception attempting to open attachment");
2736 // Just set the file descriptor to null, as the underlying provider needs
2737 // to handle the file descriptor not being set.
2738 fileDescriptor = null;
2739 }
2740
2741 if (fileDescriptor != null) {
2742 result.putParcelable(attachment.contentUri.toString(), fileDescriptor);
2743 }
2744 }
2745
2746 return result;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002747 }
2748
2749 /**
2750 * Get the to recipients.
2751 */
2752 public String[] getToAddresses() {
2753 return getAddressesFromList(mTo);
2754 }
2755
2756 /**
2757 * Get the cc recipients.
2758 */
2759 public String[] getCcAddresses() {
2760 return getAddressesFromList(mCc);
2761 }
2762
2763 /**
2764 * Get the bcc recipients.
2765 */
2766 public String[] getBccAddresses() {
2767 return getAddressesFromList(mBcc);
2768 }
2769
2770 public String[] getAddressesFromList(RecipientEditTextView list) {
2771 if (list == null) {
2772 return new String[0];
2773 }
2774 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(list.getText());
2775 int count = tokens.length;
2776 String[] result = new String[count];
2777 for (int i = 0; i < count; i++) {
2778 result[i] = tokens[i].toString();
2779 }
2780 return result;
2781 }
2782
2783 /**
2784 * Check for invalid email addresses.
2785 * @param to String array of email addresses to check.
2786 * @param wrongEmailsOut Emails addresses that were invalid.
2787 */
Scott Kennedyff8553f2013-04-05 20:57:44 -07002788 public void checkInvalidEmails(final String[] to, final List<String> wrongEmailsOut) {
Mindy Pereirae5f20bf2012-06-25 14:20:40 -07002789 if (mValidator == null) {
2790 return;
2791 }
Scott Kennedyff8553f2013-04-05 20:57:44 -07002792 for (final String email : to) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002793 if (!mValidator.isValid(email)) {
2794 wrongEmailsOut.add(email);
2795 }
2796 }
2797 }
2798
Tony Mantler2558b502013-07-09 10:53:34 -07002799 public static class RecipientErrorDialogFragment extends DialogFragment {
Paul Westbrookf0ea4842013-08-13 16:41:18 -07002800 // Public no-args constructor needed for fragment re-instantiation
2801 public RecipientErrorDialogFragment() {}
2802
Tony Mantler2558b502013-07-09 10:53:34 -07002803 public static RecipientErrorDialogFragment newInstance(final String message) {
2804 final RecipientErrorDialogFragment frag = new RecipientErrorDialogFragment();
2805 final Bundle args = new Bundle(1);
2806 args.putString("message", message);
2807 frag.setArguments(args);
2808 return frag;
2809 }
2810
2811 @Override
2812 public Dialog onCreateDialog(Bundle savedInstanceState) {
2813 final String message = getArguments().getString("message");
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07002814 return new AlertDialog.Builder(getActivity())
2815 .setMessage(message)
Tony Mantler2558b502013-07-09 10:53:34 -07002816 .setPositiveButton(
2817 R.string.ok, new Dialog.OnClickListener() {
2818 @Override
2819 public void onClick(DialogInterface dialog, int which) {
2820 ((ComposeActivity)getActivity()).finishRecipientErrorDialog();
2821 }
2822 }).create();
2823 }
2824 }
2825
2826 private void finishRecipientErrorDialog() {
2827 // after the user dismisses the recipient error
2828 // dialog we want to make sure to refocus the
2829 // recipient to field so they can fix the issue
2830 // easily
2831 if (mTo != null) {
2832 mTo.requestFocus();
2833 }
2834 }
2835
Mindy Pereira82cc5662012-01-09 17:29:30 -08002836 /**
2837 * Show an error because the user has entered an invalid recipient.
Mindy Pereira82cc5662012-01-09 17:29:30 -08002838 */
Tony Mantler2558b502013-07-09 10:53:34 -07002839 private void showRecipientErrorDialog(final String message) {
2840 final DialogFragment frag = RecipientErrorDialogFragment.newInstance(message);
2841 frag.show(getFragmentManager(), "recipient error");
Mindy Pereira82cc5662012-01-09 17:29:30 -08002842 }
2843
2844 /**
2845 * Update the state of the UI based on whether or not the current draft
2846 * needs to be saved and the message is not empty.
2847 */
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002848 public void updateSaveUi() {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002849 if (mSave != null) {
Jin Caoe0037922014-09-16 10:23:50 -07002850 mSave.setEnabled((isDraftDirty() && !isBlank()));
Mindy Pereira82cc5662012-01-09 17:29:30 -08002851 }
2852 }
2853
2854 /**
Jin Caoe0037922014-09-16 10:23:50 -07002855 * Returns true if the current draft is modified from the version we previously saved.
Mindy Pereira82cc5662012-01-09 17:29:30 -08002856 */
Jin Caoe0037922014-09-16 10:23:50 -07002857 private boolean isDraftDirty() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002858 synchronized (mDraftLock) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002859 // The message should only be saved if:
2860 // It hasn't been sent AND
2861 // Some text has been added to the message OR
2862 // an attachment has been added or removed
Mindy Pereiraa2148332012-07-02 13:54:14 -07002863 // AND there is actually something in the draft to save.
Andy Huangd47877e2012-08-09 19:31:24 -07002864 return (mTextChanged || mAttachmentsChanged || mReplyFromChanged)
Mindy Pereiraa2148332012-07-02 13:54:14 -07002865 && !isBlank();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002866 }
2867 }
2868
2869 /**
Greg Bullockd47a7042014-08-13 16:02:59 +02002870 * Returns whether the "Attach from Drive" menu item should be visible.
2871 */
2872 protected boolean shouldEnableAttachFromServiceMenu(Account mAccount) {
2873 return false;
2874 }
2875
2876 /**
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002877 * Check if all fields are blank.
Mindy Pereira82cc5662012-01-09 17:29:30 -08002878 * @return boolean
2879 */
2880 public boolean isBlank() {
Alice Yanga49b6842013-08-23 10:36:18 -07002881 // Need to check for null since isBlank() can be called from onPause()
2882 // before findViews() is called
2883 if (mSubject == null || mBodyView == null || mTo == null || mCc == null ||
2884 mAttachmentsView == null) {
2885 LogUtils.w(LOG_TAG, "null views in isBlank check");
2886 return true;
2887 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002888 return mSubject.getText().length() == 0
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002889 && (mBodyView.getText().length() == 0 || getSignatureStartPosition(mSignature,
2890 mBodyView.getText().toString()) == 0)
2891 && mTo.length() == 0
2892 && mCc.length() == 0 && mBcc.length() == 0
2893 && mAttachmentsView.getAttachments().size() == 0;
2894 }
2895
2896 @VisibleForTesting
2897 protected int getSignatureStartPosition(String signature, String bodyText) {
2898 int startPos = -1;
2899
2900 if (TextUtils.isEmpty(signature) || TextUtils.isEmpty(bodyText)) {
2901 return startPos;
2902 }
2903
2904 int bodyLength = bodyText.length();
2905 int signatureLength = signature.length();
2906 String printableVersion = convertToPrintableSignature(signature);
2907 int printableLength = printableVersion.length();
2908
2909 if (bodyLength >= printableLength
2910 && bodyText.substring(bodyLength - printableLength)
2911 .equals(printableVersion)) {
2912 startPos = bodyLength - printableLength;
2913 } else if (bodyLength >= signatureLength
2914 && bodyText.substring(bodyLength - signatureLength)
2915 .equals(signature)) {
2916 startPos = bodyLength - signatureLength;
2917 }
2918 return startPos;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002919 }
2920
2921 /**
2922 * Allows any changes made by the user to be ignored. Called when the user
2923 * decides to discard a draft.
2924 */
2925 private void discardChanges() {
2926 mTextChanged = false;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002927 mAttachmentsChanged = false;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002928 mReplyFromChanged = false;
2929 }
2930
2931 /**
Tony Mantler581edd42014-02-18 15:41:22 -08002932 * @param save True to save, false to send
2933 * @param showToast True to show a toast once the message is sent/saved
Mindy Pereira181df782012-03-01 13:32:44 -08002934 */
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002935 protected void sendOrSaveWithSanityChecks(final boolean save, final boolean showToast,
Mark Weidd19b632012-10-19 13:59:28 -07002936 final boolean orientationChanged, final boolean autoSend) {
Mark Wei009b3712012-10-18 18:07:50 -07002937 if (mAccounts == null || mAccount == null) {
2938 Toast.makeText(this, R.string.send_failed, Toast.LENGTH_SHORT).show();
Mark Weidd19b632012-10-19 13:59:28 -07002939 if (autoSend) {
2940 finish();
2941 }
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002942 return;
Mark Wei009b3712012-10-18 18:07:50 -07002943 }
2944
Scott Kennedyff8553f2013-04-05 20:57:44 -07002945 final String[] to, cc, bcc;
Mindy Pereira181df782012-03-01 13:32:44 -08002946 if (orientationChanged) {
2947 to = cc = bcc = new String[0];
2948 } else {
2949 to = getToAddresses();
2950 cc = getCcAddresses();
2951 bcc = getBccAddresses();
2952 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002953
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002954 final ArrayList<String> recipients = buildEmailAddressList(to);
2955 recipients.addAll(buildEmailAddressList(cc));
2956 recipients.addAll(buildEmailAddressList(bcc));
2957
Mindy Pereira181df782012-03-01 13:32:44 -08002958 // Don't let the user send to nobody (but it's okay to save a message
2959 // with no recipients)
2960 if (!save && (to.length == 0 && cc.length == 0 && bcc.length == 0)) {
2961 showRecipientErrorDialog(getString(R.string.recipient_needed));
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002962 return;
Mindy Pereira181df782012-03-01 13:32:44 -08002963 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002964
Mindy Pereira181df782012-03-01 13:32:44 -08002965 List<String> wrongEmails = new ArrayList<String>();
2966 if (!save) {
2967 checkInvalidEmails(to, wrongEmails);
2968 checkInvalidEmails(cc, wrongEmails);
2969 checkInvalidEmails(bcc, wrongEmails);
2970 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002971
Mindy Pereira181df782012-03-01 13:32:44 -08002972 // Don't let the user send an email with invalid recipients
2973 if (wrongEmails.size() > 0) {
2974 String errorText = String.format(getString(R.string.invalid_recipient),
2975 wrongEmails.get(0));
2976 showRecipientErrorDialog(errorText);
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002977 return;
Mindy Pereira181df782012-03-01 13:32:44 -08002978 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002979
Mindy Pereira181df782012-03-01 13:32:44 -08002980 if (!save) {
Alan Lau3d519042014-06-05 11:13:06 -07002981 if (autoSend) {
2982 // Skip all further checks during autosend. This flow is used by Android Wear
2983 // and Google Now.
2984 sendOrSave(save, showToast);
2985 return;
2986 }
2987
2988 // Show a warning before sending only if there are no attachments, body, or subject.
Mindy Pereira181df782012-03-01 13:32:44 -08002989 if (mAttachmentsView.getAttachments().isEmpty() && showEmptyTextWarnings()) {
2990 boolean warnAboutEmptySubject = isSubjectEmpty();
Tony Mantler2558b502013-07-09 10:53:34 -07002991 boolean emptyBody = TextUtils.getTrimmedLength(mBodyView.getEditableText()) == 0;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002992
Mindy Pereira181df782012-03-01 13:32:44 -08002993 // A warning about an empty body may not be warranted when
2994 // forwarding mails, since a common use case is to forward
2995 // quoted text and not append any more text.
2996 boolean warnAboutEmptyBody = emptyBody && (!mForward || isBodyEmpty());
Mindy Pereira82cc5662012-01-09 17:29:30 -08002997
Mindy Pereira181df782012-03-01 13:32:44 -08002998 // When we bring up a dialog warning the user about a send,
2999 // assume that they accept sending the message. If they do not,
3000 // the dialog listener is required to enable sending again.
3001 if (warnAboutEmptySubject) {
Tony Mantler581edd42014-02-18 15:41:22 -08003002 showSendConfirmDialog(R.string.confirm_send_message_with_no_subject,
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003003 showToast, recipients);
3004 return;
Mindy Pereira181df782012-03-01 13:32:44 -08003005 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003006
Mindy Pereira181df782012-03-01 13:32:44 -08003007 if (warnAboutEmptyBody) {
Tony Mantler581edd42014-02-18 15:41:22 -08003008 showSendConfirmDialog(R.string.confirm_send_message_with_no_body,
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003009 showToast, recipients);
3010 return;
Mindy Pereira181df782012-03-01 13:32:44 -08003011 }
3012 }
Alan Lau3d519042014-06-05 11:13:06 -07003013 // Ask for confirmation to send.
3014 if (showSendConfirmation()) {
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003015 showSendConfirmDialog(R.string.confirm_send_message, showToast, recipients);
3016 return;
Mindy Pereira181df782012-03-01 13:32:44 -08003017 }
3018 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003019
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003020 performAdditionalSendOrSaveSanityChecks(save, showToast, recipients);
Mindy Pereira181df782012-03-01 13:32:44 -08003021 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003022
Mindy Pereira181df782012-03-01 13:32:44 -08003023 /**
3024 * Returns a boolean indicating whether warnings should be shown for empty
3025 * subject and body fields
Andy Huang5c5fd572012-04-08 18:19:29 -07003026 *
Mindy Pereira181df782012-03-01 13:32:44 -08003027 * @return True if a warning should be shown for empty text fields
3028 */
3029 protected boolean showEmptyTextWarnings() {
3030 return mAttachmentsView.getAttachments().size() == 0;
3031 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003032
Mindy Pereira181df782012-03-01 13:32:44 -08003033 /**
3034 * Returns a boolean indicating whether the user should confirm each send
3035 *
3036 * @return True if a warning should be on each send
3037 */
3038 protected boolean showSendConfirmation() {
Tony Mantler581edd42014-02-18 15:41:22 -08003039 return mCachedSettings != null && mCachedSettings.confirmSend;
Mindy Pereira181df782012-03-01 13:32:44 -08003040 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003041
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07003042 public static class SendConfirmDialogFragment extends DialogFragment
3043 implements DialogInterface.OnClickListener {
3044
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003045 private static final String MESSAGE_ID = "messageId";
3046 private static final String SHOW_TOAST = "showToast";
3047 private static final String RECIPIENTS = "recipients";
3048
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07003049 private boolean mShowToast;
3050
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003051 private ArrayList<String> mRecipients;
3052
Paul Westbrookf0ea4842013-08-13 16:41:18 -07003053 // Public no-args constructor needed for fragment re-instantiation
3054 public SendConfirmDialogFragment() {}
3055
Tony Mantler2558b502013-07-09 10:53:34 -07003056 public static SendConfirmDialogFragment newInstance(final int messageId,
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003057 final boolean showToast, final ArrayList<String> recipients) {
Tony Mantler2558b502013-07-09 10:53:34 -07003058 final SendConfirmDialogFragment frag = new SendConfirmDialogFragment();
3059 final Bundle args = new Bundle(3);
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003060 args.putInt(MESSAGE_ID, messageId);
3061 args.putBoolean(SHOW_TOAST, showToast);
3062 args.putStringArrayList(RECIPIENTS, recipients);
Tony Mantler2558b502013-07-09 10:53:34 -07003063 frag.setArguments(args);
3064 return frag;
Mindy Pereira181df782012-03-01 13:32:44 -08003065 }
Tony Mantler2558b502013-07-09 10:53:34 -07003066
3067 @Override
3068 public Dialog onCreateDialog(Bundle savedInstanceState) {
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003069 final int messageId = getArguments().getInt(MESSAGE_ID);
3070 mShowToast = getArguments().getBoolean(SHOW_TOAST);
3071 mRecipients = getArguments().getStringArrayList(RECIPIENTS);
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07003072
3073 final int confirmTextId = (messageId == R.string.confirm_send_message) ?
3074 R.string.ok : R.string.send;
Tony Mantler2558b502013-07-09 10:53:34 -07003075
3076 return new AlertDialog.Builder(getActivity())
3077 .setMessage(messageId)
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07003078 .setPositiveButton(confirmTextId, this)
Paul Westbrook7d1c5c42013-10-01 23:40:04 -07003079 .setNegativeButton(R.string.cancel, null)
Tony Mantler2558b502013-07-09 10:53:34 -07003080 .create();
3081 }
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07003082
3083 @Override
3084 public void onClick(DialogInterface dialog, int which) {
3085 if (which == DialogInterface.BUTTON_POSITIVE) {
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003086 ((ComposeActivity) getActivity()).finishSendConfirmDialog(mShowToast, mRecipients);
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07003087 }
3088 }
Tony Mantler2558b502013-07-09 10:53:34 -07003089 }
3090
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003091 private void finishSendConfirmDialog(
3092 final boolean showToast, final ArrayList<String> recipients) {
3093 performAdditionalSendOrSaveSanityChecks(false /* save */, showToast, recipients);
Tony Mantler2558b502013-07-09 10:53:34 -07003094 }
3095
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003096 // The list of recipients are used by the additional sendOrSave checks.
3097 // However, the send confirm dialog may be shown before performing
3098 // the additional checks. As a result, we need to plumb the recipient
3099 // list through the send confirm dialog so that
3100 // performAdditionalSendOrSaveChecks can be performed properly.
Tony Mantler581edd42014-02-18 15:41:22 -08003101 private void showSendConfirmDialog(final int messageId,
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003102 final boolean showToast, final ArrayList<String> recipients) {
3103 final DialogFragment frag = SendConfirmDialogFragment.newInstance(
3104 messageId, showToast, recipients);
Tony Mantler2558b502013-07-09 10:53:34 -07003105 frag.show(getFragmentManager(), "send confirm");
Mindy Pereira181df782012-03-01 13:32:44 -08003106 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003107
Mindy Pereira181df782012-03-01 13:32:44 -08003108 /**
3109 * Returns whether the ComposeArea believes there is any text in the body of
3110 * the composition. TODO: When ComposeArea controls the Body as well, add
3111 * that here.
3112 */
3113 public boolean isBodyEmpty() {
3114 return !mQuotedTextView.isTextIncluded();
3115 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003116
Mindy Pereira181df782012-03-01 13:32:44 -08003117 /**
3118 * Test to see if the subject is empty.
3119 *
3120 * @return boolean.
3121 */
3122 // TODO: this will likely go away when composeArea.focus() is implemented
3123 // after all the widget control is moved over.
3124 public boolean isSubjectEmpty() {
3125 return TextUtils.getTrimmedLength(mSubject.getText()) == 0;
3126 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003127
Andy Huang0a2a3462013-12-20 15:56:13 -08003128 @VisibleForTesting
3129 public String getSubject() {
3130 return mSubject.getText().toString();
3131 }
3132
Jin Cao31bb3d62014-09-11 14:01:43 -07003133 private void sendOrSaveInternal(Context context, int requestId,
3134 ReplyFromAccount currReplyFromAccount, ReplyFromAccount originalReplyFromAccount,
3135 Message message, Message refMessage, CharSequence quotedText,
3136 SendOrSaveCallback callback, boolean save, int composeMode, ContentValues extraValues,
Jin Caoadae7a32014-09-09 18:16:25 -07003137 Bundle optionalAttachmentFds) {
Paul Westbrookb4931c62013-01-14 17:51:18 -08003138 final ContentValues values = new ContentValues();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003139
Paul Westbrookb4931c62013-01-14 17:51:18 -08003140 final String refMessageId = refMessage != null ? refMessage.uri.toString() : "";
Mindy Pereirac2031972012-04-03 09:38:35 -07003141
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07003142 MessageModification.putToAddresses(values, message.getToAddresses());
3143 MessageModification.putCcAddresses(values, message.getCcAddresses());
3144 MessageModification.putBccAddresses(values, message.getBccAddresses());
Scott Kennedy8960f0a2012-11-07 15:35:50 -08003145 MessageModification.putCustomFromAddress(values, message.getFrom());
Mindy Pereira92551d02012-04-05 11:31:12 -07003146
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07003147 MessageModification.putSubject(values, message.subject);
Anthony Lee2a3cc132014-04-22 14:15:25 -07003148
Jin Cao77b4c2c2014-05-20 13:55:53 -07003149 // bodyHtml already have the composing spans removed.
3150 final String htmlBody = message.bodyHtml;
Jin Caoa9f5a8e2014-07-22 13:48:45 -07003151 final String textBody = message.bodyText;
Jin Cao0a8e8222014-10-02 11:27:52 -07003152 // fullbodyhtml/fullbodytext will contain the actual body plus the quoted text.
3153 String fullBodyHtml = htmlBody;
3154 String fullBodyText = textBody;
3155 String quotedString = null;
Anthony Lee2a3cc132014-04-22 14:15:25 -07003156 final boolean hasQuotedText = !TextUtils.isEmpty(quotedText);
3157 if (hasQuotedText) {
3158 // The quoted text is HTML at this point.
3159 quotedString = quotedText.toString();
Jin Cao0a8e8222014-10-02 11:27:52 -07003160 fullBodyHtml = htmlBody + quotedString;
3161 fullBodyText = textBody + Utils.convertHtmlToPlainText(quotedString);
Anthony Lee2a3cc132014-04-22 14:15:25 -07003162 MessageModification.putForward(values, composeMode == ComposeActivity.FORWARD);
3163 MessageModification.putAppendRefMessageContent(values, true /* include quoted */);
Mindy Pereira29ef1b82012-01-13 11:26:21 -08003164 }
Jin Cao0a8e8222014-10-02 11:27:52 -07003165
Jin Caoa9f5a8e2014-07-22 13:48:45 -07003166 // Only take refMessage into account if either one of its html/text is not empty.
Jin Cao0a8e8222014-10-02 11:27:52 -07003167 int quotedTextPos = -1;
Jin Caoa9f5a8e2014-07-22 13:48:45 -07003168 if (refMessage != null && !(TextUtils.isEmpty(refMessage.bodyHtml) &&
3169 TextUtils.isEmpty(refMessage.bodyText))) {
Anthony Lee2a3cc132014-04-22 14:15:25 -07003170 // The code below might need to be revisited. The quoted text position is different
3171 // between text/html and text/plain parts and they should be stored seperately and
3172 // the right version should be used in the UI. text/html should have preference
3173 // if both exist. Issues like this made me file b/14256940 to make sure that we
3174 // properly handle the existing of both text/html and text/plain parts and to verify
3175 // that we are not making some assumptions that break if there is no text/html part.
Mindy Pereirac6f1e2a2012-04-04 10:33:45 -07003176 if (!TextUtils.isEmpty(refMessage.bodyHtml)) {
Jin Cao0a8e8222014-10-02 11:27:52 -07003177 MessageModification.putBodyHtml(values, fullBodyHtml);
Anthony Lee2a3cc132014-04-22 14:15:25 -07003178 if (hasQuotedText) {
3179 quotedTextPos = htmlBody.length() +
3180 QuotedTextView.getQuotedTextOffset(quotedString);
3181 }
Mindy Pereirac6f1e2a2012-04-04 10:33:45 -07003182 }
3183 if (!TextUtils.isEmpty(refMessage.bodyText)) {
Jin Cao0a8e8222014-10-02 11:27:52 -07003184 MessageModification.putBody(values, fullBodyText);
Anthony Lee2a3cc132014-04-22 14:15:25 -07003185 if (hasQuotedText && (quotedTextPos == -1)) {
3186 quotedTextPos = textBody.length();
3187 }
3188 }
3189 if (quotedTextPos != -1) {
3190 // The quoted text pos is the text/html version first and the text/plan version
3191 // if there is no text/html part. The reason for this is because preference
3192 // is given to text/html in the compose window if it exists. In the future, we
3193 // should calculate the index for both since the user could choose to compose
3194 // explicitly in text/plain.
3195 MessageModification.putQuoteStartPos(values, quotedTextPos);
Mindy Pereirac6f1e2a2012-04-04 10:33:45 -07003196 }
3197 } else {
Jin Cao0a8e8222014-10-02 11:27:52 -07003198 MessageModification.putBodyHtml(values, fullBodyHtml);
3199 MessageModification.putBody(values, fullBodyText);
Mindy Pereirac2031972012-04-03 09:38:35 -07003200 }
Anthony Lee2a3cc132014-04-22 14:15:25 -07003201 int draftType = getDraftType(composeMode);
3202 MessageModification.putDraftType(values, draftType);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07003203 MessageModification.putAttachments(values, message.getAttachments());
Mindy Pereira12575862012-03-21 16:30:54 -07003204 if (!TextUtils.isEmpty(refMessageId)) {
3205 MessageModification.putRefMessageId(values, refMessageId);
3206 }
Scott Kennedy60847252013-08-15 15:55:42 -07003207 if (extraValues != null) {
3208 values.putAll(extraValues);
3209 }
Jin Caoaff451f2014-09-09 14:32:04 -07003210
Jin Cao31bb3d62014-09-11 14:01:43 -07003211 SendOrSaveMessage sendOrSaveMessage = new SendOrSaveMessage(context, requestId,
Jin Caoadae7a32014-09-09 18:16:25 -07003212 values, refMessageId, message.getAttachments(), optionalAttachmentFds, save);
Jin Cao0a8e8222014-10-02 11:27:52 -07003213 runSendOrSaveProviderCalls(sendOrSaveMessage, callback, currReplyFromAccount,
3214 originalReplyFromAccount);
Mindy Pereira82cc5662012-01-09 17:29:30 -08003215
Jin Cao7800d292014-08-24 11:31:15 -07003216 LogUtils.i(LOG_TAG, "[compose] SendOrSaveMessage [%s] posted (isSave: %s) - " +
Jin Cao0a8e8222014-10-02 11:27:52 -07003217 "bodyHtml length: %d, bodyText length: %d, quoted text pos: %d, attach count: %d",
3218 requestId, save, message.bodyHtml.length(), message.bodyText.length(),
3219 quotedTextPos, message.getAttachmentCount(true));
Mindy Pereira181df782012-03-01 13:32:44 -08003220 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003221
Paul Westbrookb4931c62013-01-14 17:51:18 -08003222 /**
3223 * Removes any composing spans from the specified string. This will create a new
3224 * SpannableString instance, as to not modify the behavior of the EditText view.
3225 */
3226 private static SpannableString removeComposingSpans(Spanned body) {
3227 final SpannableString messageBody = new SpannableString(body);
3228 BaseInputConnection.removeComposingSpans(messageBody);
Andy Huangff017272014-06-18 00:27:35 -07003229
3230 // Remove watcher spans while we're at it, so any off-UI thread manipulation of these
3231 // spans doesn't trigger unexpected side-effects. This copy is essentially 100% detached
3232 // from the EditText.
3233 //
3234 // (must remove SpanWatchers first to avoid triggering them as we remove other spans)
3235 removeSpansOfType(messageBody, SpanWatcher.class);
3236 removeSpansOfType(messageBody, TextWatcher.class);
3237
Paul Westbrookb4931c62013-01-14 17:51:18 -08003238 return messageBody;
3239 }
3240
Andy Huangff017272014-06-18 00:27:35 -07003241 private static void removeSpansOfType(SpannableString str, Class<?> cls) {
3242 for (Object span : str.getSpans(0, str.length(), cls)) {
3243 str.removeSpan(span);
3244 }
3245 }
3246
Mindy Pereira002ff522012-05-30 10:31:26 -07003247 private static int getDraftType(int mode) {
3248 int draftType = -1;
3249 switch (mode) {
3250 case ComposeActivity.COMPOSE:
3251 draftType = DraftType.COMPOSE;
3252 break;
3253 case ComposeActivity.REPLY:
3254 draftType = DraftType.REPLY;
3255 break;
3256 case ComposeActivity.REPLY_ALL:
3257 draftType = DraftType.REPLY_ALL;
3258 break;
3259 case ComposeActivity.FORWARD:
3260 draftType = DraftType.FORWARD;
3261 break;
3262 }
3263 return draftType;
3264 }
3265
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003266 /**
3267 * Derived classes should override this step to perform additional checks before
3268 * send or save. The default implementation simply calls {@link #sendOrSave(boolean, boolean)}.
3269 */
3270 protected void performAdditionalSendOrSaveSanityChecks(
3271 final boolean save, final boolean showToast, ArrayList<String> recipients) {
3272 sendOrSave(save, showToast);
3273 }
3274
3275 protected void sendOrSave(final boolean save, final boolean showToast) {
Mindy Pereira181df782012-03-01 13:32:44 -08003276 // Check if user is a monkey. Monkeys can compose and hit send
3277 // button but are not allowed to send anything off the device.
Paul Westbrook3ae824c2012-04-06 13:29:39 -07003278 if (ActivityManager.isUserAMonkey()) {
Mindy Pereira181df782012-03-01 13:32:44 -08003279 return;
3280 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003281
Jin Cao77b4c2c2014-05-20 13:55:53 -07003282 final SendOrSaveCallback callback = new SendOrSaveCallback() {
Marc Blank0bbc8582012-04-23 15:07:57 -07003283 @Override
Jin Caoaff451f2014-09-09 14:32:04 -07003284 public void initializeSendOrSave() {
Jin Caoadae7a32014-09-09 18:16:25 -07003285 final Intent i = new Intent(ComposeActivity.this, EmptyService.class);
3286
3287 // API 16+ allows for setClipData. For pre-16 we are going to open the fds
3288 // on the main thread.
3289 if (Utils.isRunningJellybeanOrLater()) {
3290 // Grant the READ permission for the attachments to the service so that
3291 // as long as the service stays alive we won't hit PermissionExceptions.
3292 final ClipDescription desc = new ClipDescription("attachment_uris",
3293 new String[]{ClipDescription.MIMETYPE_TEXT_URILIST});
3294 ClipData clipData = null;
3295 for (Attachment a : mAttachmentsView.getAttachments()) {
3296 if (a != null && !Utils.isEmpty(a.contentUri)) {
3297 final ClipData.Item uriItem = new ClipData.Item(a.contentUri);
3298 if (clipData == null) {
3299 clipData = new ClipData(desc, uriItem);
3300 } else {
3301 clipData.addItem(uriItem);
3302 }
3303 }
3304 }
3305 i.setClipData(clipData);
3306 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
3307 }
3308
Jin Caoaff451f2014-09-09 14:32:04 -07003309 synchronized (PENDING_SEND_OR_SAVE_TASKS_NUM) {
3310 if (PENDING_SEND_OR_SAVE_TASKS_NUM.getAndAdd(1) == 0) {
Mindy Pereira181df782012-03-01 13:32:44 -08003311 // Start service so we won't be killed if this app is
3312 // put in the background.
Jin Caoadae7a32014-09-09 18:16:25 -07003313 startService(i);
Mindy Pereira181df782012-03-01 13:32:44 -08003314 }
Mindy Pereira181df782012-03-01 13:32:44 -08003315 }
3316 if (sTestSendOrSaveCallback != null) {
Jin Caoaff451f2014-09-09 14:32:04 -07003317 sTestSendOrSaveCallback.initializeSendOrSave();
Mindy Pereira181df782012-03-01 13:32:44 -08003318 }
3319 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003320
Marc Blank0bbc8582012-04-23 15:07:57 -07003321 @Override
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003322 public void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage,
3323 Message message) {
Mindy Pereira181df782012-03-01 13:32:44 -08003324 synchronized (mDraftLock) {
3325 mDraftId = message.id;
3326 mDraft = message;
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003327 if (sRequestMessageIdMap != null) {
Jin Cao31bb3d62014-09-11 14:01:43 -07003328 sRequestMessageIdMap.put(sendOrSaveMessage.mRequestId, mDraftId);
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003329 }
Mindy Pereira181df782012-03-01 13:32:44 -08003330 // Cache request message map, in case the process is killed
3331 saveRequestMap();
3332 }
3333 if (sTestSendOrSaveCallback != null) {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003334 sTestSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage, message);
Mindy Pereira181df782012-03-01 13:32:44 -08003335 }
3336 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003337
Marc Blank0bbc8582012-04-23 15:07:57 -07003338 @Override
Jin Cao31bb3d62014-09-11 14:01:43 -07003339 public long getMessageId() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003340 synchronized (mDraftLock) {
Jin Cao31bb3d62014-09-11 14:01:43 -07003341 return mDraftId;
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003342 }
3343 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003344
Marc Blank0bbc8582012-04-23 15:07:57 -07003345 @Override
Jin Caoaff451f2014-09-09 14:32:04 -07003346 public void sendOrSaveFinished(SendOrSaveMessage message, boolean success) {
Mindy Pereira47d0e652012-07-23 09:45:07 -07003347 // Update the last sent from account.
3348 if (mAccount != null) {
3349 MailAppProvider.getInstance().setLastSentFromAccount(mAccount.uri.toString());
3350 }
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003351 if (success) {
3352 // Successfully sent or saved so reset change markers
3353 discardChanges();
3354 } else {
3355 // A failure happened with saving/sending the draft
3356 // TODO(pwestbro): add a better string that should be used
3357 // when failing to send or save
3358 Toast.makeText(ComposeActivity.this, R.string.send_failed, Toast.LENGTH_SHORT)
3359 .show();
3360 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003361
Jin Caoaff451f2014-09-09 14:32:04 -07003362 synchronized (PENDING_SEND_OR_SAVE_TASKS_NUM) {
3363 if (PENDING_SEND_OR_SAVE_TASKS_NUM.addAndGet(-1) == 0) {
3364 // Stop service so we can be killed.
3365 stopService(new Intent(ComposeActivity.this, EmptyService.class));
3366 }
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003367 }
3368 if (sTestSendOrSaveCallback != null) {
Jin Caoaff451f2014-09-09 14:32:04 -07003369 sTestSendOrSaveCallback.sendOrSaveFinished(message, success);
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003370 }
3371 }
Mindy Pereira181df782012-03-01 13:32:44 -08003372 };
Tony Mantler1e05a1e2013-08-12 16:44:26 -07003373 setAccount(mReplyFromAccount.account);
Mindy Pereira82cc5662012-01-09 17:29:30 -08003374
Jin Cao77b4c2c2014-05-20 13:55:53 -07003375 final Spanned body = removeComposingSpans(mBodyView.getText());
Jin Caoadae7a32014-09-09 18:16:25 -07003376 callback.initializeSendOrSave();
3377
3378 // For pre-JB we need to open the fds on the main thread
3379 final Bundle attachmentFds;
3380 if (!Utils.isRunningJellybeanOrLater()) {
3381 attachmentFds = initializeAttachmentFds(this, mAttachmentsView.getAttachments());
3382 } else {
3383 attachmentFds = null;
3384 }
3385
Jin Cao31bb3d62014-09-11 14:01:43 -07003386 // Generate a unique message id for this request
3387 mRequestId = sRandom.nextInt();
Jin Cao77b4c2c2014-05-20 13:55:53 -07003388 SEND_SAVE_TASK_HANDLER.post(new Runnable() {
3389 @Override
3390 public void run() {
3391 final Message msg = createMessage(mReplyFromAccount, mRefMessage, getMode(), body);
Jin Cao31bb3d62014-09-11 14:01:43 -07003392 sendOrSaveInternal(ComposeActivity.this, mRequestId, mReplyFromAccount,
3393 mDraftAccount, msg, mRefMessage, mQuotedTextView.getQuotedTextIfIncluded(),
3394 callback, save, mComposeMode, mExtraValues, attachmentFds);
Jin Cao77b4c2c2014-05-20 13:55:53 -07003395 }
3396 });
Mindy Pereira82cc5662012-01-09 17:29:30 -08003397
Mindy Pereira181df782012-03-01 13:32:44 -08003398 // Don't display the toast if the user is just changing the orientation,
3399 // but we still need to save the draft to the cursor because this is how we restore
3400 // the attachments when the configuration change completes.
3401 if (showToast && (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) {
3402 Toast.makeText(this, save ? R.string.message_saved : R.string.sending_message,
3403 Toast.LENGTH_LONG).show();
3404 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003405
Mindy Pereira181df782012-03-01 13:32:44 -08003406 // Need to update variables here because the send or save completes
3407 // asynchronously even though the toast shows right away.
3408 discardChanges();
3409 updateSaveUi();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003410
Mindy Pereira181df782012-03-01 13:32:44 -08003411 // If we are sending, finish the activity
3412 if (!save) {
3413 finish();
3414 }
3415 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003416
Mindy Pereira181df782012-03-01 13:32:44 -08003417 /**
3418 * Save the state of the request messageid map. This allows for the Gmail
3419 * process to be killed, but and still allow for ComposeActivity instances
3420 * to be recreated correctly.
3421 */
3422 private void saveRequestMap() {
3423 // TODO: store the request map in user preferences.
3424 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003425
Tony Mantler581edd42014-02-18 15:41:22 -08003426 @SuppressLint("NewApi")
Mindy Pereira2db7d4a2012-08-15 11:00:02 -07003427 private void doAttach(String type) {
Mindy Pereira013194c2012-01-06 15:09:33 -08003428 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
3429 i.addCategory(Intent.CATEGORY_OPENABLE);
Paul Westbrookd6a9a3f2012-04-26 18:47:23 -07003430 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
Andrew Sapperstein05089f32013-10-01 17:00:03 -07003431 i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
Mindy Pereira2db7d4a2012-08-15 11:00:02 -07003432 i.setType(type);
Mindy Pereira013194c2012-01-06 15:09:33 -08003433 mAddingAttachment = true;
Mindy Pereira181df782012-03-01 13:32:44 -08003434 startActivityForResult(Intent.createChooser(i, getText(R.string.select_attachment_type)),
3435 RESULT_PICK_ATTACHMENT);
Mindy Pereira013194c2012-01-06 15:09:33 -08003436 }
3437
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08003438 private void showCcBccViews() {
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08003439 mCcBccView.show(true, true, true);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08003440 if (mCcBccButton != null) {
Jin Cao9d358a12014-07-24 12:15:38 -07003441 mCcBccButton.setVisibility(View.GONE);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08003442 }
3443 }
3444
Andy Huang4fe0af82013-08-20 17:24:51 -07003445 private static String getActionString(int action) {
Andy Huangdc97bf42013-08-15 16:52:45 -07003446 final String msgType;
Andy Huang4fe0af82013-08-20 17:24:51 -07003447 switch (action) {
Andy Huangdc97bf42013-08-15 16:52:45 -07003448 case COMPOSE:
3449 msgType = "new_message";
3450 break;
3451 case REPLY:
3452 msgType = "reply";
3453 break;
3454 case REPLY_ALL:
3455 msgType = "reply_all";
3456 break;
3457 case FORWARD:
3458 msgType = "forward";
3459 break;
3460 default:
3461 msgType = "unknown";
3462 break;
3463 }
Andy Huang4fe0af82013-08-20 17:24:51 -07003464 return msgType;
3465 }
3466
3467 private void logSendOrSave(boolean save) {
3468 if (!Analytics.isLoggable() || mAttachmentsView == null) {
3469 return;
3470 }
3471
3472 final String category = (save) ? "message_save" : "message_send";
3473 final int attachmentCount = getAttachments().size();
3474 final String msgType = getActionString(mComposeMode);
Andy Huangdc97bf42013-08-15 16:52:45 -07003475 final String label;
3476 final long value;
3477 if (mComposeMode == COMPOSE) {
3478 label = Integer.toString(attachmentCount);
3479 value = attachmentCount;
3480 } else {
3481 label = null;
3482 value = 0;
3483 }
3484 Analytics.getInstance().sendEvent(category, msgType, label, value);
3485 }
3486
Mindy Pereira326c6602012-01-04 15:32:42 -08003487 @Override
3488 public boolean onNavigationItemSelected(int position, long itemId) {
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08003489 int initialComposeMode = mComposeMode;
Mindy Pereira326c6602012-01-04 15:32:42 -08003490 if (position == ComposeActivity.REPLY) {
3491 mComposeMode = ComposeActivity.REPLY;
3492 } else if (position == ComposeActivity.REPLY_ALL) {
3493 mComposeMode = ComposeActivity.REPLY_ALL;
3494 } else if (position == ComposeActivity.FORWARD) {
3495 mComposeMode = ComposeActivity.FORWARD;
3496 }
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07003497 clearChangeListeners();
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08003498 if (initialComposeMode != mComposeMode) {
Mindy Pereira154386a2012-01-11 13:02:33 -08003499 resetMessageForModeChange();
mindyp68c0bfc2012-12-04 10:29:48 -08003500 if (mRefMessage != null) {
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08003501 setFieldsFromRefMessage(mComposeMode);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07003502 }
Mindy Pereiraef388302012-06-18 19:07:44 -07003503 boolean showCc = false;
3504 boolean showBcc = false;
3505 if (mDraft != null) {
3506 // Following desktop behavior, if the user has added a BCC
3507 // field to a draft, we show it regardless of compose mode.
Scott Kennedy8960f0a2012-11-07 15:35:50 -08003508 showBcc = !TextUtils.isEmpty(mDraft.getBcc());
Mindy Pereiraef388302012-06-18 19:07:44 -07003509 // Use the draft to determine what to populate.
3510 // If the Bcc field is showing, show the Cc field whether it is populated or not.
Scott Kennedy8960f0a2012-11-07 15:35:50 -08003511 showCc = showBcc
3512 || (!TextUtils.isEmpty(mDraft.getCc()) && mComposeMode == REPLY_ALL);
mindyp68c0bfc2012-12-04 10:29:48 -08003513 }
3514 if (mRefMessage != null) {
mindyp9b1ac572012-09-27 14:12:00 -07003515 showCc = !TextUtils.isEmpty(mCc.getText());
mindyp68c0bfc2012-12-04 10:29:48 -08003516 showBcc = !TextUtils.isEmpty(mBcc.getText());
Mindy Pereiraef388302012-06-18 19:07:44 -07003517 }
Jin Caoc5c550a2014-07-29 11:53:17 -07003518 mCcBccView.show(false /* animate */, showCc, showBcc);
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08003519 }
Mindy Pereiraef388302012-06-18 19:07:44 -07003520 updateHideOrShowCcBcc();
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07003521 initChangeListeners();
Mindy Pereira326c6602012-01-04 15:32:42 -08003522 return true;
3523 }
3524
Mindy Pereirab3112a22012-06-20 12:10:03 -07003525 @VisibleForTesting
3526 protected void resetMessageForModeChange() {
Mindy Pereira154386a2012-01-11 13:02:33 -08003527 // When switching between reply, reply all, forward,
3528 // follow the behavior of webview.
3529 // The contents of the following fields are cleared
3530 // so that they can be populated directly from the
3531 // ref message:
3532 // 1) Any recipient fields
3533 // 2) The subject
3534 mTo.setText("");
3535 mCc.setText("");
3536 mBcc.setText("");
3537 // Any edits to the subject are replaced with the original subject.
3538 mSubject.setText("");
3539
3540 // Any changes to the contents of the following fields are kept:
3541 // 1) Body
3542 // 2) Attachments
3543 // If the user made changes to attachments, keep their changes.
3544 if (!mAttachmentsChanged) {
3545 mAttachmentsView.deleteAllAttachments();
3546 }
3547 }
3548
Mindy Pereira326c6602012-01-04 15:32:42 -08003549 private class ComposeModeAdapter extends ArrayAdapter<String> {
3550
Jin Caof7461632014-08-11 15:21:43 -07003551 private Context mContext;
Mindy Pereira326c6602012-01-04 15:32:42 -08003552 private LayoutInflater mInflater;
3553
3554 public ComposeModeAdapter(Context context) {
3555 super(context, R.layout.compose_mode_item, R.id.mode, getResources()
3556 .getStringArray(R.array.compose_modes));
Jin Caof7461632014-08-11 15:21:43 -07003557 mContext = context;
Mindy Pereira326c6602012-01-04 15:32:42 -08003558 }
3559
3560 private LayoutInflater getInflater() {
3561 if (mInflater == null) {
Jin Caof7461632014-08-11 15:21:43 -07003562 mInflater = LayoutInflater.from(mContext);
Mindy Pereira326c6602012-01-04 15:32:42 -08003563 }
3564 return mInflater;
3565 }
3566
3567 @Override
3568 public View getView(int position, View convertView, ViewGroup parent) {
3569 if (convertView == null) {
3570 convertView = getInflater().inflate(R.layout.compose_mode_display_item, null);
3571 }
3572 ((TextView) convertView.findViewById(R.id.mode)).setText(getItem(position));
3573 return super.getView(position, convertView, parent);
3574 }
3575 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003576
3577 @Override
3578 public void onRespondInline(String text) {
3579 appendToBody(text, false);
mindyp40882432012-09-06 11:07:40 -07003580 mQuotedTextView.setUpperDividerVisible(false);
mindyp1623f9b2012-11-21 12:41:16 -08003581 mRespondedInline = true;
mindyp09dd3732012-12-17 08:37:52 -08003582 if (!mBodyView.hasFocus()) {
mindyp8654d4f2012-12-17 09:01:37 -08003583 mBodyView.requestFocus();
mindyp09dd3732012-12-17 08:37:52 -08003584 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003585 }
3586
3587 /**
3588 * Append text to the body of the message. If there is no existing body
3589 * text, just sets the body to text.
3590 *
Tony Mantler581edd42014-02-18 15:41:22 -08003591 * @param text Text to append
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003592 * @param withSignature True to append a signature.
3593 */
3594 public void appendToBody(CharSequence text, boolean withSignature) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003595 Editable bodyText = mBodyView.getEditableText();
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003596 if (bodyText != null && bodyText.length() > 0) {
3597 bodyText.append(text);
3598 } else {
3599 setBody(text, withSignature);
3600 }
3601 }
3602
3603 /**
3604 * Set the body of the message.
Jin Cao738cafe2014-09-02 16:10:29 -07003605 * Please try to exclusively use this method instead of calling mBodyView.setText(..) directly.
Mindy Pereirabdf7a402012-03-01 15:23:26 -08003606 *
Tony Mantler581edd42014-02-18 15:41:22 -08003607 * @param text text to set
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003608 * @param withSignature True to append a signature.
3609 */
3610 public void setBody(CharSequence text, boolean withSignature) {
Jin Cao738cafe2014-09-02 16:10:29 -07003611 LogUtils.i(LOG_TAG, "Body populated, len: %d, sig: %b", text.length(), withSignature);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003612 mBodyView.setText(text);
Mindy Pereirabdf7a402012-03-01 15:23:26 -08003613 if (withSignature) {
3614 appendSignature();
3615 }
3616 }
3617
3618 private void appendSignature() {
Tony Mantler6a7ac782014-02-19 15:22:02 -08003619 final String newSignature = mCachedSettings != null ? mCachedSettings.signature : null;
3620 final int signaturePos = getSignatureStartPosition(mSignature, mBodyView.getText().toString());
mindyp27083062012-11-15 09:02:01 -08003621 if (!TextUtils.equals(newSignature, mSignature) || signaturePos < 0) {
Mindy Pereirab13917c2012-03-29 08:08:19 -07003622 mSignature = newSignature;
mindyp27083062012-11-15 09:02:01 -08003623 if (!TextUtils.isEmpty(mSignature)) {
Mindy Pereirab13917c2012-03-29 08:08:19 -07003624 // Appending a signature does not count as changing text.
3625 mBodyView.removeTextChangedListener(this);
3626 mBodyView.append(convertToPrintableSignature(mSignature));
3627 mBodyView.addTextChangedListener(this);
3628 }
Tony Mantler6a7ac782014-02-19 15:22:02 -08003629 resetBodySelection();
Mindy Pereirabdf7a402012-03-01 15:23:26 -08003630 }
3631 }
3632
3633 private String convertToPrintableSignature(String signature) {
3634 String signatureResource = getResources().getString(R.string.signature);
3635 if (signature == null) {
3636 signature = "";
3637 }
3638 return String.format(signatureResource, signature);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003639 }
Mindy Pereira1a95a572012-01-05 12:21:29 -08003640
Mindy Pereira5a85e2b2012-01-11 09:53:32 -08003641 @Override
3642 public void onAccountChanged() {
Mindy Pereira92551d02012-04-05 11:31:12 -07003643 mReplyFromAccount = mFromSpinner.getCurrentAccount();
3644 if (!mAccount.equals(mReplyFromAccount.account)) {
mindypf432dbc2012-11-12 16:00:44 -08003645 // Clear a signature, if there was one.
3646 mBodyView.removeTextChangedListener(this);
3647 String oldSignature = mSignature;
3648 String bodyText = getBody().getText().toString();
3649 if (!TextUtils.isEmpty(oldSignature)) {
3650 int pos = getSignatureStartPosition(oldSignature, bodyText);
3651 if (pos > -1) {
Jin Cao738cafe2014-09-02 16:10:29 -07003652 setBody(bodyText.substring(0, pos), false);
mindypf432dbc2012-11-12 16:00:44 -08003653 }
3654 }
Paul Westbrookb1f573c2012-04-06 11:38:28 -07003655 setAccount(mReplyFromAccount.account);
mindypf432dbc2012-11-12 16:00:44 -08003656 mBodyView.addTextChangedListener(this);
Mindy Pereira181df782012-03-01 13:32:44 -08003657 // TODO: handle discarding attachments when switching accounts.
3658 // Only enable save for this draft if there is any other content
3659 // in the message.
3660 if (!isBlank()) {
3661 enableSave(true);
3662 }
3663 mReplyFromChanged = true;
3664 initRecipients();
Greg Bullockd47a7042014-08-13 16:02:59 +02003665
3666 invalidateOptionsMenu();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003667 }
Mindy Pereira1a95a572012-01-05 12:21:29 -08003668 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003669
3670 public void enableSave(boolean enabled) {
3671 if (mSave != null) {
3672 mSave.setEnabled(enabled);
3673 }
3674 }
3675
Tony Mantler2558b502013-07-09 10:53:34 -07003676 public static class DiscardConfirmDialogFragment extends DialogFragment {
Paul Westbrookf0ea4842013-08-13 16:41:18 -07003677 // Public no-args constructor needed for fragment re-instantiation
3678 public DiscardConfirmDialogFragment() {}
3679
Tony Mantler2558b502013-07-09 10:53:34 -07003680 @Override
3681 public Dialog onCreateDialog(Bundle savedInstanceState) {
3682 return new AlertDialog.Builder(getActivity())
3683 .setMessage(R.string.confirm_discard_text)
3684 .setPositiveButton(R.string.discard,
3685 new DialogInterface.OnClickListener() {
3686 @Override
3687 public void onClick(DialogInterface dialog, int which) {
3688 ((ComposeActivity)getActivity()).doDiscardWithoutConfirmation();
3689 }
3690 })
Tony Mantler2b215b72013-07-31 10:20:46 -07003691 .setNegativeButton(R.string.cancel, null)
Tony Mantler2558b502013-07-09 10:53:34 -07003692 .create();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003693 }
3694 }
3695
Mindy Pereiraefe3d252012-03-01 14:20:44 -08003696 private void doDiscard() {
Jin Caoe0037922014-09-16 10:23:50 -07003697 // Only need to ask for confirmation if the draft is in a dirty state.
3698 if (isDraftDirty()) {
3699 final DialogFragment frag = new DiscardConfirmDialogFragment();
3700 frag.show(getFragmentManager(), "discard confirm");
3701 } else {
3702 doDiscardWithoutConfirmation();
3703 }
Mindy Pereiraefe3d252012-03-01 14:20:44 -08003704 }
Jin Caoe0037922014-09-16 10:23:50 -07003705
Mindy Pereira82cc5662012-01-09 17:29:30 -08003706 /**
3707 * Effectively discard the current message.
3708 *
3709 * This method is either invoked from the menu or from the dialog
3710 * once the user has confirmed that they want to discard the message.
Mindy Pereira82cc5662012-01-09 17:29:30 -08003711 */
Tony Mantler2558b502013-07-09 10:53:34 -07003712 private void doDiscardWithoutConfirmation() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003713 synchronized (mDraftLock) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08003714 if (mDraftId != UIProvider.INVALID_MESSAGE_ID) {
3715 ContentValues values = new ContentValues();
Paul Westbrookb7050e62012-03-20 12:59:44 -07003716 values.put(BaseColumns._ID, mDraftId);
Marc Blank78ea8e22012-08-04 11:14:06 -07003717 if (!mAccount.expungeMessageUri.equals(Uri.EMPTY)) {
Mindy Pereiracfb7f332012-02-28 10:23:43 -08003718 getContentResolver().update(mAccount.expungeMessageUri, values, null, null);
3719 } else {
Marc Blank0bbc8582012-04-23 15:07:57 -07003720 getContentResolver().delete(mDraft.uri, null, null);
Mindy Pereiracfb7f332012-02-28 10:23:43 -08003721 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003722 // This is not strictly necessary (since we should not try to
3723 // save the draft after calling this) but it ensures that if we
3724 // do save again for some reason we make a new draft rather than
3725 // trying to resave an expunged draft.
3726 mDraftId = UIProvider.INVALID_MESSAGE_ID;
3727 }
3728 }
3729
Tony Mantler2558b502013-07-09 10:53:34 -07003730 // Display a toast to let the user know
3731 Toast.makeText(this, R.string.message_discarded, Toast.LENGTH_SHORT).show();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003732
3733 // This prevents the draft from being saved in onPause().
3734 discardChanges();
Andy Huangdc97bf42013-08-15 16:52:45 -07003735 mPerformedSendOrDiscard = true;
Mindy Pereira82cc5662012-01-09 17:29:30 -08003736 finish();
3737 }
3738
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003739 private void saveIfNeeded() {
3740 if (mAccount == null) {
3741 // We have not chosen an account yet so there's no way that we can save. This is ok,
3742 // though, since we are saving our state before AccountsActivity is activated. Thus, the
3743 // user has not interacted with us yet and there is no real state to save.
3744 return;
3745 }
3746
Jin Caoe0037922014-09-16 10:23:50 -07003747 if (isDraftDirty()) {
Mindy Pereira48e31b02012-05-30 13:12:24 -07003748 doSave(!mAddingAttachment /* show toast */);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003749 }
3750 }
3751
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003752 @Override
3753 public void onAttachmentDeleted() {
3754 mAttachmentsChanged = true;
mindyp40882432012-09-06 11:07:40 -07003755 // If we are showing any attachments, make sure we have an upper
3756 // divider.
3757 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003758 updateSaveUi();
3759 }
Mindy Pereira75f66632012-01-11 11:42:02 -08003760
mindyp40882432012-09-06 11:07:40 -07003761 @Override
3762 public void onAttachmentAdded() {
3763 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
3764 mAttachmentsView.focusLastAttachment();
3765 }
Mindy Pereira75f66632012-01-11 11:42:02 -08003766
3767 /**
3768 * This is called any time one of our text fields changes.
3769 */
Marc Blank0bbc8582012-04-23 15:07:57 -07003770 @Override
Mindy Pereira75f66632012-01-11 11:42:02 -08003771 public void afterTextChanged(Editable s) {
3772 mTextChanged = true;
3773 updateSaveUi();
3774 }
3775
3776 @Override
3777 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3778 // Do nothing.
3779 }
3780
Marc Blank0bbc8582012-04-23 15:07:57 -07003781 @Override
Mindy Pereira75f66632012-01-11 11:42:02 -08003782 public void onTextChanged(CharSequence s, int start, int before, int count) {
3783 // Do nothing.
3784 }
3785
3786
3787 // There is a big difference between the text associated with an address changing
3788 // to add the display name or to format properly and a recipient being added or deleted.
3789 // Make sure we only notify of changes when a recipient has been added or deleted.
3790 private class RecipientTextWatcher implements TextWatcher {
3791 private HashMap<String, Integer> mContent = new HashMap<String, Integer>();
3792
3793 private RecipientEditTextView mView;
3794
3795 private TextWatcher mListener;
3796
3797 public RecipientTextWatcher(RecipientEditTextView view, TextWatcher listener) {
3798 mView = view;
3799 mListener = listener;
3800 }
3801
3802 @Override
3803 public void afterTextChanged(Editable s) {
3804 if (hasChanged()) {
3805 mListener.afterTextChanged(s);
3806 }
3807 }
3808
3809 private boolean hasChanged() {
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003810 final ArrayList<String> currRecips = buildEmailAddressList(getAddressesFromList(mView));
3811 int totalCount = currRecips.size();
Mindy Pereira75f66632012-01-11 11:42:02 -08003812 int totalPrevCount = 0;
3813 for (Entry<String, Integer> entry : mContent.entrySet()) {
3814 totalPrevCount += entry.getValue();
3815 }
3816 if (totalCount != totalPrevCount) {
3817 return true;
3818 }
3819
3820 for (String recip : currRecips) {
3821 if (!mContent.containsKey(recip)) {
3822 return true;
3823 } else {
3824 int count = mContent.get(recip) - 1;
3825 if (count < 0) {
3826 return true;
3827 } else {
3828 mContent.put(recip, count);
3829 }
3830 }
3831 }
3832 return false;
3833 }
3834
Mindy Pereira75f66632012-01-11 11:42:02 -08003835 @Override
3836 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003837 final ArrayList<String> recips = buildEmailAddressList(getAddressesFromList(mView));
Mindy Pereira75f66632012-01-11 11:42:02 -08003838 for (String recip : recips) {
3839 if (!mContent.containsKey(recip)) {
3840 mContent.put(recip, 1);
3841 } else {
3842 mContent.put(recip, (mContent.get(recip)) + 1);
3843 }
3844 }
3845 }
3846
3847 @Override
3848 public void onTextChanged(CharSequence s, int start, int before, int count) {
3849 // Do nothing.
3850 }
3851 }
Mindy Pereirae011b1d2012-06-18 13:45:26 -07003852
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003853 /**
3854 * Returns a list of email addresses from the recipients. List only contains
3855 * email addresses strips additional info like the recipient's name.
3856 */
3857 private static ArrayList<String> buildEmailAddressList(String[] recips) {
3858 // Tokenize them all and put them in the list.
3859 final ArrayList<String> recipAddresses = Lists.newArrayListWithCapacity(recips.length);
3860 for (int i = 0; i < recips.length; i++) {
3861 recipAddresses.add(Rfc822Tokenizer.tokenize(recips[i])[0].getAddress());
3862 }
3863 return recipAddresses;
3864 }
3865
Mindy Pereirae011b1d2012-06-18 13:45:26 -07003866 public static void registerTestSendOrSaveCallback(SendOrSaveCallback testCallback) {
3867 if (sTestSendOrSaveCallback != null && testCallback != null) {
3868 throw new IllegalStateException("Attempting to register more than one test callback");
3869 }
3870 sTestSendOrSaveCallback = testCallback;
3871 }
Mindy Pereirabddd6f32012-06-20 12:10:03 -07003872
3873 @VisibleForTesting
3874 protected ArrayList<Attachment> getAttachments() {
3875 return mAttachmentsView.getAttachments();
3876 }
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003877
3878 @Override
3879 public Loader<Cursor> onCreateLoader(int id, Bundle args) {
3880 switch (id) {
Alice Yanga990a712013-03-13 18:37:00 -07003881 case INIT_DRAFT_USING_REFERENCE_MESSAGE:
3882 return new CursorLoader(this, mRefMessageUri, UIProvider.MESSAGE_PROJECTION, null,
3883 null, null);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003884 case REFERENCE_MESSAGE_LOADER:
3885 return new CursorLoader(this, mRefMessageUri, UIProvider.MESSAGE_PROJECTION, null,
3886 null, null);
Mindy Pereirab199d172012-08-13 11:04:03 -07003887 case LOADER_ACCOUNT_CURSOR:
3888 return new CursorLoader(this, MailAppProvider.getAccountsUri(),
3889 UIProvider.ACCOUNTS_PROJECTION, null, null, null);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003890 }
3891 return null;
3892 }
3893
3894 @Override
3895 public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Mindy Pereirab199d172012-08-13 11:04:03 -07003896 int id = loader.getId();
3897 switch (id) {
Alice Yanga990a712013-03-13 18:37:00 -07003898 case INIT_DRAFT_USING_REFERENCE_MESSAGE:
Mindy Pereirab199d172012-08-13 11:04:03 -07003899 if (data != null && data.moveToFirst()) {
3900 mRefMessage = new Message(data);
Mindy Pereirab199d172012-08-13 11:04:03 -07003901 Intent intent = getIntent();
Alice Yanga990a712013-03-13 18:37:00 -07003902 initFromRefMessage(mComposeMode);
3903 finishSetup(mComposeMode, intent, null);
3904 if (mComposeMode != FORWARD) {
Mindy Pereirab199d172012-08-13 11:04:03 -07003905 String to = intent.getStringExtra(EXTRA_TO);
3906 if (!TextUtils.isEmpty(to)) {
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08003907 mRefMessage.setTo(null);
3908 mRefMessage.setFrom(null);
Mindy Pereirab199d172012-08-13 11:04:03 -07003909 clearChangeListeners();
3910 mTo.append(to);
3911 initChangeListeners();
3912 }
3913 }
3914 } else {
3915 finish();
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003916 }
Mindy Pereirab199d172012-08-13 11:04:03 -07003917 break;
Alice Yanga990a712013-03-13 18:37:00 -07003918 case REFERENCE_MESSAGE_LOADER:
3919 // Only populate mRefMessage and leave other fields untouched.
3920 if (data != null && data.moveToFirst()) {
3921 mRefMessage = new Message(data);
3922 }
Andy Huang9f855d62013-05-30 17:15:03 -07003923 finishSetup(mComposeMode, getIntent(), mInnerSavedState);
Alice Yanga990a712013-03-13 18:37:00 -07003924 break;
Mindy Pereirab199d172012-08-13 11:04:03 -07003925 case LOADER_ACCOUNT_CURSOR:
3926 if (data != null && data.moveToFirst()) {
3927 // there are accounts now!
3928 Account account;
Paul Westbrookfaa742f2012-11-01 09:50:16 -07003929 final ArrayList<Account> accounts = new ArrayList<Account>();
3930 final ArrayList<Account> initializedAccounts = new ArrayList<Account>();
Mindy Pereirab199d172012-08-13 11:04:03 -07003931 do {
Ray Chen4b0c0122014-07-11 15:24:54 +02003932 account = Account.builder().buildFrom(data);
Paul Westbrookdfa1dec2012-09-26 16:27:28 -07003933 if (account.isAccountReady()) {
Mindy Pereirab199d172012-08-13 11:04:03 -07003934 initializedAccounts.add(account);
3935 }
3936 accounts.add(account);
3937 } while (data.moveToNext());
3938 if (initializedAccounts.size() > 0) {
3939 findViewById(R.id.wait).setVisibility(View.GONE);
3940 getLoaderManager().destroyLoader(LOADER_ACCOUNT_CURSOR);
3941 findViewById(R.id.compose).setVisibility(View.VISIBLE);
Paul Westbrookfaa742f2012-11-01 09:50:16 -07003942 mAccounts = initializedAccounts.toArray(
3943 new Account[initializedAccounts.size()]);
3944
Mindy Pereirab199d172012-08-13 11:04:03 -07003945 finishCreate();
3946 invalidateOptionsMenu();
3947 } else {
3948 // Show "waiting"
3949 account = accounts.size() > 0 ? accounts.get(0) : null;
3950 showWaitFragment(account);
3951 }
3952 }
3953 break;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003954 }
3955 }
3956
Mindy Pereirab199d172012-08-13 11:04:03 -07003957 private void showWaitFragment(Account account) {
3958 WaitFragment fragment = getWaitFragment();
3959 if (fragment != null) {
3960 fragment.updateAccount(account);
3961 } else {
3962 findViewById(R.id.wait).setVisibility(View.VISIBLE);
Andy Huangc96efcc2014-04-09 15:30:42 -07003963 replaceFragment(WaitFragment.newInstance(account, false /* expectingMessages */),
Mindy Pereirab199d172012-08-13 11:04:03 -07003964 FragmentTransaction.TRANSIT_FRAGMENT_OPEN, TAG_WAIT);
3965 }
3966 }
3967
3968 private WaitFragment getWaitFragment() {
3969 return (WaitFragment) getFragmentManager().findFragmentByTag(TAG_WAIT);
3970 }
3971
3972 private int replaceFragment(Fragment fragment, int transition, String tag) {
3973 FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
Mindy Pereirab199d172012-08-13 11:04:03 -07003974 fragmentTransaction.setTransition(transition);
3975 fragmentTransaction.replace(R.id.wait, fragment, tag);
3976 final int transactionId = fragmentTransaction.commitAllowingStateLoss();
3977 return transactionId;
3978 }
3979
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003980 @Override
3981 public void onLoaderReset(Loader<Cursor> arg0) {
3982 // Do nothing.
3983 }
Jin Cao77b4c2c2014-05-20 13:55:53 -07003984
3985 /**
3986 * Background task to convert the message's html to Spanned.
3987 */
3988 private class HtmlToSpannedTask extends AsyncTask<String, Void, Spanned> {
3989
3990 @Override
3991 protected Spanned doInBackground(String... input) {
Andy Huang9ed742c2014-06-18 02:34:50 -07003992 return HtmlUtils.htmlToSpan(input[0], mSpanConverterFactory);
Jin Cao77b4c2c2014-05-20 13:55:53 -07003993 }
3994
3995 @Override
3996 protected void onPostExecute(Spanned spanned) {
3997 mBodyView.removeTextChangedListener(ComposeActivity.this);
Jin Cao738cafe2014-09-02 16:10:29 -07003998 setBody(spanned, false);
Jin Cao77b4c2c2014-05-20 13:55:53 -07003999 mTextChanged = false;
4000 mBodyView.addTextChangedListener(ComposeActivity.this);
4001 }
4002 }
Andrew Sapperstein734718a2014-09-15 17:29:13 -07004003
4004 @SuppressLint("NewApi")
4005 @Override
4006 public void onSupportActionModeStarted(ActionMode mode) {
4007 super.onSupportActionModeStarted(mode);
4008 if (Utils.isRunningLOrLater()) {
4009 final Window window = getWindow();
4010 if (window != null) {
4011 window.setStatusBarColor(
4012 getResources().getColor(R.color.action_mode_statusbar_color));
4013 }
4014 }
4015 }
4016
4017 @SuppressLint("NewApi")
4018 @Override
4019 public void onSupportActionModeFinished(ActionMode mode) {
4020 super.onSupportActionModeFinished(mode);
4021 if (Utils.isRunningLOrLater()) {
4022 final Window window = getWindow();
4023 if (window != null) {
4024 window.setStatusBarColor(
Andrew Sappersteine1dc3e72014-09-18 15:07:46 -07004025 getResources().getColor(R.color.primary_dark_color));
Andrew Sapperstein734718a2014-09-15 17:29:13 -07004026 }
4027 }
4028 }
Andy Huang1f8f4dd2012-10-25 21:35:35 -07004029}