blob: fd82c987033cc712ca1285b8e15706f10eec1fca [file] [log] [blame]
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001/**
2 * Copyright (c) 2011, Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Andy Huang30e2c242012-01-06 18:14:30 -080017package com.android.mail.compose;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080018
Mindy Pereira326c6602012-01-04 15:32:42 -080019import android.app.ActionBar;
Andy Huang5c5fd572012-04-08 18:19:29 -070020import android.app.ActionBar.OnNavigationListener;
21import android.app.Activity;
Mindy Pereira82cc5662012-01-09 17:29:30 -080022import android.app.ActivityManager;
23import android.app.AlertDialog;
24import android.app.Dialog;
Tony Mantler2558b502013-07-09 10:53:34 -070025import android.app.DialogFragment;
Mindy Pereirab199d172012-08-13 11:04:03 -070026import android.app.Fragment;
Mindy Pereirab199d172012-08-13 11:04:03 -070027import android.app.FragmentTransaction;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -070028import android.app.LoaderManager;
Andrew Sapperstein05089f32013-10-01 17:00:03 -070029import android.content.ClipData;
Mindy Pereira6349a042012-01-04 11:25:01 -080030import android.content.ContentResolver;
Mindy Pereira82cc5662012-01-09 17:29:30 -080031import android.content.ContentValues;
Mindy Pereira6349a042012-01-04 11:25:01 -080032import android.content.Context;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -070033import android.content.CursorLoader;
Mindy Pereira82cc5662012-01-09 17:29:30 -080034import android.content.DialogInterface;
Mindy Pereira6349a042012-01-04 11:25:01 -080035import android.content.Intent;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -070036import android.content.Loader;
Mindy Pereira82cc5662012-01-09 17:29:30 -080037import android.content.pm.ActivityInfo;
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -070038import android.content.res.Resources;
Mindy Pereira7ed1c112012-01-18 10:59:25 -080039import android.database.Cursor;
Mindy Pereira6349a042012-01-04 11:25:01 -080040import android.net.Uri;
Andrew Sapperstein05089f32013-10-01 17:00:03 -070041import android.os.Build;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080042import android.os.Bundle;
Mindy Pereira82cc5662012-01-09 17:29:30 -080043import android.os.Handler;
44import android.os.HandlerThread;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -070045import android.os.ParcelFileDescriptor;
Alice Yang1ebc2db2013-03-14 21:21:44 -070046import android.os.Parcelable;
Mindy Pereira82cc5662012-01-09 17:29:30 -080047import android.provider.BaseColumns;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080048import android.text.Editable;
Mindy Pereira82cc5662012-01-09 17:29:30 -080049import android.text.Html;
mindyped9c2f02012-10-12 10:02:08 -070050import android.text.SpannableString;
Mindy Pereira82cc5662012-01-09 17:29:30 -080051import android.text.Spanned;
Paul Westbrookc1827622012-01-06 11:27:12 -080052import android.text.TextUtils;
Mindy Pereira82cc5662012-01-09 17:29:30 -080053import android.text.TextWatcher;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080054import android.text.util.Rfc822Token;
Mindy Pereirac17d0732011-12-29 10:46:19 -080055import android.text.util.Rfc822Tokenizer;
Mindy Pereira3cd4f402012-07-17 11:16:18 -070056import android.view.Gravity;
mindyp62d3ec72012-08-24 13:04:09 -070057import android.view.KeyEvent;
Mindy Pereira326c6602012-01-04 15:32:42 -080058import android.view.LayoutInflater;
Mindy Pereirab47f3e22011-12-13 14:25:04 -080059import android.view.Menu;
60import android.view.MenuInflater;
61import android.view.MenuItem;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080062import android.view.View;
63import android.view.View.OnClickListener;
Andy Huang5c5fd572012-04-08 18:19:29 -070064import android.view.ViewGroup;
Paul Westbrookb4931c62013-01-14 17:51:18 -080065import android.view.inputmethod.BaseInputConnection;
mindyp62d3ec72012-08-24 13:04:09 -070066import android.view.inputmethod.EditorInfo;
Mindy Pereira326c6602012-01-04 15:32:42 -080067import android.widget.ArrayAdapter;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080068import android.widget.Button;
Mindy Pereira433b1982012-04-03 11:53:07 -070069import android.widget.EditText;
Mindy Pereira6349a042012-01-04 11:25:01 -080070import android.widget.TextView;
Mindy Pereira013194c2012-01-06 15:09:33 -080071import android.widget.Toast;
Mindy Pereira7b56a612011-12-14 12:32:28 -080072
Mindy Pereirac17d0732011-12-29 10:46:19 -080073import com.android.common.Rfc822Validator;
Tony Mantler9f324232013-08-08 14:24:30 -070074import com.android.common.contacts.DataUsageStatUpdater;
Tony Mantler821e5782014-01-06 15:33:43 -080075import com.android.emailcommon.mail.Address;
Andy Huang5c5fd572012-04-08 18:19:29 -070076import com.android.ex.chips.RecipientEditTextView;
Scott Kennedy5680ec22013-01-07 13:15:20 -080077import com.android.mail.MailIntentService;
Andy Huang5c5fd572012-04-08 18:19:29 -070078import com.android.mail.R;
Andy Huang761522c2013-08-08 13:09:11 -070079import com.android.mail.analytics.Analytics;
Alice Yang1ebc2db2013-03-14 21:21:44 -070080import com.android.mail.browse.MessageHeaderView;
mindyp40882432012-09-06 11:07:40 -070081import com.android.mail.compose.AttachmentsView.AttachmentAddedOrDeletedListener;
Mindy Pereira9932dee2012-01-10 16:09:50 -080082import com.android.mail.compose.AttachmentsView.AttachmentFailureException;
Mindy Pereira5a85e2b2012-01-11 09:53:32 -080083import com.android.mail.compose.FromAddressSpinner.OnAccountChangedListener;
Andy Huang30e2c242012-01-06 18:14:30 -080084import com.android.mail.compose.QuotedTextView.RespondInlineListener;
Mindy Pereira33fe9082012-01-09 16:24:30 -080085import com.android.mail.providers.Account;
Andy Huang30e2c242012-01-06 18:14:30 -080086import com.android.mail.providers.Attachment;
Scott Kennedy5680ec22013-01-07 13:15:20 -080087import com.android.mail.providers.Folder;
Mindy Pereira47d0e652012-07-23 09:45:07 -070088import com.android.mail.providers.MailAppProvider;
Mindy Pereira3ce64e72012-01-13 14:29:45 -080089import com.android.mail.providers.Message;
Mindy Pereira82cc5662012-01-09 17:29:30 -080090import com.android.mail.providers.MessageModification;
Mindy Pereira92551d02012-04-05 11:31:12 -070091import com.android.mail.providers.ReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -080092import com.android.mail.providers.Settings;
Andy Huang30e2c242012-01-06 18:14:30 -080093import com.android.mail.providers.UIProvider;
Mindy Pereira3ca5bad2012-04-16 11:02:42 -070094import com.android.mail.providers.UIProvider.AccountCapabilities;
Mindy Pereira12575862012-03-21 16:30:54 -070095import com.android.mail.providers.UIProvider.DraftType;
Alice Yang1ebc2db2013-03-14 21:21:44 -070096import com.android.mail.ui.AttachmentTile.AttachmentPreview;
Paul Westbrook83e6b572013-02-05 16:22:42 -080097import com.android.mail.ui.FeedbackEnabledActivity;
Mindy Pereirafa20c1a2012-07-23 13:00:02 -070098import com.android.mail.ui.MailActivity;
Mindy Pereirab199d172012-08-13 11:04:03 -070099import com.android.mail.ui.WaitFragment;
Paul Westbrook92227f62012-03-20 10:32:51 -0700100import com.android.mail.utils.AccountUtils;
Mark Wei434f2942012-08-24 11:54:02 -0700101import com.android.mail.utils.AttachmentUtils;
mindypfebd2262012-11-13 17:45:09 -0800102import com.android.mail.utils.ContentProviderTask;
Paul Westbrookb334c902012-06-25 11:42:46 -0700103import com.android.mail.utils.LogTag;
Andy Huang30e2c242012-01-06 18:14:30 -0800104import com.android.mail.utils.LogUtils;
Andy Huang30e2c242012-01-06 18:14:30 -0800105import com.android.mail.utils.Utils;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800106import com.google.common.annotations.VisibleForTesting;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800107import com.google.common.collect.Lists;
Mindy Pereira4a27ea92012-01-05 15:55:25 -0800108import com.google.common.collect.Sets;
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800109
Paul Westbrook3c7f94d2012-10-23 14:13:00 -0700110import java.io.FileNotFoundException;
111import java.io.IOException;
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700112import java.io.UnsupportedEncodingException;
113import java.net.URLDecoder;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800114import java.util.ArrayList;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700115import java.util.Arrays;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800116import java.util.Collection;
Mindy Pereira75f66632012-01-11 11:42:02 -0800117import java.util.HashMap;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800118import java.util.HashSet;
119import java.util.List;
Paul Westbrook1c078cf2012-03-20 16:18:51 -0700120import java.util.Map.Entry;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700121import java.util.Set;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800122import java.util.concurrent.ConcurrentHashMap;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800123
124public class ComposeActivity extends Activity implements OnClickListener, OnNavigationListener,
Tony Mantler2558b502013-07-09 10:53:34 -0700125 RespondInlineListener, TextWatcher,
Alice Yanga990a712013-03-13 18:37:00 -0700126 AttachmentAddedOrDeletedListener, OnAccountChangedListener,
127 LoaderManager.LoaderCallbacks<Cursor>, TextView.OnEditorActionListener,
128 FeedbackEnabledActivity {
Mindy Pereira6349a042012-01-04 11:25:01 -0800129 // Identifiers for which type of composition this is
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700130 public static final int COMPOSE = -1;
131 public static final int REPLY = 0;
132 public static final int REPLY_ALL = 1;
133 public static final int FORWARD = 2;
134 public static final int EDIT_DRAFT = 3;
Mindy Pereira6349a042012-01-04 11:25:01 -0800135
136 // Integer extra holding one of the above compose action
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700137 protected static final String EXTRA_ACTION = "action";
Mindy Pereira6349a042012-01-04 11:25:01 -0800138
Mindy Pereira326689d2012-05-17 10:14:14 -0700139 private static final String EXTRA_SHOW_CC = "showCc";
140 private static final String EXTRA_SHOW_BCC = "showBcc";
mindyp1623f9b2012-11-21 12:41:16 -0800141 private static final String EXTRA_RESPONDED_INLINE = "respondedInline";
mindyp1d7e9142012-11-21 13:54:30 -0800142 private static final String EXTRA_SAVE_ENABLED = "saveEnabled";
Mindy Pereiraa34c9a02012-04-17 14:10:53 -0700143
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700144 private static final String UTF8_ENCODING_NAME = "UTF-8";
145
146 private static final String MAIL_TO = "mailto";
147
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700148 private static final String EXTRA_SUBJECT = "subject";
149
150 private static final String EXTRA_BODY = "body";
151
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700152 /**
153 * Expected to be html formatted text.
154 */
155 private static final String EXTRA_QUOTED_TEXT = "quotedText";
156
mindypd27b6ea2012-10-05 09:43:49 -0700157 protected static final String EXTRA_FROM_ACCOUNT_STRING = "fromAccountString";
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700158
Mark Wei62066e42012-09-13 12:07:02 -0700159 private static final String EXTRA_ATTACHMENT_PREVIEWS = "attachmentPreviews";
160
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700161 // Extra that we can get passed from other activities
Tony Mantler184ec732013-10-24 13:13:49 -0700162 @VisibleForTesting
163 protected static final String EXTRA_TO = "to";
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700164 private static final String EXTRA_CC = "cc";
165 private static final String EXTRA_BCC = "bcc";
166
Scott Kennedy60847252013-08-15 15:55:42 -0700167 /**
168 * An optional extra containing a {@link ContentValues} of values to be added to
169 * {@link SendOrSaveMessage#mValues}.
170 */
171 public static final String EXTRA_VALUES = "extra-values";
172
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700173 // List of all the fields
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700174 static final String[] ALL_EXTRAS = { EXTRA_SUBJECT, EXTRA_BODY, EXTRA_TO, EXTRA_CC, EXTRA_BCC,
175 EXTRA_QUOTED_TEXT };
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700176
Mindy Pereira82cc5662012-01-09 17:29:30 -0800177 private static SendOrSaveCallback sTestSendOrSaveCallback = null;
178 // Map containing information about requests to create new messages, and the id of the
179 // messages that were the result of those requests.
180 //
181 // This map is used when the activity that initiated the save a of a new message, is killed
182 // before the save has completed (and when we know the id of the newly created message). When
183 // a save is completed, the service that is running in the background, will update the map
184 //
185 // When a new ComposeActivity instance is created, it will attempt to use the information in
186 // the previously instantiated map. If ComposeActivity.onCreate() is called, with a bundle
187 // (restoring data from a previous instance), and the map hasn't been created, we will attempt
188 // to populate the map with data stored in shared preferences.
Andy Huang1f8f4dd2012-10-25 21:35:35 -0700189 // FIXME: values in this map are never read.
Mindy Pereira82cc5662012-01-09 17:29:30 -0800190 private static ConcurrentHashMap<Integer, Long> sRequestMessageIdMap = null;
Mindy Pereira6349a042012-01-04 11:25:01 -0800191 /**
192 * Notifies the {@code Activity} that the caller is an Email
193 * {@code Activity}, so that the back behavior may be modified accordingly.
194 *
195 * @see #onAppUpPressed
196 */
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700197 public static final String EXTRA_FROM_EMAIL_TASK = "fromemail";
Mindy Pereira6349a042012-01-04 11:25:01 -0800198
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700199 public static final String EXTRA_ATTACHMENTS = "attachments";
Paul Westbrookf97588b2012-03-20 11:11:37 -0700200
Scott Kennedy5680ec22013-01-07 13:15:20 -0800201 /** If set, we will clear notifications for this folder. */
202 public static final String EXTRA_NOTIFICATION_FOLDER = "extra-notification-folder";
203
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800204 // If this is a reply/forward then this extra will hold the original message
Mindy Pereira36bbcae2012-04-25 09:27:04 -0700205 private static final String EXTRA_IN_REFERENCE_TO_MESSAGE = "in-reference-to-message";
Mindy Pereirab18e5a92012-07-10 11:47:21 -0700206 // If this is a reply/forward then this extra will hold a uri we must query
207 // to get the original message.
208 protected static final String EXTRA_IN_REFERENCE_TO_MESSAGE_URI = "in-reference-to-message-uri";
Mark Wei434f2942012-08-24 11:54:02 -0700209 // If this is an action to edit an existing draft message, this extra will hold the
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700210 // draft message
211 private static final String ORIGINAL_DRAFT_MESSAGE = "original-draft-message";
Mindy Pereira4a27ea92012-01-05 15:55:25 -0800212 private static final String END_TOKEN = ", ";
Paul Westbrookb334c902012-06-25 11:42:46 -0700213 private static final String LOG_TAG = LogTag.getLogTag();
Mindy Pereira013194c2012-01-06 15:09:33 -0800214 // Request numbers for activities we start
215 private static final int RESULT_PICK_ATTACHMENT = 1;
216 private static final int RESULT_CREATE_ACCOUNT = 2;
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700217 // TODO(mindyp) set mime-type for auto send?
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700218 public static final String AUTO_SEND_ACTION = "com.android.mail.action.AUTO_SEND";
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700219
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700220 private static final String EXTRA_SELECTED_REPLY_FROM_ACCOUNT = "replyFromAccount";
221 private static final String EXTRA_REQUEST_ID = "requestId";
222 private static final String EXTRA_FOCUS_SELECTION_START = "focusSelectionStart";
Paul Westbrook176a1992013-07-22 13:57:19 -0700223 private static final String EXTRA_FOCUS_SELECTION_END = "focusSelectionEnd";
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700224 private static final String EXTRA_MESSAGE = "extraMessage";
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700225 private static final int REFERENCE_MESSAGE_LOADER = 0;
Mindy Pereirab199d172012-08-13 11:04:03 -0700226 private static final int LOADER_ACCOUNT_CURSOR = 1;
Alice Yanga990a712013-03-13 18:37:00 -0700227 private static final int INIT_DRAFT_USING_REFERENCE_MESSAGE = 2;
Mindy Pereira47d0e652012-07-23 09:45:07 -0700228 private static final String EXTRA_SELECTED_ACCOUNT = "selectedAccount";
Mindy Pereirab199d172012-08-13 11:04:03 -0700229 private static final String TAG_WAIT = "wait-fragment";
Andrew Sapperstein5cb71802013-10-01 18:31:20 -0700230 private static final String MIME_TYPE_ALL = "*/*";
Mindy Pereira2db7d4a2012-08-15 11:00:02 -0700231 private static final String MIME_TYPE_PHOTO = "image/*";
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800232
Andy Huang9f855d62013-05-30 17:15:03 -0700233 private static final String KEY_INNER_SAVED_STATE = "compose_state";
234
Mindy Pereira82cc5662012-01-09 17:29:30 -0800235 /**
236 * A single thread for running tasks in the background.
237 */
238 private Handler mSendSaveTaskHandler = null;
Mindy Pereirac17d0732011-12-29 10:46:19 -0800239 private RecipientEditTextView mTo;
240 private RecipientEditTextView mCc;
241 private RecipientEditTextView mBcc;
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800242 private Button mCcBccButton;
243 private CcBccView mCcBccView;
Mindy Pereira7b56a612011-12-14 12:32:28 -0800244 private AttachmentsView mAttachmentsView;
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700245 protected Account mAccount;
Tony Mantler59e69092013-08-14 11:05:00 -0700246 protected ReplyFromAccount mReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -0800247 private Settings mCachedSettings;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800248 private Rfc822Validator mValidator;
Mindy Pereira6349a042012-01-04 11:25:01 -0800249 private TextView mSubject;
250
Mindy Pereira326c6602012-01-04 15:32:42 -0800251 private ComposeModeAdapter mComposeModeAdapter;
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700252 protected int mComposeMode = -1;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800253 private boolean mForward;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800254 private QuotedTextView mQuotedTextView;
Tony Mantler59e69092013-08-14 11:05:00 -0700255 protected EditText mBodyView;
Mindy Pereira1a95a572012-01-05 12:21:29 -0800256 private View mFromStatic;
Mindy Pereira2eb17322012-03-07 10:07:34 -0800257 private TextView mFromStaticText;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800258 private View mFromSpinnerWrapper;
Mindy Pereira1883b342012-06-20 08:34:56 -0700259 @VisibleForTesting
260 protected FromAddressSpinner mFromSpinner;
Mindy Pereira013194c2012-01-06 15:09:33 -0800261 private boolean mAddingAttachment;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800262 private boolean mAttachmentsChanged;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800263 private boolean mTextChanged;
264 private boolean mReplyFromChanged;
265 private MenuItem mSave;
Mindy Pereirab3112a22012-06-20 12:10:03 -0700266 @VisibleForTesting
267 protected Message mRefMessage;
Mindy Pereira7ed1c112012-01-18 10:59:25 -0800268 private long mDraftId = UIProvider.INVALID_MESSAGE_ID;
269 private Message mDraft;
mindyp44a63392012-11-05 12:05:16 -0800270 private ReplyFromAccount mDraftAccount;
Mindy Pereira7ed1c112012-01-18 10:59:25 -0800271 private Object mDraftLock = new Object();
Andrew Sapperstein6aea7862013-10-24 19:59:51 -0700272 private View mAddAttachmentsButton;
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800273
Mindy Pereira326c6602012-01-04 15:32:42 -0800274 /**
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700275 * Boolean indicating whether ComposeActivity was launched from a Gmail controlled view.
276 */
277 private boolean mLaunchedFromEmail = false;
Mindy Pereiracbfb75a2012-06-25 14:52:23 -0700278 private RecipientTextWatcher mToListener;
279 private RecipientTextWatcher mCcListener;
280 private RecipientTextWatcher mBccListener;
Mindy Pereirab18e5a92012-07-10 11:47:21 -0700281 private Uri mRefMessageUri;
Alice Yanga990a712013-03-13 18:37:00 -0700282 private boolean mShowQuotedText = false;
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700283 protected Bundle mInnerSavedState;
Scott Kennedy60847252013-08-15 15:55:42 -0700284 private ContentValues mExtraValues = null;
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700285
mindyp1623f9b2012-11-21 12:41:16 -0800286 // Array of the outstanding send or save tasks. Access is synchronized
287 // with the object itself
288 /* package for testing */
289 @VisibleForTesting
290 public ArrayList<SendOrSaveTask> mActiveTasks = Lists.newArrayList();
291 // FIXME: this variable is never read. related to sRequestMessageIdMap.
292 private int mRequestId;
293 private String mSignature;
294 private Account[] mAccounts;
295 private boolean mRespondedInline;
Andy Huangdc97bf42013-08-15 16:52:45 -0700296 private boolean mPerformedSendOrDiscard = false;
mindyp1623f9b2012-11-21 12:41:16 -0800297
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700298 /**
Mindy Pereira326c6602012-01-04 15:32:42 -0800299 * Can be called from a non-UI thread.
300 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800301 public static void editDraft(Context launcher, Account account, Message message) {
Scott Kennedy60847252013-08-15 15:55:42 -0700302 launch(launcher, account, message, EDIT_DRAFT, null, null, null, null,
303 null /* extraValues */);
Mindy Pereira326c6602012-01-04 15:32:42 -0800304 }
305
Mindy Pereira6349a042012-01-04 11:25:01 -0800306 /**
307 * Can be called from a non-UI thread.
308 */
Mindy Pereira33fe9082012-01-09 16:24:30 -0800309 public static void compose(Context launcher, Account account) {
Scott Kennedy60847252013-08-15 15:55:42 -0700310 launch(launcher, account, null, COMPOSE, null, null, null, null, null /* extraValues */);
Mindy Pereira6349a042012-01-04 11:25:01 -0800311 }
312
313 /**
314 * Can be called from a non-UI thread.
315 */
Andrew Sapperstein3de76ec2013-07-16 12:08:15 -0700316 public static void composeToAddress(Context launcher, Account account, String toAddress) {
Scott Kennedy60847252013-08-15 15:55:42 -0700317 launch(launcher, account, null, COMPOSE, toAddress, null, null, null,
318 null /* extraValues */);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700319 }
320
321 /**
322 * Can be called from a non-UI thread.
323 */
324 public static void composeWithQuotedText(Context launcher, Account account,
Scott Kennedy60847252013-08-15 15:55:42 -0700325 String quotedText, String subject, final ContentValues extraValues) {
326 launch(launcher, account, null, COMPOSE, null, null, quotedText, subject, extraValues);
Andrew Sapperstein3de76ec2013-07-16 12:08:15 -0700327 }
328
329 /**
330 * Can be called from a non-UI thread.
331 */
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700332 public static void composeWithExtraValues(Context launcher, Account account,
333 String subject, final ContentValues extraValues) {
334 launch(launcher, account, null, COMPOSE, null, null, null, subject, extraValues);
335 }
336
337 /**
338 * Can be called from a non-UI thread.
339 */
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -0800340 public static Intent createReplyIntent(final Context launcher, final Account account,
341 final Uri messageUri, final boolean isReplyAll) {
342 return createActionIntent(launcher, account, messageUri, isReplyAll ? REPLY_ALL : REPLY);
343 }
344
345 /**
346 * Can be called from a non-UI thread.
347 */
348 public static Intent createForwardIntent(final Context launcher, final Account account,
349 final Uri messageUri) {
350 return createActionIntent(launcher, account, messageUri, FORWARD);
351 }
352
353 private static Intent createActionIntent(final Context launcher, final Account account,
354 final Uri messageUri, final int action) {
355 final Intent intent = new Intent(launcher, ComposeActivity.class);
356
Paul Westbrook6d2442b2013-07-17 17:51:51 -0700357 updateActionIntent(account, messageUri, action, intent);
358
359 return intent;
360 }
361
362 @VisibleForTesting
363 static Intent updateActionIntent(Account account, Uri messageUri, int action, Intent intent) {
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -0800364 intent.putExtra(EXTRA_FROM_EMAIL_TASK, true);
365 intent.putExtra(EXTRA_ACTION, action);
366 intent.putExtra(Utils.EXTRA_ACCOUNT, account);
367 intent.putExtra(EXTRA_IN_REFERENCE_TO_MESSAGE_URI, messageUri);
368
369 return intent;
370 }
371
372 /**
373 * Can be called from a non-UI thread.
374 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800375 public static void reply(Context launcher, Account account, Message message) {
Scott Kennedy60847252013-08-15 15:55:42 -0700376 launch(launcher, account, message, REPLY, null, null, null, null, null /* extraValues */);
Mindy Pereira6349a042012-01-04 11:25:01 -0800377 }
378
379 /**
380 * Can be called from a non-UI thread.
381 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800382 public static void replyAll(Context launcher, Account account, Message message) {
Scott Kennedy60847252013-08-15 15:55:42 -0700383 launch(launcher, account, message, REPLY_ALL, null, null, null, null,
384 null /* extraValues */);
Mindy Pereira6349a042012-01-04 11:25:01 -0800385 }
386
387 /**
388 * Can be called from a non-UI thread.
389 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800390 public static void forward(Context launcher, Account account, Message message) {
Scott Kennedy60847252013-08-15 15:55:42 -0700391 launch(launcher, account, message, FORWARD, null, null, null, null, null /* extraValues */);
Mindy Pereira6349a042012-01-04 11:25:01 -0800392 }
393
Alice Yang1ebc2db2013-03-14 21:21:44 -0700394 public static void reportRenderingFeedback(Context launcher, Account account, Message message,
395 String body) {
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700396 launch(launcher, account, message, FORWARD,
Scott Kennedy60847252013-08-15 15:55:42 -0700397 "android-gmail-readability@google.com", body, null, null, null /* extraValues */);
Alice Yang1ebc2db2013-03-14 21:21:44 -0700398 }
399
400 private static void launch(Context launcher, Account account, Message message, int action,
Scott Kennedy60847252013-08-15 15:55:42 -0700401 String toAddress, String body, String quotedText, String subject,
402 final ContentValues extraValues) {
Mindy Pereira6349a042012-01-04 11:25:01 -0800403 Intent intent = new Intent(launcher, ComposeActivity.class);
404 intent.putExtra(EXTRA_FROM_EMAIL_TASK, true);
405 intent.putExtra(EXTRA_ACTION, action);
406 intent.putExtra(Utils.EXTRA_ACCOUNT, account);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700407 if (action == EDIT_DRAFT) {
408 intent.putExtra(ORIGINAL_DRAFT_MESSAGE, message);
409 } else {
410 intent.putExtra(EXTRA_IN_REFERENCE_TO_MESSAGE, message);
411 }
Alice Yang1ebc2db2013-03-14 21:21:44 -0700412 if (toAddress != null) {
413 intent.putExtra(EXTRA_TO, toAddress);
414 }
415 if (body != null) {
416 intent.putExtra(EXTRA_BODY, body);
417 }
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700418 if (quotedText != null) {
419 intent.putExtra(EXTRA_QUOTED_TEXT, quotedText);
420 }
421 if (subject != null) {
422 intent.putExtra(EXTRA_SUBJECT, subject);
423 }
Scott Kennedy60847252013-08-15 15:55:42 -0700424 if (extraValues != null) {
425 LogUtils.d(LOG_TAG, "Launching with extraValues: %s", extraValues.toString());
426 intent.putExtra(EXTRA_VALUES, extraValues);
427 }
Mindy Pereira6349a042012-01-04 11:25:01 -0800428 launcher.startActivity(intent);
429 }
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800430
Andy Huang0a2a3462013-12-20 15:56:13 -0800431 public static void composeMailto(Context launcher, Account account, Uri mailto) {
432 final Intent intent = new Intent(Intent.ACTION_VIEW, mailto, launcher,
433 ComposeActivity.class);
434 intent.putExtra(EXTRA_FROM_EMAIL_TASK, true);
435 intent.putExtra(Utils.EXTRA_ACCOUNT, account);
436 launcher.startActivity(intent);
437 }
438
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800439 @Override
Scott Kennedyd9063902013-08-02 22:14:37 -0700440 protected void onCreate(Bundle savedInstanceState) {
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800441 super.onCreate(savedInstanceState);
Mindy Pereira3528d362012-01-05 14:39:44 -0800442 setContentView(R.layout.compose);
Andy Huang9f855d62013-05-30 17:15:03 -0700443 mInnerSavedState = (savedInstanceState != null) ?
444 savedInstanceState.getBundle(KEY_INNER_SAVED_STATE) : null;
Mindy Pereirab199d172012-08-13 11:04:03 -0700445 checkValidAccounts();
446 }
447
448 private void finishCreate() {
Andy Huang9f855d62013-05-30 17:15:03 -0700449 final Bundle savedState = mInnerSavedState;
Mindy Pereira3528d362012-01-05 14:39:44 -0800450 findViews();
Mindy Pereira818143e2012-01-11 13:59:49 -0800451 Intent intent = getIntent();
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700452 Message message;
Mark Wei62066e42012-09-13 12:07:02 -0700453 ArrayList<AttachmentPreview> previews;
Alice Yanga990a712013-03-13 18:37:00 -0700454 mShowQuotedText = false;
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700455 CharSequence quotedText = null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700456 int action;
Mindy Pereira47d0e652012-07-23 09:45:07 -0700457 // Check for any of the possibly supplied accounts.;
458 Account account = null;
Andy Huang9f855d62013-05-30 17:15:03 -0700459 if (hadSavedInstanceStateMessage(savedState)) {
460 action = savedState.getInt(EXTRA_ACTION, COMPOSE);
461 account = savedState.getParcelable(Utils.EXTRA_ACCOUNT);
462 message = (Message) savedState.getParcelable(EXTRA_MESSAGE);
Mark Wei62066e42012-09-13 12:07:02 -0700463
Andy Huang9f855d62013-05-30 17:15:03 -0700464 previews = savedState.getParcelableArrayList(EXTRA_ATTACHMENT_PREVIEWS);
465 mRefMessage = (Message) savedState.getParcelable(EXTRA_IN_REFERENCE_TO_MESSAGE);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700466 quotedText = savedState.getCharSequence(EXTRA_QUOTED_TEXT);
Scott Kennedy44d44812013-08-19 14:18:31 -0700467
468 mExtraValues = savedState.getParcelable(EXTRA_VALUES);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700469 } else {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700470 account = obtainAccount(intent);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700471 action = intent.getIntExtra(EXTRA_ACTION, COMPOSE);
472 // Initialize the message from the message in the intent
473 message = (Message) intent.getParcelableExtra(ORIGINAL_DRAFT_MESSAGE);
Mark Wei62066e42012-09-13 12:07:02 -0700474 previews = intent.getParcelableArrayListExtra(EXTRA_ATTACHMENT_PREVIEWS);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700475 mRefMessage = (Message) intent.getParcelableExtra(EXTRA_IN_REFERENCE_TO_MESSAGE);
Mindy Pereirab18e5a92012-07-10 11:47:21 -0700476 mRefMessageUri = (Uri) intent.getParcelableExtra(EXTRA_IN_REFERENCE_TO_MESSAGE_URI);
Andy Huang4fe0af82013-08-20 17:24:51 -0700477
478 if (Analytics.isLoggable()) {
479 if (intent.getBooleanExtra(Utils.EXTRA_FROM_NOTIFICATION, false)) {
480 Analytics.getInstance().sendEvent(
481 "notification_action", "compose", getActionString(action), 0);
482 }
483 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700484 }
Mark Wei62066e42012-09-13 12:07:02 -0700485 mAttachmentsView.setAttachmentPreviews(previews);
Paul Westbrook92227f62012-03-20 10:32:51 -0700486
487 setAccount(account);
Mindy Pereira818143e2012-01-11 13:59:49 -0800488 if (mAccount == null) {
489 return;
490 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700491
Scott Kennedyfe853d32013-06-19 11:47:35 -0700492 initRecipients();
493
Scott Kennedy5680ec22013-01-07 13:15:20 -0800494 // Clear the notification and mark the conversation as seen, if necessary
495 final Folder notificationFolder =
496 intent.getParcelableExtra(EXTRA_NOTIFICATION_FOLDER);
497 if (notificationFolder != null) {
498 final Intent clearNotifIntent =
499 new Intent(MailIntentService.ACTION_CLEAR_NEW_MAIL_NOTIFICATIONS);
Scott Kennedyd5edd2d2012-12-05 11:11:32 -0800500 clearNotifIntent.setPackage(getPackageName());
Scott Kennedy48cfe462013-04-10 11:32:02 -0700501 clearNotifIntent.putExtra(Utils.EXTRA_ACCOUNT, account);
502 clearNotifIntent.putExtra(Utils.EXTRA_FOLDER, notificationFolder);
Scott Kennedy5680ec22013-01-07 13:15:20 -0800503
504 startService(clearNotifIntent);
505 }
506
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700507 if (intent.getBooleanExtra(EXTRA_FROM_EMAIL_TASK, false)) {
508 mLaunchedFromEmail = true;
509 } else if (Intent.ACTION_SEND.equals(intent.getAction())) {
510 final Uri dataUri = intent.getData();
511 if (dataUri != null) {
512 final String dataScheme = intent.getData().getScheme();
513 final String accountScheme = mAccount.composeIntentUri.getScheme();
514 mLaunchedFromEmail = TextUtils.equals(dataScheme, accountScheme);
515 }
516 }
517
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700518 if (mRefMessageUri != null) {
Alice Yanga990a712013-03-13 18:37:00 -0700519 mShowQuotedText = true;
520 mComposeMode = action;
521 getLoaderManager().initLoader(INIT_DRAFT_USING_REFERENCE_MESSAGE, null, this);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700522 return;
523 } else if (message != null && action != EDIT_DRAFT) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700524 initFromDraftMessage(message);
525 initQuotedTextFromRefMessage(mRefMessage, action);
Andy Huang9f855d62013-05-30 17:15:03 -0700526 showCcBcc(savedState);
Alice Yanga990a712013-03-13 18:37:00 -0700527 mShowQuotedText = message.appendRefMessageContent;
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700528 // if we should be showing quoted text but mRefMessage is null
529 // and we have some quotedText, display that
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700530 if (mShowQuotedText && mRefMessage == null) {
531 if (quotedText != null) {
532 initQuotedText(quotedText, false /* shouldQuoteText */);
533 } else if (mExtraValues != null) {
534 initExtraValues(mExtraValues);
535 return;
536 }
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700537 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700538 } else if (action == EDIT_DRAFT) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700539 initFromDraftMessage(message);
Scott Kennedy8960f0a2012-11-07 15:35:50 -0800540 boolean showBcc = !TextUtils.isEmpty(message.getBcc());
541 boolean showCc = showBcc || !TextUtils.isEmpty(message.getCc());
Mindy Pereiraef388302012-06-18 19:07:44 -0700542 mCcBccView.show(false, showCc, showBcc);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700543 // Update the action to the draft type of the previous draft
544 switch (message.draftType) {
545 case UIProvider.DraftType.REPLY:
546 action = REPLY;
547 break;
548 case UIProvider.DraftType.REPLY_ALL:
549 action = REPLY_ALL;
550 break;
551 case UIProvider.DraftType.FORWARD:
552 action = FORWARD;
553 break;
554 case UIProvider.DraftType.COMPOSE:
555 default:
556 action = COMPOSE;
557 break;
558 }
Alice Yanga990a712013-03-13 18:37:00 -0700559 LogUtils.d(LOG_TAG, "Previous draft had action type: %d", action);
560
561 mShowQuotedText = message.appendRefMessageContent;
562 if (message.refMessageUri != null) {
563 // If we're editing an existing draft that was in reference to an existing message,
564 // still need to load that original message since we might need to refer to the
565 // original sender and recipients if user switches "reply <-> reply-all".
566 mRefMessageUri = message.refMessageUri;
567 mComposeMode = action;
568 getLoaderManager().initLoader(REFERENCE_MESSAGE_LOADER, null, this);
569 return;
570 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700571 } else if ((action == REPLY || action == REPLY_ALL || action == FORWARD)) {
572 if (mRefMessage != null) {
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -0800573 initFromRefMessage(action);
Alice Yanga990a712013-03-13 18:37:00 -0700574 mShowQuotedText = true;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700575 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700576 } else {
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700577 if (initFromExtras(intent)) {
578 return;
579 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700580 }
Alice Yanga990a712013-03-13 18:37:00 -0700581
582 mComposeMode = action;
Andy Huang9f855d62013-05-30 17:15:03 -0700583 finishSetup(action, intent, savedState);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700584 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700585
Mindy Pereirab199d172012-08-13 11:04:03 -0700586 private void checkValidAccounts() {
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700587 final Account[] allAccounts = AccountUtils.getAccounts(this);
588 if (allAccounts == null || allAccounts.length == 0) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700589 final Intent noAccountIntent = MailAppProvider.getNoAccountIntent(this);
590 if (noAccountIntent != null) {
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700591 mAccounts = null;
Mindy Pereirab199d172012-08-13 11:04:03 -0700592 startActivityForResult(noAccountIntent, RESULT_CREATE_ACCOUNT);
593 }
594 } else {
mindyp26d4d2d2012-09-18 17:30:32 -0700595 // If none of the accounts are syncing, setup a watcher.
Mindy Pereirab199d172012-08-13 11:04:03 -0700596 boolean anySyncing = false;
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700597 for (Account a : allAccounts) {
Paul Westbrookdfa1dec2012-09-26 16:27:28 -0700598 if (a.isAccountReady()) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700599 anySyncing = true;
600 break;
601 }
602 }
603 if (!anySyncing) {
604 // There are accounts, but none are sync'd, which is just like having no accounts.
605 mAccounts = null;
606 getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, null, this);
607 return;
608 }
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700609 mAccounts = AccountUtils.getSyncingAccounts(this);
Mindy Pereirab199d172012-08-13 11:04:03 -0700610 finishCreate();
611 }
612 }
613
Mindy Pereira47d0e652012-07-23 09:45:07 -0700614 private Account obtainAccount(Intent intent) {
615 Account account = null;
616 Object accountExtra = null;
617 if (intent != null && intent.getExtras() != null) {
618 accountExtra = intent.getExtras().get(Utils.EXTRA_ACCOUNT);
619 if (accountExtra instanceof Account) {
620 return (Account) accountExtra;
mindyp7ae042e2012-08-27 13:27:37 -0700621 } else if (accountExtra instanceof String) {
622 // This is the Account attached to the widget compose intent.
623 account = Account.newinstance((String)accountExtra);
624 if (account != null) {
625 return account;
626 }
Mindy Pereira47d0e652012-07-23 09:45:07 -0700627 }
mindyp5ee9dc42013-01-08 09:54:54 -0800628 accountExtra = intent.hasExtra(Utils.EXTRA_ACCOUNT) ?
629 intent.getStringExtra(Utils.EXTRA_ACCOUNT) :
630 intent.getStringExtra(EXTRA_SELECTED_ACCOUNT);
Mindy Pereira47d0e652012-07-23 09:45:07 -0700631 }
632 if (account == null) {
mindyp06174462012-10-12 09:11:27 -0700633 MailAppProvider provider = MailAppProvider.getInstance();
634 String lastAccountUri = provider.getLastSentFromAccount();
635 if (TextUtils.isEmpty(lastAccountUri)) {
636 lastAccountUri = provider.getLastViewedAccount();
637 }
Mindy Pereira47d0e652012-07-23 09:45:07 -0700638 if (!TextUtils.isEmpty(lastAccountUri)) {
639 accountExtra = Uri.parse(lastAccountUri);
640 }
641 }
Mindy Pereirab199d172012-08-13 11:04:03 -0700642 if (mAccounts != null && mAccounts.length > 0) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700643 if (accountExtra instanceof String && !TextUtils.isEmpty((String) accountExtra)) {
644 // For backwards compatibility, we need to check account
645 // names.
Mindy Pereirab199d172012-08-13 11:04:03 -0700646 for (Account a : mAccounts) {
Tony Mantler79b11562013-10-09 15:31:50 -0700647 if (a.getEmailAddress().equals(accountExtra)) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700648 account = a;
649 }
650 }
651 } else if (accountExtra instanceof Uri) {
652 // The uri of the last viewed account is what is stored in
653 // the current code base.
Mindy Pereirab199d172012-08-13 11:04:03 -0700654 for (Account a : mAccounts) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700655 if (a.uri.equals(accountExtra)) {
656 account = a;
657 }
658 }
Mindy Pereirab199d172012-08-13 11:04:03 -0700659 }
660 if (account == null) {
661 account = mAccounts[0];
Mindy Pereira47d0e652012-07-23 09:45:07 -0700662 }
663 }
664 return account;
665 }
666
Andrew Sapperstein746d8612013-08-26 15:56:32 -0700667 protected void finishSetup(int action, Intent intent, Bundle savedInstanceState) {
mindyp34a3c562012-11-06 15:12:15 -0800668 setFocus(action);
Mindy Pereiraf7fc6c32012-06-19 15:18:33 -0700669 // Don't bother with the intent if we have procured a message from the
670 // intent already.
671 if (!hadSavedInstanceStateMessage(savedInstanceState)) {
672 initAttachmentsFromIntent(intent);
673 }
Alice Yanga990a712013-03-13 18:37:00 -0700674 initActionBar();
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700675 initFromSpinner(savedInstanceState != null ? savedInstanceState : intent.getExtras(),
676 action);
mindypd4a48662012-11-08 17:13:49 -0800677
678 // If this is a draft message, the draft account is whatever account was
679 // used to open the draft message in Compose.
680 if (mDraft != null) {
681 mDraftAccount = mReplyFromAccount;
682 }
683
Mindy Pereira75f66632012-01-11 11:42:02 -0800684 initChangeListeners();
Mindy Pereira326689d2012-05-17 10:14:14 -0700685 updateHideOrShowCcBcc();
Alice Yanga990a712013-03-13 18:37:00 -0700686 updateHideOrShowQuotedText(mShowQuotedText);
mindyp1623f9b2012-11-21 12:41:16 -0800687
Andy Huang9f855d62013-05-30 17:15:03 -0700688 mRespondedInline = mInnerSavedState != null ?
689 mInnerSavedState.getBoolean(EXTRA_RESPONDED_INLINE) : false;
mindyp1623f9b2012-11-21 12:41:16 -0800690 if (mRespondedInline) {
691 mQuotedTextView.setVisibility(View.GONE);
692 }
Mindy Pereira71c9e562012-05-17 11:01:02 -0700693 }
694
Scott Kennedyff8553f2013-04-05 20:57:44 -0700695 private static boolean hadSavedInstanceStateMessage(final Bundle savedInstanceState) {
Mindy Pereiraf7fc6c32012-06-19 15:18:33 -0700696 return savedInstanceState != null && savedInstanceState.containsKey(EXTRA_MESSAGE);
697 }
698
Mindy Pereira71c9e562012-05-17 11:01:02 -0700699 private void updateHideOrShowQuotedText(boolean showQuotedText) {
700 mQuotedTextView.updateCheckedState(showQuotedText);
mindyp40882432012-09-06 11:07:40 -0700701 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
Mindy Pereira433b1982012-04-03 11:53:07 -0700702 }
703
704 private void setFocus(int action) {
705 if (action == EDIT_DRAFT) {
706 int type = mDraft.draftType;
707 switch (type) {
708 case UIProvider.DraftType.COMPOSE:
709 case UIProvider.DraftType.FORWARD:
710 action = COMPOSE;
711 break;
712 case UIProvider.DraftType.REPLY:
713 case UIProvider.DraftType.REPLY_ALL:
714 default:
715 action = REPLY;
716 break;
717 }
718 }
719 switch (action) {
720 case FORWARD:
721 case COMPOSE:
mindyp27083062012-11-15 09:02:01 -0800722 if (TextUtils.isEmpty(mTo.getText())) {
723 mTo.requestFocus();
724 break;
725 }
Scott Kennedyff8553f2013-04-05 20:57:44 -0700726 //$FALL-THROUGH$
Mindy Pereira433b1982012-04-03 11:53:07 -0700727 case REPLY:
728 case REPLY_ALL:
729 default:
730 focusBody();
731 break;
732 }
733 }
734
735 /**
736 * Focus the body of the message.
737 */
738 public void focusBody() {
739 mBodyView.requestFocus();
740 int length = mBodyView.getText().length();
741
742 int signatureStartPos = getSignatureStartPosition(
743 mSignature, mBodyView.getText().toString());
744 if (signatureStartPos > -1) {
745 // In case the user deleted the newlines...
746 mBodyView.setSelection(signatureStartPos);
mindyp8743cfc2012-09-18 13:29:08 -0700747 } else if (length >= 0) {
Mindy Pereira433b1982012-04-03 11:53:07 -0700748 // Move cursor to the end.
749 mBodyView.setSelection(length);
750 }
Mindy Pereira1a95a572012-01-05 12:21:29 -0800751 }
752
753 @Override
Andy Huang761522c2013-08-08 13:09:11 -0700754 protected void onStart() {
755 super.onStart();
756
757 Analytics.getInstance().activityStart(this);
758 }
759
760 @Override
761 protected void onStop() {
762 super.onStop();
763
764 Analytics.getInstance().activityStop(this);
765 }
766
767 @Override
Mindy Pereira1a95a572012-01-05 12:21:29 -0800768 protected void onResume() {
769 super.onResume();
770 // Update the from spinner as other accounts
771 // may now be available.
Mindy Pereira818143e2012-01-11 13:59:49 -0800772 if (mFromSpinner != null && mAccount != null) {
Paul Westbrookc97ec3e2013-07-12 18:17:19 -0700773 mFromSpinner.initialize(mComposeMode, mAccount, mAccounts, mRefMessage);
Mindy Pereira818143e2012-01-11 13:59:49 -0800774 }
Mindy Pereira1a95a572012-01-05 12:21:29 -0800775 }
776
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800777 @Override
778 protected void onPause() {
779 super.onPause();
780
Mindy Pereiraa2148332012-07-02 13:54:14 -0700781 // When the user exits the compose view, see if this draft needs saving.
Yorke Lee3d7048e2012-09-19 14:19:25 -0700782 // Don't save unnecessary drafts if we are only changing the orientation.
783 if (!isChangingConfigurations()) {
Mindy Pereiraa2148332012-07-02 13:54:14 -0700784 saveIfNeeded();
Andy Huangdc97bf42013-08-15 16:52:45 -0700785
Andy Huange003b4c2013-08-16 10:32:05 -0700786 if (isFinishing() && !mPerformedSendOrDiscard && !isBlank()) {
Andy Huangdc97bf42013-08-15 16:52:45 -0700787 // log saving upon backing out of activity. (we avoid logging every sendOrSave()
788 // because that method can be invoked many times in a single compose session.)
789 logSendOrSave(true /* save */);
790 }
Mindy Pereiraa2148332012-07-02 13:54:14 -0700791 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800792 }
793
794 @Override
795 protected final void onActivityResult(int request, int result, Intent data) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700796 if (request == RESULT_PICK_ATTACHMENT && result == RESULT_OK) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800797 addAttachmentAndUpdateView(data);
Mindy Pereirab199d172012-08-13 11:04:03 -0700798 mAddingAttachment = false;
799 } else if (request == RESULT_CREATE_ACCOUNT) {
Alice Yanga990a712013-03-13 18:37:00 -0700800 // We were waiting for the user to create an account
Mindy Pereirab199d172012-08-13 11:04:03 -0700801 if (result != RESULT_OK) {
802 finish();
803 } else {
804 // Watch for accounts to show up!
805 // restart the loader to get the updated list of accounts
806 getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, null, this);
807 showWaitFragment(null);
808 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800809 }
810 }
811
812 @Override
Scott Kennedyd9063902013-08-02 22:14:37 -0700813 protected final void onRestoreInstanceState(Bundle savedInstanceState) {
Yorke Lee7bec2b92013-04-26 08:31:42 -0700814 final boolean hasAccounts = mAccounts != null && mAccounts.length > 0;
815 if (hasAccounts) {
816 clearChangeListeners();
817 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700818 super.onRestoreInstanceState(savedInstanceState);
Andy Huang9f855d62013-05-30 17:15:03 -0700819 if (mInnerSavedState != null) {
820 if (mInnerSavedState.containsKey(EXTRA_FOCUS_SELECTION_START)) {
821 int selectionStart = mInnerSavedState.getInt(EXTRA_FOCUS_SELECTION_START);
822 int selectionEnd = mInnerSavedState.getInt(EXTRA_FOCUS_SELECTION_END);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700823 // There should be a focus and it should be an EditText since we
824 // only save these extras if these conditions are true.
825 EditText focusEditText = (EditText) getCurrentFocus();
826 final int length = focusEditText.getText().length();
827 if (selectionStart < length && selectionEnd < length) {
828 focusEditText.setSelection(selectionStart, selectionEnd);
829 }
830 }
831 }
Yorke Lee7bec2b92013-04-26 08:31:42 -0700832 if (hasAccounts) {
833 initChangeListeners();
834 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700835 }
836
837 @Override
Scott Kennedyd9063902013-08-02 22:14:37 -0700838 protected final void onSaveInstanceState(Bundle state) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800839 super.onSaveInstanceState(state);
Andy Huang9f855d62013-05-30 17:15:03 -0700840 final Bundle inner = new Bundle();
841 saveState(inner);
842 state.putBundle(KEY_INNER_SAVED_STATE, inner);
843 }
844
845 private void saveState(Bundle state) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700846 // We have no accounts so there is nothing to compose, and therefore, nothing to save.
847 if (mAccounts == null || mAccounts.length == 0) {
848 return;
849 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700850 // The framework is happy to save and restore the selection but only if it also saves and
851 // restores the contents of the edit text. That's a lot of text to put in a bundle so we do
852 // this manually.
853 View focus = getCurrentFocus();
854 if (focus != null && focus instanceof EditText) {
855 EditText focusEditText = (EditText) focus;
856 state.putInt(EXTRA_FOCUS_SELECTION_START, focusEditText.getSelectionStart());
857 state.putInt(EXTRA_FOCUS_SELECTION_END, focusEditText.getSelectionEnd());
858 }
Paul Westbrook6273e962012-04-23 10:44:15 -0700859
860 final List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
Paul Westbrook151f1ad2012-04-24 09:13:00 -0700861 final int selectedPos = mFromSpinner.getSelectedItemPosition();
Mindy Pereirad90f7ac2012-06-27 10:31:06 -0700862 final ReplyFromAccount selectedReplyFromAccount = (replyFromAccounts != null
863 && replyFromAccounts.size() > 0 && replyFromAccounts.size() > selectedPos) ?
864 replyFromAccounts.get(selectedPos) : null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700865 if (selectedReplyFromAccount != null) {
866 state.putString(EXTRA_SELECTED_REPLY_FROM_ACCOUNT, selectedReplyFromAccount.serialize()
867 .toString());
868 state.putParcelable(Utils.EXTRA_ACCOUNT, selectedReplyFromAccount.account);
869 } else {
870 state.putParcelable(Utils.EXTRA_ACCOUNT, mAccount);
871 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800872
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700873 if (mDraftId == UIProvider.INVALID_MESSAGE_ID && mRequestId !=0) {
874 // We don't have a draft id, and we have a request id,
875 // save the request id.
876 state.putInt(EXTRA_REQUEST_ID, mRequestId);
877 }
878
879 // We want to restore the current mode after a pause
880 // or rotation.
881 int mode = getMode();
882 state.putInt(EXTRA_ACTION, mode);
883
mindype7b76aa2012-11-14 16:19:13 -0800884 final Message message = createMessage(selectedReplyFromAccount, mode);
Andy Huang1f8f4dd2012-10-25 21:35:35 -0700885 if (mDraft != null) {
mindype7b76aa2012-11-14 16:19:13 -0800886 message.id = mDraft.id;
887 message.serverId = mDraft.serverId;
888 message.uri = mDraft.uri;
Andy Huang1f8f4dd2012-10-25 21:35:35 -0700889 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700890 state.putParcelable(EXTRA_MESSAGE, message);
891
892 if (mRefMessage != null) {
893 state.putParcelable(EXTRA_IN_REFERENCE_TO_MESSAGE, mRefMessage);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -0700894 } else if (message.appendRefMessageContent) {
895 // If we have no ref message but should be appending
896 // ref message content, we have orphaned quoted text. Save it.
897 state.putCharSequence(EXTRA_QUOTED_TEXT, mQuotedTextView.getQuotedTextIfIncluded());
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700898 }
Mindy Pereira326689d2012-05-17 10:14:14 -0700899 state.putBoolean(EXTRA_SHOW_CC, mCcBccView.isCcVisible());
900 state.putBoolean(EXTRA_SHOW_BCC, mCcBccView.isBccVisible());
mindyp1623f9b2012-11-21 12:41:16 -0800901 state.putBoolean(EXTRA_RESPONDED_INLINE, mRespondedInline);
mindyp816b3f02012-12-11 08:25:04 -0800902 state.putBoolean(EXTRA_SAVE_ENABLED, mSave != null && mSave.isEnabled());
Mark Wei62066e42012-09-13 12:07:02 -0700903 state.putParcelableArrayList(
904 EXTRA_ATTACHMENT_PREVIEWS, mAttachmentsView.getAttachmentPreviews());
Scott Kennedy44d44812013-08-19 14:18:31 -0700905
906 state.putParcelable(EXTRA_VALUES, mExtraValues);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700907 }
908
909 private int getMode() {
910 int mode = ComposeActivity.COMPOSE;
911 ActionBar actionBar = getActionBar();
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700912 if (actionBar != null
913 && actionBar.getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700914 mode = actionBar.getSelectedNavigationIndex();
915 }
916 return mode;
917 }
918
919 private Message createMessage(ReplyFromAccount selectedReplyFromAccount, int mode) {
920 Message message = new Message();
921 message.id = UIProvider.INVALID_MESSAGE_ID;
Andy Huangd47877e2012-08-09 19:31:24 -0700922 message.serverId = null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700923 message.uri = null;
924 message.conversationUri = null;
925 message.subject = mSubject.getText().toString();
926 message.snippet = null;
Scott Kennedy8960f0a2012-11-07 15:35:50 -0800927 message.setTo(formatSenders(mTo.getText().toString()));
928 message.setCc(formatSenders(mCc.getText().toString()));
929 message.setBcc(formatSenders(mBcc.getText().toString()));
930 message.setReplyTo(null);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700931 message.dateReceivedMs = 0;
Paul Westbrookb4931c62013-01-14 17:51:18 -0800932 final String htmlBody = Html.toHtml(removeComposingSpans(mBodyView.getText()));
933 final StringBuilder fullBody = new StringBuilder(htmlBody);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700934 message.bodyHtml = fullBody.toString();
935 message.bodyText = mBodyView.getText().toString();
936 message.embedsExternalResources = false;
Alice Yanga990a712013-03-13 18:37:00 -0700937 message.refMessageUri = mRefMessage != null ? mRefMessage.uri : null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700938 message.appendRefMessageContent = mQuotedTextView.getQuotedTextIfIncluded() != null;
939 ArrayList<Attachment> attachments = mAttachmentsView.getAttachments();
940 message.hasAttachments = attachments != null && attachments.size() > 0;
941 message.attachmentListUri = null;
942 message.messageFlags = 0;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700943 message.alwaysShowImages = false;
944 message.attachmentsJson = Attachment.toJSONArray(attachments);
945 CharSequence quotedText = mQuotedTextView.getQuotedText();
946 message.quotedTextOffset = !TextUtils.isEmpty(quotedText) ? QuotedTextView
947 .getQuotedTextOffset(quotedText.toString()) : -1;
948 message.accountUri = null;
Tony Mantlerbb036ff72013-10-18 14:03:43 -0700949 final String email = selectedReplyFromAccount != null ? selectedReplyFromAccount.address
950 : mAccount != null ? mAccount.getEmailAddress() : null;
Tony Mantlerf441d142013-10-22 11:46:00 -0700951 final String senderName = selectedReplyFromAccount != null ? selectedReplyFromAccount.name
952 : mAccount != null ? mAccount.getSenderName() : null;
Tony Mantler821e5782014-01-06 15:33:43 -0800953 final Address address = new Address(email, senderName);
Tony Mantlerf441d142013-10-22 11:46:00 -0700954 message.setFrom(address.toHeader());
Andy Huang1f8f4dd2012-10-25 21:35:35 -0700955 message.draftType = getDraftType(mode);
mindype7b76aa2012-11-14 16:19:13 -0800956 return message;
Andy Huang1f8f4dd2012-10-25 21:35:35 -0700957 }
958
Scott Kennedyff8553f2013-04-05 20:57:44 -0700959 private static String formatSenders(final String string) {
Mindy Pereira3c911582012-08-09 16:59:09 -0700960 if (!TextUtils.isEmpty(string) && string.charAt(string.length() - 1) == ',') {
961 return string.substring(0, string.length() - 1);
962 }
963 return string;
964 }
965
Mindy Pereira818143e2012-01-11 13:59:49 -0800966 @VisibleForTesting
967 void setAccount(Account account) {
Mindy Pereirabb5217e2012-04-17 11:08:29 -0700968 if (account == null) {
969 return;
970 }
Mindy Pereira23e9fde2012-03-20 15:08:24 -0700971 if (!account.equals(mAccount)) {
972 mAccount = account;
Paul Westbrookb1f573c2012-04-06 11:38:28 -0700973 mCachedSettings = mAccount.settings;
974 appendSignature();
Mindy Pereira23e9fde2012-03-20 15:08:24 -0700975 }
Mindy Pereirafa20c1a2012-07-23 13:00:02 -0700976 if (mAccount != null) {
Tony Mantler79b11562013-10-09 15:31:50 -0700977 MailActivity.setNfcMessage(mAccount.getEmailAddress());
Mindy Pereirafa20c1a2012-07-23 13:00:02 -0700978 }
Mindy Pereira818143e2012-01-11 13:59:49 -0800979 }
980
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700981 private void initFromSpinner(Bundle bundle, int action) {
982 if (action == EDIT_DRAFT && mDraft.draftType == UIProvider.DraftType.COMPOSE) {
Mindy Pereira62de1b12012-04-06 12:17:56 -0700983 action = COMPOSE;
984 }
Paul Westbrookc97ec3e2013-07-12 18:17:19 -0700985 mFromSpinner.initialize(action, mAccount, mAccounts, mRefMessage);
986
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700987 if (bundle != null) {
988 if (bundle.containsKey(EXTRA_SELECTED_REPLY_FROM_ACCOUNT)) {
989 mReplyFromAccount = ReplyFromAccount.deserialize(mAccount,
990 bundle.getString(EXTRA_SELECTED_REPLY_FROM_ACCOUNT));
991 } else if (bundle.containsKey(EXTRA_FROM_ACCOUNT_STRING)) {
Paul Westbrookc97ec3e2013-07-12 18:17:19 -0700992 final String accountString = bundle.getString(EXTRA_FROM_ACCOUNT_STRING);
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700993 mReplyFromAccount = mFromSpinner.getMatchingReplyFromAccount(accountString);
994 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700995 }
996 if (mReplyFromAccount == null) {
997 if (mDraft != null) {
998 mReplyFromAccount = getReplyFromAccountFromDraft(mAccount, mDraft);
999 } else if (mRefMessage != null) {
1000 mReplyFromAccount = getReplyFromAccountForReply(mAccount, mRefMessage);
1001 }
Mindy Pereira62de1b12012-04-06 12:17:56 -07001002 }
1003 if (mReplyFromAccount == null) {
Andy Huang238aa472012-10-30 17:45:17 -07001004 mReplyFromAccount = getDefaultReplyFromAccount(mAccount);
Mindy Pereira62de1b12012-04-06 12:17:56 -07001005 }
Mindy Pereira9a42bb42012-04-18 15:21:33 -07001006
Mindy Pereira62de1b12012-04-06 12:17:56 -07001007 mFromSpinner.setCurrentAccount(mReplyFromAccount);
Mindy Pereira9a42bb42012-04-18 15:21:33 -07001008
Mindy Pereira62de1b12012-04-06 12:17:56 -07001009 if (mFromSpinner.getCount() > 1) {
Mindy Pereiraa83e7082012-03-30 08:53:11 -07001010 // If there is only 1 account, just show that account.
1011 // Otherwise, give the user the ability to choose which account to
Mindy Pereira62de1b12012-04-06 12:17:56 -07001012 // send mail from / save drafts to.
1013 mFromStatic.setVisibility(View.GONE);
Andy Huangca4676f2014-01-16 13:22:20 -08001014 mFromStaticText.setText(mReplyFromAccount.address);
Mindy Pereira62de1b12012-04-06 12:17:56 -07001015 mFromSpinnerWrapper.setVisibility(View.VISIBLE);
Mindy Pereiraa83e7082012-03-30 08:53:11 -07001016 } else {
1017 mFromStatic.setVisibility(View.VISIBLE);
Andy Huangca4676f2014-01-16 13:22:20 -08001018 mFromStaticText.setText(mReplyFromAccount.address);
Mindy Pereiraa83e7082012-03-30 08:53:11 -07001019 mFromSpinnerWrapper.setVisibility(View.GONE);
Mindy Pereiraa83e7082012-03-30 08:53:11 -07001020 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001021 }
1022
Mindy Pereira62de1b12012-04-06 12:17:56 -07001023 private ReplyFromAccount getReplyFromAccountForReply(Account account, Message refMessage) {
1024 if (refMessage.accountUri != null) {
1025 // This must be from combined inbox.
1026 List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
1027 for (ReplyFromAccount from : replyFromAccounts) {
1028 if (from.account.uri.equals(refMessage.accountUri)) {
1029 return from;
1030 }
1031 }
1032 return null;
1033 } else {
1034 return getReplyFromAccount(account, refMessage);
1035 }
1036 }
1037
1038 /**
Tony Mantler9016a5e2013-07-19 11:54:17 -07001039 * Given an account and the message we're replying to,
Mindy Pereira62de1b12012-04-06 12:17:56 -07001040 * return who the message should be sent from.
1041 * @param account Account in which the message arrived.
Tony Mantler9016a5e2013-07-19 11:54:17 -07001042 * @param refMessage Message to analyze for account selection
Mindy Pereira62de1b12012-04-06 12:17:56 -07001043 * @return the address from which to reply.
1044 */
1045 public ReplyFromAccount getReplyFromAccount(Account account, Message refMessage) {
1046 // First see if we are supposed to use the default address or
1047 // the address it was sentTo.
Mindy Pereira326689d2012-05-17 10:14:14 -07001048 if (mCachedSettings.forceReplyFromDefault) {
Mindy Pereira62de1b12012-04-06 12:17:56 -07001049 return getDefaultReplyFromAccount(account);
1050 } else {
Mindy Pereira89bae572012-06-18 11:34:36 -07001051 // If we aren't explicitly told which account to look for, look at
Mindy Pereira62de1b12012-04-06 12:17:56 -07001052 // all the message recipients and find one that matches
1053 // a custom from or account.
1054 List<String> allRecipients = new ArrayList<String>();
Tony Mantler9016a5e2013-07-19 11:54:17 -07001055 allRecipients.addAll(Arrays.asList(refMessage.getToAddressesUnescaped()));
1056 allRecipients.addAll(Arrays.asList(refMessage.getCcAddressesUnescaped()));
Mindy Pereira62de1b12012-04-06 12:17:56 -07001057 return getMatchingRecipient(account, allRecipients);
1058 }
1059 }
1060
1061 /**
1062 * Compare all the recipients of an email to the current account and all
1063 * custom addresses associated with that account. Return the match if there
1064 * is one, or the default account if there isn't.
1065 */
1066 protected ReplyFromAccount getMatchingRecipient(Account account, List<String> sentTo) {
1067 // Tokenize the list and place in a hashmap.
1068 ReplyFromAccount matchingReplyFrom = null;
1069 Rfc822Token[] tokens;
1070 HashSet<String> recipientsMap = new HashSet<String>();
1071 for (String address : sentTo) {
1072 tokens = Rfc822Tokenizer.tokenize(address);
1073 for (int i = 0; i < tokens.length; i++) {
1074 recipientsMap.add(tokens[i].getAddress());
1075 }
1076 }
1077
1078 int matchingAddressCount = 0;
1079 List<ReplyFromAccount> customFroms;
Andy Huang16174812012-08-16 16:40:35 -07001080 customFroms = account.getReplyFroms();
1081 if (customFroms != null) {
1082 for (ReplyFromAccount entry : customFroms) {
1083 if (recipientsMap.contains(entry.address)) {
1084 matchingReplyFrom = entry;
1085 matchingAddressCount++;
Mindy Pereira62de1b12012-04-06 12:17:56 -07001086 }
1087 }
Mindy Pereira62de1b12012-04-06 12:17:56 -07001088 }
1089 if (matchingAddressCount > 1) {
1090 matchingReplyFrom = getDefaultReplyFromAccount(account);
1091 }
1092 return matchingReplyFrom;
1093 }
1094
Scott Kennedyff8553f2013-04-05 20:57:44 -07001095 private static ReplyFromAccount getDefaultReplyFromAccount(final Account account) {
1096 for (final ReplyFromAccount from : account.getReplyFroms()) {
Mindy Pereira62de1b12012-04-06 12:17:56 -07001097 if (from.isDefault) {
1098 return from;
1099 }
1100 }
Tony Mantlerf441d142013-10-22 11:46:00 -07001101 return new ReplyFromAccount(account, account.uri, account.getEmailAddress(),
1102 account.getSenderName(), account.getEmailAddress(), true, false);
Mindy Pereira62de1b12012-04-06 12:17:56 -07001103 }
1104
Tony Mantlerf441d142013-10-22 11:46:00 -07001105 private ReplyFromAccount getReplyFromAccountFromDraft(final Account account,
1106 final Message msg) {
1107 final Address[] draftFroms = Address.parse(msg.getFrom());
1108 final String sender = draftFroms.length > 0 ? draftFroms[0].getAddress() : "";
Mindy Pereira62de1b12012-04-06 12:17:56 -07001109 ReplyFromAccount replyFromAccount = null;
1110 List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
Tony Mantler79b11562013-10-09 15:31:50 -07001111 if (TextUtils.equals(account.getEmailAddress(), sender)) {
Tony Mantlerf441d142013-10-22 11:46:00 -07001112 replyFromAccount = getDefaultReplyFromAccount(account);
Mindy Pereira62de1b12012-04-06 12:17:56 -07001113 } else {
1114 for (ReplyFromAccount fromAccount : replyFromAccounts) {
Tony Mantler79b11562013-10-09 15:31:50 -07001115 if (TextUtils.equals(fromAccount.address, sender)) {
Mindy Pereira62de1b12012-04-06 12:17:56 -07001116 replyFromAccount = fromAccount;
1117 break;
1118 }
1119 }
1120 }
1121 return replyFromAccount;
1122 }
1123
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001124 private void findViews() {
Mindy Pereirab199d172012-08-13 11:04:03 -07001125 findViewById(R.id.compose).setVisibility(View.VISIBLE);
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001126 mCcBccButton = (Button) findViewById(R.id.add_cc_bcc);
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001127 if (mCcBccButton != null) {
1128 mCcBccButton.setOnClickListener(this);
1129 }
1130 mCcBccView = (CcBccView) findViewById(R.id.cc_bcc_wrapper);
Mindy Pereira7b56a612011-12-14 12:32:28 -08001131 mAttachmentsView = (AttachmentsView)findViewById(R.id.attachments);
Andrew Sapperstein6aea7862013-10-24 19:59:51 -07001132 mAddAttachmentsButton = findViewById(R.id.add_attachment);
1133 if (mAddAttachmentsButton != null) {
1134 mAddAttachmentsButton.setOnClickListener(this);
mindypcd0b0b92012-08-23 14:33:17 -07001135 }
Mindy Pereira818143e2012-01-11 13:59:49 -08001136 mTo = (RecipientEditTextView) findViewById(R.id.to);
Scott Kennedy41500392013-04-24 18:46:36 -07001137 mTo.setTokenizer(new Rfc822Tokenizer());
Mindy Pereira818143e2012-01-11 13:59:49 -08001138 mCc = (RecipientEditTextView) findViewById(R.id.cc);
Scott Kennedy41500392013-04-24 18:46:36 -07001139 mCc.setTokenizer(new Rfc822Tokenizer());
Mindy Pereira818143e2012-01-11 13:59:49 -08001140 mBcc = (RecipientEditTextView) findViewById(R.id.bcc);
Scott Kennedy41500392013-04-24 18:46:36 -07001141 mBcc.setTokenizer(new Rfc822Tokenizer());
Mindy Pereira82cc5662012-01-09 17:29:30 -08001142 // TODO: add special chips text change watchers before adding
1143 // this as a text changed watcher to the to, cc, bcc fields.
Mindy Pereira6349a042012-01-04 11:25:01 -08001144 mSubject = (TextView) findViewById(R.id.subject);
mindyp62d3ec72012-08-24 13:04:09 -07001145 mSubject.setOnEditorActionListener(this);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001146 mQuotedTextView = (QuotedTextView) findViewById(R.id.quoted_text_view);
1147 mQuotedTextView.setRespondInlineListener(this);
Mindy Pereira433b1982012-04-03 11:53:07 -07001148 mBodyView = (EditText) findViewById(R.id.body);
Mindy Pereira1a95a572012-01-05 12:21:29 -08001149 mFromStatic = findViewById(R.id.static_from_content);
Mindy Pereira2eb17322012-03-07 10:07:34 -08001150 mFromStaticText = (TextView) findViewById(R.id.from_account_name);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001151 mFromSpinnerWrapper = findViewById(R.id.spinner_from_content);
Mindy Pereira5a85e2b2012-01-11 09:53:32 -08001152 mFromSpinner = (FromAddressSpinner) findViewById(R.id.from_picker);
Mindy Pereira6349a042012-01-04 11:25:01 -08001153 }
1154
mindyp62d3ec72012-08-24 13:04:09 -07001155 @Override
1156 public boolean onEditorAction(TextView view, int action, KeyEvent keyEvent) {
1157 if (action == EditorInfo.IME_ACTION_DONE) {
1158 focusBody();
1159 return true;
1160 }
1161 return false;
1162 }
1163
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001164 protected TextView getBody() {
1165 return mBodyView;
1166 }
1167
1168 @VisibleForTesting
Andy Huang0a2a3462013-12-20 15:56:13 -08001169 public String getBodyHtml() {
1170 return Html.toHtml(removeComposingSpans(mBodyView.getText()));
1171 }
1172
1173 @VisibleForTesting
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001174 public Account getFromAccount() {
1175 return mReplyFromAccount != null && mReplyFromAccount.account != null ?
1176 mReplyFromAccount.account : mAccount;
1177 }
1178
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07001179 private void clearChangeListeners() {
1180 mSubject.removeTextChangedListener(this);
1181 mBodyView.removeTextChangedListener(this);
1182 mTo.removeTextChangedListener(mToListener);
1183 mCc.removeTextChangedListener(mCcListener);
1184 mBcc.removeTextChangedListener(mBccListener);
1185 mFromSpinner.setOnAccountChangedListener(null);
1186 mAttachmentsView.setAttachmentChangesListener(null);
1187 }
1188
Mindy Pereira75f66632012-01-11 11:42:02 -08001189 // Now that the message has been initialized from any existing draft or
1190 // ref message data, set up listeners for any changes that occur to the
1191 // message.
1192 private void initChangeListeners() {
mindyp1d7e9142012-11-21 13:54:30 -08001193 // Make sure we only add text changed listeners once!
1194 clearChangeListeners();
Mindy Pereira75f66632012-01-11 11:42:02 -08001195 mSubject.addTextChangedListener(this);
1196 mBodyView.addTextChangedListener(this);
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07001197 if (mToListener == null) {
1198 mToListener = new RecipientTextWatcher(mTo, this);
1199 }
1200 mTo.addTextChangedListener(mToListener);
1201 if (mCcListener == null) {
1202 mCcListener = new RecipientTextWatcher(mCc, this);
1203 }
1204 mCc.addTextChangedListener(mCcListener);
1205 if (mBccListener == null) {
1206 mBccListener = new RecipientTextWatcher(mBcc, this);
1207 }
1208 mBcc.addTextChangedListener(mBccListener);
Mindy Pereira75f66632012-01-11 11:42:02 -08001209 mFromSpinner.setOnAccountChangedListener(this);
Mindy Pereira818143e2012-01-11 13:59:49 -08001210 mAttachmentsView.setAttachmentChangesListener(this);
Mindy Pereira75f66632012-01-11 11:42:02 -08001211 }
1212
Alice Yanga990a712013-03-13 18:37:00 -07001213 private void initActionBar() {
1214 LogUtils.d(LOG_TAG, "initializing action bar in ComposeActivity");
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001215 ActionBar actionBar = getActionBar();
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001216 if (actionBar == null) {
1217 return;
1218 }
Alice Yanga990a712013-03-13 18:37:00 -07001219 if (mComposeMode == ComposeActivity.COMPOSE) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001220 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1221 actionBar.setTitle(R.string.compose);
Mindy Pereira326c6602012-01-04 15:32:42 -08001222 } else {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001223 actionBar.setTitle(null);
Mindy Pereira326c6602012-01-04 15:32:42 -08001224 if (mComposeModeAdapter == null) {
1225 mComposeModeAdapter = new ComposeModeAdapter(this);
1226 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001227 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
1228 actionBar.setListNavigationCallbacks(mComposeModeAdapter, this);
Alice Yanga990a712013-03-13 18:37:00 -07001229 switch (mComposeMode) {
Mindy Pereira326c6602012-01-04 15:32:42 -08001230 case ComposeActivity.REPLY:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001231 actionBar.setSelectedNavigationItem(0);
Mindy Pereira326c6602012-01-04 15:32:42 -08001232 break;
1233 case ComposeActivity.REPLY_ALL:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001234 actionBar.setSelectedNavigationItem(1);
Mindy Pereira326c6602012-01-04 15:32:42 -08001235 break;
1236 case ComposeActivity.FORWARD:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001237 actionBar.setSelectedNavigationItem(2);
Mindy Pereira326c6602012-01-04 15:32:42 -08001238 break;
1239 }
1240 }
Mindy Pereirafbe40192012-03-20 10:40:45 -07001241 actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME,
1242 ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME);
1243 actionBar.setHomeButtonEnabled(true);
Mindy Pereira326c6602012-01-04 15:32:42 -08001244 }
1245
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08001246 private void initFromRefMessage(int action) {
1247 setFieldsFromRefMessage(action);
Alice Yang1ebc2db2013-03-14 21:21:44 -07001248
1249 // Check if To: address and email body needs to be prefilled based on extras.
1250 // This is used for reporting rendering feedback.
1251 if (MessageHeaderView.ENABLE_REPORT_RENDERING_PROBLEM) {
1252 Intent intent = getIntent();
1253 if (intent.getExtras() != null) {
1254 String toAddresses = intent.getStringExtra(EXTRA_TO);
1255 if (toAddresses != null) {
1256 addToAddresses(Arrays.asList(TextUtils.split(toAddresses, ",")));
1257 }
1258 String body = intent.getStringExtra(EXTRA_BODY);
1259 if (body != null) {
1260 setBody(body, false /* withSignature */);
1261 }
1262 }
1263 }
1264
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07001265 if (mRefMessage != null) {
1266 // CC field only gets populated when doing REPLY_ALL.
1267 // BCC never gets auto-populated, unless the user is editing
1268 // a draft with one.
Mindy Pereira29a717e2012-07-25 18:05:48 -07001269 if (!TextUtils.isEmpty(mCc.getText()) && action == REPLY_ALL) {
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07001270 mCcBccView.show(false, true, false);
1271 }
1272 }
1273 updateHideOrShowCcBcc();
1274 }
1275
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08001276 private void setFieldsFromRefMessage(int action) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001277 setSubject(mRefMessage, action);
1278 // Setup recipients
1279 if (action == FORWARD) {
1280 mForward = true;
Mindy Pereira6349a042012-01-04 11:25:01 -08001281 }
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08001282 initRecipientsFromRefMessage(mRefMessage, action);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001283 initQuotedTextFromRefMessage(mRefMessage, action);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001284 if (action == ComposeActivity.FORWARD || mAttachmentsChanged) {
1285 initAttachments(mRefMessage);
1286 }
Mindy Pereirac17d0732011-12-29 10:46:19 -08001287 }
1288
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001289 private void initFromDraftMessage(Message message) {
Andy Huang1f8f4dd2012-10-25 21:35:35 -07001290 LogUtils.d(LOG_TAG, "Intializing draft from previous draft message: %s", message);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001291
1292 mDraft = message;
1293 mDraftId = message.id;
1294 mSubject.setText(message.subject);
1295 mForward = message.draftType == UIProvider.DraftType.FORWARD;
Tony Mantler9016a5e2013-07-19 11:54:17 -07001296 final List<String> toAddresses = Arrays.asList(message.getToAddressesUnescaped());
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001297 addToAddresses(toAddresses);
Tony Mantler9016a5e2013-07-19 11:54:17 -07001298 addCcAddresses(Arrays.asList(message.getCcAddressesUnescaped()), toAddresses);
1299 addBccAddresses(Arrays.asList(message.getBccAddressesUnescaped()));
Mindy Pereira2421dc82012-03-27 13:32:31 -07001300 if (message.hasAttachments) {
1301 List<Attachment> attachments = message.getAttachments();
1302 for (Attachment a : attachments) {
Andy Huang5c5fd572012-04-08 18:19:29 -07001303 addAttachmentAndUpdateView(a);
Mindy Pereira2421dc82012-03-27 13:32:31 -07001304 }
1305 }
Mindy Pereiracc8e7db2012-05-30 12:57:42 -07001306 int quotedTextIndex = message.appendRefMessageContent ?
Mindy Pereira002ff522012-05-30 10:31:26 -07001307 message.quotedTextOffset : -1;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001308 // Set the body
Mindy Pereira002ff522012-05-30 10:31:26 -07001309 CharSequence quotedText = null;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001310 if (!TextUtils.isEmpty(message.bodyHtml)) {
Mindy Pereira752222d2012-07-19 09:58:53 -07001311 CharSequence htmlText = "";
Mindy Pereira002ff522012-05-30 10:31:26 -07001312 if (quotedTextIndex > -1) {
Mindy Pereira752222d2012-07-19 09:58:53 -07001313 // Find the offset in the htmltext of the actual quoted text and strip it out.
1314 quotedTextIndex = QuotedTextView.findQuotedTextIndex(message.bodyHtml);
1315 if (quotedTextIndex > -1) {
mindypc59dd822012-11-13 10:56:21 -08001316 htmlText = Utils.convertHtmlToPlainText(message.bodyHtml.substring(0,
1317 quotedTextIndex));
Mindy Pereira752222d2012-07-19 09:58:53 -07001318 quotedText = message.bodyHtml.subSequence(quotedTextIndex,
1319 message.bodyHtml.length());
1320 }
Mindy Pereira1a6e9382012-08-14 15:51:22 -07001321 } else {
mindypc59dd822012-11-13 10:56:21 -08001322 htmlText = Utils.convertHtmlToPlainText(message.bodyHtml);
Mindy Pereira002ff522012-05-30 10:31:26 -07001323 }
1324 mBodyView.setText(htmlText);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001325 } else {
Mindy Pereira752222d2012-07-19 09:58:53 -07001326 final String body = message.bodyText;
1327 final CharSequence bodyText = !TextUtils.isEmpty(body) ?
1328 (quotedTextIndex > -1 ?
1329 message.bodyText.substring(0, quotedTextIndex) : message.bodyText)
1330 : "";
Mindy Pereira002ff522012-05-30 10:31:26 -07001331 if (quotedTextIndex > -1) {
Mindy Pereira752222d2012-07-19 09:58:53 -07001332 quotedText = !TextUtils.isEmpty(body) ? message.bodyText.substring(quotedTextIndex)
1333 : null;
Mindy Pereira002ff522012-05-30 10:31:26 -07001334 }
1335 mBodyView.setText(bodyText);
1336 }
1337 if (quotedTextIndex > -1 && quotedText != null) {
Mindy Pereira39713232012-05-30 11:48:41 -07001338 mQuotedTextView.setQuotedTextFromDraft(quotedText, mForward);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001339 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001340 }
1341
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001342 /**
1343 * Fill all the widgets with the content found in the Intent Extra, if any.
1344 * Also apply the same style to all widgets. Note: if initFromExtras is
1345 * called as a result of switching between reply, reply all, and forward per
1346 * the latest revision of Gmail, and the user has already made changes to
1347 * attachments on a previous incarnation of the message (as a reply, reply
1348 * all, or forward), the original attachments from the message will not be
1349 * re-instantiated. The user's changes will be respected. This follows the
1350 * web gmail interaction.
Andrew Sapperstein746d8612013-08-26 15:56:32 -07001351 * @return {@code true} if the activity should not call {@link #finishSetup}.
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001352 */
Andrew Sapperstein746d8612013-08-26 15:56:32 -07001353 public boolean initFromExtras(Intent intent) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001354 // If we were invoked with a SENDTO intent, the value
1355 // should take precedence
1356 final Uri dataUri = intent.getData();
1357 if (dataUri != null) {
1358 if (MAIL_TO.equals(dataUri.getScheme())) {
1359 initFromMailTo(dataUri.toString());
1360 } else {
Mindy Pereira0b4f28e2012-03-28 14:12:21 -07001361 if (!mAccount.composeIntentUri.equals(dataUri)) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001362 String toText = dataUri.getSchemeSpecificPart();
1363 if (toText != null) {
1364 mTo.setText("");
Mindy Pereiradbe89962012-04-13 09:42:38 -07001365 addToAddresses(Arrays.asList(TextUtils.split(toText, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001366 }
1367 }
1368 }
1369 }
1370
1371 String[] extraStrings = intent.getStringArrayExtra(Intent.EXTRA_EMAIL);
1372 if (extraStrings != null) {
1373 addToAddresses(Arrays.asList(extraStrings));
1374 }
1375 extraStrings = intent.getStringArrayExtra(Intent.EXTRA_CC);
1376 if (extraStrings != null) {
1377 addCcAddresses(Arrays.asList(extraStrings), null);
1378 }
1379 extraStrings = intent.getStringArrayExtra(Intent.EXTRA_BCC);
1380 if (extraStrings != null) {
1381 addBccAddresses(Arrays.asList(extraStrings));
1382 }
1383
1384 String extraString = intent.getStringExtra(Intent.EXTRA_SUBJECT);
1385 if (extraString != null) {
1386 mSubject.setText(extraString);
1387 }
1388
1389 for (String extra : ALL_EXTRAS) {
1390 if (intent.hasExtra(extra)) {
1391 String value = intent.getStringExtra(extra);
1392 if (EXTRA_TO.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001393 addToAddresses(Arrays.asList(TextUtils.split(value, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001394 } else if (EXTRA_CC.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001395 addCcAddresses(Arrays.asList(TextUtils.split(value, ",")), null);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001396 } else if (EXTRA_BCC.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001397 addBccAddresses(Arrays.asList(TextUtils.split(value, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001398 } else if (EXTRA_SUBJECT.equals(extra)) {
1399 mSubject.setText(value);
1400 } else if (EXTRA_BODY.equals(extra)) {
1401 setBody(value, true /* with signature */);
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001402 } else if (EXTRA_QUOTED_TEXT.equals(extra)) {
1403 initQuotedText(value, true /* shouldQuoteText */);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001404 }
1405 }
1406 }
1407
1408 Bundle extras = intent.getExtras();
1409 if (extras != null) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001410 CharSequence text = extras.getCharSequence(Intent.EXTRA_TEXT);
1411 if (text != null) {
1412 setBody(text, true /* with signature */);
1413 }
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001414
1415 // TODO - support EXTRA_HTML_TEXT
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001416 }
Andrew Sapperstein746d8612013-08-26 15:56:32 -07001417
1418 mExtraValues = intent.getParcelableExtra(EXTRA_VALUES);
1419 if (mExtraValues != null) {
1420 LogUtils.d(LOG_TAG, "Launched with extra values: %s", mExtraValues.toString());
1421 initExtraValues(mExtraValues);
1422 return true;
1423 }
1424
1425 return false;
1426 }
1427
1428 protected void initExtraValues(ContentValues extraValues) {
1429 // DO NOTHING - Gmail will override
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001430 }
1431
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001432
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001433 @VisibleForTesting
1434 protected String decodeEmailInUri(String s) throws UnsupportedEncodingException {
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001435 // TODO: handle the case where there are spaces in the display name as
1436 // well as the email such as "Guy with spaces <guy+with+spaces@gmail.com>"
1437 // as they could be encoded ambiguously.
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001438 // Since URLDecode.decode changes + into ' ', and + is a valid
1439 // email character, we need to find/ replace these ourselves before
1440 // decoding.
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001441 try {
Yorke Lee7dd05b12013-04-25 10:04:43 -07001442 return URLDecoder.decode(replacePlus(s), UTF8_ENCODING_NAME);
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001443 } catch (IllegalArgumentException e) {
1444 if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
1445 LogUtils.e(LOG_TAG, "%s while decoding '%s'", e.getMessage(), s);
1446 } else {
1447 LogUtils.e(LOG_TAG, e, "Exception while decoding mailto address");
1448 }
1449 return null;
1450 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001451 }
1452
1453 /**
Yorke Lee7dd05b12013-04-25 10:04:43 -07001454 * Replaces all occurrences of '+' with "%2B", to prevent URLDecode.decode from
1455 * changing '+' into ' '
1456 *
1457 * @param toReplace Input string
1458 * @return The string with all "+" characters replaced with "%2B"
1459 */
Scott Kennedy3b965d72013-06-25 14:36:55 -07001460 private static String replacePlus(String toReplace) {
Yorke Lee7dd05b12013-04-25 10:04:43 -07001461 return toReplace.replace("+", "%2B");
1462 }
1463
1464 /**
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001465 * Initialize the compose view from a String representing a mailTo uri.
1466 * @param mailToString The uri as a string.
1467 */
1468 public void initFromMailTo(String mailToString) {
1469 // We need to disguise this string as a URI in order to parse it
1470 // TODO: Remove this hack when http://b/issue?id=1445295 gets fixed
1471 Uri uri = Uri.parse("foo://" + mailToString);
1472 int index = mailToString.indexOf("?");
1473 int length = "mailto".length() + 1;
1474 String to;
1475 try {
1476 // Extract the recipient after mailto:
1477 if (index == -1) {
1478 to = decodeEmailInUri(mailToString.substring(length));
1479 } else {
1480 to = decodeEmailInUri(mailToString.substring(length, index));
1481 }
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001482 if (!TextUtils.isEmpty(to)) {
1483 addToAddresses(Arrays.asList(TextUtils.split(to, ",")));
1484 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001485 } catch (UnsupportedEncodingException e) {
1486 if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
1487 LogUtils.e(LOG_TAG, "%s while decoding '%s'", e.getMessage(), mailToString);
1488 } else {
1489 LogUtils.e(LOG_TAG, e, "Exception while decoding mailto address");
1490 }
1491 }
1492
1493 List<String> cc = uri.getQueryParameters("cc");
1494 addCcAddresses(Arrays.asList(cc.toArray(new String[cc.size()])), null);
1495
1496 List<String> otherTo = uri.getQueryParameters("to");
1497 addToAddresses(Arrays.asList(otherTo.toArray(new String[otherTo.size()])));
1498
1499 List<String> bcc = uri.getQueryParameters("bcc");
1500 addBccAddresses(Arrays.asList(bcc.toArray(new String[bcc.size()])));
1501
1502 List<String> subject = uri.getQueryParameters("subject");
1503 if (subject.size() > 0) {
1504 try {
Yorke Lee7dd05b12013-04-25 10:04:43 -07001505 mSubject.setText(URLDecoder.decode(replacePlus(subject.get(0)),
1506 UTF8_ENCODING_NAME));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001507 } catch (UnsupportedEncodingException e) {
1508 LogUtils.e(LOG_TAG, "%s while decoding subject '%s'",
1509 e.getMessage(), subject);
1510 }
1511 }
1512
1513 List<String> body = uri.getQueryParameters("body");
1514 if (body.size() > 0) {
1515 try {
Yorke Lee7dd05b12013-04-25 10:04:43 -07001516 setBody(URLDecoder.decode(replacePlus(body.get(0)), UTF8_ENCODING_NAME),
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001517 true /* with signature */);
1518 } catch (UnsupportedEncodingException e) {
1519 LogUtils.e(LOG_TAG, "%s while decoding body '%s'", e.getMessage(), body);
1520 }
1521 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001522 }
1523
Mindy Pereirabddd6f32012-06-20 12:10:03 -07001524 @VisibleForTesting
1525 protected void initAttachments(Message refMessage) {
Mark Wei434f2942012-08-24 11:54:02 -07001526 addAttachments(refMessage.getAttachments());
1527 }
1528
1529 public long addAttachments(List<Attachment> attachments) {
1530 long size = 0;
1531 AttachmentFailureException error = null;
1532 for (Attachment a : attachments) {
1533 try {
1534 size += mAttachmentsView.addAttachment(mAccount, a);
1535 } catch (AttachmentFailureException e) {
1536 error = e;
1537 }
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001538 }
Mark Wei434f2942012-08-24 11:54:02 -07001539 if (error != null) {
1540 LogUtils.e(LOG_TAG, error, "Error adding attachment");
1541 if (attachments.size() > 1) {
1542 showAttachmentTooBigToast(R.string.too_large_to_attach_multiple);
1543 } else {
1544 showAttachmentTooBigToast(error.getErrorRes());
1545 }
1546 }
1547 return size;
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001548 }
1549
1550 /**
1551 * When an attachment is too large to be added to a message, show a toast.
1552 * This method also updates the position of the toast so that it is shown
1553 * clearly above they keyboard if it happens to be open.
1554 */
Mark Wei434f2942012-08-24 11:54:02 -07001555 private void showAttachmentTooBigToast(int errorRes) {
1556 String maxSize = AttachmentUtils.convertToHumanReadableSize(
1557 getApplicationContext(), mAccount.settings.getMaxAttachmentSize());
1558 showErrorToast(getString(errorRes, maxSize));
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001559 }
1560
Mark Wei434f2942012-08-24 11:54:02 -07001561 private void showErrorToast(String message) {
1562 Toast t = Toast.makeText(this, message, Toast.LENGTH_LONG);
1563 t.setText(message);
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001564 t.setGravity(Gravity.CENTER_HORIZONTAL, 0,
1565 getResources().getDimensionPixelSize(R.dimen.attachment_toast_yoffset));
1566 t.show();
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001567 }
1568
Paul Westbrookf97588b2012-03-20 11:11:37 -07001569 private void initAttachmentsFromIntent(Intent intent) {
Paul Westbrook03ee9712012-04-02 09:51:51 -07001570 Bundle extras = intent.getExtras();
1571 if (extras == null) {
1572 extras = Bundle.EMPTY;
1573 }
Paul Westbrookf97588b2012-03-20 11:11:37 -07001574 final String action = intent.getAction();
1575 if (!mAttachmentsChanged) {
1576 long totalSize = 0;
1577 if (extras.containsKey(EXTRA_ATTACHMENTS)) {
1578 String[] uris = (String[]) extras.getSerializable(EXTRA_ATTACHMENTS);
1579 for (String uriString : uris) {
1580 final Uri uri = Uri.parse(uriString);
1581 long size = 0;
1582 try {
Andy Huange003b4c2013-08-16 10:32:05 -07001583 final Attachment a = mAttachmentsView.generateLocalAttachment(uri);
1584 size = mAttachmentsView.addAttachment(mAccount, a);
1585
1586 Analytics.getInstance().sendEvent("send_intent_attachment",
1587 Utils.normalizeMimeType(a.getContentType()), null, size);
1588
Paul Westbrookf97588b2012-03-20 11:11:37 -07001589 } catch (AttachmentFailureException e) {
Paul Westbrookf97588b2012-03-20 11:11:37 -07001590 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Mark Wei434f2942012-08-24 11:54:02 -07001591 showAttachmentTooBigToast(e.getErrorRes());
Paul Westbrookf97588b2012-03-20 11:11:37 -07001592 }
1593 totalSize += size;
1594 }
1595 }
mindyp9a9e8d62012-10-03 12:24:07 -07001596 if (extras.containsKey(Intent.EXTRA_STREAM)) {
1597 if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
1598 ArrayList<Parcelable> uris = extras
1599 .getParcelableArrayList(Intent.EXTRA_STREAM);
1600 ArrayList<Attachment> attachments = new ArrayList<Attachment>();
1601 for (Parcelable uri : uris) {
1602 try {
Andy Huange003b4c2013-08-16 10:32:05 -07001603 final Attachment a = mAttachmentsView.generateLocalAttachment(
1604 (Uri) uri);
1605 attachments.add(a);
1606
1607 Analytics.getInstance().sendEvent("send_intent_attachment",
1608 Utils.normalizeMimeType(a.getContentType()), null, a.size);
1609
mindyp9a9e8d62012-10-03 12:24:07 -07001610 } catch (AttachmentFailureException e) {
1611 LogUtils.e(LOG_TAG, e, "Error adding attachment");
1612 String maxSize = AttachmentUtils.convertToHumanReadableSize(
1613 getApplicationContext(),
1614 mAccount.settings.getMaxAttachmentSize());
1615 showErrorToast(getString
1616 (R.string.generic_attachment_problem, maxSize));
1617 }
1618 }
1619 totalSize += addAttachments(attachments);
1620 } else {
1621 final Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
1622 long size = 0;
Paul Westbrookf97588b2012-03-20 11:11:37 -07001623 try {
Andy Huange003b4c2013-08-16 10:32:05 -07001624 final Attachment a = mAttachmentsView.generateLocalAttachment(uri);
1625 size = mAttachmentsView.addAttachment(mAccount, a);
1626
1627 Analytics.getInstance().sendEvent("send_intent_attachment",
1628 Utils.normalizeMimeType(a.getContentType()), null, size);
1629
Paul Westbrookf97588b2012-03-20 11:11:37 -07001630 } catch (AttachmentFailureException e) {
Paul Westbrookf97588b2012-03-20 11:11:37 -07001631 LogUtils.e(LOG_TAG, e, "Error adding attachment");
mindyp9a9e8d62012-10-03 12:24:07 -07001632 showAttachmentTooBigToast(e.getErrorRes());
Paul Westbrookf97588b2012-03-20 11:11:37 -07001633 }
mindyp9a9e8d62012-10-03 12:24:07 -07001634 totalSize += size;
Paul Westbrookf97588b2012-03-20 11:11:37 -07001635 }
1636 }
1637
1638 if (totalSize > 0) {
1639 mAttachmentsChanged = true;
1640 updateSaveUi();
Andy Huange003b4c2013-08-16 10:32:05 -07001641
1642 Analytics.getInstance().sendEvent("send_intent_with_attachments",
1643 Integer.toString(getAttachments().size()), null, totalSize);
Paul Westbrookf97588b2012-03-20 11:11:37 -07001644 }
1645 }
1646 }
1647
Andrew Sapperstein746d8612013-08-26 15:56:32 -07001648 protected void initQuotedText(CharSequence quotedText, boolean shouldQuoteText) {
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001649 mQuotedTextView.setQuotedTextFromHtml(quotedText, shouldQuoteText);
1650 mShowQuotedText = true;
1651 }
Paul Westbrookf97588b2012-03-20 11:11:37 -07001652
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001653 private void initQuotedTextFromRefMessage(Message refMessage, int action) {
1654 if (mRefMessage != null && (action == REPLY || action == REPLY_ALL || action == FORWARD)) {
Mindy Pereira9932dee2012-01-10 16:09:50 -08001655 mQuotedTextView.setQuotedText(action, refMessage, action != FORWARD);
1656 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001657 }
1658
1659 private void updateHideOrShowCcBcc() {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001660 // Its possible there is a menu item OR a button.
Mindy Pereira326689d2012-05-17 10:14:14 -07001661 boolean ccVisible = mCcBccView.isCcVisible();
1662 boolean bccVisible = mCcBccView.isBccVisible();
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001663 if (mCcBccButton != null) {
Mindy Pereira326689d2012-05-17 10:14:14 -07001664 if (!ccVisible || !bccVisible) {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001665 mCcBccButton.setVisibility(View.VISIBLE);
Mindy Pereira326689d2012-05-17 10:14:14 -07001666 mCcBccButton.setText(getString(!ccVisible ? R.string.add_cc_label
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001667 : R.string.add_bcc_label));
1668 } else {
mindypcd0b0b92012-08-23 14:33:17 -07001669 mCcBccButton.setVisibility(View.INVISIBLE);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001670 }
1671 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001672 }
1673
Mindy Pereiraa34c9a02012-04-17 14:10:53 -07001674 private void showCcBcc(Bundle state) {
Mindy Pereira326689d2012-05-17 10:14:14 -07001675 if (state != null && state.containsKey(EXTRA_SHOW_CC)) {
1676 boolean showCc = state.getBoolean(EXTRA_SHOW_CC);
1677 boolean showBcc = state.getBoolean(EXTRA_SHOW_BCC);
1678 if (showCc || showBcc) {
1679 mCcBccView.show(false, showCc, showBcc);
Mindy Pereira6faeedf2012-04-18 16:11:39 -07001680 }
Mindy Pereiraa34c9a02012-04-17 14:10:53 -07001681 }
1682 }
1683
Mindy Pereira013194c2012-01-06 15:09:33 -08001684 /**
1685 * Add attachment and update the compose area appropriately.
1686 * @param data
1687 */
1688 public void addAttachmentAndUpdateView(Intent data) {
Andrew Sapperstein05089f32013-10-01 17:00:03 -07001689 if (data == null) {
1690 return;
1691 }
1692
1693 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
1694 final ClipData clipData = data.getClipData();
1695 if (clipData != null) {
1696 for (int i = 0, size = clipData.getItemCount(); i < size; i++) {
1697 addAttachmentAndUpdateView(clipData.getItemAt(i).getUri());
1698 }
1699 return;
1700 }
1701 }
1702
1703 addAttachmentAndUpdateView(data.getData());
Mindy Pereira2421dc82012-03-27 13:32:31 -07001704 }
1705
Andy Huang5c5fd572012-04-08 18:19:29 -07001706 public void addAttachmentAndUpdateView(Uri contentUri) {
1707 if (contentUri == null) {
Mindy Pereira2421dc82012-03-27 13:32:31 -07001708 return;
1709 }
Mindy Pereira013194c2012-01-06 15:09:33 -08001710 try {
Andy Huang5c5fd572012-04-08 18:19:29 -07001711 addAttachmentAndUpdateView(mAttachmentsView.generateLocalAttachment(contentUri));
1712 } catch (AttachmentFailureException e) {
Andy Huang5c5fd572012-04-08 18:19:29 -07001713 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Mark Wei434f2942012-08-24 11:54:02 -07001714 showErrorToast(getResources().getString(
1715 e.getErrorRes(),
1716 AttachmentUtils.convertToHumanReadableSize(
1717 getApplicationContext(), mAccount.settings.getMaxAttachmentSize())));
Andy Huang5c5fd572012-04-08 18:19:29 -07001718 }
1719 }
1720
1721 public void addAttachmentAndUpdateView(Attachment attachment) {
1722 try {
Mark Wei434f2942012-08-24 11:54:02 -07001723 long size = mAttachmentsView.addAttachment(mAccount, attachment);
Mindy Pereira9932dee2012-01-10 16:09:50 -08001724 if (size > 0) {
1725 mAttachmentsChanged = true;
1726 updateSaveUi();
Mindy Pereira013194c2012-01-06 15:09:33 -08001727 }
Mindy Pereira9932dee2012-01-10 16:09:50 -08001728 } catch (AttachmentFailureException e) {
Mindy Pereira9932dee2012-01-10 16:09:50 -08001729 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Mark Wei434f2942012-08-24 11:54:02 -07001730 showAttachmentTooBigToast(e.getErrorRes());
Mindy Pereira013194c2012-01-06 15:09:33 -08001731 }
1732 }
1733
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08001734 void initRecipientsFromRefMessage(Message refMessage, int action) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001735 // Don't populate the address if this is a forward.
1736 if (action == ComposeActivity.FORWARD) {
1737 return;
1738 }
Scott Kennedyff8553f2013-04-05 20:57:44 -07001739 initReplyRecipients(refMessage, action);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001740 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001741
Paul Westbrook6d2442b2013-07-17 17:51:51 -07001742 // TODO: This should be private. This method shouldn't be used by ComposeActivityTests, as
1743 // it doesn't setup the state of the activity correctly
Mindy Pereira818143e2012-01-11 13:59:49 -08001744 @VisibleForTesting
Scott Kennedyff8553f2013-04-05 20:57:44 -07001745 void initReplyRecipients(final Message refMessage, final int action) {
Tony Mantler9016a5e2013-07-19 11:54:17 -07001746 String[] sentToAddresses = refMessage.getToAddressesUnescaped();
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001747 final Collection<String> toAddresses;
Tony Mantler89de9eb2013-07-25 11:43:58 -07001748 final String[] fromAddresses = refMessage.getFromAddressesUnescaped();
1749 final String fromAddress = fromAddresses.length > 0 ? fromAddresses[0] : null;
Andy Huange2af8872014-01-16 12:36:27 -08001750 final String[] replyToAddresses = getReplyToAddresses(
1751 refMessage.getReplyToAddressesUnescaped(), fromAddress);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001752
1753 // If this is a reply, the Cc list is empty. If this is a reply-all, the
1754 // Cc list is the union of the To and Cc recipients of the original
1755 // message, excluding the current user's email address and any addresses
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001756 // already on the To list.
1757 if (action == ComposeActivity.REPLY) {
Tony Mantler24f116f2014-01-16 10:20:50 -08001758 toAddresses = initToRecipients(fromAddress, replyToAddresses, sentToAddresses);
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001759 addToAddresses(toAddresses);
1760 } else if (action == ComposeActivity.REPLY_ALL) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001761 final Set<String> ccAddresses = Sets.newHashSet();
Tony Mantler24f116f2014-01-16 10:20:50 -08001762 toAddresses = initToRecipients(fromAddress, replyToAddresses, sentToAddresses);
Mindy Pereira154386a2012-01-11 13:02:33 -08001763 addToAddresses(toAddresses);
Scott Kennedyff8553f2013-04-05 20:57:44 -07001764 addRecipients(ccAddresses, sentToAddresses);
Tony Mantler9016a5e2013-07-19 11:54:17 -07001765 addRecipients(ccAddresses, refMessage.getCcAddressesUnescaped());
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001766 addCcAddresses(ccAddresses, toAddresses);
1767 }
1768 }
1769
Andy Huange2af8872014-01-16 12:36:27 -08001770 // If there is no reply to address, the reply to address is the sender.
1771 private static String[] getReplyToAddresses(String[] replyTo, String from) {
1772 boolean hasReplyTo = false;
1773 for (final String replyToAddress : replyTo) {
1774 if (!TextUtils.isEmpty(replyToAddress)) {
1775 hasReplyTo = true;
1776 }
1777 }
1778 return hasReplyTo ? replyTo : new String[] {from};
1779 }
1780
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001781 private void addToAddresses(Collection<String> addresses) {
1782 addAddressesToList(addresses, mTo);
1783 }
1784
1785 private void addCcAddresses(Collection<String> addresses, Collection<String> toAddresses) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001786 addCcAddressesToList(tokenizeAddressList(addresses),
1787 toAddresses != null ? tokenizeAddressList(toAddresses) : null, mCc);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001788 }
1789
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001790 private void addBccAddresses(Collection<String> addresses) {
1791 addAddressesToList(addresses, mBcc);
1792 }
1793
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001794 @VisibleForTesting
1795 protected void addCcAddressesToList(List<Rfc822Token[]> addresses,
1796 List<Rfc822Token[]> compareToList, RecipientEditTextView list) {
1797 String address;
1798
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001799 if (compareToList == null) {
1800 for (Rfc822Token[] tokens : addresses) {
1801 for (int i = 0; i < tokens.length; i++) {
1802 address = tokens[i].toString();
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001803 list.append(address + END_TOKEN);
1804 }
1805 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001806 } else {
1807 HashSet<String> compareTo = convertToHashSet(compareToList);
1808 for (Rfc822Token[] tokens : addresses) {
1809 for (int i = 0; i < tokens.length; i++) {
1810 address = tokens[i].toString();
1811 // Check if this is a duplicate:
1812 if (!compareTo.contains(tokens[i].getAddress())) {
1813 // Get the address here
1814 list.append(address + END_TOKEN);
1815 }
1816 }
1817 }
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001818 }
1819 }
1820
Scott Kennedyff8553f2013-04-05 20:57:44 -07001821 private static HashSet<String> convertToHashSet(final List<Rfc822Token[]> list) {
1822 final HashSet<String> hash = new HashSet<String>();
1823 for (final Rfc822Token[] tokens : list) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001824 for (int i = 0; i < tokens.length; i++) {
1825 hash.add(tokens[i].getAddress());
1826 }
1827 }
1828 return hash;
1829 }
1830
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001831 protected List<Rfc822Token[]> tokenizeAddressList(Collection<String> addresses) {
1832 @VisibleForTesting
1833 List<Rfc822Token[]> tokenized = new ArrayList<Rfc822Token[]>();
1834
1835 for (String address: addresses) {
1836 tokenized.add(Rfc822Tokenizer.tokenize(address));
1837 }
1838 return tokenized;
1839 }
1840
1841 @VisibleForTesting
1842 void addAddressesToList(Collection<String> addresses, RecipientEditTextView list) {
1843 for (String address : addresses) {
1844 addAddressToList(address, list);
1845 }
1846 }
1847
Scott Kennedyff8553f2013-04-05 20:57:44 -07001848 private static void addAddressToList(final String address, final RecipientEditTextView list) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001849 if (address == null || list == null)
1850 return;
1851
Scott Kennedyff8553f2013-04-05 20:57:44 -07001852 final Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(address);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001853
1854 for (int i = 0; i < tokens.length; i++) {
1855 list.append(tokens[i] + END_TOKEN);
1856 }
1857 }
1858
1859 @VisibleForTesting
Scott Kennedyff8553f2013-04-05 20:57:44 -07001860 protected Collection<String> initToRecipients(final String fullSenderAddress,
Tony Mantler24f116f2014-01-16 10:20:50 -08001861 final String[] replyToAddresses, final String[] inToAddresses) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001862 // The To recipient is the reply-to address specified in the original
1863 // message, unless it is:
1864 // the current user OR a custom from of the current user, in which case
1865 // it's the To recipient list of the original message.
1866 // OR missing, in which case use the sender of the original message
1867 Set<String> toAddresses = Sets.newHashSet();
Tony Mantler24f116f2014-01-16 10:20:50 -08001868 for (final String replyToAddress : replyToAddresses) {
1869 if (!TextUtils.isEmpty(replyToAddress)
1870 && !recipientMatchesThisAccount(replyToAddress)) {
1871 toAddresses.add(replyToAddress);
1872 }
1873 }
1874 if (toAddresses.size() == 0) {
mindyp65b06f52012-11-21 10:35:08 -08001875 // In this case, the user is replying to a message in which their
Tony Mantler24f116f2014-01-16 10:20:50 -08001876 // current account or some of their custom from addresses are the only
1877 // recipients and they sent the original message.
mindyp65b06f52012-11-21 10:35:08 -08001878 if (inToAddresses.length == 1 && recipientMatchesThisAccount(fullSenderAddress)
1879 && recipientMatchesThisAccount(inToAddresses[0])) {
1880 toAddresses.add(inToAddresses[0]);
1881 return toAddresses;
1882 }
1883 // This happens if the user replies to a message they originally
1884 // wrote. In this case, "reply" really means "re-send," so we
1885 // target the original recipients. This works as expected even
1886 // if the user sent the original message to themselves.
1887 for (String address : inToAddresses) {
1888 if (!recipientMatchesThisAccount(address)) {
1889 toAddresses.add(address);
mindypfe8557b2012-11-05 12:05:16 -08001890 }
Mindy Pereira1469b4e2012-06-19 19:18:54 -07001891 }
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001892 }
1893 return toAddresses;
1894 }
1895
Scott Kennedyff8553f2013-04-05 20:57:44 -07001896 private void addRecipients(final Set<String> recipients, final String[] addresses) {
1897 for (final String email : addresses) {
Mindy Pereiracecc54a2012-07-31 09:38:11 -07001898 // Do not add this account, or any of its custom from addresses, to
1899 // the list of recipients.
Mindy Pereira4a20b702012-01-05 16:24:24 -08001900 final String recipientAddress = Address.getEmailAddress(email).getAddress();
mindyp5ee5d692012-11-19 16:02:16 -08001901 if (!recipientMatchesThisAccount(recipientAddress)) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001902 recipients.add(email.replace("\"\"", ""));
1903 }
1904 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001905 }
1906
Mindy Pereiracecc54a2012-07-31 09:38:11 -07001907 /**
1908 * A recipient matches this account if it has the same address as the
1909 * currently selected account OR one of the custom from addresses associated
1910 * with the currently selected account.
Mindy Pereiracecc54a2012-07-31 09:38:11 -07001911 * @param recipientAddress address we are comparing with the currently selected account
1912 * @return
1913 */
mindyp5ee5d692012-11-19 16:02:16 -08001914 protected boolean recipientMatchesThisAccount(String recipientAddress) {
1915 return ReplyFromAccount.matchesAccountOrCustomFrom(mAccount, recipientAddress,
mindypfe8557b2012-11-05 12:05:16 -08001916 mAccount.getReplyFroms());
Mindy Pereiracecc54a2012-07-31 09:38:11 -07001917 }
1918
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001919 /**
1920 * Returns a formatted subject string with the appropriate prefix for the action type.
1921 * E.g., "FWD: " is prepended if action is {@link ComposeActivity#FORWARD}.
1922 */
Tony Mantlera954f992013-12-03 11:22:56 -08001923 public static String buildFormattedSubject(final Resources res, final String subject,
1924 final int action) {
1925 final String prefix;
1926 final String correctedSubject;
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001927 if (action == ComposeActivity.COMPOSE) {
1928 prefix = "";
1929 } else if (action == ComposeActivity.FORWARD) {
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001930 prefix = res.getString(R.string.forward_subject_label);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001931 } else {
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001932 prefix = res.getString(R.string.reply_subject_label);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001933 }
1934
1935 // Don't duplicate the prefix
Mindy Pereirac7a36992012-07-30 14:00:37 -07001936 if (!TextUtils.isEmpty(subject)
1937 && subject.toLowerCase().startsWith(prefix.toLowerCase())) {
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001938 correctedSubject = subject;
1939 } else {
Tony Mantlera954f992013-12-03 11:22:56 -08001940 final String subjectOrNoSubject = TextUtils.isEmpty(subject) ?
1941 res.getString(R.string.no_subject) :
1942 subject;
1943
1944 correctedSubject =
1945 res.getString(R.string.formatted_subject, prefix, subjectOrNoSubject);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001946 }
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07001947
1948 return correctedSubject;
1949 }
1950
1951 private void setSubject(Message refMessage, int action) {
1952 mSubject.setText(buildFormattedSubject(getResources(), refMessage.subject, action));
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001953 }
1954
Mindy Pereira818143e2012-01-11 13:59:49 -08001955 private void initRecipients() {
1956 setupRecipients(mTo);
1957 setupRecipients(mCc);
1958 setupRecipients(mBcc);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001959 }
1960
Mindy Pereira818143e2012-01-11 13:59:49 -08001961 private void setupRecipients(RecipientEditTextView view) {
Paul Westbrook679a8cc2012-02-21 16:37:58 -08001962 view.setAdapter(new RecipientAdapter(this, mAccount));
Mindy Pereira82cc5662012-01-09 17:29:30 -08001963 if (mValidator == null) {
Tony Mantler79b11562013-10-09 15:31:50 -07001964 final String accountName = mAccount.getEmailAddress();
Mindy Pereira33fe9082012-01-09 16:24:30 -08001965 int offset = accountName.indexOf("@") + 1;
1966 String account = accountName;
Tony Mantler79b11562013-10-09 15:31:50 -07001967 if (offset > 0) {
1968 account = account.substring(offset);
Mindy Pereirac17d0732011-12-29 10:46:19 -08001969 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001970 mValidator = new Rfc822Validator(account);
Mindy Pereirac17d0732011-12-29 10:46:19 -08001971 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001972 view.setValidator(mValidator);
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001973 }
1974
1975 @Override
1976 public void onClick(View v) {
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07001977 final int id = v.getId();
1978 if (id == R.id.add_cc_bcc) {
1979 // Verify that cc/ bcc aren't showing.
1980 // Animate in cc/bcc.
1981 showCcBccViews();
Andrew Sapperstein6aea7862013-10-24 19:59:51 -07001982 } else if (id == R.id.add_attachment) {
1983 doAttach(Utils.isRunningKitkatOrLater() ? MIME_TYPE_ALL : MIME_TYPE_PHOTO);
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001984 }
1985 }
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001986
1987 @Override
1988 public boolean onCreateOptionsMenu(Menu menu) {
Tony Mantler5b8799a2013-10-31 10:43:03 -07001989 final boolean superCreated = super.onCreateOptionsMenu(menu);
Mindy Pereirab199d172012-08-13 11:04:03 -07001990 // Don't render any menu items when there are no accounts.
1991 if (mAccounts == null || mAccounts.length == 0) {
Tony Mantler5b8799a2013-10-31 10:43:03 -07001992 return superCreated;
Mindy Pereirab199d172012-08-13 11:04:03 -07001993 }
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001994 MenuInflater inflater = getMenuInflater();
1995 inflater.inflate(R.menu.compose_menu, menu);
mindyp1d7e9142012-11-21 13:54:30 -08001996
1997 /*
1998 * Start save in the correct enabled state.
1999 * 1) If a user launches compose from within gmail, save is disabled
2000 * until they add something, at which point, save is enabled, auto save
2001 * on exit; if the user empties everything, save is disabled, exiting does not
2002 * auto-save
2003 * 2) if a user replies/ reply all/ forwards from within gmail, save is
2004 * disabled until they change something, at which point, save is
2005 * enabled, auto save on exit; if the user empties everything, save is
2006 * disabled, exiting does not auto-save.
2007 * 3) If a user launches compose from another application and something
2008 * gets populated (attachments, recipients, body, subject, etc), save is
2009 * enabled, auto save on exit; if the user empties everything, save is
2010 * disabled, exiting does not auto-save
2011 */
Mindy Pereira82cc5662012-01-09 17:29:30 -08002012 mSave = menu.findItem(R.id.save);
mindyp1d7e9142012-11-21 13:54:30 -08002013 String action = getIntent() != null ? getIntent().getAction() : null;
Andy Huang9f855d62013-05-30 17:15:03 -07002014 enableSave(mInnerSavedState != null ?
2015 mInnerSavedState.getBoolean(EXTRA_SAVE_ENABLED)
mindyp1d7e9142012-11-21 13:54:30 -08002016 : (Intent.ACTION_SEND.equals(action)
2017 || Intent.ACTION_SEND_MULTIPLE.equals(action)
2018 || Intent.ACTION_SENDTO.equals(action)
2019 || shouldSave()));
2020
Mindy Pereira3ca5bad2012-04-16 11:02:42 -07002021 MenuItem helpItem = menu.findItem(R.id.help_info_menu_item);
2022 MenuItem sendFeedbackItem = menu.findItem(R.id.feedback_menu_item);
2023 if (helpItem != null) {
2024 helpItem.setVisible(mAccount != null
2025 && mAccount.supportsCapability(AccountCapabilities.HELP_CONTENT));
2026 }
2027 if (sendFeedbackItem != null) {
2028 sendFeedbackItem.setVisible(mAccount != null
2029 && mAccount.supportsCapability(AccountCapabilities.SEND_FEEDBACK));
2030 }
Andrew Sapperstein5cb71802013-10-01 18:31:20 -07002031
Andrew Sapperstein8809f9f2013-10-11 16:13:35 -07002032 // Show attach picture on pre-K devices.
2033 menu.findItem(R.id.add_photo_attachment).setVisible(!Utils.isRunningKitkatOrLater());
Andrew Sapperstein5cb71802013-10-01 18:31:20 -07002034
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002035 return true;
2036 }
2037
2038 @Override
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08002039 public boolean onPrepareOptionsMenu(Menu menu) {
2040 MenuItem ccBcc = menu.findItem(R.id.add_cc_bcc);
Mindy Pereira818143e2012-01-11 13:59:49 -08002041 if (ccBcc != null && mCc != null) {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08002042 // Its possible there is a menu item OR a button.
2043 boolean ccFieldVisible = mCc.isShown();
2044 boolean bccFieldVisible = mBcc.isShown();
2045 if (!ccFieldVisible || !bccFieldVisible) {
2046 ccBcc.setVisible(true);
2047 ccBcc.setTitle(getString(!ccFieldVisible ? R.string.add_cc_label
2048 : R.string.add_bcc_label));
2049 } else {
2050 ccBcc.setVisible(false);
2051 }
2052 }
2053 return true;
2054 }
2055
2056 @Override
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002057 public boolean onOptionsItemSelected(MenuItem item) {
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002058 final int id = item.getItemId();
Andy Huangdc97bf42013-08-15 16:52:45 -07002059
2060 Analytics.getInstance().sendMenuItemEvent(Analytics.EVENT_CATEGORY_MENU_ITEM, id, null, 0);
2061
Mindy Pereira75f66632012-01-11 11:42:02 -08002062 boolean handled = true;
Andrew Sapperstein5cb71802013-10-01 18:31:20 -07002063 if (id == R.id.add_file_attachment) {
2064 doAttach(MIME_TYPE_ALL);
2065 } else if (id == R.id.add_photo_attachment) {
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002066 doAttach(MIME_TYPE_PHOTO);
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002067 } else if (id == R.id.add_cc_bcc) {
2068 showCcBccViews();
2069 } else if (id == R.id.save) {
2070 doSave(true);
2071 } else if (id == R.id.send) {
2072 doSend();
2073 } else if (id == R.id.discard) {
2074 doDiscard();
2075 } else if (id == R.id.settings) {
2076 Utils.showSettings(this, mAccount);
2077 } else if (id == android.R.id.home) {
2078 onAppUpPressed();
2079 } else if (id == R.id.help_info_menu_item) {
2080 Utils.showHelp(this, mAccount, getString(R.string.compose_help_context));
2081 } else if (id == R.id.feedback_menu_item) {
2082 Utils.sendFeedback(this, mAccount, false);
2083 } else {
2084 handled = false;
Mindy Pereirab47f3e22011-12-13 14:25:04 -08002085 }
2086 return !handled ? super.onOptionsItemSelected(item) : handled;
2087 }
Mindy Pereira326c6602012-01-04 15:32:42 -08002088
Mindy Pereirab199d172012-08-13 11:04:03 -07002089 @Override
2090 public void onBackPressed() {
2091 // If we are showing the wait fragment, just exit.
2092 if (getWaitFragment() != null) {
2093 finish();
2094 } else {
2095 super.onBackPressed();
2096 }
2097 }
2098
Vikram Aggarwal1672ff82012-09-21 10:15:22 -07002099 /**
2100 * Carries out the "up" action in the action bar.
2101 */
Paul Westbrookdaecb4b2012-05-31 10:21:26 -07002102 private void onAppUpPressed() {
2103 if (mLaunchedFromEmail) {
2104 // If this was started from Gmail, simply treat app up as the system back button, so
2105 // that the last view is restored.
2106 onBackPressed();
2107 return;
2108 }
2109
2110 // Fire the main activity to ensure it launches the "top" screen of mail.
2111 // Since the main Activity is singleTask, it should revive that task if it was already
2112 // started.
Vikram Aggarwal0c3c2052012-09-21 11:06:28 -07002113 final Intent mailIntent = Utils.createViewInboxIntent(mAccount);
Paul Westbrookdaecb4b2012-05-31 10:21:26 -07002114 mailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |
2115 Intent.FLAG_ACTIVITY_TASK_ON_HOME);
2116 startActivity(mailIntent);
2117 finish();
2118 }
2119
Mindy Pereira33fe9082012-01-09 16:24:30 -08002120 private void doSend() {
Mark Weidd19b632012-10-19 13:59:28 -07002121 sendOrSaveWithSanityChecks(false, true, false, false);
Andy Huangdc97bf42013-08-15 16:52:45 -07002122 logSendOrSave(false /* save */);
2123 mPerformedSendOrDiscard = true;
Mindy Pereira33fe9082012-01-09 16:24:30 -08002124 }
2125
Mindy Pereira48e31b02012-05-30 13:12:24 -07002126 private void doSave(boolean showToast) {
Mark Weidd19b632012-10-19 13:59:28 -07002127 sendOrSaveWithSanityChecks(true, showToast, false, false);
Mindy Pereira48e31b02012-05-30 13:12:24 -07002128 }
2129
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002130 @VisibleForTesting
2131 public interface SendOrSaveCallback {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002132 public void initializeSendOrSave(SendOrSaveTask sendOrSaveTask);
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002133 public void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage, Message message);
2134 public Message getMessage();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002135 public void sendOrSaveFinished(SendOrSaveTask sendOrSaveTask, boolean success);
2136 }
2137
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002138 @VisibleForTesting
2139 public static class SendOrSaveTask implements Runnable {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002140 private final Context mContext;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002141 @VisibleForTesting
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002142 public final SendOrSaveCallback mSendOrSaveCallback;
2143 @VisibleForTesting
2144 public final SendOrSaveMessage mSendOrSaveMessage;
mindyp44a63392012-11-05 12:05:16 -08002145 private ReplyFromAccount mExistingDraftAccount;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002146
2147 public SendOrSaveTask(Context context, SendOrSaveMessage message,
mindyp44a63392012-11-05 12:05:16 -08002148 SendOrSaveCallback callback, ReplyFromAccount draftAccount) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002149 mContext = context;
2150 mSendOrSaveCallback = callback;
2151 mSendOrSaveMessage = message;
mindyp44a63392012-11-05 12:05:16 -08002152 mExistingDraftAccount = draftAccount;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002153 }
2154
2155 @Override
2156 public void run() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002157 final SendOrSaveMessage sendOrSaveMessage = mSendOrSaveMessage;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002158
Mindy Pereira92551d02012-04-05 11:31:12 -07002159 final ReplyFromAccount selectedAccount = sendOrSaveMessage.mAccount;
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002160 Message message = mSendOrSaveCallback.getMessage();
2161 long messageId = message != null ? message.id : UIProvider.INVALID_MESSAGE_ID;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002162 // If a previous draft has been saved, in an account that is different
2163 // than what the user wants to send from, remove the old draft, and treat this
2164 // as a new message
mindyp44a63392012-11-05 12:05:16 -08002165 if (mExistingDraftAccount != null
2166 && !selectedAccount.account.uri.equals(mExistingDraftAccount.account.uri)) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002167 if (messageId != UIProvider.INVALID_MESSAGE_ID) {
2168 ContentResolver resolver = mContext.getContentResolver();
2169 ContentValues values = new ContentValues();
2170 values.put(BaseColumns._ID, messageId);
mindypfebd2262012-11-13 17:45:09 -08002171 if (mExistingDraftAccount.account.expungeMessageUri != null) {
2172 new ContentProviderTask.UpdateTask()
2173 .run(resolver, mExistingDraftAccount.account.expungeMessageUri,
2174 values, null, null);
Mindy Pereiracfb7f332012-02-28 10:23:43 -08002175 } else {
2176 // TODO(mindyp) delete the conversation.
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002177 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002178 // reset messageId to 0, so a new message will be created
2179 messageId = UIProvider.INVALID_MESSAGE_ID;
2180 }
2181 }
2182
2183 final long messageIdToSave = messageId;
Scott Kennedyff8553f2013-04-05 20:57:44 -07002184 sendOrSaveMessage(messageIdToSave, sendOrSaveMessage, selectedAccount);
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002185
2186 if (!sendOrSaveMessage.mSave) {
Tony Mantler9f324232013-08-08 14:24:30 -07002187 incrementRecipientsTimesContacted(mContext,
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002188 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.TO));
Tony Mantler9f324232013-08-08 14:24:30 -07002189 incrementRecipientsTimesContacted(mContext,
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002190 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.CC));
Tony Mantler9f324232013-08-08 14:24:30 -07002191 incrementRecipientsTimesContacted(mContext,
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002192 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.BCC));
2193 }
2194 mSendOrSaveCallback.sendOrSaveFinished(SendOrSaveTask.this, true);
2195 }
2196
Tony Mantler9f324232013-08-08 14:24:30 -07002197 private static void incrementRecipientsTimesContacted(final Context context,
2198 final String addressString) {
2199 if (TextUtils.isEmpty(addressString)) {
2200 return;
2201 }
2202 final Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(addressString);
2203 final ArrayList<String> recipients = new ArrayList<String>(tokens.length);
2204 for (int i = 0; i < tokens.length;i++) {
2205 recipients.add(tokens[i].getAddress());
2206 }
2207 final DataUsageStatUpdater statsUpdater = new DataUsageStatUpdater(context);
2208 statsUpdater.updateWithAddress(recipients);
2209 }
2210
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002211 /**
2212 * Send or Save a message.
2213 */
Scott Kennedyff8553f2013-04-05 20:57:44 -07002214 private void sendOrSaveMessage(final long messageIdToSave,
2215 final SendOrSaveMessage sendOrSaveMessage, final ReplyFromAccount selectedAccount) {
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002216 final ContentResolver resolver = mContext.getContentResolver();
2217 final boolean updateExistingMessage = messageIdToSave != UIProvider.INVALID_MESSAGE_ID;
2218
2219 final String accountMethod = sendOrSaveMessage.mSave ?
2220 UIProvider.AccountCallMethods.SAVE_MESSAGE :
2221 UIProvider.AccountCallMethods.SEND_MESSAGE;
2222
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002223 try {
2224 if (updateExistingMessage) {
2225 sendOrSaveMessage.mValues.put(BaseColumns._ID, messageIdToSave);
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002226
Paul Westbrook013a23c2013-02-22 10:37:41 -08002227 callAccountSendSaveMethod(resolver,
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002228 selectedAccount.account, accountMethod, sendOrSaveMessage);
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002229 } else {
Paul Westbrook013a23c2013-02-22 10:37:41 -08002230 Uri messageUri = null;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002231 final Bundle result = callAccountSendSaveMethod(resolver,
2232 selectedAccount.account, accountMethod, sendOrSaveMessage);
2233 if (result != null) {
2234 // If a non-null value was returned, then the provider handled the call
2235 // method
2236 messageUri = result.getParcelable(UIProvider.MessageColumns.URI);
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002237 }
2238 if (sendOrSaveMessage.mSave && messageUri != null) {
2239 final Cursor messageCursor = resolver.query(messageUri,
2240 UIProvider.MESSAGE_PROJECTION, null, null, null);
2241 if (messageCursor != null) {
2242 try {
2243 if (messageCursor.moveToFirst()) {
2244 // Broadcast notification that a new message has
2245 // been allocated
2246 mSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage,
2247 new Message(messageCursor));
2248 }
2249 } finally {
2250 messageCursor.close();
Paul Westbrookba558482012-03-19 11:00:24 -07002251 }
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002252 }
2253 }
2254 }
2255 } finally {
2256 // Close any opened file descriptors
2257 closeOpenedAttachmentFds(sendOrSaveMessage);
2258 }
2259 }
2260
Scott Kennedyff8553f2013-04-05 20:57:44 -07002261 private static void closeOpenedAttachmentFds(final SendOrSaveMessage sendOrSaveMessage) {
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002262 final Bundle openedFds = sendOrSaveMessage.attachmentFds();
2263 if (openedFds != null) {
2264 final Set<String> keys = openedFds.keySet();
Scott Kennedyff8553f2013-04-05 20:57:44 -07002265 for (final String key : keys) {
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002266 final ParcelFileDescriptor fd = openedFds.getParcelable(key);
2267 if (fd != null) {
2268 try {
2269 fd.close();
2270 } catch (IOException e) {
2271 // Do nothing
Paul Westbrookba558482012-03-19 11:00:24 -07002272 }
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002273 }
2274 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002275 }
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002276 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002277
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002278 /**
Andrew Sappersteinbc5e0dc2013-08-07 21:15:22 -07002279 * Use the {@link ContentResolver#call} method to send or save the message.
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002280 *
2281 * If this was successful, this method will return an non-null Bundle instance
2282 */
Scott Kennedyff8553f2013-04-05 20:57:44 -07002283 private static Bundle callAccountSendSaveMethod(final ContentResolver resolver,
2284 final Account account, final String method,
2285 final SendOrSaveMessage sendOrSaveMessage) {
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002286 // Copy all of the values from the content values to the bundle
2287 final Bundle methodExtras = new Bundle(sendOrSaveMessage.mValues.size());
2288 final Set<Entry<String, Object>> valueSet = sendOrSaveMessage.mValues.valueSet();
2289
2290 for (Entry<String, Object> entry : valueSet) {
2291 final Object entryValue = entry.getValue();
2292 final String key = entry.getKey();
2293 if (entryValue instanceof String) {
2294 methodExtras.putString(key, (String)entryValue);
2295 } else if (entryValue instanceof Boolean) {
2296 methodExtras.putBoolean(key, (Boolean)entryValue);
2297 } else if (entryValue instanceof Integer) {
2298 methodExtras.putInt(key, (Integer)entryValue);
2299 } else if (entryValue instanceof Long) {
2300 methodExtras.putLong(key, (Long)entryValue);
2301 } else {
2302 LogUtils.wtf(LOG_TAG, "Unexpected object type: %s",
2303 entryValue.getClass().getName());
2304 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002305 }
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002306
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002307 // If the SendOrSaveMessage has some opened fds, add them to the bundle
2308 final Bundle fdMap = sendOrSaveMessage.attachmentFds();
2309 if (fdMap != null) {
2310 methodExtras.putParcelable(
2311 UIProvider.SendOrSaveMethodParamKeys.OPENED_FD_MAP, fdMap);
2312 }
2313
Paul Westbrook72e2ea82012-10-22 16:25:22 -07002314 return resolver.call(account.uri, method, account.uri.toString(), methodExtras);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002315 }
2316 }
2317
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002318 @VisibleForTesting
2319 public static class SendOrSaveMessage {
Mindy Pereira92551d02012-04-05 11:31:12 -07002320 final ReplyFromAccount mAccount;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002321 final ContentValues mValues;
Mindy Pereira3ce64e72012-01-13 14:29:45 -08002322 final String mRefMessageId;
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002323 @VisibleForTesting
2324 public final boolean mSave;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002325 final int mRequestId;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002326 private final Bundle mAttachmentFds;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002327
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002328 public SendOrSaveMessage(Context context, ReplyFromAccount account, ContentValues values,
2329 String refMessageId, List<Attachment> attachments, boolean save) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002330 mAccount = account;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002331 mValues = values;
2332 mRefMessageId = refMessageId;
2333 mSave = save;
2334 mRequestId = mValues.hashCode() ^ hashCode();
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002335
2336 mAttachmentFds = initializeAttachmentFds(context, attachments);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002337 }
2338
2339 int requestId() {
2340 return mRequestId;
2341 }
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002342
2343 Bundle attachmentFds() {
2344 return mAttachmentFds;
2345 }
2346
2347 /**
2348 * Opens {@link ParcelFileDescriptor} for each of the attachments. This method must be
2349 * called before the ComposeActivity finishes.
2350 * Note: The caller is responsible for closing these file descriptors.
2351 */
Scott Kennedyff8553f2013-04-05 20:57:44 -07002352 private static Bundle initializeAttachmentFds(final Context context,
2353 final List<Attachment> attachments) {
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002354 if (attachments == null || attachments.size() == 0) {
2355 return null;
2356 }
2357
2358 final Bundle result = new Bundle(attachments.size());
2359 final ContentResolver resolver = context.getContentResolver();
2360
2361 for (Attachment attachment : attachments) {
2362 if (attachment == null || Utils.isEmpty(attachment.contentUri)) {
2363 continue;
2364 }
2365
2366 ParcelFileDescriptor fileDescriptor;
2367 try {
2368 fileDescriptor = resolver.openFileDescriptor(attachment.contentUri, "r");
2369 } catch (FileNotFoundException e) {
2370 LogUtils.e(LOG_TAG, e, "Exception attempting to open attachment");
2371 fileDescriptor = null;
Paul Westbrookc537fd42013-02-20 11:10:03 -08002372 } catch (SecurityException e) {
2373 // We have encountered a security exception when attempting to open the file
2374 // specified by the content uri. If the attachment has been cached, this
2375 // isn't a problem, as even through the original permission may have been
2376 // revoked, we have cached the file. This will happen when saving/sending
2377 // a previously saved draft.
2378 // TODO(markwei): Expose whether the attachment has been cached through the
2379 // attachment object. This would allow us to limit when the log is made, as
2380 // if the attachment has been cached, this really isn't an error
2381 LogUtils.e(LOG_TAG, e, "Security Exception attempting to open attachment");
2382 // Just set the file descriptor to null, as the underlying provider needs
2383 // to handle the file descriptor not being set.
2384 fileDescriptor = null;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002385 }
2386
2387 if (fileDescriptor != null) {
2388 result.putParcelable(attachment.contentUri.toString(), fileDescriptor);
2389 }
2390 }
2391
2392 return result;
2393 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002394 }
2395
2396 /**
2397 * Get the to recipients.
2398 */
2399 public String[] getToAddresses() {
2400 return getAddressesFromList(mTo);
2401 }
2402
2403 /**
2404 * Get the cc recipients.
2405 */
2406 public String[] getCcAddresses() {
2407 return getAddressesFromList(mCc);
2408 }
2409
2410 /**
2411 * Get the bcc recipients.
2412 */
2413 public String[] getBccAddresses() {
2414 return getAddressesFromList(mBcc);
2415 }
2416
2417 public String[] getAddressesFromList(RecipientEditTextView list) {
2418 if (list == null) {
2419 return new String[0];
2420 }
2421 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(list.getText());
2422 int count = tokens.length;
2423 String[] result = new String[count];
2424 for (int i = 0; i < count; i++) {
2425 result[i] = tokens[i].toString();
2426 }
2427 return result;
2428 }
2429
2430 /**
2431 * Check for invalid email addresses.
2432 * @param to String array of email addresses to check.
2433 * @param wrongEmailsOut Emails addresses that were invalid.
2434 */
Scott Kennedyff8553f2013-04-05 20:57:44 -07002435 public void checkInvalidEmails(final String[] to, final List<String> wrongEmailsOut) {
Mindy Pereirae5f20bf2012-06-25 14:20:40 -07002436 if (mValidator == null) {
2437 return;
2438 }
Scott Kennedyff8553f2013-04-05 20:57:44 -07002439 for (final String email : to) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002440 if (!mValidator.isValid(email)) {
2441 wrongEmailsOut.add(email);
2442 }
2443 }
2444 }
2445
Tony Mantler2558b502013-07-09 10:53:34 -07002446 public static class RecipientErrorDialogFragment extends DialogFragment {
Paul Westbrookf0ea4842013-08-13 16:41:18 -07002447 // Public no-args constructor needed for fragment re-instantiation
2448 public RecipientErrorDialogFragment() {}
2449
Tony Mantler2558b502013-07-09 10:53:34 -07002450 public static RecipientErrorDialogFragment newInstance(final String message) {
2451 final RecipientErrorDialogFragment frag = new RecipientErrorDialogFragment();
2452 final Bundle args = new Bundle(1);
2453 args.putString("message", message);
2454 frag.setArguments(args);
2455 return frag;
2456 }
2457
2458 @Override
2459 public Dialog onCreateDialog(Bundle savedInstanceState) {
2460 final String message = getArguments().getString("message");
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07002461 return new AlertDialog.Builder(getActivity())
2462 .setMessage(message)
Tony Mantler2558b502013-07-09 10:53:34 -07002463 .setPositiveButton(
2464 R.string.ok, new Dialog.OnClickListener() {
2465 @Override
2466 public void onClick(DialogInterface dialog, int which) {
2467 ((ComposeActivity)getActivity()).finishRecipientErrorDialog();
2468 }
2469 }).create();
2470 }
2471 }
2472
2473 private void finishRecipientErrorDialog() {
2474 // after the user dismisses the recipient error
2475 // dialog we want to make sure to refocus the
2476 // recipient to field so they can fix the issue
2477 // easily
2478 if (mTo != null) {
2479 mTo.requestFocus();
2480 }
2481 }
2482
Mindy Pereira82cc5662012-01-09 17:29:30 -08002483 /**
2484 * Show an error because the user has entered an invalid recipient.
2485 * @param message
2486 */
Tony Mantler2558b502013-07-09 10:53:34 -07002487 private void showRecipientErrorDialog(final String message) {
2488 final DialogFragment frag = RecipientErrorDialogFragment.newInstance(message);
2489 frag.show(getFragmentManager(), "recipient error");
Mindy Pereira82cc5662012-01-09 17:29:30 -08002490 }
2491
2492 /**
2493 * Update the state of the UI based on whether or not the current draft
2494 * needs to be saved and the message is not empty.
2495 */
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002496 public void updateSaveUi() {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002497 if (mSave != null) {
2498 mSave.setEnabled((shouldSave() && !isBlank()));
2499 }
2500 }
2501
2502 /**
2503 * Returns true if we need to save the current draft.
2504 */
2505 private boolean shouldSave() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002506 synchronized (mDraftLock) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002507 // The message should only be saved if:
2508 // It hasn't been sent AND
2509 // Some text has been added to the message OR
2510 // an attachment has been added or removed
Mindy Pereiraa2148332012-07-02 13:54:14 -07002511 // AND there is actually something in the draft to save.
Andy Huangd47877e2012-08-09 19:31:24 -07002512 return (mTextChanged || mAttachmentsChanged || mReplyFromChanged)
Mindy Pereiraa2148332012-07-02 13:54:14 -07002513 && !isBlank();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002514 }
2515 }
2516
2517 /**
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002518 * Check if all fields are blank.
Mindy Pereira82cc5662012-01-09 17:29:30 -08002519 * @return boolean
2520 */
2521 public boolean isBlank() {
Alice Yanga49b6842013-08-23 10:36:18 -07002522 // Need to check for null since isBlank() can be called from onPause()
2523 // before findViews() is called
2524 if (mSubject == null || mBodyView == null || mTo == null || mCc == null ||
2525 mAttachmentsView == null) {
2526 LogUtils.w(LOG_TAG, "null views in isBlank check");
2527 return true;
2528 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002529 return mSubject.getText().length() == 0
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002530 && (mBodyView.getText().length() == 0 || getSignatureStartPosition(mSignature,
2531 mBodyView.getText().toString()) == 0)
2532 && mTo.length() == 0
2533 && mCc.length() == 0 && mBcc.length() == 0
2534 && mAttachmentsView.getAttachments().size() == 0;
2535 }
2536
2537 @VisibleForTesting
2538 protected int getSignatureStartPosition(String signature, String bodyText) {
2539 int startPos = -1;
2540
2541 if (TextUtils.isEmpty(signature) || TextUtils.isEmpty(bodyText)) {
2542 return startPos;
2543 }
2544
2545 int bodyLength = bodyText.length();
2546 int signatureLength = signature.length();
2547 String printableVersion = convertToPrintableSignature(signature);
2548 int printableLength = printableVersion.length();
2549
2550 if (bodyLength >= printableLength
2551 && bodyText.substring(bodyLength - printableLength)
2552 .equals(printableVersion)) {
2553 startPos = bodyLength - printableLength;
2554 } else if (bodyLength >= signatureLength
2555 && bodyText.substring(bodyLength - signatureLength)
2556 .equals(signature)) {
2557 startPos = bodyLength - signatureLength;
2558 }
2559 return startPos;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002560 }
2561
2562 /**
2563 * Allows any changes made by the user to be ignored. Called when the user
2564 * decides to discard a draft.
2565 */
2566 private void discardChanges() {
2567 mTextChanged = false;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002568 mAttachmentsChanged = false;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002569 mReplyFromChanged = false;
2570 }
2571
2572 /**
Mindy Pereira181df782012-03-01 13:32:44 -08002573 * @param save
2574 * @param showToast
2575 * @return Whether the send or save succeeded.
2576 */
2577 protected boolean sendOrSaveWithSanityChecks(final boolean save, final boolean showToast,
Mark Weidd19b632012-10-19 13:59:28 -07002578 final boolean orientationChanged, final boolean autoSend) {
Mark Wei009b3712012-10-18 18:07:50 -07002579 if (mAccounts == null || mAccount == null) {
2580 Toast.makeText(this, R.string.send_failed, Toast.LENGTH_SHORT).show();
Mark Weidd19b632012-10-19 13:59:28 -07002581 if (autoSend) {
2582 finish();
2583 }
Mark Wei009b3712012-10-18 18:07:50 -07002584 return false;
2585 }
2586
Scott Kennedyff8553f2013-04-05 20:57:44 -07002587 final String[] to, cc, bcc;
Mindy Pereira181df782012-03-01 13:32:44 -08002588 if (orientationChanged) {
2589 to = cc = bcc = new String[0];
2590 } else {
2591 to = getToAddresses();
2592 cc = getCcAddresses();
2593 bcc = getBccAddresses();
2594 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002595
Mindy Pereira181df782012-03-01 13:32:44 -08002596 // Don't let the user send to nobody (but it's okay to save a message
2597 // with no recipients)
2598 if (!save && (to.length == 0 && cc.length == 0 && bcc.length == 0)) {
2599 showRecipientErrorDialog(getString(R.string.recipient_needed));
2600 return false;
2601 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002602
Mindy Pereira181df782012-03-01 13:32:44 -08002603 List<String> wrongEmails = new ArrayList<String>();
2604 if (!save) {
2605 checkInvalidEmails(to, wrongEmails);
2606 checkInvalidEmails(cc, wrongEmails);
2607 checkInvalidEmails(bcc, wrongEmails);
2608 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002609
Mindy Pereira181df782012-03-01 13:32:44 -08002610 // Don't let the user send an email with invalid recipients
2611 if (wrongEmails.size() > 0) {
2612 String errorText = String.format(getString(R.string.invalid_recipient),
2613 wrongEmails.get(0));
2614 showRecipientErrorDialog(errorText);
2615 return false;
2616 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002617
Mindy Pereira181df782012-03-01 13:32:44 -08002618 // Show a warning before sending only if there are no attachments.
2619 if (!save) {
2620 if (mAttachmentsView.getAttachments().isEmpty() && showEmptyTextWarnings()) {
2621 boolean warnAboutEmptySubject = isSubjectEmpty();
Tony Mantler2558b502013-07-09 10:53:34 -07002622 boolean emptyBody = TextUtils.getTrimmedLength(mBodyView.getEditableText()) == 0;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002623
Mindy Pereira181df782012-03-01 13:32:44 -08002624 // A warning about an empty body may not be warranted when
2625 // forwarding mails, since a common use case is to forward
2626 // quoted text and not append any more text.
2627 boolean warnAboutEmptyBody = emptyBody && (!mForward || isBodyEmpty());
Mindy Pereira82cc5662012-01-09 17:29:30 -08002628
Mindy Pereira181df782012-03-01 13:32:44 -08002629 // When we bring up a dialog warning the user about a send,
2630 // assume that they accept sending the message. If they do not,
2631 // the dialog listener is required to enable sending again.
2632 if (warnAboutEmptySubject) {
Tony Mantler2558b502013-07-09 10:53:34 -07002633 showSendConfirmDialog(R.string.confirm_send_message_with_no_subject, save,
2634 showToast);
Mindy Pereira181df782012-03-01 13:32:44 -08002635 return true;
2636 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002637
Mindy Pereira181df782012-03-01 13:32:44 -08002638 if (warnAboutEmptyBody) {
Tony Mantler2558b502013-07-09 10:53:34 -07002639 showSendConfirmDialog(R.string.confirm_send_message_with_no_body, save,
2640 showToast);
Mindy Pereira181df782012-03-01 13:32:44 -08002641 return true;
2642 }
2643 }
2644 // Ask for confirmation to send (if always required)
2645 if (showSendConfirmation()) {
Tony Mantler2558b502013-07-09 10:53:34 -07002646 showSendConfirmDialog(R.string.confirm_send_message, save, showToast);
Mindy Pereira181df782012-03-01 13:32:44 -08002647 return true;
2648 }
2649 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002650
Tony Mantler2558b502013-07-09 10:53:34 -07002651 sendOrSave(save, showToast);
Mindy Pereira181df782012-03-01 13:32:44 -08002652 return true;
2653 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002654
Mindy Pereira181df782012-03-01 13:32:44 -08002655 /**
2656 * Returns a boolean indicating whether warnings should be shown for empty
2657 * subject and body fields
Andy Huang5c5fd572012-04-08 18:19:29 -07002658 *
Mindy Pereira181df782012-03-01 13:32:44 -08002659 * @return True if a warning should be shown for empty text fields
2660 */
2661 protected boolean showEmptyTextWarnings() {
2662 return mAttachmentsView.getAttachments().size() == 0;
2663 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002664
Mindy Pereira181df782012-03-01 13:32:44 -08002665 /**
2666 * Returns a boolean indicating whether the user should confirm each send
2667 *
2668 * @return True if a warning should be on each send
2669 */
2670 protected boolean showSendConfirmation() {
2671 return mCachedSettings != null ? mCachedSettings.confirmSend : false;
2672 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002673
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07002674 public static class SendConfirmDialogFragment extends DialogFragment
2675 implements DialogInterface.OnClickListener {
2676
2677 private boolean mSave;
2678 private boolean mShowToast;
2679
Paul Westbrookf0ea4842013-08-13 16:41:18 -07002680 // Public no-args constructor needed for fragment re-instantiation
2681 public SendConfirmDialogFragment() {}
2682
Tony Mantler2558b502013-07-09 10:53:34 -07002683 public static SendConfirmDialogFragment newInstance(final int messageId,
2684 final boolean save, final boolean showToast) {
2685 final SendConfirmDialogFragment frag = new SendConfirmDialogFragment();
2686 final Bundle args = new Bundle(3);
2687 args.putInt("messageId", messageId);
2688 args.putBoolean("save", save);
2689 args.putBoolean("showToast", showToast);
2690 frag.setArguments(args);
2691 return frag;
Mindy Pereira181df782012-03-01 13:32:44 -08002692 }
Tony Mantler2558b502013-07-09 10:53:34 -07002693
2694 @Override
2695 public Dialog onCreateDialog(Bundle savedInstanceState) {
2696 final int messageId = getArguments().getInt("messageId");
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07002697 mSave = getArguments().getBoolean("save");
2698 mShowToast = getArguments().getBoolean("showToast");
2699
2700 final int confirmTextId = (messageId == R.string.confirm_send_message) ?
2701 R.string.ok : R.string.send;
Tony Mantler2558b502013-07-09 10:53:34 -07002702
2703 return new AlertDialog.Builder(getActivity())
2704 .setMessage(messageId)
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07002705 .setPositiveButton(confirmTextId, this)
Paul Westbrook7d1c5c42013-10-01 23:40:04 -07002706 .setNegativeButton(R.string.cancel, null)
Tony Mantler2558b502013-07-09 10:53:34 -07002707 .create();
2708 }
Andrew Sapperstein530ac7a2013-10-29 19:12:17 -07002709
2710 @Override
2711 public void onClick(DialogInterface dialog, int which) {
2712 if (which == DialogInterface.BUTTON_POSITIVE) {
2713 ((ComposeActivity) getActivity()).finishSendConfirmDialog(mSave, mShowToast);
2714 }
2715 }
Tony Mantler2558b502013-07-09 10:53:34 -07002716 }
2717
2718 private void finishSendConfirmDialog(final boolean save, final boolean showToast) {
2719 sendOrSave(save, showToast);
2720 }
2721
2722 private void showSendConfirmDialog(final int messageId, final boolean save,
2723 final boolean showToast) {
2724 final DialogFragment frag = SendConfirmDialogFragment.newInstance(messageId, save,
2725 showToast);
2726 frag.show(getFragmentManager(), "send confirm");
Mindy Pereira181df782012-03-01 13:32:44 -08002727 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002728
Mindy Pereira181df782012-03-01 13:32:44 -08002729 /**
2730 * Returns whether the ComposeArea believes there is any text in the body of
2731 * the composition. TODO: When ComposeArea controls the Body as well, add
2732 * that here.
2733 */
2734 public boolean isBodyEmpty() {
2735 return !mQuotedTextView.isTextIncluded();
2736 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002737
Mindy Pereira181df782012-03-01 13:32:44 -08002738 /**
2739 * Test to see if the subject is empty.
2740 *
2741 * @return boolean.
2742 */
2743 // TODO: this will likely go away when composeArea.focus() is implemented
2744 // after all the widget control is moved over.
2745 public boolean isSubjectEmpty() {
2746 return TextUtils.getTrimmedLength(mSubject.getText()) == 0;
2747 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002748
Andy Huang0a2a3462013-12-20 15:56:13 -08002749 @VisibleForTesting
2750 public String getSubject() {
2751 return mSubject.getText().toString();
2752 }
2753
Mindy Pereira181df782012-03-01 13:32:44 -08002754 /* package */
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002755 static int sendOrSaveInternal(Context context, ReplyFromAccount replyFromAccount,
Paul Westbrook05b92b82012-04-20 13:29:37 -07002756 Message message, final Message refMessage, Spanned body, final CharSequence quotedText,
mindyp44a63392012-11-05 12:05:16 -08002757 SendOrSaveCallback callback, Handler handler, boolean save, int composeMode,
Scott Kennedy60847252013-08-15 15:55:42 -07002758 ReplyFromAccount draftAccount, final ContentValues extraValues) {
Paul Westbrookb4931c62013-01-14 17:51:18 -08002759 final ContentValues values = new ContentValues();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002760
Paul Westbrookb4931c62013-01-14 17:51:18 -08002761 final String refMessageId = refMessage != null ? refMessage.uri.toString() : "";
Mindy Pereirac2031972012-04-03 09:38:35 -07002762
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002763 MessageModification.putToAddresses(values, message.getToAddresses());
2764 MessageModification.putCcAddresses(values, message.getCcAddresses());
2765 MessageModification.putBccAddresses(values, message.getBccAddresses());
Mindy Pereira82cc5662012-01-09 17:29:30 -08002766
Scott Kennedy8960f0a2012-11-07 15:35:50 -08002767 MessageModification.putCustomFromAddress(values, message.getFrom());
Mindy Pereira92551d02012-04-05 11:31:12 -07002768
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002769 MessageModification.putSubject(values, message.subject);
Paul Westbrookb4931c62013-01-14 17:51:18 -08002770 // Make sure to remove only the composing spans from the Spannable before saving.
2771 final String htmlBody = Html.toHtml(removeComposingSpans(body));
Paul Westbrook05b92b82012-04-20 13:29:37 -07002772
Mindy Pereira29ef1b82012-01-13 11:26:21 -08002773 boolean includeQuotedText = !TextUtils.isEmpty(quotedText);
2774 StringBuilder fullBody = new StringBuilder(htmlBody);
2775 if (includeQuotedText) {
Mindy Pereirae8caf122012-03-20 15:23:31 -07002776 // HTML gets converted to text for now
2777 final String text = quotedText.toString();
2778 if (QuotedTextView.containsQuotedText(text)) {
2779 int pos = QuotedTextView.getQuotedTextOffset(text);
Paul Westbrook55271cf2012-04-20 16:25:02 -07002780 final int quoteStartPos = fullBody.length() + pos;
2781 fullBody.append(text);
2782 MessageModification.putQuoteStartPos(values, quoteStartPos);
Mindy Pereira12575862012-03-21 16:30:54 -07002783 MessageModification.putForward(values, composeMode == ComposeActivity.FORWARD);
Mindy Pereirae8caf122012-03-20 15:23:31 -07002784 MessageModification.putAppendRefMessageContent(values, includeQuotedText);
Mindy Pereira29ef1b82012-01-13 11:26:21 -08002785 } else {
Mindy Pereirae8caf122012-03-20 15:23:31 -07002786 LogUtils.w(LOG_TAG, "Couldn't find quoted text");
2787 // This shouldn't happen, but just use what we have,
2788 // and don't do server-side expansion
2789 fullBody.append(text);
Mindy Pereira29ef1b82012-01-13 11:26:21 -08002790 }
2791 }
Mindy Pereira002ff522012-05-30 10:31:26 -07002792 int draftType = getDraftType(composeMode);
Mindy Pereira12575862012-03-21 16:30:54 -07002793 MessageModification.putDraftType(values, draftType);
Mindy Pereirac6f1e2a2012-04-04 10:33:45 -07002794 if (refMessage != null) {
2795 if (!TextUtils.isEmpty(refMessage.bodyHtml)) {
2796 MessageModification.putBodyHtml(values, fullBody.toString());
2797 }
2798 if (!TextUtils.isEmpty(refMessage.bodyText)) {
mindypc59dd822012-11-13 10:56:21 -08002799 MessageModification.putBody(values,
2800 Utils.convertHtmlToPlainText(fullBody.toString()).toString());
Mindy Pereirac6f1e2a2012-04-04 10:33:45 -07002801 }
2802 } else {
Mindy Pereirac2031972012-04-03 09:38:35 -07002803 MessageModification.putBodyHtml(values, fullBody.toString());
mindypc59dd822012-11-13 10:56:21 -08002804 MessageModification.putBody(values, Utils.convertHtmlToPlainText(fullBody.toString())
2805 .toString());
Mindy Pereirac2031972012-04-03 09:38:35 -07002806 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002807 MessageModification.putAttachments(values, message.getAttachments());
Mindy Pereira12575862012-03-21 16:30:54 -07002808 if (!TextUtils.isEmpty(refMessageId)) {
2809 MessageModification.putRefMessageId(values, refMessageId);
2810 }
Scott Kennedy60847252013-08-15 15:55:42 -07002811 if (extraValues != null) {
2812 values.putAll(extraValues);
2813 }
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002814 SendOrSaveMessage sendOrSaveMessage = new SendOrSaveMessage(context, replyFromAccount,
2815 values, refMessageId, message.getAttachments(), save);
mindyp44a63392012-11-05 12:05:16 -08002816 SendOrSaveTask sendOrSaveTask = new SendOrSaveTask(context, sendOrSaveMessage, callback,
2817 draftAccount);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002818
Mindy Pereira181df782012-03-01 13:32:44 -08002819 callback.initializeSendOrSave(sendOrSaveTask);
Mindy Pereira181df782012-03-01 13:32:44 -08002820 // Do the send/save action on the specified handler to avoid possible
2821 // ANRs
2822 handler.post(sendOrSaveTask);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002823
Mindy Pereira181df782012-03-01 13:32:44 -08002824 return sendOrSaveMessage.requestId();
2825 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002826
Paul Westbrookb4931c62013-01-14 17:51:18 -08002827 /**
2828 * Removes any composing spans from the specified string. This will create a new
2829 * SpannableString instance, as to not modify the behavior of the EditText view.
2830 */
2831 private static SpannableString removeComposingSpans(Spanned body) {
2832 final SpannableString messageBody = new SpannableString(body);
2833 BaseInputConnection.removeComposingSpans(messageBody);
2834 return messageBody;
2835 }
2836
Mindy Pereira002ff522012-05-30 10:31:26 -07002837 private static int getDraftType(int mode) {
2838 int draftType = -1;
2839 switch (mode) {
2840 case ComposeActivity.COMPOSE:
2841 draftType = DraftType.COMPOSE;
2842 break;
2843 case ComposeActivity.REPLY:
2844 draftType = DraftType.REPLY;
2845 break;
2846 case ComposeActivity.REPLY_ALL:
2847 draftType = DraftType.REPLY_ALL;
2848 break;
2849 case ComposeActivity.FORWARD:
2850 draftType = DraftType.FORWARD;
2851 break;
2852 }
2853 return draftType;
2854 }
2855
Tony Mantler2558b502013-07-09 10:53:34 -07002856 private void sendOrSave(final boolean save, final boolean showToast) {
Mindy Pereira181df782012-03-01 13:32:44 -08002857 // Check if user is a monkey. Monkeys can compose and hit send
2858 // button but are not allowed to send anything off the device.
Paul Westbrook3ae824c2012-04-06 13:29:39 -07002859 if (ActivityManager.isUserAMonkey()) {
Mindy Pereira181df782012-03-01 13:32:44 -08002860 return;
2861 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002862
Tony Mantler2558b502013-07-09 10:53:34 -07002863 final Spanned body = mBodyView.getEditableText();
2864
Mindy Pereira181df782012-03-01 13:32:44 -08002865 SendOrSaveCallback callback = new SendOrSaveCallback() {
Andy Huang1f8f4dd2012-10-25 21:35:35 -07002866 // FIXME: unused
Mindy Pereira82cc5662012-01-09 17:29:30 -08002867 private int mRestoredRequestId;
2868
Marc Blank0bbc8582012-04-23 15:07:57 -07002869 @Override
Mindy Pereira82cc5662012-01-09 17:29:30 -08002870 public void initializeSendOrSave(SendOrSaveTask sendOrSaveTask) {
Mindy Pereira181df782012-03-01 13:32:44 -08002871 synchronized (mActiveTasks) {
2872 int numTasks = mActiveTasks.size();
2873 if (numTasks == 0) {
2874 // Start service so we won't be killed if this app is
2875 // put in the background.
2876 startService(new Intent(ComposeActivity.this, EmptyService.class));
2877 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002878
Mindy Pereira181df782012-03-01 13:32:44 -08002879 mActiveTasks.add(sendOrSaveTask);
2880 }
2881 if (sTestSendOrSaveCallback != null) {
2882 sTestSendOrSaveCallback.initializeSendOrSave(sendOrSaveTask);
2883 }
2884 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002885
Marc Blank0bbc8582012-04-23 15:07:57 -07002886 @Override
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002887 public void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage,
2888 Message message) {
Mindy Pereira181df782012-03-01 13:32:44 -08002889 synchronized (mDraftLock) {
mindyp44a63392012-11-05 12:05:16 -08002890 mDraftAccount = sendOrSaveMessage.mAccount;
Mindy Pereira181df782012-03-01 13:32:44 -08002891 mDraftId = message.id;
2892 mDraft = message;
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002893 if (sRequestMessageIdMap != null) {
2894 sRequestMessageIdMap.put(sendOrSaveMessage.requestId(), mDraftId);
2895 }
Mindy Pereira181df782012-03-01 13:32:44 -08002896 // Cache request message map, in case the process is killed
2897 saveRequestMap();
2898 }
2899 if (sTestSendOrSaveCallback != null) {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002900 sTestSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage, message);
Mindy Pereira181df782012-03-01 13:32:44 -08002901 }
2902 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002903
Marc Blank0bbc8582012-04-23 15:07:57 -07002904 @Override
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002905 public Message getMessage() {
2906 synchronized (mDraftLock) {
2907 return mDraft;
2908 }
2909 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002910
Marc Blank0bbc8582012-04-23 15:07:57 -07002911 @Override
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002912 public void sendOrSaveFinished(SendOrSaveTask task, boolean success) {
Mindy Pereira47d0e652012-07-23 09:45:07 -07002913 // Update the last sent from account.
2914 if (mAccount != null) {
2915 MailAppProvider.getInstance().setLastSentFromAccount(mAccount.uri.toString());
2916 }
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002917 if (success) {
2918 // Successfully sent or saved so reset change markers
2919 discardChanges();
2920 } else {
2921 // A failure happened with saving/sending the draft
2922 // TODO(pwestbro): add a better string that should be used
2923 // when failing to send or save
2924 Toast.makeText(ComposeActivity.this, R.string.send_failed, Toast.LENGTH_SHORT)
2925 .show();
2926 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002927
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002928 int numTasks;
2929 synchronized (mActiveTasks) {
2930 // Remove the task from the list of active tasks
2931 mActiveTasks.remove(task);
2932 numTasks = mActiveTasks.size();
2933 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002934
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002935 if (numTasks == 0) {
2936 // Stop service so we can be killed.
2937 stopService(new Intent(ComposeActivity.this, EmptyService.class));
2938 }
2939 if (sTestSendOrSaveCallback != null) {
2940 sTestSendOrSaveCallback.sendOrSaveFinished(task, success);
2941 }
2942 }
Mindy Pereira181df782012-03-01 13:32:44 -08002943 };
Mindy Pereira82cc5662012-01-09 17:29:30 -08002944
Tony Mantler1e05a1e2013-08-12 16:44:26 -07002945 setAccount(mReplyFromAccount.account);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002946
Mindy Pereira181df782012-03-01 13:32:44 -08002947 if (mSendSaveTaskHandler == null) {
2948 HandlerThread handlerThread = new HandlerThread("Send Message Task Thread");
2949 handlerThread.start();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002950
Mindy Pereira181df782012-03-01 13:32:44 -08002951 mSendSaveTaskHandler = new Handler(handlerThread.getLooper());
2952 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002953
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002954 Message msg = createMessage(mReplyFromAccount, getMode());
Paul Westbrook05b92b82012-04-20 13:29:37 -07002955 mRequestId = sendOrSaveInternal(this, mReplyFromAccount, msg, mRefMessage, body,
2956 mQuotedTextView.getQuotedTextIfIncluded(), callback,
Scott Kennedy60847252013-08-15 15:55:42 -07002957 mSendSaveTaskHandler, save, mComposeMode, mDraftAccount, mExtraValues);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002958
Mindy Pereira181df782012-03-01 13:32:44 -08002959 // Don't display the toast if the user is just changing the orientation,
2960 // but we still need to save the draft to the cursor because this is how we restore
2961 // the attachments when the configuration change completes.
2962 if (showToast && (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) {
2963 Toast.makeText(this, save ? R.string.message_saved : R.string.sending_message,
2964 Toast.LENGTH_LONG).show();
2965 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002966
Mindy Pereira181df782012-03-01 13:32:44 -08002967 // Need to update variables here because the send or save completes
2968 // asynchronously even though the toast shows right away.
2969 discardChanges();
2970 updateSaveUi();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002971
Mindy Pereira181df782012-03-01 13:32:44 -08002972 // If we are sending, finish the activity
2973 if (!save) {
2974 finish();
2975 }
2976 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002977
Mindy Pereira181df782012-03-01 13:32:44 -08002978 /**
2979 * Save the state of the request messageid map. This allows for the Gmail
2980 * process to be killed, but and still allow for ComposeActivity instances
2981 * to be recreated correctly.
2982 */
2983 private void saveRequestMap() {
2984 // TODO: store the request map in user preferences.
2985 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002986
Mindy Pereira2db7d4a2012-08-15 11:00:02 -07002987 private void doAttach(String type) {
Mindy Pereira013194c2012-01-06 15:09:33 -08002988 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2989 i.addCategory(Intent.CATEGORY_OPENABLE);
Paul Westbrookd6a9a3f2012-04-26 18:47:23 -07002990 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
Andrew Sapperstein05089f32013-10-01 17:00:03 -07002991 i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
Mindy Pereira2db7d4a2012-08-15 11:00:02 -07002992 i.setType(type);
Mindy Pereira013194c2012-01-06 15:09:33 -08002993 mAddingAttachment = true;
Mindy Pereira181df782012-03-01 13:32:44 -08002994 startActivityForResult(Intent.createChooser(i, getText(R.string.select_attachment_type)),
2995 RESULT_PICK_ATTACHMENT);
Mindy Pereira013194c2012-01-06 15:09:33 -08002996 }
2997
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08002998 private void showCcBccViews() {
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08002999 mCcBccView.show(true, true, true);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08003000 if (mCcBccButton != null) {
mindypcd0b0b92012-08-23 14:33:17 -07003001 mCcBccButton.setVisibility(View.INVISIBLE);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08003002 }
3003 }
3004
Andy Huang4fe0af82013-08-20 17:24:51 -07003005 private static String getActionString(int action) {
Andy Huangdc97bf42013-08-15 16:52:45 -07003006 final String msgType;
Andy Huang4fe0af82013-08-20 17:24:51 -07003007 switch (action) {
Andy Huangdc97bf42013-08-15 16:52:45 -07003008 case COMPOSE:
3009 msgType = "new_message";
3010 break;
3011 case REPLY:
3012 msgType = "reply";
3013 break;
3014 case REPLY_ALL:
3015 msgType = "reply_all";
3016 break;
3017 case FORWARD:
3018 msgType = "forward";
3019 break;
3020 default:
3021 msgType = "unknown";
3022 break;
3023 }
Andy Huang4fe0af82013-08-20 17:24:51 -07003024 return msgType;
3025 }
3026
3027 private void logSendOrSave(boolean save) {
3028 if (!Analytics.isLoggable() || mAttachmentsView == null) {
3029 return;
3030 }
3031
3032 final String category = (save) ? "message_save" : "message_send";
3033 final int attachmentCount = getAttachments().size();
3034 final String msgType = getActionString(mComposeMode);
Andy Huangdc97bf42013-08-15 16:52:45 -07003035 final String label;
3036 final long value;
3037 if (mComposeMode == COMPOSE) {
3038 label = Integer.toString(attachmentCount);
3039 value = attachmentCount;
3040 } else {
3041 label = null;
3042 value = 0;
3043 }
3044 Analytics.getInstance().sendEvent(category, msgType, label, value);
3045 }
3046
Mindy Pereira326c6602012-01-04 15:32:42 -08003047 @Override
3048 public boolean onNavigationItemSelected(int position, long itemId) {
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08003049 int initialComposeMode = mComposeMode;
Mindy Pereira326c6602012-01-04 15:32:42 -08003050 if (position == ComposeActivity.REPLY) {
3051 mComposeMode = ComposeActivity.REPLY;
3052 } else if (position == ComposeActivity.REPLY_ALL) {
3053 mComposeMode = ComposeActivity.REPLY_ALL;
3054 } else if (position == ComposeActivity.FORWARD) {
3055 mComposeMode = ComposeActivity.FORWARD;
3056 }
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07003057 clearChangeListeners();
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08003058 if (initialComposeMode != mComposeMode) {
Mindy Pereira154386a2012-01-11 13:02:33 -08003059 resetMessageForModeChange();
mindyp68c0bfc2012-12-04 10:29:48 -08003060 if (mRefMessage != null) {
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08003061 setFieldsFromRefMessage(mComposeMode);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07003062 }
Mindy Pereiraef388302012-06-18 19:07:44 -07003063 boolean showCc = false;
3064 boolean showBcc = false;
3065 if (mDraft != null) {
3066 // Following desktop behavior, if the user has added a BCC
3067 // field to a draft, we show it regardless of compose mode.
Scott Kennedy8960f0a2012-11-07 15:35:50 -08003068 showBcc = !TextUtils.isEmpty(mDraft.getBcc());
Mindy Pereiraef388302012-06-18 19:07:44 -07003069 // Use the draft to determine what to populate.
3070 // If the Bcc field is showing, show the Cc field whether it is populated or not.
Scott Kennedy8960f0a2012-11-07 15:35:50 -08003071 showCc = showBcc
3072 || (!TextUtils.isEmpty(mDraft.getCc()) && mComposeMode == REPLY_ALL);
mindyp68c0bfc2012-12-04 10:29:48 -08003073 }
3074 if (mRefMessage != null) {
mindyp9b1ac572012-09-27 14:12:00 -07003075 showCc = !TextUtils.isEmpty(mCc.getText());
mindyp68c0bfc2012-12-04 10:29:48 -08003076 showBcc = !TextUtils.isEmpty(mBcc.getText());
Mindy Pereiraef388302012-06-18 19:07:44 -07003077 }
3078 mCcBccView.show(false, showCc, showBcc);
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08003079 }
Mindy Pereiraef388302012-06-18 19:07:44 -07003080 updateHideOrShowCcBcc();
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07003081 initChangeListeners();
Mindy Pereira326c6602012-01-04 15:32:42 -08003082 return true;
3083 }
3084
Mindy Pereirab3112a22012-06-20 12:10:03 -07003085 @VisibleForTesting
3086 protected void resetMessageForModeChange() {
Mindy Pereira154386a2012-01-11 13:02:33 -08003087 // When switching between reply, reply all, forward,
3088 // follow the behavior of webview.
3089 // The contents of the following fields are cleared
3090 // so that they can be populated directly from the
3091 // ref message:
3092 // 1) Any recipient fields
3093 // 2) The subject
3094 mTo.setText("");
3095 mCc.setText("");
3096 mBcc.setText("");
3097 // Any edits to the subject are replaced with the original subject.
3098 mSubject.setText("");
3099
3100 // Any changes to the contents of the following fields are kept:
3101 // 1) Body
3102 // 2) Attachments
3103 // If the user made changes to attachments, keep their changes.
3104 if (!mAttachmentsChanged) {
3105 mAttachmentsView.deleteAllAttachments();
3106 }
3107 }
3108
Mindy Pereira326c6602012-01-04 15:32:42 -08003109 private class ComposeModeAdapter extends ArrayAdapter<String> {
3110
3111 private LayoutInflater mInflater;
3112
3113 public ComposeModeAdapter(Context context) {
3114 super(context, R.layout.compose_mode_item, R.id.mode, getResources()
3115 .getStringArray(R.array.compose_modes));
3116 }
3117
3118 private LayoutInflater getInflater() {
3119 if (mInflater == null) {
3120 mInflater = LayoutInflater.from(getContext());
3121 }
3122 return mInflater;
3123 }
3124
3125 @Override
3126 public View getView(int position, View convertView, ViewGroup parent) {
3127 if (convertView == null) {
3128 convertView = getInflater().inflate(R.layout.compose_mode_display_item, null);
3129 }
3130 ((TextView) convertView.findViewById(R.id.mode)).setText(getItem(position));
3131 return super.getView(position, convertView, parent);
3132 }
3133 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003134
3135 @Override
3136 public void onRespondInline(String text) {
3137 appendToBody(text, false);
mindyp40882432012-09-06 11:07:40 -07003138 mQuotedTextView.setUpperDividerVisible(false);
mindyp1623f9b2012-11-21 12:41:16 -08003139 mRespondedInline = true;
mindyp09dd3732012-12-17 08:37:52 -08003140 if (!mBodyView.hasFocus()) {
mindyp8654d4f2012-12-17 09:01:37 -08003141 mBodyView.requestFocus();
mindyp09dd3732012-12-17 08:37:52 -08003142 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003143 }
3144
3145 /**
3146 * Append text to the body of the message. If there is no existing body
3147 * text, just sets the body to text.
3148 *
3149 * @param text
3150 * @param withSignature True to append a signature.
3151 */
3152 public void appendToBody(CharSequence text, boolean withSignature) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003153 Editable bodyText = mBodyView.getEditableText();
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003154 if (bodyText != null && bodyText.length() > 0) {
3155 bodyText.append(text);
3156 } else {
3157 setBody(text, withSignature);
3158 }
3159 }
3160
3161 /**
3162 * Set the body of the message.
Mindy Pereirabdf7a402012-03-01 15:23:26 -08003163 *
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003164 * @param text
3165 * @param withSignature True to append a signature.
3166 */
3167 public void setBody(CharSequence text, boolean withSignature) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003168 mBodyView.setText(text);
Mindy Pereirabdf7a402012-03-01 15:23:26 -08003169 if (withSignature) {
3170 appendSignature();
3171 }
3172 }
3173
3174 private void appendSignature() {
Mindy Pereirab13917c2012-03-29 08:08:19 -07003175 String newSignature = mCachedSettings != null ? mCachedSettings.signature : null;
Mindy Pereira433b1982012-04-03 11:53:07 -07003176 boolean hasFocus = mBodyView.hasFocus();
mindyp27083062012-11-15 09:02:01 -08003177 int signaturePos = getSignatureStartPosition(mSignature, mBodyView.getText().toString());
3178 if (!TextUtils.equals(newSignature, mSignature) || signaturePos < 0) {
Mindy Pereirab13917c2012-03-29 08:08:19 -07003179 mSignature = newSignature;
mindyp27083062012-11-15 09:02:01 -08003180 if (!TextUtils.isEmpty(mSignature)) {
Mindy Pereirab13917c2012-03-29 08:08:19 -07003181 // Appending a signature does not count as changing text.
3182 mBodyView.removeTextChangedListener(this);
3183 mBodyView.append(convertToPrintableSignature(mSignature));
3184 mBodyView.addTextChangedListener(this);
3185 }
Mindy Pereira433b1982012-04-03 11:53:07 -07003186 if (hasFocus) {
3187 focusBody();
3188 }
Mindy Pereirabdf7a402012-03-01 15:23:26 -08003189 }
3190 }
3191
3192 private String convertToPrintableSignature(String signature) {
3193 String signatureResource = getResources().getString(R.string.signature);
3194 if (signature == null) {
3195 signature = "";
3196 }
3197 return String.format(signatureResource, signature);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08003198 }
Mindy Pereira1a95a572012-01-05 12:21:29 -08003199
Mindy Pereira5a85e2b2012-01-11 09:53:32 -08003200 @Override
3201 public void onAccountChanged() {
Mindy Pereira92551d02012-04-05 11:31:12 -07003202 mReplyFromAccount = mFromSpinner.getCurrentAccount();
3203 if (!mAccount.equals(mReplyFromAccount.account)) {
mindypf432dbc2012-11-12 16:00:44 -08003204 // Clear a signature, if there was one.
3205 mBodyView.removeTextChangedListener(this);
3206 String oldSignature = mSignature;
3207 String bodyText = getBody().getText().toString();
3208 if (!TextUtils.isEmpty(oldSignature)) {
3209 int pos = getSignatureStartPosition(oldSignature, bodyText);
3210 if (pos > -1) {
3211 mBodyView.setText(bodyText.substring(0, pos));
3212 }
3213 }
Paul Westbrookb1f573c2012-04-06 11:38:28 -07003214 setAccount(mReplyFromAccount.account);
mindypf432dbc2012-11-12 16:00:44 -08003215 mBodyView.addTextChangedListener(this);
Mindy Pereira181df782012-03-01 13:32:44 -08003216 // TODO: handle discarding attachments when switching accounts.
3217 // Only enable save for this draft if there is any other content
3218 // in the message.
3219 if (!isBlank()) {
3220 enableSave(true);
3221 }
3222 mReplyFromChanged = true;
3223 initRecipients();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003224 }
Mindy Pereira1a95a572012-01-05 12:21:29 -08003225 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003226
3227 public void enableSave(boolean enabled) {
3228 if (mSave != null) {
3229 mSave.setEnabled(enabled);
3230 }
3231 }
3232
Tony Mantler2558b502013-07-09 10:53:34 -07003233 public static class DiscardConfirmDialogFragment extends DialogFragment {
Paul Westbrookf0ea4842013-08-13 16:41:18 -07003234 // Public no-args constructor needed for fragment re-instantiation
3235 public DiscardConfirmDialogFragment() {}
3236
Tony Mantler2558b502013-07-09 10:53:34 -07003237 @Override
3238 public Dialog onCreateDialog(Bundle savedInstanceState) {
3239 return new AlertDialog.Builder(getActivity())
3240 .setMessage(R.string.confirm_discard_text)
3241 .setPositiveButton(R.string.discard,
3242 new DialogInterface.OnClickListener() {
3243 @Override
3244 public void onClick(DialogInterface dialog, int which) {
3245 ((ComposeActivity)getActivity()).doDiscardWithoutConfirmation();
3246 }
3247 })
Tony Mantler2b215b72013-07-31 10:20:46 -07003248 .setNegativeButton(R.string.cancel, null)
Tony Mantler2558b502013-07-09 10:53:34 -07003249 .create();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003250 }
3251 }
3252
Mindy Pereiraefe3d252012-03-01 14:20:44 -08003253 private void doDiscard() {
Tony Mantler2558b502013-07-09 10:53:34 -07003254 final DialogFragment frag = new DiscardConfirmDialogFragment();
3255 frag.show(getFragmentManager(), "discard confirm");
Mindy Pereiraefe3d252012-03-01 14:20:44 -08003256 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003257 /**
3258 * Effectively discard the current message.
3259 *
3260 * This method is either invoked from the menu or from the dialog
3261 * once the user has confirmed that they want to discard the message.
Mindy Pereira82cc5662012-01-09 17:29:30 -08003262 */
Tony Mantler2558b502013-07-09 10:53:34 -07003263 private void doDiscardWithoutConfirmation() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08003264 synchronized (mDraftLock) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08003265 if (mDraftId != UIProvider.INVALID_MESSAGE_ID) {
3266 ContentValues values = new ContentValues();
Paul Westbrookb7050e62012-03-20 12:59:44 -07003267 values.put(BaseColumns._ID, mDraftId);
Marc Blank78ea8e22012-08-04 11:14:06 -07003268 if (!mAccount.expungeMessageUri.equals(Uri.EMPTY)) {
Mindy Pereiracfb7f332012-02-28 10:23:43 -08003269 getContentResolver().update(mAccount.expungeMessageUri, values, null, null);
3270 } else {
Marc Blank0bbc8582012-04-23 15:07:57 -07003271 getContentResolver().delete(mDraft.uri, null, null);
Mindy Pereiracfb7f332012-02-28 10:23:43 -08003272 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08003273 // This is not strictly necessary (since we should not try to
3274 // save the draft after calling this) but it ensures that if we
3275 // do save again for some reason we make a new draft rather than
3276 // trying to resave an expunged draft.
3277 mDraftId = UIProvider.INVALID_MESSAGE_ID;
3278 }
3279 }
3280
Tony Mantler2558b502013-07-09 10:53:34 -07003281 // Display a toast to let the user know
3282 Toast.makeText(this, R.string.message_discarded, Toast.LENGTH_SHORT).show();
Mindy Pereira82cc5662012-01-09 17:29:30 -08003283
3284 // This prevents the draft from being saved in onPause().
3285 discardChanges();
Andy Huangdc97bf42013-08-15 16:52:45 -07003286 mPerformedSendOrDiscard = true;
Mindy Pereira82cc5662012-01-09 17:29:30 -08003287 finish();
3288 }
3289
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003290 private void saveIfNeeded() {
3291 if (mAccount == null) {
3292 // We have not chosen an account yet so there's no way that we can save. This is ok,
3293 // though, since we are saving our state before AccountsActivity is activated. Thus, the
3294 // user has not interacted with us yet and there is no real state to save.
3295 return;
3296 }
3297
3298 if (shouldSave()) {
Mindy Pereira48e31b02012-05-30 13:12:24 -07003299 doSave(!mAddingAttachment /* show toast */);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003300 }
3301 }
3302
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003303 @Override
3304 public void onAttachmentDeleted() {
3305 mAttachmentsChanged = true;
mindyp40882432012-09-06 11:07:40 -07003306 // If we are showing any attachments, make sure we have an upper
3307 // divider.
3308 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08003309 updateSaveUi();
3310 }
Mindy Pereira75f66632012-01-11 11:42:02 -08003311
mindyp40882432012-09-06 11:07:40 -07003312 @Override
3313 public void onAttachmentAdded() {
3314 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
3315 mAttachmentsView.focusLastAttachment();
3316 }
Mindy Pereira75f66632012-01-11 11:42:02 -08003317
3318 /**
3319 * This is called any time one of our text fields changes.
3320 */
Marc Blank0bbc8582012-04-23 15:07:57 -07003321 @Override
Mindy Pereira75f66632012-01-11 11:42:02 -08003322 public void afterTextChanged(Editable s) {
3323 mTextChanged = true;
3324 updateSaveUi();
3325 }
3326
3327 @Override
3328 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3329 // Do nothing.
3330 }
3331
Marc Blank0bbc8582012-04-23 15:07:57 -07003332 @Override
Mindy Pereira75f66632012-01-11 11:42:02 -08003333 public void onTextChanged(CharSequence s, int start, int before, int count) {
3334 // Do nothing.
3335 }
3336
3337
3338 // There is a big difference between the text associated with an address changing
3339 // to add the display name or to format properly and a recipient being added or deleted.
3340 // Make sure we only notify of changes when a recipient has been added or deleted.
3341 private class RecipientTextWatcher implements TextWatcher {
3342 private HashMap<String, Integer> mContent = new HashMap<String, Integer>();
3343
3344 private RecipientEditTextView mView;
3345
3346 private TextWatcher mListener;
3347
3348 public RecipientTextWatcher(RecipientEditTextView view, TextWatcher listener) {
3349 mView = view;
3350 mListener = listener;
3351 }
3352
3353 @Override
3354 public void afterTextChanged(Editable s) {
3355 if (hasChanged()) {
3356 mListener.afterTextChanged(s);
3357 }
3358 }
3359
3360 private boolean hasChanged() {
3361 String[] currRecips = tokenizeRecips(getAddressesFromList(mView));
3362 int totalCount = currRecips.length;
3363 int totalPrevCount = 0;
3364 for (Entry<String, Integer> entry : mContent.entrySet()) {
3365 totalPrevCount += entry.getValue();
3366 }
3367 if (totalCount != totalPrevCount) {
3368 return true;
3369 }
3370
3371 for (String recip : currRecips) {
3372 if (!mContent.containsKey(recip)) {
3373 return true;
3374 } else {
3375 int count = mContent.get(recip) - 1;
3376 if (count < 0) {
3377 return true;
3378 } else {
3379 mContent.put(recip, count);
3380 }
3381 }
3382 }
3383 return false;
3384 }
3385
3386 private String[] tokenizeRecips(String[] recips) {
3387 // Tokenize them all and put them in the list.
3388 String[] recipAddresses = new String[recips.length];
3389 for (int i = 0; i < recips.length; i++) {
3390 recipAddresses[i] = Rfc822Tokenizer.tokenize(recips[i])[0].getAddress();
3391 }
3392 return recipAddresses;
3393 }
3394
3395 @Override
3396 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3397 String[] recips = tokenizeRecips(getAddressesFromList(mView));
3398 for (String recip : recips) {
3399 if (!mContent.containsKey(recip)) {
3400 mContent.put(recip, 1);
3401 } else {
3402 mContent.put(recip, (mContent.get(recip)) + 1);
3403 }
3404 }
3405 }
3406
3407 @Override
3408 public void onTextChanged(CharSequence s, int start, int before, int count) {
3409 // Do nothing.
3410 }
3411 }
Mindy Pereirae011b1d2012-06-18 13:45:26 -07003412
3413 public static void registerTestSendOrSaveCallback(SendOrSaveCallback testCallback) {
3414 if (sTestSendOrSaveCallback != null && testCallback != null) {
3415 throw new IllegalStateException("Attempting to register more than one test callback");
3416 }
3417 sTestSendOrSaveCallback = testCallback;
3418 }
Mindy Pereirabddd6f32012-06-20 12:10:03 -07003419
3420 @VisibleForTesting
3421 protected ArrayList<Attachment> getAttachments() {
3422 return mAttachmentsView.getAttachments();
3423 }
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003424
3425 @Override
3426 public Loader<Cursor> onCreateLoader(int id, Bundle args) {
3427 switch (id) {
Alice Yanga990a712013-03-13 18:37:00 -07003428 case INIT_DRAFT_USING_REFERENCE_MESSAGE:
3429 return new CursorLoader(this, mRefMessageUri, UIProvider.MESSAGE_PROJECTION, null,
3430 null, null);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003431 case REFERENCE_MESSAGE_LOADER:
3432 return new CursorLoader(this, mRefMessageUri, UIProvider.MESSAGE_PROJECTION, null,
3433 null, null);
Mindy Pereirab199d172012-08-13 11:04:03 -07003434 case LOADER_ACCOUNT_CURSOR:
3435 return new CursorLoader(this, MailAppProvider.getAccountsUri(),
3436 UIProvider.ACCOUNTS_PROJECTION, null, null, null);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003437 }
3438 return null;
3439 }
3440
3441 @Override
3442 public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Mindy Pereirab199d172012-08-13 11:04:03 -07003443 int id = loader.getId();
3444 switch (id) {
Alice Yanga990a712013-03-13 18:37:00 -07003445 case INIT_DRAFT_USING_REFERENCE_MESSAGE:
Mindy Pereirab199d172012-08-13 11:04:03 -07003446 if (data != null && data.moveToFirst()) {
3447 mRefMessage = new Message(data);
Mindy Pereirab199d172012-08-13 11:04:03 -07003448 Intent intent = getIntent();
Alice Yanga990a712013-03-13 18:37:00 -07003449 initFromRefMessage(mComposeMode);
3450 finishSetup(mComposeMode, intent, null);
3451 if (mComposeMode != FORWARD) {
Mindy Pereirab199d172012-08-13 11:04:03 -07003452 String to = intent.getStringExtra(EXTRA_TO);
3453 if (!TextUtils.isEmpty(to)) {
Scott Kennedy0aeaf7d2012-11-14 18:56:05 -08003454 mRefMessage.setTo(null);
3455 mRefMessage.setFrom(null);
Mindy Pereirab199d172012-08-13 11:04:03 -07003456 clearChangeListeners();
3457 mTo.append(to);
3458 initChangeListeners();
3459 }
3460 }
3461 } else {
3462 finish();
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003463 }
Mindy Pereirab199d172012-08-13 11:04:03 -07003464 break;
Alice Yanga990a712013-03-13 18:37:00 -07003465 case REFERENCE_MESSAGE_LOADER:
3466 // Only populate mRefMessage and leave other fields untouched.
3467 if (data != null && data.moveToFirst()) {
3468 mRefMessage = new Message(data);
3469 }
Andy Huang9f855d62013-05-30 17:15:03 -07003470 finishSetup(mComposeMode, getIntent(), mInnerSavedState);
Alice Yanga990a712013-03-13 18:37:00 -07003471 break;
Mindy Pereirab199d172012-08-13 11:04:03 -07003472 case LOADER_ACCOUNT_CURSOR:
3473 if (data != null && data.moveToFirst()) {
3474 // there are accounts now!
3475 Account account;
Paul Westbrookfaa742f2012-11-01 09:50:16 -07003476 final ArrayList<Account> accounts = new ArrayList<Account>();
3477 final ArrayList<Account> initializedAccounts = new ArrayList<Account>();
Mindy Pereirab199d172012-08-13 11:04:03 -07003478 do {
3479 account = new Account(data);
Paul Westbrookdfa1dec2012-09-26 16:27:28 -07003480 if (account.isAccountReady()) {
Mindy Pereirab199d172012-08-13 11:04:03 -07003481 initializedAccounts.add(account);
3482 }
3483 accounts.add(account);
3484 } while (data.moveToNext());
3485 if (initializedAccounts.size() > 0) {
3486 findViewById(R.id.wait).setVisibility(View.GONE);
3487 getLoaderManager().destroyLoader(LOADER_ACCOUNT_CURSOR);
3488 findViewById(R.id.compose).setVisibility(View.VISIBLE);
Paul Westbrookfaa742f2012-11-01 09:50:16 -07003489 mAccounts = initializedAccounts.toArray(
3490 new Account[initializedAccounts.size()]);
3491
Mindy Pereirab199d172012-08-13 11:04:03 -07003492 finishCreate();
3493 invalidateOptionsMenu();
3494 } else {
3495 // Show "waiting"
3496 account = accounts.size() > 0 ? accounts.get(0) : null;
3497 showWaitFragment(account);
3498 }
3499 }
3500 break;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003501 }
3502 }
3503
Mindy Pereirab199d172012-08-13 11:04:03 -07003504 private void showWaitFragment(Account account) {
3505 WaitFragment fragment = getWaitFragment();
3506 if (fragment != null) {
3507 fragment.updateAccount(account);
3508 } else {
3509 findViewById(R.id.wait).setVisibility(View.VISIBLE);
3510 replaceFragment(WaitFragment.newInstance(account, true),
3511 FragmentTransaction.TRANSIT_FRAGMENT_OPEN, TAG_WAIT);
3512 }
3513 }
3514
3515 private WaitFragment getWaitFragment() {
3516 return (WaitFragment) getFragmentManager().findFragmentByTag(TAG_WAIT);
3517 }
3518
3519 private int replaceFragment(Fragment fragment, int transition, String tag) {
3520 FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
Mindy Pereirab199d172012-08-13 11:04:03 -07003521 fragmentTransaction.setTransition(transition);
3522 fragmentTransaction.replace(R.id.wait, fragment, tag);
3523 final int transactionId = fragmentTransaction.commitAllowingStateLoss();
3524 return transactionId;
3525 }
3526
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003527 @Override
3528 public void onLoaderReset(Loader<Cursor> arg0) {
3529 // Do nothing.
3530 }
Paul Westbrook83e6b572013-02-05 16:22:42 -08003531
3532 @Override
3533 public Context getActivityContext() {
3534 return this;
3535 }
Andy Huang1f8f4dd2012-10-25 21:35:35 -07003536}