blob: e5ffe2990f390139149f28fd95795dd9a588aa5d [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;
Mindy Pereira326c6602012-01-04 15:32:42 -080021import android.app.ActionBar;
Andy Huang5c5fd572012-04-08 18:19:29 -070022import android.app.ActionBar.OnNavigationListener;
23import android.app.Activity;
Mindy Pereira82cc5662012-01-09 17:29:30 -080024import android.app.ActivityManager;
25import android.app.AlertDialog;
26import android.app.Dialog;
Tony Mantler2558b502013-07-09 10:53:34 -070027import android.app.DialogFragment;
Mindy Pereirab199d172012-08-13 11:04:03 -070028import android.app.Fragment;
Mindy Pereirab199d172012-08-13 11:04:03 -070029import android.app.FragmentTransaction;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -070030import android.app.LoaderManager;
Andrew Sapperstein05089f32013-10-01 17:00:03 -070031import android.content.ClipData;
Mindy Pereira6349a042012-01-04 11:25:01 -080032import android.content.ContentResolver;
Mindy Pereira82cc5662012-01-09 17:29:30 -080033import android.content.ContentValues;
Mindy Pereira6349a042012-01-04 11:25:01 -080034import android.content.Context;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -070035import android.content.CursorLoader;
Mindy Pereira82cc5662012-01-09 17:29:30 -080036import android.content.DialogInterface;
Mindy Pereira6349a042012-01-04 11:25:01 -080037import android.content.Intent;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -070038import android.content.Loader;
Mindy Pereira82cc5662012-01-09 17:29:30 -080039import android.content.pm.ActivityInfo;
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -070040import android.content.res.Resources;
Mindy Pereira7ed1c112012-01-18 10:59:25 -080041import android.database.Cursor;
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;
Mindy Pereira82cc5662012-01-09 17:29:30 -080046import android.os.Handler;
47import android.os.HandlerThread;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -070048import android.os.ParcelFileDescriptor;
Mindy Pereira82cc5662012-01-09 17:29:30 -080049import android.provider.BaseColumns;
Alan Lau439aa5d2014-05-27 17:57:13 -070050import android.support.v4.app.RemoteInput;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080051import android.text.Editable;
Mindy Pereira82cc5662012-01-09 17:29:30 -080052import android.text.Html;
mindyped9c2f02012-10-12 10:02:08 -070053import android.text.SpannableString;
Mindy Pereira82cc5662012-01-09 17:29:30 -080054import android.text.Spanned;
Paul Westbrookc1827622012-01-06 11:27:12 -080055import android.text.TextUtils;
Mindy Pereira82cc5662012-01-09 17:29:30 -080056import android.text.TextWatcher;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080057import android.text.util.Rfc822Token;
Mindy Pereirac17d0732011-12-29 10:46:19 -080058import android.text.util.Rfc822Tokenizer;
Mindy Pereira3cd4f402012-07-17 11:16:18 -070059import android.view.Gravity;
mindyp62d3ec72012-08-24 13:04:09 -070060import android.view.KeyEvent;
Mindy Pereira326c6602012-01-04 15:32:42 -080061import android.view.LayoutInflater;
Mindy Pereirab47f3e22011-12-13 14:25:04 -080062import android.view.Menu;
63import android.view.MenuInflater;
64import android.view.MenuItem;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080065import android.view.View;
66import android.view.View.OnClickListener;
Andy Huang5c5fd572012-04-08 18:19:29 -070067import android.view.ViewGroup;
Paul Westbrookb4931c62013-01-14 17:51:18 -080068import android.view.inputmethod.BaseInputConnection;
mindyp62d3ec72012-08-24 13:04:09 -070069import android.view.inputmethod.EditorInfo;
Mindy Pereira326c6602012-01-04 15:32:42 -080070import android.widget.ArrayAdapter;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080071import android.widget.Button;
Mindy Pereira433b1982012-04-03 11:53:07 -070072import android.widget.EditText;
Mindy Pereira6349a042012-01-04 11:25:01 -080073import android.widget.TextView;
Mindy Pereira013194c2012-01-06 15:09:33 -080074import android.widget.Toast;
Mindy Pereira7b56a612011-12-14 12:32:28 -080075
Mindy Pereirac17d0732011-12-29 10:46:19 -080076import com.android.common.Rfc822Validator;
Tony Mantler9f324232013-08-08 14:24:30 -070077import com.android.common.contacts.DataUsageStatUpdater;
Tony Mantler821e5782014-01-06 15:33:43 -080078import com.android.emailcommon.mail.Address;
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -070079import com.android.ex.chips.BaseRecipientAdapter;
80import com.android.ex.chips.DropdownChipLayouter;
Andy Huang5c5fd572012-04-08 18:19:29 -070081import com.android.ex.chips.RecipientEditTextView;
Scott Kennedy5680ec22013-01-07 13:15:20 -080082import com.android.mail.MailIntentService;
Andy Huang5c5fd572012-04-08 18:19:29 -070083import com.android.mail.R;
Andy Huang761522c2013-08-08 13:09:11 -070084import com.android.mail.analytics.Analytics;
Alice Yang1ebc2db2013-03-14 21:21:44 -070085import com.android.mail.browse.MessageHeaderView;
mindyp40882432012-09-06 11:07:40 -070086import com.android.mail.compose.AttachmentsView.AttachmentAddedOrDeletedListener;
Mindy Pereira9932dee2012-01-10 16:09:50 -080087import com.android.mail.compose.AttachmentsView.AttachmentFailureException;
Mindy Pereira5a85e2b2012-01-11 09:53:32 -080088import com.android.mail.compose.FromAddressSpinner.OnAccountChangedListener;
Andy Huang30e2c242012-01-06 18:14:30 -080089import com.android.mail.compose.QuotedTextView.RespondInlineListener;
Mindy Pereira33fe9082012-01-09 16:24:30 -080090import com.android.mail.providers.Account;
Andy Huang30e2c242012-01-06 18:14:30 -080091import com.android.mail.providers.Attachment;
Scott Kennedy5680ec22013-01-07 13:15:20 -080092import com.android.mail.providers.Folder;
Mindy Pereira47d0e652012-07-23 09:45:07 -070093import com.android.mail.providers.MailAppProvider;
Mindy Pereira3ce64e72012-01-13 14:29:45 -080094import com.android.mail.providers.Message;
Mindy Pereira82cc5662012-01-09 17:29:30 -080095import com.android.mail.providers.MessageModification;
Mindy Pereira92551d02012-04-05 11:31:12 -070096import com.android.mail.providers.ReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -080097import com.android.mail.providers.Settings;
Andy Huang30e2c242012-01-06 18:14:30 -080098import com.android.mail.providers.UIProvider;
Mindy Pereira3ca5bad2012-04-16 11:02:42 -070099import com.android.mail.providers.UIProvider.AccountCapabilities;
Mindy Pereira12575862012-03-21 16:30:54 -0700100import com.android.mail.providers.UIProvider.DraftType;
Alice Yang1ebc2db2013-03-14 21:21:44 -0700101import com.android.mail.ui.AttachmentTile.AttachmentPreview;
Mindy Pereirafa20c1a2012-07-23 13:00:02 -0700102import com.android.mail.ui.MailActivity;
Mindy Pereirab199d172012-08-13 11:04:03 -0700103import com.android.mail.ui.WaitFragment;
Paul Westbrook92227f62012-03-20 10:32:51 -0700104import com.android.mail.utils.AccountUtils;
Mark Wei434f2942012-08-24 11:54:02 -0700105import com.android.mail.utils.AttachmentUtils;
mindypfebd2262012-11-13 17:45:09 -0800106import com.android.mail.utils.ContentProviderTask;
Jin Cao77b4c2c2014-05-20 13:55:53 -0700107import com.android.mail.utils.HtmlUtils;
Paul Westbrookb334c902012-06-25 11:42:46 -0700108import com.android.mail.utils.LogTag;
Andy Huang30e2c242012-01-06 18:14:30 -0800109import com.android.mail.utils.LogUtils;
Alan Lau15490232014-03-06 14:53:14 -0800110import com.android.mail.utils.NotificationActionUtils;
Andy Huang30e2c242012-01-06 18:14:30 -0800111import com.android.mail.utils.Utils;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800112import com.google.common.annotations.VisibleForTesting;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800113import com.google.common.collect.Lists;
Mindy Pereira4a27ea92012-01-05 15:55:25 -0800114import com.google.common.collect.Sets;
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800115
Paul Westbrook3c7f94d2012-10-23 14:13:00 -0700116import java.io.FileNotFoundException;
117import java.io.IOException;
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700118import java.io.UnsupportedEncodingException;
119import java.net.URLDecoder;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800120import java.util.ArrayList;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700121import java.util.Arrays;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800122import java.util.Collection;
Mindy Pereira75f66632012-01-11 11:42:02 -0800123import java.util.HashMap;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800124import java.util.HashSet;
125import java.util.List;
Paul Westbrook1c078cf2012-03-20 16:18:51 -0700126import java.util.Map.Entry;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700127import java.util.Set;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800128import java.util.concurrent.ConcurrentHashMap;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800129
130public class ComposeActivity extends Activity implements OnClickListener, OnNavigationListener,
Tony Mantler2558b502013-07-09 10:53:34 -0700131 RespondInlineListener, TextWatcher,
Alice Yanga990a712013-03-13 18:37:00 -0700132 AttachmentAddedOrDeletedListener, OnAccountChangedListener,
Andrew Sappersteinffd61552014-05-14 15:04:23 -0700133 LoaderManager.LoaderCallbacks<Cursor>, TextView.OnEditorActionListener,
134 RecipientEditTextView.RecipientEntryItemClickedListener {
Scott Kennedya0287a82014-04-07 14:30:13 -0700135 /**
136 * An {@link Intent} action that launches {@link ComposeActivity}, but is handled as if the
137 * {@link Activity} were launched with no special action.
138 */
139 private static final String ACTION_LAUNCH_COMPOSE =
140 "com.android.mail.intent.action.LAUNCH_COMPOSE";
141
Mindy Pereira6349a042012-01-04 11:25:01 -0800142 // Identifiers for which type of composition this is
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700143 public static final int COMPOSE = -1;
144 public static final int REPLY = 0;
145 public static final int REPLY_ALL = 1;
146 public static final int FORWARD = 2;
147 public static final int EDIT_DRAFT = 3;
Mindy Pereira6349a042012-01-04 11:25:01 -0800148
149 // Integer extra holding one of the above compose action
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700150 protected static final String EXTRA_ACTION = "action";
Mindy Pereira6349a042012-01-04 11:25:01 -0800151
Mindy Pereira326689d2012-05-17 10:14:14 -0700152 private static final String EXTRA_SHOW_CC = "showCc";
153 private static final String EXTRA_SHOW_BCC = "showBcc";
mindyp1623f9b2012-11-21 12:41:16 -0800154 private static final String EXTRA_RESPONDED_INLINE = "respondedInline";
mindyp1d7e9142012-11-21 13:54:30 -0800155 private static final String EXTRA_SAVE_ENABLED = "saveEnabled";
Mindy Pereiraa34c9a02012-04-17 14:10:53 -0700156
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700157 private static final String UTF8_ENCODING_NAME = "UTF-8";
158
159 private static final String MAIL_TO = "mailto";
160
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700161 private static final String EXTRA_SUBJECT = "subject";
162
163 private static final String EXTRA_BODY = "body";
164
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700165 /**
166 * Expected to be html formatted text.
167 */
168 private static final String EXTRA_QUOTED_TEXT = "quotedText";
169
mindypd27b6ea2012-10-05 09:43:49 -0700170 protected static final String EXTRA_FROM_ACCOUNT_STRING = "fromAccountString";
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700171
Mark Wei62066e42012-09-13 12:07:02 -0700172 private static final String EXTRA_ATTACHMENT_PREVIEWS = "attachmentPreviews";
173
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700174 // Extra that we can get passed from other activities
Tony Mantler184ec732013-10-24 13:13:49 -0700175 @VisibleForTesting
176 protected static final String EXTRA_TO = "to";
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700177 private static final String EXTRA_CC = "cc";
178 private static final String EXTRA_BCC = "bcc";
179
Scott Kennedy60847252013-08-15 15:55:42 -0700180 /**
181 * An optional extra containing a {@link ContentValues} of values to be added to
182 * {@link SendOrSaveMessage#mValues}.
183 */
184 public static final String EXTRA_VALUES = "extra-values";
185
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700186 // List of all the fields
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700187 static final String[] ALL_EXTRAS = { EXTRA_SUBJECT, EXTRA_BODY, EXTRA_TO, EXTRA_CC, EXTRA_BCC,
188 EXTRA_QUOTED_TEXT };
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700189
Alan Lau439aa5d2014-05-27 17:57:13 -0700190 private static final String LEGACY_WEAR_EXTRA = "com.google.android.wearable.extras";
191
Andrew Sapperstein09da9422014-05-30 09:48:08 -0700192 /**
193 * Constant value for the threshold to use for auto-complete suggestions
194 * for the to/cc/bcc fields.
195 */
196 private static final int COMPLETION_THRESHOLD = 1;
197
Mindy Pereira82cc5662012-01-09 17:29:30 -0800198 private static SendOrSaveCallback sTestSendOrSaveCallback = null;
199 // Map containing information about requests to create new messages, and the id of the
200 // messages that were the result of those requests.
201 //
202 // This map is used when the activity that initiated the save a of a new message, is killed
203 // before the save has completed (and when we know the id of the newly created message). When
204 // a save is completed, the service that is running in the background, will update the map
205 //
206 // When a new ComposeActivity instance is created, it will attempt to use the information in
207 // the previously instantiated map. If ComposeActivity.onCreate() is called, with a bundle
208 // (restoring data from a previous instance), and the map hasn't been created, we will attempt
209 // to populate the map with data stored in shared preferences.
Andy Huang1f8f4dd2012-10-25 21:35:35 -0700210 // FIXME: values in this map are never read.
Mindy Pereira82cc5662012-01-09 17:29:30 -0800211 private static ConcurrentHashMap<Integer, Long> sRequestMessageIdMap = null;
Mindy Pereira6349a042012-01-04 11:25:01 -0800212 /**
213 * Notifies the {@code Activity} that the caller is an Email
214 * {@code Activity}, so that the back behavior may be modified accordingly.
215 *
216 * @see #onAppUpPressed
217 */
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700218 public static final String EXTRA_FROM_EMAIL_TASK = "fromemail";
Mindy Pereira6349a042012-01-04 11:25:01 -0800219
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700220 public static final String EXTRA_ATTACHMENTS = "attachments";
Paul Westbrookf97588b2012-03-20 11:11:37 -0700221
Scott Kennedy5680ec22013-01-07 13:15:20 -0800222 /** If set, we will clear notifications for this folder. */
223 public static final String EXTRA_NOTIFICATION_FOLDER = "extra-notification-folder";
Alan Laue806c942014-06-06 16:19:15 -0700224 public static final String EXTRA_NOTIFICATION_CONVERSATION = "extra-notification-conversation";
Scott Kennedy5680ec22013-01-07 13:15:20 -0800225
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800226 // If this is a reply/forward then this extra will hold the original message
Mindy Pereira36bbcae2012-04-25 09:27:04 -0700227 private static final String EXTRA_IN_REFERENCE_TO_MESSAGE = "in-reference-to-message";
Mindy Pereirab18e5a92012-07-10 11:47:21 -0700228 // If this is a reply/forward then this extra will hold a uri we must query
229 // to get the original message.
230 protected static final String EXTRA_IN_REFERENCE_TO_MESSAGE_URI = "in-reference-to-message-uri";
Mark Wei434f2942012-08-24 11:54:02 -0700231 // If this is an action to edit an existing draft message, this extra will hold the
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700232 // draft message
233 private static final String ORIGINAL_DRAFT_MESSAGE = "original-draft-message";
Mindy Pereira4a27ea92012-01-05 15:55:25 -0800234 private static final String END_TOKEN = ", ";
Paul Westbrookb334c902012-06-25 11:42:46 -0700235 private static final String LOG_TAG = LogTag.getLogTag();
Mindy Pereira013194c2012-01-06 15:09:33 -0800236 // Request numbers for activities we start
237 private static final int RESULT_PICK_ATTACHMENT = 1;
238 private static final int RESULT_CREATE_ACCOUNT = 2;
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700239 // TODO(mindyp) set mime-type for auto send?
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700240 public static final String AUTO_SEND_ACTION = "com.android.mail.action.AUTO_SEND";
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700241
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700242 private static final String EXTRA_SELECTED_REPLY_FROM_ACCOUNT = "replyFromAccount";
243 private static final String EXTRA_REQUEST_ID = "requestId";
244 private static final String EXTRA_FOCUS_SELECTION_START = "focusSelectionStart";
Paul Westbrook176a1992013-07-22 13:57:19 -0700245 private static final String EXTRA_FOCUS_SELECTION_END = "focusSelectionEnd";
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700246 private static final String EXTRA_MESSAGE = "extraMessage";
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700247 private static final int REFERENCE_MESSAGE_LOADER = 0;
Mindy Pereirab199d172012-08-13 11:04:03 -0700248 private static final int LOADER_ACCOUNT_CURSOR = 1;
Alice Yanga990a712013-03-13 18:37:00 -0700249 private static final int INIT_DRAFT_USING_REFERENCE_MESSAGE = 2;
Mindy Pereira47d0e652012-07-23 09:45:07 -0700250 private static final String EXTRA_SELECTED_ACCOUNT = "selectedAccount";
Mindy Pereirab199d172012-08-13 11:04:03 -0700251 private static final String TAG_WAIT = "wait-fragment";
Andrew Sapperstein5cb71802013-10-01 18:31:20 -0700252 private static final String MIME_TYPE_ALL = "*/*";
Mindy Pereira2db7d4a2012-08-15 11:00:02 -0700253 private static final String MIME_TYPE_PHOTO = "image/*";
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800254
Andy Huang9f855d62013-05-30 17:15:03 -0700255 private static final String KEY_INNER_SAVED_STATE = "compose_state";
256
Mindy Pereira82cc5662012-01-09 17:29:30 -0800257 /**
258 * A single thread for running tasks in the background.
259 */
Jin Cao5134be52014-05-06 19:18:38 -0700260 private final static Handler SEND_SAVE_TASK_HANDLER;
261 static {
262 HandlerThread handlerThread = new HandlerThread("Send Message Task Thread");
263 handlerThread.start();
264
265 SEND_SAVE_TASK_HANDLER = new Handler(handlerThread.getLooper());
266 }
267
Andrew Sapperstein50453e42014-05-16 09:25:10 -0700268 private boolean mUseNewChips = false;
269
Mindy Pereirac17d0732011-12-29 10:46:19 -0800270 private RecipientEditTextView mTo;
271 private RecipientEditTextView mCc;
272 private RecipientEditTextView mBcc;
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800273 private Button mCcBccButton;
274 private CcBccView mCcBccView;
Mindy Pereira7b56a612011-12-14 12:32:28 -0800275 private AttachmentsView mAttachmentsView;
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700276 protected Account mAccount;
Tony Mantler59e69092013-08-14 11:05:00 -0700277 protected ReplyFromAccount mReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -0800278 private Settings mCachedSettings;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800279 private Rfc822Validator mValidator;
Mindy Pereira6349a042012-01-04 11:25:01 -0800280 private TextView mSubject;
281
Mindy Pereira326c6602012-01-04 15:32:42 -0800282 private ComposeModeAdapter mComposeModeAdapter;
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700283 protected int mComposeMode = -1;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800284 private boolean mForward;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800285 private QuotedTextView mQuotedTextView;
Tony Mantler59e69092013-08-14 11:05:00 -0700286 protected EditText mBodyView;
Mindy Pereira1a95a572012-01-05 12:21:29 -0800287 private View mFromStatic;
Mindy Pereira2eb17322012-03-07 10:07:34 -0800288 private TextView mFromStaticText;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800289 private View mFromSpinnerWrapper;
Mindy Pereira1883b342012-06-20 08:34:56 -0700290 @VisibleForTesting
291 protected FromAddressSpinner mFromSpinner;
Andy Huang5f082212014-06-11 22:19:21 -0700292 protected boolean mAddingAttachment;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800293 private boolean mAttachmentsChanged;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800294 private boolean mTextChanged;
295 private boolean mReplyFromChanged;
296 private MenuItem mSave;
Mindy Pereirab3112a22012-06-20 12:10:03 -0700297 @VisibleForTesting
298 protected Message mRefMessage;
Mindy Pereira7ed1c112012-01-18 10:59:25 -0800299 private long mDraftId = UIProvider.INVALID_MESSAGE_ID;
300 private Message mDraft;
mindyp44a63392012-11-05 12:05:16 -0800301 private ReplyFromAccount mDraftAccount;
Tony Mantler581edd42014-02-18 15:41:22 -0800302 private final Object mDraftLock = new Object();
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800303
Mindy Pereira326c6602012-01-04 15:32:42 -0800304 /**
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700305 * Boolean indicating whether ComposeActivity was launched from a Gmail controlled view.
306 */
307 private boolean mLaunchedFromEmail = false;
Mindy Pereiracbfb75a2012-06-25 14:52:23 -0700308 private RecipientTextWatcher mToListener;
309 private RecipientTextWatcher mCcListener;
310 private RecipientTextWatcher mBccListener;
Mindy Pereirab18e5a92012-07-10 11:47:21 -0700311 private Uri mRefMessageUri;
Alice Yanga990a712013-03-13 18:37:00 -0700312 private boolean mShowQuotedText = false;
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700313 protected Bundle mInnerSavedState;
Scott Kennedy60847252013-08-15 15:55:42 -0700314 private ContentValues mExtraValues = null;
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700315
mindyp1623f9b2012-11-21 12:41:16 -0800316 // Array of the outstanding send or save tasks. Access is synchronized
317 // with the object itself
318 /* package for testing */
319 @VisibleForTesting
Tony Mantler581edd42014-02-18 15:41:22 -0800320 public final ArrayList<SendOrSaveTask> mActiveTasks = Lists.newArrayList();
mindyp1623f9b2012-11-21 12:41:16 -0800321 // FIXME: this variable is never read. related to sRequestMessageIdMap.
322 private int mRequestId;
323 private String mSignature;
324 private Account[] mAccounts;
325 private boolean mRespondedInline;
Andy Huangdc97bf42013-08-15 16:52:45 -0700326 private boolean mPerformedSendOrDiscard = false;
mindyp1623f9b2012-11-21 12:41:16 -0800327
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700328 /**
Mindy Pereira326c6602012-01-04 15:32:42 -0800329 * Can be called from a non-UI thread.
330 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800331 public static void editDraft(Context launcher, Account account, Message message) {
Scott Kennedy60847252013-08-15 15:55:42 -0700332 launch(launcher, account, message, EDIT_DRAFT, null, null, null, null,
333 null /* extraValues */);
Mindy Pereira326c6602012-01-04 15:32:42 -0800334 }
335
Mindy Pereira6349a042012-01-04 11:25:01 -0800336 /**
337 * Can be called from a non-UI thread.
338 */
Mindy Pereira33fe9082012-01-09 16:24:30 -0800339 public static void compose(Context launcher, Account account) {
Scott Kennedy60847252013-08-15 15:55:42 -0700340 launch(launcher, account, null, COMPOSE, null, null, null, null, null /* extraValues */);
Mindy Pereira6349a042012-01-04 11:25:01 -0800341 }
342
343 /**
344 * Can be called from a non-UI thread.
345 */
Andrew Sapperstein3de76ec2013-07-16 12:08:15 -0700346 public static void composeToAddress(Context launcher, Account account, String toAddress) {
Scott Kennedy60847252013-08-15 15:55:42 -0700347 launch(launcher, account, null, COMPOSE, toAddress, null, null, null,
348 null /* extraValues */);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700349 }
350
351 /**
352 * Can be called from a non-UI thread.
353 */
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700354 public static void composeWithExtraValues(Context launcher, Account account,
355 String subject, final ContentValues extraValues) {
356 launch(launcher, account, null, COMPOSE, null, null, null, subject, extraValues);
357 }
358
359 /**
360 * Can be called from a non-UI thread.
361 */
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -0800362 public static Intent createReplyIntent(final Context launcher, final Account account,
363 final Uri messageUri, final boolean isReplyAll) {
364 return createActionIntent(launcher, account, messageUri, isReplyAll ? REPLY_ALL : REPLY);
365 }
366
367 /**
368 * Can be called from a non-UI thread.
369 */
370 public static Intent createForwardIntent(final Context launcher, final Account account,
371 final Uri messageUri) {
372 return createActionIntent(launcher, account, messageUri, FORWARD);
373 }
374
Scott Kennedya0287a82014-04-07 14:30:13 -0700375 private static Intent createActionIntent(final Context context, final Account account,
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -0800376 final Uri messageUri, final int action) {
Scott Kennedya0287a82014-04-07 14:30:13 -0700377 final Intent intent = new Intent(ACTION_LAUNCH_COMPOSE);
378 intent.setPackage(context.getPackageName());
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -0800379
Paul Westbrook6d2442b2013-07-17 17:51:51 -0700380 updateActionIntent(account, messageUri, action, intent);
381
382 return intent;
383 }
384
385 @VisibleForTesting
386 static Intent updateActionIntent(Account account, Uri messageUri, int action, Intent intent) {
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -0800387 intent.putExtra(EXTRA_FROM_EMAIL_TASK, true);
388 intent.putExtra(EXTRA_ACTION, action);
389 intent.putExtra(Utils.EXTRA_ACCOUNT, account);
390 intent.putExtra(EXTRA_IN_REFERENCE_TO_MESSAGE_URI, messageUri);
391
392 return intent;
393 }
394
395 /**
396 * Can be called from a non-UI thread.
397 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800398 public static void reply(Context launcher, Account account, Message message) {
Scott Kennedy60847252013-08-15 15:55:42 -0700399 launch(launcher, account, message, REPLY, null, null, null, null, null /* extraValues */);
Mindy Pereira6349a042012-01-04 11:25:01 -0800400 }
401
402 /**
403 * Can be called from a non-UI thread.
404 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800405 public static void replyAll(Context launcher, Account account, Message message) {
Scott Kennedy60847252013-08-15 15:55:42 -0700406 launch(launcher, account, message, REPLY_ALL, null, null, null, null,
407 null /* extraValues */);
Mindy Pereira6349a042012-01-04 11:25:01 -0800408 }
409
410 /**
411 * Can be called from a non-UI thread.
412 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800413 public static void forward(Context launcher, Account account, Message message) {
Scott Kennedy60847252013-08-15 15:55:42 -0700414 launch(launcher, account, message, FORWARD, null, null, null, null, null /* extraValues */);
Mindy Pereira6349a042012-01-04 11:25:01 -0800415 }
416
Alice Yang1ebc2db2013-03-14 21:21:44 -0700417 public static void reportRenderingFeedback(Context launcher, Account account, Message message,
418 String body) {
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700419 launch(launcher, account, message, FORWARD,
Scott Kennedy60847252013-08-15 15:55:42 -0700420 "android-gmail-readability@google.com", body, null, null, null /* extraValues */);
Alice Yang1ebc2db2013-03-14 21:21:44 -0700421 }
422
Scott Kennedya0287a82014-04-07 14:30:13 -0700423 private static void launch(Context context, Account account, Message message, int action,
Scott Kennedy60847252013-08-15 15:55:42 -0700424 String toAddress, String body, String quotedText, String subject,
425 final ContentValues extraValues) {
Scott Kennedya0287a82014-04-07 14:30:13 -0700426 Intent intent = new Intent(ACTION_LAUNCH_COMPOSE);
427 intent.setPackage(context.getPackageName());
Mindy Pereira6349a042012-01-04 11:25:01 -0800428 intent.putExtra(EXTRA_FROM_EMAIL_TASK, true);
429 intent.putExtra(EXTRA_ACTION, action);
430 intent.putExtra(Utils.EXTRA_ACCOUNT, account);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700431 if (action == EDIT_DRAFT) {
432 intent.putExtra(ORIGINAL_DRAFT_MESSAGE, message);
433 } else {
434 intent.putExtra(EXTRA_IN_REFERENCE_TO_MESSAGE, message);
435 }
Alice Yang1ebc2db2013-03-14 21:21:44 -0700436 if (toAddress != null) {
437 intent.putExtra(EXTRA_TO, toAddress);
438 }
439 if (body != null) {
440 intent.putExtra(EXTRA_BODY, body);
441 }
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700442 if (quotedText != null) {
443 intent.putExtra(EXTRA_QUOTED_TEXT, quotedText);
444 }
445 if (subject != null) {
446 intent.putExtra(EXTRA_SUBJECT, subject);
447 }
Scott Kennedy60847252013-08-15 15:55:42 -0700448 if (extraValues != null) {
449 LogUtils.d(LOG_TAG, "Launching with extraValues: %s", extraValues.toString());
450 intent.putExtra(EXTRA_VALUES, extraValues);
451 }
Scott Kennedya0287a82014-04-07 14:30:13 -0700452 context.startActivity(intent);
Mindy Pereira6349a042012-01-04 11:25:01 -0800453 }
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800454
Scott Kennedya0287a82014-04-07 14:30:13 -0700455 public static void composeMailto(Context context, Account account, Uri mailto) {
456 final Intent intent = new Intent(Intent.ACTION_VIEW, mailto);
457 intent.setPackage(context.getPackageName());
Andy Huang0a2a3462013-12-20 15:56:13 -0800458 intent.putExtra(EXTRA_FROM_EMAIL_TASK, true);
459 intent.putExtra(Utils.EXTRA_ACCOUNT, account);
Scott Kennedya0287a82014-04-07 14:30:13 -0700460 context.startActivity(intent);
Andy Huang0a2a3462013-12-20 15:56:13 -0800461 }
462
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800463 @Override
Scott Kennedyd9063902013-08-02 22:14:37 -0700464 protected void onCreate(Bundle savedInstanceState) {
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800465 super.onCreate(savedInstanceState);
Mindy Pereira3528d362012-01-05 14:39:44 -0800466 setContentView(R.layout.compose);
Andy Huang9f855d62013-05-30 17:15:03 -0700467 mInnerSavedState = (savedInstanceState != null) ?
468 savedInstanceState.getBundle(KEY_INNER_SAVED_STATE) : null;
Mindy Pereirab199d172012-08-13 11:04:03 -0700469 checkValidAccounts();
470 }
471
Andrew Sapperstein50453e42014-05-16 09:25:10 -0700472 private boolean shouldUseNewChips() {
473 // Get the Android ID from this device
474 String androidId = android.provider.Settings.Secure
475 .getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
476
477 // If we don't have a valid android id, just use account name hash code
478 if (TextUtils.isEmpty(androidId)) {
479 LogUtils.d(LOG_TAG, "Fallback to email address");
480 androidId = mAccount.getEmailAddress();
481 }
482
483 // randomly cut our userbase in half
484 return (androidId.hashCode() % 2) == 1;
485 }
486
Mindy Pereirab199d172012-08-13 11:04:03 -0700487 private void finishCreate() {
Andy Huang9f855d62013-05-30 17:15:03 -0700488 final Bundle savedState = mInnerSavedState;
Mindy Pereira3528d362012-01-05 14:39:44 -0800489 findViews();
Tony Mantler581edd42014-02-18 15:41:22 -0800490 final Intent intent = getIntent();
491 final Message message;
492 final ArrayList<AttachmentPreview> previews;
Alice Yanga990a712013-03-13 18:37:00 -0700493 mShowQuotedText = false;
Tony Mantler581edd42014-02-18 15:41:22 -0800494 final CharSequence quotedText;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700495 int action;
Mindy Pereira47d0e652012-07-23 09:45:07 -0700496 // Check for any of the possibly supplied accounts.;
Tony Mantler581edd42014-02-18 15:41:22 -0800497 final Account account;
Andy Huang9f855d62013-05-30 17:15:03 -0700498 if (hadSavedInstanceStateMessage(savedState)) {
499 action = savedState.getInt(EXTRA_ACTION, COMPOSE);
500 account = savedState.getParcelable(Utils.EXTRA_ACCOUNT);
Tony Mantler581edd42014-02-18 15:41:22 -0800501 message = savedState.getParcelable(EXTRA_MESSAGE);
Mark Wei62066e42012-09-13 12:07:02 -0700502
Andy Huang9f855d62013-05-30 17:15:03 -0700503 previews = savedState.getParcelableArrayList(EXTRA_ATTACHMENT_PREVIEWS);
Tony Mantler581edd42014-02-18 15:41:22 -0800504 mRefMessage = savedState.getParcelable(EXTRA_IN_REFERENCE_TO_MESSAGE);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700505 quotedText = savedState.getCharSequence(EXTRA_QUOTED_TEXT);
Scott Kennedy44d44812013-08-19 14:18:31 -0700506
507 mExtraValues = savedState.getParcelable(EXTRA_VALUES);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700508 } else {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700509 account = obtainAccount(intent);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700510 action = intent.getIntExtra(EXTRA_ACTION, COMPOSE);
511 // Initialize the message from the message in the intent
Tony Mantler581edd42014-02-18 15:41:22 -0800512 message = intent.getParcelableExtra(ORIGINAL_DRAFT_MESSAGE);
Mark Wei62066e42012-09-13 12:07:02 -0700513 previews = intent.getParcelableArrayListExtra(EXTRA_ATTACHMENT_PREVIEWS);
Tony Mantler581edd42014-02-18 15:41:22 -0800514 mRefMessage = intent.getParcelableExtra(EXTRA_IN_REFERENCE_TO_MESSAGE);
515 mRefMessageUri = intent.getParcelableExtra(EXTRA_IN_REFERENCE_TO_MESSAGE_URI);
516 quotedText = null;
Andy Huang4fe0af82013-08-20 17:24:51 -0700517
518 if (Analytics.isLoggable()) {
519 if (intent.getBooleanExtra(Utils.EXTRA_FROM_NOTIFICATION, false)) {
520 Analytics.getInstance().sendEvent(
521 "notification_action", "compose", getActionString(action), 0);
522 }
523 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700524 }
Mark Wei62066e42012-09-13 12:07:02 -0700525 mAttachmentsView.setAttachmentPreviews(previews);
Paul Westbrook92227f62012-03-20 10:32:51 -0700526
527 setAccount(account);
Mindy Pereira818143e2012-01-11 13:59:49 -0800528 if (mAccount == null) {
529 return;
530 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700531
Andrew Sapperstein50453e42014-05-16 09:25:10 -0700532 mUseNewChips = shouldUseNewChips();
Scott Kennedyfe853d32013-06-19 11:47:35 -0700533 initRecipients();
534
Scott Kennedy5680ec22013-01-07 13:15:20 -0800535 // Clear the notification and mark the conversation as seen, if necessary
536 final Folder notificationFolder =
537 intent.getParcelableExtra(EXTRA_NOTIFICATION_FOLDER);
Scott Kennedy5680ec22013-01-07 13:15:20 -0800538
Alan Laue806c942014-06-06 16:19:15 -0700539 if (notificationFolder != null) {
540 final Uri conversationUri = intent.getParcelableExtra(EXTRA_NOTIFICATION_CONVERSATION);
541 Intent actionIntent;
542 if (conversationUri != null) {
543 actionIntent = new Intent(MailIntentService.ACTION_RESEND_NOTIFICATIONS_WEAR);
544 actionIntent.putExtra(Utils.EXTRA_CONVERSATION, conversationUri);
545 } else {
546 actionIntent = new Intent(MailIntentService.ACTION_CLEAR_NEW_MAIL_NOTIFICATIONS);
547 actionIntent.setData(Utils.appendVersionQueryParameter(this,
548 notificationFolder.folderUri.fullUri));
549 }
550 actionIntent.setPackage(getPackageName());
551 actionIntent.putExtra(Utils.EXTRA_ACCOUNT, account);
552 actionIntent.putExtra(Utils.EXTRA_FOLDER, notificationFolder);
553
554 startService(actionIntent);
Scott Kennedy5680ec22013-01-07 13:15:20 -0800555 }
556
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700557 if (intent.getBooleanExtra(EXTRA_FROM_EMAIL_TASK, false)) {
558 mLaunchedFromEmail = true;
559 } else if (Intent.ACTION_SEND.equals(intent.getAction())) {
560 final Uri dataUri = intent.getData();
561 if (dataUri != null) {
562 final String dataScheme = intent.getData().getScheme();
563 final String accountScheme = mAccount.composeIntentUri.getScheme();
564 mLaunchedFromEmail = TextUtils.equals(dataScheme, accountScheme);
565 }
566 }
567
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700568 if (mRefMessageUri != null) {
Alice Yanga990a712013-03-13 18:37:00 -0700569 mShowQuotedText = true;
570 mComposeMode = action;
Alan Lau15490232014-03-06 14:53:14 -0800571
572 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
Alan Lauc4288f22014-05-16 11:44:27 -0700573 Bundle remoteInput = RemoteInput.getResultsFromIntent(intent);
Alan Lau439aa5d2014-05-27 17:57:13 -0700574 String wearReply = null;
Alan Lauc4288f22014-05-16 11:44:27 -0700575 if (remoteInput != null) {
Alan Lau439aa5d2014-05-27 17:57:13 -0700576 LogUtils.d(LOG_TAG, "Got remote input from new api");
577 CharSequence input = remoteInput.getCharSequence(
Alan Lauc4288f22014-05-16 11:44:27 -0700578 NotificationActionUtils.WEAR_REPLY_INPUT);
Alan Lau439aa5d2014-05-27 17:57:13 -0700579 if (input != null) {
580 wearReply = input.toString();
Alan Lau15490232014-03-06 14:53:14 -0800581 }
Alan Lauc4288f22014-05-16 11:44:27 -0700582 } else {
Alan Lau439aa5d2014-05-27 17:57:13 -0700583 // TODO: remove after legacy code has been removed.
584 LogUtils.d(LOG_TAG,
585 "No remote input from new api, falling back to compatibility mode");
586 ClipData clipData = intent.getClipData();
587 if (clipData != null
588 && LEGACY_WEAR_EXTRA.equals(clipData.getDescription().getLabel())) {
589 Bundle extras = clipData.getItemAt(0).getIntent().getExtras();
590 if (extras != null) {
591 wearReply = extras.getString(NotificationActionUtils.WEAR_REPLY_INPUT);
592 }
593 }
594 }
595
596 if (!TextUtils.isEmpty(wearReply)) {
597 createWearReplyTask(this, mRefMessageUri, UIProvider.MESSAGE_PROJECTION,
598 mComposeMode, wearReply).execute();
599 finish();
600 return;
601 } else {
602 LogUtils.w(LOG_TAG, "remote input string is null");
Alan Lau15490232014-03-06 14:53:14 -0800603 }
604 }
605
Alice Yanga990a712013-03-13 18:37:00 -0700606 getLoaderManager().initLoader(INIT_DRAFT_USING_REFERENCE_MESSAGE, null, this);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700607 return;
608 } else if (message != null && action != EDIT_DRAFT) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700609 initFromDraftMessage(message);
610 initQuotedTextFromRefMessage(mRefMessage, action);
Alice Yanga990a712013-03-13 18:37:00 -0700611 mShowQuotedText = message.appendRefMessageContent;
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700612 // if we should be showing quoted text but mRefMessage is null
613 // and we have some quotedText, display that
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700614 if (mShowQuotedText && mRefMessage == null) {
615 if (quotedText != null) {
616 initQuotedText(quotedText, false /* shouldQuoteText */);
617 } else if (mExtraValues != null) {
618 initExtraValues(mExtraValues);
619 return;
620 }
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700621 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700622 } else if (action == EDIT_DRAFT) {
Tony Mantler581edd42014-02-18 15:41:22 -0800623 if (message == null) {
624 throw new IllegalStateException("Message must not be null to edit draft");
625 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700626 initFromDraftMessage(message);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700627 // Update the action to the draft type of the previous draft
628 switch (message.draftType) {
629 case UIProvider.DraftType.REPLY:
630 action = REPLY;
631 break;
632 case UIProvider.DraftType.REPLY_ALL:
633 action = REPLY_ALL;
634 break;
635 case UIProvider.DraftType.FORWARD:
636 action = FORWARD;
637 break;
638 case UIProvider.DraftType.COMPOSE:
639 default:
640 action = COMPOSE;
641 break;
642 }
Alice Yanga990a712013-03-13 18:37:00 -0700643 LogUtils.d(LOG_TAG, "Previous draft had action type: %d", action);
644
645 mShowQuotedText = message.appendRefMessageContent;
646 if (message.refMessageUri != null) {
647 // If we're editing an existing draft that was in reference to an existing message,
648 // still need to load that original message since we might need to refer to the
649 // original sender and recipients if user switches "reply <-> reply-all".
650 mRefMessageUri = message.refMessageUri;
651 mComposeMode = action;
652 getLoaderManager().initLoader(REFERENCE_MESSAGE_LOADER, null, this);
653 return;
654 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700655 } else if ((action == REPLY || action == REPLY_ALL || action == FORWARD)) {
656 if (mRefMessage != null) {
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -0800657 initFromRefMessage(action);
Alice Yanga990a712013-03-13 18:37:00 -0700658 mShowQuotedText = true;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700659 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700660 } else {
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700661 if (initFromExtras(intent)) {
662 return;
663 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700664 }
Alice Yanga990a712013-03-13 18:37:00 -0700665
666 mComposeMode = action;
Andy Huang9f855d62013-05-30 17:15:03 -0700667 finishSetup(action, intent, savedState);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700668 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700669
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -0700670 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
Alan Lau15490232014-03-06 14:53:14 -0800671 private static AsyncTask<Void, Void, Message> createWearReplyTask(
672 final ComposeActivity composeActivity,
673 final Uri refMessageUri, final String[] projection, final int action,
674 final String wearReply) {
675 return new AsyncTask<Void, Void, Message>() {
676 private Intent mEmptyServiceIntent = new Intent(composeActivity, EmptyService.class);
677
678 @Override
679 protected void onPreExecute() {
680 // Start service so we won't be killed if this app is put in the background.
681 composeActivity.startService(mEmptyServiceIntent);
682 }
683
684 @Override
685 protected Message doInBackground(Void... params) {
686 Cursor cursor = composeActivity.getContentResolver()
687 .query(refMessageUri, projection, null, null, null, null);
688 if (cursor != null) {
689 try {
690 cursor.moveToFirst();
691 return new Message(cursor);
692 } finally {
693 cursor.close();
694 }
695 }
696 return null;
697 }
698
699 @Override
700 protected void onPostExecute(Message message) {
701 composeActivity.stopService(mEmptyServiceIntent);
702
703 composeActivity.mRefMessage = message;
704 composeActivity.initFromRefMessage(action);
705 composeActivity.setBody(wearReply, false);
706 composeActivity.finishSetup(action, composeActivity.getIntent(), null);
707 composeActivity.sendOrSaveWithSanityChecks(false /* save */, true /* show toast */,
708 false /* orientationChanged */, true /* autoSend */);
709 }
710 };
711 }
712
Mindy Pereirab199d172012-08-13 11:04:03 -0700713 private void checkValidAccounts() {
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700714 final Account[] allAccounts = AccountUtils.getAccounts(this);
715 if (allAccounts == null || allAccounts.length == 0) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700716 final Intent noAccountIntent = MailAppProvider.getNoAccountIntent(this);
717 if (noAccountIntent != null) {
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700718 mAccounts = null;
Mindy Pereirab199d172012-08-13 11:04:03 -0700719 startActivityForResult(noAccountIntent, RESULT_CREATE_ACCOUNT);
720 }
721 } else {
mindyp26d4d2d2012-09-18 17:30:32 -0700722 // If none of the accounts are syncing, setup a watcher.
Mindy Pereirab199d172012-08-13 11:04:03 -0700723 boolean anySyncing = false;
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700724 for (Account a : allAccounts) {
Paul Westbrookdfa1dec2012-09-26 16:27:28 -0700725 if (a.isAccountReady()) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700726 anySyncing = true;
727 break;
728 }
729 }
730 if (!anySyncing) {
731 // There are accounts, but none are sync'd, which is just like having no accounts.
732 mAccounts = null;
733 getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, null, this);
734 return;
735 }
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700736 mAccounts = AccountUtils.getSyncingAccounts(this);
Mindy Pereirab199d172012-08-13 11:04:03 -0700737 finishCreate();
738 }
739 }
740
Mindy Pereira47d0e652012-07-23 09:45:07 -0700741 private Account obtainAccount(Intent intent) {
742 Account account = null;
743 Object accountExtra = null;
744 if (intent != null && intent.getExtras() != null) {
745 accountExtra = intent.getExtras().get(Utils.EXTRA_ACCOUNT);
746 if (accountExtra instanceof Account) {
747 return (Account) accountExtra;
mindyp7ae042e2012-08-27 13:27:37 -0700748 } else if (accountExtra instanceof String) {
749 // This is the Account attached to the widget compose intent.
Tony Mantler26a20752014-02-28 16:44:24 -0800750 account = Account.newInstance((String) accountExtra);
mindyp7ae042e2012-08-27 13:27:37 -0700751 if (account != null) {
752 return account;
753 }
Mindy Pereira47d0e652012-07-23 09:45:07 -0700754 }
mindyp5ee9dc42013-01-08 09:54:54 -0800755 accountExtra = intent.hasExtra(Utils.EXTRA_ACCOUNT) ?
756 intent.getStringExtra(Utils.EXTRA_ACCOUNT) :
757 intent.getStringExtra(EXTRA_SELECTED_ACCOUNT);
Mindy Pereira47d0e652012-07-23 09:45:07 -0700758 }
Tony Mantler581edd42014-02-18 15:41:22 -0800759
760 MailAppProvider provider = MailAppProvider.getInstance();
761 String lastAccountUri = provider.getLastSentFromAccount();
762 if (TextUtils.isEmpty(lastAccountUri)) {
763 lastAccountUri = provider.getLastViewedAccount();
Mindy Pereira47d0e652012-07-23 09:45:07 -0700764 }
Tony Mantler581edd42014-02-18 15:41:22 -0800765 if (!TextUtils.isEmpty(lastAccountUri)) {
766 accountExtra = Uri.parse(lastAccountUri);
767 }
768
Mindy Pereirab199d172012-08-13 11:04:03 -0700769 if (mAccounts != null && mAccounts.length > 0) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700770 if (accountExtra instanceof String && !TextUtils.isEmpty((String) accountExtra)) {
771 // For backwards compatibility, we need to check account
772 // names.
Mindy Pereirab199d172012-08-13 11:04:03 -0700773 for (Account a : mAccounts) {
Tony Mantler79b11562013-10-09 15:31:50 -0700774 if (a.getEmailAddress().equals(accountExtra)) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700775 account = a;
776 }
777 }
778 } else if (accountExtra instanceof Uri) {
779 // The uri of the last viewed account is what is stored in
780 // the current code base.
Mindy Pereirab199d172012-08-13 11:04:03 -0700781 for (Account a : mAccounts) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700782 if (a.uri.equals(accountExtra)) {
783 account = a;
784 }
785 }
Mindy Pereirab199d172012-08-13 11:04:03 -0700786 }
787 if (account == null) {
788 account = mAccounts[0];
Mindy Pereira47d0e652012-07-23 09:45:07 -0700789 }
790 }
791 return account;
792 }
793
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700794 protected void finishSetup(int action, Intent intent, Bundle savedInstanceState) {
mindyp34a3c562012-11-06 15:12:15 -0800795 setFocus(action);
Mindy Pereiraf7fc6c32012-06-19 15:18:33 -0700796 // Don't bother with the intent if we have procured a message from the
797 // intent already.
798 if (!hadSavedInstanceStateMessage(savedInstanceState)) {
799 initAttachmentsFromIntent(intent);
800 }
Alice Yanga990a712013-03-13 18:37:00 -0700801 initActionBar();
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700802 initFromSpinner(savedInstanceState != null ? savedInstanceState : intent.getExtras(),
803 action);
mindypd4a48662012-11-08 17:13:49 -0800804
805 // If this is a draft message, the draft account is whatever account was
806 // used to open the draft message in Compose.
807 if (mDraft != null) {
808 mDraftAccount = mReplyFromAccount;
809 }
810
Mindy Pereira75f66632012-01-11 11:42:02 -0800811 initChangeListeners();
Jin Cao32973b42014-05-06 16:12:11 -0700812
813 // These two should be identical since we check CC and BCC the same way
814 boolean showCc = !TextUtils.isEmpty(mCc.getText()) || (savedInstanceState != null &&
815 savedInstanceState.getBoolean(EXTRA_SHOW_CC));
816 boolean showBcc = !TextUtils.isEmpty(mBcc.getText()) || (savedInstanceState != null &&
817 savedInstanceState.getBoolean(EXTRA_SHOW_BCC));
818 mCcBccView.show(false /* animate */, showCc, showBcc);
Mindy Pereira326689d2012-05-17 10:14:14 -0700819 updateHideOrShowCcBcc();
Alice Yanga990a712013-03-13 18:37:00 -0700820 updateHideOrShowQuotedText(mShowQuotedText);
mindyp1623f9b2012-11-21 12:41:16 -0800821
Tony Mantler581edd42014-02-18 15:41:22 -0800822 mRespondedInline = mInnerSavedState != null &&
823 mInnerSavedState.getBoolean(EXTRA_RESPONDED_INLINE);
mindyp1623f9b2012-11-21 12:41:16 -0800824 if (mRespondedInline) {
825 mQuotedTextView.setVisibility(View.GONE);
826 }
Mindy Pereira71c9e562012-05-17 11:01:02 -0700827 }
828
Scott Kennedyff8553f2013-04-05 20:57:44 -0700829 private static boolean hadSavedInstanceStateMessage(final Bundle savedInstanceState) {
Mindy Pereiraf7fc6c32012-06-19 15:18:33 -0700830 return savedInstanceState != null && savedInstanceState.containsKey(EXTRA_MESSAGE);
831 }
832
Mindy Pereira71c9e562012-05-17 11:01:02 -0700833 private void updateHideOrShowQuotedText(boolean showQuotedText) {
834 mQuotedTextView.updateCheckedState(showQuotedText);
mindyp40882432012-09-06 11:07:40 -0700835 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
Mindy Pereira433b1982012-04-03 11:53:07 -0700836 }
837
838 private void setFocus(int action) {
839 if (action == EDIT_DRAFT) {
840 int type = mDraft.draftType;
841 switch (type) {
842 case UIProvider.DraftType.COMPOSE:
843 case UIProvider.DraftType.FORWARD:
844 action = COMPOSE;
845 break;
846 case UIProvider.DraftType.REPLY:
847 case UIProvider.DraftType.REPLY_ALL:
848 default:
849 action = REPLY;
850 break;
851 }
852 }
853 switch (action) {
854 case FORWARD:
855 case COMPOSE:
mindyp27083062012-11-15 09:02:01 -0800856 if (TextUtils.isEmpty(mTo.getText())) {
857 mTo.requestFocus();
858 break;
859 }
Scott Kennedyff8553f2013-04-05 20:57:44 -0700860 //$FALL-THROUGH$
Mindy Pereira433b1982012-04-03 11:53:07 -0700861 case REPLY:
862 case REPLY_ALL:
863 default:
864 focusBody();
865 break;
866 }
867 }
868
869 /**
870 * Focus the body of the message.
871 */
Tony Mantler6a7ac782014-02-19 15:22:02 -0800872 private void focusBody() {
Mindy Pereira433b1982012-04-03 11:53:07 -0700873 mBodyView.requestFocus();
Tony Mantler6a7ac782014-02-19 15:22:02 -0800874 resetBodySelection();
875 }
Mindy Pereira433b1982012-04-03 11:53:07 -0700876
Tony Mantler6a7ac782014-02-19 15:22:02 -0800877 private void resetBodySelection() {
878 int length = mBodyView.getText().length();
Mindy Pereira433b1982012-04-03 11:53:07 -0700879 int signatureStartPos = getSignatureStartPosition(
880 mSignature, mBodyView.getText().toString());
881 if (signatureStartPos > -1) {
882 // In case the user deleted the newlines...
883 mBodyView.setSelection(signatureStartPos);
mindyp8743cfc2012-09-18 13:29:08 -0700884 } else if (length >= 0) {
Mindy Pereira433b1982012-04-03 11:53:07 -0700885 // Move cursor to the end.
886 mBodyView.setSelection(length);
887 }
Mindy Pereira1a95a572012-01-05 12:21:29 -0800888 }
889
890 @Override
Andy Huang761522c2013-08-08 13:09:11 -0700891 protected void onStart() {
892 super.onStart();
893
894 Analytics.getInstance().activityStart(this);
895 }
896
897 @Override
898 protected void onStop() {
899 super.onStop();
900
901 Analytics.getInstance().activityStop(this);
902 }
903
904 @Override
Mindy Pereira1a95a572012-01-05 12:21:29 -0800905 protected void onResume() {
906 super.onResume();
907 // Update the from spinner as other accounts
908 // may now be available.
Mindy Pereira818143e2012-01-11 13:59:49 -0800909 if (mFromSpinner != null && mAccount != null) {
Andrew Sappersteina01ddca2014-03-04 10:59:56 -0800910 mFromSpinner.initialize(mComposeMode, mAccount, mAccounts, mRefMessage);
Mindy Pereira818143e2012-01-11 13:59:49 -0800911 }
Mindy Pereira1a95a572012-01-05 12:21:29 -0800912 }
913
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800914 @Override
915 protected void onPause() {
916 super.onPause();
917
Mindy Pereiraa2148332012-07-02 13:54:14 -0700918 // When the user exits the compose view, see if this draft needs saving.
Yorke Lee3d7048e2012-09-19 14:19:25 -0700919 // Don't save unnecessary drafts if we are only changing the orientation.
920 if (!isChangingConfigurations()) {
Mindy Pereiraa2148332012-07-02 13:54:14 -0700921 saveIfNeeded();
Andy Huangdc97bf42013-08-15 16:52:45 -0700922
Andy Huange003b4c2013-08-16 10:32:05 -0700923 if (isFinishing() && !mPerformedSendOrDiscard && !isBlank()) {
Andy Huangdc97bf42013-08-15 16:52:45 -0700924 // log saving upon backing out of activity. (we avoid logging every sendOrSave()
925 // because that method can be invoked many times in a single compose session.)
926 logSendOrSave(true /* save */);
927 }
Mindy Pereiraa2148332012-07-02 13:54:14 -0700928 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800929 }
930
931 @Override
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -0700932 protected void onActivityResult(int request, int result, Intent data) {
Andy Huang5f082212014-06-11 22:19:21 -0700933 if (request == RESULT_PICK_ATTACHMENT) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700934 mAddingAttachment = false;
Andy Huang5f082212014-06-11 22:19:21 -0700935 if (result == RESULT_OK) {
936 addAttachmentAndUpdateView(data);
937 }
Mindy Pereirab199d172012-08-13 11:04:03 -0700938 } else if (request == RESULT_CREATE_ACCOUNT) {
Alice Yanga990a712013-03-13 18:37:00 -0700939 // We were waiting for the user to create an account
Mindy Pereirab199d172012-08-13 11:04:03 -0700940 if (result != RESULT_OK) {
941 finish();
942 } else {
943 // Watch for accounts to show up!
944 // restart the loader to get the updated list of accounts
945 getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, null, this);
946 showWaitFragment(null);
947 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800948 }
949 }
950
951 @Override
Scott Kennedyd9063902013-08-02 22:14:37 -0700952 protected final void onRestoreInstanceState(Bundle savedInstanceState) {
Yorke Lee7bec2b92013-04-26 08:31:42 -0700953 final boolean hasAccounts = mAccounts != null && mAccounts.length > 0;
954 if (hasAccounts) {
955 clearChangeListeners();
956 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700957 super.onRestoreInstanceState(savedInstanceState);
Andy Huang9f855d62013-05-30 17:15:03 -0700958 if (mInnerSavedState != null) {
959 if (mInnerSavedState.containsKey(EXTRA_FOCUS_SELECTION_START)) {
960 int selectionStart = mInnerSavedState.getInt(EXTRA_FOCUS_SELECTION_START);
961 int selectionEnd = mInnerSavedState.getInt(EXTRA_FOCUS_SELECTION_END);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700962 // There should be a focus and it should be an EditText since we
963 // only save these extras if these conditions are true.
964 EditText focusEditText = (EditText) getCurrentFocus();
965 final int length = focusEditText.getText().length();
966 if (selectionStart < length && selectionEnd < length) {
967 focusEditText.setSelection(selectionStart, selectionEnd);
968 }
969 }
970 }
Yorke Lee7bec2b92013-04-26 08:31:42 -0700971 if (hasAccounts) {
972 initChangeListeners();
973 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700974 }
975
976 @Override
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -0700977 protected void onSaveInstanceState(Bundle state) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800978 super.onSaveInstanceState(state);
Andy Huang9f855d62013-05-30 17:15:03 -0700979 final Bundle inner = new Bundle();
980 saveState(inner);
981 state.putBundle(KEY_INNER_SAVED_STATE, inner);
982 }
983
984 private void saveState(Bundle state) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700985 // We have no accounts so there is nothing to compose, and therefore, nothing to save.
986 if (mAccounts == null || mAccounts.length == 0) {
987 return;
988 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700989 // The framework is happy to save and restore the selection but only if it also saves and
990 // restores the contents of the edit text. That's a lot of text to put in a bundle so we do
991 // this manually.
992 View focus = getCurrentFocus();
993 if (focus != null && focus instanceof EditText) {
994 EditText focusEditText = (EditText) focus;
995 state.putInt(EXTRA_FOCUS_SELECTION_START, focusEditText.getSelectionStart());
996 state.putInt(EXTRA_FOCUS_SELECTION_END, focusEditText.getSelectionEnd());
997 }
Paul Westbrook6273e962012-04-23 10:44:15 -0700998
999 final List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
Paul Westbrook151f1ad2012-04-24 09:13:00 -07001000 final int selectedPos = mFromSpinner.getSelectedItemPosition();
Mindy Pereirad90f7ac2012-06-27 10:31:06 -07001001 final ReplyFromAccount selectedReplyFromAccount = (replyFromAccounts != null
1002 && replyFromAccounts.size() > 0 && replyFromAccounts.size() > selectedPos) ?
1003 replyFromAccounts.get(selectedPos) : null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001004 if (selectedReplyFromAccount != null) {
1005 state.putString(EXTRA_SELECTED_REPLY_FROM_ACCOUNT, selectedReplyFromAccount.serialize()
1006 .toString());
1007 state.putParcelable(Utils.EXTRA_ACCOUNT, selectedReplyFromAccount.account);
1008 } else {
1009 state.putParcelable(Utils.EXTRA_ACCOUNT, mAccount);
1010 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001011
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001012 if (mDraftId == UIProvider.INVALID_MESSAGE_ID && mRequestId !=0) {
1013 // We don't have a draft id, and we have a request id,
1014 // save the request id.
1015 state.putInt(EXTRA_REQUEST_ID, mRequestId);
1016 }
1017
1018 // We want to restore the current mode after a pause
1019 // or rotation.
1020 int mode = getMode();
1021 state.putInt(EXTRA_ACTION, mode);
1022
Jin Cao77b4c2c2014-05-20 13:55:53 -07001023 final Message message = createMessage(selectedReplyFromAccount, mRefMessage, mode,
1024 removeComposingSpans(mBodyView.getText()));
Andy Huang1f8f4dd2012-10-25 21:35:35 -07001025 if (mDraft != null) {
mindype7b76aa2012-11-14 16:19:13 -08001026 message.id = mDraft.id;
1027 message.serverId = mDraft.serverId;
1028 message.uri = mDraft.uri;
Andy Huang1f8f4dd2012-10-25 21:35:35 -07001029 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001030 state.putParcelable(EXTRA_MESSAGE, message);
1031
1032 if (mRefMessage != null) {
1033 state.putParcelable(EXTRA_IN_REFERENCE_TO_MESSAGE, mRefMessage);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001034 } else if (message.appendRefMessageContent) {
1035 // If we have no ref message but should be appending
1036 // ref message content, we have orphaned quoted text. Save it.
1037 state.putCharSequence(EXTRA_QUOTED_TEXT, mQuotedTextView.getQuotedTextIfIncluded());
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001038 }
Mindy Pereira326689d2012-05-17 10:14:14 -07001039 state.putBoolean(EXTRA_SHOW_CC, mCcBccView.isCcVisible());
1040 state.putBoolean(EXTRA_SHOW_BCC, mCcBccView.isBccVisible());
mindyp1623f9b2012-11-21 12:41:16 -08001041 state.putBoolean(EXTRA_RESPONDED_INLINE, mRespondedInline);
mindyp816b3f02012-12-11 08:25:04 -08001042 state.putBoolean(EXTRA_SAVE_ENABLED, mSave != null && mSave.isEnabled());
Mark Wei62066e42012-09-13 12:07:02 -07001043 state.putParcelableArrayList(
1044 EXTRA_ATTACHMENT_PREVIEWS, mAttachmentsView.getAttachmentPreviews());
Scott Kennedy44d44812013-08-19 14:18:31 -07001045
1046 state.putParcelable(EXTRA_VALUES, mExtraValues);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001047 }
1048
1049 private int getMode() {
1050 int mode = ComposeActivity.COMPOSE;
1051 ActionBar actionBar = getActionBar();
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001052 if (actionBar != null
1053 && actionBar.getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001054 mode = actionBar.getSelectedNavigationIndex();
1055 }
1056 return mode;
1057 }
1058
Jin Cao77b4c2c2014-05-20 13:55:53 -07001059 /**
1060 * This function might be called from a background thread, so be sure to move everything that
1061 * can potentially modify the UI to the main thread (e.g. removeComposingSpans for body).
1062 */
Anthony Lee2a3cc132014-04-22 14:15:25 -07001063 private Message createMessage(ReplyFromAccount selectedReplyFromAccount, Message refMessage,
Jin Cao77b4c2c2014-05-20 13:55:53 -07001064 int mode, Spanned body) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001065 Message message = new Message();
1066 message.id = UIProvider.INVALID_MESSAGE_ID;
Andy Huangd47877e2012-08-09 19:31:24 -07001067 message.serverId = null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001068 message.uri = null;
1069 message.conversationUri = null;
1070 message.subject = mSubject.getText().toString();
1071 message.snippet = null;
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001072 message.setTo(formatSenders(mTo.getText().toString()));
1073 message.setCc(formatSenders(mCc.getText().toString()));
1074 message.setBcc(formatSenders(mBcc.getText().toString()));
1075 message.setReplyTo(null);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001076 message.dateReceivedMs = 0;
Jin Cao77b4c2c2014-05-20 13:55:53 -07001077 message.bodyHtml = spannedBodyToHtml(body, true);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001078 message.bodyText = mBodyView.getText().toString();
1079 message.embedsExternalResources = false;
Alice Yanga990a712013-03-13 18:37:00 -07001080 message.refMessageUri = mRefMessage != null ? mRefMessage.uri : null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001081 message.appendRefMessageContent = mQuotedTextView.getQuotedTextIfIncluded() != null;
1082 ArrayList<Attachment> attachments = mAttachmentsView.getAttachments();
1083 message.hasAttachments = attachments != null && attachments.size() > 0;
1084 message.attachmentListUri = null;
1085 message.messageFlags = 0;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001086 message.alwaysShowImages = false;
1087 message.attachmentsJson = Attachment.toJSONArray(attachments);
1088 CharSequence quotedText = mQuotedTextView.getQuotedText();
Anthony Lee2a3cc132014-04-22 14:15:25 -07001089 message.quotedTextOffset = -1; // Just a default value.
1090 if (refMessage != null && !TextUtils.isEmpty(quotedText)) {
1091 if (!TextUtils.isEmpty(refMessage.bodyHtml)) {
1092 // We want the index to point to just the quoted text and not the
1093 // "On December 25, 2014..." part of it.
1094 message.quotedTextOffset =
1095 QuotedTextView.getQuotedTextOffset(quotedText.toString());
1096 } else if (!TextUtils.isEmpty(refMessage.bodyText)) {
1097 // We want to point to the entire quoted text.
1098 message.quotedTextOffset = QuotedTextView.findQuotedTextIndex(quotedText);
1099 }
1100 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001101 message.accountUri = null;
Tony Mantlerbb036ff72013-10-18 14:03:43 -07001102 final String email = selectedReplyFromAccount != null ? selectedReplyFromAccount.address
1103 : mAccount != null ? mAccount.getEmailAddress() : null;
Tony Mantlerf441d142013-10-22 11:46:00 -07001104 final String senderName = selectedReplyFromAccount != null ? selectedReplyFromAccount.name
1105 : mAccount != null ? mAccount.getSenderName() : null;
Tony Mantler821e5782014-01-06 15:33:43 -08001106 final Address address = new Address(email, senderName);
Tony Mantlerf441d142013-10-22 11:46:00 -07001107 message.setFrom(address.toHeader());
Andy Huang1f8f4dd2012-10-25 21:35:35 -07001108 message.draftType = getDraftType(mode);
mindype7b76aa2012-11-14 16:19:13 -08001109 return message;
Andy Huang1f8f4dd2012-10-25 21:35:35 -07001110 }
1111
Scott Kennedyff8553f2013-04-05 20:57:44 -07001112 private static String formatSenders(final String string) {
Mindy Pereira3c911582012-08-09 16:59:09 -07001113 if (!TextUtils.isEmpty(string) && string.charAt(string.length() - 1) == ',') {
1114 return string.substring(0, string.length() - 1);
1115 }
1116 return string;
1117 }
1118
Mindy Pereira818143e2012-01-11 13:59:49 -08001119 @VisibleForTesting
Andy Huang91ede362014-01-21 19:16:00 -08001120 protected void setAccount(Account account) {
Mindy Pereirabb5217e2012-04-17 11:08:29 -07001121 if (account == null) {
1122 return;
1123 }
Mindy Pereira23e9fde2012-03-20 15:08:24 -07001124 if (!account.equals(mAccount)) {
1125 mAccount = account;
Paul Westbrookb1f573c2012-04-06 11:38:28 -07001126 mCachedSettings = mAccount.settings;
1127 appendSignature();
Mindy Pereira23e9fde2012-03-20 15:08:24 -07001128 }
Mindy Pereirafa20c1a2012-07-23 13:00:02 -07001129 if (mAccount != null) {
Tony Mantler79b11562013-10-09 15:31:50 -07001130 MailActivity.setNfcMessage(mAccount.getEmailAddress());
Mindy Pereirafa20c1a2012-07-23 13:00:02 -07001131 }
Mindy Pereira818143e2012-01-11 13:59:49 -08001132 }
1133
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001134 private void initFromSpinner(Bundle bundle, int action) {
1135 if (action == EDIT_DRAFT && mDraft.draftType == UIProvider.DraftType.COMPOSE) {
Mindy Pereira62de1b12012-04-06 12:17:56 -07001136 action = COMPOSE;
1137 }
Andrew Sappersteina01ddca2014-03-04 10:59:56 -08001138 mFromSpinner.initialize(action, mAccount, mAccounts, mRefMessage);
Paul Westbrookc97ec3e2013-07-12 18:17:19 -07001139
Mindy Pereira9a42bb42012-04-18 15:21:33 -07001140 if (bundle != null) {
1141 if (bundle.containsKey(EXTRA_SELECTED_REPLY_FROM_ACCOUNT)) {
1142 mReplyFromAccount = ReplyFromAccount.deserialize(mAccount,
1143 bundle.getString(EXTRA_SELECTED_REPLY_FROM_ACCOUNT));
1144 } else if (bundle.containsKey(EXTRA_FROM_ACCOUNT_STRING)) {
Paul Westbrookc97ec3e2013-07-12 18:17:19 -07001145 final String accountString = bundle.getString(EXTRA_FROM_ACCOUNT_STRING);
Mindy Pereira9a42bb42012-04-18 15:21:33 -07001146 mReplyFromAccount = mFromSpinner.getMatchingReplyFromAccount(accountString);
1147 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001148 }
1149 if (mReplyFromAccount == null) {
1150 if (mDraft != null) {
1151 mReplyFromAccount = getReplyFromAccountFromDraft(mAccount, mDraft);
1152 } else if (mRefMessage != null) {
1153 mReplyFromAccount = getReplyFromAccountForReply(mAccount, mRefMessage);
1154 }
Mindy Pereira62de1b12012-04-06 12:17:56 -07001155 }
1156 if (mReplyFromAccount == null) {
Andy Huang238aa472012-10-30 17:45:17 -07001157 mReplyFromAccount = getDefaultReplyFromAccount(mAccount);
Mindy Pereira62de1b12012-04-06 12:17:56 -07001158 }
Mindy Pereira9a42bb42012-04-18 15:21:33 -07001159
Mindy Pereira62de1b12012-04-06 12:17:56 -07001160 mFromSpinner.setCurrentAccount(mReplyFromAccount);
Mindy Pereira9a42bb42012-04-18 15:21:33 -07001161
Mindy Pereira62de1b12012-04-06 12:17:56 -07001162 if (mFromSpinner.getCount() > 1) {
Mindy Pereiraa83e7082012-03-30 08:53:11 -07001163 // If there is only 1 account, just show that account.
1164 // Otherwise, give the user the ability to choose which account to
Mindy Pereira62de1b12012-04-06 12:17:56 -07001165 // send mail from / save drafts to.
1166 mFromStatic.setVisibility(View.GONE);
Andy Huangca4676f2014-01-16 13:22:20 -08001167 mFromStaticText.setText(mReplyFromAccount.address);
Mindy Pereira62de1b12012-04-06 12:17:56 -07001168 mFromSpinnerWrapper.setVisibility(View.VISIBLE);
Mindy Pereiraa83e7082012-03-30 08:53:11 -07001169 } else {
1170 mFromStatic.setVisibility(View.VISIBLE);
Andy Huangca4676f2014-01-16 13:22:20 -08001171 mFromStaticText.setText(mReplyFromAccount.address);
Mindy Pereiraa83e7082012-03-30 08:53:11 -07001172 mFromSpinnerWrapper.setVisibility(View.GONE);
Mindy Pereiraa83e7082012-03-30 08:53:11 -07001173 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001174 }
1175
Mindy Pereira62de1b12012-04-06 12:17:56 -07001176 private ReplyFromAccount getReplyFromAccountForReply(Account account, Message refMessage) {
1177 if (refMessage.accountUri != null) {
1178 // This must be from combined inbox.
1179 List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
1180 for (ReplyFromAccount from : replyFromAccounts) {
1181 if (from.account.uri.equals(refMessage.accountUri)) {
1182 return from;
1183 }
1184 }
1185 return null;
1186 } else {
1187 return getReplyFromAccount(account, refMessage);
1188 }
1189 }
1190
1191 /**
Tony Mantler9016a5e2013-07-19 11:54:17 -07001192 * Given an account and the message we're replying to,
Mindy Pereira62de1b12012-04-06 12:17:56 -07001193 * return who the message should be sent from.
1194 * @param account Account in which the message arrived.
Tony Mantler9016a5e2013-07-19 11:54:17 -07001195 * @param refMessage Message to analyze for account selection
Mindy Pereira62de1b12012-04-06 12:17:56 -07001196 * @return the address from which to reply.
1197 */
1198 public ReplyFromAccount getReplyFromAccount(Account account, Message refMessage) {
1199 // First see if we are supposed to use the default address or
1200 // the address it was sentTo.
Mindy Pereira326689d2012-05-17 10:14:14 -07001201 if (mCachedSettings.forceReplyFromDefault) {
Mindy Pereira62de1b12012-04-06 12:17:56 -07001202 return getDefaultReplyFromAccount(account);
1203 } else {
Mindy Pereira89bae572012-06-18 11:34:36 -07001204 // If we aren't explicitly told which account to look for, look at
Mindy Pereira62de1b12012-04-06 12:17:56 -07001205 // all the message recipients and find one that matches
1206 // a custom from or account.
1207 List<String> allRecipients = new ArrayList<String>();
Tony Mantler9016a5e2013-07-19 11:54:17 -07001208 allRecipients.addAll(Arrays.asList(refMessage.getToAddressesUnescaped()));
1209 allRecipients.addAll(Arrays.asList(refMessage.getCcAddressesUnescaped()));
Mindy Pereira62de1b12012-04-06 12:17:56 -07001210 return getMatchingRecipient(account, allRecipients);
1211 }
1212 }
1213
1214 /**
1215 * Compare all the recipients of an email to the current account and all
1216 * custom addresses associated with that account. Return the match if there
1217 * is one, or the default account if there isn't.
1218 */
1219 protected ReplyFromAccount getMatchingRecipient(Account account, List<String> sentTo) {
1220 // Tokenize the list and place in a hashmap.
1221 ReplyFromAccount matchingReplyFrom = null;
1222 Rfc822Token[] tokens;
1223 HashSet<String> recipientsMap = new HashSet<String>();
1224 for (String address : sentTo) {
1225 tokens = Rfc822Tokenizer.tokenize(address);
Tony Mantler581edd42014-02-18 15:41:22 -08001226 for (final Rfc822Token token : tokens) {
1227 recipientsMap.add(token.getAddress());
Mindy Pereira62de1b12012-04-06 12:17:56 -07001228 }
1229 }
1230
1231 int matchingAddressCount = 0;
1232 List<ReplyFromAccount> customFroms;
Andy Huang16174812012-08-16 16:40:35 -07001233 customFroms = account.getReplyFroms();
1234 if (customFroms != null) {
1235 for (ReplyFromAccount entry : customFroms) {
1236 if (recipientsMap.contains(entry.address)) {
1237 matchingReplyFrom = entry;
1238 matchingAddressCount++;
Mindy Pereira62de1b12012-04-06 12:17:56 -07001239 }
1240 }
Mindy Pereira62de1b12012-04-06 12:17:56 -07001241 }
1242 if (matchingAddressCount > 1) {
1243 matchingReplyFrom = getDefaultReplyFromAccount(account);
1244 }
1245 return matchingReplyFrom;
1246 }
1247
Scott Kennedyff8553f2013-04-05 20:57:44 -07001248 private static ReplyFromAccount getDefaultReplyFromAccount(final Account account) {
1249 for (final ReplyFromAccount from : account.getReplyFroms()) {
Mindy Pereira62de1b12012-04-06 12:17:56 -07001250 if (from.isDefault) {
1251 return from;
1252 }
1253 }
Tony Mantlerf441d142013-10-22 11:46:00 -07001254 return new ReplyFromAccount(account, account.uri, account.getEmailAddress(),
1255 account.getSenderName(), account.getEmailAddress(), true, false);
Mindy Pereira62de1b12012-04-06 12:17:56 -07001256 }
1257
Tony Mantlerf441d142013-10-22 11:46:00 -07001258 private ReplyFromAccount getReplyFromAccountFromDraft(final Account account,
1259 final Message msg) {
1260 final Address[] draftFroms = Address.parse(msg.getFrom());
1261 final String sender = draftFroms.length > 0 ? draftFroms[0].getAddress() : "";
Mindy Pereira62de1b12012-04-06 12:17:56 -07001262 ReplyFromAccount replyFromAccount = null;
1263 List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
Tony Mantler79b11562013-10-09 15:31:50 -07001264 if (TextUtils.equals(account.getEmailAddress(), sender)) {
Tony Mantlerf441d142013-10-22 11:46:00 -07001265 replyFromAccount = getDefaultReplyFromAccount(account);
Mindy Pereira62de1b12012-04-06 12:17:56 -07001266 } else {
1267 for (ReplyFromAccount fromAccount : replyFromAccounts) {
Tony Mantler79b11562013-10-09 15:31:50 -07001268 if (TextUtils.equals(fromAccount.address, sender)) {
Mindy Pereira62de1b12012-04-06 12:17:56 -07001269 replyFromAccount = fromAccount;
1270 break;
1271 }
1272 }
1273 }
1274 return replyFromAccount;
1275 }
1276
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001277 private void findViews() {
Mindy Pereirab199d172012-08-13 11:04:03 -07001278 findViewById(R.id.compose).setVisibility(View.VISIBLE);
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001279 mCcBccButton = (Button) findViewById(R.id.add_cc_bcc);
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001280 if (mCcBccButton != null) {
1281 mCcBccButton.setOnClickListener(this);
1282 }
1283 mCcBccView = (CcBccView) findViewById(R.id.cc_bcc_wrapper);
Mindy Pereira7b56a612011-12-14 12:32:28 -08001284 mAttachmentsView = (AttachmentsView)findViewById(R.id.attachments);
Tony Mantler581edd42014-02-18 15:41:22 -08001285 final View addAttachmentsButton = findViewById(R.id.add_attachment);
1286 if (addAttachmentsButton != null) {
1287 addAttachmentsButton.setOnClickListener(this);
mindypcd0b0b92012-08-23 14:33:17 -07001288 }
Mindy Pereira818143e2012-01-11 13:59:49 -08001289 mTo = (RecipientEditTextView) findViewById(R.id.to);
Andrew Sapperstein09da9422014-05-30 09:48:08 -07001290 initializeRecipientEditTextView(mTo);
Mindy Pereira818143e2012-01-11 13:59:49 -08001291 mCc = (RecipientEditTextView) findViewById(R.id.cc);
Andrew Sapperstein09da9422014-05-30 09:48:08 -07001292 initializeRecipientEditTextView(mCc);
Mindy Pereira818143e2012-01-11 13:59:49 -08001293 mBcc = (RecipientEditTextView) findViewById(R.id.bcc);
Andrew Sapperstein09da9422014-05-30 09:48:08 -07001294 initializeRecipientEditTextView(mBcc);
Mindy Pereira82cc5662012-01-09 17:29:30 -08001295 // TODO: add special chips text change watchers before adding
1296 // this as a text changed watcher to the to, cc, bcc fields.
Mindy Pereira6349a042012-01-04 11:25:01 -08001297 mSubject = (TextView) findViewById(R.id.subject);
mindyp62d3ec72012-08-24 13:04:09 -07001298 mSubject.setOnEditorActionListener(this);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001299 mQuotedTextView = (QuotedTextView) findViewById(R.id.quoted_text_view);
1300 mQuotedTextView.setRespondInlineListener(this);
Mindy Pereira433b1982012-04-03 11:53:07 -07001301 mBodyView = (EditText) findViewById(R.id.body);
Mindy Pereira1a95a572012-01-05 12:21:29 -08001302 mFromStatic = findViewById(R.id.static_from_content);
Mindy Pereira2eb17322012-03-07 10:07:34 -08001303 mFromStaticText = (TextView) findViewById(R.id.from_account_name);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001304 mFromSpinnerWrapper = findViewById(R.id.spinner_from_content);
Mindy Pereira5a85e2b2012-01-11 09:53:32 -08001305 mFromSpinner = (FromAddressSpinner) findViewById(R.id.from_picker);
Mindy Pereira6349a042012-01-04 11:25:01 -08001306 }
1307
Andrew Sapperstein09da9422014-05-30 09:48:08 -07001308 private void initializeRecipientEditTextView(RecipientEditTextView view) {
1309 view.setTokenizer(new Rfc822Tokenizer());
1310 view.setThreshold(COMPLETION_THRESHOLD);
1311 }
1312
mindyp62d3ec72012-08-24 13:04:09 -07001313 @Override
1314 public boolean onEditorAction(TextView view, int action, KeyEvent keyEvent) {
1315 if (action == EditorInfo.IME_ACTION_DONE) {
1316 focusBody();
1317 return true;
1318 }
1319 return false;
1320 }
1321
Andy Huang91ede362014-01-21 19:16:00 -08001322 /**
1323 * Convert the body text (in {@link Spanned} form) to ready-to-send HTML format as a plain
1324 * String.
1325 *
1326 * @param body the body text including fancy style spans
Jin Cao77b4c2c2014-05-20 13:55:53 -07001327 * @param removedComposing whether the function already removed composingSpans. Necessary
1328 * because we cannot call removeComposingSpans from a background thread.
Andy Huang91ede362014-01-21 19:16:00 -08001329 * @return HTML formatted body that's suitable for sending or saving
1330 */
Jin Cao77b4c2c2014-05-20 13:55:53 -07001331 private String spannedBodyToHtml(Spanned body, boolean removedComposing) {
1332 if (!removedComposing) {
1333 body = removeComposingSpans(body);
1334 }
1335 final HtmlifyBeginResult r = onHtmlifyBegin(body);
Andy Huang91ede362014-01-21 19:16:00 -08001336 return onHtmlifyEnd(Html.toHtml(r.result), r.extras);
1337 }
1338
1339 /**
1340 * A hook for subclasses to convert custom spans in the body text prior to system HTML
1341 * conversion. That HTML conversion is lossy, so anything above and beyond its capability
1342 * has to be handled here.
1343 *
1344 * @param body
1345 * @return a copy of the body text with custom spans replaced with HTML
1346 */
1347 protected HtmlifyBeginResult onHtmlifyBegin(Spanned body) {
1348 return new HtmlifyBeginResult(body, null /* extras */);
1349 }
1350
1351 protected String onHtmlifyEnd(String html, Object extras) {
1352 return html;
1353 }
1354
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001355 protected TextView getBody() {
1356 return mBodyView;
1357 }
1358
1359 @VisibleForTesting
Andy Huang0a2a3462013-12-20 15:56:13 -08001360 public String getBodyHtml() {
Jin Cao77b4c2c2014-05-20 13:55:53 -07001361 return spannedBodyToHtml(mBodyView.getText(), false);
Andy Huang0a2a3462013-12-20 15:56:13 -08001362 }
1363
1364 @VisibleForTesting
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001365 public Account getFromAccount() {
1366 return mReplyFromAccount != null && mReplyFromAccount.account != null ?
1367 mReplyFromAccount.account : mAccount;
1368 }
1369
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07001370 private void clearChangeListeners() {
1371 mSubject.removeTextChangedListener(this);
1372 mBodyView.removeTextChangedListener(this);
1373 mTo.removeTextChangedListener(mToListener);
1374 mCc.removeTextChangedListener(mCcListener);
1375 mBcc.removeTextChangedListener(mBccListener);
1376 mFromSpinner.setOnAccountChangedListener(null);
1377 mAttachmentsView.setAttachmentChangesListener(null);
1378 }
1379
Mindy Pereira75f66632012-01-11 11:42:02 -08001380 // Now that the message has been initialized from any existing draft or
1381 // ref message data, set up listeners for any changes that occur to the
1382 // message.
1383 private void initChangeListeners() {
mindyp1d7e9142012-11-21 13:54:30 -08001384 // Make sure we only add text changed listeners once!
1385 clearChangeListeners();
Mindy Pereira75f66632012-01-11 11:42:02 -08001386 mSubject.addTextChangedListener(this);
1387 mBodyView.addTextChangedListener(this);
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07001388 if (mToListener == null) {
1389 mToListener = new RecipientTextWatcher(mTo, this);
1390 }
1391 mTo.addTextChangedListener(mToListener);
1392 if (mCcListener == null) {
1393 mCcListener = new RecipientTextWatcher(mCc, this);
1394 }
1395 mCc.addTextChangedListener(mCcListener);
1396 if (mBccListener == null) {
1397 mBccListener = new RecipientTextWatcher(mBcc, this);
1398 }
1399 mBcc.addTextChangedListener(mBccListener);
Mindy Pereira75f66632012-01-11 11:42:02 -08001400 mFromSpinner.setOnAccountChangedListener(this);
Mindy Pereira818143e2012-01-11 13:59:49 -08001401 mAttachmentsView.setAttachmentChangesListener(this);
Mindy Pereira75f66632012-01-11 11:42:02 -08001402 }
1403
Alice Yanga990a712013-03-13 18:37:00 -07001404 private void initActionBar() {
1405 LogUtils.d(LOG_TAG, "initializing action bar in ComposeActivity");
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001406 ActionBar actionBar = getActionBar();
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001407 if (actionBar == null) {
1408 return;
1409 }
Alice Yanga990a712013-03-13 18:37:00 -07001410 if (mComposeMode == ComposeActivity.COMPOSE) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001411 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1412 actionBar.setTitle(R.string.compose);
Mindy Pereira326c6602012-01-04 15:32:42 -08001413 } else {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001414 actionBar.setTitle(null);
Mindy Pereira326c6602012-01-04 15:32:42 -08001415 if (mComposeModeAdapter == null) {
1416 mComposeModeAdapter = new ComposeModeAdapter(this);
1417 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001418 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
1419 actionBar.setListNavigationCallbacks(mComposeModeAdapter, this);
Alice Yanga990a712013-03-13 18:37:00 -07001420 switch (mComposeMode) {
Mindy Pereira326c6602012-01-04 15:32:42 -08001421 case ComposeActivity.REPLY:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001422 actionBar.setSelectedNavigationItem(0);
Mindy Pereira326c6602012-01-04 15:32:42 -08001423 break;
1424 case ComposeActivity.REPLY_ALL:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001425 actionBar.setSelectedNavigationItem(1);
Mindy Pereira326c6602012-01-04 15:32:42 -08001426 break;
1427 case ComposeActivity.FORWARD:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001428 actionBar.setSelectedNavigationItem(2);
Mindy Pereira326c6602012-01-04 15:32:42 -08001429 break;
1430 }
1431 }
Mindy Pereirafbe40192012-03-20 10:40:45 -07001432 actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME,
1433 ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME);
1434 actionBar.setHomeButtonEnabled(true);
Mindy Pereira326c6602012-01-04 15:32:42 -08001435 }
1436
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08001437 private void initFromRefMessage(int action) {
1438 setFieldsFromRefMessage(action);
Alice Yang1ebc2db2013-03-14 21:21:44 -07001439
1440 // Check if To: address and email body needs to be prefilled based on extras.
1441 // This is used for reporting rendering feedback.
1442 if (MessageHeaderView.ENABLE_REPORT_RENDERING_PROBLEM) {
1443 Intent intent = getIntent();
1444 if (intent.getExtras() != null) {
1445 String toAddresses = intent.getStringExtra(EXTRA_TO);
1446 if (toAddresses != null) {
1447 addToAddresses(Arrays.asList(TextUtils.split(toAddresses, ",")));
1448 }
1449 String body = intent.getStringExtra(EXTRA_BODY);
1450 if (body != null) {
1451 setBody(body, false /* withSignature */);
1452 }
1453 }
1454 }
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07001455 }
1456
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08001457 private void setFieldsFromRefMessage(int action) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001458 setSubject(mRefMessage, action);
1459 // Setup recipients
1460 if (action == FORWARD) {
1461 mForward = true;
Mindy Pereira6349a042012-01-04 11:25:01 -08001462 }
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08001463 initRecipientsFromRefMessage(mRefMessage, action);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001464 initQuotedTextFromRefMessage(mRefMessage, action);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001465 if (action == ComposeActivity.FORWARD || mAttachmentsChanged) {
1466 initAttachments(mRefMessage);
1467 }
Mindy Pereirac17d0732011-12-29 10:46:19 -08001468 }
1469
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001470 private void initFromDraftMessage(Message message) {
Andy Huang1f8f4dd2012-10-25 21:35:35 -07001471 LogUtils.d(LOG_TAG, "Intializing draft from previous draft message: %s", message);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001472
1473 mDraft = message;
1474 mDraftId = message.id;
1475 mSubject.setText(message.subject);
1476 mForward = message.draftType == UIProvider.DraftType.FORWARD;
Tony Mantler9016a5e2013-07-19 11:54:17 -07001477 final List<String> toAddresses = Arrays.asList(message.getToAddressesUnescaped());
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001478 addToAddresses(toAddresses);
Tony Mantler9016a5e2013-07-19 11:54:17 -07001479 addCcAddresses(Arrays.asList(message.getCcAddressesUnescaped()), toAddresses);
1480 addBccAddresses(Arrays.asList(message.getBccAddressesUnescaped()));
Mindy Pereira2421dc82012-03-27 13:32:31 -07001481 if (message.hasAttachments) {
1482 List<Attachment> attachments = message.getAttachments();
1483 for (Attachment a : attachments) {
Andy Huang5c5fd572012-04-08 18:19:29 -07001484 addAttachmentAndUpdateView(a);
Mindy Pereira2421dc82012-03-27 13:32:31 -07001485 }
1486 }
Anthony Lee2a3cc132014-04-22 14:15:25 -07001487 int quotedTextIndex = message.appendRefMessageContent ? message.quotedTextOffset : -1;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001488 // Set the body
Mindy Pereira002ff522012-05-30 10:31:26 -07001489 CharSequence quotedText = null;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001490 if (!TextUtils.isEmpty(message.bodyHtml)) {
Mindy Pereira002ff522012-05-30 10:31:26 -07001491 if (quotedTextIndex > -1) {
Anthony Lee2a3cc132014-04-22 14:15:25 -07001492 // Find the offset in the html text of the actual quoted text and strip it out.
1493 // Note that the actual quotedTextOffset in the message has not changed as
1494 // this different offset is used only for display purposes. They point to different
1495 // parts of the original message. Please see the comments in QuoteTextView
1496 // to see the differences.
Mindy Pereira752222d2012-07-19 09:58:53 -07001497 quotedTextIndex = QuotedTextView.findQuotedTextIndex(message.bodyHtml);
1498 if (quotedTextIndex > -1) {
Jin Cao77b4c2c2014-05-20 13:55:53 -07001499 new HtmlToSpannedTask().execute(message.bodyHtml.substring(0, quotedTextIndex));
Mindy Pereira752222d2012-07-19 09:58:53 -07001500 quotedText = message.bodyHtml.subSequence(quotedTextIndex,
1501 message.bodyHtml.length());
1502 }
Mindy Pereira1a6e9382012-08-14 15:51:22 -07001503 } else {
Jin Cao77b4c2c2014-05-20 13:55:53 -07001504 new HtmlToSpannedTask().execute(message.bodyHtml);
Mindy Pereira002ff522012-05-30 10:31:26 -07001505 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001506 } else {
Mindy Pereira752222d2012-07-19 09:58:53 -07001507 final String body = message.bodyText;
Anthony Lee2a3cc132014-04-22 14:15:25 -07001508 final CharSequence bodyText;
1509 if (TextUtils.isEmpty(body)) {
1510 bodyText = "";
1511 quotedText = null;
1512 } else {
1513 if (quotedTextIndex > body.length()) {
1514 // Sanity check to guarantee that we will not over index the String.
1515 // If this happens there is a bigger problem. This should never happen hence
1516 // the wtf logging.
1517 quotedTextIndex = -1;
1518 LogUtils.wtf(LOG_TAG, "quotedTextIndex (%d) > body.length() (%d)",
1519 quotedTextIndex, body.length());
1520 }
1521 bodyText = quotedTextIndex > -1 ? body.substring(0, quotedTextIndex) : body;
1522 if (quotedTextIndex > -1) {
1523 quotedText = body.substring(quotedTextIndex);
1524 }
Mindy Pereira002ff522012-05-30 10:31:26 -07001525 }
1526 mBodyView.setText(bodyText);
1527 }
1528 if (quotedTextIndex > -1 && quotedText != null) {
Mindy Pereira39713232012-05-30 11:48:41 -07001529 mQuotedTextView.setQuotedTextFromDraft(quotedText, mForward);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001530 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001531 }
1532
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001533 /**
1534 * Fill all the widgets with the content found in the Intent Extra, if any.
1535 * Also apply the same style to all widgets. Note: if initFromExtras is
1536 * called as a result of switching between reply, reply all, and forward per
1537 * the latest revision of Gmail, and the user has already made changes to
1538 * attachments on a previous incarnation of the message (as a reply, reply
1539 * all, or forward), the original attachments from the message will not be
1540 * re-instantiated. The user's changes will be respected. This follows the
1541 * web gmail interaction.
Andrew Sapperstein746d8612013-08-26 15:56:32 -07001542 * @return {@code true} if the activity should not call {@link #finishSetup}.
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001543 */
Andrew Sapperstein746d8612013-08-26 15:56:32 -07001544 public boolean initFromExtras(Intent intent) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001545 // If we were invoked with a SENDTO intent, the value
1546 // should take precedence
1547 final Uri dataUri = intent.getData();
1548 if (dataUri != null) {
1549 if (MAIL_TO.equals(dataUri.getScheme())) {
1550 initFromMailTo(dataUri.toString());
1551 } else {
Mindy Pereira0b4f28e2012-03-28 14:12:21 -07001552 if (!mAccount.composeIntentUri.equals(dataUri)) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001553 String toText = dataUri.getSchemeSpecificPart();
1554 if (toText != null) {
1555 mTo.setText("");
Mindy Pereiradbe89962012-04-13 09:42:38 -07001556 addToAddresses(Arrays.asList(TextUtils.split(toText, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001557 }
1558 }
1559 }
1560 }
1561
1562 String[] extraStrings = intent.getStringArrayExtra(Intent.EXTRA_EMAIL);
1563 if (extraStrings != null) {
1564 addToAddresses(Arrays.asList(extraStrings));
1565 }
1566 extraStrings = intent.getStringArrayExtra(Intent.EXTRA_CC);
1567 if (extraStrings != null) {
1568 addCcAddresses(Arrays.asList(extraStrings), null);
1569 }
1570 extraStrings = intent.getStringArrayExtra(Intent.EXTRA_BCC);
1571 if (extraStrings != null) {
1572 addBccAddresses(Arrays.asList(extraStrings));
1573 }
1574
1575 String extraString = intent.getStringExtra(Intent.EXTRA_SUBJECT);
1576 if (extraString != null) {
1577 mSubject.setText(extraString);
1578 }
1579
1580 for (String extra : ALL_EXTRAS) {
1581 if (intent.hasExtra(extra)) {
1582 String value = intent.getStringExtra(extra);
1583 if (EXTRA_TO.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001584 addToAddresses(Arrays.asList(TextUtils.split(value, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001585 } else if (EXTRA_CC.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001586 addCcAddresses(Arrays.asList(TextUtils.split(value, ",")), null);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001587 } else if (EXTRA_BCC.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001588 addBccAddresses(Arrays.asList(TextUtils.split(value, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001589 } else if (EXTRA_SUBJECT.equals(extra)) {
1590 mSubject.setText(value);
1591 } else if (EXTRA_BODY.equals(extra)) {
1592 setBody(value, true /* with signature */);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001593 } else if (EXTRA_QUOTED_TEXT.equals(extra)) {
1594 initQuotedText(value, true /* shouldQuoteText */);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001595 }
1596 }
1597 }
1598
1599 Bundle extras = intent.getExtras();
1600 if (extras != null) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001601 CharSequence text = extras.getCharSequence(Intent.EXTRA_TEXT);
1602 if (text != null) {
1603 setBody(text, true /* with signature */);
1604 }
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001605
1606 // TODO - support EXTRA_HTML_TEXT
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001607 }
Andrew Sapperstein746d8612013-08-26 15:56:32 -07001608
1609 mExtraValues = intent.getParcelableExtra(EXTRA_VALUES);
1610 if (mExtraValues != null) {
1611 LogUtils.d(LOG_TAG, "Launched with extra values: %s", mExtraValues.toString());
1612 initExtraValues(mExtraValues);
1613 return true;
1614 }
1615
1616 return false;
1617 }
1618
1619 protected void initExtraValues(ContentValues extraValues) {
1620 // DO NOTHING - Gmail will override
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001621 }
1622
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001623
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001624 @VisibleForTesting
1625 protected String decodeEmailInUri(String s) throws UnsupportedEncodingException {
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001626 // TODO: handle the case where there are spaces in the display name as
1627 // well as the email such as "Guy with spaces <guy+with+spaces@gmail.com>"
1628 // as they could be encoded ambiguously.
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001629 // Since URLDecode.decode changes + into ' ', and + is a valid
1630 // email character, we need to find/ replace these ourselves before
1631 // decoding.
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001632 try {
Yorke Lee7dd05b12013-04-25 10:04:43 -07001633 return URLDecoder.decode(replacePlus(s), UTF8_ENCODING_NAME);
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001634 } catch (IllegalArgumentException e) {
1635 if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
1636 LogUtils.e(LOG_TAG, "%s while decoding '%s'", e.getMessage(), s);
1637 } else {
1638 LogUtils.e(LOG_TAG, e, "Exception while decoding mailto address");
1639 }
1640 return null;
1641 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001642 }
1643
1644 /**
Yorke Lee7dd05b12013-04-25 10:04:43 -07001645 * Replaces all occurrences of '+' with "%2B", to prevent URLDecode.decode from
1646 * changing '+' into ' '
1647 *
1648 * @param toReplace Input string
1649 * @return The string with all "+" characters replaced with "%2B"
1650 */
Scott Kennedy3b965d72013-06-25 14:36:55 -07001651 private static String replacePlus(String toReplace) {
Yorke Lee7dd05b12013-04-25 10:04:43 -07001652 return toReplace.replace("+", "%2B");
1653 }
1654
1655 /**
Jin Caod67d7e32014-03-26 16:49:48 -07001656 * Replaces all occurrences of '%' with "%25", to prevent URLDecode.decode from
1657 * crashing on decoded '%' symbols
1658 *
1659 * @param toReplace Input string
1660 * @return The string with all "%" characters replaced with "%25"
1661 */
1662 private static String replacePercent(String toReplace) {
1663 return toReplace.replace("%", "%25");
1664 }
1665
1666 /**
1667 * Helper function to encapsulate encoding/decoding string from Uri.getQueryParameters
1668 * @param content Input string
1669 * @return The string that's properly escaped to be shown in mail subject/content
1670 */
1671 private static String decodeContentFromQueryParam(String content) {
1672 try {
1673 return URLDecoder.decode(replacePlus(replacePercent(content)), UTF8_ENCODING_NAME);
1674 } catch (UnsupportedEncodingException e) {
1675 LogUtils.e(LOG_TAG, "%s while decoding '%s'", e.getMessage(), content);
1676 return ""; // Default to empty string so setText/setBody has same behavior as before.
1677 }
1678 }
1679
1680 /**
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001681 * Initialize the compose view from a String representing a mailTo uri.
1682 * @param mailToString The uri as a string.
1683 */
1684 public void initFromMailTo(String mailToString) {
1685 // We need to disguise this string as a URI in order to parse it
1686 // TODO: Remove this hack when http://b/issue?id=1445295 gets fixed
1687 Uri uri = Uri.parse("foo://" + mailToString);
1688 int index = mailToString.indexOf("?");
1689 int length = "mailto".length() + 1;
1690 String to;
1691 try {
1692 // Extract the recipient after mailto:
1693 if (index == -1) {
1694 to = decodeEmailInUri(mailToString.substring(length));
1695 } else {
1696 to = decodeEmailInUri(mailToString.substring(length, index));
1697 }
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001698 if (!TextUtils.isEmpty(to)) {
1699 addToAddresses(Arrays.asList(TextUtils.split(to, ",")));
1700 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001701 } catch (UnsupportedEncodingException e) {
1702 if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
1703 LogUtils.e(LOG_TAG, "%s while decoding '%s'", e.getMessage(), mailToString);
1704 } else {
1705 LogUtils.e(LOG_TAG, e, "Exception while decoding mailto address");
1706 }
1707 }
1708
1709 List<String> cc = uri.getQueryParameters("cc");
1710 addCcAddresses(Arrays.asList(cc.toArray(new String[cc.size()])), null);
1711
1712 List<String> otherTo = uri.getQueryParameters("to");
1713 addToAddresses(Arrays.asList(otherTo.toArray(new String[otherTo.size()])));
1714
1715 List<String> bcc = uri.getQueryParameters("bcc");
1716 addBccAddresses(Arrays.asList(bcc.toArray(new String[bcc.size()])));
1717
Jin Caod67d7e32014-03-26 16:49:48 -07001718 // NOTE: Uri.getQueryParameters already decodes % encoded characters
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001719 List<String> subject = uri.getQueryParameters("subject");
1720 if (subject.size() > 0) {
Jin Caod67d7e32014-03-26 16:49:48 -07001721 mSubject.setText(decodeContentFromQueryParam(subject.get(0)));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001722 }
1723
1724 List<String> body = uri.getQueryParameters("body");
1725 if (body.size() > 0) {
Jin Caod67d7e32014-03-26 16:49:48 -07001726 setBody(decodeContentFromQueryParam(body.get(0)), true /* with signature */);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001727 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001728 }
1729
Mindy Pereirabddd6f32012-06-20 12:10:03 -07001730 @VisibleForTesting
1731 protected void initAttachments(Message refMessage) {
Mark Wei434f2942012-08-24 11:54:02 -07001732 addAttachments(refMessage.getAttachments());
1733 }
1734
1735 public long addAttachments(List<Attachment> attachments) {
1736 long size = 0;
1737 AttachmentFailureException error = null;
1738 for (Attachment a : attachments) {
1739 try {
1740 size += mAttachmentsView.addAttachment(mAccount, a);
1741 } catch (AttachmentFailureException e) {
1742 error = e;
1743 }
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001744 }
Mark Wei434f2942012-08-24 11:54:02 -07001745 if (error != null) {
1746 LogUtils.e(LOG_TAG, error, "Error adding attachment");
1747 if (attachments.size() > 1) {
1748 showAttachmentTooBigToast(R.string.too_large_to_attach_multiple);
1749 } else {
1750 showAttachmentTooBigToast(error.getErrorRes());
1751 }
1752 }
1753 return size;
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001754 }
1755
1756 /**
1757 * When an attachment is too large to be added to a message, show a toast.
1758 * This method also updates the position of the toast so that it is shown
1759 * clearly above they keyboard if it happens to be open.
1760 */
Mark Wei434f2942012-08-24 11:54:02 -07001761 private void showAttachmentTooBigToast(int errorRes) {
1762 String maxSize = AttachmentUtils.convertToHumanReadableSize(
1763 getApplicationContext(), mAccount.settings.getMaxAttachmentSize());
1764 showErrorToast(getString(errorRes, maxSize));
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001765 }
1766
Mark Wei434f2942012-08-24 11:54:02 -07001767 private void showErrorToast(String message) {
1768 Toast t = Toast.makeText(this, message, Toast.LENGTH_LONG);
1769 t.setText(message);
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001770 t.setGravity(Gravity.CENTER_HORIZONTAL, 0,
1771 getResources().getDimensionPixelSize(R.dimen.attachment_toast_yoffset));
1772 t.show();
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001773 }
1774
Paul Westbrookf97588b2012-03-20 11:11:37 -07001775 private void initAttachmentsFromIntent(Intent intent) {
Paul Westbrook03ee9712012-04-02 09:51:51 -07001776 Bundle extras = intent.getExtras();
1777 if (extras == null) {
1778 extras = Bundle.EMPTY;
1779 }
Paul Westbrookf97588b2012-03-20 11:11:37 -07001780 final String action = intent.getAction();
1781 if (!mAttachmentsChanged) {
1782 long totalSize = 0;
1783 if (extras.containsKey(EXTRA_ATTACHMENTS)) {
1784 String[] uris = (String[]) extras.getSerializable(EXTRA_ATTACHMENTS);
1785 for (String uriString : uris) {
1786 final Uri uri = Uri.parse(uriString);
1787 long size = 0;
1788 try {
Andy Huang91ede362014-01-21 19:16:00 -08001789 if (handleSpecialAttachmentUri(uri)) {
1790 continue;
1791 }
1792
Andy Huange003b4c2013-08-16 10:32:05 -07001793 final Attachment a = mAttachmentsView.generateLocalAttachment(uri);
1794 size = mAttachmentsView.addAttachment(mAccount, a);
1795
1796 Analytics.getInstance().sendEvent("send_intent_attachment",
1797 Utils.normalizeMimeType(a.getContentType()), null, size);
1798
Paul Westbrookf97588b2012-03-20 11:11:37 -07001799 } catch (AttachmentFailureException e) {
Paul Westbrookf97588b2012-03-20 11:11:37 -07001800 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Mark Wei434f2942012-08-24 11:54:02 -07001801 showAttachmentTooBigToast(e.getErrorRes());
Paul Westbrookf97588b2012-03-20 11:11:37 -07001802 }
1803 totalSize += size;
1804 }
1805 }
mindyp9a9e8d62012-10-03 12:24:07 -07001806 if (extras.containsKey(Intent.EXTRA_STREAM)) {
1807 if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
Andy Huang91ede362014-01-21 19:16:00 -08001808 final ArrayList<Uri> uris = extras
mindyp9a9e8d62012-10-03 12:24:07 -07001809 .getParcelableArrayList(Intent.EXTRA_STREAM);
1810 ArrayList<Attachment> attachments = new ArrayList<Attachment>();
Andy Huang91ede362014-01-21 19:16:00 -08001811 for (Uri uri : uris) {
mindyp9a9e8d62012-10-03 12:24:07 -07001812 try {
Andy Huang91ede362014-01-21 19:16:00 -08001813 if (handleSpecialAttachmentUri(uri)) {
1814 continue;
1815 }
1816
1817 final Attachment a = mAttachmentsView.generateLocalAttachment(uri);
Andy Huange003b4c2013-08-16 10:32:05 -07001818 attachments.add(a);
1819
1820 Analytics.getInstance().sendEvent("send_intent_attachment",
1821 Utils.normalizeMimeType(a.getContentType()), null, a.size);
1822
mindyp9a9e8d62012-10-03 12:24:07 -07001823 } catch (AttachmentFailureException e) {
1824 LogUtils.e(LOG_TAG, e, "Error adding attachment");
1825 String maxSize = AttachmentUtils.convertToHumanReadableSize(
1826 getApplicationContext(),
1827 mAccount.settings.getMaxAttachmentSize());
1828 showErrorToast(getString
1829 (R.string.generic_attachment_problem, maxSize));
1830 }
1831 }
1832 totalSize += addAttachments(attachments);
1833 } else {
Tony Mantler581edd42014-02-18 15:41:22 -08001834 final Uri uri = extras.getParcelable(Intent.EXTRA_STREAM);
mindyp9a9e8d62012-10-03 12:24:07 -07001835 long size = 0;
Paul Westbrookf97588b2012-03-20 11:11:37 -07001836 try {
Andy Huang91ede362014-01-21 19:16:00 -08001837 if (!handleSpecialAttachmentUri(uri)) {
1838 final Attachment a = mAttachmentsView.generateLocalAttachment(uri);
1839 size = mAttachmentsView.addAttachment(mAccount, a);
Andy Huange003b4c2013-08-16 10:32:05 -07001840
Andy Huang91ede362014-01-21 19:16:00 -08001841 Analytics.getInstance().sendEvent("send_intent_attachment",
1842 Utils.normalizeMimeType(a.getContentType()), null, size);
1843 }
Andy Huange003b4c2013-08-16 10:32:05 -07001844
Paul Westbrookf97588b2012-03-20 11:11:37 -07001845 } catch (AttachmentFailureException e) {
Paul Westbrookf97588b2012-03-20 11:11:37 -07001846 LogUtils.e(LOG_TAG, e, "Error adding attachment");
mindyp9a9e8d62012-10-03 12:24:07 -07001847 showAttachmentTooBigToast(e.getErrorRes());
Paul Westbrookf97588b2012-03-20 11:11:37 -07001848 }
mindyp9a9e8d62012-10-03 12:24:07 -07001849 totalSize += size;
Paul Westbrookf97588b2012-03-20 11:11:37 -07001850 }
1851 }
1852
1853 if (totalSize > 0) {
1854 mAttachmentsChanged = true;
1855 updateSaveUi();
Andy Huange003b4c2013-08-16 10:32:05 -07001856
1857 Analytics.getInstance().sendEvent("send_intent_with_attachments",
1858 Integer.toString(getAttachments().size()), null, totalSize);
Paul Westbrookf97588b2012-03-20 11:11:37 -07001859 }
1860 }
1861 }
1862
Andrew Sapperstein746d8612013-08-26 15:56:32 -07001863 protected void initQuotedText(CharSequence quotedText, boolean shouldQuoteText) {
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001864 mQuotedTextView.setQuotedTextFromHtml(quotedText, shouldQuoteText);
1865 mShowQuotedText = true;
1866 }
Paul Westbrookf97588b2012-03-20 11:11:37 -07001867
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001868 private void initQuotedTextFromRefMessage(Message refMessage, int action) {
1869 if (mRefMessage != null && (action == REPLY || action == REPLY_ALL || action == FORWARD)) {
Mindy Pereira9932dee2012-01-10 16:09:50 -08001870 mQuotedTextView.setQuotedText(action, refMessage, action != FORWARD);
1871 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001872 }
1873
1874 private void updateHideOrShowCcBcc() {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001875 // Its possible there is a menu item OR a button.
Mindy Pereira326689d2012-05-17 10:14:14 -07001876 boolean ccVisible = mCcBccView.isCcVisible();
1877 boolean bccVisible = mCcBccView.isBccVisible();
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001878 if (mCcBccButton != null) {
Mindy Pereira326689d2012-05-17 10:14:14 -07001879 if (!ccVisible || !bccVisible) {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001880 mCcBccButton.setVisibility(View.VISIBLE);
Mindy Pereira326689d2012-05-17 10:14:14 -07001881 mCcBccButton.setText(getString(!ccVisible ? R.string.add_cc_label
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001882 : R.string.add_bcc_label));
1883 } else {
mindypcd0b0b92012-08-23 14:33:17 -07001884 mCcBccButton.setVisibility(View.INVISIBLE);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001885 }
1886 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001887 }
1888
Mindy Pereira013194c2012-01-06 15:09:33 -08001889 /**
1890 * Add attachment and update the compose area appropriately.
Mindy Pereira013194c2012-01-06 15:09:33 -08001891 */
Andrew Sapperstein865ae9c2014-02-10 18:23:48 -08001892 private void addAttachmentAndUpdateView(Intent data) {
Andrew Sapperstein05089f32013-10-01 17:00:03 -07001893 if (data == null) {
1894 return;
1895 }
1896
1897 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
1898 final ClipData clipData = data.getClipData();
1899 if (clipData != null) {
1900 for (int i = 0, size = clipData.getItemCount(); i < size; i++) {
1901 addAttachmentAndUpdateView(clipData.getItemAt(i).getUri());
1902 }
1903 return;
1904 }
1905 }
1906
1907 addAttachmentAndUpdateView(data.getData());
Mindy Pereira2421dc82012-03-27 13:32:31 -07001908 }
1909
Andrew Sapperstein865ae9c2014-02-10 18:23:48 -08001910 private void addAttachmentAndUpdateView(Uri contentUri) {
Andy Huang5c5fd572012-04-08 18:19:29 -07001911 if (contentUri == null) {
Mindy Pereira2421dc82012-03-27 13:32:31 -07001912 return;
1913 }
Mindy Pereira013194c2012-01-06 15:09:33 -08001914 try {
Andy Huang91ede362014-01-21 19:16:00 -08001915
1916 if (handleSpecialAttachmentUri(contentUri)) {
1917 return;
1918 }
1919
Andy Huang5c5fd572012-04-08 18:19:29 -07001920 addAttachmentAndUpdateView(mAttachmentsView.generateLocalAttachment(contentUri));
1921 } catch (AttachmentFailureException e) {
Andy Huang5c5fd572012-04-08 18:19:29 -07001922 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Mark Wei434f2942012-08-24 11:54:02 -07001923 showErrorToast(getResources().getString(
1924 e.getErrorRes(),
1925 AttachmentUtils.convertToHumanReadableSize(
1926 getApplicationContext(), mAccount.settings.getMaxAttachmentSize())));
Andy Huang5c5fd572012-04-08 18:19:29 -07001927 }
1928 }
1929
Andy Huang91ede362014-01-21 19:16:00 -08001930 /**
1931 * Allow subclasses to implement custom handling of attachments.
1932 *
1933 * @param contentUri a passed-in URI from a pick intent
1934 * @return true iff handled
1935 */
1936 protected boolean handleSpecialAttachmentUri(final Uri contentUri) {
1937 return false;
1938 }
1939
Andrew Sapperstein865ae9c2014-02-10 18:23:48 -08001940 private void addAttachmentAndUpdateView(Attachment attachment) {
Andy Huang5c5fd572012-04-08 18:19:29 -07001941 try {
Mark Wei434f2942012-08-24 11:54:02 -07001942 long size = mAttachmentsView.addAttachment(mAccount, attachment);
Mindy Pereira9932dee2012-01-10 16:09:50 -08001943 if (size > 0) {
1944 mAttachmentsChanged = true;
1945 updateSaveUi();
Mindy Pereira013194c2012-01-06 15:09:33 -08001946 }
Mindy Pereira9932dee2012-01-10 16:09:50 -08001947 } catch (AttachmentFailureException e) {
Mindy Pereira9932dee2012-01-10 16:09:50 -08001948 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Mark Wei434f2942012-08-24 11:54:02 -07001949 showAttachmentTooBigToast(e.getErrorRes());
Mindy Pereira013194c2012-01-06 15:09:33 -08001950 }
1951 }
1952
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08001953 void initRecipientsFromRefMessage(Message refMessage, int action) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001954 // Don't populate the address if this is a forward.
1955 if (action == ComposeActivity.FORWARD) {
1956 return;
1957 }
Scott Kennedyff8553f2013-04-05 20:57:44 -07001958 initReplyRecipients(refMessage, action);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001959 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001960
Paul Westbrook6d2442b2013-07-17 17:51:51 -07001961 // TODO: This should be private. This method shouldn't be used by ComposeActivityTests, as
1962 // it doesn't setup the state of the activity correctly
Mindy Pereira818143e2012-01-11 13:59:49 -08001963 @VisibleForTesting
Scott Kennedyff8553f2013-04-05 20:57:44 -07001964 void initReplyRecipients(final Message refMessage, final int action) {
Tony Mantler9016a5e2013-07-19 11:54:17 -07001965 String[] sentToAddresses = refMessage.getToAddressesUnescaped();
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001966 final Collection<String> toAddresses;
Tony Mantler89de9eb2013-07-25 11:43:58 -07001967 final String[] fromAddresses = refMessage.getFromAddressesUnescaped();
1968 final String fromAddress = fromAddresses.length > 0 ? fromAddresses[0] : null;
Andy Huange2af8872014-01-16 12:36:27 -08001969 final String[] replyToAddresses = getReplyToAddresses(
1970 refMessage.getReplyToAddressesUnescaped(), fromAddress);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001971
1972 // If this is a reply, the Cc list is empty. If this is a reply-all, the
1973 // Cc list is the union of the To and Cc recipients of the original
1974 // message, excluding the current user's email address and any addresses
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001975 // already on the To list.
1976 if (action == ComposeActivity.REPLY) {
Tony Mantler24f116f2014-01-16 10:20:50 -08001977 toAddresses = initToRecipients(fromAddress, replyToAddresses, sentToAddresses);
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001978 addToAddresses(toAddresses);
1979 } else if (action == ComposeActivity.REPLY_ALL) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001980 final Set<String> ccAddresses = Sets.newHashSet();
Tony Mantler24f116f2014-01-16 10:20:50 -08001981 toAddresses = initToRecipients(fromAddress, replyToAddresses, sentToAddresses);
Mindy Pereira154386a2012-01-11 13:02:33 -08001982 addToAddresses(toAddresses);
Scott Kennedyff8553f2013-04-05 20:57:44 -07001983 addRecipients(ccAddresses, sentToAddresses);
Tony Mantler9016a5e2013-07-19 11:54:17 -07001984 addRecipients(ccAddresses, refMessage.getCcAddressesUnescaped());
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001985 addCcAddresses(ccAddresses, toAddresses);
1986 }
1987 }
1988
Andy Huange2af8872014-01-16 12:36:27 -08001989 // If there is no reply to address, the reply to address is the sender.
1990 private static String[] getReplyToAddresses(String[] replyTo, String from) {
1991 boolean hasReplyTo = false;
1992 for (final String replyToAddress : replyTo) {
1993 if (!TextUtils.isEmpty(replyToAddress)) {
1994 hasReplyTo = true;
1995 }
1996 }
1997 return hasReplyTo ? replyTo : new String[] {from};
1998 }
1999
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002000 private void addToAddresses(Collection<String> addresses) {
2001 addAddressesToList(addresses, mTo);
2002 }
2003
2004 private void addCcAddresses(Collection<String> addresses, Collection<String> toAddresses) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07002005 addCcAddressesToList(tokenizeAddressList(addresses),
2006 toAddresses != null ? tokenizeAddressList(toAddresses) : null, mCc);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002007 }
2008
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07002009 private void addBccAddresses(Collection<String> addresses) {
2010 addAddressesToList(addresses, mBcc);
2011 }
2012
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002013 @VisibleForTesting
2014 protected void addCcAddressesToList(List<Rfc822Token[]> addresses,
2015 List<Rfc822Token[]> compareToList, RecipientEditTextView list) {
2016 String address;
2017
Mindy Pereira8eca57a2012-03-20 16:42:34 -07002018 if (compareToList == null) {
Tony Mantler581edd42014-02-18 15:41:22 -08002019 for (final Rfc822Token[] tokens : addresses) {
2020 for (final Rfc822Token token : tokens) {
2021 address = token.toString();
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002022 list.append(address + END_TOKEN);
2023 }
2024 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07002025 } else {
2026 HashSet<String> compareTo = convertToHashSet(compareToList);
Tony Mantler581edd42014-02-18 15:41:22 -08002027 for (final Rfc822Token[] tokens : addresses) {
2028 for (final Rfc822Token token : tokens) {
2029 address = token.toString();
Mindy Pereira8eca57a2012-03-20 16:42:34 -07002030 // Check if this is a duplicate:
Tony Mantler581edd42014-02-18 15:41:22 -08002031 if (!compareTo.contains(token.getAddress())) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07002032 // Get the address here
2033 list.append(address + END_TOKEN);
2034 }
2035 }
2036 }
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002037 }
2038 }
2039
Scott Kennedyff8553f2013-04-05 20:57:44 -07002040 private static HashSet<String> convertToHashSet(final List<Rfc822Token[]> list) {
2041 final HashSet<String> hash = new HashSet<String>();
2042 for (final Rfc822Token[] tokens : list) {
Tony Mantler581edd42014-02-18 15:41:22 -08002043 for (final Rfc822Token token : tokens) {
2044 hash.add(token.getAddress());
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002045 }
2046 }
2047 return hash;
2048 }
2049
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002050 protected List<Rfc822Token[]> tokenizeAddressList(Collection<String> addresses) {
2051 @VisibleForTesting
2052 List<Rfc822Token[]> tokenized = new ArrayList<Rfc822Token[]>();
2053
2054 for (String address: addresses) {
2055 tokenized.add(Rfc822Tokenizer.tokenize(address));
2056 }
2057 return tokenized;
2058 }
2059
2060 @VisibleForTesting
2061 void addAddressesToList(Collection<String> addresses, RecipientEditTextView list) {
2062 for (String address : addresses) {
2063 addAddressToList(address, list);
2064 }
2065 }
2066
Scott Kennedyff8553f2013-04-05 20:57:44 -07002067 private static void addAddressToList(final String address, final RecipientEditTextView list) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002068 if (address == null || list == null)
2069 return;
2070
Scott Kennedyff8553f2013-04-05 20:57:44 -07002071 final Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(address);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002072
Tony Mantler581edd42014-02-18 15:41:22 -08002073 for (final Rfc822Token token : tokens) {
2074 list.append(token + END_TOKEN);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002075 }
2076 }
2077
2078 @VisibleForTesting
Scott Kennedyff8553f2013-04-05 20:57:44 -07002079 protected Collection<String> initToRecipients(final String fullSenderAddress,
Tony Mantler24f116f2014-01-16 10:20:50 -08002080 final String[] replyToAddresses, final String[] inToAddresses) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002081 // The To recipient is the reply-to address specified in the original
2082 // message, unless it is:
2083 // the current user OR a custom from of the current user, in which case
2084 // it's the To recipient list of the original message.
2085 // OR missing, in which case use the sender of the original message
2086 Set<String> toAddresses = Sets.newHashSet();
Tony Mantler24f116f2014-01-16 10:20:50 -08002087 for (final String replyToAddress : replyToAddresses) {
2088 if (!TextUtils.isEmpty(replyToAddress)
2089 && !recipientMatchesThisAccount(replyToAddress)) {
2090 toAddresses.add(replyToAddress);
2091 }
2092 }
2093 if (toAddresses.size() == 0) {
mindyp65b06f52012-11-21 10:35:08 -08002094 // In this case, the user is replying to a message in which their
Tony Mantler24f116f2014-01-16 10:20:50 -08002095 // current account or some of their custom from addresses are the only
2096 // recipients and they sent the original message.
mindyp65b06f52012-11-21 10:35:08 -08002097 if (inToAddresses.length == 1 && recipientMatchesThisAccount(fullSenderAddress)
2098 && recipientMatchesThisAccount(inToAddresses[0])) {
2099 toAddresses.add(inToAddresses[0]);
2100 return toAddresses;
2101 }
2102 // This happens if the user replies to a message they originally
2103 // wrote. In this case, "reply" really means "re-send," so we
2104 // target the original recipients. This works as expected even
2105 // if the user sent the original message to themselves.
2106 for (String address : inToAddresses) {
2107 if (!recipientMatchesThisAccount(address)) {
2108 toAddresses.add(address);
mindypfe8557b2012-11-05 12:05:16 -08002109 }
Mindy Pereira1469b4e2012-06-19 19:18:54 -07002110 }
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002111 }
2112 return toAddresses;
2113 }
2114
Scott Kennedyff8553f2013-04-05 20:57:44 -07002115 private void addRecipients(final Set<String> recipients, final String[] addresses) {
2116 for (final String email : addresses) {
Mindy Pereiracecc54a2012-07-31 09:38:11 -07002117 // Do not add this account, or any of its custom from addresses, to
2118 // the list of recipients.
Mindy Pereira4a20b702012-01-05 16:24:24 -08002119 final String recipientAddress = Address.getEmailAddress(email).getAddress();
mindyp5ee5d692012-11-19 16:02:16 -08002120 if (!recipientMatchesThisAccount(recipientAddress)) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08002121 recipients.add(email.replace("\"\"", ""));
2122 }
2123 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002124 }
2125
Mindy Pereiracecc54a2012-07-31 09:38:11 -07002126 /**
2127 * A recipient matches this account if it has the same address as the
2128 * currently selected account OR one of the custom from addresses associated
2129 * with the currently selected account.
Mindy Pereiracecc54a2012-07-31 09:38:11 -07002130 * @param recipientAddress address we are comparing with the currently selected account
Mindy Pereiracecc54a2012-07-31 09:38:11 -07002131 */
mindyp5ee5d692012-11-19 16:02:16 -08002132 protected boolean recipientMatchesThisAccount(String recipientAddress) {
2133 return ReplyFromAccount.matchesAccountOrCustomFrom(mAccount, recipientAddress,
mindypfe8557b2012-11-05 12:05:16 -08002134 mAccount.getReplyFroms());
Mindy Pereiracecc54a2012-07-31 09:38:11 -07002135 }
2136
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07002137 /**
2138 * Returns a formatted subject string with the appropriate prefix for the action type.
2139 * E.g., "FWD: " is prepended if action is {@link ComposeActivity#FORWARD}.
2140 */
Andrew Sapperstein7e04f142014-06-11 13:43:07 -07002141 public static String buildFormattedSubject(Resources res, String subject, int action) {
2142 String prefix;
2143 String correctedSubject = null;
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002144 if (action == ComposeActivity.COMPOSE) {
2145 prefix = "";
2146 } else if (action == ComposeActivity.FORWARD) {
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07002147 prefix = res.getString(R.string.forward_subject_label);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002148 } else {
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07002149 prefix = res.getString(R.string.reply_subject_label);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002150 }
2151
2152 // Don't duplicate the prefix
Mindy Pereirac7a36992012-07-30 14:00:37 -07002153 if (!TextUtils.isEmpty(subject)
2154 && subject.toLowerCase().startsWith(prefix.toLowerCase())) {
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002155 correctedSubject = subject;
2156 } else {
Andrew Sapperstein7e04f142014-06-11 13:43:07 -07002157 correctedSubject = String.format(
2158 res.getString(R.string.formatted_subject), prefix, subject);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002159 }
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07002160
2161 return correctedSubject;
2162 }
2163
2164 private void setSubject(Message refMessage, int action) {
2165 mSubject.setText(buildFormattedSubject(getResources(), refMessage.subject, action));
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002166 }
2167
Mindy Pereira818143e2012-01-11 13:59:49 -08002168 private void initRecipients() {
2169 setupRecipients(mTo);
2170 setupRecipients(mCc);
2171 setupRecipients(mBcc);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002172 }
2173
Mindy Pereira818143e2012-01-11 13:59:49 -08002174 private void setupRecipients(RecipientEditTextView view) {
Andrew Sapperstein47c30c22014-06-04 10:26:22 -07002175 // todo - remove this experiment
2176 if (LogUtils.isLoggable("NewChips", LogUtils.DEBUG) || mUseNewChips) {
Andrew Sapperstein50453e42014-05-16 09:25:10 -07002177 final DropdownChipLayouter layouter = getDropdownChipLayouter();
2178 if (layouter != null) {
2179 view.setDropdownChipLayouter(layouter);
2180 }
2181 view.setAdapter(getRecipientAdapter());
2182 } else {
2183 view.setAdapter(new RecipientAdapter(this, mAccount));
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07002184 }
Andrew Sappersteinffd61552014-05-14 15:04:23 -07002185 view.setRecipientEntryItemClickedListener(this);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002186 if (mValidator == null) {
Tony Mantler79b11562013-10-09 15:31:50 -07002187 final String accountName = mAccount.getEmailAddress();
Mindy Pereira33fe9082012-01-09 16:24:30 -08002188 int offset = accountName.indexOf("@") + 1;
2189 String account = accountName;
Tony Mantler79b11562013-10-09 15:31:50 -07002190 if (offset > 0) {
2191 account = account.substring(offset);
Mindy Pereirac17d0732011-12-29 10:46:19 -08002192 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002193 mValidator = new Rfc822Validator(account);
Mindy Pereirac17d0732011-12-29 10:46:19 -08002194 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002195 view.setValidator(mValidator);
Mindy Pereira8e9305e2011-12-13 14:25:04 -08002196 }
2197
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07002198 /**
2199 * Derived classes should override if they wish to provide their own autocomplete behavior.
2200 */
2201 public BaseRecipientAdapter getRecipientAdapter() {
2202 return new RecipientAdapter(this, mAccount);
2203 }
2204
2205 /**
2206 * Derived classes should override this to provide their own dropdown behavior.
2207 * If the result is null, the default {@link com.android.ex.chips.DropdownChipLayouter}
2208 * is used.
2209 */
2210 public DropdownChipLayouter getDropdownChipLayouter() {
2211 return null;
2212 }
2213
Mindy Pereira8e9305e2011-12-13 14:25:04 -08002214 @Override
2215 public void onClick(View v) {
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002216 final int id = v.getId();
2217 if (id == R.id.add_cc_bcc) {
2218 // Verify that cc/ bcc aren't showing.
2219 // Animate in cc/bcc.
2220 showCcBccViews();
Andrew Sapperstein6aea7862013-10-24 19:59:51 -07002221 } else if (id == R.id.add_attachment) {
2222 doAttach(Utils.isRunningKitkatOrLater() ? MIME_TYPE_ALL : MIME_TYPE_PHOTO);
Mindy Pereira8e9305e2011-12-13 14:25:04 -08002223 }
2224 }
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002225
2226 @Override
2227 public boolean onCreateOptionsMenu(Menu menu) {
Tony Mantler5b8799a2013-10-31 10:43:03 -07002228 final boolean superCreated = super.onCreateOptionsMenu(menu);
Mindy Pereirab199d172012-08-13 11:04:03 -07002229 // Don't render any menu items when there are no accounts.
2230 if (mAccounts == null || mAccounts.length == 0) {
Tony Mantler5b8799a2013-10-31 10:43:03 -07002231 return superCreated;
Mindy Pereirab199d172012-08-13 11:04:03 -07002232 }
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002233 MenuInflater inflater = getMenuInflater();
2234 inflater.inflate(R.menu.compose_menu, menu);
mindyp1d7e9142012-11-21 13:54:30 -08002235
2236 /*
2237 * Start save in the correct enabled state.
2238 * 1) If a user launches compose from within gmail, save is disabled
2239 * until they add something, at which point, save is enabled, auto save
2240 * on exit; if the user empties everything, save is disabled, exiting does not
2241 * auto-save
2242 * 2) if a user replies/ reply all/ forwards from within gmail, save is
2243 * disabled until they change something, at which point, save is
2244 * enabled, auto save on exit; if the user empties everything, save is
2245 * disabled, exiting does not auto-save.
2246 * 3) If a user launches compose from another application and something
2247 * gets populated (attachments, recipients, body, subject, etc), save is
2248 * enabled, auto save on exit; if the user empties everything, save is
2249 * disabled, exiting does not auto-save
2250 */
Mindy Pereira82cc5662012-01-09 17:29:30 -08002251 mSave = menu.findItem(R.id.save);
mindyp1d7e9142012-11-21 13:54:30 -08002252 String action = getIntent() != null ? getIntent().getAction() : null;
Andy Huang9f855d62013-05-30 17:15:03 -07002253 enableSave(mInnerSavedState != null ?
2254 mInnerSavedState.getBoolean(EXTRA_SAVE_ENABLED)
mindyp1d7e9142012-11-21 13:54:30 -08002255 : (Intent.ACTION_SEND.equals(action)
2256 || Intent.ACTION_SEND_MULTIPLE.equals(action)
2257 || Intent.ACTION_SENDTO.equals(action)
2258 || shouldSave()));
2259
Mindy Pereira3ca5bad2012-04-16 11:02:42 -07002260 MenuItem helpItem = menu.findItem(R.id.help_info_menu_item);
2261 MenuItem sendFeedbackItem = menu.findItem(R.id.feedback_menu_item);
2262 if (helpItem != null) {
2263 helpItem.setVisible(mAccount != null
2264 && mAccount.supportsCapability(AccountCapabilities.HELP_CONTENT));
2265 }
2266 if (sendFeedbackItem != null) {
2267 sendFeedbackItem.setVisible(mAccount != null
2268 && mAccount.supportsCapability(AccountCapabilities.SEND_FEEDBACK));
2269 }
Andrew Sapperstein5cb71802013-10-01 18:31:20 -07002270
Andrew Sapperstein8809f9f2013-10-11 16:13:35 -07002271 // Show attach picture on pre-K devices.
2272 menu.findItem(R.id.add_photo_attachment).setVisible(!Utils.isRunningKitkatOrLater());
Andrew Sapperstein5cb71802013-10-01 18:31:20 -07002273
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002274 return true;
2275 }
2276
2277 @Override
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08002278 public boolean onPrepareOptionsMenu(Menu menu) {
2279 MenuItem ccBcc = menu.findItem(R.id.add_cc_bcc);
Mindy Pereira818143e2012-01-11 13:59:49 -08002280 if (ccBcc != null && mCc != null) {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08002281 // Its possible there is a menu item OR a button.
2282 boolean ccFieldVisible = mCc.isShown();
2283 boolean bccFieldVisible = mBcc.isShown();
2284 if (!ccFieldVisible || !bccFieldVisible) {
2285 ccBcc.setVisible(true);
2286 ccBcc.setTitle(getString(!ccFieldVisible ? R.string.add_cc_label
2287 : R.string.add_bcc_label));
2288 } else {
2289 ccBcc.setVisible(false);
2290 }
2291 }
2292 return true;
2293 }
2294
2295 @Override
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002296 public boolean onOptionsItemSelected(MenuItem item) {
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002297 final int id = item.getItemId();
Andy Huangdc97bf42013-08-15 16:52:45 -07002298
Andy Huangf8c59b02014-03-19 20:00:53 -07002299 Analytics.getInstance().sendMenuItemEvent(Analytics.EVENT_CATEGORY_MENU_ITEM, id,
2300 "compose", 0);
Andy Huangdc97bf42013-08-15 16:52:45 -07002301
Mindy Pereira75f66632012-01-11 11:42:02 -08002302 boolean handled = true;
Andrew Sapperstein5cb71802013-10-01 18:31:20 -07002303 if (id == R.id.add_file_attachment) {
2304 doAttach(MIME_TYPE_ALL);
2305 } else if (id == R.id.add_photo_attachment) {
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002306 doAttach(MIME_TYPE_PHOTO);
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002307 } else if (id == R.id.add_cc_bcc) {
2308 showCcBccViews();
2309 } else if (id == R.id.save) {
2310 doSave(true);
2311 } else if (id == R.id.send) {
2312 doSend();
2313 } else if (id == R.id.discard) {
2314 doDiscard();
2315 } else if (id == R.id.settings) {
2316 Utils.showSettings(this, mAccount);
2317 } else if (id == android.R.id.home) {
2318 onAppUpPressed();
2319 } else if (id == R.id.help_info_menu_item) {
2320 Utils.showHelp(this, mAccount, getString(R.string.compose_help_context));
2321 } else if (id == R.id.feedback_menu_item) {
2322 Utils.sendFeedback(this, mAccount, false);
2323 } else {
2324 handled = false;
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002325 }
Tony Mantler581edd42014-02-18 15:41:22 -08002326 return handled || super.onOptionsItemSelected(item);
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002327 }
Mindy Pereira326c6602012-01-04 15:32:42 -08002328
Mindy Pereirab199d172012-08-13 11:04:03 -07002329 @Override
2330 public void onBackPressed() {
2331 // If we are showing the wait fragment, just exit.
2332 if (getWaitFragment() != null) {
2333 finish();
2334 } else {
2335 super.onBackPressed();
2336 }
2337 }
2338
Vikram Aggarwal1672ff82012-09-21 10:15:22 -07002339 /**
2340 * Carries out the "up" action in the action bar.
2341 */
Paul Westbrookdaecb4b2012-05-31 10:21:26 -07002342 private void onAppUpPressed() {
2343 if (mLaunchedFromEmail) {
2344 // If this was started from Gmail, simply treat app up as the system back button, so
2345 // that the last view is restored.
2346 onBackPressed();
2347 return;
2348 }
2349
2350 // Fire the main activity to ensure it launches the "top" screen of mail.
2351 // Since the main Activity is singleTask, it should revive that task if it was already
2352 // started.
Vikram Aggarwal0c3c2052012-09-21 11:06:28 -07002353 final Intent mailIntent = Utils.createViewInboxIntent(mAccount);
Paul Westbrookdaecb4b2012-05-31 10:21:26 -07002354 mailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |
2355 Intent.FLAG_ACTIVITY_TASK_ON_HOME);
2356 startActivity(mailIntent);
2357 finish();
2358 }
2359
Mindy Pereira33fe9082012-01-09 16:24:30 -08002360 private void doSend() {
Mark Weidd19b632012-10-19 13:59:28 -07002361 sendOrSaveWithSanityChecks(false, true, false, false);
Andy Huangdc97bf42013-08-15 16:52:45 -07002362 logSendOrSave(false /* save */);
2363 mPerformedSendOrDiscard = true;
Mindy Pereira33fe9082012-01-09 16:24:30 -08002364 }
2365
Mindy Pereira48e31b02012-05-30 13:12:24 -07002366 private void doSave(boolean showToast) {
Mark Weidd19b632012-10-19 13:59:28 -07002367 sendOrSaveWithSanityChecks(true, showToast, false, false);
Mindy Pereira48e31b02012-05-30 13:12:24 -07002368 }
2369
Andrew Sappersteinffd61552014-05-14 15:04:23 -07002370 @Override
2371 public void onRecipientEntryItemClicked(int charactersTyped, int position) {
2372 // Send analytics of characters typed and position in dropdown selected.
Andrew Sapperstein50453e42014-05-16 09:25:10 -07002373 final String category = mUseNewChips ? "suggest_click_new" : "suggest_click_old";
Andrew Sappersteinffd61552014-05-14 15:04:23 -07002374 Analytics.getInstance().sendEvent(
Andrew Sapperstein50453e42014-05-16 09:25:10 -07002375 category, Integer.toString(charactersTyped), Integer.toString(position), 0);
Andrew Sappersteinffd61552014-05-14 15:04:23 -07002376 }
2377
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002378 @VisibleForTesting
2379 public interface SendOrSaveCallback {
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07002380 void initializeSendOrSave(SendOrSaveTask sendOrSaveTask);
2381 void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage, Message message);
2382 Message getMessage();
2383 void sendOrSaveFinished(SendOrSaveTask sendOrSaveTask, boolean success);
2384 void incrementRecipientsTimesContacted(List<String> recipients);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002385 }
2386
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002387 @VisibleForTesting
2388 public static class SendOrSaveTask implements Runnable {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002389 private final Context mContext;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002390 @VisibleForTesting
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002391 public final SendOrSaveCallback mSendOrSaveCallback;
2392 @VisibleForTesting
2393 public final SendOrSaveMessage mSendOrSaveMessage;
mindyp44a63392012-11-05 12:05:16 -08002394 private ReplyFromAccount mExistingDraftAccount;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002395
2396 public SendOrSaveTask(Context context, SendOrSaveMessage message,
mindyp44a63392012-11-05 12:05:16 -08002397 SendOrSaveCallback callback, ReplyFromAccount draftAccount) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002398 mContext = context;
2399 mSendOrSaveCallback = callback;
2400 mSendOrSaveMessage = message;
mindyp44a63392012-11-05 12:05:16 -08002401 mExistingDraftAccount = draftAccount;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002402 }
2403
2404 @Override
2405 public void run() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002406 final SendOrSaveMessage sendOrSaveMessage = mSendOrSaveMessage;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002407
Mindy Pereira92551d02012-04-05 11:31:12 -07002408 final ReplyFromAccount selectedAccount = sendOrSaveMessage.mAccount;
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002409 Message message = mSendOrSaveCallback.getMessage();
2410 long messageId = message != null ? message.id : UIProvider.INVALID_MESSAGE_ID;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002411 // If a previous draft has been saved, in an account that is different
2412 // than what the user wants to send from, remove the old draft, and treat this
2413 // as a new message
mindyp44a63392012-11-05 12:05:16 -08002414 if (mExistingDraftAccount != null
2415 && !selectedAccount.account.uri.equals(mExistingDraftAccount.account.uri)) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002416 if (messageId != UIProvider.INVALID_MESSAGE_ID) {
2417 ContentResolver resolver = mContext.getContentResolver();
2418 ContentValues values = new ContentValues();
2419 values.put(BaseColumns._ID, messageId);
mindypfebd2262012-11-13 17:45:09 -08002420 if (mExistingDraftAccount.account.expungeMessageUri != null) {
2421 new ContentProviderTask.UpdateTask()
2422 .run(resolver, mExistingDraftAccount.account.expungeMessageUri,
2423 values, null, null);
Mindy Pereiracfb7f332012-02-28 10:23:43 -08002424 } else {
2425 // TODO(mindyp) delete the conversation.
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002426 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002427 // reset messageId to 0, so a new message will be created
2428 messageId = UIProvider.INVALID_MESSAGE_ID;
2429 }
2430 }
2431
2432 final long messageIdToSave = messageId;
Scott Kennedyff8553f2013-04-05 20:57:44 -07002433 sendOrSaveMessage(messageIdToSave, sendOrSaveMessage, selectedAccount);
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002434
2435 if (!sendOrSaveMessage.mSave) {
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07002436 incrementRecipientsTimesContacted(
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002437 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.TO));
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07002438 incrementRecipientsTimesContacted(
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002439 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.CC));
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07002440 incrementRecipientsTimesContacted(
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002441 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.BCC));
2442 }
2443 mSendOrSaveCallback.sendOrSaveFinished(SendOrSaveTask.this, true);
2444 }
2445
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07002446 private void incrementRecipientsTimesContacted(final String addressString) {
Tony Mantler9f324232013-08-08 14:24:30 -07002447 if (TextUtils.isEmpty(addressString)) {
2448 return;
2449 }
2450 final Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(addressString);
2451 final ArrayList<String> recipients = new ArrayList<String>(tokens.length);
Tony Mantler581edd42014-02-18 15:41:22 -08002452 for (final Rfc822Token token : tokens) {
2453 recipients.add(token.getAddress());
Tony Mantler9f324232013-08-08 14:24:30 -07002454 }
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07002455 mSendOrSaveCallback.incrementRecipientsTimesContacted(recipients);
Tony Mantler9f324232013-08-08 14:24:30 -07002456 }
2457
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002458 /**
2459 * Send or Save a message.
2460 */
Scott Kennedyff8553f2013-04-05 20:57:44 -07002461 private void sendOrSaveMessage(final long messageIdToSave,
2462 final SendOrSaveMessage sendOrSaveMessage, final ReplyFromAccount selectedAccount) {
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002463 final ContentResolver resolver = mContext.getContentResolver();
2464 final boolean updateExistingMessage = messageIdToSave != UIProvider.INVALID_MESSAGE_ID;
2465
2466 final String accountMethod = sendOrSaveMessage.mSave ?
2467 UIProvider.AccountCallMethods.SAVE_MESSAGE :
2468 UIProvider.AccountCallMethods.SEND_MESSAGE;
2469
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002470 try {
2471 if (updateExistingMessage) {
2472 sendOrSaveMessage.mValues.put(BaseColumns._ID, messageIdToSave);
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002473
Paul Westbrook013a23c2013-02-22 10:37:41 -08002474 callAccountSendSaveMethod(resolver,
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002475 selectedAccount.account, accountMethod, sendOrSaveMessage);
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002476 } else {
Paul Westbrook013a23c2013-02-22 10:37:41 -08002477 Uri messageUri = null;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002478 final Bundle result = callAccountSendSaveMethod(resolver,
2479 selectedAccount.account, accountMethod, sendOrSaveMessage);
2480 if (result != null) {
2481 // If a non-null value was returned, then the provider handled the call
2482 // method
2483 messageUri = result.getParcelable(UIProvider.MessageColumns.URI);
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002484 }
2485 if (sendOrSaveMessage.mSave && messageUri != null) {
2486 final Cursor messageCursor = resolver.query(messageUri,
2487 UIProvider.MESSAGE_PROJECTION, null, null, null);
2488 if (messageCursor != null) {
2489 try {
2490 if (messageCursor.moveToFirst()) {
2491 // Broadcast notification that a new message has
2492 // been allocated
2493 mSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage,
2494 new Message(messageCursor));
2495 }
2496 } finally {
2497 messageCursor.close();
Paul Westbrookba558482012-03-19 11:00:24 -07002498 }
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002499 }
2500 }
2501 }
2502 } finally {
2503 // Close any opened file descriptors
2504 closeOpenedAttachmentFds(sendOrSaveMessage);
2505 }
2506 }
2507
Scott Kennedyff8553f2013-04-05 20:57:44 -07002508 private static void closeOpenedAttachmentFds(final SendOrSaveMessage sendOrSaveMessage) {
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002509 final Bundle openedFds = sendOrSaveMessage.attachmentFds();
2510 if (openedFds != null) {
2511 final Set<String> keys = openedFds.keySet();
Scott Kennedyff8553f2013-04-05 20:57:44 -07002512 for (final String key : keys) {
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002513 final ParcelFileDescriptor fd = openedFds.getParcelable(key);
2514 if (fd != null) {
2515 try {
2516 fd.close();
2517 } catch (IOException e) {
2518 // Do nothing
Paul Westbrookba558482012-03-19 11:00:24 -07002519 }
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002520 }
2521 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002522 }
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002523 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002524
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002525 /**
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07002526 * Use the {@link ContentResolver#call} method to send or save the message.
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002527 *
2528 * If this was successful, this method will return an non-null Bundle instance
2529 */
Scott Kennedyff8553f2013-04-05 20:57:44 -07002530 private static Bundle callAccountSendSaveMethod(final ContentResolver resolver,
2531 final Account account, final String method,
2532 final SendOrSaveMessage sendOrSaveMessage) {
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002533 // Copy all of the values from the content values to the bundle
2534 final Bundle methodExtras = new Bundle(sendOrSaveMessage.mValues.size());
2535 final Set<Entry<String, Object>> valueSet = sendOrSaveMessage.mValues.valueSet();
2536
2537 for (Entry<String, Object> entry : valueSet) {
2538 final Object entryValue = entry.getValue();
2539 final String key = entry.getKey();
2540 if (entryValue instanceof String) {
2541 methodExtras.putString(key, (String)entryValue);
2542 } else if (entryValue instanceof Boolean) {
2543 methodExtras.putBoolean(key, (Boolean)entryValue);
2544 } else if (entryValue instanceof Integer) {
2545 methodExtras.putInt(key, (Integer)entryValue);
2546 } else if (entryValue instanceof Long) {
2547 methodExtras.putLong(key, (Long)entryValue);
2548 } else {
2549 LogUtils.wtf(LOG_TAG, "Unexpected object type: %s",
2550 entryValue.getClass().getName());
2551 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002552 }
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002553
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002554 // If the SendOrSaveMessage has some opened fds, add them to the bundle
2555 final Bundle fdMap = sendOrSaveMessage.attachmentFds();
2556 if (fdMap != null) {
2557 methodExtras.putParcelable(
2558 UIProvider.SendOrSaveMethodParamKeys.OPENED_FD_MAP, fdMap);
2559 }
2560
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002561 return resolver.call(account.uri, method, account.uri.toString(), methodExtras);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002562 }
2563 }
2564
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07002565 /**
2566 * Reports recipients that have been contacted in order to improve auto-complete
2567 * suggestions. Default behavior updates usage statistics in ContactsProvider.
2568 * @param recipients addresses
2569 */
2570 protected void incrementRecipientsTimesContacted(List<String> recipients) {
2571 final DataUsageStatUpdater statsUpdater = new DataUsageStatUpdater(this);
2572 statsUpdater.updateWithAddress(recipients);
2573 }
2574
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002575 @VisibleForTesting
2576 public static class SendOrSaveMessage {
Mindy Pereira92551d02012-04-05 11:31:12 -07002577 final ReplyFromAccount mAccount;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002578 final ContentValues mValues;
Mindy Pereira3ce64e72012-01-13 14:29:45 -08002579 final String mRefMessageId;
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002580 @VisibleForTesting
2581 public final boolean mSave;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002582 final int mRequestId;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002583 private final Bundle mAttachmentFds;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002584
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002585 public SendOrSaveMessage(Context context, ReplyFromAccount account, ContentValues values,
2586 String refMessageId, List<Attachment> attachments, boolean save) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002587 mAccount = account;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002588 mValues = values;
2589 mRefMessageId = refMessageId;
2590 mSave = save;
2591 mRequestId = mValues.hashCode() ^ hashCode();
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002592
2593 mAttachmentFds = initializeAttachmentFds(context, attachments);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002594 }
2595
2596 int requestId() {
2597 return mRequestId;
2598 }
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002599
2600 Bundle attachmentFds() {
2601 return mAttachmentFds;
2602 }
2603
2604 /**
2605 * Opens {@link ParcelFileDescriptor} for each of the attachments. This method must be
2606 * called before the ComposeActivity finishes.
2607 * Note: The caller is responsible for closing these file descriptors.
2608 */
Scott Kennedyff8553f2013-04-05 20:57:44 -07002609 private static Bundle initializeAttachmentFds(final Context context,
2610 final List<Attachment> attachments) {
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002611 if (attachments == null || attachments.size() == 0) {
2612 return null;
2613 }
2614
2615 final Bundle result = new Bundle(attachments.size());
2616 final ContentResolver resolver = context.getContentResolver();
2617
2618 for (Attachment attachment : attachments) {
2619 if (attachment == null || Utils.isEmpty(attachment.contentUri)) {
2620 continue;
2621 }
2622
2623 ParcelFileDescriptor fileDescriptor;
2624 try {
2625 fileDescriptor = resolver.openFileDescriptor(attachment.contentUri, "r");
2626 } catch (FileNotFoundException e) {
2627 LogUtils.e(LOG_TAG, e, "Exception attempting to open attachment");
2628 fileDescriptor = null;
Paul Westbrookc537fd42013-02-20 11:10:03 -08002629 } catch (SecurityException e) {
2630 // We have encountered a security exception when attempting to open the file
2631 // specified by the content uri. If the attachment has been cached, this
2632 // isn't a problem, as even through the original permission may have been
2633 // revoked, we have cached the file. This will happen when saving/sending
2634 // a previously saved draft.
2635 // TODO(markwei): Expose whether the attachment has been cached through the
2636 // attachment object. This would allow us to limit when the log is made, as
2637 // if the attachment has been cached, this really isn't an error
2638 LogUtils.e(LOG_TAG, e, "Security Exception attempting to open attachment");
2639 // Just set the file descriptor to null, as the underlying provider needs
2640 // to handle the file descriptor not being set.
2641 fileDescriptor = null;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002642 }
2643
2644 if (fileDescriptor != null) {
2645 result.putParcelable(attachment.contentUri.toString(), fileDescriptor);
2646 }
2647 }
2648
2649 return result;
2650 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002651 }
2652
2653 /**
2654 * Get the to recipients.
2655 */
2656 public String[] getToAddresses() {
2657 return getAddressesFromList(mTo);
2658 }
2659
2660 /**
2661 * Get the cc recipients.
2662 */
2663 public String[] getCcAddresses() {
2664 return getAddressesFromList(mCc);
2665 }
2666
2667 /**
2668 * Get the bcc recipients.
2669 */
2670 public String[] getBccAddresses() {
2671 return getAddressesFromList(mBcc);
2672 }
2673
2674 public String[] getAddressesFromList(RecipientEditTextView list) {
2675 if (list == null) {
2676 return new String[0];
2677 }
2678 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(list.getText());
2679 int count = tokens.length;
2680 String[] result = new String[count];
2681 for (int i = 0; i < count; i++) {
2682 result[i] = tokens[i].toString();
2683 }
2684 return result;
2685 }
2686
2687 /**
2688 * Check for invalid email addresses.
2689 * @param to String array of email addresses to check.
2690 * @param wrongEmailsOut Emails addresses that were invalid.
2691 */
Scott Kennedyff8553f2013-04-05 20:57:44 -07002692 public void checkInvalidEmails(final String[] to, final List<String> wrongEmailsOut) {
Mindy Pereirae5f20bf2012-06-25 14:20:40 -07002693 if (mValidator == null) {
2694 return;
2695 }
Scott Kennedyff8553f2013-04-05 20:57:44 -07002696 for (final String email : to) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002697 if (!mValidator.isValid(email)) {
2698 wrongEmailsOut.add(email);
2699 }
2700 }
2701 }
2702
Tony Mantler2558b502013-07-09 10:53:34 -07002703 public static class RecipientErrorDialogFragment extends DialogFragment {
Paul Westbrookf0ea4842013-08-13 16:41:18 -07002704 // Public no-args constructor needed for fragment re-instantiation
2705 public RecipientErrorDialogFragment() {}
2706
Tony Mantler2558b502013-07-09 10:53:34 -07002707 public static RecipientErrorDialogFragment newInstance(final String message) {
2708 final RecipientErrorDialogFragment frag = new RecipientErrorDialogFragment();
2709 final Bundle args = new Bundle(1);
2710 args.putString("message", message);
2711 frag.setArguments(args);
2712 return frag;
2713 }
2714
2715 @Override
2716 public Dialog onCreateDialog(Bundle savedInstanceState) {
2717 final String message = getArguments().getString("message");
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07002718 return new AlertDialog.Builder(getActivity())
2719 .setMessage(message)
Tony Mantler2558b502013-07-09 10:53:34 -07002720 .setPositiveButton(
2721 R.string.ok, new Dialog.OnClickListener() {
2722 @Override
2723 public void onClick(DialogInterface dialog, int which) {
2724 ((ComposeActivity)getActivity()).finishRecipientErrorDialog();
2725 }
2726 }).create();
2727 }
2728 }
2729
2730 private void finishRecipientErrorDialog() {
2731 // after the user dismisses the recipient error
2732 // dialog we want to make sure to refocus the
2733 // recipient to field so they can fix the issue
2734 // easily
2735 if (mTo != null) {
2736 mTo.requestFocus();
2737 }
2738 }
2739
Mindy Pereira82cc5662012-01-09 17:29:30 -08002740 /**
2741 * Show an error because the user has entered an invalid recipient.
Mindy Pereira82cc5662012-01-09 17:29:30 -08002742 */
Tony Mantler2558b502013-07-09 10:53:34 -07002743 private void showRecipientErrorDialog(final String message) {
2744 final DialogFragment frag = RecipientErrorDialogFragment.newInstance(message);
2745 frag.show(getFragmentManager(), "recipient error");
Mindy Pereira82cc5662012-01-09 17:29:30 -08002746 }
2747
2748 /**
2749 * Update the state of the UI based on whether or not the current draft
2750 * needs to be saved and the message is not empty.
2751 */
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002752 public void updateSaveUi() {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002753 if (mSave != null) {
2754 mSave.setEnabled((shouldSave() && !isBlank()));
2755 }
2756 }
2757
2758 /**
2759 * Returns true if we need to save the current draft.
2760 */
2761 private boolean shouldSave() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002762 synchronized (mDraftLock) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002763 // The message should only be saved if:
2764 // It hasn't been sent AND
2765 // Some text has been added to the message OR
2766 // an attachment has been added or removed
Mindy Pereiraa2148332012-07-02 13:54:14 -07002767 // AND there is actually something in the draft to save.
Andy Huangd47877e2012-08-09 19:31:24 -07002768 return (mTextChanged || mAttachmentsChanged || mReplyFromChanged)
Mindy Pereiraa2148332012-07-02 13:54:14 -07002769 && !isBlank();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002770 }
2771 }
2772
2773 /**
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002774 * Check if all fields are blank.
Mindy Pereira82cc5662012-01-09 17:29:30 -08002775 * @return boolean
2776 */
2777 public boolean isBlank() {
Alice Yanga49b6842013-08-23 10:36:18 -07002778 // Need to check for null since isBlank() can be called from onPause()
2779 // before findViews() is called
2780 if (mSubject == null || mBodyView == null || mTo == null || mCc == null ||
2781 mAttachmentsView == null) {
2782 LogUtils.w(LOG_TAG, "null views in isBlank check");
2783 return true;
2784 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002785 return mSubject.getText().length() == 0
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002786 && (mBodyView.getText().length() == 0 || getSignatureStartPosition(mSignature,
2787 mBodyView.getText().toString()) == 0)
2788 && mTo.length() == 0
2789 && mCc.length() == 0 && mBcc.length() == 0
2790 && mAttachmentsView.getAttachments().size() == 0;
2791 }
2792
2793 @VisibleForTesting
2794 protected int getSignatureStartPosition(String signature, String bodyText) {
2795 int startPos = -1;
2796
2797 if (TextUtils.isEmpty(signature) || TextUtils.isEmpty(bodyText)) {
2798 return startPos;
2799 }
2800
2801 int bodyLength = bodyText.length();
2802 int signatureLength = signature.length();
2803 String printableVersion = convertToPrintableSignature(signature);
2804 int printableLength = printableVersion.length();
2805
2806 if (bodyLength >= printableLength
2807 && bodyText.substring(bodyLength - printableLength)
2808 .equals(printableVersion)) {
2809 startPos = bodyLength - printableLength;
2810 } else if (bodyLength >= signatureLength
2811 && bodyText.substring(bodyLength - signatureLength)
2812 .equals(signature)) {
2813 startPos = bodyLength - signatureLength;
2814 }
2815 return startPos;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002816 }
2817
2818 /**
2819 * Allows any changes made by the user to be ignored. Called when the user
2820 * decides to discard a draft.
2821 */
2822 private void discardChanges() {
2823 mTextChanged = false;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002824 mAttachmentsChanged = false;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002825 mReplyFromChanged = false;
2826 }
2827
2828 /**
Tony Mantler581edd42014-02-18 15:41:22 -08002829 * @param save True to save, false to send
2830 * @param showToast True to show a toast once the message is sent/saved
Mindy Pereira181df782012-03-01 13:32:44 -08002831 */
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002832 protected void sendOrSaveWithSanityChecks(final boolean save, final boolean showToast,
Mark Weidd19b632012-10-19 13:59:28 -07002833 final boolean orientationChanged, final boolean autoSend) {
Mark Wei009b3712012-10-18 18:07:50 -07002834 if (mAccounts == null || mAccount == null) {
2835 Toast.makeText(this, R.string.send_failed, Toast.LENGTH_SHORT).show();
Mark Weidd19b632012-10-19 13:59:28 -07002836 if (autoSend) {
2837 finish();
2838 }
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002839 return;
Mark Wei009b3712012-10-18 18:07:50 -07002840 }
2841
Scott Kennedyff8553f2013-04-05 20:57:44 -07002842 final String[] to, cc, bcc;
Mindy Pereira181df782012-03-01 13:32:44 -08002843 if (orientationChanged) {
2844 to = cc = bcc = new String[0];
2845 } else {
2846 to = getToAddresses();
2847 cc = getCcAddresses();
2848 bcc = getBccAddresses();
2849 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002850
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002851 final ArrayList<String> recipients = buildEmailAddressList(to);
2852 recipients.addAll(buildEmailAddressList(cc));
2853 recipients.addAll(buildEmailAddressList(bcc));
2854
Mindy Pereira181df782012-03-01 13:32:44 -08002855 // Don't let the user send to nobody (but it's okay to save a message
2856 // with no recipients)
2857 if (!save && (to.length == 0 && cc.length == 0 && bcc.length == 0)) {
2858 showRecipientErrorDialog(getString(R.string.recipient_needed));
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002859 return;
Mindy Pereira181df782012-03-01 13:32:44 -08002860 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002861
Mindy Pereira181df782012-03-01 13:32:44 -08002862 List<String> wrongEmails = new ArrayList<String>();
2863 if (!save) {
2864 checkInvalidEmails(to, wrongEmails);
2865 checkInvalidEmails(cc, wrongEmails);
2866 checkInvalidEmails(bcc, wrongEmails);
2867 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002868
Mindy Pereira181df782012-03-01 13:32:44 -08002869 // Don't let the user send an email with invalid recipients
2870 if (wrongEmails.size() > 0) {
2871 String errorText = String.format(getString(R.string.invalid_recipient),
2872 wrongEmails.get(0));
2873 showRecipientErrorDialog(errorText);
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002874 return;
Mindy Pereira181df782012-03-01 13:32:44 -08002875 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002876
Mindy Pereira181df782012-03-01 13:32:44 -08002877 if (!save) {
Alan Lau3d519042014-06-05 11:13:06 -07002878 if (autoSend) {
2879 // Skip all further checks during autosend. This flow is used by Android Wear
2880 // and Google Now.
2881 sendOrSave(save, showToast);
2882 return;
2883 }
2884
2885 // Show a warning before sending only if there are no attachments, body, or subject.
Mindy Pereira181df782012-03-01 13:32:44 -08002886 if (mAttachmentsView.getAttachments().isEmpty() && showEmptyTextWarnings()) {
2887 boolean warnAboutEmptySubject = isSubjectEmpty();
Tony Mantler2558b502013-07-09 10:53:34 -07002888 boolean emptyBody = TextUtils.getTrimmedLength(mBodyView.getEditableText()) == 0;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002889
Mindy Pereira181df782012-03-01 13:32:44 -08002890 // A warning about an empty body may not be warranted when
2891 // forwarding mails, since a common use case is to forward
2892 // quoted text and not append any more text.
2893 boolean warnAboutEmptyBody = emptyBody && (!mForward || isBodyEmpty());
Mindy Pereira82cc5662012-01-09 17:29:30 -08002894
Mindy Pereira181df782012-03-01 13:32:44 -08002895 // When we bring up a dialog warning the user about a send,
2896 // assume that they accept sending the message. If they do not,
2897 // the dialog listener is required to enable sending again.
2898 if (warnAboutEmptySubject) {
Tony Mantler581edd42014-02-18 15:41:22 -08002899 showSendConfirmDialog(R.string.confirm_send_message_with_no_subject,
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002900 showToast, recipients);
2901 return;
Mindy Pereira181df782012-03-01 13:32:44 -08002902 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002903
Mindy Pereira181df782012-03-01 13:32:44 -08002904 if (warnAboutEmptyBody) {
Tony Mantler581edd42014-02-18 15:41:22 -08002905 showSendConfirmDialog(R.string.confirm_send_message_with_no_body,
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002906 showToast, recipients);
2907 return;
Mindy Pereira181df782012-03-01 13:32:44 -08002908 }
2909 }
Alan Lau3d519042014-06-05 11:13:06 -07002910 // Ask for confirmation to send.
2911 if (showSendConfirmation()) {
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002912 showSendConfirmDialog(R.string.confirm_send_message, showToast, recipients);
2913 return;
Mindy Pereira181df782012-03-01 13:32:44 -08002914 }
2915 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002916
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002917 performAdditionalSendOrSaveSanityChecks(save, showToast, recipients);
Mindy Pereira181df782012-03-01 13:32:44 -08002918 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002919
Mindy Pereira181df782012-03-01 13:32:44 -08002920 /**
2921 * Returns a boolean indicating whether warnings should be shown for empty
2922 * subject and body fields
Andy Huang5c5fd572012-04-08 18:19:29 -07002923 *
Mindy Pereira181df782012-03-01 13:32:44 -08002924 * @return True if a warning should be shown for empty text fields
2925 */
2926 protected boolean showEmptyTextWarnings() {
2927 return mAttachmentsView.getAttachments().size() == 0;
2928 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002929
Mindy Pereira181df782012-03-01 13:32:44 -08002930 /**
2931 * Returns a boolean indicating whether the user should confirm each send
2932 *
2933 * @return True if a warning should be on each send
2934 */
2935 protected boolean showSendConfirmation() {
Tony Mantler581edd42014-02-18 15:41:22 -08002936 return mCachedSettings != null && mCachedSettings.confirmSend;
Mindy Pereira181df782012-03-01 13:32:44 -08002937 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002938
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07002939 public static class SendConfirmDialogFragment extends DialogFragment
2940 implements DialogInterface.OnClickListener {
2941
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002942 private static final String MESSAGE_ID = "messageId";
2943 private static final String SHOW_TOAST = "showToast";
2944 private static final String RECIPIENTS = "recipients";
2945
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07002946 private boolean mShowToast;
2947
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002948 private ArrayList<String> mRecipients;
2949
Paul Westbrookf0ea4842013-08-13 16:41:18 -07002950 // Public no-args constructor needed for fragment re-instantiation
2951 public SendConfirmDialogFragment() {}
2952
Tony Mantler2558b502013-07-09 10:53:34 -07002953 public static SendConfirmDialogFragment newInstance(final int messageId,
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002954 final boolean showToast, final ArrayList<String> recipients) {
Tony Mantler2558b502013-07-09 10:53:34 -07002955 final SendConfirmDialogFragment frag = new SendConfirmDialogFragment();
2956 final Bundle args = new Bundle(3);
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002957 args.putInt(MESSAGE_ID, messageId);
2958 args.putBoolean(SHOW_TOAST, showToast);
2959 args.putStringArrayList(RECIPIENTS, recipients);
Tony Mantler2558b502013-07-09 10:53:34 -07002960 frag.setArguments(args);
2961 return frag;
Mindy Pereira181df782012-03-01 13:32:44 -08002962 }
Tony Mantler2558b502013-07-09 10:53:34 -07002963
2964 @Override
2965 public Dialog onCreateDialog(Bundle savedInstanceState) {
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002966 final int messageId = getArguments().getInt(MESSAGE_ID);
2967 mShowToast = getArguments().getBoolean(SHOW_TOAST);
2968 mRecipients = getArguments().getStringArrayList(RECIPIENTS);
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07002969
2970 final int confirmTextId = (messageId == R.string.confirm_send_message) ?
2971 R.string.ok : R.string.send;
Tony Mantler2558b502013-07-09 10:53:34 -07002972
2973 return new AlertDialog.Builder(getActivity())
2974 .setMessage(messageId)
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07002975 .setPositiveButton(confirmTextId, this)
Paul Westbrook7d1c5c42013-10-01 23:40:04 -07002976 .setNegativeButton(R.string.cancel, null)
Tony Mantler2558b502013-07-09 10:53:34 -07002977 .create();
2978 }
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07002979
2980 @Override
2981 public void onClick(DialogInterface dialog, int which) {
2982 if (which == DialogInterface.BUTTON_POSITIVE) {
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002983 ((ComposeActivity) getActivity()).finishSendConfirmDialog(mShowToast, mRecipients);
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07002984 }
2985 }
Tony Mantler2558b502013-07-09 10:53:34 -07002986 }
2987
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002988 private void finishSendConfirmDialog(
2989 final boolean showToast, final ArrayList<String> recipients) {
2990 performAdditionalSendOrSaveSanityChecks(false /* save */, showToast, recipients);
Tony Mantler2558b502013-07-09 10:53:34 -07002991 }
2992
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002993 // The list of recipients are used by the additional sendOrSave checks.
2994 // However, the send confirm dialog may be shown before performing
2995 // the additional checks. As a result, we need to plumb the recipient
2996 // list through the send confirm dialog so that
2997 // performAdditionalSendOrSaveChecks can be performed properly.
Tony Mantler581edd42014-02-18 15:41:22 -08002998 private void showSendConfirmDialog(final int messageId,
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07002999 final boolean showToast, final ArrayList<String> recipients) {
3000 final DialogFragment frag = SendConfirmDialogFragment.newInstance(
3001 messageId, showToast, recipients);
Tony Mantler2558b502013-07-09 10:53:34 -07003002 frag.show(getFragmentManager(), "send confirm");
Mindy Pereira181df782012-03-01 13:32:44 -08003003 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003004
Mindy Pereira181df782012-03-01 13:32:44 -08003005 /**
3006 * Returns whether the ComposeArea believes there is any text in the body of
3007 * the composition. TODO: When ComposeArea controls the Body as well, add
3008 * that here.
3009 */
3010 public boolean isBodyEmpty() {
3011 return !mQuotedTextView.isTextIncluded();
3012 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003013
Mindy Pereira181df782012-03-01 13:32:44 -08003014 /**
3015 * Test to see if the subject is empty.
3016 *
3017 * @return boolean.
3018 */
3019 // TODO: this will likely go away when composeArea.focus() is implemented
3020 // after all the widget control is moved over.
3021 public boolean isSubjectEmpty() {
3022 return TextUtils.getTrimmedLength(mSubject.getText()) == 0;
3023 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003024
Andy Huang0a2a3462013-12-20 15:56:13 -08003025 @VisibleForTesting
3026 public String getSubject() {
3027 return mSubject.getText().toString();
3028 }
3029
Andy Huang91ede362014-01-21 19:16:00 -08003030 private int sendOrSaveInternal(Context context, ReplyFromAccount replyFromAccount,
Jin Cao77b4c2c2014-05-20 13:55:53 -07003031 Message message, final Message refMessage, final CharSequence quotedText,
mindyp44a63392012-11-05 12:05:16 -08003032 SendOrSaveCallback callback, Handler handler, boolean save, int composeMode,
Scott Kennedy60847252013-08-15 15:55:42 -07003033 ReplyFromAccount draftAccount, final ContentValues extraValues) {
Paul Westbrookb4931c62013-01-14 17:51:18 -08003034 final ContentValues values = new ContentValues();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003035
Paul Westbrookb4931c62013-01-14 17:51:18 -08003036 final String refMessageId = refMessage != null ? refMessage.uri.toString() : "";
Mindy Pereirac2031972012-04-03 09:38:35 -07003037
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07003038 MessageModification.putToAddresses(values, message.getToAddresses());
3039 MessageModification.putCcAddresses(values, message.getCcAddresses());
3040 MessageModification.putBccAddresses(values, message.getBccAddresses());
Scott Kennedy8960f0a2012-11-07 15:35:50 -08003041 MessageModification.putCustomFromAddress(values, message.getFrom());
Mindy Pereira92551d02012-04-05 11:31:12 -07003042
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07003043 MessageModification.putSubject(values, message.subject);
Anthony Lee2a3cc132014-04-22 14:15:25 -07003044
Jin Cao77b4c2c2014-05-20 13:55:53 -07003045 // bodyHtml already have the composing spans removed.
3046 final String htmlBody = message.bodyHtml;
Anthony Lee2a3cc132014-04-22 14:15:25 -07003047 final String textBody = Utils.convertHtmlToPlainText(htmlBody);
3048 // fullbody will contain the actual body plus the quoted text.
3049 final String fullBody;
3050 final String quotedString;
3051 final boolean hasQuotedText = !TextUtils.isEmpty(quotedText);
3052 if (hasQuotedText) {
3053 // The quoted text is HTML at this point.
3054 quotedString = quotedText.toString();
3055 fullBody = htmlBody + quotedString;
3056 MessageModification.putForward(values, composeMode == ComposeActivity.FORWARD);
3057 MessageModification.putAppendRefMessageContent(values, true /* include quoted */);
3058 } else {
3059 fullBody = htmlBody;
3060 quotedString = null;
Mindy Pereira29ef1b82012-01-13 11:26:21 -08003061 }
Mindy Pereirac6f1e2a2012-04-04 10:33:45 -07003062 if (refMessage != null) {
Anthony Lee2a3cc132014-04-22 14:15:25 -07003063 // The code below might need to be revisited. The quoted text position is different
3064 // between text/html and text/plain parts and they should be stored seperately and
3065 // the right version should be used in the UI. text/html should have preference
3066 // if both exist. Issues like this made me file b/14256940 to make sure that we
3067 // properly handle the existing of both text/html and text/plain parts and to verify
3068 // that we are not making some assumptions that break if there is no text/html part.
3069 int quotedTextPos = -1;
Mindy Pereirac6f1e2a2012-04-04 10:33:45 -07003070 if (!TextUtils.isEmpty(refMessage.bodyHtml)) {
3071 MessageModification.putBodyHtml(values, fullBody.toString());
Anthony Lee2a3cc132014-04-22 14:15:25 -07003072 if (hasQuotedText) {
3073 quotedTextPos = htmlBody.length() +
3074 QuotedTextView.getQuotedTextOffset(quotedString);
3075 }
Mindy Pereirac6f1e2a2012-04-04 10:33:45 -07003076 }
3077 if (!TextUtils.isEmpty(refMessage.bodyText)) {
mindypc59dd822012-11-13 10:56:21 -08003078 MessageModification.putBody(values,
Tony Mantler581edd42014-02-18 15:41:22 -08003079 Utils.convertHtmlToPlainText(fullBody.toString()));
Anthony Lee2a3cc132014-04-22 14:15:25 -07003080 if (hasQuotedText && (quotedTextPos == -1)) {
3081 quotedTextPos = textBody.length();
3082 }
3083 }
3084 if (quotedTextPos != -1) {
3085 // The quoted text pos is the text/html version first and the text/plan version
3086 // if there is no text/html part. The reason for this is because preference
3087 // is given to text/html in the compose window if it exists. In the future, we
3088 // should calculate the index for both since the user could choose to compose
3089 // explicitly in text/plain.
3090 MessageModification.putQuoteStartPos(values, quotedTextPos);
Mindy Pereirac6f1e2a2012-04-04 10:33:45 -07003091 }
3092 } else {
Mindy Pereirac2031972012-04-03 09:38:35 -07003093 MessageModification.putBodyHtml(values, fullBody.toString());
Tony Mantler581edd42014-02-18 15:41:22 -08003094 MessageModification.putBody(values, Utils.convertHtmlToPlainText(fullBody.toString()));
Mindy Pereirac2031972012-04-03 09:38:35 -07003095 }
Anthony Lee2a3cc132014-04-22 14:15:25 -07003096 int draftType = getDraftType(composeMode);
3097 MessageModification.putDraftType(values, draftType);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07003098 MessageModification.putAttachments(values, message.getAttachments());
Mindy Pereira12575862012-03-21 16:30:54 -07003099 if (!TextUtils.isEmpty(refMessageId)) {
3100 MessageModification.putRefMessageId(values, refMessageId);
3101 }
Scott Kennedy60847252013-08-15 15:55:42 -07003102 if (extraValues != null) {
3103 values.putAll(extraValues);
3104 }
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07003105 SendOrSaveMessage sendOrSaveMessage = new SendOrSaveMessage(context, replyFromAccount,
3106 values, refMessageId, message.getAttachments(), save);
mindyp44a63392012-11-05 12:05:16 -08003107 SendOrSaveTask sendOrSaveTask = new SendOrSaveTask(context, sendOrSaveMessage, callback,
3108 draftAccount);
Mindy Pereira82cc5662012-01-09 17:29:30 -08003109
Mindy Pereira181df782012-03-01 13:32:44 -08003110 callback.initializeSendOrSave(sendOrSaveTask);
Mindy Pereira181df782012-03-01 13:32:44 -08003111 // Do the send/save action on the specified handler to avoid possible
3112 // ANRs
3113 handler.post(sendOrSaveTask);
Mindy Pereira82cc5662012-01-09 17:29:30 -08003114
Mindy Pereira181df782012-03-01 13:32:44 -08003115 return sendOrSaveMessage.requestId();
3116 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003117
Paul Westbrookb4931c62013-01-14 17:51:18 -08003118 /**
3119 * Removes any composing spans from the specified string. This will create a new
3120 * SpannableString instance, as to not modify the behavior of the EditText view.
3121 */
3122 private static SpannableString removeComposingSpans(Spanned body) {
3123 final SpannableString messageBody = new SpannableString(body);
3124 BaseInputConnection.removeComposingSpans(messageBody);
3125 return messageBody;
3126 }
3127
Mindy Pereira002ff522012-05-30 10:31:26 -07003128 private static int getDraftType(int mode) {
3129 int draftType = -1;
3130 switch (mode) {
3131 case ComposeActivity.COMPOSE:
3132 draftType = DraftType.COMPOSE;
3133 break;
3134 case ComposeActivity.REPLY:
3135 draftType = DraftType.REPLY;
3136 break;
3137 case ComposeActivity.REPLY_ALL:
3138 draftType = DraftType.REPLY_ALL;
3139 break;
3140 case ComposeActivity.FORWARD:
3141 draftType = DraftType.FORWARD;
3142 break;
3143 }
3144 return draftType;
3145 }
3146
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003147 /**
3148 * Derived classes should override this step to perform additional checks before
3149 * send or save. The default implementation simply calls {@link #sendOrSave(boolean, boolean)}.
3150 */
3151 protected void performAdditionalSendOrSaveSanityChecks(
3152 final boolean save, final boolean showToast, ArrayList<String> recipients) {
3153 sendOrSave(save, showToast);
3154 }
3155
3156 protected void sendOrSave(final boolean save, final boolean showToast) {
Mindy Pereira181df782012-03-01 13:32:44 -08003157 // Check if user is a monkey. Monkeys can compose and hit send
3158 // button but are not allowed to send anything off the device.
Paul Westbrook3ae824c2012-04-06 13:29:39 -07003159 if (ActivityManager.isUserAMonkey()) {
Mindy Pereira181df782012-03-01 13:32:44 -08003160 return;
3161 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003162
Jin Cao77b4c2c2014-05-20 13:55:53 -07003163 final SendOrSaveCallback callback = new SendOrSaveCallback() {
Andy Huang1f8f4dd2012-10-25 21:35:35 -07003164 // FIXME: unused
Mindy Pereira82cc5662012-01-09 17:29:30 -08003165 private int mRestoredRequestId;
3166
Marc Blank0bbc8582012-04-23 15:07:57 -07003167 @Override
Mindy Pereira82cc5662012-01-09 17:29:30 -08003168 public void initializeSendOrSave(SendOrSaveTask sendOrSaveTask) {
Mindy Pereira181df782012-03-01 13:32:44 -08003169 synchronized (mActiveTasks) {
3170 int numTasks = mActiveTasks.size();
3171 if (numTasks == 0) {
3172 // Start service so we won't be killed if this app is
3173 // put in the background.
3174 startService(new Intent(ComposeActivity.this, EmptyService.class));
3175 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003176
Mindy Pereira181df782012-03-01 13:32:44 -08003177 mActiveTasks.add(sendOrSaveTask);
3178 }
3179 if (sTestSendOrSaveCallback != null) {
3180 sTestSendOrSaveCallback.initializeSendOrSave(sendOrSaveTask);
3181 }
3182 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003183
Marc Blank0bbc8582012-04-23 15:07:57 -07003184 @Override
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003185 public void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage,
3186 Message message) {
Mindy Pereira181df782012-03-01 13:32:44 -08003187 synchronized (mDraftLock) {
mindyp44a63392012-11-05 12:05:16 -08003188 mDraftAccount = sendOrSaveMessage.mAccount;
Mindy Pereira181df782012-03-01 13:32:44 -08003189 mDraftId = message.id;
3190 mDraft = message;
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003191 if (sRequestMessageIdMap != null) {
3192 sRequestMessageIdMap.put(sendOrSaveMessage.requestId(), mDraftId);
3193 }
Mindy Pereira181df782012-03-01 13:32:44 -08003194 // Cache request message map, in case the process is killed
3195 saveRequestMap();
3196 }
3197 if (sTestSendOrSaveCallback != null) {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003198 sTestSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage, message);
Mindy Pereira181df782012-03-01 13:32:44 -08003199 }
3200 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003201
Marc Blank0bbc8582012-04-23 15:07:57 -07003202 @Override
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003203 public Message getMessage() {
3204 synchronized (mDraftLock) {
3205 return mDraft;
3206 }
3207 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003208
Marc Blank0bbc8582012-04-23 15:07:57 -07003209 @Override
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003210 public void sendOrSaveFinished(SendOrSaveTask task, boolean success) {
Mindy Pereira47d0e652012-07-23 09:45:07 -07003211 // Update the last sent from account.
3212 if (mAccount != null) {
3213 MailAppProvider.getInstance().setLastSentFromAccount(mAccount.uri.toString());
3214 }
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003215 if (success) {
3216 // Successfully sent or saved so reset change markers
3217 discardChanges();
3218 } else {
3219 // A failure happened with saving/sending the draft
3220 // TODO(pwestbro): add a better string that should be used
3221 // when failing to send or save
3222 Toast.makeText(ComposeActivity.this, R.string.send_failed, Toast.LENGTH_SHORT)
3223 .show();
3224 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003225
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003226 int numTasks;
3227 synchronized (mActiveTasks) {
3228 // Remove the task from the list of active tasks
3229 mActiveTasks.remove(task);
3230 numTasks = mActiveTasks.size();
3231 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003232
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003233 if (numTasks == 0) {
3234 // Stop service so we can be killed.
3235 stopService(new Intent(ComposeActivity.this, EmptyService.class));
3236 }
3237 if (sTestSendOrSaveCallback != null) {
3238 sTestSendOrSaveCallback.sendOrSaveFinished(task, success);
3239 }
3240 }
Andrew Sappersteinf5ab8ac2014-05-02 15:14:54 -07003241
3242 @Override
3243 public void incrementRecipientsTimesContacted(final List<String> recipients) {
3244 ComposeActivity.this.incrementRecipientsTimesContacted(recipients);
3245 }
Mindy Pereira181df782012-03-01 13:32:44 -08003246 };
Tony Mantler1e05a1e2013-08-12 16:44:26 -07003247 setAccount(mReplyFromAccount.account);
Mindy Pereira82cc5662012-01-09 17:29:30 -08003248
Jin Cao77b4c2c2014-05-20 13:55:53 -07003249 final Spanned body = removeComposingSpans(mBodyView.getText());
3250 SEND_SAVE_TASK_HANDLER.post(new Runnable() {
3251 @Override
3252 public void run() {
3253 final Message msg = createMessage(mReplyFromAccount, mRefMessage, getMode(), body);
3254 mRequestId = sendOrSaveInternal(ComposeActivity.this, mReplyFromAccount, msg,
3255 mRefMessage, mQuotedTextView.getQuotedTextIfIncluded(), callback,
3256 SEND_SAVE_TASK_HANDLER, save, mComposeMode, mDraftAccount, mExtraValues);
3257 }
3258 });
Mindy Pereira82cc5662012-01-09 17:29:30 -08003259
Mindy Pereira181df782012-03-01 13:32:44 -08003260 // Don't display the toast if the user is just changing the orientation,
3261 // but we still need to save the draft to the cursor because this is how we restore
3262 // the attachments when the configuration change completes.
3263 if (showToast && (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) {
3264 Toast.makeText(this, save ? R.string.message_saved : R.string.sending_message,
3265 Toast.LENGTH_LONG).show();
3266 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003267
Mindy Pereira181df782012-03-01 13:32:44 -08003268 // Need to update variables here because the send or save completes
3269 // asynchronously even though the toast shows right away.
3270 discardChanges();
3271 updateSaveUi();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003272
Mindy Pereira181df782012-03-01 13:32:44 -08003273 // If we are sending, finish the activity
3274 if (!save) {
3275 finish();
3276 }
3277 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003278
Mindy Pereira181df782012-03-01 13:32:44 -08003279 /**
3280 * Save the state of the request messageid map. This allows for the Gmail
3281 * process to be killed, but and still allow for ComposeActivity instances
3282 * to be recreated correctly.
3283 */
3284 private void saveRequestMap() {
3285 // TODO: store the request map in user preferences.
3286 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003287
Tony Mantler581edd42014-02-18 15:41:22 -08003288 @SuppressLint("NewApi")
Mindy Pereira2db7d4a2012-08-15 11:00:02 -07003289 private void doAttach(String type) {
Mindy Pereira013194c2012-01-06 15:09:33 -08003290 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
3291 i.addCategory(Intent.CATEGORY_OPENABLE);
Paul Westbrookd6a9a3f2012-04-26 18:47:23 -07003292 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
Andrew Sapperstein05089f32013-10-01 17:00:03 -07003293 i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
Mindy Pereira2db7d4a2012-08-15 11:00:02 -07003294 i.setType(type);
Mindy Pereira013194c2012-01-06 15:09:33 -08003295 mAddingAttachment = true;
Mindy Pereira181df782012-03-01 13:32:44 -08003296 startActivityForResult(Intent.createChooser(i, getText(R.string.select_attachment_type)),
3297 RESULT_PICK_ATTACHMENT);
Mindy Pereira013194c2012-01-06 15:09:33 -08003298 }
3299
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08003300 private void showCcBccViews() {
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08003301 mCcBccView.show(true, true, true);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08003302 if (mCcBccButton != null) {
mindypcd0b0b92012-08-23 14:33:17 -07003303 mCcBccButton.setVisibility(View.INVISIBLE);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08003304 }
3305 }
3306
Andy Huang4fe0af82013-08-20 17:24:51 -07003307 private static String getActionString(int action) {
Andy Huangdc97bf42013-08-15 16:52:45 -07003308 final String msgType;
Andy Huang4fe0af82013-08-20 17:24:51 -07003309 switch (action) {
Andy Huangdc97bf42013-08-15 16:52:45 -07003310 case COMPOSE:
3311 msgType = "new_message";
3312 break;
3313 case REPLY:
3314 msgType = "reply";
3315 break;
3316 case REPLY_ALL:
3317 msgType = "reply_all";
3318 break;
3319 case FORWARD:
3320 msgType = "forward";
3321 break;
3322 default:
3323 msgType = "unknown";
3324 break;
3325 }
Andy Huang4fe0af82013-08-20 17:24:51 -07003326 return msgType;
3327 }
3328
3329 private void logSendOrSave(boolean save) {
3330 if (!Analytics.isLoggable() || mAttachmentsView == null) {
3331 return;
3332 }
3333
3334 final String category = (save) ? "message_save" : "message_send";
3335 final int attachmentCount = getAttachments().size();
3336 final String msgType = getActionString(mComposeMode);
Andy Huangdc97bf42013-08-15 16:52:45 -07003337 final String label;
3338 final long value;
3339 if (mComposeMode == COMPOSE) {
3340 label = Integer.toString(attachmentCount);
3341 value = attachmentCount;
3342 } else {
3343 label = null;
3344 value = 0;
3345 }
3346 Analytics.getInstance().sendEvent(category, msgType, label, value);
3347 }
3348
Mindy Pereira326c6602012-01-04 15:32:42 -08003349 @Override
3350 public boolean onNavigationItemSelected(int position, long itemId) {
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08003351 int initialComposeMode = mComposeMode;
Mindy Pereira326c6602012-01-04 15:32:42 -08003352 if (position == ComposeActivity.REPLY) {
3353 mComposeMode = ComposeActivity.REPLY;
3354 } else if (position == ComposeActivity.REPLY_ALL) {
3355 mComposeMode = ComposeActivity.REPLY_ALL;
3356 } else if (position == ComposeActivity.FORWARD) {
3357 mComposeMode = ComposeActivity.FORWARD;
3358 }
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07003359 clearChangeListeners();
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08003360 if (initialComposeMode != mComposeMode) {
Mindy Pereira154386a2012-01-11 13:02:33 -08003361 resetMessageForModeChange();
mindyp68c0bfc2012-12-04 10:29:48 -08003362 if (mRefMessage != null) {
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08003363 setFieldsFromRefMessage(mComposeMode);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07003364 }
Mindy Pereiraef388302012-06-18 19:07:44 -07003365 boolean showCc = false;
3366 boolean showBcc = false;
3367 if (mDraft != null) {
3368 // Following desktop behavior, if the user has added a BCC
3369 // field to a draft, we show it regardless of compose mode.
Scott Kennedy8960f0a2012-11-07 15:35:50 -08003370 showBcc = !TextUtils.isEmpty(mDraft.getBcc());
Mindy Pereiraef388302012-06-18 19:07:44 -07003371 // Use the draft to determine what to populate.
3372 // If the Bcc field is showing, show the Cc field whether it is populated or not.
Scott Kennedy8960f0a2012-11-07 15:35:50 -08003373 showCc = showBcc
3374 || (!TextUtils.isEmpty(mDraft.getCc()) && mComposeMode == REPLY_ALL);
mindyp68c0bfc2012-12-04 10:29:48 -08003375 }
3376 if (mRefMessage != null) {
mindyp9b1ac572012-09-27 14:12:00 -07003377 showCc = !TextUtils.isEmpty(mCc.getText());
mindyp68c0bfc2012-12-04 10:29:48 -08003378 showBcc = !TextUtils.isEmpty(mBcc.getText());
Mindy Pereiraef388302012-06-18 19:07:44 -07003379 }
3380 mCcBccView.show(false, showCc, showBcc);
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08003381 }
Mindy Pereiraef388302012-06-18 19:07:44 -07003382 updateHideOrShowCcBcc();
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07003383 initChangeListeners();
Mindy Pereira326c6602012-01-04 15:32:42 -08003384 return true;
3385 }
3386
Mindy Pereirab3112a22012-06-20 12:10:03 -07003387 @VisibleForTesting
3388 protected void resetMessageForModeChange() {
Mindy Pereira154386a2012-01-11 13:02:33 -08003389 // When switching between reply, reply all, forward,
3390 // follow the behavior of webview.
3391 // The contents of the following fields are cleared
3392 // so that they can be populated directly from the
3393 // ref message:
3394 // 1) Any recipient fields
3395 // 2) The subject
3396 mTo.setText("");
3397 mCc.setText("");
3398 mBcc.setText("");
3399 // Any edits to the subject are replaced with the original subject.
3400 mSubject.setText("");
3401
3402 // Any changes to the contents of the following fields are kept:
3403 // 1) Body
3404 // 2) Attachments
3405 // If the user made changes to attachments, keep their changes.
3406 if (!mAttachmentsChanged) {
3407 mAttachmentsView.deleteAllAttachments();
3408 }
3409 }
3410
Mindy Pereira326c6602012-01-04 15:32:42 -08003411 private class ComposeModeAdapter extends ArrayAdapter<String> {
3412
3413 private LayoutInflater mInflater;
3414
3415 public ComposeModeAdapter(Context context) {
3416 super(context, R.layout.compose_mode_item, R.id.mode, getResources()
3417 .getStringArray(R.array.compose_modes));
3418 }
3419
3420 private LayoutInflater getInflater() {
3421 if (mInflater == null) {
3422 mInflater = LayoutInflater.from(getContext());
3423 }
3424 return mInflater;
3425 }
3426
3427 @Override
3428 public View getView(int position, View convertView, ViewGroup parent) {
3429 if (convertView == null) {
3430 convertView = getInflater().inflate(R.layout.compose_mode_display_item, null);
3431 }
3432 ((TextView) convertView.findViewById(R.id.mode)).setText(getItem(position));
3433 return super.getView(position, convertView, parent);
3434 }
3435 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003436
3437 @Override
3438 public void onRespondInline(String text) {
3439 appendToBody(text, false);
mindyp40882432012-09-06 11:07:40 -07003440 mQuotedTextView.setUpperDividerVisible(false);
mindyp1623f9b2012-11-21 12:41:16 -08003441 mRespondedInline = true;
mindyp09dd3732012-12-17 08:37:52 -08003442 if (!mBodyView.hasFocus()) {
mindyp8654d4f2012-12-17 09:01:37 -08003443 mBodyView.requestFocus();
mindyp09dd3732012-12-17 08:37:52 -08003444 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003445 }
3446
3447 /**
3448 * Append text to the body of the message. If there is no existing body
3449 * text, just sets the body to text.
3450 *
Tony Mantler581edd42014-02-18 15:41:22 -08003451 * @param text Text to append
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003452 * @param withSignature True to append a signature.
3453 */
3454 public void appendToBody(CharSequence text, boolean withSignature) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003455 Editable bodyText = mBodyView.getEditableText();
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003456 if (bodyText != null && bodyText.length() > 0) {
3457 bodyText.append(text);
3458 } else {
3459 setBody(text, withSignature);
3460 }
3461 }
3462
3463 /**
3464 * Set the body of the message.
Mindy Pereirabdf7a402012-03-01 15:23:26 -08003465 *
Tony Mantler581edd42014-02-18 15:41:22 -08003466 * @param text text to set
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003467 * @param withSignature True to append a signature.
3468 */
3469 public void setBody(CharSequence text, boolean withSignature) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003470 mBodyView.setText(text);
Mindy Pereirabdf7a402012-03-01 15:23:26 -08003471 if (withSignature) {
3472 appendSignature();
3473 }
3474 }
3475
3476 private void appendSignature() {
Tony Mantler6a7ac782014-02-19 15:22:02 -08003477 final String newSignature = mCachedSettings != null ? mCachedSettings.signature : null;
3478 final int signaturePos = getSignatureStartPosition(mSignature, mBodyView.getText().toString());
mindyp27083062012-11-15 09:02:01 -08003479 if (!TextUtils.equals(newSignature, mSignature) || signaturePos < 0) {
Mindy Pereirab13917c2012-03-29 08:08:19 -07003480 mSignature = newSignature;
mindyp27083062012-11-15 09:02:01 -08003481 if (!TextUtils.isEmpty(mSignature)) {
Mindy Pereirab13917c2012-03-29 08:08:19 -07003482 // Appending a signature does not count as changing text.
3483 mBodyView.removeTextChangedListener(this);
3484 mBodyView.append(convertToPrintableSignature(mSignature));
3485 mBodyView.addTextChangedListener(this);
3486 }
Tony Mantler6a7ac782014-02-19 15:22:02 -08003487 resetBodySelection();
Mindy Pereirabdf7a402012-03-01 15:23:26 -08003488 }
3489 }
3490
3491 private String convertToPrintableSignature(String signature) {
3492 String signatureResource = getResources().getString(R.string.signature);
3493 if (signature == null) {
3494 signature = "";
3495 }
3496 return String.format(signatureResource, signature);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003497 }
Mindy Pereira1a95a572012-01-05 12:21:29 -08003498
Mindy Pereira5a85e2b2012-01-11 09:53:32 -08003499 @Override
3500 public void onAccountChanged() {
Mindy Pereira92551d02012-04-05 11:31:12 -07003501 mReplyFromAccount = mFromSpinner.getCurrentAccount();
3502 if (!mAccount.equals(mReplyFromAccount.account)) {
mindypf432dbc2012-11-12 16:00:44 -08003503 // Clear a signature, if there was one.
3504 mBodyView.removeTextChangedListener(this);
3505 String oldSignature = mSignature;
3506 String bodyText = getBody().getText().toString();
3507 if (!TextUtils.isEmpty(oldSignature)) {
3508 int pos = getSignatureStartPosition(oldSignature, bodyText);
3509 if (pos > -1) {
3510 mBodyView.setText(bodyText.substring(0, pos));
3511 }
3512 }
Paul Westbrookb1f573c2012-04-06 11:38:28 -07003513 setAccount(mReplyFromAccount.account);
mindypf432dbc2012-11-12 16:00:44 -08003514 mBodyView.addTextChangedListener(this);
Mindy Pereira181df782012-03-01 13:32:44 -08003515 // TODO: handle discarding attachments when switching accounts.
3516 // Only enable save for this draft if there is any other content
3517 // in the message.
3518 if (!isBlank()) {
3519 enableSave(true);
3520 }
3521 mReplyFromChanged = true;
3522 initRecipients();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003523 }
Mindy Pereira1a95a572012-01-05 12:21:29 -08003524 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003525
3526 public void enableSave(boolean enabled) {
3527 if (mSave != null) {
3528 mSave.setEnabled(enabled);
3529 }
3530 }
3531
Tony Mantler2558b502013-07-09 10:53:34 -07003532 public static class DiscardConfirmDialogFragment extends DialogFragment {
Paul Westbrookf0ea4842013-08-13 16:41:18 -07003533 // Public no-args constructor needed for fragment re-instantiation
3534 public DiscardConfirmDialogFragment() {}
3535
Tony Mantler2558b502013-07-09 10:53:34 -07003536 @Override
3537 public Dialog onCreateDialog(Bundle savedInstanceState) {
3538 return new AlertDialog.Builder(getActivity())
3539 .setMessage(R.string.confirm_discard_text)
3540 .setPositiveButton(R.string.discard,
3541 new DialogInterface.OnClickListener() {
3542 @Override
3543 public void onClick(DialogInterface dialog, int which) {
3544 ((ComposeActivity)getActivity()).doDiscardWithoutConfirmation();
3545 }
3546 })
Tony Mantler2b215b72013-07-31 10:20:46 -07003547 .setNegativeButton(R.string.cancel, null)
Tony Mantler2558b502013-07-09 10:53:34 -07003548 .create();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003549 }
3550 }
3551
Mindy Pereiraefe3d252012-03-01 14:20:44 -08003552 private void doDiscard() {
Tony Mantler2558b502013-07-09 10:53:34 -07003553 final DialogFragment frag = new DiscardConfirmDialogFragment();
3554 frag.show(getFragmentManager(), "discard confirm");
Mindy Pereiraefe3d252012-03-01 14:20:44 -08003555 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003556 /**
3557 * Effectively discard the current message.
3558 *
3559 * This method is either invoked from the menu or from the dialog
3560 * once the user has confirmed that they want to discard the message.
Mindy Pereira82cc5662012-01-09 17:29:30 -08003561 */
Tony Mantler2558b502013-07-09 10:53:34 -07003562 private void doDiscardWithoutConfirmation() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003563 synchronized (mDraftLock) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08003564 if (mDraftId != UIProvider.INVALID_MESSAGE_ID) {
3565 ContentValues values = new ContentValues();
Paul Westbrookb7050e62012-03-20 12:59:44 -07003566 values.put(BaseColumns._ID, mDraftId);
Marc Blank78ea8e22012-08-04 11:14:06 -07003567 if (!mAccount.expungeMessageUri.equals(Uri.EMPTY)) {
Mindy Pereiracfb7f332012-02-28 10:23:43 -08003568 getContentResolver().update(mAccount.expungeMessageUri, values, null, null);
3569 } else {
Marc Blank0bbc8582012-04-23 15:07:57 -07003570 getContentResolver().delete(mDraft.uri, null, null);
Mindy Pereiracfb7f332012-02-28 10:23:43 -08003571 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003572 // This is not strictly necessary (since we should not try to
3573 // save the draft after calling this) but it ensures that if we
3574 // do save again for some reason we make a new draft rather than
3575 // trying to resave an expunged draft.
3576 mDraftId = UIProvider.INVALID_MESSAGE_ID;
3577 }
3578 }
3579
Tony Mantler2558b502013-07-09 10:53:34 -07003580 // Display a toast to let the user know
3581 Toast.makeText(this, R.string.message_discarded, Toast.LENGTH_SHORT).show();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003582
3583 // This prevents the draft from being saved in onPause().
3584 discardChanges();
Andy Huangdc97bf42013-08-15 16:52:45 -07003585 mPerformedSendOrDiscard = true;
Mindy Pereira82cc5662012-01-09 17:29:30 -08003586 finish();
3587 }
3588
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003589 private void saveIfNeeded() {
3590 if (mAccount == null) {
3591 // We have not chosen an account yet so there's no way that we can save. This is ok,
3592 // though, since we are saving our state before AccountsActivity is activated. Thus, the
3593 // user has not interacted with us yet and there is no real state to save.
3594 return;
3595 }
3596
3597 if (shouldSave()) {
Mindy Pereira48e31b02012-05-30 13:12:24 -07003598 doSave(!mAddingAttachment /* show toast */);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003599 }
3600 }
3601
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003602 @Override
3603 public void onAttachmentDeleted() {
3604 mAttachmentsChanged = true;
mindyp40882432012-09-06 11:07:40 -07003605 // If we are showing any attachments, make sure we have an upper
3606 // divider.
3607 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003608 updateSaveUi();
3609 }
Mindy Pereira75f66632012-01-11 11:42:02 -08003610
mindyp40882432012-09-06 11:07:40 -07003611 @Override
3612 public void onAttachmentAdded() {
3613 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
3614 mAttachmentsView.focusLastAttachment();
3615 }
Mindy Pereira75f66632012-01-11 11:42:02 -08003616
3617 /**
3618 * This is called any time one of our text fields changes.
3619 */
Marc Blank0bbc8582012-04-23 15:07:57 -07003620 @Override
Mindy Pereira75f66632012-01-11 11:42:02 -08003621 public void afterTextChanged(Editable s) {
3622 mTextChanged = true;
3623 updateSaveUi();
3624 }
3625
3626 @Override
3627 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3628 // Do nothing.
3629 }
3630
Marc Blank0bbc8582012-04-23 15:07:57 -07003631 @Override
Mindy Pereira75f66632012-01-11 11:42:02 -08003632 public void onTextChanged(CharSequence s, int start, int before, int count) {
3633 // Do nothing.
3634 }
3635
3636
3637 // There is a big difference between the text associated with an address changing
3638 // to add the display name or to format properly and a recipient being added or deleted.
3639 // Make sure we only notify of changes when a recipient has been added or deleted.
3640 private class RecipientTextWatcher implements TextWatcher {
3641 private HashMap<String, Integer> mContent = new HashMap<String, Integer>();
3642
3643 private RecipientEditTextView mView;
3644
3645 private TextWatcher mListener;
3646
3647 public RecipientTextWatcher(RecipientEditTextView view, TextWatcher listener) {
3648 mView = view;
3649 mListener = listener;
3650 }
3651
3652 @Override
3653 public void afterTextChanged(Editable s) {
3654 if (hasChanged()) {
3655 mListener.afterTextChanged(s);
3656 }
3657 }
3658
3659 private boolean hasChanged() {
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003660 final ArrayList<String> currRecips = buildEmailAddressList(getAddressesFromList(mView));
3661 int totalCount = currRecips.size();
Mindy Pereira75f66632012-01-11 11:42:02 -08003662 int totalPrevCount = 0;
3663 for (Entry<String, Integer> entry : mContent.entrySet()) {
3664 totalPrevCount += entry.getValue();
3665 }
3666 if (totalCount != totalPrevCount) {
3667 return true;
3668 }
3669
3670 for (String recip : currRecips) {
3671 if (!mContent.containsKey(recip)) {
3672 return true;
3673 } else {
3674 int count = mContent.get(recip) - 1;
3675 if (count < 0) {
3676 return true;
3677 } else {
3678 mContent.put(recip, count);
3679 }
3680 }
3681 }
3682 return false;
3683 }
3684
Mindy Pereira75f66632012-01-11 11:42:02 -08003685 @Override
3686 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003687 final ArrayList<String> recips = buildEmailAddressList(getAddressesFromList(mView));
Mindy Pereira75f66632012-01-11 11:42:02 -08003688 for (String recip : recips) {
3689 if (!mContent.containsKey(recip)) {
3690 mContent.put(recip, 1);
3691 } else {
3692 mContent.put(recip, (mContent.get(recip)) + 1);
3693 }
3694 }
3695 }
3696
3697 @Override
3698 public void onTextChanged(CharSequence s, int start, int before, int count) {
3699 // Do nothing.
3700 }
3701 }
Mindy Pereirae011b1d2012-06-18 13:45:26 -07003702
Andrew Sapperstein1b7ad922014-05-28 11:23:33 -07003703 /**
3704 * Returns a list of email addresses from the recipients. List only contains
3705 * email addresses strips additional info like the recipient's name.
3706 */
3707 private static ArrayList<String> buildEmailAddressList(String[] recips) {
3708 // Tokenize them all and put them in the list.
3709 final ArrayList<String> recipAddresses = Lists.newArrayListWithCapacity(recips.length);
3710 for (int i = 0; i < recips.length; i++) {
3711 recipAddresses.add(Rfc822Tokenizer.tokenize(recips[i])[0].getAddress());
3712 }
3713 return recipAddresses;
3714 }
3715
Mindy Pereirae011b1d2012-06-18 13:45:26 -07003716 public static void registerTestSendOrSaveCallback(SendOrSaveCallback testCallback) {
3717 if (sTestSendOrSaveCallback != null && testCallback != null) {
3718 throw new IllegalStateException("Attempting to register more than one test callback");
3719 }
3720 sTestSendOrSaveCallback = testCallback;
3721 }
Mindy Pereirabddd6f32012-06-20 12:10:03 -07003722
3723 @VisibleForTesting
3724 protected ArrayList<Attachment> getAttachments() {
3725 return mAttachmentsView.getAttachments();
3726 }
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003727
3728 @Override
3729 public Loader<Cursor> onCreateLoader(int id, Bundle args) {
3730 switch (id) {
Alice Yanga990a712013-03-13 18:37:00 -07003731 case INIT_DRAFT_USING_REFERENCE_MESSAGE:
3732 return new CursorLoader(this, mRefMessageUri, UIProvider.MESSAGE_PROJECTION, null,
3733 null, null);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003734 case REFERENCE_MESSAGE_LOADER:
3735 return new CursorLoader(this, mRefMessageUri, UIProvider.MESSAGE_PROJECTION, null,
3736 null, null);
Mindy Pereirab199d172012-08-13 11:04:03 -07003737 case LOADER_ACCOUNT_CURSOR:
3738 return new CursorLoader(this, MailAppProvider.getAccountsUri(),
3739 UIProvider.ACCOUNTS_PROJECTION, null, null, null);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003740 }
3741 return null;
3742 }
3743
3744 @Override
3745 public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Mindy Pereirab199d172012-08-13 11:04:03 -07003746 int id = loader.getId();
3747 switch (id) {
Alice Yanga990a712013-03-13 18:37:00 -07003748 case INIT_DRAFT_USING_REFERENCE_MESSAGE:
Mindy Pereirab199d172012-08-13 11:04:03 -07003749 if (data != null && data.moveToFirst()) {
3750 mRefMessage = new Message(data);
Mindy Pereirab199d172012-08-13 11:04:03 -07003751 Intent intent = getIntent();
Alice Yanga990a712013-03-13 18:37:00 -07003752 initFromRefMessage(mComposeMode);
3753 finishSetup(mComposeMode, intent, null);
3754 if (mComposeMode != FORWARD) {
Mindy Pereirab199d172012-08-13 11:04:03 -07003755 String to = intent.getStringExtra(EXTRA_TO);
3756 if (!TextUtils.isEmpty(to)) {
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08003757 mRefMessage.setTo(null);
3758 mRefMessage.setFrom(null);
Mindy Pereirab199d172012-08-13 11:04:03 -07003759 clearChangeListeners();
3760 mTo.append(to);
3761 initChangeListeners();
3762 }
3763 }
3764 } else {
3765 finish();
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003766 }
Mindy Pereirab199d172012-08-13 11:04:03 -07003767 break;
Alice Yanga990a712013-03-13 18:37:00 -07003768 case REFERENCE_MESSAGE_LOADER:
3769 // Only populate mRefMessage and leave other fields untouched.
3770 if (data != null && data.moveToFirst()) {
3771 mRefMessage = new Message(data);
3772 }
Andy Huang9f855d62013-05-30 17:15:03 -07003773 finishSetup(mComposeMode, getIntent(), mInnerSavedState);
Alice Yanga990a712013-03-13 18:37:00 -07003774 break;
Mindy Pereirab199d172012-08-13 11:04:03 -07003775 case LOADER_ACCOUNT_CURSOR:
3776 if (data != null && data.moveToFirst()) {
3777 // there are accounts now!
3778 Account account;
Paul Westbrookfaa742f2012-11-01 09:50:16 -07003779 final ArrayList<Account> accounts = new ArrayList<Account>();
3780 final ArrayList<Account> initializedAccounts = new ArrayList<Account>();
Mindy Pereirab199d172012-08-13 11:04:03 -07003781 do {
3782 account = new Account(data);
Paul Westbrookdfa1dec2012-09-26 16:27:28 -07003783 if (account.isAccountReady()) {
Mindy Pereirab199d172012-08-13 11:04:03 -07003784 initializedAccounts.add(account);
3785 }
3786 accounts.add(account);
3787 } while (data.moveToNext());
3788 if (initializedAccounts.size() > 0) {
3789 findViewById(R.id.wait).setVisibility(View.GONE);
3790 getLoaderManager().destroyLoader(LOADER_ACCOUNT_CURSOR);
3791 findViewById(R.id.compose).setVisibility(View.VISIBLE);
Paul Westbrookfaa742f2012-11-01 09:50:16 -07003792 mAccounts = initializedAccounts.toArray(
3793 new Account[initializedAccounts.size()]);
3794
Mindy Pereirab199d172012-08-13 11:04:03 -07003795 finishCreate();
3796 invalidateOptionsMenu();
3797 } else {
3798 // Show "waiting"
3799 account = accounts.size() > 0 ? accounts.get(0) : null;
3800 showWaitFragment(account);
3801 }
3802 }
3803 break;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003804 }
3805 }
3806
Mindy Pereirab199d172012-08-13 11:04:03 -07003807 private void showWaitFragment(Account account) {
3808 WaitFragment fragment = getWaitFragment();
3809 if (fragment != null) {
3810 fragment.updateAccount(account);
3811 } else {
3812 findViewById(R.id.wait).setVisibility(View.VISIBLE);
Andy Huangc96efcc2014-04-09 15:30:42 -07003813 replaceFragment(WaitFragment.newInstance(account, false /* expectingMessages */),
Mindy Pereirab199d172012-08-13 11:04:03 -07003814 FragmentTransaction.TRANSIT_FRAGMENT_OPEN, TAG_WAIT);
3815 }
3816 }
3817
3818 private WaitFragment getWaitFragment() {
3819 return (WaitFragment) getFragmentManager().findFragmentByTag(TAG_WAIT);
3820 }
3821
3822 private int replaceFragment(Fragment fragment, int transition, String tag) {
3823 FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
Mindy Pereirab199d172012-08-13 11:04:03 -07003824 fragmentTransaction.setTransition(transition);
3825 fragmentTransaction.replace(R.id.wait, fragment, tag);
3826 final int transactionId = fragmentTransaction.commitAllowingStateLoss();
3827 return transactionId;
3828 }
3829
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003830 @Override
3831 public void onLoaderReset(Loader<Cursor> arg0) {
3832 // Do nothing.
3833 }
Jin Cao77b4c2c2014-05-20 13:55:53 -07003834
3835 /**
3836 * Background task to convert the message's html to Spanned.
3837 */
3838 private class HtmlToSpannedTask extends AsyncTask<String, Void, Spanned> {
3839
3840 @Override
3841 protected Spanned doInBackground(String... input) {
3842 return HtmlUtils.htmlToSpan(input[0]);
3843 }
3844
3845 @Override
3846 protected void onPostExecute(Spanned spanned) {
3847 mBodyView.removeTextChangedListener(ComposeActivity.this);
3848 mBodyView.setText(spanned);
3849 mTextChanged = false;
3850 mBodyView.addTextChangedListener(ComposeActivity.this);
3851 }
3852 }
Andy Huang1f8f4dd2012-10-25 21:35:35 -07003853}