blob: 5f125abe6dffdc392dbbd306bf7011395d8ca7a6 [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;
Paul Westbrookb4931c62013-01-14 17:51:18 -080073import android.view.inputmethod.BaseInputConnection;
mindyp62d3ec72012-08-24 13:04:09 -070074import android.view.inputmethod.EditorInfo;
Mindy Pereira326c6602012-01-04 15:32:42 -080075import android.widget.ArrayAdapter;
Mindy Pereira433b1982012-04-03 11:53:07 -070076import android.widget.EditText;
Jin Cao36e23872014-07-29 13:41:12 -070077import android.widget.ScrollView;
Mindy Pereira6349a042012-01-04 11:25:01 -080078import android.widget.TextView;
Mindy Pereira013194c2012-01-06 15:09:33 -080079import android.widget.Toast;
Mindy Pereira7b56a612011-12-14 12:32:28 -080080
Mindy Pereirac17d0732011-12-29 10:46:19 -080081import com.android.common.Rfc822Validator;
Tony Mantler9f324232013-08-08 14:24:30 -070082import com.android.common.contacts.DataUsageStatUpdater;
Tony Mantler821e5782014-01-06 15:33:43 -080083import com.android.emailcommon.mail.Address;
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -070084import com.android.ex.chips.BaseRecipientAdapter;
85import com.android.ex.chips.DropdownChipLayouter;
Andy Huang5c5fd572012-04-08 18:19:29 -070086import com.android.ex.chips.RecipientEditTextView;
Scott Kennedy5680ec22013-01-07 13:15:20 -080087import com.android.mail.MailIntentService;
Andy Huang5c5fd572012-04-08 18:19:29 -070088import com.android.mail.R;
Andy Huang761522c2013-08-08 13:09:11 -070089import com.android.mail.analytics.Analytics;
Alice Yang1ebc2db2013-03-14 21:21:44 -070090import com.android.mail.browse.MessageHeaderView;
mindyp40882432012-09-06 11:07:40 -070091import com.android.mail.compose.AttachmentsView.AttachmentAddedOrDeletedListener;
Mindy Pereira9932dee2012-01-10 16:09:50 -080092import com.android.mail.compose.AttachmentsView.AttachmentFailureException;
Mindy Pereira5a85e2b2012-01-11 09:53:32 -080093import com.android.mail.compose.FromAddressSpinner.OnAccountChangedListener;
Andy Huang30e2c242012-01-06 18:14:30 -080094import com.android.mail.compose.QuotedTextView.RespondInlineListener;
Mindy Pereira33fe9082012-01-09 16:24:30 -080095import com.android.mail.providers.Account;
Andy Huang30e2c242012-01-06 18:14:30 -080096import com.android.mail.providers.Attachment;
Scott Kennedy5680ec22013-01-07 13:15:20 -080097import com.android.mail.providers.Folder;
Mindy Pereira47d0e652012-07-23 09:45:07 -070098import com.android.mail.providers.MailAppProvider;
Mindy Pereira3ce64e72012-01-13 14:29:45 -080099import com.android.mail.providers.Message;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800100import com.android.mail.providers.MessageModification;
Mindy Pereira92551d02012-04-05 11:31:12 -0700101import com.android.mail.providers.ReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -0800102import com.android.mail.providers.Settings;
Andy Huang30e2c242012-01-06 18:14:30 -0800103import com.android.mail.providers.UIProvider;
Mindy Pereira3ca5bad2012-04-16 11:02:42 -0700104import com.android.mail.providers.UIProvider.AccountCapabilities;
Mindy Pereira12575862012-03-21 16:30:54 -0700105import com.android.mail.providers.UIProvider.DraftType;
Alice Yang1ebc2db2013-03-14 21:21:44 -0700106import com.android.mail.ui.AttachmentTile.AttachmentPreview;
Mindy Pereirafa20c1a2012-07-23 13:00:02 -0700107import com.android.mail.ui.MailActivity;
Mindy Pereirab199d172012-08-13 11:04:03 -0700108import com.android.mail.ui.WaitFragment;
Paul Westbrook92227f62012-03-20 10:32:51 -0700109import com.android.mail.utils.AccountUtils;
Mark Wei434f2942012-08-24 11:54:02 -0700110import com.android.mail.utils.AttachmentUtils;
mindypfebd2262012-11-13 17:45:09 -0800111import com.android.mail.utils.ContentProviderTask;
Jin Cao77b4c2c2014-05-20 13:55:53 -0700112import com.android.mail.utils.HtmlUtils;
Paul Westbrookb334c902012-06-25 11:42:46 -0700113import com.android.mail.utils.LogTag;
Andy Huang30e2c242012-01-06 18:14:30 -0800114import com.android.mail.utils.LogUtils;
Alan Lau15490232014-03-06 14:53:14 -0800115import com.android.mail.utils.NotificationActionUtils;
Andy Huang30e2c242012-01-06 18:14:30 -0800116import com.android.mail.utils.Utils;
Jin Caof14d8b32014-10-07 18:19:41 -0700117import com.android.mail.utils.ViewUtils;
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
Régis Décampse70f67a2016-02-23 16:16:54 +0100194 public static final String ANALYTICS_CATEGORY_ERRORS = "compose_errors";
195
Scott Kennedy60847252013-08-15 15:55:42 -0700196 /**
197 * An optional extra containing a {@link ContentValues} of values to be added to
198 * {@link SendOrSaveMessage#mValues}.
199 */
200 public static final String EXTRA_VALUES = "extra-values";
201
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700202 // List of all the fields
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700203 static final String[] ALL_EXTRAS = { EXTRA_SUBJECT, EXTRA_BODY, EXTRA_TO, EXTRA_CC, EXTRA_BCC,
204 EXTRA_QUOTED_TEXT };
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700205
Alan Lau439aa5d2014-05-27 17:57:13 -0700206 private static final String LEGACY_WEAR_EXTRA = "com.google.android.wearable.extras";
207
Andrew Sapperstein09da9422014-05-30 09:48:08 -0700208 /**
209 * Constant value for the threshold to use for auto-complete suggestions
210 * for the to/cc/bcc fields.
211 */
212 private static final int COMPLETION_THRESHOLD = 1;
213
Mindy Pereira82cc5662012-01-09 17:29:30 -0800214 private static SendOrSaveCallback sTestSendOrSaveCallback = null;
215 // Map containing information about requests to create new messages, and the id of the
216 // messages that were the result of those requests.
217 //
218 // This map is used when the activity that initiated the save a of a new message, is killed
219 // before the save has completed (and when we know the id of the newly created message). When
220 // a save is completed, the service that is running in the background, will update the map
221 //
222 // When a new ComposeActivity instance is created, it will attempt to use the information in
223 // the previously instantiated map. If ComposeActivity.onCreate() is called, with a bundle
224 // (restoring data from a previous instance), and the map hasn't been created, we will attempt
225 // to populate the map with data stored in shared preferences.
Jin Cao31bb3d62014-09-11 14:01:43 -0700226 private static final ConcurrentHashMap<Integer, Long> sRequestMessageIdMap =
227 new ConcurrentHashMap<Integer, Long>(10);
228 private static final Random sRandom = new Random(System.currentTimeMillis());
229
Mindy Pereira6349a042012-01-04 11:25:01 -0800230 /**
231 * Notifies the {@code Activity} that the caller is an Email
232 * {@code Activity}, so that the back behavior may be modified accordingly.
233 *
234 * @see #onAppUpPressed
235 */
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700236 public static final String EXTRA_FROM_EMAIL_TASK = "fromemail";
Mindy Pereira6349a042012-01-04 11:25:01 -0800237
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700238 public static final String EXTRA_ATTACHMENTS = "attachments";
Paul Westbrookf97588b2012-03-20 11:11:37 -0700239
Scott Kennedy5680ec22013-01-07 13:15:20 -0800240 /** If set, we will clear notifications for this folder. */
241 public static final String EXTRA_NOTIFICATION_FOLDER = "extra-notification-folder";
Alan Laue806c942014-06-06 16:19:15 -0700242 public static final String EXTRA_NOTIFICATION_CONVERSATION = "extra-notification-conversation";
Scott Kennedy5680ec22013-01-07 13:15:20 -0800243
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800244 // If this is a reply/forward then this extra will hold the original message
Mindy Pereira36bbcae2012-04-25 09:27:04 -0700245 private static final String EXTRA_IN_REFERENCE_TO_MESSAGE = "in-reference-to-message";
Mindy Pereirab18e5a92012-07-10 11:47:21 -0700246 // If this is a reply/forward then this extra will hold a uri we must query
247 // to get the original message.
248 protected static final String EXTRA_IN_REFERENCE_TO_MESSAGE_URI = "in-reference-to-message-uri";
Mark Wei434f2942012-08-24 11:54:02 -0700249 // If this is an action to edit an existing draft message, this extra will hold the
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700250 // draft message
251 private static final String ORIGINAL_DRAFT_MESSAGE = "original-draft-message";
Mindy Pereira4a27ea92012-01-05 15:55:25 -0800252 private static final String END_TOKEN = ", ";
Paul Westbrookb334c902012-06-25 11:42:46 -0700253 private static final String LOG_TAG = LogTag.getLogTag();
Mindy Pereira013194c2012-01-06 15:09:33 -0800254 // Request numbers for activities we start
255 private static final int RESULT_PICK_ATTACHMENT = 1;
256 private static final int RESULT_CREATE_ACCOUNT = 2;
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700257 // TODO(mindyp) set mime-type for auto send?
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700258 public static final String AUTO_SEND_ACTION = "com.android.mail.action.AUTO_SEND";
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700259
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700260 private static final String EXTRA_SELECTED_REPLY_FROM_ACCOUNT = "replyFromAccount";
261 private static final String EXTRA_REQUEST_ID = "requestId";
262 private static final String EXTRA_FOCUS_SELECTION_START = "focusSelectionStart";
Paul Westbrook176a1992013-07-22 13:57:19 -0700263 private static final String EXTRA_FOCUS_SELECTION_END = "focusSelectionEnd";
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700264 private static final String EXTRA_MESSAGE = "extraMessage";
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700265 private static final int REFERENCE_MESSAGE_LOADER = 0;
Mindy Pereirab199d172012-08-13 11:04:03 -0700266 private static final int LOADER_ACCOUNT_CURSOR = 1;
Alice Yanga990a712013-03-13 18:37:00 -0700267 private static final int INIT_DRAFT_USING_REFERENCE_MESSAGE = 2;
Mindy Pereira47d0e652012-07-23 09:45:07 -0700268 private static final String EXTRA_SELECTED_ACCOUNT = "selectedAccount";
Mindy Pereirab199d172012-08-13 11:04:03 -0700269 private static final String TAG_WAIT = "wait-fragment";
Andrew Sapperstein5cb71802013-10-01 18:31:20 -0700270 private static final String MIME_TYPE_ALL = "*/*";
Mindy Pereira2db7d4a2012-08-15 11:00:02 -0700271 private static final String MIME_TYPE_PHOTO = "image/*";
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800272
Andy Huang9f855d62013-05-30 17:15:03 -0700273 private static final String KEY_INNER_SAVED_STATE = "compose_state";
274
Jin Caoadea2c82014-08-28 12:25:52 -0700275 // A single thread for running tasks in the background.
276 private static final Handler SEND_SAVE_TASK_HANDLER;
Jin Caoaff451f2014-09-09 14:32:04 -0700277 @VisibleForTesting
278 public static final AtomicInteger PENDING_SEND_OR_SAVE_TASKS_NUM = new AtomicInteger(0);
279
Régis Décampse70f67a2016-02-23 16:16:54 +0100280 /* Path of the data directory (used for attachment uri checking). */
Jin Caoadea2c82014-08-28 12:25:52 -0700281 private static final String DATA_DIRECTORY_ROOT;
282
283 // Static initializations
Jin Cao5134be52014-05-06 19:18:38 -0700284 static {
285 HandlerThread handlerThread = new HandlerThread("Send Message Task Thread");
286 handlerThread.start();
Jin Cao5134be52014-05-06 19:18:38 -0700287 SEND_SAVE_TASK_HANDLER = new Handler(handlerThread.getLooper());
Jin Caoadea2c82014-08-28 12:25:52 -0700288
289 DATA_DIRECTORY_ROOT = Environment.getDataDirectory().toString();
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);
Andrew Sappersteinae47d922014-10-09 14:35:51 -0700515 // Change the title for accessibility so we announce "Compose" instead
516 // of the app_name while still showing the app_name in recents.
517 setTitle(R.string.compose_title);
Mindy Pereira3528d362012-01-05 14:39:44 -0800518 setContentView(R.layout.compose);
Andrew Sapperstein52882ff2014-07-27 12:30:18 -0700519 final ActionBar actionBar = getSupportActionBar();
Paul Westbrook4def3bf2014-07-01 00:38:17 -0700520 if (actionBar != null) {
521 // Hide the app icon.
Paul Westbrook5043cc22014-06-28 05:04:21 -0700522 actionBar.setIcon(null);
Paul Westbrook4def3bf2014-07-01 00:38:17 -0700523 actionBar.setDisplayUseLogoEnabled(false);
Paul Westbrook5043cc22014-06-28 05:04:21 -0700524 }
525
Andy Huang9f855d62013-05-30 17:15:03 -0700526 mInnerSavedState = (savedInstanceState != null) ?
527 savedInstanceState.getBundle(KEY_INNER_SAVED_STATE) : null;
Mindy Pereirab199d172012-08-13 11:04:03 -0700528 checkValidAccounts();
529 }
530
531 private void finishCreate() {
Andy Huang9f855d62013-05-30 17:15:03 -0700532 final Bundle savedState = mInnerSavedState;
Mindy Pereira3528d362012-01-05 14:39:44 -0800533 findViews();
Tony Mantler581edd42014-02-18 15:41:22 -0800534 final Intent intent = getIntent();
535 final Message message;
536 final ArrayList<AttachmentPreview> previews;
Alice Yanga990a712013-03-13 18:37:00 -0700537 mShowQuotedText = false;
Tony Mantler581edd42014-02-18 15:41:22 -0800538 final CharSequence quotedText;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700539 int action;
Mindy Pereira47d0e652012-07-23 09:45:07 -0700540 // Check for any of the possibly supplied accounts.;
Tony Mantler581edd42014-02-18 15:41:22 -0800541 final Account account;
Andy Huang9f855d62013-05-30 17:15:03 -0700542 if (hadSavedInstanceStateMessage(savedState)) {
543 action = savedState.getInt(EXTRA_ACTION, COMPOSE);
544 account = savedState.getParcelable(Utils.EXTRA_ACCOUNT);
Tony Mantler581edd42014-02-18 15:41:22 -0800545 message = savedState.getParcelable(EXTRA_MESSAGE);
Mark Wei62066e42012-09-13 12:07:02 -0700546
Andy Huang9f855d62013-05-30 17:15:03 -0700547 previews = savedState.getParcelableArrayList(EXTRA_ATTACHMENT_PREVIEWS);
Tony Mantler581edd42014-02-18 15:41:22 -0800548 mRefMessage = savedState.getParcelable(EXTRA_IN_REFERENCE_TO_MESSAGE);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700549 quotedText = savedState.getCharSequence(EXTRA_QUOTED_TEXT);
Scott Kennedy44d44812013-08-19 14:18:31 -0700550
551 mExtraValues = savedState.getParcelable(EXTRA_VALUES);
Jin Cao31bb3d62014-09-11 14:01:43 -0700552
553 // Get the draft id from the request id if there is one.
554 if (savedState.containsKey(EXTRA_REQUEST_ID)) {
555 final int requestId = savedState.getInt(EXTRA_REQUEST_ID);
556 if (sRequestMessageIdMap.containsKey(requestId)) {
557 synchronized (mDraftLock) {
558 mDraftId = sRequestMessageIdMap.get(requestId);
559 }
560 }
561 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700562 } else {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700563 account = obtainAccount(intent);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700564 action = intent.getIntExtra(EXTRA_ACTION, COMPOSE);
565 // Initialize the message from the message in the intent
Tony Mantler581edd42014-02-18 15:41:22 -0800566 message = intent.getParcelableExtra(ORIGINAL_DRAFT_MESSAGE);
Mark Wei62066e42012-09-13 12:07:02 -0700567 previews = intent.getParcelableArrayListExtra(EXTRA_ATTACHMENT_PREVIEWS);
Tony Mantler581edd42014-02-18 15:41:22 -0800568 mRefMessage = intent.getParcelableExtra(EXTRA_IN_REFERENCE_TO_MESSAGE);
569 mRefMessageUri = intent.getParcelableExtra(EXTRA_IN_REFERENCE_TO_MESSAGE_URI);
570 quotedText = null;
Andy Huang4fe0af82013-08-20 17:24:51 -0700571
572 if (Analytics.isLoggable()) {
573 if (intent.getBooleanExtra(Utils.EXTRA_FROM_NOTIFICATION, false)) {
574 Analytics.getInstance().sendEvent(
575 "notification_action", "compose", getActionString(action), 0);
576 }
577 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700578 }
Mark Wei62066e42012-09-13 12:07:02 -0700579 mAttachmentsView.setAttachmentPreviews(previews);
Paul Westbrook92227f62012-03-20 10:32:51 -0700580
581 setAccount(account);
Mindy Pereira818143e2012-01-11 13:59:49 -0800582 if (mAccount == null) {
583 return;
584 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700585
Scott Kennedyfe853d32013-06-19 11:47:35 -0700586 initRecipients();
587
Scott Kennedy5680ec22013-01-07 13:15:20 -0800588 // Clear the notification and mark the conversation as seen, if necessary
589 final Folder notificationFolder =
590 intent.getParcelableExtra(EXTRA_NOTIFICATION_FOLDER);
Scott Kennedy5680ec22013-01-07 13:15:20 -0800591
Alan Laue806c942014-06-06 16:19:15 -0700592 if (notificationFolder != null) {
593 final Uri conversationUri = intent.getParcelableExtra(EXTRA_NOTIFICATION_CONVERSATION);
594 Intent actionIntent;
595 if (conversationUri != null) {
596 actionIntent = new Intent(MailIntentService.ACTION_RESEND_NOTIFICATIONS_WEAR);
597 actionIntent.putExtra(Utils.EXTRA_CONVERSATION, conversationUri);
598 } else {
599 actionIntent = new Intent(MailIntentService.ACTION_CLEAR_NEW_MAIL_NOTIFICATIONS);
600 actionIntent.setData(Utils.appendVersionQueryParameter(this,
601 notificationFolder.folderUri.fullUri));
602 }
603 actionIntent.setPackage(getPackageName());
604 actionIntent.putExtra(Utils.EXTRA_ACCOUNT, account);
605 actionIntent.putExtra(Utils.EXTRA_FOLDER, notificationFolder);
606
607 startService(actionIntent);
Scott Kennedy5680ec22013-01-07 13:15:20 -0800608 }
609
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700610 if (intent.getBooleanExtra(EXTRA_FROM_EMAIL_TASK, false)) {
611 mLaunchedFromEmail = true;
612 } else if (Intent.ACTION_SEND.equals(intent.getAction())) {
613 final Uri dataUri = intent.getData();
614 if (dataUri != null) {
615 final String dataScheme = intent.getData().getScheme();
616 final String accountScheme = mAccount.composeIntentUri.getScheme();
617 mLaunchedFromEmail = TextUtils.equals(dataScheme, accountScheme);
618 }
619 }
620
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700621 if (mRefMessageUri != null) {
Alice Yanga990a712013-03-13 18:37:00 -0700622 mShowQuotedText = true;
623 mComposeMode = action;
Alan Lau15490232014-03-06 14:53:14 -0800624
625 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
Alan Lau575255c2014-05-16 11:44:27 -0700626 Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
Alan Lau439aa5d2014-05-27 17:57:13 -0700627 String wearReply = null;
Alan Lau575255c2014-05-16 11:44:27 -0700628 if (remoteInput != null) {
Alan Lau439aa5d2014-05-27 17:57:13 -0700629 LogUtils.d(LOG_TAG, "Got remote input from new api");
630 CharSequence input = remoteInput.getCharSequence(
Alan Lau575255c2014-05-16 11:44:27 -0700631 NotificationActionUtils.WEAR_REPLY_INPUT);
Alan Lau439aa5d2014-05-27 17:57:13 -0700632 if (input != null) {
633 wearReply = input.toString();
Alan Lau15490232014-03-06 14:53:14 -0800634 }
Alan Lau575255c2014-05-16 11:44:27 -0700635 } else {
Alan Lau439aa5d2014-05-27 17:57:13 -0700636 // TODO: remove after legacy code has been removed.
637 LogUtils.d(LOG_TAG,
638 "No remote input from new api, falling back to compatibility mode");
639 ClipData clipData = intent.getClipData();
640 if (clipData != null
641 && LEGACY_WEAR_EXTRA.equals(clipData.getDescription().getLabel())) {
642 Bundle extras = clipData.getItemAt(0).getIntent().getExtras();
643 if (extras != null) {
644 wearReply = extras.getString(NotificationActionUtils.WEAR_REPLY_INPUT);
645 }
646 }
647 }
648
649 if (!TextUtils.isEmpty(wearReply)) {
650 createWearReplyTask(this, mRefMessageUri, UIProvider.MESSAGE_PROJECTION,
651 mComposeMode, wearReply).execute();
652 finish();
653 return;
654 } else {
655 LogUtils.w(LOG_TAG, "remote input string is null");
Alan Lau15490232014-03-06 14:53:14 -0800656 }
657 }
658
Alice Yanga990a712013-03-13 18:37:00 -0700659 getLoaderManager().initLoader(INIT_DRAFT_USING_REFERENCE_MESSAGE, null, this);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700660 return;
661 } else if (message != null && action != EDIT_DRAFT) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700662 initFromDraftMessage(message);
663 initQuotedTextFromRefMessage(mRefMessage, action);
Alice Yanga990a712013-03-13 18:37:00 -0700664 mShowQuotedText = message.appendRefMessageContent;
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700665 // if we should be showing quoted text but mRefMessage is null
666 // and we have some quotedText, display that
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700667 if (mShowQuotedText && mRefMessage == null) {
668 if (quotedText != null) {
669 initQuotedText(quotedText, false /* shouldQuoteText */);
670 } else if (mExtraValues != null) {
671 initExtraValues(mExtraValues);
672 return;
673 }
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700674 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700675 } else if (action == EDIT_DRAFT) {
Tony Mantler581edd42014-02-18 15:41:22 -0800676 if (message == null) {
677 throw new IllegalStateException("Message must not be null to edit draft");
678 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700679 initFromDraftMessage(message);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700680 // Update the action to the draft type of the previous draft
681 switch (message.draftType) {
682 case UIProvider.DraftType.REPLY:
683 action = REPLY;
684 break;
685 case UIProvider.DraftType.REPLY_ALL:
686 action = REPLY_ALL;
687 break;
688 case UIProvider.DraftType.FORWARD:
689 action = FORWARD;
690 break;
691 case UIProvider.DraftType.COMPOSE:
692 default:
693 action = COMPOSE;
694 break;
695 }
Alice Yanga990a712013-03-13 18:37:00 -0700696 LogUtils.d(LOG_TAG, "Previous draft had action type: %d", action);
697
698 mShowQuotedText = message.appendRefMessageContent;
699 if (message.refMessageUri != null) {
700 // If we're editing an existing draft that was in reference to an existing message,
701 // still need to load that original message since we might need to refer to the
702 // original sender and recipients if user switches "reply <-> reply-all".
703 mRefMessageUri = message.refMessageUri;
704 mComposeMode = action;
705 getLoaderManager().initLoader(REFERENCE_MESSAGE_LOADER, null, this);
706 return;
707 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700708 } else if ((action == REPLY || action == REPLY_ALL || action == FORWARD)) {
709 if (mRefMessage != null) {
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -0800710 initFromRefMessage(action);
Alice Yanga990a712013-03-13 18:37:00 -0700711 mShowQuotedText = true;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700712 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700713 } else {
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700714 if (initFromExtras(intent)) {
715 return;
716 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700717 }
Alice Yanga990a712013-03-13 18:37:00 -0700718
719 mComposeMode = action;
Andy Huang9f855d62013-05-30 17:15:03 -0700720 finishSetup(action, intent, savedState);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700721 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700722
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -0700723 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
Alan Lau15490232014-03-06 14:53:14 -0800724 private static AsyncTask<Void, Void, Message> createWearReplyTask(
725 final ComposeActivity composeActivity,
726 final Uri refMessageUri, final String[] projection, final int action,
727 final String wearReply) {
728 return new AsyncTask<Void, Void, Message>() {
729 private Intent mEmptyServiceIntent = new Intent(composeActivity, EmptyService.class);
730
731 @Override
732 protected void onPreExecute() {
733 // Start service so we won't be killed if this app is put in the background.
734 composeActivity.startService(mEmptyServiceIntent);
735 }
736
737 @Override
738 protected Message doInBackground(Void... params) {
739 Cursor cursor = composeActivity.getContentResolver()
740 .query(refMessageUri, projection, null, null, null, null);
741 if (cursor != null) {
742 try {
743 cursor.moveToFirst();
744 return new Message(cursor);
745 } finally {
746 cursor.close();
747 }
748 }
749 return null;
750 }
751
752 @Override
753 protected void onPostExecute(Message message) {
754 composeActivity.stopService(mEmptyServiceIntent);
755
756 composeActivity.mRefMessage = message;
757 composeActivity.initFromRefMessage(action);
758 composeActivity.setBody(wearReply, false);
759 composeActivity.finishSetup(action, composeActivity.getIntent(), null);
760 composeActivity.sendOrSaveWithSanityChecks(false /* save */, true /* show toast */,
761 false /* orientationChanged */, true /* autoSend */);
762 }
763 };
764 }
765
Mindy Pereirab199d172012-08-13 11:04:03 -0700766 private void checkValidAccounts() {
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700767 final Account[] allAccounts = AccountUtils.getAccounts(this);
768 if (allAccounts == null || allAccounts.length == 0) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700769 final Intent noAccountIntent = MailAppProvider.getNoAccountIntent(this);
770 if (noAccountIntent != null) {
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700771 mAccounts = null;
Mindy Pereirab199d172012-08-13 11:04:03 -0700772 startActivityForResult(noAccountIntent, RESULT_CREATE_ACCOUNT);
773 }
774 } else {
mindyp26d4d2d2012-09-18 17:30:32 -0700775 // If none of the accounts are syncing, setup a watcher.
Mindy Pereirab199d172012-08-13 11:04:03 -0700776 boolean anySyncing = false;
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700777 for (Account a : allAccounts) {
Paul Westbrookdfa1dec2012-09-26 16:27:28 -0700778 if (a.isAccountReady()) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700779 anySyncing = true;
780 break;
781 }
782 }
783 if (!anySyncing) {
784 // There are accounts, but none are sync'd, which is just like having no accounts.
785 mAccounts = null;
786 getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, null, this);
787 return;
788 }
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700789 mAccounts = AccountUtils.getSyncingAccounts(this);
Mindy Pereirab199d172012-08-13 11:04:03 -0700790 finishCreate();
791 }
792 }
793
Mindy Pereira47d0e652012-07-23 09:45:07 -0700794 private Account obtainAccount(Intent intent) {
795 Account account = null;
796 Object accountExtra = null;
797 if (intent != null && intent.getExtras() != null) {
798 accountExtra = intent.getExtras().get(Utils.EXTRA_ACCOUNT);
799 if (accountExtra instanceof Account) {
800 return (Account) accountExtra;
mindyp7ae042e2012-08-27 13:27:37 -0700801 } else if (accountExtra instanceof String) {
802 // This is the Account attached to the widget compose intent.
Tony Mantler26a20752014-02-28 16:44:24 -0800803 account = Account.newInstance((String) accountExtra);
mindyp7ae042e2012-08-27 13:27:37 -0700804 if (account != null) {
805 return account;
806 }
Mindy Pereira47d0e652012-07-23 09:45:07 -0700807 }
mindyp5ee9dc42013-01-08 09:54:54 -0800808 accountExtra = intent.hasExtra(Utils.EXTRA_ACCOUNT) ?
809 intent.getStringExtra(Utils.EXTRA_ACCOUNT) :
810 intent.getStringExtra(EXTRA_SELECTED_ACCOUNT);
Mindy Pereira47d0e652012-07-23 09:45:07 -0700811 }
Tony Mantler581edd42014-02-18 15:41:22 -0800812
813 MailAppProvider provider = MailAppProvider.getInstance();
814 String lastAccountUri = provider.getLastSentFromAccount();
815 if (TextUtils.isEmpty(lastAccountUri)) {
816 lastAccountUri = provider.getLastViewedAccount();
Mindy Pereira47d0e652012-07-23 09:45:07 -0700817 }
Tony Mantler581edd42014-02-18 15:41:22 -0800818 if (!TextUtils.isEmpty(lastAccountUri)) {
819 accountExtra = Uri.parse(lastAccountUri);
820 }
821
Mindy Pereirab199d172012-08-13 11:04:03 -0700822 if (mAccounts != null && mAccounts.length > 0) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700823 if (accountExtra instanceof String && !TextUtils.isEmpty((String) accountExtra)) {
824 // For backwards compatibility, we need to check account
825 // names.
Mindy Pereirab199d172012-08-13 11:04:03 -0700826 for (Account a : mAccounts) {
Tony Mantler79b11562013-10-09 15:31:50 -0700827 if (a.getEmailAddress().equals(accountExtra)) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700828 account = a;
829 }
830 }
831 } else if (accountExtra instanceof Uri) {
832 // The uri of the last viewed account is what is stored in
833 // the current code base.
Mindy Pereirab199d172012-08-13 11:04:03 -0700834 for (Account a : mAccounts) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700835 if (a.uri.equals(accountExtra)) {
836 account = a;
837 }
838 }
Mindy Pereirab199d172012-08-13 11:04:03 -0700839 }
840 if (account == null) {
841 account = mAccounts[0];
Mindy Pereira47d0e652012-07-23 09:45:07 -0700842 }
843 }
844 return account;
845 }
846
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700847 protected void finishSetup(int action, Intent intent, Bundle savedInstanceState) {
mindyp34a3c562012-11-06 15:12:15 -0800848 setFocus(action);
Mindy Pereiraf7fc6c32012-06-19 15:18:33 -0700849 // Don't bother with the intent if we have procured a message from the
850 // intent already.
851 if (!hadSavedInstanceStateMessage(savedInstanceState)) {
852 initAttachmentsFromIntent(intent);
853 }
Alice Yanga990a712013-03-13 18:37:00 -0700854 initActionBar();
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700855 initFromSpinner(savedInstanceState != null ? savedInstanceState : intent.getExtras(),
856 action);
mindypd4a48662012-11-08 17:13:49 -0800857
858 // If this is a draft message, the draft account is whatever account was
859 // used to open the draft message in Compose.
860 if (mDraft != null) {
861 mDraftAccount = mReplyFromAccount;
862 }
863
Mindy Pereira75f66632012-01-11 11:42:02 -0800864 initChangeListeners();
Jin Cao32973b42014-05-06 16:12:11 -0700865
866 // These two should be identical since we check CC and BCC the same way
867 boolean showCc = !TextUtils.isEmpty(mCc.getText()) || (savedInstanceState != null &&
868 savedInstanceState.getBoolean(EXTRA_SHOW_CC));
869 boolean showBcc = !TextUtils.isEmpty(mBcc.getText()) || (savedInstanceState != null &&
870 savedInstanceState.getBoolean(EXTRA_SHOW_BCC));
871 mCcBccView.show(false /* animate */, showCc, showBcc);
Mindy Pereira326689d2012-05-17 10:14:14 -0700872 updateHideOrShowCcBcc();
Alice Yanga990a712013-03-13 18:37:00 -0700873 updateHideOrShowQuotedText(mShowQuotedText);
mindyp1623f9b2012-11-21 12:41:16 -0800874
Tony Mantler581edd42014-02-18 15:41:22 -0800875 mRespondedInline = mInnerSavedState != null &&
876 mInnerSavedState.getBoolean(EXTRA_RESPONDED_INLINE);
mindyp1623f9b2012-11-21 12:41:16 -0800877 if (mRespondedInline) {
878 mQuotedTextView.setVisibility(View.GONE);
879 }
Jin Cao1fdbe1f2014-08-19 13:51:26 -0700880
881 mTextChanged = (savedInstanceState != null) ?
882 savedInstanceState.getBoolean(EXTRA_TEXT_CHANGED) : false;
Mindy Pereira71c9e562012-05-17 11:01:02 -0700883 }
884
Scott Kennedyff8553f2013-04-05 20:57:44 -0700885 private static boolean hadSavedInstanceStateMessage(final Bundle savedInstanceState) {
Mindy Pereiraf7fc6c32012-06-19 15:18:33 -0700886 return savedInstanceState != null && savedInstanceState.containsKey(EXTRA_MESSAGE);
887 }
888
Mindy Pereira71c9e562012-05-17 11:01:02 -0700889 private void updateHideOrShowQuotedText(boolean showQuotedText) {
890 mQuotedTextView.updateCheckedState(showQuotedText);
mindyp40882432012-09-06 11:07:40 -0700891 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
Mindy Pereira433b1982012-04-03 11:53:07 -0700892 }
893
894 private void setFocus(int action) {
895 if (action == EDIT_DRAFT) {
896 int type = mDraft.draftType;
897 switch (type) {
898 case UIProvider.DraftType.COMPOSE:
899 case UIProvider.DraftType.FORWARD:
900 action = COMPOSE;
901 break;
902 case UIProvider.DraftType.REPLY:
903 case UIProvider.DraftType.REPLY_ALL:
904 default:
905 action = REPLY;
906 break;
907 }
908 }
909 switch (action) {
910 case FORWARD:
911 case COMPOSE:
mindyp27083062012-11-15 09:02:01 -0800912 if (TextUtils.isEmpty(mTo.getText())) {
913 mTo.requestFocus();
914 break;
915 }
Scott Kennedyff8553f2013-04-05 20:57:44 -0700916 //$FALL-THROUGH$
Mindy Pereira433b1982012-04-03 11:53:07 -0700917 case REPLY:
918 case REPLY_ALL:
919 default:
920 focusBody();
921 break;
922 }
923 }
924
925 /**
926 * Focus the body of the message.
927 */
Tony Mantler6a7ac782014-02-19 15:22:02 -0800928 private void focusBody() {
Mindy Pereira433b1982012-04-03 11:53:07 -0700929 mBodyView.requestFocus();
Tony Mantler6a7ac782014-02-19 15:22:02 -0800930 resetBodySelection();
931 }
Mindy Pereira433b1982012-04-03 11:53:07 -0700932
Tony Mantler6a7ac782014-02-19 15:22:02 -0800933 private void resetBodySelection() {
934 int length = mBodyView.getText().length();
Mindy Pereira433b1982012-04-03 11:53:07 -0700935 int signatureStartPos = getSignatureStartPosition(
936 mSignature, mBodyView.getText().toString());
937 if (signatureStartPos > -1) {
938 // In case the user deleted the newlines...
939 mBodyView.setSelection(signatureStartPos);
mindyp8743cfc2012-09-18 13:29:08 -0700940 } else if (length >= 0) {
Mindy Pereira433b1982012-04-03 11:53:07 -0700941 // Move cursor to the end.
942 mBodyView.setSelection(length);
943 }
Mindy Pereira1a95a572012-01-05 12:21:29 -0800944 }
945
946 @Override
Andy Huang761522c2013-08-08 13:09:11 -0700947 protected void onStart() {
948 super.onStart();
949
950 Analytics.getInstance().activityStart(this);
951 }
952
953 @Override
954 protected void onStop() {
955 super.onStop();
956
957 Analytics.getInstance().activityStop(this);
958 }
959
960 @Override
Mindy Pereira1a95a572012-01-05 12:21:29 -0800961 protected void onResume() {
962 super.onResume();
963 // Update the from spinner as other accounts
964 // may now be available.
Mindy Pereira818143e2012-01-11 13:59:49 -0800965 if (mFromSpinner != null && mAccount != null) {
Andrew Sappersteina01ddca2014-03-04 10:59:56 -0800966 mFromSpinner.initialize(mComposeMode, mAccount, mAccounts, mRefMessage);
Mindy Pereira818143e2012-01-11 13:59:49 -0800967 }
Mindy Pereira1a95a572012-01-05 12:21:29 -0800968 }
969
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800970 @Override
971 protected void onPause() {
972 super.onPause();
973
Mindy Pereiraa2148332012-07-02 13:54:14 -0700974 // When the user exits the compose view, see if this draft needs saving.
Yorke Lee3d7048e2012-09-19 14:19:25 -0700975 // Don't save unnecessary drafts if we are only changing the orientation.
976 if (!isChangingConfigurations()) {
Mindy Pereiraa2148332012-07-02 13:54:14 -0700977 saveIfNeeded();
Andy Huangdc97bf42013-08-15 16:52:45 -0700978
Andy Huange003b4c2013-08-16 10:32:05 -0700979 if (isFinishing() && !mPerformedSendOrDiscard && !isBlank()) {
Andy Huangdc97bf42013-08-15 16:52:45 -0700980 // log saving upon backing out of activity. (we avoid logging every sendOrSave()
981 // because that method can be invoked many times in a single compose session.)
982 logSendOrSave(true /* save */);
983 }
Mindy Pereiraa2148332012-07-02 13:54:14 -0700984 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800985 }
986
987 @Override
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -0700988 protected void onActivityResult(int request, int result, Intent data) {
Andy Huang5f082212014-06-11 22:19:21 -0700989 if (request == RESULT_PICK_ATTACHMENT) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700990 mAddingAttachment = false;
Andy Huang5f082212014-06-11 22:19:21 -0700991 if (result == RESULT_OK) {
992 addAttachmentAndUpdateView(data);
993 }
Mindy Pereirab199d172012-08-13 11:04:03 -0700994 } else if (request == RESULT_CREATE_ACCOUNT) {
Alice Yanga990a712013-03-13 18:37:00 -0700995 // We were waiting for the user to create an account
Mindy Pereirab199d172012-08-13 11:04:03 -0700996 if (result != RESULT_OK) {
997 finish();
998 } else {
999 // Watch for accounts to show up!
1000 // restart the loader to get the updated list of accounts
1001 getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, null, this);
1002 showWaitFragment(null);
1003 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001004 }
1005 }
1006
1007 @Override
Scott Kennedyd9063902013-08-02 22:14:37 -07001008 protected final void onRestoreInstanceState(Bundle savedInstanceState) {
Yorke Lee7bec2b92013-04-26 08:31:42 -07001009 final boolean hasAccounts = mAccounts != null && mAccounts.length > 0;
1010 if (hasAccounts) {
1011 clearChangeListeners();
1012 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001013 super.onRestoreInstanceState(savedInstanceState);
Andy Huang9f855d62013-05-30 17:15:03 -07001014 if (mInnerSavedState != null) {
1015 if (mInnerSavedState.containsKey(EXTRA_FOCUS_SELECTION_START)) {
1016 int selectionStart = mInnerSavedState.getInt(EXTRA_FOCUS_SELECTION_START);
1017 int selectionEnd = mInnerSavedState.getInt(EXTRA_FOCUS_SELECTION_END);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001018 // There should be a focus and it should be an EditText since we
1019 // only save these extras if these conditions are true.
1020 EditText focusEditText = (EditText) getCurrentFocus();
1021 final int length = focusEditText.getText().length();
1022 if (selectionStart < length && selectionEnd < length) {
1023 focusEditText.setSelection(selectionStart, selectionEnd);
1024 }
1025 }
1026 }
Yorke Lee7bec2b92013-04-26 08:31:42 -07001027 if (hasAccounts) {
1028 initChangeListeners();
1029 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001030 }
1031
1032 @Override
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07001033 protected void onSaveInstanceState(Bundle state) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001034 super.onSaveInstanceState(state);
Andy Huang9f855d62013-05-30 17:15:03 -07001035 final Bundle inner = new Bundle();
1036 saveState(inner);
1037 state.putBundle(KEY_INNER_SAVED_STATE, inner);
1038 }
1039
1040 private void saveState(Bundle state) {
Mindy Pereirab199d172012-08-13 11:04:03 -07001041 // We have no accounts so there is nothing to compose, and therefore, nothing to save.
1042 if (mAccounts == null || mAccounts.length == 0) {
1043 return;
1044 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001045 // The framework is happy to save and restore the selection but only if it also saves and
1046 // restores the contents of the edit text. That's a lot of text to put in a bundle so we do
1047 // this manually.
1048 View focus = getCurrentFocus();
1049 if (focus != null && focus instanceof EditText) {
1050 EditText focusEditText = (EditText) focus;
1051 state.putInt(EXTRA_FOCUS_SELECTION_START, focusEditText.getSelectionStart());
1052 state.putInt(EXTRA_FOCUS_SELECTION_END, focusEditText.getSelectionEnd());
1053 }
Paul Westbrook6273e962012-04-23 10:44:15 -07001054
1055 final List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
Paul Westbrook151f1ad2012-04-24 09:13:00 -07001056 final int selectedPos = mFromSpinner.getSelectedItemPosition();
Mindy Pereirad90f7ac2012-06-27 10:31:06 -07001057 final ReplyFromAccount selectedReplyFromAccount = (replyFromAccounts != null
1058 && replyFromAccounts.size() > 0 && replyFromAccounts.size() > selectedPos) ?
1059 replyFromAccounts.get(selectedPos) : null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001060 if (selectedReplyFromAccount != null) {
1061 state.putString(EXTRA_SELECTED_REPLY_FROM_ACCOUNT, selectedReplyFromAccount.serialize()
1062 .toString());
1063 state.putParcelable(Utils.EXTRA_ACCOUNT, selectedReplyFromAccount.account);
1064 } else {
1065 state.putParcelable(Utils.EXTRA_ACCOUNT, mAccount);
1066 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001067
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001068 if (mDraftId == UIProvider.INVALID_MESSAGE_ID && mRequestId !=0) {
1069 // We don't have a draft id, and we have a request id,
1070 // save the request id.
1071 state.putInt(EXTRA_REQUEST_ID, mRequestId);
1072 }
1073
1074 // We want to restore the current mode after a pause
1075 // or rotation.
1076 int mode = getMode();
1077 state.putInt(EXTRA_ACTION, mode);
1078
Jin Cao77b4c2c2014-05-20 13:55:53 -07001079 final Message message = createMessage(selectedReplyFromAccount, mRefMessage, mode,
1080 removeComposingSpans(mBodyView.getText()));
Andy Huang1f8f4dd2012-10-25 21:35:35 -07001081 if (mDraft != null) {
mindype7b76aa2012-11-14 16:19:13 -08001082 message.id = mDraft.id;
1083 message.serverId = mDraft.serverId;
1084 message.uri = mDraft.uri;
Andy Huang1f8f4dd2012-10-25 21:35:35 -07001085 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001086 state.putParcelable(EXTRA_MESSAGE, message);
1087
1088 if (mRefMessage != null) {
1089 state.putParcelable(EXTRA_IN_REFERENCE_TO_MESSAGE, mRefMessage);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001090 } else if (message.appendRefMessageContent) {
1091 // If we have no ref message but should be appending
1092 // ref message content, we have orphaned quoted text. Save it.
1093 state.putCharSequence(EXTRA_QUOTED_TEXT, mQuotedTextView.getQuotedTextIfIncluded());
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001094 }
Mindy Pereira326689d2012-05-17 10:14:14 -07001095 state.putBoolean(EXTRA_SHOW_CC, mCcBccView.isCcVisible());
1096 state.putBoolean(EXTRA_SHOW_BCC, mCcBccView.isBccVisible());
mindyp1623f9b2012-11-21 12:41:16 -08001097 state.putBoolean(EXTRA_RESPONDED_INLINE, mRespondedInline);
mindyp816b3f02012-12-11 08:25:04 -08001098 state.putBoolean(EXTRA_SAVE_ENABLED, mSave != null && mSave.isEnabled());
Mark Wei62066e42012-09-13 12:07:02 -07001099 state.putParcelableArrayList(
1100 EXTRA_ATTACHMENT_PREVIEWS, mAttachmentsView.getAttachmentPreviews());
Scott Kennedy44d44812013-08-19 14:18:31 -07001101
1102 state.putParcelable(EXTRA_VALUES, mExtraValues);
Jin Cao1fdbe1f2014-08-19 13:51:26 -07001103
1104 state.putBoolean(EXTRA_TEXT_CHANGED, mTextChanged);
1105 // On configuration changes, we don't actually need to parse the body html ourselves because
1106 // the framework can correctly restore the body EditText to its exact original state.
1107 state.putBoolean(EXTRA_SKIP_PARSING_BODY, isChangingConfigurations());
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001108 }
1109
1110 private int getMode() {
1111 int mode = ComposeActivity.COMPOSE;
Andrew Sapperstein52882ff2014-07-27 12:30:18 -07001112 final ActionBar actionBar = getSupportActionBar();
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001113 if (actionBar != null
1114 && actionBar.getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001115 mode = actionBar.getSelectedNavigationIndex();
1116 }
1117 return mode;
1118 }
1119
Jin Cao77b4c2c2014-05-20 13:55:53 -07001120 /**
1121 * This function might be called from a background thread, so be sure to move everything that
1122 * can potentially modify the UI to the main thread (e.g. removeComposingSpans for body).
1123 */
Anthony Lee2a3cc132014-04-22 14:15:25 -07001124 private Message createMessage(ReplyFromAccount selectedReplyFromAccount, Message refMessage,
Jin Cao77b4c2c2014-05-20 13:55:53 -07001125 int mode, Spanned body) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001126 Message message = new Message();
1127 message.id = UIProvider.INVALID_MESSAGE_ID;
Andy Huangd47877e2012-08-09 19:31:24 -07001128 message.serverId = null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001129 message.uri = null;
1130 message.conversationUri = null;
1131 message.subject = mSubject.getText().toString();
1132 message.snippet = null;
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001133 message.setTo(formatSenders(mTo.getText().toString()));
1134 message.setCc(formatSenders(mCc.getText().toString()));
1135 message.setBcc(formatSenders(mBcc.getText().toString()));
1136 message.setReplyTo(null);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001137 message.dateReceivedMs = 0;
Jin Cao77b4c2c2014-05-20 13:55:53 -07001138 message.bodyHtml = spannedBodyToHtml(body, true);
Jin Cao7800d292014-08-24 11:31:15 -07001139 message.bodyText = body.toString();
Jin Cao0a8e8222014-10-02 11:27:52 -07001140 // Fallback to use the text version if html conversion fails for whatever the reason.
Jin Caoefd62cb2014-10-02 17:50:07 -07001141 final String htmlInPlainText = Utils.convertHtmlToPlainText(message.bodyHtml);
Jin Cao0d9a37e2014-10-14 12:07:29 -07001142 if (message.bodyText != null && message.bodyText.trim().length() > 0 &&
1143 TextUtils.isEmpty(htmlInPlainText)) {
Jin Caoefd62cb2014-10-02 17:50:07 -07001144 LogUtils.w(LOG_TAG, "FAILED HTML CONVERSION: from %d to %d", message.bodyText.length(),
1145 htmlInPlainText.length());
Régis Décampse70f67a2016-02-23 16:16:54 +01001146 Analytics.getInstance().sendEvent(ANALYTICS_CATEGORY_ERRORS,
1147 "failed_html_conversion", null, 0);
Jin Cao0a8e8222014-10-02 11:27:52 -07001148 message.bodyHtml = "<p>" + message.bodyText + "</p>";
1149 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001150 message.embedsExternalResources = false;
Alice Yanga990a712013-03-13 18:37:00 -07001151 message.refMessageUri = mRefMessage != null ? mRefMessage.uri : null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001152 message.appendRefMessageContent = mQuotedTextView.getQuotedTextIfIncluded() != null;
1153 ArrayList<Attachment> attachments = mAttachmentsView.getAttachments();
1154 message.hasAttachments = attachments != null && attachments.size() > 0;
1155 message.attachmentListUri = null;
1156 message.messageFlags = 0;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001157 message.alwaysShowImages = false;
1158 message.attachmentsJson = Attachment.toJSONArray(attachments);
1159 CharSequence quotedText = mQuotedTextView.getQuotedText();
Anthony Lee2a3cc132014-04-22 14:15:25 -07001160 message.quotedTextOffset = -1; // Just a default value.
1161 if (refMessage != null && !TextUtils.isEmpty(quotedText)) {
1162 if (!TextUtils.isEmpty(refMessage.bodyHtml)) {
1163 // We want the index to point to just the quoted text and not the
1164 // "On December 25, 2014..." part of it.
1165 message.quotedTextOffset =
1166 QuotedTextView.getQuotedTextOffset(quotedText.toString());
1167 } else if (!TextUtils.isEmpty(refMessage.bodyText)) {
1168 // We want to point to the entire quoted text.
1169 message.quotedTextOffset = QuotedTextView.findQuotedTextIndex(quotedText);
1170 }
1171 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001172 message.accountUri = null;
Greg Bullock14fd3042014-08-12 09:21:15 +02001173 message.setFrom(computeFromForAccount(selectedReplyFromAccount));
1174 message.draftType = getDraftType(mode);
1175 return message;
1176 }
1177
1178 protected String computeFromForAccount(ReplyFromAccount selectedReplyFromAccount) {
Tony Mantlerbb036ff72013-10-18 14:03:43 -07001179 final String email = selectedReplyFromAccount != null ? selectedReplyFromAccount.address
1180 : mAccount != null ? mAccount.getEmailAddress() : null;
Tony Mantlerf441d142013-10-22 11:46:00 -07001181 final String senderName = selectedReplyFromAccount != null ? selectedReplyFromAccount.name
1182 : mAccount != null ? mAccount.getSenderName() : null;
Tony Mantler821e5782014-01-06 15:33:43 -08001183 final Address address = new Address(email, senderName);
Greg Bullock14fd3042014-08-12 09:21:15 +02001184 return address.toHeader();
Andy Huang1f8f4dd2012-10-25 21:35:35 -07001185 }
1186
Scott Kennedyff8553f2013-04-05 20:57:44 -07001187 private static String formatSenders(final String string) {
Mindy Pereira3c911582012-08-09 16:59:09 -07001188 if (!TextUtils.isEmpty(string) && string.charAt(string.length() - 1) == ',') {
1189 return string.substring(0, string.length() - 1);
1190 }
1191 return string;
1192 }
1193
Mindy Pereira818143e2012-01-11 13:59:49 -08001194 @VisibleForTesting
Andy Huang91ede362014-01-21 19:16:00 -08001195 protected void setAccount(Account account) {
Mindy Pereirabb5217e2012-04-17 11:08:29 -07001196 if (account == null) {
1197 return;
1198 }
Mindy Pereira23e9fde2012-03-20 15:08:24 -07001199 if (!account.equals(mAccount)) {
1200 mAccount = account;
Paul Westbrookb1f573c2012-04-06 11:38:28 -07001201 mCachedSettings = mAccount.settings;
1202 appendSignature();
Mindy Pereira23e9fde2012-03-20 15:08:24 -07001203 }
Mindy Pereirafa20c1a2012-07-23 13:00:02 -07001204 if (mAccount != null) {
Tony Mantler79b11562013-10-09 15:31:50 -07001205 MailActivity.setNfcMessage(mAccount.getEmailAddress());
Mindy Pereirafa20c1a2012-07-23 13:00:02 -07001206 }
Mindy Pereira818143e2012-01-11 13:59:49 -08001207 }
1208
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001209 private void initFromSpinner(Bundle bundle, int action) {
1210 if (action == EDIT_DRAFT && mDraft.draftType == UIProvider.DraftType.COMPOSE) {
Mindy Pereira62de1b12012-04-06 12:17:56 -07001211 action = COMPOSE;
1212 }
Andrew Sappersteina01ddca2014-03-04 10:59:56 -08001213 mFromSpinner.initialize(action, mAccount, mAccounts, mRefMessage);
Paul Westbrookc97ec3e2013-07-12 18:17:19 -07001214
Mindy Pereira9a42bb42012-04-18 15:21:33 -07001215 if (bundle != null) {
1216 if (bundle.containsKey(EXTRA_SELECTED_REPLY_FROM_ACCOUNT)) {
1217 mReplyFromAccount = ReplyFromAccount.deserialize(mAccount,
1218 bundle.getString(EXTRA_SELECTED_REPLY_FROM_ACCOUNT));
1219 } else if (bundle.containsKey(EXTRA_FROM_ACCOUNT_STRING)) {
Paul Westbrookc97ec3e2013-07-12 18:17:19 -07001220 final String accountString = bundle.getString(EXTRA_FROM_ACCOUNT_STRING);
Mindy Pereira9a42bb42012-04-18 15:21:33 -07001221 mReplyFromAccount = mFromSpinner.getMatchingReplyFromAccount(accountString);
1222 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001223 }
1224 if (mReplyFromAccount == null) {
1225 if (mDraft != null) {
Jin Cao24c892d2014-09-29 11:06:03 -07001226 mReplyFromAccount = getReplyFromAccountFromDraft(mDraft);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001227 } else if (mRefMessage != null) {
1228 mReplyFromAccount = getReplyFromAccountForReply(mAccount, mRefMessage);
1229 }
Mindy Pereira62de1b12012-04-06 12:17:56 -07001230 }
1231 if (mReplyFromAccount == null) {
Andy Huang238aa472012-10-30 17:45:17 -07001232 mReplyFromAccount = getDefaultReplyFromAccount(mAccount);
Mindy Pereira62de1b12012-04-06 12:17:56 -07001233 }
Mindy Pereira9a42bb42012-04-18 15:21:33 -07001234
Mindy Pereira62de1b12012-04-06 12:17:56 -07001235 mFromSpinner.setCurrentAccount(mReplyFromAccount);
Mindy Pereira9a42bb42012-04-18 15:21:33 -07001236
Mindy Pereira62de1b12012-04-06 12:17:56 -07001237 if (mFromSpinner.getCount() > 1) {
Mindy Pereiraa83e7082012-03-30 08:53:11 -07001238 // If there is only 1 account, just show that account.
1239 // Otherwise, give the user the ability to choose which account to
Mindy Pereira62de1b12012-04-06 12:17:56 -07001240 // send mail from / save drafts to.
1241 mFromStatic.setVisibility(View.GONE);
Andy Huangca4676f2014-01-16 13:22:20 -08001242 mFromStaticText.setText(mReplyFromAccount.address);
Mindy Pereira62de1b12012-04-06 12:17:56 -07001243 mFromSpinnerWrapper.setVisibility(View.VISIBLE);
Mindy Pereiraa83e7082012-03-30 08:53:11 -07001244 } else {
1245 mFromStatic.setVisibility(View.VISIBLE);
Andy Huangca4676f2014-01-16 13:22:20 -08001246 mFromStaticText.setText(mReplyFromAccount.address);
Mindy Pereiraa83e7082012-03-30 08:53:11 -07001247 mFromSpinnerWrapper.setVisibility(View.GONE);
Mindy Pereiraa83e7082012-03-30 08:53:11 -07001248 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001249 }
1250
Mindy Pereira62de1b12012-04-06 12:17:56 -07001251 private ReplyFromAccount getReplyFromAccountForReply(Account account, Message refMessage) {
1252 if (refMessage.accountUri != null) {
1253 // This must be from combined inbox.
1254 List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
1255 for (ReplyFromAccount from : replyFromAccounts) {
1256 if (from.account.uri.equals(refMessage.accountUri)) {
1257 return from;
1258 }
1259 }
1260 return null;
1261 } else {
1262 return getReplyFromAccount(account, refMessage);
1263 }
1264 }
1265
1266 /**
Tony Mantler9016a5e2013-07-19 11:54:17 -07001267 * Given an account and the message we're replying to,
Mindy Pereira62de1b12012-04-06 12:17:56 -07001268 * return who the message should be sent from.
1269 * @param account Account in which the message arrived.
Tony Mantler9016a5e2013-07-19 11:54:17 -07001270 * @param refMessage Message to analyze for account selection
Mindy Pereira62de1b12012-04-06 12:17:56 -07001271 * @return the address from which to reply.
1272 */
1273 public ReplyFromAccount getReplyFromAccount(Account account, Message refMessage) {
1274 // First see if we are supposed to use the default address or
1275 // the address it was sentTo.
Mindy Pereira326689d2012-05-17 10:14:14 -07001276 if (mCachedSettings.forceReplyFromDefault) {
Mindy Pereira62de1b12012-04-06 12:17:56 -07001277 return getDefaultReplyFromAccount(account);
1278 } else {
Mindy Pereira89bae572012-06-18 11:34:36 -07001279 // If we aren't explicitly told which account to look for, look at
Mindy Pereira62de1b12012-04-06 12:17:56 -07001280 // all the message recipients and find one that matches
1281 // a custom from or account.
1282 List<String> allRecipients = new ArrayList<String>();
Tony Mantler9016a5e2013-07-19 11:54:17 -07001283 allRecipients.addAll(Arrays.asList(refMessage.getToAddressesUnescaped()));
1284 allRecipients.addAll(Arrays.asList(refMessage.getCcAddressesUnescaped()));
Mindy Pereira62de1b12012-04-06 12:17:56 -07001285 return getMatchingRecipient(account, allRecipients);
1286 }
1287 }
1288
1289 /**
1290 * Compare all the recipients of an email to the current account and all
1291 * custom addresses associated with that account. Return the match if there
1292 * is one, or the default account if there isn't.
1293 */
1294 protected ReplyFromAccount getMatchingRecipient(Account account, List<String> sentTo) {
1295 // Tokenize the list and place in a hashmap.
1296 ReplyFromAccount matchingReplyFrom = null;
1297 Rfc822Token[] tokens;
1298 HashSet<String> recipientsMap = new HashSet<String>();
1299 for (String address : sentTo) {
1300 tokens = Rfc822Tokenizer.tokenize(address);
Tony Mantler581edd42014-02-18 15:41:22 -08001301 for (final Rfc822Token token : tokens) {
1302 recipientsMap.add(token.getAddress());
Mindy Pereira62de1b12012-04-06 12:17:56 -07001303 }
1304 }
1305
1306 int matchingAddressCount = 0;
1307 List<ReplyFromAccount> customFroms;
Andy Huang16174812012-08-16 16:40:35 -07001308 customFroms = account.getReplyFroms();
1309 if (customFroms != null) {
1310 for (ReplyFromAccount entry : customFroms) {
1311 if (recipientsMap.contains(entry.address)) {
1312 matchingReplyFrom = entry;
1313 matchingAddressCount++;
Mindy Pereira62de1b12012-04-06 12:17:56 -07001314 }
1315 }
Mindy Pereira62de1b12012-04-06 12:17:56 -07001316 }
1317 if (matchingAddressCount > 1) {
1318 matchingReplyFrom = getDefaultReplyFromAccount(account);
1319 }
1320 return matchingReplyFrom;
1321 }
1322
Scott Kennedyff8553f2013-04-05 20:57:44 -07001323 private static ReplyFromAccount getDefaultReplyFromAccount(final Account account) {
1324 for (final ReplyFromAccount from : account.getReplyFroms()) {
Mindy Pereira62de1b12012-04-06 12:17:56 -07001325 if (from.isDefault) {
1326 return from;
1327 }
1328 }
Tony Mantlerf441d142013-10-22 11:46:00 -07001329 return new ReplyFromAccount(account, account.uri, account.getEmailAddress(),
1330 account.getSenderName(), account.getEmailAddress(), true, false);
Mindy Pereira62de1b12012-04-06 12:17:56 -07001331 }
1332
Jin Cao24c892d2014-09-29 11:06:03 -07001333 private ReplyFromAccount getReplyFromAccountFromDraft(final Message msg) {
Tony Mantlerf441d142013-10-22 11:46:00 -07001334 final Address[] draftFroms = Address.parse(msg.getFrom());
1335 final String sender = draftFroms.length > 0 ? draftFroms[0].getAddress() : "";
Mindy Pereira62de1b12012-04-06 12:17:56 -07001336 ReplyFromAccount replyFromAccount = null;
Jin Cao24c892d2014-09-29 11:06:03 -07001337 // Do not try to check against the "default" account because the default might be an alias.
1338 for (ReplyFromAccount fromAccount : mFromSpinner.getReplyFromAccounts()) {
1339 if (TextUtils.equals(fromAccount.address, sender)) {
1340 replyFromAccount = fromAccount;
1341 break;
Mindy Pereira62de1b12012-04-06 12:17:56 -07001342 }
1343 }
1344 return replyFromAccount;
1345 }
1346
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001347 private void findViews() {
Jin Cao36e23872014-07-29 13:41:12 -07001348 mScrollView = (ScrollView) findViewById(R.id.compose);
1349 mScrollView.setVisibility(View.VISIBLE);
Jin Cao9d358a12014-07-24 12:15:38 -07001350 mCcBccButton = findViewById(R.id.add_cc_bcc);
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001351 if (mCcBccButton != null) {
1352 mCcBccButton.setOnClickListener(this);
1353 }
1354 mCcBccView = (CcBccView) findViewById(R.id.cc_bcc_wrapper);
Mindy Pereira7b56a612011-12-14 12:32:28 -08001355 mAttachmentsView = (AttachmentsView)findViewById(R.id.attachments);
Mindy Pereira818143e2012-01-11 13:59:49 -08001356 mTo = (RecipientEditTextView) findViewById(R.id.to);
Jin Cao23ab6ea2014-09-24 15:28:18 -07001357 mTo.setOnKeyListener(mKeyListenerForSendShortcut);
Andrew Sapperstein09da9422014-05-30 09:48:08 -07001358 initializeRecipientEditTextView(mTo);
Jin Cao15f09d72014-08-08 13:27:34 -07001359 mTo.setAlternatePopupAnchor(findViewById(R.id.compose_to_dropdown_anchor));
Mindy Pereira818143e2012-01-11 13:59:49 -08001360 mCc = (RecipientEditTextView) findViewById(R.id.cc);
Jin Cao23ab6ea2014-09-24 15:28:18 -07001361 mCc.setOnKeyListener(mKeyListenerForSendShortcut);
Andrew Sapperstein09da9422014-05-30 09:48:08 -07001362 initializeRecipientEditTextView(mCc);
Mindy Pereira818143e2012-01-11 13:59:49 -08001363 mBcc = (RecipientEditTextView) findViewById(R.id.bcc);
Jin Cao23ab6ea2014-09-24 15:28:18 -07001364 mBcc.setOnKeyListener(mKeyListenerForSendShortcut);
Andrew Sapperstein09da9422014-05-30 09:48:08 -07001365 initializeRecipientEditTextView(mBcc);
Mindy Pereira82cc5662012-01-09 17:29:30 -08001366 // TODO: add special chips text change watchers before adding
1367 // this as a text changed watcher to the to, cc, bcc fields.
Mindy Pereira6349a042012-01-04 11:25:01 -08001368 mSubject = (TextView) findViewById(R.id.subject);
Jin Cao23ab6ea2014-09-24 15:28:18 -07001369 mSubject.setOnKeyListener(mKeyListenerForSendShortcut);
mindyp62d3ec72012-08-24 13:04:09 -07001370 mSubject.setOnEditorActionListener(this);
Jin Caoc5c550a2014-07-29 11:53:17 -07001371 mSubject.setOnFocusChangeListener(this);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001372 mQuotedTextView = (QuotedTextView) findViewById(R.id.quoted_text_view);
1373 mQuotedTextView.setRespondInlineListener(this);
Mindy Pereira433b1982012-04-03 11:53:07 -07001374 mBodyView = (EditText) findViewById(R.id.body);
Jin Cao23ab6ea2014-09-24 15:28:18 -07001375 mBodyView.setOnKeyListener(mKeyListenerForSendShortcut);
Jin Caoc5c550a2014-07-29 11:53:17 -07001376 mBodyView.setOnFocusChangeListener(this);
Mindy Pereira1a95a572012-01-05 12:21:29 -08001377 mFromStatic = findViewById(R.id.static_from_content);
Mindy Pereira2eb17322012-03-07 10:07:34 -08001378 mFromStaticText = (TextView) findViewById(R.id.from_account_name);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001379 mFromSpinnerWrapper = findViewById(R.id.spinner_from_content);
Mindy Pereira5a85e2b2012-01-11 09:53:32 -08001380 mFromSpinner = (FromAddressSpinner) findViewById(R.id.from_picker);
Jin Cao95b8a7b2014-09-02 16:45:42 -07001381
1382 // Bottom placeholder to forward click events to the body
1383 findViewById(R.id.composearea_tap_trap_bottom).setOnClickListener(new OnClickListener() {
1384 @Override
1385 public void onClick(View v) {
1386 mBodyView.requestFocus();
1387 mBodyView.setSelection(mBodyView.getText().length());
1388 }
1389 });
Mindy Pereira6349a042012-01-04 11:25:01 -08001390 }
1391
Andrew Sapperstein09da9422014-05-30 09:48:08 -07001392 private void initializeRecipientEditTextView(RecipientEditTextView view) {
1393 view.setTokenizer(new Rfc822Tokenizer());
1394 view.setThreshold(COMPLETION_THRESHOLD);
1395 }
1396
mindyp62d3ec72012-08-24 13:04:09 -07001397 @Override
1398 public boolean onEditorAction(TextView view, int action, KeyEvent keyEvent) {
1399 if (action == EditorInfo.IME_ACTION_DONE) {
1400 focusBody();
1401 return true;
1402 }
1403 return false;
1404 }
1405
Andy Huang91ede362014-01-21 19:16:00 -08001406 /**
1407 * Convert the body text (in {@link Spanned} form) to ready-to-send HTML format as a plain
1408 * String.
1409 *
1410 * @param body the body text including fancy style spans
Jin Cao77b4c2c2014-05-20 13:55:53 -07001411 * @param removedComposing whether the function already removed composingSpans. Necessary
1412 * because we cannot call removeComposingSpans from a background thread.
Andy Huang91ede362014-01-21 19:16:00 -08001413 * @return HTML formatted body that's suitable for sending or saving
1414 */
Jin Cao77b4c2c2014-05-20 13:55:53 -07001415 private String spannedBodyToHtml(Spanned body, boolean removedComposing) {
1416 if (!removedComposing) {
1417 body = removeComposingSpans(body);
1418 }
1419 final HtmlifyBeginResult r = onHtmlifyBegin(body);
Andy Huang91ede362014-01-21 19:16:00 -08001420 return onHtmlifyEnd(Html.toHtml(r.result), r.extras);
1421 }
1422
1423 /**
1424 * A hook for subclasses to convert custom spans in the body text prior to system HTML
1425 * conversion. That HTML conversion is lossy, so anything above and beyond its capability
1426 * has to be handled here.
1427 *
1428 * @param body
1429 * @return a copy of the body text with custom spans replaced with HTML
1430 */
1431 protected HtmlifyBeginResult onHtmlifyBegin(Spanned body) {
1432 return new HtmlifyBeginResult(body, null /* extras */);
1433 }
1434
1435 protected String onHtmlifyEnd(String html, Object extras) {
1436 return html;
1437 }
1438
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001439 protected TextView getBody() {
1440 return mBodyView;
1441 }
1442
1443 @VisibleForTesting
Andy Huang0a2a3462013-12-20 15:56:13 -08001444 public String getBodyHtml() {
Jin Cao77b4c2c2014-05-20 13:55:53 -07001445 return spannedBodyToHtml(mBodyView.getText(), false);
Andy Huang0a2a3462013-12-20 15:56:13 -08001446 }
1447
1448 @VisibleForTesting
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001449 public Account getFromAccount() {
1450 return mReplyFromAccount != null && mReplyFromAccount.account != null ?
1451 mReplyFromAccount.account : mAccount;
1452 }
1453
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07001454 private void clearChangeListeners() {
1455 mSubject.removeTextChangedListener(this);
1456 mBodyView.removeTextChangedListener(this);
1457 mTo.removeTextChangedListener(mToListener);
1458 mCc.removeTextChangedListener(mCcListener);
1459 mBcc.removeTextChangedListener(mBccListener);
1460 mFromSpinner.setOnAccountChangedListener(null);
1461 mAttachmentsView.setAttachmentChangesListener(null);
1462 }
1463
Mindy Pereira75f66632012-01-11 11:42:02 -08001464 // Now that the message has been initialized from any existing draft or
1465 // ref message data, set up listeners for any changes that occur to the
1466 // message.
1467 private void initChangeListeners() {
mindyp1d7e9142012-11-21 13:54:30 -08001468 // Make sure we only add text changed listeners once!
1469 clearChangeListeners();
Mindy Pereira75f66632012-01-11 11:42:02 -08001470 mSubject.addTextChangedListener(this);
1471 mBodyView.addTextChangedListener(this);
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07001472 if (mToListener == null) {
1473 mToListener = new RecipientTextWatcher(mTo, this);
1474 }
1475 mTo.addTextChangedListener(mToListener);
1476 if (mCcListener == null) {
1477 mCcListener = new RecipientTextWatcher(mCc, this);
1478 }
1479 mCc.addTextChangedListener(mCcListener);
1480 if (mBccListener == null) {
1481 mBccListener = new RecipientTextWatcher(mBcc, this);
1482 }
1483 mBcc.addTextChangedListener(mBccListener);
Mindy Pereira75f66632012-01-11 11:42:02 -08001484 mFromSpinner.setOnAccountChangedListener(this);
Mindy Pereira818143e2012-01-11 13:59:49 -08001485 mAttachmentsView.setAttachmentChangesListener(this);
Mindy Pereira75f66632012-01-11 11:42:02 -08001486 }
1487
Alice Yanga990a712013-03-13 18:37:00 -07001488 private void initActionBar() {
1489 LogUtils.d(LOG_TAG, "initializing action bar in ComposeActivity");
Andrew Sapperstein52882ff2014-07-27 12:30:18 -07001490 final ActionBar actionBar = getSupportActionBar();
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001491 if (actionBar == null) {
1492 return;
1493 }
Alice Yanga990a712013-03-13 18:37:00 -07001494 if (mComposeMode == ComposeActivity.COMPOSE) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001495 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
Jin Caof0a0b4c2014-08-20 15:35:50 -07001496 actionBar.setTitle(R.string.compose_title);
Mindy Pereira326c6602012-01-04 15:32:42 -08001497 } else {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001498 actionBar.setTitle(null);
Mindy Pereira326c6602012-01-04 15:32:42 -08001499 if (mComposeModeAdapter == null) {
Jin Caof7461632014-08-11 15:21:43 -07001500 mComposeModeAdapter = new ComposeModeAdapter(actionBar.getThemedContext());
Mindy Pereira326c6602012-01-04 15:32:42 -08001501 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001502 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
1503 actionBar.setListNavigationCallbacks(mComposeModeAdapter, this);
Alice Yanga990a712013-03-13 18:37:00 -07001504 switch (mComposeMode) {
Mindy Pereira326c6602012-01-04 15:32:42 -08001505 case ComposeActivity.REPLY:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001506 actionBar.setSelectedNavigationItem(0);
Mindy Pereira326c6602012-01-04 15:32:42 -08001507 break;
1508 case ComposeActivity.REPLY_ALL:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001509 actionBar.setSelectedNavigationItem(1);
Mindy Pereira326c6602012-01-04 15:32:42 -08001510 break;
1511 case ComposeActivity.FORWARD:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001512 actionBar.setSelectedNavigationItem(2);
Mindy Pereira326c6602012-01-04 15:32:42 -08001513 break;
1514 }
1515 }
Paul Westbrook4def3bf2014-07-01 00:38:17 -07001516 actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP,
1517 ActionBar.DISPLAY_HOME_AS_UP);
Mindy Pereirafbe40192012-03-20 10:40:45 -07001518 actionBar.setHomeButtonEnabled(true);
Mindy Pereira326c6602012-01-04 15:32:42 -08001519 }
1520
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08001521 private void initFromRefMessage(int action) {
1522 setFieldsFromRefMessage(action);
Alice Yang1ebc2db2013-03-14 21:21:44 -07001523
1524 // Check if To: address and email body needs to be prefilled based on extras.
1525 // This is used for reporting rendering feedback.
1526 if (MessageHeaderView.ENABLE_REPORT_RENDERING_PROBLEM) {
1527 Intent intent = getIntent();
1528 if (intent.getExtras() != null) {
1529 String toAddresses = intent.getStringExtra(EXTRA_TO);
1530 if (toAddresses != null) {
1531 addToAddresses(Arrays.asList(TextUtils.split(toAddresses, ",")));
1532 }
1533 String body = intent.getStringExtra(EXTRA_BODY);
1534 if (body != null) {
1535 setBody(body, false /* withSignature */);
1536 }
1537 }
1538 }
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07001539 }
1540
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08001541 private void setFieldsFromRefMessage(int action) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001542 setSubject(mRefMessage, action);
1543 // Setup recipients
1544 if (action == FORWARD) {
1545 mForward = true;
Mindy Pereira6349a042012-01-04 11:25:01 -08001546 }
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08001547 initRecipientsFromRefMessage(mRefMessage, action);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001548 initQuotedTextFromRefMessage(mRefMessage, action);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001549 if (action == ComposeActivity.FORWARD || mAttachmentsChanged) {
1550 initAttachments(mRefMessage);
1551 }
Mindy Pereirac17d0732011-12-29 10:46:19 -08001552 }
1553
Andy Huang9ed742c2014-06-18 02:34:50 -07001554 protected HtmlTree.Converter<Spanned> getSpanConverter() {
1555 return new HtmlUtils.SpannedConverter();
1556 }
1557
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001558 private void initFromDraftMessage(Message message) {
Jin Cao31bb3d62014-09-11 14:01:43 -07001559 LogUtils.d(LOG_TAG, "Initializing draft from previous draft message: %s", message);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001560
Jin Cao31bb3d62014-09-11 14:01:43 -07001561 synchronized (mDraftLock) {
1562 // Draft id might already be set by the request to id map, if so we don't need to set it
1563 if (mDraftId == UIProvider.INVALID_MESSAGE_ID) {
1564 mDraftId = message.id;
1565 } else {
1566 message.id = mDraftId;
1567 }
1568 mDraft = message;
1569 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001570 mSubject.setText(message.subject);
1571 mForward = message.draftType == UIProvider.DraftType.FORWARD;
Jin Cao1fdbe1f2014-08-19 13:51:26 -07001572
Tony Mantler9016a5e2013-07-19 11:54:17 -07001573 final List<String> toAddresses = Arrays.asList(message.getToAddressesUnescaped());
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001574 addToAddresses(toAddresses);
Tony Mantler9016a5e2013-07-19 11:54:17 -07001575 addCcAddresses(Arrays.asList(message.getCcAddressesUnescaped()), toAddresses);
1576 addBccAddresses(Arrays.asList(message.getBccAddressesUnescaped()));
Mindy Pereira2421dc82012-03-27 13:32:31 -07001577 if (message.hasAttachments) {
1578 List<Attachment> attachments = message.getAttachments();
1579 for (Attachment a : attachments) {
Andy Huang5c5fd572012-04-08 18:19:29 -07001580 addAttachmentAndUpdateView(a);
Mindy Pereira2421dc82012-03-27 13:32:31 -07001581 }
1582 }
Jin Cao1fdbe1f2014-08-19 13:51:26 -07001583
1584 // If we don't need to re-populate the body, and the quoted text will be restored from
1585 // ref message. So we can skip rest of this code.
1586 if (mInnerSavedState != null && mInnerSavedState.getBoolean(EXTRA_SKIP_PARSING_BODY)) {
1587 LogUtils.i(LOG_TAG, "Skipping manually populating body and quoted text from draft.");
1588 return;
1589 }
1590
Anthony Lee2a3cc132014-04-22 14:15:25 -07001591 int quotedTextIndex = message.appendRefMessageContent ? message.quotedTextOffset : -1;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001592 // Set the body
Mindy Pereira002ff522012-05-30 10:31:26 -07001593 CharSequence quotedText = null;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001594 if (!TextUtils.isEmpty(message.bodyHtml)) {
Jin Cao32f453b2014-07-22 14:21:15 -07001595 String body = message.bodyHtml;
Mindy Pereira002ff522012-05-30 10:31:26 -07001596 if (quotedTextIndex > -1) {
Anthony Lee2a3cc132014-04-22 14:15:25 -07001597 // Find the offset in the html text of the actual quoted text and strip it out.
1598 // Note that the actual quotedTextOffset in the message has not changed as
1599 // this different offset is used only for display purposes. They point to different
1600 // parts of the original message. Please see the comments in QuoteTextView
1601 // to see the differences.
Mindy Pereira752222d2012-07-19 09:58:53 -07001602 quotedTextIndex = QuotedTextView.findQuotedTextIndex(message.bodyHtml);
1603 if (quotedTextIndex > -1) {
Jin Cao32f453b2014-07-22 14:21:15 -07001604 body = message.bodyHtml.substring(0, quotedTextIndex);
Mindy Pereira752222d2012-07-19 09:58:53 -07001605 quotedText = message.bodyHtml.subSequence(quotedTextIndex,
1606 message.bodyHtml.length());
1607 }
Mindy Pereira002ff522012-05-30 10:31:26 -07001608 }
Jin Cao32f453b2014-07-22 14:21:15 -07001609 new HtmlToSpannedTask().execute(body);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001610 } else {
Mindy Pereira752222d2012-07-19 09:58:53 -07001611 final String body = message.bodyText;
Anthony Lee2a3cc132014-04-22 14:15:25 -07001612 final CharSequence bodyText;
1613 if (TextUtils.isEmpty(body)) {
1614 bodyText = "";
1615 quotedText = null;
1616 } else {
1617 if (quotedTextIndex > body.length()) {
1618 // Sanity check to guarantee that we will not over index the String.
1619 // If this happens there is a bigger problem. This should never happen hence
1620 // the wtf logging.
1621 quotedTextIndex = -1;
1622 LogUtils.wtf(LOG_TAG, "quotedTextIndex (%d) > body.length() (%d)",
1623 quotedTextIndex, body.length());
1624 }
1625 bodyText = quotedTextIndex > -1 ? body.substring(0, quotedTextIndex) : body;
1626 if (quotedTextIndex > -1) {
1627 quotedText = body.substring(quotedTextIndex);
1628 }
Mindy Pereira002ff522012-05-30 10:31:26 -07001629 }
Jin Cao738cafe2014-09-02 16:10:29 -07001630 setBody(bodyText, false);
Mindy Pereira002ff522012-05-30 10:31:26 -07001631 }
1632 if (quotedTextIndex > -1 && quotedText != null) {
Mindy Pereira39713232012-05-30 11:48:41 -07001633 mQuotedTextView.setQuotedTextFromDraft(quotedText, mForward);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001634 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001635 }
1636
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001637 /**
1638 * Fill all the widgets with the content found in the Intent Extra, if any.
1639 * Also apply the same style to all widgets. Note: if initFromExtras is
1640 * called as a result of switching between reply, reply all, and forward per
1641 * the latest revision of Gmail, and the user has already made changes to
1642 * attachments on a previous incarnation of the message (as a reply, reply
1643 * all, or forward), the original attachments from the message will not be
1644 * re-instantiated. The user's changes will be respected. This follows the
1645 * web gmail interaction.
Andrew Sapperstein746d8612013-08-26 15:56:32 -07001646 * @return {@code true} if the activity should not call {@link #finishSetup}.
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001647 */
Andrew Sapperstein746d8612013-08-26 15:56:32 -07001648 public boolean initFromExtras(Intent intent) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001649 // If we were invoked with a SENDTO intent, the value
1650 // should take precedence
1651 final Uri dataUri = intent.getData();
1652 if (dataUri != null) {
1653 if (MAIL_TO.equals(dataUri.getScheme())) {
1654 initFromMailTo(dataUri.toString());
1655 } else {
Mindy Pereira0b4f28e2012-03-28 14:12:21 -07001656 if (!mAccount.composeIntentUri.equals(dataUri)) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001657 String toText = dataUri.getSchemeSpecificPart();
1658 if (toText != null) {
1659 mTo.setText("");
Mindy Pereiradbe89962012-04-13 09:42:38 -07001660 addToAddresses(Arrays.asList(TextUtils.split(toText, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001661 }
1662 }
1663 }
1664 }
1665
1666 String[] extraStrings = intent.getStringArrayExtra(Intent.EXTRA_EMAIL);
1667 if (extraStrings != null) {
1668 addToAddresses(Arrays.asList(extraStrings));
1669 }
1670 extraStrings = intent.getStringArrayExtra(Intent.EXTRA_CC);
1671 if (extraStrings != null) {
1672 addCcAddresses(Arrays.asList(extraStrings), null);
1673 }
1674 extraStrings = intent.getStringArrayExtra(Intent.EXTRA_BCC);
1675 if (extraStrings != null) {
1676 addBccAddresses(Arrays.asList(extraStrings));
1677 }
1678
1679 String extraString = intent.getStringExtra(Intent.EXTRA_SUBJECT);
1680 if (extraString != null) {
1681 mSubject.setText(extraString);
1682 }
1683
1684 for (String extra : ALL_EXTRAS) {
1685 if (intent.hasExtra(extra)) {
1686 String value = intent.getStringExtra(extra);
1687 if (EXTRA_TO.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001688 addToAddresses(Arrays.asList(TextUtils.split(value, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001689 } else if (EXTRA_CC.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001690 addCcAddresses(Arrays.asList(TextUtils.split(value, ",")), null);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001691 } else if (EXTRA_BCC.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001692 addBccAddresses(Arrays.asList(TextUtils.split(value, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001693 } else if (EXTRA_SUBJECT.equals(extra)) {
1694 mSubject.setText(value);
1695 } else if (EXTRA_BODY.equals(extra)) {
1696 setBody(value, true /* with signature */);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001697 } else if (EXTRA_QUOTED_TEXT.equals(extra)) {
1698 initQuotedText(value, true /* shouldQuoteText */);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001699 }
1700 }
1701 }
1702
1703 Bundle extras = intent.getExtras();
1704 if (extras != null) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001705 CharSequence text = extras.getCharSequence(Intent.EXTRA_TEXT);
Jin Caoa8f34ff2014-07-24 14:43:57 -07001706 setBody((text != null) ? text : "", true /* with signature */);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001707
1708 // TODO - support EXTRA_HTML_TEXT
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001709 }
Andrew Sapperstein746d8612013-08-26 15:56:32 -07001710
1711 mExtraValues = intent.getParcelableExtra(EXTRA_VALUES);
1712 if (mExtraValues != null) {
1713 LogUtils.d(LOG_TAG, "Launched with extra values: %s", mExtraValues.toString());
1714 initExtraValues(mExtraValues);
1715 return true;
1716 }
1717
1718 return false;
1719 }
1720
1721 protected void initExtraValues(ContentValues extraValues) {
1722 // DO NOTHING - Gmail will override
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001723 }
1724
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001725
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001726 @VisibleForTesting
1727 protected String decodeEmailInUri(String s) throws UnsupportedEncodingException {
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001728 // TODO: handle the case where there are spaces in the display name as
1729 // well as the email such as "Guy with spaces <guy+with+spaces@gmail.com>"
1730 // as they could be encoded ambiguously.
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001731 // Since URLDecode.decode changes + into ' ', and + is a valid
1732 // email character, we need to find/ replace these ourselves before
1733 // decoding.
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001734 try {
Yorke Lee7dd05b12013-04-25 10:04:43 -07001735 return URLDecoder.decode(replacePlus(s), UTF8_ENCODING_NAME);
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001736 } catch (IllegalArgumentException e) {
1737 if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
1738 LogUtils.e(LOG_TAG, "%s while decoding '%s'", e.getMessage(), s);
1739 } else {
1740 LogUtils.e(LOG_TAG, e, "Exception while decoding mailto address");
1741 }
1742 return null;
1743 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001744 }
1745
1746 /**
Yorke Lee7dd05b12013-04-25 10:04:43 -07001747 * Replaces all occurrences of '+' with "%2B", to prevent URLDecode.decode from
1748 * changing '+' into ' '
1749 *
1750 * @param toReplace Input string
1751 * @return The string with all "+" characters replaced with "%2B"
1752 */
Scott Kennedy3b965d72013-06-25 14:36:55 -07001753 private static String replacePlus(String toReplace) {
Yorke Lee7dd05b12013-04-25 10:04:43 -07001754 return toReplace.replace("+", "%2B");
1755 }
1756
1757 /**
Jin Caod67d7e32014-03-26 16:49:48 -07001758 * Replaces all occurrences of '%' with "%25", to prevent URLDecode.decode from
1759 * crashing on decoded '%' symbols
1760 *
1761 * @param toReplace Input string
1762 * @return The string with all "%" characters replaced with "%25"
1763 */
1764 private static String replacePercent(String toReplace) {
1765 return toReplace.replace("%", "%25");
1766 }
1767
1768 /**
1769 * Helper function to encapsulate encoding/decoding string from Uri.getQueryParameters
1770 * @param content Input string
1771 * @return The string that's properly escaped to be shown in mail subject/content
1772 */
1773 private static String decodeContentFromQueryParam(String content) {
1774 try {
1775 return URLDecoder.decode(replacePlus(replacePercent(content)), UTF8_ENCODING_NAME);
1776 } catch (UnsupportedEncodingException e) {
1777 LogUtils.e(LOG_TAG, "%s while decoding '%s'", e.getMessage(), content);
1778 return ""; // Default to empty string so setText/setBody has same behavior as before.
1779 }
1780 }
1781
1782 /**
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001783 * Initialize the compose view from a String representing a mailTo uri.
1784 * @param mailToString The uri as a string.
1785 */
1786 public void initFromMailTo(String mailToString) {
1787 // We need to disguise this string as a URI in order to parse it
1788 // TODO: Remove this hack when http://b/issue?id=1445295 gets fixed
1789 Uri uri = Uri.parse("foo://" + mailToString);
1790 int index = mailToString.indexOf("?");
1791 int length = "mailto".length() + 1;
1792 String to;
1793 try {
1794 // Extract the recipient after mailto:
1795 if (index == -1) {
1796 to = decodeEmailInUri(mailToString.substring(length));
1797 } else {
1798 to = decodeEmailInUri(mailToString.substring(length, index));
1799 }
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001800 if (!TextUtils.isEmpty(to)) {
1801 addToAddresses(Arrays.asList(TextUtils.split(to, ",")));
1802 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001803 } catch (UnsupportedEncodingException e) {
1804 if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
1805 LogUtils.e(LOG_TAG, "%s while decoding '%s'", e.getMessage(), mailToString);
1806 } else {
1807 LogUtils.e(LOG_TAG, e, "Exception while decoding mailto address");
1808 }
1809 }
1810
1811 List<String> cc = uri.getQueryParameters("cc");
1812 addCcAddresses(Arrays.asList(cc.toArray(new String[cc.size()])), null);
1813
1814 List<String> otherTo = uri.getQueryParameters("to");
1815 addToAddresses(Arrays.asList(otherTo.toArray(new String[otherTo.size()])));
1816
1817 List<String> bcc = uri.getQueryParameters("bcc");
1818 addBccAddresses(Arrays.asList(bcc.toArray(new String[bcc.size()])));
1819
Jin Caod67d7e32014-03-26 16:49:48 -07001820 // NOTE: Uri.getQueryParameters already decodes % encoded characters
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001821 List<String> subject = uri.getQueryParameters("subject");
1822 if (subject.size() > 0) {
Jin Caod67d7e32014-03-26 16:49:48 -07001823 mSubject.setText(decodeContentFromQueryParam(subject.get(0)));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001824 }
1825
1826 List<String> body = uri.getQueryParameters("body");
1827 if (body.size() > 0) {
Jin Caod67d7e32014-03-26 16:49:48 -07001828 setBody(decodeContentFromQueryParam(body.get(0)), true /* with signature */);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001829 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001830 }
1831
Mindy Pereirabddd6f32012-06-20 12:10:03 -07001832 @VisibleForTesting
1833 protected void initAttachments(Message refMessage) {
Mark Wei434f2942012-08-24 11:54:02 -07001834 addAttachments(refMessage.getAttachments());
1835 }
1836
1837 public long addAttachments(List<Attachment> attachments) {
1838 long size = 0;
1839 AttachmentFailureException error = null;
1840 for (Attachment a : attachments) {
1841 try {
1842 size += mAttachmentsView.addAttachment(mAccount, a);
1843 } catch (AttachmentFailureException e) {
1844 error = e;
1845 }
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001846 }
Mark Wei434f2942012-08-24 11:54:02 -07001847 if (error != null) {
1848 LogUtils.e(LOG_TAG, error, "Error adding attachment");
1849 if (attachments.size() > 1) {
1850 showAttachmentTooBigToast(R.string.too_large_to_attach_multiple);
1851 } else {
1852 showAttachmentTooBigToast(error.getErrorRes());
1853 }
1854 }
1855 return size;
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001856 }
1857
1858 /**
1859 * When an attachment is too large to be added to a message, show a toast.
1860 * This method also updates the position of the toast so that it is shown
1861 * clearly above they keyboard if it happens to be open.
1862 */
Mark Wei434f2942012-08-24 11:54:02 -07001863 private void showAttachmentTooBigToast(int errorRes) {
1864 String maxSize = AttachmentUtils.convertToHumanReadableSize(
1865 getApplicationContext(), mAccount.settings.getMaxAttachmentSize());
1866 showErrorToast(getString(errorRes, maxSize));
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001867 }
1868
Mark Wei434f2942012-08-24 11:54:02 -07001869 private void showErrorToast(String message) {
1870 Toast t = Toast.makeText(this, message, Toast.LENGTH_LONG);
1871 t.setText(message);
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001872 t.setGravity(Gravity.CENTER_HORIZONTAL, 0,
1873 getResources().getDimensionPixelSize(R.dimen.attachment_toast_yoffset));
1874 t.show();
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001875 }
1876
Paul Westbrookf97588b2012-03-20 11:11:37 -07001877 private void initAttachmentsFromIntent(Intent intent) {
Paul Westbrook03ee9712012-04-02 09:51:51 -07001878 Bundle extras = intent.getExtras();
1879 if (extras == null) {
1880 extras = Bundle.EMPTY;
1881 }
Paul Westbrookf97588b2012-03-20 11:11:37 -07001882 final String action = intent.getAction();
1883 if (!mAttachmentsChanged) {
1884 long totalSize = 0;
1885 if (extras.containsKey(EXTRA_ATTACHMENTS)) {
Jin Caoadea2c82014-08-28 12:25:52 -07001886 final String[] uris = (String[]) extras.getSerializable(EXTRA_ATTACHMENTS);
1887 final ArrayList<Uri> parsedUris = Lists.newArrayListWithCapacity(uris.length);
1888 for (String uri : uris) {
1889 parsedUris.add(Uri.parse(uri));
Paul Westbrookf97588b2012-03-20 11:11:37 -07001890 }
Jin Caoadea2c82014-08-28 12:25:52 -07001891 totalSize += handleAttachmentUrisFromIntent(parsedUris);
Paul Westbrookf97588b2012-03-20 11:11:37 -07001892 }
mindyp9a9e8d62012-10-03 12:24:07 -07001893 if (extras.containsKey(Intent.EXTRA_STREAM)) {
1894 if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
Andy Huang91ede362014-01-21 19:16:00 -08001895 final ArrayList<Uri> uris = extras
mindyp9a9e8d62012-10-03 12:24:07 -07001896 .getParcelableArrayList(Intent.EXTRA_STREAM);
Jin Caoadea2c82014-08-28 12:25:52 -07001897 totalSize += handleAttachmentUrisFromIntent(uris);
mindyp9a9e8d62012-10-03 12:24:07 -07001898 } else {
Tony Mantler581edd42014-02-18 15:41:22 -08001899 final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
Jin Caoadea2c82014-08-28 12:25:52 -07001900 final ArrayList<Uri> uris = Lists.newArrayList(uri);
1901 totalSize += handleAttachmentUrisFromIntent(uris);
Paul Westbrookf97588b2012-03-20 11:11:37 -07001902 }
1903 }
1904
1905 if (totalSize > 0) {
1906 mAttachmentsChanged = true;
1907 updateSaveUi();
Andy Huange003b4c2013-08-16 10:32:05 -07001908
1909 Analytics.getInstance().sendEvent("send_intent_with_attachments",
1910 Integer.toString(getAttachments().size()), null, totalSize);
Paul Westbrookf97588b2012-03-20 11:11:37 -07001911 }
1912 }
1913 }
1914
Jin Caoadea2c82014-08-28 12:25:52 -07001915 /**
Sam Lee72930a12016-03-23 16:53:20 -07001916 * @return the authority of EmailProvider for this app. should be overridden in concrete
1917 * app implementations. can't be known here because this project doesn't know about that sort
1918 * of thing.
1919 */
1920 protected String getEmailProviderAuthority() {
1921 throw new UnsupportedOperationException("unimplemented, EmailProvider unknown");
1922 }
1923
1924 /**
Jin Caoadea2c82014-08-28 12:25:52 -07001925 * Helper function to handle a list of uris to attach.
1926 * @return the total size of all successfully attached files.
1927 */
1928 private long handleAttachmentUrisFromIntent(List<Uri> uris) {
1929 ArrayList<Attachment> attachments = Lists.newArrayList();
1930 for (Uri uri : uris) {
1931 try {
1932 if (uri != null) {
Sam Lee72930a12016-03-23 16:53:20 -07001933 if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
Régis Décampse70f67a2016-02-23 16:16:54 +01001934 // We must not allow files from /data, even from our process.
Jin Caoadea2c82014-08-28 12:25:52 -07001935 final File f = new File(uri.getPath());
Jin Cao24ed2942014-09-02 10:21:37 -07001936 final String filePath = f.getCanonicalPath();
1937 if (filePath.startsWith(DATA_DIRECTORY_ROOT)) {
Régis Décampse70f67a2016-02-23 16:16:54 +01001938 showErrorToast(getString(R.string.attachment_permission_denied));
1939 Analytics.getInstance().sendEvent(ANALYTICS_CATEGORY_ERRORS,
1940 "send_intent_attachment", "data_dir", 0);
1941 continue;
Jin Caoadea2c82014-08-28 12:25:52 -07001942 }
Sam Lee72930a12016-03-23 16:53:20 -07001943 } else if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
1944 // disallow attachments from our own EmailProvider (b/27308057)
1945 if (getEmailProviderAuthority().equals(uri.getAuthority())) {
1946 showErrorToast(getString(R.string.attachment_permission_denied));
1947 Analytics.getInstance().sendEvent(ANALYTICS_CATEGORY_ERRORS,
1948 "send_intent_attachment", "email_provider", 0);
1949 continue;
1950 }
Jin Caoadea2c82014-08-28 12:25:52 -07001951 }
Sam Lee72930a12016-03-23 16:53:20 -07001952
Jin Caoadea2c82014-08-28 12:25:52 -07001953 if (!handleSpecialAttachmentUri(uri)) {
1954 final Attachment a = mAttachmentsView.generateLocalAttachment(uri);
1955 attachments.add(a);
1956
1957 Analytics.getInstance().sendEvent("send_intent_attachment",
1958 Utils.normalizeMimeType(a.getContentType()), null, a.size);
1959 }
1960 }
1961 } catch (AttachmentFailureException e) {
1962 LogUtils.e(LOG_TAG, e, "Error adding attachment");
1963 showAttachmentTooBigToast(e.getErrorRes());
1964 } catch (IOException | SecurityException e) {
Jin Cao24ed2942014-09-02 10:21:37 -07001965 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Jin Caoadea2c82014-08-28 12:25:52 -07001966 showErrorToast(getString(R.string.attachment_permission_denied));
1967 }
1968 }
1969 return addAttachments(attachments);
1970 }
1971
Andrew Sapperstein746d8612013-08-26 15:56:32 -07001972 protected void initQuotedText(CharSequence quotedText, boolean shouldQuoteText) {
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001973 mQuotedTextView.setQuotedTextFromHtml(quotedText, shouldQuoteText);
1974 mShowQuotedText = true;
1975 }
Paul Westbrookf97588b2012-03-20 11:11:37 -07001976
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001977 private void initQuotedTextFromRefMessage(Message refMessage, int action) {
1978 if (mRefMessage != null && (action == REPLY || action == REPLY_ALL || action == FORWARD)) {
Mindy Pereira9932dee2012-01-10 16:09:50 -08001979 mQuotedTextView.setQuotedText(action, refMessage, action != FORWARD);
1980 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001981 }
1982
1983 private void updateHideOrShowCcBcc() {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001984 // Its possible there is a menu item OR a button.
Mindy Pereira326689d2012-05-17 10:14:14 -07001985 boolean ccVisible = mCcBccView.isCcVisible();
1986 boolean bccVisible = mCcBccView.isBccVisible();
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001987 if (mCcBccButton != null) {
Mindy Pereira326689d2012-05-17 10:14:14 -07001988 if (!ccVisible || !bccVisible) {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001989 mCcBccButton.setVisibility(View.VISIBLE);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001990 } else {
Jin Cao9d358a12014-07-24 12:15:38 -07001991 mCcBccButton.setVisibility(View.GONE);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001992 }
1993 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001994 }
1995
Mindy Pereira013194c2012-01-06 15:09:33 -08001996 /**
1997 * Add attachment and update the compose area appropriately.
Mindy Pereira013194c2012-01-06 15:09:33 -08001998 */
Andrew Sapperstein865ae9c2014-02-10 18:23:48 -08001999 private void addAttachmentAndUpdateView(Intent data) {
Andrew Sapperstein05089f32013-10-01 17:00:03 -07002000 if (data == null) {
2001 return;
2002 }
2003
2004 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
2005 final ClipData clipData = data.getClipData();
2006 if (clipData != null) {
2007 for (int i = 0, size = clipData.getItemCount(); i < size; i++) {
2008 addAttachmentAndUpdateView(clipData.getItemAt(i).getUri());
2009 }
2010 return;
2011 }
2012 }
2013
2014 addAttachmentAndUpdateView(data.getData());
Mindy Pereira2421dc82012-03-27 13:32:31 -07002015 }
2016
Andrew Sapperstein865ae9c2014-02-10 18:23:48 -08002017 private void addAttachmentAndUpdateView(Uri contentUri) {
Andy Huang5c5fd572012-04-08 18:19:29 -07002018 if (contentUri == null) {
Mindy Pereira2421dc82012-03-27 13:32:31 -07002019 return;
2020 }
Andy Huang91ede362014-01-21 19:16:00 -08002021
Ekin Oguz177f7682016-11-28 15:34:02 -08002022 if (handleSpecialAttachmentUri(contentUri)) {
2023 return;
2024 }
Andy Huang91ede362014-01-21 19:16:00 -08002025
Ekin Oguz177f7682016-11-28 15:34:02 -08002026 final long size = handleAttachmentUrisFromIntent(Arrays.asList(contentUri));
2027 if (size > 0) {
2028 mAttachmentsChanged = true;
2029 updateSaveUi();
Andy Huang5c5fd572012-04-08 18:19:29 -07002030 }
2031 }
2032
Andy Huang91ede362014-01-21 19:16:00 -08002033 /**
2034 * Allow subclasses to implement custom handling of attachments.
2035 *
2036 * @param contentUri a passed-in URI from a pick intent
2037 * @return true iff handled
2038 */
2039 protected boolean handleSpecialAttachmentUri(final Uri contentUri) {
2040 return false;
2041 }
2042
Andrew Sapperstein865ae9c2014-02-10 18:23:48 -08002043 private void addAttachmentAndUpdateView(Attachment attachment) {
Andy Huang5c5fd572012-04-08 18:19:29 -07002044 try {
Mark Wei434f2942012-08-24 11:54:02 -07002045 long size = mAttachmentsView.addAttachment(mAccount, attachment);
Mindy Pereira9932dee2012-01-10 16:09:50 -08002046 if (size > 0) {
2047 mAttachmentsChanged = true;
2048 updateSaveUi();
Mindy Pereira013194c2012-01-06 15:09:33 -08002049 }
Mindy Pereira9932dee2012-01-10 16:09:50 -08002050 } catch (AttachmentFailureException e) {
Mindy Pereira9932dee2012-01-10 16:09:50 -08002051 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Mark Wei434f2942012-08-24 11:54:02 -07002052 showAttachmentTooBigToast(e.getErrorRes());
Mindy Pereira013194c2012-01-06 15:09:33 -08002053 }
2054 }
2055
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08002056 void initRecipientsFromRefMessage(Message refMessage, int action) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002057 // Don't populate the address if this is a forward.
2058 if (action == ComposeActivity.FORWARD) {
2059 return;
2060 }
Scott Kennedyff8553f2013-04-05 20:57:44 -07002061 initReplyRecipients(refMessage, action);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002062 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002063
Paul Westbrook6d2442b2013-07-17 17:51:51 -07002064 // TODO: This should be private. This method shouldn't be used by ComposeActivityTests, as
2065 // it doesn't setup the state of the activity correctly
Mindy Pereira818143e2012-01-11 13:59:49 -08002066 @VisibleForTesting
Scott Kennedyff8553f2013-04-05 20:57:44 -07002067 void initReplyRecipients(final Message refMessage, final int action) {
Tony Mantler9016a5e2013-07-19 11:54:17 -07002068 String[] sentToAddresses = refMessage.getToAddressesUnescaped();
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08002069 final Collection<String> toAddresses;
Tony Mantler89de9eb2013-07-25 11:43:58 -07002070 final String[] fromAddresses = refMessage.getFromAddressesUnescaped();
2071 final String fromAddress = fromAddresses.length > 0 ? fromAddresses[0] : null;
Andy Huange2af8872014-01-16 12:36:27 -08002072 final String[] replyToAddresses = getReplyToAddresses(
2073 refMessage.getReplyToAddressesUnescaped(), fromAddress);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002074
2075 // If this is a reply, the Cc list is empty. If this is a reply-all, the
2076 // Cc list is the union of the To and Cc recipients of the original
2077 // message, excluding the current user's email address and any addresses
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08002078 // already on the To list.
2079 if (action == ComposeActivity.REPLY) {
Tony Mantler24f116f2014-01-16 10:20:50 -08002080 toAddresses = initToRecipients(fromAddress, replyToAddresses, sentToAddresses);
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08002081 addToAddresses(toAddresses);
2082 } else if (action == ComposeActivity.REPLY_ALL) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002083 final Set<String> ccAddresses = Sets.newHashSet();
Tony Mantler24f116f2014-01-16 10:20:50 -08002084 toAddresses = initToRecipients(fromAddress, replyToAddresses, sentToAddresses);
Mindy Pereira154386a2012-01-11 13:02:33 -08002085 addToAddresses(toAddresses);
Scott Kennedyff8553f2013-04-05 20:57:44 -07002086 addRecipients(ccAddresses, sentToAddresses);
Tony Mantler9016a5e2013-07-19 11:54:17 -07002087 addRecipients(ccAddresses, refMessage.getCcAddressesUnescaped());
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002088 addCcAddresses(ccAddresses, toAddresses);
2089 }
2090 }
2091
Andy Huange2af8872014-01-16 12:36:27 -08002092 // If there is no reply to address, the reply to address is the sender.
2093 private static String[] getReplyToAddresses(String[] replyTo, String from) {
2094 boolean hasReplyTo = false;
2095 for (final String replyToAddress : replyTo) {
2096 if (!TextUtils.isEmpty(replyToAddress)) {
2097 hasReplyTo = true;
2098 }
2099 }
2100 return hasReplyTo ? replyTo : new String[] {from};
2101 }
2102
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002103 private void addToAddresses(Collection<String> addresses) {
2104 addAddressesToList(addresses, mTo);
2105 }
2106
2107 private void addCcAddresses(Collection<String> addresses, Collection<String> toAddresses) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07002108 addCcAddressesToList(tokenizeAddressList(addresses),
2109 toAddresses != null ? tokenizeAddressList(toAddresses) : null, mCc);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002110 }
2111
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07002112 private void addBccAddresses(Collection<String> addresses) {
2113 addAddressesToList(addresses, mBcc);
2114 }
2115
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002116 @VisibleForTesting
2117 protected void addCcAddressesToList(List<Rfc822Token[]> addresses,
2118 List<Rfc822Token[]> compareToList, RecipientEditTextView list) {
2119 String address;
2120
Mindy Pereira8eca57a2012-03-20 16:42:34 -07002121 if (compareToList == null) {
Tony Mantler581edd42014-02-18 15:41:22 -08002122 for (final Rfc822Token[] tokens : addresses) {
2123 for (final Rfc822Token token : tokens) {
2124 address = token.toString();
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002125 list.append(address + END_TOKEN);
2126 }
2127 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07002128 } else {
2129 HashSet<String> compareTo = convertToHashSet(compareToList);
Tony Mantler581edd42014-02-18 15:41:22 -08002130 for (final Rfc822Token[] tokens : addresses) {
2131 for (final Rfc822Token token : tokens) {
2132 address = token.toString();
Mindy Pereira8eca57a2012-03-20 16:42:34 -07002133 // Check if this is a duplicate:
Tony Mantler581edd42014-02-18 15:41:22 -08002134 if (!compareTo.contains(token.getAddress())) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07002135 // Get the address here
2136 list.append(address + END_TOKEN);
2137 }
2138 }
2139 }
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002140 }
2141 }
2142
Scott Kennedyff8553f2013-04-05 20:57:44 -07002143 private static HashSet<String> convertToHashSet(final List<Rfc822Token[]> list) {
2144 final HashSet<String> hash = new HashSet<String>();
2145 for (final Rfc822Token[] tokens : list) {
Tony Mantler581edd42014-02-18 15:41:22 -08002146 for (final Rfc822Token token : tokens) {
2147 hash.add(token.getAddress());
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002148 }
2149 }
2150 return hash;
2151 }
2152
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002153 protected List<Rfc822Token[]> tokenizeAddressList(Collection<String> addresses) {
2154 @VisibleForTesting
2155 List<Rfc822Token[]> tokenized = new ArrayList<Rfc822Token[]>();
2156
2157 for (String address: addresses) {
2158 tokenized.add(Rfc822Tokenizer.tokenize(address));
2159 }
2160 return tokenized;
2161 }
2162
2163 @VisibleForTesting
2164 void addAddressesToList(Collection<String> addresses, RecipientEditTextView list) {
2165 for (String address : addresses) {
2166 addAddressToList(address, list);
2167 }
2168 }
2169
Scott Kennedyff8553f2013-04-05 20:57:44 -07002170 private static void addAddressToList(final String address, final RecipientEditTextView list) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002171 if (address == null || list == null)
2172 return;
2173
Scott Kennedyff8553f2013-04-05 20:57:44 -07002174 final Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(address);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002175
Tony Mantler581edd42014-02-18 15:41:22 -08002176 for (final Rfc822Token token : tokens) {
2177 list.append(token + END_TOKEN);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002178 }
2179 }
2180
2181 @VisibleForTesting
Scott Kennedyff8553f2013-04-05 20:57:44 -07002182 protected Collection<String> initToRecipients(final String fullSenderAddress,
Tony Mantler24f116f2014-01-16 10:20:50 -08002183 final String[] replyToAddresses, final String[] inToAddresses) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002184 // The To recipient is the reply-to address specified in the original
2185 // message, unless it is:
2186 // the current user OR a custom from of the current user, in which case
2187 // it's the To recipient list of the original message.
2188 // OR missing, in which case use the sender of the original message
2189 Set<String> toAddresses = Sets.newHashSet();
Tony Mantler24f116f2014-01-16 10:20:50 -08002190 for (final String replyToAddress : replyToAddresses) {
2191 if (!TextUtils.isEmpty(replyToAddress)
2192 && !recipientMatchesThisAccount(replyToAddress)) {
2193 toAddresses.add(replyToAddress);
2194 }
2195 }
2196 if (toAddresses.size() == 0) {
mindyp65b06f52012-11-21 10:35:08 -08002197 // In this case, the user is replying to a message in which their
Tony Mantler24f116f2014-01-16 10:20:50 -08002198 // current account or some of their custom from addresses are the only
2199 // recipients and they sent the original message.
mindyp65b06f52012-11-21 10:35:08 -08002200 if (inToAddresses.length == 1 && recipientMatchesThisAccount(fullSenderAddress)
2201 && recipientMatchesThisAccount(inToAddresses[0])) {
2202 toAddresses.add(inToAddresses[0]);
2203 return toAddresses;
2204 }
2205 // This happens if the user replies to a message they originally
2206 // wrote. In this case, "reply" really means "re-send," so we
2207 // target the original recipients. This works as expected even
2208 // if the user sent the original message to themselves.
2209 for (String address : inToAddresses) {
2210 if (!recipientMatchesThisAccount(address)) {
2211 toAddresses.add(address);
mindypfe8557b2012-11-05 12:05:16 -08002212 }
Mindy Pereira1469b4e2012-06-19 19:18:54 -07002213 }
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002214 }
2215 return toAddresses;
2216 }
2217
Scott Kennedyff8553f2013-04-05 20:57:44 -07002218 private void addRecipients(final Set<String> recipients, final String[] addresses) {
2219 for (final String email : addresses) {
Mindy Pereiracecc54a2012-07-31 09:38:11 -07002220 // Do not add this account, or any of its custom from addresses, to
2221 // the list of recipients.
Mindy Pereira4a20b702012-01-05 16:24:24 -08002222 final String recipientAddress = Address.getEmailAddress(email).getAddress();
mindyp5ee5d692012-11-19 16:02:16 -08002223 if (!recipientMatchesThisAccount(recipientAddress)) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002224 recipients.add(email.replace("\"\"", ""));
2225 }
2226 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002227 }
2228
Mindy Pereiracecc54a2012-07-31 09:38:11 -07002229 /**
2230 * A recipient matches this account if it has the same address as the
2231 * currently selected account OR one of the custom from addresses associated
2232 * with the currently selected account.
Mindy Pereiracecc54a2012-07-31 09:38:11 -07002233 * @param recipientAddress address we are comparing with the currently selected account
Mindy Pereiracecc54a2012-07-31 09:38:11 -07002234 */
mindyp5ee5d692012-11-19 16:02:16 -08002235 protected boolean recipientMatchesThisAccount(String recipientAddress) {
2236 return ReplyFromAccount.matchesAccountOrCustomFrom(mAccount, recipientAddress,
mindypfe8557b2012-11-05 12:05:16 -08002237 mAccount.getReplyFroms());
Mindy Pereiracecc54a2012-07-31 09:38:11 -07002238 }
2239
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07002240 /**
2241 * Returns a formatted subject string with the appropriate prefix for the action type.
2242 * E.g., "FWD: " is prepended if action is {@link ComposeActivity#FORWARD}.
2243 */
Andrew Sapperstein7e04f142014-06-11 13:43:07 -07002244 public static String buildFormattedSubject(Resources res, String subject, int action) {
Tony Mantler41c3a252014-06-30 11:00:43 -07002245 final String prefix;
2246 final String correctedSubject;
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002247 if (action == ComposeActivity.COMPOSE) {
2248 prefix = "";
2249 } else if (action == ComposeActivity.FORWARD) {
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07002250 prefix = res.getString(R.string.forward_subject_label);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002251 } else {
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07002252 prefix = res.getString(R.string.reply_subject_label);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002253 }
2254
Tony Mantler41c3a252014-06-30 11:00:43 -07002255 if (TextUtils.isEmpty(subject)) {
2256 correctedSubject = prefix;
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002257 } else {
Tony Mantler41c3a252014-06-30 11:00:43 -07002258 // Don't duplicate the prefix
2259 if (subject.toLowerCase().startsWith(prefix.toLowerCase())) {
2260 correctedSubject = subject;
2261 } else {
2262 correctedSubject = String.format(
2263 res.getString(R.string.formatted_subject), prefix, subject);
2264 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002265 }
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07002266
2267 return correctedSubject;
2268 }
2269
2270 private void setSubject(Message refMessage, int action) {
2271 mSubject.setText(buildFormattedSubject(getResources(), refMessage.subject, action));
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002272 }
2273
Mindy Pereira818143e2012-01-11 13:59:49 -08002274 private void initRecipients() {
2275 setupRecipients(mTo);
2276 setupRecipients(mCc);
2277 setupRecipients(mBcc);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002278 }
2279
Mindy Pereira818143e2012-01-11 13:59:49 -08002280 private void setupRecipients(RecipientEditTextView view) {
Andrew Sapperstein9afa8222014-06-23 16:19:23 -07002281 final DropdownChipLayouter layouter = getDropdownChipLayouter();
2282 if (layouter != null) {
2283 view.setDropdownChipLayouter(layouter);
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07002284 }
Andrew Sapperstein9afa8222014-06-23 16:19:23 -07002285 view.setAdapter(getRecipientAdapter());
Andrew Sappersteinffd61552014-05-14 15:04:23 -07002286 view.setRecipientEntryItemClickedListener(this);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002287 if (mValidator == null) {
Tony Mantler79b11562013-10-09 15:31:50 -07002288 final String accountName = mAccount.getEmailAddress();
Mindy Pereira33fe9082012-01-09 16:24:30 -08002289 int offset = accountName.indexOf("@") + 1;
2290 String account = accountName;
Tony Mantler79b11562013-10-09 15:31:50 -07002291 if (offset > 0) {
2292 account = account.substring(offset);
Mindy Pereirac17d0732011-12-29 10:46:19 -08002293 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002294 mValidator = new Rfc822Validator(account);
Mindy Pereirac17d0732011-12-29 10:46:19 -08002295 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002296 view.setValidator(mValidator);
Mindy Pereira8e9305e2011-12-13 14:25:04 -08002297 }
2298
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07002299 /**
2300 * Derived classes should override if they wish to provide their own autocomplete behavior.
2301 */
2302 public BaseRecipientAdapter getRecipientAdapter() {
2303 return new RecipientAdapter(this, mAccount);
2304 }
2305
2306 /**
2307 * Derived classes should override this to provide their own dropdown behavior.
2308 * If the result is null, the default {@link com.android.ex.chips.DropdownChipLayouter}
2309 * is used.
2310 */
2311 public DropdownChipLayouter getDropdownChipLayouter() {
2312 return null;
2313 }
2314
Mindy Pereira8e9305e2011-12-13 14:25:04 -08002315 @Override
2316 public void onClick(View v) {
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002317 final int id = v.getId();
2318 if (id == R.id.add_cc_bcc) {
2319 // Verify that cc/ bcc aren't showing.
2320 // Animate in cc/bcc.
2321 showCcBccViews();
Mindy Pereira8e9305e2011-12-13 14:25:04 -08002322 }
2323 }
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002324
2325 @Override
Jin Caoc5c550a2014-07-29 11:53:17 -07002326 public void onFocusChange (View v, boolean hasFocus) {
2327 final int id = v.getId();
2328 if (hasFocus && (id == R.id.subject || id == R.id.body)) {
2329 // Collapse cc/bcc iff both are empty
2330 final boolean showCcBccFields = !TextUtils.isEmpty(mCc.getText()) ||
2331 !TextUtils.isEmpty(mBcc.getText());
2332 mCcBccView.show(false /* animate */, showCcBccFields, showCcBccFields);
Jin Cao36e23872014-07-29 13:41:12 -07002333 mCcBccButton.setVisibility(showCcBccFields ? View.GONE : View.VISIBLE);
2334
2335 // On phones autoscroll down so that Cc aligns to the top if we are showing cc/bcc.
2336 if (getResources().getBoolean(R.bool.auto_scroll_cc) && showCcBccFields) {
2337 final int[] coords = new int[2];
2338 mCc.getLocationOnScreen(coords);
2339
2340 // Subtract status bar and action bar height from y-coord.
Jin Caocfba4bb2014-10-07 19:29:15 -07002341 getWindow().getDecorView().getWindowVisibleDisplayFrame(mRect);
2342 final int deltaY = coords[1] - getSupportActionBar().getHeight() - mRect.top;
Jin Cao36e23872014-07-29 13:41:12 -07002343
2344 // Only scroll down
2345 if (deltaY > 0) {
2346 mScrollView.smoothScrollBy(0, deltaY);
2347 }
2348 }
Jin Caoc5c550a2014-07-29 11:53:17 -07002349 }
2350 }
2351
2352 @Override
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002353 public boolean onCreateOptionsMenu(Menu menu) {
Tony Mantler5b8799a2013-10-31 10:43:03 -07002354 final boolean superCreated = super.onCreateOptionsMenu(menu);
Mindy Pereirab199d172012-08-13 11:04:03 -07002355 // Don't render any menu items when there are no accounts.
2356 if (mAccounts == null || mAccounts.length == 0) {
Tony Mantler5b8799a2013-10-31 10:43:03 -07002357 return superCreated;
Mindy Pereirab199d172012-08-13 11:04:03 -07002358 }
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002359 MenuInflater inflater = getMenuInflater();
2360 inflater.inflate(R.menu.compose_menu, menu);
mindyp1d7e9142012-11-21 13:54:30 -08002361
2362 /*
2363 * Start save in the correct enabled state.
2364 * 1) If a user launches compose from within gmail, save is disabled
2365 * until they add something, at which point, save is enabled, auto save
2366 * on exit; if the user empties everything, save is disabled, exiting does not
2367 * auto-save
2368 * 2) if a user replies/ reply all/ forwards from within gmail, save is
2369 * disabled until they change something, at which point, save is
2370 * enabled, auto save on exit; if the user empties everything, save is
2371 * disabled, exiting does not auto-save.
2372 * 3) If a user launches compose from another application and something
2373 * gets populated (attachments, recipients, body, subject, etc), save is
2374 * enabled, auto save on exit; if the user empties everything, save is
2375 * disabled, exiting does not auto-save
2376 */
Mindy Pereira82cc5662012-01-09 17:29:30 -08002377 mSave = menu.findItem(R.id.save);
mindyp1d7e9142012-11-21 13:54:30 -08002378 String action = getIntent() != null ? getIntent().getAction() : null;
Andy Huang9f855d62013-05-30 17:15:03 -07002379 enableSave(mInnerSavedState != null ?
2380 mInnerSavedState.getBoolean(EXTRA_SAVE_ENABLED)
mindyp1d7e9142012-11-21 13:54:30 -08002381 : (Intent.ACTION_SEND.equals(action)
2382 || Intent.ACTION_SEND_MULTIPLE.equals(action)
2383 || Intent.ACTION_SENDTO.equals(action)
Jin Caoe0037922014-09-16 10:23:50 -07002384 || isDraftDirty()));
mindyp1d7e9142012-11-21 13:54:30 -08002385
Greg Bullockd47a7042014-08-13 16:02:59 +02002386 final MenuItem helpItem = menu.findItem(R.id.help_info_menu_item);
2387 final MenuItem sendFeedbackItem = menu.findItem(R.id.feedback_menu_item);
2388 final MenuItem attachFromServiceItem = menu.findItem(R.id.attach_from_service_stub1);
Mindy Pereira3ca5bad2012-04-16 11:02:42 -07002389 if (helpItem != null) {
2390 helpItem.setVisible(mAccount != null
2391 && mAccount.supportsCapability(AccountCapabilities.HELP_CONTENT));
2392 }
2393 if (sendFeedbackItem != null) {
2394 sendFeedbackItem.setVisible(mAccount != null
2395 && mAccount.supportsCapability(AccountCapabilities.SEND_FEEDBACK));
2396 }
Greg Bullockd47a7042014-08-13 16:02:59 +02002397 if (attachFromServiceItem != null) {
2398 attachFromServiceItem.setVisible(shouldEnableAttachFromServiceMenu(mAccount));
2399 }
Andrew Sapperstein5cb71802013-10-01 18:31:20 -07002400
Andrew Sapperstein8809f9f2013-10-11 16:13:35 -07002401 // Show attach picture on pre-K devices.
2402 menu.findItem(R.id.add_photo_attachment).setVisible(!Utils.isRunningKitkatOrLater());
Andrew Sapperstein5cb71802013-10-01 18:31:20 -07002403
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002404 return true;
2405 }
2406
2407 @Override
2408 public boolean onOptionsItemSelected(MenuItem item) {
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002409 final int id = item.getItemId();
Andy Huangdc97bf42013-08-15 16:52:45 -07002410
Andy Huangf8c59b02014-03-19 20:00:53 -07002411 Analytics.getInstance().sendMenuItemEvent(Analytics.EVENT_CATEGORY_MENU_ITEM, id,
2412 "compose", 0);
Andy Huangdc97bf42013-08-15 16:52:45 -07002413
Mindy Pereira75f66632012-01-11 11:42:02 -08002414 boolean handled = true;
Andrew Sapperstein5cb71802013-10-01 18:31:20 -07002415 if (id == R.id.add_file_attachment) {
2416 doAttach(MIME_TYPE_ALL);
2417 } else if (id == R.id.add_photo_attachment) {
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002418 doAttach(MIME_TYPE_PHOTO);
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002419 } else if (id == R.id.save) {
2420 doSave(true);
2421 } else if (id == R.id.send) {
2422 doSend();
2423 } else if (id == R.id.discard) {
2424 doDiscard();
2425 } else if (id == R.id.settings) {
2426 Utils.showSettings(this, mAccount);
2427 } else if (id == android.R.id.home) {
2428 onAppUpPressed();
2429 } else if (id == R.id.help_info_menu_item) {
2430 Utils.showHelp(this, mAccount, getString(R.string.compose_help_context));
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002431 } else {
2432 handled = false;
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002433 }
Tony Mantler581edd42014-02-18 15:41:22 -08002434 return handled || super.onOptionsItemSelected(item);
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002435 }
Mindy Pereira326c6602012-01-04 15:32:42 -08002436
Mindy Pereirab199d172012-08-13 11:04:03 -07002437 @Override
2438 public void onBackPressed() {
2439 // If we are showing the wait fragment, just exit.
2440 if (getWaitFragment() != null) {
2441 finish();
2442 } else {
2443 super.onBackPressed();
2444 }
2445 }
2446
Vikram Aggarwal1672ff82012-09-21 10:15:22 -07002447 /**
2448 * Carries out the "up" action in the action bar.
2449 */
Paul Westbrookdaecb4b2012-05-31 10:21:26 -07002450 private void onAppUpPressed() {
2451 if (mLaunchedFromEmail) {
2452 // If this was started from Gmail, simply treat app up as the system back button, so
2453 // that the last view is restored.
2454 onBackPressed();
2455 return;
2456 }
2457
2458 // Fire the main activity to ensure it launches the "top" screen of mail.
2459 // Since the main Activity is singleTask, it should revive that task if it was already
2460 // started.
Vikram Aggarwal0c3c2052012-09-21 11:06:28 -07002461 final Intent mailIntent = Utils.createViewInboxIntent(mAccount);
Paul Westbrookdaecb4b2012-05-31 10:21:26 -07002462 mailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |
2463 Intent.FLAG_ACTIVITY_TASK_ON_HOME);
2464 startActivity(mailIntent);
2465 finish();
2466 }
2467
Mindy Pereira33fe9082012-01-09 16:24:30 -08002468 private void doSend() {
Mark Weidd19b632012-10-19 13:59:28 -07002469 sendOrSaveWithSanityChecks(false, true, false, false);
Andy Huangdc97bf42013-08-15 16:52:45 -07002470 logSendOrSave(false /* save */);
2471 mPerformedSendOrDiscard = true;
Mindy Pereira33fe9082012-01-09 16:24:30 -08002472 }
2473
Mindy Pereira48e31b02012-05-30 13:12:24 -07002474 private void doSave(boolean showToast) {
Mark Weidd19b632012-10-19 13:59:28 -07002475 sendOrSaveWithSanityChecks(true, showToast, false, false);
Mindy Pereira48e31b02012-05-30 13:12:24 -07002476 }
2477
Andrew Sappersteinffd61552014-05-14 15:04:23 -07002478 @Override
2479 public void onRecipientEntryItemClicked(int charactersTyped, int position) {
2480 // Send analytics of characters typed and position in dropdown selected.
2481 Analytics.getInstance().sendEvent(
Andrew Sapperstein9afa8222014-06-23 16:19:23 -07002482 "suggest_click", Integer.toString(charactersTyped), Integer.toString(position), 0);
Andrew Sappersteinffd61552014-05-14 15:04:23 -07002483 }
2484
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002485 @VisibleForTesting
2486 public interface SendOrSaveCallback {
Jin Caoaff451f2014-09-09 14:32:04 -07002487 void initializeSendOrSave();
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07002488 void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage, Message message);
Jin Cao31bb3d62014-09-11 14:01:43 -07002489 long getMessageId();
Jin Caoaff451f2014-09-09 14:32:04 -07002490 void sendOrSaveFinished(SendOrSaveMessage message, boolean success);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002491 }
2492
Jin Caoaff451f2014-09-09 14:32:04 -07002493 private void runSendOrSaveProviderCalls(SendOrSaveMessage sendOrSaveMessage,
Jin Cao31bb3d62014-09-11 14:01:43 -07002494 SendOrSaveCallback callback, ReplyFromAccount currReplyFromAccount,
2495 ReplyFromAccount originalReplyFromAccount) {
2496 long messageId = callback.getMessageId();
Jin Caoaff451f2014-09-09 14:32:04 -07002497 // If a previous draft has been saved, in an account that is different
2498 // than what the user wants to send from, remove the old draft, and treat this
2499 // as a new message
Jin Cao31bb3d62014-09-11 14:01:43 -07002500 if (originalReplyFromAccount != null
2501 && !currReplyFromAccount.account.uri.equals(originalReplyFromAccount.account.uri)) {
Jin Caoaff451f2014-09-09 14:32:04 -07002502 if (messageId != UIProvider.INVALID_MESSAGE_ID) {
2503 ContentResolver resolver = getContentResolver();
2504 ContentValues values = new ContentValues();
2505 values.put(BaseColumns._ID, messageId);
Jin Cao31bb3d62014-09-11 14:01:43 -07002506 if (originalReplyFromAccount.account.expungeMessageUri != null) {
Jin Caoaff451f2014-09-09 14:32:04 -07002507 new ContentProviderTask.UpdateTask()
Jin Cao31bb3d62014-09-11 14:01:43 -07002508 .run(resolver, originalReplyFromAccount.account.expungeMessageUri,
Jin Caoaff451f2014-09-09 14:32:04 -07002509 values, null, null);
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002510 } else {
Jin Caoaff451f2014-09-09 14:32:04 -07002511 // TODO(mindyp) delete the conversation.
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002512 }
Jin Caoaff451f2014-09-09 14:32:04 -07002513 // reset messageId to 0, so a new message will be created
2514 messageId = UIProvider.INVALID_MESSAGE_ID;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002515 }
2516 }
2517
Jin Caoaff451f2014-09-09 14:32:04 -07002518 final long messageIdToSave = messageId;
Jin Cao31bb3d62014-09-11 14:01:43 -07002519 sendOrSaveMessage(callback, messageIdToSave, sendOrSaveMessage, currReplyFromAccount);
Jin Caoaff451f2014-09-09 14:32:04 -07002520
2521 if (!sendOrSaveMessage.mSave) {
2522 incrementRecipientsTimesContacted(
2523 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.TO),
2524 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.CC),
2525 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.BCC));
2526 }
2527 callback.sendOrSaveFinished(sendOrSaveMessage, true);
2528 }
2529
2530 private void incrementRecipientsTimesContacted(
2531 final String toAddresses, final String ccAddresses, final String bccAddresses) {
2532 final List<String> recipients = Lists.newArrayList();
2533 addAddressesToRecipientList(recipients, toAddresses);
2534 addAddressesToRecipientList(recipients, ccAddresses);
2535 addAddressesToRecipientList(recipients, bccAddresses);
2536 incrementRecipientsTimesContacted(recipients);
2537 }
2538
2539 private void addAddressesToRecipientList(
2540 final List<String> recipients, final String addressString) {
2541 if (recipients == null) {
2542 throw new IllegalArgumentException("recipientList cannot be null");
2543 }
2544 if (TextUtils.isEmpty(addressString)) {
2545 return;
2546 }
2547 final Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(addressString);
2548 for (final Rfc822Token token : tokens) {
2549 recipients.add(token.getAddress());
2550 }
2551 }
2552
2553 /**
2554 * Send or Save a message.
2555 */
2556 private void sendOrSaveMessage(SendOrSaveCallback callback, final long messageIdToSave,
2557 final SendOrSaveMessage sendOrSaveMessage, final ReplyFromAccount selectedAccount) {
2558 final ContentResolver resolver = getContentResolver();
2559 final boolean updateExistingMessage = messageIdToSave != UIProvider.INVALID_MESSAGE_ID;
2560
2561 final String accountMethod = sendOrSaveMessage.mSave ?
2562 UIProvider.AccountCallMethods.SAVE_MESSAGE :
2563 UIProvider.AccountCallMethods.SEND_MESSAGE;
2564
2565 try {
2566 if (updateExistingMessage) {
2567 sendOrSaveMessage.mValues.put(BaseColumns._ID, messageIdToSave);
2568
2569 callAccountSendSaveMethod(resolver,
2570 selectedAccount.account, accountMethod, sendOrSaveMessage);
2571 } else {
2572 Uri messageUri = null;
2573 final Bundle result = callAccountSendSaveMethod(resolver,
2574 selectedAccount.account, accountMethod, sendOrSaveMessage);
2575 if (result != null) {
2576 // If a non-null value was returned, then the provider handled the call
2577 // method
2578 messageUri = result.getParcelable(UIProvider.MessageColumns.URI);
2579 }
2580 if (sendOrSaveMessage.mSave && messageUri != null) {
2581 final Cursor messageCursor = resolver.query(messageUri,
2582 UIProvider.MESSAGE_PROJECTION, null, null, null);
2583 if (messageCursor != null) {
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002584 try {
Jin Caoaff451f2014-09-09 14:32:04 -07002585 if (messageCursor.moveToFirst()) {
2586 // Broadcast notification that a new message has
2587 // been allocated
2588 callback.notifyMessageIdAllocated(sendOrSaveMessage,
2589 new Message(messageCursor));
2590 }
2591 } finally {
2592 messageCursor.close();
Paul Westbrookba558482012-03-19 11:00:24 -07002593 }
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002594 }
2595 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002596 }
Jin Caoaff451f2014-09-09 14:32:04 -07002597 } finally {
2598 // Close any opened file descriptors
2599 closeOpenedAttachmentFds(sendOrSaveMessage);
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002600 }
Jin Caoaff451f2014-09-09 14:32:04 -07002601 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002602
Jin Caoaff451f2014-09-09 14:32:04 -07002603 private static void closeOpenedAttachmentFds(final SendOrSaveMessage sendOrSaveMessage) {
2604 final Bundle openedFds = sendOrSaveMessage.attachmentFds();
2605 if (openedFds != null) {
2606 final Set<String> keys = openedFds.keySet();
2607 for (final String key : keys) {
2608 final ParcelFileDescriptor fd = openedFds.getParcelable(key);
2609 if (fd != null) {
2610 try {
2611 fd.close();
2612 } catch (IOException e) {
2613 // Do nothing
2614 }
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002615 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002616 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002617 }
2618 }
2619
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07002620 /**
Jin Caoaff451f2014-09-09 14:32:04 -07002621 * Use the {@link ContentResolver#call} method to send or save the message.
2622 *
2623 * If this was successful, this method will return an non-null Bundle instance
2624 */
2625 private static Bundle callAccountSendSaveMethod(final ContentResolver resolver,
2626 final Account account, final String method,
2627 final SendOrSaveMessage sendOrSaveMessage) {
2628 // Copy all of the values from the content values to the bundle
2629 final Bundle methodExtras = new Bundle(sendOrSaveMessage.mValues.size());
2630 final Set<Entry<String, Object>> valueSet = sendOrSaveMessage.mValues.valueSet();
2631
2632 for (Entry<String, Object> entry : valueSet) {
2633 final Object entryValue = entry.getValue();
2634 final String key = entry.getKey();
2635 if (entryValue instanceof String) {
2636 methodExtras.putString(key, (String)entryValue);
2637 } else if (entryValue instanceof Boolean) {
2638 methodExtras.putBoolean(key, (Boolean)entryValue);
2639 } else if (entryValue instanceof Integer) {
2640 methodExtras.putInt(key, (Integer)entryValue);
2641 } else if (entryValue instanceof Long) {
2642 methodExtras.putLong(key, (Long)entryValue);
2643 } else {
2644 LogUtils.wtf(LOG_TAG, "Unexpected object type: %s",
2645 entryValue.getClass().getName());
2646 }
2647 }
2648
2649 // If the SendOrSaveMessage has some opened fds, add them to the bundle
2650 final Bundle fdMap = sendOrSaveMessage.attachmentFds();
2651 if (fdMap != null) {
2652 methodExtras.putParcelable(
2653 UIProvider.SendOrSaveMethodParamKeys.OPENED_FD_MAP, fdMap);
2654 }
2655
2656 return resolver.call(account.uri, method, account.uri.toString(), methodExtras);
2657 }
2658
2659 /**
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07002660 * Reports recipients that have been contacted in order to improve auto-complete
2661 * suggestions. Default behavior updates usage statistics in ContactsProvider.
2662 * @param recipients addresses
2663 */
2664 protected void incrementRecipientsTimesContacted(List<String> recipients) {
2665 final DataUsageStatUpdater statsUpdater = new DataUsageStatUpdater(this);
2666 statsUpdater.updateWithAddress(recipients);
2667 }
2668
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002669 @VisibleForTesting
2670 public static class SendOrSaveMessage {
Jin Cao31bb3d62014-09-11 14:01:43 -07002671 final int mRequestId;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002672 final ContentValues mValues;
Mindy Pereira3ce64e72012-01-13 14:29:45 -08002673 final String mRefMessageId;
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002674 @VisibleForTesting
2675 public final boolean mSave;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002676 private final Bundle mAttachmentFds;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002677
Jin Cao31bb3d62014-09-11 14:01:43 -07002678 public SendOrSaveMessage(Context context, int requestId, ContentValues values,
Jin Caoadae7a32014-09-09 18:16:25 -07002679 String refMessageId, List<Attachment> attachments, Bundle optionalAttachmentFds,
2680 boolean save) {
Jin Cao31bb3d62014-09-11 14:01:43 -07002681 mRequestId = requestId;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002682 mValues = values;
2683 mRefMessageId = refMessageId;
2684 mSave = save;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002685
Jin Caoadae7a32014-09-09 18:16:25 -07002686 // If the attachments are already open for us (pre-JB), then don't open them again
2687 if (optionalAttachmentFds != null) {
2688 mAttachmentFds = optionalAttachmentFds;
2689 } else {
2690 mAttachmentFds = initializeAttachmentFds(context, attachments);
2691 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002692 }
2693
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002694 Bundle attachmentFds() {
2695 return mAttachmentFds;
2696 }
Jin Caoadae7a32014-09-09 18:16:25 -07002697 }
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002698
Jin Caoadae7a32014-09-09 18:16:25 -07002699 /**
2700 * Opens {@link ParcelFileDescriptor} for each of the attachments. This method must be
2701 * called before the ComposeActivity finishes.
2702 * Note: The caller is responsible for closing these file descriptors.
2703 */
2704 private static Bundle initializeAttachmentFds(final Context context,
2705 final List<Attachment> attachments) {
2706 if (attachments == null || attachments.size() == 0) {
2707 return null;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002708 }
Jin Caoadae7a32014-09-09 18:16:25 -07002709
2710 final Bundle result = new Bundle(attachments.size());
2711 final ContentResolver resolver = context.getContentResolver();
2712
2713 for (Attachment attachment : attachments) {
2714 if (attachment == null || Utils.isEmpty(attachment.contentUri)) {
2715 continue;
2716 }
2717
2718 ParcelFileDescriptor fileDescriptor;
2719 try {
2720 fileDescriptor = resolver.openFileDescriptor(attachment.contentUri, "r");
2721 } catch (FileNotFoundException e) {
2722 LogUtils.e(LOG_TAG, e, "Exception attempting to open attachment");
2723 fileDescriptor = null;
2724 } catch (SecurityException e) {
2725 // We have encountered a security exception when attempting to open the file
2726 // specified by the content uri. If the attachment has been cached, this
2727 // isn't a problem, as even through the original permission may have been
2728 // revoked, we have cached the file. This will happen when saving/sending
2729 // a previously saved draft.
2730 // TODO(markwei): Expose whether the attachment has been cached through the
2731 // attachment object. This would allow us to limit when the log is made, as
2732 // if the attachment has been cached, this really isn't an error
2733 LogUtils.e(LOG_TAG, e, "Security Exception attempting to open attachment");
2734 // Just set the file descriptor to null, as the underlying provider needs
2735 // to handle the file descriptor not being set.
2736 fileDescriptor = null;
2737 }
2738
2739 if (fileDescriptor != null) {
2740 result.putParcelable(attachment.contentUri.toString(), fileDescriptor);
2741 }
2742 }
2743
2744 return result;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002745 }
2746
2747 /**
2748 * Get the to recipients.
2749 */
2750 public String[] getToAddresses() {
2751 return getAddressesFromList(mTo);
2752 }
2753
2754 /**
2755 * Get the cc recipients.
2756 */
2757 public String[] getCcAddresses() {
2758 return getAddressesFromList(mCc);
2759 }
2760
2761 /**
2762 * Get the bcc recipients.
2763 */
2764 public String[] getBccAddresses() {
2765 return getAddressesFromList(mBcc);
2766 }
2767
2768 public String[] getAddressesFromList(RecipientEditTextView list) {
2769 if (list == null) {
2770 return new String[0];
2771 }
2772 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(list.getText());
2773 int count = tokens.length;
2774 String[] result = new String[count];
2775 for (int i = 0; i < count; i++) {
2776 result[i] = tokens[i].toString();
2777 }
2778 return result;
2779 }
2780
2781 /**
2782 * Check for invalid email addresses.
2783 * @param to String array of email addresses to check.
2784 * @param wrongEmailsOut Emails addresses that were invalid.
2785 */
Scott Kennedyff8553f2013-04-05 20:57:44 -07002786 public void checkInvalidEmails(final String[] to, final List<String> wrongEmailsOut) {
Mindy Pereirae5f20bf2012-06-25 14:20:40 -07002787 if (mValidator == null) {
2788 return;
2789 }
Scott Kennedyff8553f2013-04-05 20:57:44 -07002790 for (final String email : to) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002791 if (!mValidator.isValid(email)) {
2792 wrongEmailsOut.add(email);
2793 }
2794 }
2795 }
2796
Tony Mantler2558b502013-07-09 10:53:34 -07002797 public static class RecipientErrorDialogFragment extends DialogFragment {
Paul Westbrookf0ea4842013-08-13 16:41:18 -07002798 // Public no-args constructor needed for fragment re-instantiation
2799 public RecipientErrorDialogFragment() {}
2800
Tony Mantler2558b502013-07-09 10:53:34 -07002801 public static RecipientErrorDialogFragment newInstance(final String message) {
2802 final RecipientErrorDialogFragment frag = new RecipientErrorDialogFragment();
2803 final Bundle args = new Bundle(1);
2804 args.putString("message", message);
2805 frag.setArguments(args);
2806 return frag;
2807 }
2808
2809 @Override
2810 public Dialog onCreateDialog(Bundle savedInstanceState) {
2811 final String message = getArguments().getString("message");
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07002812 return new AlertDialog.Builder(getActivity())
2813 .setMessage(message)
Tony Mantler2558b502013-07-09 10:53:34 -07002814 .setPositiveButton(
2815 R.string.ok, new Dialog.OnClickListener() {
2816 @Override
2817 public void onClick(DialogInterface dialog, int which) {
2818 ((ComposeActivity)getActivity()).finishRecipientErrorDialog();
2819 }
2820 }).create();
2821 }
2822 }
2823
2824 private void finishRecipientErrorDialog() {
2825 // after the user dismisses the recipient error
2826 // dialog we want to make sure to refocus the
2827 // recipient to field so they can fix the issue
2828 // easily
2829 if (mTo != null) {
2830 mTo.requestFocus();
2831 }
2832 }
2833
Mindy Pereira82cc5662012-01-09 17:29:30 -08002834 /**
2835 * Show an error because the user has entered an invalid recipient.
Mindy Pereira82cc5662012-01-09 17:29:30 -08002836 */
Tony Mantler2558b502013-07-09 10:53:34 -07002837 private void showRecipientErrorDialog(final String message) {
2838 final DialogFragment frag = RecipientErrorDialogFragment.newInstance(message);
2839 frag.show(getFragmentManager(), "recipient error");
Mindy Pereira82cc5662012-01-09 17:29:30 -08002840 }
2841
2842 /**
2843 * Update the state of the UI based on whether or not the current draft
2844 * needs to be saved and the message is not empty.
2845 */
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002846 public void updateSaveUi() {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002847 if (mSave != null) {
Jin Caoe0037922014-09-16 10:23:50 -07002848 mSave.setEnabled((isDraftDirty() && !isBlank()));
Mindy Pereira82cc5662012-01-09 17:29:30 -08002849 }
2850 }
2851
2852 /**
Jin Caoe0037922014-09-16 10:23:50 -07002853 * Returns true if the current draft is modified from the version we previously saved.
Mindy Pereira82cc5662012-01-09 17:29:30 -08002854 */
Jin Caoe0037922014-09-16 10:23:50 -07002855 private boolean isDraftDirty() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002856 synchronized (mDraftLock) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002857 // The message should only be saved if:
2858 // It hasn't been sent AND
2859 // Some text has been added to the message OR
2860 // an attachment has been added or removed
Mindy Pereiraa2148332012-07-02 13:54:14 -07002861 // AND there is actually something in the draft to save.
Andy Huangd47877e2012-08-09 19:31:24 -07002862 return (mTextChanged || mAttachmentsChanged || mReplyFromChanged)
Mindy Pereiraa2148332012-07-02 13:54:14 -07002863 && !isBlank();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002864 }
2865 }
2866
2867 /**
Greg Bullockd47a7042014-08-13 16:02:59 +02002868 * Returns whether the "Attach from Drive" menu item should be visible.
2869 */
2870 protected boolean shouldEnableAttachFromServiceMenu(Account mAccount) {
2871 return false;
2872 }
2873
2874 /**
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002875 * Check if all fields are blank.
Mindy Pereira82cc5662012-01-09 17:29:30 -08002876 * @return boolean
2877 */
2878 public boolean isBlank() {
Alice Yanga49b6842013-08-23 10:36:18 -07002879 // Need to check for null since isBlank() can be called from onPause()
2880 // before findViews() is called
2881 if (mSubject == null || mBodyView == null || mTo == null || mCc == null ||
2882 mAttachmentsView == null) {
2883 LogUtils.w(LOG_TAG, "null views in isBlank check");
2884 return true;
2885 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002886 return mSubject.getText().length() == 0
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002887 && (mBodyView.getText().length() == 0 || getSignatureStartPosition(mSignature,
2888 mBodyView.getText().toString()) == 0)
2889 && mTo.length() == 0
2890 && mCc.length() == 0 && mBcc.length() == 0
2891 && mAttachmentsView.getAttachments().size() == 0;
2892 }
2893
2894 @VisibleForTesting
2895 protected int getSignatureStartPosition(String signature, String bodyText) {
2896 int startPos = -1;
2897
2898 if (TextUtils.isEmpty(signature) || TextUtils.isEmpty(bodyText)) {
2899 return startPos;
2900 }
2901
2902 int bodyLength = bodyText.length();
2903 int signatureLength = signature.length();
2904 String printableVersion = convertToPrintableSignature(signature);
2905 int printableLength = printableVersion.length();
2906
2907 if (bodyLength >= printableLength
2908 && bodyText.substring(bodyLength - printableLength)
2909 .equals(printableVersion)) {
2910 startPos = bodyLength - printableLength;
2911 } else if (bodyLength >= signatureLength
2912 && bodyText.substring(bodyLength - signatureLength)
2913 .equals(signature)) {
2914 startPos = bodyLength - signatureLength;
2915 }
2916 return startPos;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002917 }
2918
2919 /**
2920 * Allows any changes made by the user to be ignored. Called when the user
2921 * decides to discard a draft.
2922 */
2923 private void discardChanges() {
2924 mTextChanged = false;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002925 mAttachmentsChanged = false;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002926 mReplyFromChanged = false;
2927 }
2928
2929 /**
Tony Mantler581edd42014-02-18 15:41:22 -08002930 * @param save True to save, false to send
2931 * @param showToast True to show a toast once the message is sent/saved
Mindy Pereira181df782012-03-01 13:32:44 -08002932 */
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002933 protected void sendOrSaveWithSanityChecks(final boolean save, final boolean showToast,
Mark Weidd19b632012-10-19 13:59:28 -07002934 final boolean orientationChanged, final boolean autoSend) {
Mark Wei009b3712012-10-18 18:07:50 -07002935 if (mAccounts == null || mAccount == null) {
2936 Toast.makeText(this, R.string.send_failed, Toast.LENGTH_SHORT).show();
Mark Weidd19b632012-10-19 13:59:28 -07002937 if (autoSend) {
2938 finish();
2939 }
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002940 return;
Mark Wei009b3712012-10-18 18:07:50 -07002941 }
2942
Scott Kennedyff8553f2013-04-05 20:57:44 -07002943 final String[] to, cc, bcc;
Mindy Pereira181df782012-03-01 13:32:44 -08002944 if (orientationChanged) {
2945 to = cc = bcc = new String[0];
2946 } else {
2947 to = getToAddresses();
2948 cc = getCcAddresses();
2949 bcc = getBccAddresses();
2950 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002951
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002952 final ArrayList<String> recipients = buildEmailAddressList(to);
2953 recipients.addAll(buildEmailAddressList(cc));
2954 recipients.addAll(buildEmailAddressList(bcc));
2955
Mindy Pereira181df782012-03-01 13:32:44 -08002956 // Don't let the user send to nobody (but it's okay to save a message
2957 // with no recipients)
2958 if (!save && (to.length == 0 && cc.length == 0 && bcc.length == 0)) {
2959 showRecipientErrorDialog(getString(R.string.recipient_needed));
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002960 return;
Mindy Pereira181df782012-03-01 13:32:44 -08002961 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002962
Mindy Pereira181df782012-03-01 13:32:44 -08002963 List<String> wrongEmails = new ArrayList<String>();
2964 if (!save) {
2965 checkInvalidEmails(to, wrongEmails);
2966 checkInvalidEmails(cc, wrongEmails);
2967 checkInvalidEmails(bcc, wrongEmails);
2968 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002969
Mindy Pereira181df782012-03-01 13:32:44 -08002970 // Don't let the user send an email with invalid recipients
2971 if (wrongEmails.size() > 0) {
2972 String errorText = String.format(getString(R.string.invalid_recipient),
2973 wrongEmails.get(0));
2974 showRecipientErrorDialog(errorText);
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002975 return;
Mindy Pereira181df782012-03-01 13:32:44 -08002976 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002977
Mindy Pereira181df782012-03-01 13:32:44 -08002978 if (!save) {
Alan Lau3d519042014-06-05 11:13:06 -07002979 if (autoSend) {
2980 // Skip all further checks during autosend. This flow is used by Android Wear
2981 // and Google Now.
2982 sendOrSave(save, showToast);
2983 return;
2984 }
2985
2986 // Show a warning before sending only if there are no attachments, body, or subject.
Mindy Pereira181df782012-03-01 13:32:44 -08002987 if (mAttachmentsView.getAttachments().isEmpty() && showEmptyTextWarnings()) {
2988 boolean warnAboutEmptySubject = isSubjectEmpty();
Tony Mantler2558b502013-07-09 10:53:34 -07002989 boolean emptyBody = TextUtils.getTrimmedLength(mBodyView.getEditableText()) == 0;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002990
Mindy Pereira181df782012-03-01 13:32:44 -08002991 // A warning about an empty body may not be warranted when
2992 // forwarding mails, since a common use case is to forward
2993 // quoted text and not append any more text.
2994 boolean warnAboutEmptyBody = emptyBody && (!mForward || isBodyEmpty());
Mindy Pereira82cc5662012-01-09 17:29:30 -08002995
Mindy Pereira181df782012-03-01 13:32:44 -08002996 // When we bring up a dialog warning the user about a send,
2997 // assume that they accept sending the message. If they do not,
2998 // the dialog listener is required to enable sending again.
2999 if (warnAboutEmptySubject) {
Tony Mantler581edd42014-02-18 15:41:22 -08003000 showSendConfirmDialog(R.string.confirm_send_message_with_no_subject,
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003001 showToast, recipients);
3002 return;
Mindy Pereira181df782012-03-01 13:32:44 -08003003 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003004
Mindy Pereira181df782012-03-01 13:32:44 -08003005 if (warnAboutEmptyBody) {
Tony Mantler581edd42014-02-18 15:41:22 -08003006 showSendConfirmDialog(R.string.confirm_send_message_with_no_body,
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003007 showToast, recipients);
3008 return;
Mindy Pereira181df782012-03-01 13:32:44 -08003009 }
3010 }
Alan Lau3d519042014-06-05 11:13:06 -07003011 // Ask for confirmation to send.
3012 if (showSendConfirmation()) {
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003013 showSendConfirmDialog(R.string.confirm_send_message, showToast, recipients);
3014 return;
Mindy Pereira181df782012-03-01 13:32:44 -08003015 }
3016 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003017
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003018 performAdditionalSendOrSaveSanityChecks(save, showToast, recipients);
Mindy Pereira181df782012-03-01 13:32:44 -08003019 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003020
Mindy Pereira181df782012-03-01 13:32:44 -08003021 /**
3022 * Returns a boolean indicating whether warnings should be shown for empty
3023 * subject and body fields
Andy Huang5c5fd572012-04-08 18:19:29 -07003024 *
Mindy Pereira181df782012-03-01 13:32:44 -08003025 * @return True if a warning should be shown for empty text fields
3026 */
3027 protected boolean showEmptyTextWarnings() {
3028 return mAttachmentsView.getAttachments().size() == 0;
3029 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003030
Mindy Pereira181df782012-03-01 13:32:44 -08003031 /**
3032 * Returns a boolean indicating whether the user should confirm each send
3033 *
3034 * @return True if a warning should be on each send
3035 */
3036 protected boolean showSendConfirmation() {
Tony Mantler581edd42014-02-18 15:41:22 -08003037 return mCachedSettings != null && mCachedSettings.confirmSend;
Mindy Pereira181df782012-03-01 13:32:44 -08003038 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003039
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07003040 public static class SendConfirmDialogFragment extends DialogFragment
3041 implements DialogInterface.OnClickListener {
3042
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003043 private static final String MESSAGE_ID = "messageId";
3044 private static final String SHOW_TOAST = "showToast";
3045 private static final String RECIPIENTS = "recipients";
3046
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07003047 private boolean mShowToast;
3048
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003049 private ArrayList<String> mRecipients;
3050
Paul Westbrookf0ea4842013-08-13 16:41:18 -07003051 // Public no-args constructor needed for fragment re-instantiation
3052 public SendConfirmDialogFragment() {}
3053
Tony Mantler2558b502013-07-09 10:53:34 -07003054 public static SendConfirmDialogFragment newInstance(final int messageId,
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003055 final boolean showToast, final ArrayList<String> recipients) {
Tony Mantler2558b502013-07-09 10:53:34 -07003056 final SendConfirmDialogFragment frag = new SendConfirmDialogFragment();
3057 final Bundle args = new Bundle(3);
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003058 args.putInt(MESSAGE_ID, messageId);
3059 args.putBoolean(SHOW_TOAST, showToast);
3060 args.putStringArrayList(RECIPIENTS, recipients);
Tony Mantler2558b502013-07-09 10:53:34 -07003061 frag.setArguments(args);
3062 return frag;
Mindy Pereira181df782012-03-01 13:32:44 -08003063 }
Tony Mantler2558b502013-07-09 10:53:34 -07003064
3065 @Override
3066 public Dialog onCreateDialog(Bundle savedInstanceState) {
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003067 final int messageId = getArguments().getInt(MESSAGE_ID);
3068 mShowToast = getArguments().getBoolean(SHOW_TOAST);
3069 mRecipients = getArguments().getStringArrayList(RECIPIENTS);
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07003070
3071 final int confirmTextId = (messageId == R.string.confirm_send_message) ?
3072 R.string.ok : R.string.send;
Tony Mantler2558b502013-07-09 10:53:34 -07003073
3074 return new AlertDialog.Builder(getActivity())
3075 .setMessage(messageId)
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07003076 .setPositiveButton(confirmTextId, this)
Paul Westbrook7d1c5c42013-10-01 23:40:04 -07003077 .setNegativeButton(R.string.cancel, null)
Tony Mantler2558b502013-07-09 10:53:34 -07003078 .create();
3079 }
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07003080
3081 @Override
3082 public void onClick(DialogInterface dialog, int which) {
3083 if (which == DialogInterface.BUTTON_POSITIVE) {
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003084 ((ComposeActivity) getActivity()).finishSendConfirmDialog(mShowToast, mRecipients);
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07003085 }
3086 }
Tony Mantler2558b502013-07-09 10:53:34 -07003087 }
3088
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003089 private void finishSendConfirmDialog(
3090 final boolean showToast, final ArrayList<String> recipients) {
3091 performAdditionalSendOrSaveSanityChecks(false /* save */, showToast, recipients);
Tony Mantler2558b502013-07-09 10:53:34 -07003092 }
3093
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003094 // The list of recipients are used by the additional sendOrSave checks.
3095 // However, the send confirm dialog may be shown before performing
3096 // the additional checks. As a result, we need to plumb the recipient
3097 // list through the send confirm dialog so that
3098 // performAdditionalSendOrSaveChecks can be performed properly.
Tony Mantler581edd42014-02-18 15:41:22 -08003099 private void showSendConfirmDialog(final int messageId,
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003100 final boolean showToast, final ArrayList<String> recipients) {
3101 final DialogFragment frag = SendConfirmDialogFragment.newInstance(
3102 messageId, showToast, recipients);
Tony Mantler2558b502013-07-09 10:53:34 -07003103 frag.show(getFragmentManager(), "send confirm");
Mindy Pereira181df782012-03-01 13:32:44 -08003104 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003105
Mindy Pereira181df782012-03-01 13:32:44 -08003106 /**
3107 * Returns whether the ComposeArea believes there is any text in the body of
3108 * the composition. TODO: When ComposeArea controls the Body as well, add
3109 * that here.
3110 */
3111 public boolean isBodyEmpty() {
3112 return !mQuotedTextView.isTextIncluded();
3113 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003114
Mindy Pereira181df782012-03-01 13:32:44 -08003115 /**
3116 * Test to see if the subject is empty.
3117 *
3118 * @return boolean.
3119 */
3120 // TODO: this will likely go away when composeArea.focus() is implemented
3121 // after all the widget control is moved over.
3122 public boolean isSubjectEmpty() {
3123 return TextUtils.getTrimmedLength(mSubject.getText()) == 0;
3124 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003125
Andy Huang0a2a3462013-12-20 15:56:13 -08003126 @VisibleForTesting
3127 public String getSubject() {
3128 return mSubject.getText().toString();
3129 }
3130
Jin Cao31bb3d62014-09-11 14:01:43 -07003131 private void sendOrSaveInternal(Context context, int requestId,
3132 ReplyFromAccount currReplyFromAccount, ReplyFromAccount originalReplyFromAccount,
3133 Message message, Message refMessage, CharSequence quotedText,
3134 SendOrSaveCallback callback, boolean save, int composeMode, ContentValues extraValues,
Jin Caoadae7a32014-09-09 18:16:25 -07003135 Bundle optionalAttachmentFds) {
Paul Westbrookb4931c62013-01-14 17:51:18 -08003136 final ContentValues values = new ContentValues();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003137
Paul Westbrookb4931c62013-01-14 17:51:18 -08003138 final String refMessageId = refMessage != null ? refMessage.uri.toString() : "";
Mindy Pereirac2031972012-04-03 09:38:35 -07003139
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07003140 MessageModification.putToAddresses(values, message.getToAddresses());
3141 MessageModification.putCcAddresses(values, message.getCcAddresses());
3142 MessageModification.putBccAddresses(values, message.getBccAddresses());
Scott Kennedy8960f0a2012-11-07 15:35:50 -08003143 MessageModification.putCustomFromAddress(values, message.getFrom());
Mindy Pereira92551d02012-04-05 11:31:12 -07003144
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07003145 MessageModification.putSubject(values, message.subject);
Anthony Lee2a3cc132014-04-22 14:15:25 -07003146
Jin Cao77b4c2c2014-05-20 13:55:53 -07003147 // bodyHtml already have the composing spans removed.
3148 final String htmlBody = message.bodyHtml;
Jin Caoa9f5a8e2014-07-22 13:48:45 -07003149 final String textBody = message.bodyText;
Jin Cao0a8e8222014-10-02 11:27:52 -07003150 // fullbodyhtml/fullbodytext will contain the actual body plus the quoted text.
3151 String fullBodyHtml = htmlBody;
3152 String fullBodyText = textBody;
3153 String quotedString = null;
Anthony Lee2a3cc132014-04-22 14:15:25 -07003154 final boolean hasQuotedText = !TextUtils.isEmpty(quotedText);
3155 if (hasQuotedText) {
3156 // The quoted text is HTML at this point.
3157 quotedString = quotedText.toString();
Jin Cao0a8e8222014-10-02 11:27:52 -07003158 fullBodyHtml = htmlBody + quotedString;
3159 fullBodyText = textBody + Utils.convertHtmlToPlainText(quotedString);
Anthony Lee2a3cc132014-04-22 14:15:25 -07003160 MessageModification.putForward(values, composeMode == ComposeActivity.FORWARD);
3161 MessageModification.putAppendRefMessageContent(values, true /* include quoted */);
Mindy Pereira29ef1b82012-01-13 11:26:21 -08003162 }
Jin Cao0a8e8222014-10-02 11:27:52 -07003163
Jin Caoa9f5a8e2014-07-22 13:48:45 -07003164 // Only take refMessage into account if either one of its html/text is not empty.
Jin Cao0a8e8222014-10-02 11:27:52 -07003165 int quotedTextPos = -1;
Jin Caoa9f5a8e2014-07-22 13:48:45 -07003166 if (refMessage != null && !(TextUtils.isEmpty(refMessage.bodyHtml) &&
3167 TextUtils.isEmpty(refMessage.bodyText))) {
Anthony Lee2a3cc132014-04-22 14:15:25 -07003168 // The code below might need to be revisited. The quoted text position is different
3169 // between text/html and text/plain parts and they should be stored seperately and
3170 // the right version should be used in the UI. text/html should have preference
3171 // if both exist. Issues like this made me file b/14256940 to make sure that we
3172 // properly handle the existing of both text/html and text/plain parts and to verify
3173 // that we are not making some assumptions that break if there is no text/html part.
Mindy Pereirac6f1e2a2012-04-04 10:33:45 -07003174 if (!TextUtils.isEmpty(refMessage.bodyHtml)) {
Jin Cao0a8e8222014-10-02 11:27:52 -07003175 MessageModification.putBodyHtml(values, fullBodyHtml);
Anthony Lee2a3cc132014-04-22 14:15:25 -07003176 if (hasQuotedText) {
3177 quotedTextPos = htmlBody.length() +
3178 QuotedTextView.getQuotedTextOffset(quotedString);
3179 }
Mindy Pereirac6f1e2a2012-04-04 10:33:45 -07003180 }
3181 if (!TextUtils.isEmpty(refMessage.bodyText)) {
Jin Cao0a8e8222014-10-02 11:27:52 -07003182 MessageModification.putBody(values, fullBodyText);
Anthony Lee2a3cc132014-04-22 14:15:25 -07003183 if (hasQuotedText && (quotedTextPos == -1)) {
3184 quotedTextPos = textBody.length();
3185 }
3186 }
3187 if (quotedTextPos != -1) {
3188 // The quoted text pos is the text/html version first and the text/plan version
3189 // if there is no text/html part. The reason for this is because preference
3190 // is given to text/html in the compose window if it exists. In the future, we
3191 // should calculate the index for both since the user could choose to compose
3192 // explicitly in text/plain.
3193 MessageModification.putQuoteStartPos(values, quotedTextPos);
Mindy Pereirac6f1e2a2012-04-04 10:33:45 -07003194 }
3195 } else {
Jin Cao0a8e8222014-10-02 11:27:52 -07003196 MessageModification.putBodyHtml(values, fullBodyHtml);
3197 MessageModification.putBody(values, fullBodyText);
Mindy Pereirac2031972012-04-03 09:38:35 -07003198 }
Anthony Lee2a3cc132014-04-22 14:15:25 -07003199 int draftType = getDraftType(composeMode);
3200 MessageModification.putDraftType(values, draftType);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07003201 MessageModification.putAttachments(values, message.getAttachments());
Mindy Pereira12575862012-03-21 16:30:54 -07003202 if (!TextUtils.isEmpty(refMessageId)) {
3203 MessageModification.putRefMessageId(values, refMessageId);
3204 }
Scott Kennedy60847252013-08-15 15:55:42 -07003205 if (extraValues != null) {
3206 values.putAll(extraValues);
3207 }
Jin Caoaff451f2014-09-09 14:32:04 -07003208
Jin Cao31bb3d62014-09-11 14:01:43 -07003209 SendOrSaveMessage sendOrSaveMessage = new SendOrSaveMessage(context, requestId,
Jin Caoadae7a32014-09-09 18:16:25 -07003210 values, refMessageId, message.getAttachments(), optionalAttachmentFds, save);
Jin Cao0a8e8222014-10-02 11:27:52 -07003211 runSendOrSaveProviderCalls(sendOrSaveMessage, callback, currReplyFromAccount,
3212 originalReplyFromAccount);
Mindy Pereira82cc5662012-01-09 17:29:30 -08003213
Jin Cao7800d292014-08-24 11:31:15 -07003214 LogUtils.i(LOG_TAG, "[compose] SendOrSaveMessage [%s] posted (isSave: %s) - " +
Jin Cao0a8e8222014-10-02 11:27:52 -07003215 "bodyHtml length: %d, bodyText length: %d, quoted text pos: %d, attach count: %d",
3216 requestId, save, message.bodyHtml.length(), message.bodyText.length(),
3217 quotedTextPos, message.getAttachmentCount(true));
Mindy Pereira181df782012-03-01 13:32:44 -08003218 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003219
Paul Westbrookb4931c62013-01-14 17:51:18 -08003220 /**
3221 * Removes any composing spans from the specified string. This will create a new
3222 * SpannableString instance, as to not modify the behavior of the EditText view.
3223 */
3224 private static SpannableString removeComposingSpans(Spanned body) {
3225 final SpannableString messageBody = new SpannableString(body);
3226 BaseInputConnection.removeComposingSpans(messageBody);
Andy Huangff017272014-06-18 00:27:35 -07003227
3228 // Remove watcher spans while we're at it, so any off-UI thread manipulation of these
3229 // spans doesn't trigger unexpected side-effects. This copy is essentially 100% detached
3230 // from the EditText.
3231 //
3232 // (must remove SpanWatchers first to avoid triggering them as we remove other spans)
3233 removeSpansOfType(messageBody, SpanWatcher.class);
3234 removeSpansOfType(messageBody, TextWatcher.class);
3235
Paul Westbrookb4931c62013-01-14 17:51:18 -08003236 return messageBody;
3237 }
3238
Andy Huangff017272014-06-18 00:27:35 -07003239 private static void removeSpansOfType(SpannableString str, Class<?> cls) {
3240 for (Object span : str.getSpans(0, str.length(), cls)) {
3241 str.removeSpan(span);
3242 }
3243 }
3244
Mindy Pereira002ff522012-05-30 10:31:26 -07003245 private static int getDraftType(int mode) {
3246 int draftType = -1;
3247 switch (mode) {
3248 case ComposeActivity.COMPOSE:
3249 draftType = DraftType.COMPOSE;
3250 break;
3251 case ComposeActivity.REPLY:
3252 draftType = DraftType.REPLY;
3253 break;
3254 case ComposeActivity.REPLY_ALL:
3255 draftType = DraftType.REPLY_ALL;
3256 break;
3257 case ComposeActivity.FORWARD:
3258 draftType = DraftType.FORWARD;
3259 break;
3260 }
3261 return draftType;
3262 }
3263
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003264 /**
3265 * Derived classes should override this step to perform additional checks before
3266 * send or save. The default implementation simply calls {@link #sendOrSave(boolean, boolean)}.
3267 */
3268 protected void performAdditionalSendOrSaveSanityChecks(
3269 final boolean save, final boolean showToast, ArrayList<String> recipients) {
3270 sendOrSave(save, showToast);
3271 }
3272
3273 protected void sendOrSave(final boolean save, final boolean showToast) {
Mindy Pereira181df782012-03-01 13:32:44 -08003274 // Check if user is a monkey. Monkeys can compose and hit send
3275 // button but are not allowed to send anything off the device.
Paul Westbrook3ae824c2012-04-06 13:29:39 -07003276 if (ActivityManager.isUserAMonkey()) {
Mindy Pereira181df782012-03-01 13:32:44 -08003277 return;
3278 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003279
Jin Cao77b4c2c2014-05-20 13:55:53 -07003280 final SendOrSaveCallback callback = new SendOrSaveCallback() {
Marc Blank0bbc8582012-04-23 15:07:57 -07003281 @Override
Jin Caoaff451f2014-09-09 14:32:04 -07003282 public void initializeSendOrSave() {
Jin Caoadae7a32014-09-09 18:16:25 -07003283 final Intent i = new Intent(ComposeActivity.this, EmptyService.class);
3284
3285 // API 16+ allows for setClipData. For pre-16 we are going to open the fds
3286 // on the main thread.
3287 if (Utils.isRunningJellybeanOrLater()) {
3288 // Grant the READ permission for the attachments to the service so that
3289 // as long as the service stays alive we won't hit PermissionExceptions.
3290 final ClipDescription desc = new ClipDescription("attachment_uris",
3291 new String[]{ClipDescription.MIMETYPE_TEXT_URILIST});
3292 ClipData clipData = null;
3293 for (Attachment a : mAttachmentsView.getAttachments()) {
3294 if (a != null && !Utils.isEmpty(a.contentUri)) {
3295 final ClipData.Item uriItem = new ClipData.Item(a.contentUri);
3296 if (clipData == null) {
3297 clipData = new ClipData(desc, uriItem);
3298 } else {
3299 clipData.addItem(uriItem);
3300 }
3301 }
3302 }
3303 i.setClipData(clipData);
3304 i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
3305 }
3306
Jin Caoaff451f2014-09-09 14:32:04 -07003307 synchronized (PENDING_SEND_OR_SAVE_TASKS_NUM) {
3308 if (PENDING_SEND_OR_SAVE_TASKS_NUM.getAndAdd(1) == 0) {
Mindy Pereira181df782012-03-01 13:32:44 -08003309 // Start service so we won't be killed if this app is
3310 // put in the background.
Jin Caoadae7a32014-09-09 18:16:25 -07003311 startService(i);
Mindy Pereira181df782012-03-01 13:32:44 -08003312 }
Mindy Pereira181df782012-03-01 13:32:44 -08003313 }
3314 if (sTestSendOrSaveCallback != null) {
Jin Caoaff451f2014-09-09 14:32:04 -07003315 sTestSendOrSaveCallback.initializeSendOrSave();
Mindy Pereira181df782012-03-01 13:32:44 -08003316 }
3317 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003318
Marc Blank0bbc8582012-04-23 15:07:57 -07003319 @Override
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003320 public void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage,
3321 Message message) {
Mindy Pereira181df782012-03-01 13:32:44 -08003322 synchronized (mDraftLock) {
3323 mDraftId = message.id;
3324 mDraft = message;
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003325 if (sRequestMessageIdMap != null) {
Jin Cao31bb3d62014-09-11 14:01:43 -07003326 sRequestMessageIdMap.put(sendOrSaveMessage.mRequestId, mDraftId);
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003327 }
Mindy Pereira181df782012-03-01 13:32:44 -08003328 // Cache request message map, in case the process is killed
3329 saveRequestMap();
3330 }
3331 if (sTestSendOrSaveCallback != null) {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003332 sTestSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage, message);
Mindy Pereira181df782012-03-01 13:32:44 -08003333 }
3334 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003335
Marc Blank0bbc8582012-04-23 15:07:57 -07003336 @Override
Jin Cao31bb3d62014-09-11 14:01:43 -07003337 public long getMessageId() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003338 synchronized (mDraftLock) {
Jin Cao31bb3d62014-09-11 14:01:43 -07003339 return mDraftId;
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003340 }
3341 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003342
Marc Blank0bbc8582012-04-23 15:07:57 -07003343 @Override
Jin Caoaff451f2014-09-09 14:32:04 -07003344 public void sendOrSaveFinished(SendOrSaveMessage message, boolean success) {
Mindy Pereira47d0e652012-07-23 09:45:07 -07003345 // Update the last sent from account.
3346 if (mAccount != null) {
3347 MailAppProvider.getInstance().setLastSentFromAccount(mAccount.uri.toString());
3348 }
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003349 if (success) {
3350 // Successfully sent or saved so reset change markers
3351 discardChanges();
3352 } else {
3353 // A failure happened with saving/sending the draft
3354 // TODO(pwestbro): add a better string that should be used
3355 // when failing to send or save
3356 Toast.makeText(ComposeActivity.this, R.string.send_failed, Toast.LENGTH_SHORT)
3357 .show();
3358 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003359
Jin Caoaff451f2014-09-09 14:32:04 -07003360 synchronized (PENDING_SEND_OR_SAVE_TASKS_NUM) {
3361 if (PENDING_SEND_OR_SAVE_TASKS_NUM.addAndGet(-1) == 0) {
3362 // Stop service so we can be killed.
3363 stopService(new Intent(ComposeActivity.this, EmptyService.class));
3364 }
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003365 }
3366 if (sTestSendOrSaveCallback != null) {
Jin Caoaff451f2014-09-09 14:32:04 -07003367 sTestSendOrSaveCallback.sendOrSaveFinished(message, success);
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003368 }
3369 }
Mindy Pereira181df782012-03-01 13:32:44 -08003370 };
Tony Mantler1e05a1e2013-08-12 16:44:26 -07003371 setAccount(mReplyFromAccount.account);
Mindy Pereira82cc5662012-01-09 17:29:30 -08003372
Jin Cao77b4c2c2014-05-20 13:55:53 -07003373 final Spanned body = removeComposingSpans(mBodyView.getText());
Jin Caoadae7a32014-09-09 18:16:25 -07003374 callback.initializeSendOrSave();
3375
3376 // For pre-JB we need to open the fds on the main thread
3377 final Bundle attachmentFds;
3378 if (!Utils.isRunningJellybeanOrLater()) {
3379 attachmentFds = initializeAttachmentFds(this, mAttachmentsView.getAttachments());
3380 } else {
3381 attachmentFds = null;
3382 }
3383
Jin Cao31bb3d62014-09-11 14:01:43 -07003384 // Generate a unique message id for this request
3385 mRequestId = sRandom.nextInt();
Jin Cao77b4c2c2014-05-20 13:55:53 -07003386 SEND_SAVE_TASK_HANDLER.post(new Runnable() {
3387 @Override
3388 public void run() {
3389 final Message msg = createMessage(mReplyFromAccount, mRefMessage, getMode(), body);
Jin Cao31bb3d62014-09-11 14:01:43 -07003390 sendOrSaveInternal(ComposeActivity.this, mRequestId, mReplyFromAccount,
3391 mDraftAccount, msg, mRefMessage, mQuotedTextView.getQuotedTextIfIncluded(),
3392 callback, save, mComposeMode, mExtraValues, attachmentFds);
Jin Cao77b4c2c2014-05-20 13:55:53 -07003393 }
3394 });
Mindy Pereira82cc5662012-01-09 17:29:30 -08003395
Mindy Pereira181df782012-03-01 13:32:44 -08003396 // Don't display the toast if the user is just changing the orientation,
3397 // but we still need to save the draft to the cursor because this is how we restore
3398 // the attachments when the configuration change completes.
3399 if (showToast && (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) {
3400 Toast.makeText(this, save ? R.string.message_saved : R.string.sending_message,
3401 Toast.LENGTH_LONG).show();
3402 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003403
Mindy Pereira181df782012-03-01 13:32:44 -08003404 // Need to update variables here because the send or save completes
3405 // asynchronously even though the toast shows right away.
3406 discardChanges();
3407 updateSaveUi();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003408
Mindy Pereira181df782012-03-01 13:32:44 -08003409 // If we are sending, finish the activity
3410 if (!save) {
3411 finish();
3412 }
3413 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003414
Mindy Pereira181df782012-03-01 13:32:44 -08003415 /**
3416 * Save the state of the request messageid map. This allows for the Gmail
3417 * process to be killed, but and still allow for ComposeActivity instances
3418 * to be recreated correctly.
3419 */
3420 private void saveRequestMap() {
3421 // TODO: store the request map in user preferences.
3422 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003423
Tony Mantler581edd42014-02-18 15:41:22 -08003424 @SuppressLint("NewApi")
Mindy Pereira2db7d4a2012-08-15 11:00:02 -07003425 private void doAttach(String type) {
Mindy Pereira013194c2012-01-06 15:09:33 -08003426 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
3427 i.addCategory(Intent.CATEGORY_OPENABLE);
Paul Westbrookd6a9a3f2012-04-26 18:47:23 -07003428 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
Andrew Sapperstein05089f32013-10-01 17:00:03 -07003429 i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
Mindy Pereira2db7d4a2012-08-15 11:00:02 -07003430 i.setType(type);
Mindy Pereira013194c2012-01-06 15:09:33 -08003431 mAddingAttachment = true;
Mindy Pereira181df782012-03-01 13:32:44 -08003432 startActivityForResult(Intent.createChooser(i, getText(R.string.select_attachment_type)),
3433 RESULT_PICK_ATTACHMENT);
Mindy Pereira013194c2012-01-06 15:09:33 -08003434 }
3435
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08003436 private void showCcBccViews() {
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08003437 mCcBccView.show(true, true, true);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08003438 if (mCcBccButton != null) {
Jin Cao9d358a12014-07-24 12:15:38 -07003439 mCcBccButton.setVisibility(View.GONE);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08003440 }
3441 }
3442
Andy Huang4fe0af82013-08-20 17:24:51 -07003443 private static String getActionString(int action) {
Andy Huangdc97bf42013-08-15 16:52:45 -07003444 final String msgType;
Andy Huang4fe0af82013-08-20 17:24:51 -07003445 switch (action) {
Andy Huangdc97bf42013-08-15 16:52:45 -07003446 case COMPOSE:
3447 msgType = "new_message";
3448 break;
3449 case REPLY:
3450 msgType = "reply";
3451 break;
3452 case REPLY_ALL:
3453 msgType = "reply_all";
3454 break;
3455 case FORWARD:
3456 msgType = "forward";
3457 break;
3458 default:
3459 msgType = "unknown";
3460 break;
3461 }
Andy Huang4fe0af82013-08-20 17:24:51 -07003462 return msgType;
3463 }
3464
3465 private void logSendOrSave(boolean save) {
3466 if (!Analytics.isLoggable() || mAttachmentsView == null) {
3467 return;
3468 }
3469
3470 final String category = (save) ? "message_save" : "message_send";
3471 final int attachmentCount = getAttachments().size();
3472 final String msgType = getActionString(mComposeMode);
Andy Huangdc97bf42013-08-15 16:52:45 -07003473 final String label;
3474 final long value;
3475 if (mComposeMode == COMPOSE) {
3476 label = Integer.toString(attachmentCount);
3477 value = attachmentCount;
3478 } else {
3479 label = null;
3480 value = 0;
3481 }
3482 Analytics.getInstance().sendEvent(category, msgType, label, value);
3483 }
3484
Mindy Pereira326c6602012-01-04 15:32:42 -08003485 @Override
3486 public boolean onNavigationItemSelected(int position, long itemId) {
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08003487 int initialComposeMode = mComposeMode;
Mindy Pereira326c6602012-01-04 15:32:42 -08003488 if (position == ComposeActivity.REPLY) {
3489 mComposeMode = ComposeActivity.REPLY;
3490 } else if (position == ComposeActivity.REPLY_ALL) {
3491 mComposeMode = ComposeActivity.REPLY_ALL;
3492 } else if (position == ComposeActivity.FORWARD) {
3493 mComposeMode = ComposeActivity.FORWARD;
3494 }
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07003495 clearChangeListeners();
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08003496 if (initialComposeMode != mComposeMode) {
Mindy Pereira154386a2012-01-11 13:02:33 -08003497 resetMessageForModeChange();
mindyp68c0bfc2012-12-04 10:29:48 -08003498 if (mRefMessage != null) {
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08003499 setFieldsFromRefMessage(mComposeMode);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07003500 }
Mindy Pereiraef388302012-06-18 19:07:44 -07003501 boolean showCc = false;
3502 boolean showBcc = false;
3503 if (mDraft != null) {
3504 // Following desktop behavior, if the user has added a BCC
3505 // field to a draft, we show it regardless of compose mode.
Scott Kennedy8960f0a2012-11-07 15:35:50 -08003506 showBcc = !TextUtils.isEmpty(mDraft.getBcc());
Mindy Pereiraef388302012-06-18 19:07:44 -07003507 // Use the draft to determine what to populate.
3508 // If the Bcc field is showing, show the Cc field whether it is populated or not.
Scott Kennedy8960f0a2012-11-07 15:35:50 -08003509 showCc = showBcc
3510 || (!TextUtils.isEmpty(mDraft.getCc()) && mComposeMode == REPLY_ALL);
mindyp68c0bfc2012-12-04 10:29:48 -08003511 }
3512 if (mRefMessage != null) {
mindyp9b1ac572012-09-27 14:12:00 -07003513 showCc = !TextUtils.isEmpty(mCc.getText());
mindyp68c0bfc2012-12-04 10:29:48 -08003514 showBcc = !TextUtils.isEmpty(mBcc.getText());
Mindy Pereiraef388302012-06-18 19:07:44 -07003515 }
Jin Caoc5c550a2014-07-29 11:53:17 -07003516 mCcBccView.show(false /* animate */, showCc, showBcc);
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08003517 }
Mindy Pereiraef388302012-06-18 19:07:44 -07003518 updateHideOrShowCcBcc();
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07003519 initChangeListeners();
Mindy Pereira326c6602012-01-04 15:32:42 -08003520 return true;
3521 }
3522
Mindy Pereirab3112a22012-06-20 12:10:03 -07003523 @VisibleForTesting
3524 protected void resetMessageForModeChange() {
Mindy Pereira154386a2012-01-11 13:02:33 -08003525 // When switching between reply, reply all, forward,
3526 // follow the behavior of webview.
3527 // The contents of the following fields are cleared
3528 // so that they can be populated directly from the
3529 // ref message:
3530 // 1) Any recipient fields
3531 // 2) The subject
3532 mTo.setText("");
3533 mCc.setText("");
3534 mBcc.setText("");
3535 // Any edits to the subject are replaced with the original subject.
3536 mSubject.setText("");
3537
3538 // Any changes to the contents of the following fields are kept:
3539 // 1) Body
3540 // 2) Attachments
3541 // If the user made changes to attachments, keep their changes.
3542 if (!mAttachmentsChanged) {
3543 mAttachmentsView.deleteAllAttachments();
3544 }
3545 }
3546
Mindy Pereira326c6602012-01-04 15:32:42 -08003547 private class ComposeModeAdapter extends ArrayAdapter<String> {
3548
Jin Caof7461632014-08-11 15:21:43 -07003549 private Context mContext;
Mindy Pereira326c6602012-01-04 15:32:42 -08003550 private LayoutInflater mInflater;
3551
3552 public ComposeModeAdapter(Context context) {
3553 super(context, R.layout.compose_mode_item, R.id.mode, getResources()
3554 .getStringArray(R.array.compose_modes));
Jin Caof7461632014-08-11 15:21:43 -07003555 mContext = context;
Mindy Pereira326c6602012-01-04 15:32:42 -08003556 }
3557
3558 private LayoutInflater getInflater() {
3559 if (mInflater == null) {
Jin Caof7461632014-08-11 15:21:43 -07003560 mInflater = LayoutInflater.from(mContext);
Mindy Pereira326c6602012-01-04 15:32:42 -08003561 }
3562 return mInflater;
3563 }
3564
3565 @Override
3566 public View getView(int position, View convertView, ViewGroup parent) {
3567 if (convertView == null) {
3568 convertView = getInflater().inflate(R.layout.compose_mode_display_item, null);
3569 }
3570 ((TextView) convertView.findViewById(R.id.mode)).setText(getItem(position));
3571 return super.getView(position, convertView, parent);
3572 }
3573 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003574
3575 @Override
3576 public void onRespondInline(String text) {
3577 appendToBody(text, false);
mindyp40882432012-09-06 11:07:40 -07003578 mQuotedTextView.setUpperDividerVisible(false);
mindyp1623f9b2012-11-21 12:41:16 -08003579 mRespondedInline = true;
mindyp09dd3732012-12-17 08:37:52 -08003580 if (!mBodyView.hasFocus()) {
mindyp8654d4f2012-12-17 09:01:37 -08003581 mBodyView.requestFocus();
mindyp09dd3732012-12-17 08:37:52 -08003582 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003583 }
3584
3585 /**
3586 * Append text to the body of the message. If there is no existing body
3587 * text, just sets the body to text.
3588 *
Tony Mantler581edd42014-02-18 15:41:22 -08003589 * @param text Text to append
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003590 * @param withSignature True to append a signature.
3591 */
3592 public void appendToBody(CharSequence text, boolean withSignature) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003593 Editable bodyText = mBodyView.getEditableText();
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003594 if (bodyText != null && bodyText.length() > 0) {
3595 bodyText.append(text);
3596 } else {
3597 setBody(text, withSignature);
3598 }
3599 }
3600
3601 /**
3602 * Set the body of the message.
Jin Cao738cafe2014-09-02 16:10:29 -07003603 * Please try to exclusively use this method instead of calling mBodyView.setText(..) directly.
Mindy Pereirabdf7a402012-03-01 15:23:26 -08003604 *
Tony Mantler581edd42014-02-18 15:41:22 -08003605 * @param text text to set
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003606 * @param withSignature True to append a signature.
3607 */
3608 public void setBody(CharSequence text, boolean withSignature) {
Jin Cao738cafe2014-09-02 16:10:29 -07003609 LogUtils.i(LOG_TAG, "Body populated, len: %d, sig: %b", text.length(), withSignature);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003610 mBodyView.setText(text);
Mindy Pereirabdf7a402012-03-01 15:23:26 -08003611 if (withSignature) {
3612 appendSignature();
3613 }
3614 }
3615
3616 private void appendSignature() {
Tony Mantler6a7ac782014-02-19 15:22:02 -08003617 final String newSignature = mCachedSettings != null ? mCachedSettings.signature : null;
3618 final int signaturePos = getSignatureStartPosition(mSignature, mBodyView.getText().toString());
mindyp27083062012-11-15 09:02:01 -08003619 if (!TextUtils.equals(newSignature, mSignature) || signaturePos < 0) {
Mindy Pereirab13917c2012-03-29 08:08:19 -07003620 mSignature = newSignature;
mindyp27083062012-11-15 09:02:01 -08003621 if (!TextUtils.isEmpty(mSignature)) {
Mindy Pereirab13917c2012-03-29 08:08:19 -07003622 // Appending a signature does not count as changing text.
3623 mBodyView.removeTextChangedListener(this);
3624 mBodyView.append(convertToPrintableSignature(mSignature));
3625 mBodyView.addTextChangedListener(this);
3626 }
Tony Mantler6a7ac782014-02-19 15:22:02 -08003627 resetBodySelection();
Mindy Pereirabdf7a402012-03-01 15:23:26 -08003628 }
3629 }
3630
3631 private String convertToPrintableSignature(String signature) {
3632 String signatureResource = getResources().getString(R.string.signature);
3633 if (signature == null) {
3634 signature = "";
3635 }
3636 return String.format(signatureResource, signature);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003637 }
Mindy Pereira1a95a572012-01-05 12:21:29 -08003638
Mindy Pereira5a85e2b2012-01-11 09:53:32 -08003639 @Override
3640 public void onAccountChanged() {
Mindy Pereira92551d02012-04-05 11:31:12 -07003641 mReplyFromAccount = mFromSpinner.getCurrentAccount();
3642 if (!mAccount.equals(mReplyFromAccount.account)) {
mindypf432dbc2012-11-12 16:00:44 -08003643 // Clear a signature, if there was one.
3644 mBodyView.removeTextChangedListener(this);
3645 String oldSignature = mSignature;
3646 String bodyText = getBody().getText().toString();
3647 if (!TextUtils.isEmpty(oldSignature)) {
3648 int pos = getSignatureStartPosition(oldSignature, bodyText);
3649 if (pos > -1) {
Jin Cao738cafe2014-09-02 16:10:29 -07003650 setBody(bodyText.substring(0, pos), false);
mindypf432dbc2012-11-12 16:00:44 -08003651 }
3652 }
Paul Westbrookb1f573c2012-04-06 11:38:28 -07003653 setAccount(mReplyFromAccount.account);
mindypf432dbc2012-11-12 16:00:44 -08003654 mBodyView.addTextChangedListener(this);
Mindy Pereira181df782012-03-01 13:32:44 -08003655 // TODO: handle discarding attachments when switching accounts.
3656 // Only enable save for this draft if there is any other content
3657 // in the message.
3658 if (!isBlank()) {
3659 enableSave(true);
3660 }
3661 mReplyFromChanged = true;
3662 initRecipients();
Greg Bullockd47a7042014-08-13 16:02:59 +02003663
3664 invalidateOptionsMenu();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003665 }
Mindy Pereira1a95a572012-01-05 12:21:29 -08003666 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003667
3668 public void enableSave(boolean enabled) {
3669 if (mSave != null) {
3670 mSave.setEnabled(enabled);
3671 }
3672 }
3673
Tony Mantler2558b502013-07-09 10:53:34 -07003674 public static class DiscardConfirmDialogFragment extends DialogFragment {
Paul Westbrookf0ea4842013-08-13 16:41:18 -07003675 // Public no-args constructor needed for fragment re-instantiation
3676 public DiscardConfirmDialogFragment() {}
3677
Tony Mantler2558b502013-07-09 10:53:34 -07003678 @Override
3679 public Dialog onCreateDialog(Bundle savedInstanceState) {
3680 return new AlertDialog.Builder(getActivity())
3681 .setMessage(R.string.confirm_discard_text)
3682 .setPositiveButton(R.string.discard,
3683 new DialogInterface.OnClickListener() {
3684 @Override
3685 public void onClick(DialogInterface dialog, int which) {
3686 ((ComposeActivity)getActivity()).doDiscardWithoutConfirmation();
3687 }
3688 })
Tony Mantler2b215b72013-07-31 10:20:46 -07003689 .setNegativeButton(R.string.cancel, null)
Tony Mantler2558b502013-07-09 10:53:34 -07003690 .create();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003691 }
3692 }
3693
Mindy Pereiraefe3d252012-03-01 14:20:44 -08003694 private void doDiscard() {
Jin Caoe0037922014-09-16 10:23:50 -07003695 // Only need to ask for confirmation if the draft is in a dirty state.
3696 if (isDraftDirty()) {
3697 final DialogFragment frag = new DiscardConfirmDialogFragment();
3698 frag.show(getFragmentManager(), "discard confirm");
3699 } else {
3700 doDiscardWithoutConfirmation();
3701 }
Mindy Pereiraefe3d252012-03-01 14:20:44 -08003702 }
Jin Caoe0037922014-09-16 10:23:50 -07003703
Mindy Pereira82cc5662012-01-09 17:29:30 -08003704 /**
3705 * Effectively discard the current message.
3706 *
3707 * This method is either invoked from the menu or from the dialog
3708 * once the user has confirmed that they want to discard the message.
Mindy Pereira82cc5662012-01-09 17:29:30 -08003709 */
Tony Mantler2558b502013-07-09 10:53:34 -07003710 private void doDiscardWithoutConfirmation() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003711 synchronized (mDraftLock) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08003712 if (mDraftId != UIProvider.INVALID_MESSAGE_ID) {
3713 ContentValues values = new ContentValues();
Paul Westbrookb7050e62012-03-20 12:59:44 -07003714 values.put(BaseColumns._ID, mDraftId);
Marc Blank78ea8e22012-08-04 11:14:06 -07003715 if (!mAccount.expungeMessageUri.equals(Uri.EMPTY)) {
Mindy Pereiracfb7f332012-02-28 10:23:43 -08003716 getContentResolver().update(mAccount.expungeMessageUri, values, null, null);
3717 } else {
Marc Blank0bbc8582012-04-23 15:07:57 -07003718 getContentResolver().delete(mDraft.uri, null, null);
Mindy Pereiracfb7f332012-02-28 10:23:43 -08003719 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003720 // This is not strictly necessary (since we should not try to
3721 // save the draft after calling this) but it ensures that if we
3722 // do save again for some reason we make a new draft rather than
3723 // trying to resave an expunged draft.
3724 mDraftId = UIProvider.INVALID_MESSAGE_ID;
3725 }
3726 }
3727
Tony Mantler2558b502013-07-09 10:53:34 -07003728 // Display a toast to let the user know
3729 Toast.makeText(this, R.string.message_discarded, Toast.LENGTH_SHORT).show();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003730
3731 // This prevents the draft from being saved in onPause().
3732 discardChanges();
Andy Huangdc97bf42013-08-15 16:52:45 -07003733 mPerformedSendOrDiscard = true;
Mindy Pereira82cc5662012-01-09 17:29:30 -08003734 finish();
3735 }
3736
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003737 private void saveIfNeeded() {
3738 if (mAccount == null) {
3739 // We have not chosen an account yet so there's no way that we can save. This is ok,
3740 // though, since we are saving our state before AccountsActivity is activated. Thus, the
3741 // user has not interacted with us yet and there is no real state to save.
3742 return;
3743 }
3744
Jin Caoe0037922014-09-16 10:23:50 -07003745 if (isDraftDirty()) {
Mindy Pereira48e31b02012-05-30 13:12:24 -07003746 doSave(!mAddingAttachment /* show toast */);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003747 }
3748 }
3749
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003750 @Override
3751 public void onAttachmentDeleted() {
3752 mAttachmentsChanged = true;
mindyp40882432012-09-06 11:07:40 -07003753 // If we are showing any attachments, make sure we have an upper
3754 // divider.
3755 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003756 updateSaveUi();
3757 }
Mindy Pereira75f66632012-01-11 11:42:02 -08003758
mindyp40882432012-09-06 11:07:40 -07003759 @Override
3760 public void onAttachmentAdded() {
3761 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
3762 mAttachmentsView.focusLastAttachment();
3763 }
Mindy Pereira75f66632012-01-11 11:42:02 -08003764
3765 /**
3766 * This is called any time one of our text fields changes.
3767 */
Marc Blank0bbc8582012-04-23 15:07:57 -07003768 @Override
Mindy Pereira75f66632012-01-11 11:42:02 -08003769 public void afterTextChanged(Editable s) {
3770 mTextChanged = true;
3771 updateSaveUi();
3772 }
3773
3774 @Override
3775 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3776 // Do nothing.
3777 }
3778
Marc Blank0bbc8582012-04-23 15:07:57 -07003779 @Override
Mindy Pereira75f66632012-01-11 11:42:02 -08003780 public void onTextChanged(CharSequence s, int start, int before, int count) {
3781 // Do nothing.
3782 }
3783
3784
3785 // There is a big difference between the text associated with an address changing
3786 // to add the display name or to format properly and a recipient being added or deleted.
3787 // Make sure we only notify of changes when a recipient has been added or deleted.
3788 private class RecipientTextWatcher implements TextWatcher {
3789 private HashMap<String, Integer> mContent = new HashMap<String, Integer>();
3790
3791 private RecipientEditTextView mView;
3792
3793 private TextWatcher mListener;
3794
3795 public RecipientTextWatcher(RecipientEditTextView view, TextWatcher listener) {
3796 mView = view;
3797 mListener = listener;
3798 }
3799
3800 @Override
3801 public void afterTextChanged(Editable s) {
3802 if (hasChanged()) {
3803 mListener.afterTextChanged(s);
3804 }
3805 }
3806
3807 private boolean hasChanged() {
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003808 final ArrayList<String> currRecips = buildEmailAddressList(getAddressesFromList(mView));
3809 int totalCount = currRecips.size();
Mindy Pereira75f66632012-01-11 11:42:02 -08003810 int totalPrevCount = 0;
3811 for (Entry<String, Integer> entry : mContent.entrySet()) {
3812 totalPrevCount += entry.getValue();
3813 }
3814 if (totalCount != totalPrevCount) {
3815 return true;
3816 }
3817
3818 for (String recip : currRecips) {
3819 if (!mContent.containsKey(recip)) {
3820 return true;
3821 } else {
3822 int count = mContent.get(recip) - 1;
3823 if (count < 0) {
3824 return true;
3825 } else {
3826 mContent.put(recip, count);
3827 }
3828 }
3829 }
3830 return false;
3831 }
3832
Mindy Pereira75f66632012-01-11 11:42:02 -08003833 @Override
3834 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003835 final ArrayList<String> recips = buildEmailAddressList(getAddressesFromList(mView));
Mindy Pereira75f66632012-01-11 11:42:02 -08003836 for (String recip : recips) {
3837 if (!mContent.containsKey(recip)) {
3838 mContent.put(recip, 1);
3839 } else {
3840 mContent.put(recip, (mContent.get(recip)) + 1);
3841 }
3842 }
3843 }
3844
3845 @Override
3846 public void onTextChanged(CharSequence s, int start, int before, int count) {
3847 // Do nothing.
3848 }
3849 }
Mindy Pereirae011b1d2012-06-18 13:45:26 -07003850
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003851 /**
3852 * Returns a list of email addresses from the recipients. List only contains
3853 * email addresses strips additional info like the recipient's name.
3854 */
3855 private static ArrayList<String> buildEmailAddressList(String[] recips) {
3856 // Tokenize them all and put them in the list.
3857 final ArrayList<String> recipAddresses = Lists.newArrayListWithCapacity(recips.length);
3858 for (int i = 0; i < recips.length; i++) {
3859 recipAddresses.add(Rfc822Tokenizer.tokenize(recips[i])[0].getAddress());
3860 }
3861 return recipAddresses;
3862 }
3863
Mindy Pereirae011b1d2012-06-18 13:45:26 -07003864 public static void registerTestSendOrSaveCallback(SendOrSaveCallback testCallback) {
3865 if (sTestSendOrSaveCallback != null && testCallback != null) {
3866 throw new IllegalStateException("Attempting to register more than one test callback");
3867 }
3868 sTestSendOrSaveCallback = testCallback;
3869 }
Mindy Pereirabddd6f32012-06-20 12:10:03 -07003870
3871 @VisibleForTesting
3872 protected ArrayList<Attachment> getAttachments() {
3873 return mAttachmentsView.getAttachments();
3874 }
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003875
3876 @Override
3877 public Loader<Cursor> onCreateLoader(int id, Bundle args) {
3878 switch (id) {
Alice Yanga990a712013-03-13 18:37:00 -07003879 case INIT_DRAFT_USING_REFERENCE_MESSAGE:
3880 return new CursorLoader(this, mRefMessageUri, UIProvider.MESSAGE_PROJECTION, null,
3881 null, null);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003882 case REFERENCE_MESSAGE_LOADER:
3883 return new CursorLoader(this, mRefMessageUri, UIProvider.MESSAGE_PROJECTION, null,
3884 null, null);
Mindy Pereirab199d172012-08-13 11:04:03 -07003885 case LOADER_ACCOUNT_CURSOR:
3886 return new CursorLoader(this, MailAppProvider.getAccountsUri(),
3887 UIProvider.ACCOUNTS_PROJECTION, null, null, null);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003888 }
3889 return null;
3890 }
3891
3892 @Override
3893 public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Mindy Pereirab199d172012-08-13 11:04:03 -07003894 int id = loader.getId();
3895 switch (id) {
Alice Yanga990a712013-03-13 18:37:00 -07003896 case INIT_DRAFT_USING_REFERENCE_MESSAGE:
Mindy Pereirab199d172012-08-13 11:04:03 -07003897 if (data != null && data.moveToFirst()) {
3898 mRefMessage = new Message(data);
Mindy Pereirab199d172012-08-13 11:04:03 -07003899 Intent intent = getIntent();
Alice Yanga990a712013-03-13 18:37:00 -07003900 initFromRefMessage(mComposeMode);
3901 finishSetup(mComposeMode, intent, null);
3902 if (mComposeMode != FORWARD) {
Mindy Pereirab199d172012-08-13 11:04:03 -07003903 String to = intent.getStringExtra(EXTRA_TO);
3904 if (!TextUtils.isEmpty(to)) {
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08003905 mRefMessage.setTo(null);
3906 mRefMessage.setFrom(null);
Mindy Pereirab199d172012-08-13 11:04:03 -07003907 clearChangeListeners();
3908 mTo.append(to);
3909 initChangeListeners();
3910 }
3911 }
3912 } else {
3913 finish();
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003914 }
Mindy Pereirab199d172012-08-13 11:04:03 -07003915 break;
Alice Yanga990a712013-03-13 18:37:00 -07003916 case REFERENCE_MESSAGE_LOADER:
3917 // Only populate mRefMessage and leave other fields untouched.
3918 if (data != null && data.moveToFirst()) {
3919 mRefMessage = new Message(data);
3920 }
Andy Huang9f855d62013-05-30 17:15:03 -07003921 finishSetup(mComposeMode, getIntent(), mInnerSavedState);
Alice Yanga990a712013-03-13 18:37:00 -07003922 break;
Mindy Pereirab199d172012-08-13 11:04:03 -07003923 case LOADER_ACCOUNT_CURSOR:
3924 if (data != null && data.moveToFirst()) {
3925 // there are accounts now!
3926 Account account;
Paul Westbrookfaa742f2012-11-01 09:50:16 -07003927 final ArrayList<Account> accounts = new ArrayList<Account>();
3928 final ArrayList<Account> initializedAccounts = new ArrayList<Account>();
Mindy Pereirab199d172012-08-13 11:04:03 -07003929 do {
Ray Chen4b0c0122014-07-11 15:24:54 +02003930 account = Account.builder().buildFrom(data);
Paul Westbrookdfa1dec2012-09-26 16:27:28 -07003931 if (account.isAccountReady()) {
Mindy Pereirab199d172012-08-13 11:04:03 -07003932 initializedAccounts.add(account);
3933 }
3934 accounts.add(account);
3935 } while (data.moveToNext());
3936 if (initializedAccounts.size() > 0) {
3937 findViewById(R.id.wait).setVisibility(View.GONE);
3938 getLoaderManager().destroyLoader(LOADER_ACCOUNT_CURSOR);
3939 findViewById(R.id.compose).setVisibility(View.VISIBLE);
Paul Westbrookfaa742f2012-11-01 09:50:16 -07003940 mAccounts = initializedAccounts.toArray(
3941 new Account[initializedAccounts.size()]);
3942
Mindy Pereirab199d172012-08-13 11:04:03 -07003943 finishCreate();
3944 invalidateOptionsMenu();
3945 } else {
3946 // Show "waiting"
3947 account = accounts.size() > 0 ? accounts.get(0) : null;
3948 showWaitFragment(account);
3949 }
3950 }
3951 break;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003952 }
3953 }
3954
Mindy Pereirab199d172012-08-13 11:04:03 -07003955 private void showWaitFragment(Account account) {
3956 WaitFragment fragment = getWaitFragment();
3957 if (fragment != null) {
3958 fragment.updateAccount(account);
3959 } else {
3960 findViewById(R.id.wait).setVisibility(View.VISIBLE);
Andy Huangc96efcc2014-04-09 15:30:42 -07003961 replaceFragment(WaitFragment.newInstance(account, false /* expectingMessages */),
Mindy Pereirab199d172012-08-13 11:04:03 -07003962 FragmentTransaction.TRANSIT_FRAGMENT_OPEN, TAG_WAIT);
3963 }
3964 }
3965
3966 private WaitFragment getWaitFragment() {
3967 return (WaitFragment) getFragmentManager().findFragmentByTag(TAG_WAIT);
3968 }
3969
3970 private int replaceFragment(Fragment fragment, int transition, String tag) {
3971 FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
Mindy Pereirab199d172012-08-13 11:04:03 -07003972 fragmentTransaction.setTransition(transition);
3973 fragmentTransaction.replace(R.id.wait, fragment, tag);
3974 final int transactionId = fragmentTransaction.commitAllowingStateLoss();
3975 return transactionId;
3976 }
3977
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003978 @Override
3979 public void onLoaderReset(Loader<Cursor> arg0) {
3980 // Do nothing.
3981 }
Jin Cao77b4c2c2014-05-20 13:55:53 -07003982
3983 /**
3984 * Background task to convert the message's html to Spanned.
3985 */
3986 private class HtmlToSpannedTask extends AsyncTask<String, Void, Spanned> {
3987
3988 @Override
3989 protected Spanned doInBackground(String... input) {
Andy Huang9ed742c2014-06-18 02:34:50 -07003990 return HtmlUtils.htmlToSpan(input[0], mSpanConverterFactory);
Jin Cao77b4c2c2014-05-20 13:55:53 -07003991 }
3992
3993 @Override
3994 protected void onPostExecute(Spanned spanned) {
3995 mBodyView.removeTextChangedListener(ComposeActivity.this);
Jin Cao738cafe2014-09-02 16:10:29 -07003996 setBody(spanned, false);
Jin Cao77b4c2c2014-05-20 13:55:53 -07003997 mTextChanged = false;
3998 mBodyView.addTextChangedListener(ComposeActivity.this);
3999 }
4000 }
Andrew Sapperstein734718a2014-09-15 17:29:13 -07004001
Andrew Sapperstein734718a2014-09-15 17:29:13 -07004002 @Override
4003 public void onSupportActionModeStarted(ActionMode mode) {
4004 super.onSupportActionModeStarted(mode);
Jin Caof14d8b32014-10-07 18:19:41 -07004005 ViewUtils.setStatusBarColor(this, R.color.action_mode_statusbar_color);
Andrew Sapperstein734718a2014-09-15 17:29:13 -07004006 }
4007
Andrew Sapperstein734718a2014-09-15 17:29:13 -07004008 @Override
4009 public void onSupportActionModeFinished(ActionMode mode) {
4010 super.onSupportActionModeFinished(mode);
Jin Caof14d8b32014-10-07 18:19:41 -07004011 ViewUtils.setStatusBarColor(this, R.color.primary_dark_color);
Andrew Sapperstein734718a2014-09-15 17:29:13 -07004012 }
Andy Huang1f8f4dd2012-10-25 21:35:35 -07004013}