blob: 6d2b9f0865f9caa90135381173e7ddd8240d8ebb [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;
Mindy Pereirab199d172012-08-13 11:04:03 -070025import android.app.Fragment;
Mindy Pereirab199d172012-08-13 11:04:03 -070026import android.app.FragmentTransaction;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -070027import android.app.LoaderManager;
Mindy Pereira6349a042012-01-04 11:25:01 -080028import android.content.ContentResolver;
Mindy Pereira82cc5662012-01-09 17:29:30 -080029import android.content.ContentValues;
Mindy Pereira6349a042012-01-04 11:25:01 -080030import android.content.Context;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -070031import android.content.CursorLoader;
Mindy Pereira82cc5662012-01-09 17:29:30 -080032import android.content.DialogInterface;
Mindy Pereira6349a042012-01-04 11:25:01 -080033import android.content.Intent;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -070034import android.content.Loader;
Mindy Pereira82cc5662012-01-09 17:29:30 -080035import android.content.pm.ActivityInfo;
Mindy Pereira7ed1c112012-01-18 10:59:25 -080036import android.database.Cursor;
Mindy Pereira6349a042012-01-04 11:25:01 -080037import android.net.Uri;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080038import android.os.Bundle;
Mindy Pereira82cc5662012-01-09 17:29:30 -080039import android.os.Handler;
40import android.os.HandlerThread;
Paul Westbrookf97588b2012-03-20 11:11:37 -070041import android.os.Parcelable;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -070042import android.os.ParcelFileDescriptor;
Mindy Pereira82cc5662012-01-09 17:29:30 -080043import android.provider.BaseColumns;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080044import android.text.Editable;
Mindy Pereira82cc5662012-01-09 17:29:30 -080045import android.text.Html;
mindyped9c2f02012-10-12 10:02:08 -070046import android.text.SpannableString;
Mindy Pereira82cc5662012-01-09 17:29:30 -080047import android.text.Spanned;
Paul Westbrookc1827622012-01-06 11:27:12 -080048import android.text.TextUtils;
Mindy Pereira82cc5662012-01-09 17:29:30 -080049import android.text.TextWatcher;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080050import android.text.util.Rfc822Token;
Mindy Pereirac17d0732011-12-29 10:46:19 -080051import android.text.util.Rfc822Tokenizer;
Mindy Pereira3cd4f402012-07-17 11:16:18 -070052import android.view.Gravity;
mindyp62d3ec72012-08-24 13:04:09 -070053import android.view.KeyEvent;
Mindy Pereira326c6602012-01-04 15:32:42 -080054import android.view.LayoutInflater;
Mindy Pereirab47f3e22011-12-13 14:25:04 -080055import android.view.Menu;
56import android.view.MenuInflater;
57import android.view.MenuItem;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080058import android.view.View;
59import android.view.View.OnClickListener;
Andy Huang5c5fd572012-04-08 18:19:29 -070060import android.view.ViewGroup;
mindyp62d3ec72012-08-24 13:04:09 -070061import android.view.inputmethod.EditorInfo;
Mindy Pereira326c6602012-01-04 15:32:42 -080062import android.widget.ArrayAdapter;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080063import android.widget.Button;
Mindy Pereira433b1982012-04-03 11:53:07 -070064import android.widget.EditText;
Mindy Pereira6349a042012-01-04 11:25:01 -080065import android.widget.TextView;
Mindy Pereira013194c2012-01-06 15:09:33 -080066import android.widget.Toast;
Mindy Pereira7b56a612011-12-14 12:32:28 -080067
Mindy Pereirac17d0732011-12-29 10:46:19 -080068import com.android.common.Rfc822Validator;
Andy Huang5c5fd572012-04-08 18:19:29 -070069import com.android.ex.chips.RecipientEditTextView;
70import com.android.mail.R;
mindyp40882432012-09-06 11:07:40 -070071import com.android.mail.compose.AttachmentsView.AttachmentAddedOrDeletedListener;
Mindy Pereira9932dee2012-01-10 16:09:50 -080072import com.android.mail.compose.AttachmentsView.AttachmentFailureException;
Mindy Pereira5a85e2b2012-01-11 09:53:32 -080073import com.android.mail.compose.FromAddressSpinner.OnAccountChangedListener;
Andy Huang30e2c242012-01-06 18:14:30 -080074import com.android.mail.compose.QuotedTextView.RespondInlineListener;
Mindy Pereira33fe9082012-01-09 16:24:30 -080075import com.android.mail.providers.Account;
Andy Huang30e2c242012-01-06 18:14:30 -080076import com.android.mail.providers.Address;
77import com.android.mail.providers.Attachment;
Mindy Pereira47d0e652012-07-23 09:45:07 -070078import com.android.mail.providers.MailAppProvider;
Mindy Pereira3ce64e72012-01-13 14:29:45 -080079import com.android.mail.providers.Message;
Mindy Pereira82cc5662012-01-09 17:29:30 -080080import com.android.mail.providers.MessageModification;
Mindy Pereira92551d02012-04-05 11:31:12 -070081import com.android.mail.providers.ReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -080082import com.android.mail.providers.Settings;
Andy Huang30e2c242012-01-06 18:14:30 -080083import com.android.mail.providers.UIProvider;
Mindy Pereira3ca5bad2012-04-16 11:02:42 -070084import com.android.mail.providers.UIProvider.AccountCapabilities;
Mindy Pereira12575862012-03-21 16:30:54 -070085import com.android.mail.providers.UIProvider.DraftType;
Mindy Pereirafa20c1a2012-07-23 13:00:02 -070086import com.android.mail.ui.MailActivity;
Mindy Pereirab199d172012-08-13 11:04:03 -070087import com.android.mail.ui.WaitFragment;
Mark Wei62066e42012-09-13 12:07:02 -070088import com.android.mail.ui.AttachmentTile.AttachmentPreview;
Paul Westbrook92227f62012-03-20 10:32:51 -070089import com.android.mail.utils.AccountUtils;
Mark Wei434f2942012-08-24 11:54:02 -070090import com.android.mail.utils.AttachmentUtils;
mindypfebd2262012-11-13 17:45:09 -080091import com.android.mail.utils.ContentProviderTask;
Paul Westbrookb334c902012-06-25 11:42:46 -070092import com.android.mail.utils.LogTag;
Andy Huang30e2c242012-01-06 18:14:30 -080093import com.android.mail.utils.LogUtils;
Andy Huang30e2c242012-01-06 18:14:30 -080094import com.android.mail.utils.Utils;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080095import com.google.common.annotations.VisibleForTesting;
Mindy Pereira82cc5662012-01-09 17:29:30 -080096import com.google.common.collect.Lists;
Mindy Pereira4a27ea92012-01-05 15:55:25 -080097import com.google.common.collect.Sets;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080098
Paul Westbrook3c7f94d2012-10-23 14:13:00 -070099import java.io.FileNotFoundException;
100import java.io.IOException;
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700101import java.io.UnsupportedEncodingException;
102import java.net.URLDecoder;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800103import java.util.ArrayList;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700104import java.util.Arrays;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800105import java.util.Collection;
Mindy Pereira75f66632012-01-11 11:42:02 -0800106import java.util.HashMap;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800107import java.util.HashSet;
108import java.util.List;
Paul Westbrook1c078cf2012-03-20 16:18:51 -0700109import java.util.Map.Entry;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700110import java.util.Set;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800111import java.util.concurrent.ConcurrentHashMap;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800112
113public class ComposeActivity extends Activity implements OnClickListener, OnNavigationListener,
Mindy Pereira5a85e2b2012-01-11 09:53:32 -0800114 RespondInlineListener, DialogInterface.OnClickListener, TextWatcher,
mindyp40882432012-09-06 11:07:40 -0700115 AttachmentAddedOrDeletedListener, OnAccountChangedListener, LoaderManager.LoaderCallbacks<Cursor>,
mindyp62d3ec72012-08-24 13:04:09 -0700116 TextView.OnEditorActionListener {
Mindy Pereira6349a042012-01-04 11:25:01 -0800117 // Identifiers for which type of composition this is
Mindy Pereira36bbcae2012-04-25 09:27:04 -0700118 static final int COMPOSE = -1;
119 static final int REPLY = 0;
120 static final int REPLY_ALL = 1;
121 static final int FORWARD = 2;
122 static final int EDIT_DRAFT = 3;
Mindy Pereira6349a042012-01-04 11:25:01 -0800123
124 // Integer extra holding one of the above compose action
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700125 protected static final String EXTRA_ACTION = "action";
Mindy Pereira6349a042012-01-04 11:25:01 -0800126
Mindy Pereira326689d2012-05-17 10:14:14 -0700127 private static final String EXTRA_SHOW_CC = "showCc";
128 private static final String EXTRA_SHOW_BCC = "showBcc";
Mindy Pereiraa34c9a02012-04-17 14:10:53 -0700129
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700130 private static final String UTF8_ENCODING_NAME = "UTF-8";
131
132 private static final String MAIL_TO = "mailto";
133
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700134 private static final String EXTRA_SUBJECT = "subject";
135
136 private static final String EXTRA_BODY = "body";
137
mindypd27b6ea2012-10-05 09:43:49 -0700138 protected static final String EXTRA_FROM_ACCOUNT_STRING = "fromAccountString";
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700139
Mark Wei62066e42012-09-13 12:07:02 -0700140 private static final String EXTRA_ATTACHMENT_PREVIEWS = "attachmentPreviews";
141
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700142 // Extra that we can get passed from other activities
143 private static final String EXTRA_TO = "to";
144 private static final String EXTRA_CC = "cc";
145 private static final String EXTRA_BCC = "bcc";
146
147 // List of all the fields
148 static final String[] ALL_EXTRAS = { EXTRA_SUBJECT, EXTRA_BODY, EXTRA_TO, EXTRA_CC, EXTRA_BCC };
149
Mindy Pereira82cc5662012-01-09 17:29:30 -0800150 private static SendOrSaveCallback sTestSendOrSaveCallback = null;
151 // Map containing information about requests to create new messages, and the id of the
152 // messages that were the result of those requests.
153 //
154 // This map is used when the activity that initiated the save a of a new message, is killed
155 // before the save has completed (and when we know the id of the newly created message). When
156 // a save is completed, the service that is running in the background, will update the map
157 //
158 // When a new ComposeActivity instance is created, it will attempt to use the information in
159 // the previously instantiated map. If ComposeActivity.onCreate() is called, with a bundle
160 // (restoring data from a previous instance), and the map hasn't been created, we will attempt
161 // to populate the map with data stored in shared preferences.
Andy Huang1f8f4dd2012-10-25 21:35:35 -0700162 // FIXME: values in this map are never read.
Mindy Pereira82cc5662012-01-09 17:29:30 -0800163 private static ConcurrentHashMap<Integer, Long> sRequestMessageIdMap = null;
164 // Key used to store the above map
165 private static final String CACHED_MESSAGE_REQUEST_IDS_KEY = "cache-message-request-ids";
Mindy Pereira6349a042012-01-04 11:25:01 -0800166 /**
167 * Notifies the {@code Activity} that the caller is an Email
168 * {@code Activity}, so that the back behavior may be modified accordingly.
169 *
170 * @see #onAppUpPressed
171 */
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700172 public static final String EXTRA_FROM_EMAIL_TASK = "fromemail";
Mindy Pereira6349a042012-01-04 11:25:01 -0800173
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700174 public static final String EXTRA_ATTACHMENTS = "attachments";
Paul Westbrookf97588b2012-03-20 11:11:37 -0700175
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800176 // If this is a reply/forward then this extra will hold the original message
Mindy Pereira36bbcae2012-04-25 09:27:04 -0700177 private static final String EXTRA_IN_REFERENCE_TO_MESSAGE = "in-reference-to-message";
Mindy Pereirab18e5a92012-07-10 11:47:21 -0700178 // If this is a reply/forward then this extra will hold a uri we must query
179 // to get the original message.
180 protected static final String EXTRA_IN_REFERENCE_TO_MESSAGE_URI = "in-reference-to-message-uri";
Mark Wei434f2942012-08-24 11:54:02 -0700181 // If this is an action to edit an existing draft message, this extra will hold the
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700182 // draft message
183 private static final String ORIGINAL_DRAFT_MESSAGE = "original-draft-message";
Mindy Pereira4a27ea92012-01-05 15:55:25 -0800184 private static final String END_TOKEN = ", ";
Paul Westbrookb334c902012-06-25 11:42:46 -0700185 private static final String LOG_TAG = LogTag.getLogTag();
Mindy Pereira013194c2012-01-06 15:09:33 -0800186 // Request numbers for activities we start
187 private static final int RESULT_PICK_ATTACHMENT = 1;
188 private static final int RESULT_CREATE_ACCOUNT = 2;
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700189 // TODO(mindyp) set mime-type for auto send?
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700190 public static final String AUTO_SEND_ACTION = "com.android.mail.action.AUTO_SEND";
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700191
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700192 private static final String EXTRA_SELECTED_REPLY_FROM_ACCOUNT = "replyFromAccount";
193 private static final String EXTRA_REQUEST_ID = "requestId";
194 private static final String EXTRA_FOCUS_SELECTION_START = "focusSelectionStart";
195 private static final String EXTRA_FOCUS_SELECTION_END = null;
196 private static final String EXTRA_MESSAGE = "extraMessage";
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700197 private static final int REFERENCE_MESSAGE_LOADER = 0;
Mindy Pereirab199d172012-08-13 11:04:03 -0700198 private static final int LOADER_ACCOUNT_CURSOR = 1;
Mindy Pereira47d0e652012-07-23 09:45:07 -0700199 private static final String EXTRA_SELECTED_ACCOUNT = "selectedAccount";
Mindy Pereirab199d172012-08-13 11:04:03 -0700200 private static final String TAG_WAIT = "wait-fragment";
Mindy Pereira2db7d4a2012-08-15 11:00:02 -0700201 private static final String MIME_TYPE_PHOTO = "image/*";
202 private static final String MIME_TYPE_VIDEO = "video/*";
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800203
Mindy Pereira82cc5662012-01-09 17:29:30 -0800204 /**
205 * A single thread for running tasks in the background.
206 */
207 private Handler mSendSaveTaskHandler = null;
Mindy Pereirac17d0732011-12-29 10:46:19 -0800208 private RecipientEditTextView mTo;
209 private RecipientEditTextView mCc;
210 private RecipientEditTextView mBcc;
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800211 private Button mCcBccButton;
212 private CcBccView mCcBccView;
Mindy Pereira7b56a612011-12-14 12:32:28 -0800213 private AttachmentsView mAttachmentsView;
Mindy Pereira33fe9082012-01-09 16:24:30 -0800214 private Account mAccount;
Mindy Pereira92551d02012-04-05 11:31:12 -0700215 private ReplyFromAccount mReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -0800216 private Settings mCachedSettings;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800217 private Rfc822Validator mValidator;
Mindy Pereira6349a042012-01-04 11:25:01 -0800218 private TextView mSubject;
219
Mindy Pereira326c6602012-01-04 15:32:42 -0800220 private ComposeModeAdapter mComposeModeAdapter;
221 private int mComposeMode = -1;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800222 private boolean mForward;
223 private String mRecipient;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800224 private QuotedTextView mQuotedTextView;
Mindy Pereira433b1982012-04-03 11:53:07 -0700225 private EditText mBodyView;
Mindy Pereira1a95a572012-01-05 12:21:29 -0800226 private View mFromStatic;
Mindy Pereira2eb17322012-03-07 10:07:34 -0800227 private TextView mFromStaticText;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800228 private View mFromSpinnerWrapper;
Mindy Pereira1883b342012-06-20 08:34:56 -0700229 @VisibleForTesting
230 protected FromAddressSpinner mFromSpinner;
Mindy Pereira013194c2012-01-06 15:09:33 -0800231 private boolean mAddingAttachment;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800232 private boolean mAttachmentsChanged;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800233 private boolean mTextChanged;
234 private boolean mReplyFromChanged;
235 private MenuItem mSave;
236 private MenuItem mSend;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800237 private AlertDialog mRecipientErrorDialog;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800238 private AlertDialog mSendConfirmDialog;
Mindy Pereirab3112a22012-06-20 12:10:03 -0700239 @VisibleForTesting
240 protected Message mRefMessage;
Mindy Pereira7ed1c112012-01-18 10:59:25 -0800241 private long mDraftId = UIProvider.INVALID_MESSAGE_ID;
242 private Message mDraft;
mindyp44a63392012-11-05 12:05:16 -0800243 private ReplyFromAccount mDraftAccount;
Mindy Pereira7ed1c112012-01-18 10:59:25 -0800244 private Object mDraftLock = new Object();
mindyp93b079b2012-08-29 16:32:15 -0700245 private View mPhotoAttachmentsButton;
246 private View mVideoAttachmentsButton;
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800247
Mindy Pereira326c6602012-01-04 15:32:42 -0800248 /**
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700249 * Boolean indicating whether ComposeActivity was launched from a Gmail controlled view.
250 */
251 private boolean mLaunchedFromEmail = false;
Mindy Pereiracbfb75a2012-06-25 14:52:23 -0700252 private RecipientTextWatcher mToListener;
253 private RecipientTextWatcher mCcListener;
254 private RecipientTextWatcher mBccListener;
Mindy Pereirab18e5a92012-07-10 11:47:21 -0700255 private Uri mRefMessageUri;
Mindy Pereirab199d172012-08-13 11:04:03 -0700256 private Bundle mSavedInstanceState;
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700257
258
259 /**
Mindy Pereira326c6602012-01-04 15:32:42 -0800260 * Can be called from a non-UI thread.
261 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800262 public static void editDraft(Context launcher, Account account, Message message) {
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700263 launch(launcher, account, message, EDIT_DRAFT);
Mindy Pereira326c6602012-01-04 15:32:42 -0800264 }
265
Mindy Pereira6349a042012-01-04 11:25:01 -0800266 /**
267 * Can be called from a non-UI thread.
268 */
Mindy Pereira33fe9082012-01-09 16:24:30 -0800269 public static void compose(Context launcher, Account account) {
Mindy Pereira6349a042012-01-04 11:25:01 -0800270 launch(launcher, account, null, COMPOSE);
271 }
272
273 /**
274 * Can be called from a non-UI thread.
275 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800276 public static void reply(Context launcher, Account account, Message message) {
277 launch(launcher, account, message, REPLY);
Mindy Pereira6349a042012-01-04 11:25:01 -0800278 }
279
280 /**
281 * Can be called from a non-UI thread.
282 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800283 public static void replyAll(Context launcher, Account account, Message message) {
284 launch(launcher, account, message, REPLY_ALL);
Mindy Pereira6349a042012-01-04 11:25:01 -0800285 }
286
287 /**
288 * Can be called from a non-UI thread.
289 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800290 public static void forward(Context launcher, Account account, Message message) {
291 launch(launcher, account, message, FORWARD);
Mindy Pereira6349a042012-01-04 11:25:01 -0800292 }
293
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800294 private static void launch(Context launcher, Account account, Message message, int action) {
Mindy Pereira6349a042012-01-04 11:25:01 -0800295 Intent intent = new Intent(launcher, ComposeActivity.class);
296 intent.putExtra(EXTRA_FROM_EMAIL_TASK, true);
297 intent.putExtra(EXTRA_ACTION, action);
298 intent.putExtra(Utils.EXTRA_ACCOUNT, account);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700299 if (action == EDIT_DRAFT) {
300 intent.putExtra(ORIGINAL_DRAFT_MESSAGE, message);
301 } else {
302 intent.putExtra(EXTRA_IN_REFERENCE_TO_MESSAGE, message);
303 }
Mindy Pereira6349a042012-01-04 11:25:01 -0800304 launcher.startActivity(intent);
305 }
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800306
307 @Override
308 public void onCreate(Bundle savedInstanceState) {
309 super.onCreate(savedInstanceState);
Mindy Pereira3528d362012-01-05 14:39:44 -0800310 setContentView(R.layout.compose);
Mindy Pereirab199d172012-08-13 11:04:03 -0700311 mSavedInstanceState = savedInstanceState;
312 checkValidAccounts();
313 }
314
315 private void finishCreate() {
316 Bundle savedInstanceState = mSavedInstanceState;
Mindy Pereira3528d362012-01-05 14:39:44 -0800317 findViews();
Mindy Pereira818143e2012-01-11 13:59:49 -0800318 Intent intent = getIntent();
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700319 Message message;
Mark Wei62066e42012-09-13 12:07:02 -0700320 ArrayList<AttachmentPreview> previews;
Mindy Pereira71c9e562012-05-17 11:01:02 -0700321 boolean showQuotedText = false;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700322 int action;
Mindy Pereira47d0e652012-07-23 09:45:07 -0700323 // Check for any of the possibly supplied accounts.;
324 Account account = null;
Mindy Pereiraf7fc6c32012-06-19 15:18:33 -0700325 if (hadSavedInstanceStateMessage(savedInstanceState)) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700326 action = savedInstanceState.getInt(EXTRA_ACTION, COMPOSE);
327 account = savedInstanceState.getParcelable(Utils.EXTRA_ACCOUNT);
328 message = (Message) savedInstanceState.getParcelable(EXTRA_MESSAGE);
Mark Wei62066e42012-09-13 12:07:02 -0700329
330 previews = savedInstanceState.getParcelableArrayList(EXTRA_ATTACHMENT_PREVIEWS);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700331 mRefMessage = (Message) savedInstanceState.getParcelable(EXTRA_IN_REFERENCE_TO_MESSAGE);
332 } else {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700333 account = obtainAccount(intent);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700334 action = intent.getIntExtra(EXTRA_ACTION, COMPOSE);
335 // Initialize the message from the message in the intent
336 message = (Message) intent.getParcelableExtra(ORIGINAL_DRAFT_MESSAGE);
Mark Wei62066e42012-09-13 12:07:02 -0700337 previews = intent.getParcelableArrayListExtra(EXTRA_ATTACHMENT_PREVIEWS);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700338 mRefMessage = (Message) intent.getParcelableExtra(EXTRA_IN_REFERENCE_TO_MESSAGE);
Mindy Pereirab18e5a92012-07-10 11:47:21 -0700339 mRefMessageUri = (Uri) intent.getParcelableExtra(EXTRA_IN_REFERENCE_TO_MESSAGE_URI);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700340 }
Mark Wei62066e42012-09-13 12:07:02 -0700341 mAttachmentsView.setAttachmentPreviews(previews);
Paul Westbrook92227f62012-03-20 10:32:51 -0700342
343 setAccount(account);
Mindy Pereira818143e2012-01-11 13:59:49 -0800344 if (mAccount == null) {
345 return;
346 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700347
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700348 if (intent.getBooleanExtra(EXTRA_FROM_EMAIL_TASK, false)) {
349 mLaunchedFromEmail = true;
350 } else if (Intent.ACTION_SEND.equals(intent.getAction())) {
351 final Uri dataUri = intent.getData();
352 if (dataUri != null) {
353 final String dataScheme = intent.getData().getScheme();
354 final String accountScheme = mAccount.composeIntentUri.getScheme();
355 mLaunchedFromEmail = TextUtils.equals(dataScheme, accountScheme);
356 }
357 }
358
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700359 if (mRefMessageUri != null) {
360 // We have a referenced message that we must look up.
361 getLoaderManager().initLoader(REFERENCE_MESSAGE_LOADER, null, this);
362 return;
363 } else if (message != null && action != EDIT_DRAFT) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700364 initFromDraftMessage(message);
365 initQuotedTextFromRefMessage(mRefMessage, action);
Mindy Pereiraa34c9a02012-04-17 14:10:53 -0700366 showCcBcc(savedInstanceState);
Mindy Pereira71c9e562012-05-17 11:01:02 -0700367 showQuotedText = message.appendRefMessageContent;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700368 } else if (action == EDIT_DRAFT) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700369 initFromDraftMessage(message);
Scott Kennedy8960f0a2012-11-07 15:35:50 -0800370 boolean showBcc = !TextUtils.isEmpty(message.getBcc());
371 boolean showCc = showBcc || !TextUtils.isEmpty(message.getCc());
Mindy Pereiraef388302012-06-18 19:07:44 -0700372 mCcBccView.show(false, showCc, showBcc);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700373 // Update the action to the draft type of the previous draft
374 switch (message.draftType) {
375 case UIProvider.DraftType.REPLY:
376 action = REPLY;
377 break;
378 case UIProvider.DraftType.REPLY_ALL:
379 action = REPLY_ALL;
380 break;
381 case UIProvider.DraftType.FORWARD:
382 action = FORWARD;
383 break;
384 case UIProvider.DraftType.COMPOSE:
385 default:
386 action = COMPOSE;
387 break;
388 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700389 initQuotedTextFromRefMessage(mRefMessage, action);
Mindy Pereira71c9e562012-05-17 11:01:02 -0700390 showQuotedText = message.appendRefMessageContent;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700391 } else if ((action == REPLY || action == REPLY_ALL || action == FORWARD)) {
392 if (mRefMessage != null) {
393 initFromRefMessage(action, mAccount.name);
Mindy Pereira71c9e562012-05-17 11:01:02 -0700394 showQuotedText = true;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700395 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700396 } else {
397 initFromExtras(intent);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700398 }
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700399 finishSetup(action, intent, savedInstanceState, showQuotedText);
400 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700401
Mindy Pereirab199d172012-08-13 11:04:03 -0700402 private void checkValidAccounts() {
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700403 final Account[] allAccounts = AccountUtils.getAccounts(this);
404 if (allAccounts == null || allAccounts.length == 0) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700405 final Intent noAccountIntent = MailAppProvider.getNoAccountIntent(this);
406 if (noAccountIntent != null) {
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700407 mAccounts = null;
Mindy Pereirab199d172012-08-13 11:04:03 -0700408 startActivityForResult(noAccountIntent, RESULT_CREATE_ACCOUNT);
409 }
410 } else {
mindyp26d4d2d2012-09-18 17:30:32 -0700411 // If none of the accounts are syncing, setup a watcher.
Mindy Pereirab199d172012-08-13 11:04:03 -0700412 boolean anySyncing = false;
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700413 for (Account a : allAccounts) {
Paul Westbrookdfa1dec2012-09-26 16:27:28 -0700414 if (a.isAccountReady()) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700415 anySyncing = true;
416 break;
417 }
418 }
419 if (!anySyncing) {
420 // There are accounts, but none are sync'd, which is just like having no accounts.
421 mAccounts = null;
422 getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, null, this);
423 return;
424 }
Paul Westbrookfaa742f2012-11-01 09:50:16 -0700425 mAccounts = AccountUtils.getSyncingAccounts(this);
Mindy Pereirab199d172012-08-13 11:04:03 -0700426 finishCreate();
427 }
428 }
429
Mindy Pereira47d0e652012-07-23 09:45:07 -0700430 private Account obtainAccount(Intent intent) {
431 Account account = null;
432 Object accountExtra = null;
433 if (intent != null && intent.getExtras() != null) {
434 accountExtra = intent.getExtras().get(Utils.EXTRA_ACCOUNT);
435 if (accountExtra instanceof Account) {
436 return (Account) accountExtra;
mindyp7ae042e2012-08-27 13:27:37 -0700437 } else if (accountExtra instanceof String) {
438 // This is the Account attached to the widget compose intent.
439 account = Account.newinstance((String)accountExtra);
440 if (account != null) {
441 return account;
442 }
Mindy Pereira47d0e652012-07-23 09:45:07 -0700443 }
444 accountExtra = intent.getStringExtra(EXTRA_SELECTED_ACCOUNT);
445 }
446 if (account == null) {
mindyp06174462012-10-12 09:11:27 -0700447 MailAppProvider provider = MailAppProvider.getInstance();
448 String lastAccountUri = provider.getLastSentFromAccount();
449 if (TextUtils.isEmpty(lastAccountUri)) {
450 lastAccountUri = provider.getLastViewedAccount();
451 }
Mindy Pereira47d0e652012-07-23 09:45:07 -0700452 if (!TextUtils.isEmpty(lastAccountUri)) {
453 accountExtra = Uri.parse(lastAccountUri);
454 }
455 }
Mindy Pereirab199d172012-08-13 11:04:03 -0700456 if (mAccounts != null && mAccounts.length > 0) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700457 if (accountExtra instanceof String && !TextUtils.isEmpty((String) accountExtra)) {
458 // For backwards compatibility, we need to check account
459 // names.
Mindy Pereirab199d172012-08-13 11:04:03 -0700460 for (Account a : mAccounts) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700461 if (a.name.equals(accountExtra)) {
462 account = a;
463 }
464 }
465 } else if (accountExtra instanceof Uri) {
466 // The uri of the last viewed account is what is stored in
467 // the current code base.
Mindy Pereirab199d172012-08-13 11:04:03 -0700468 for (Account a : mAccounts) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700469 if (a.uri.equals(accountExtra)) {
470 account = a;
471 }
472 }
Mindy Pereirab199d172012-08-13 11:04:03 -0700473 }
474 if (account == null) {
475 account = mAccounts[0];
Mindy Pereira47d0e652012-07-23 09:45:07 -0700476 }
477 }
478 return account;
479 }
480
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700481 private void finishSetup(int action, Intent intent, Bundle savedInstanceState,
482 boolean showQuotedText) {
mindyp34a3c562012-11-06 15:12:15 -0800483 setFocus(action);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700484 if (action == COMPOSE) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800485 mQuotedTextView.setVisibility(View.GONE);
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800486 }
Mindy Pereira818143e2012-01-11 13:59:49 -0800487 initRecipients();
Mindy Pereiraf7fc6c32012-06-19 15:18:33 -0700488 // Don't bother with the intent if we have procured a message from the
489 // intent already.
490 if (!hadSavedInstanceStateMessage(savedInstanceState)) {
491 initAttachmentsFromIntent(intent);
492 }
Mindy Pereira1a95a572012-01-05 12:21:29 -0800493 initActionBar(action);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700494 initFromSpinner(savedInstanceState != null ? savedInstanceState : intent.getExtras(),
495 action);
mindypd4a48662012-11-08 17:13:49 -0800496
497 // If this is a draft message, the draft account is whatever account was
498 // used to open the draft message in Compose.
499 if (mDraft != null) {
500 mDraftAccount = mReplyFromAccount;
501 }
502
Mindy Pereira75f66632012-01-11 11:42:02 -0800503 initChangeListeners();
Mindy Pereira326689d2012-05-17 10:14:14 -0700504 updateHideOrShowCcBcc();
Mindy Pereira71c9e562012-05-17 11:01:02 -0700505 updateHideOrShowQuotedText(showQuotedText);
506 }
507
Mindy Pereiraf7fc6c32012-06-19 15:18:33 -0700508 private boolean hadSavedInstanceStateMessage(Bundle savedInstanceState) {
509 return savedInstanceState != null && savedInstanceState.containsKey(EXTRA_MESSAGE);
510 }
511
Mindy Pereira71c9e562012-05-17 11:01:02 -0700512 private void updateHideOrShowQuotedText(boolean showQuotedText) {
513 mQuotedTextView.updateCheckedState(showQuotedText);
mindyp40882432012-09-06 11:07:40 -0700514 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
Mindy Pereira433b1982012-04-03 11:53:07 -0700515 }
516
517 private void setFocus(int action) {
518 if (action == EDIT_DRAFT) {
519 int type = mDraft.draftType;
520 switch (type) {
521 case UIProvider.DraftType.COMPOSE:
522 case UIProvider.DraftType.FORWARD:
523 action = COMPOSE;
524 break;
525 case UIProvider.DraftType.REPLY:
526 case UIProvider.DraftType.REPLY_ALL:
527 default:
528 action = REPLY;
529 break;
530 }
531 }
532 switch (action) {
533 case FORWARD:
534 case COMPOSE:
535 mTo.requestFocus();
536 break;
537 case REPLY:
538 case REPLY_ALL:
539 default:
540 focusBody();
541 break;
542 }
543 }
544
545 /**
546 * Focus the body of the message.
547 */
548 public void focusBody() {
549 mBodyView.requestFocus();
550 int length = mBodyView.getText().length();
551
552 int signatureStartPos = getSignatureStartPosition(
553 mSignature, mBodyView.getText().toString());
554 if (signatureStartPos > -1) {
555 // In case the user deleted the newlines...
556 mBodyView.setSelection(signatureStartPos);
mindyp8743cfc2012-09-18 13:29:08 -0700557 } else if (length >= 0) {
Mindy Pereira433b1982012-04-03 11:53:07 -0700558 // Move cursor to the end.
559 mBodyView.setSelection(length);
560 }
Mindy Pereira1a95a572012-01-05 12:21:29 -0800561 }
562
563 @Override
564 protected void onResume() {
565 super.onResume();
566 // Update the from spinner as other accounts
567 // may now be available.
Mindy Pereira818143e2012-01-11 13:59:49 -0800568 if (mFromSpinner != null && mAccount != null) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700569 mFromSpinner.asyncInitFromSpinner(mComposeMode, mAccount, mAccounts);
Mindy Pereira818143e2012-01-11 13:59:49 -0800570 }
Mindy Pereira1a95a572012-01-05 12:21:29 -0800571 }
572
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800573 @Override
574 protected void onPause() {
575 super.onPause();
576
577 if (mSendConfirmDialog != null) {
578 mSendConfirmDialog.dismiss();
579 }
580 if (mRecipientErrorDialog != null) {
581 mRecipientErrorDialog.dismiss();
582 }
Mindy Pereiraa2148332012-07-02 13:54:14 -0700583 // When the user exits the compose view, see if this draft needs saving.
Yorke Lee3d7048e2012-09-19 14:19:25 -0700584 // Don't save unnecessary drafts if we are only changing the orientation.
585 if (!isChangingConfigurations()) {
Mindy Pereiraa2148332012-07-02 13:54:14 -0700586 saveIfNeeded();
587 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800588 }
589
590 @Override
591 protected final void onActivityResult(int request, int result, Intent data) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700592 if (request == RESULT_PICK_ATTACHMENT && result == RESULT_OK) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800593 addAttachmentAndUpdateView(data);
Mindy Pereirab199d172012-08-13 11:04:03 -0700594 mAddingAttachment = false;
595 } else if (request == RESULT_CREATE_ACCOUNT) {
596 // We were waiting for the user to create an account
597 if (result != RESULT_OK) {
598 finish();
599 } else {
600 // Watch for accounts to show up!
601 // restart the loader to get the updated list of accounts
602 getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, null, this);
603 showWaitFragment(null);
604 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800605 }
606 }
607
608 @Override
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700609 public final void onRestoreInstanceState(Bundle savedInstanceState) {
mindyp47db6d72012-11-14 09:58:28 -0800610 clearChangeListeners();
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700611 super.onRestoreInstanceState(savedInstanceState);
612 if (savedInstanceState != null) {
613 if (savedInstanceState.containsKey(EXTRA_FOCUS_SELECTION_START)) {
614 int selectionStart = savedInstanceState.getInt(EXTRA_FOCUS_SELECTION_START);
615 int selectionEnd = savedInstanceState.getInt(EXTRA_FOCUS_SELECTION_END);
616 // There should be a focus and it should be an EditText since we
617 // only save these extras if these conditions are true.
618 EditText focusEditText = (EditText) getCurrentFocus();
619 final int length = focusEditText.getText().length();
620 if (selectionStart < length && selectionEnd < length) {
621 focusEditText.setSelection(selectionStart, selectionEnd);
622 }
623 }
624 }
625 }
626
627 @Override
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800628 public final void onSaveInstanceState(Bundle state) {
629 super.onSaveInstanceState(state);
Mindy Pereirab199d172012-08-13 11:04:03 -0700630 // We have no accounts so there is nothing to compose, and therefore, nothing to save.
631 if (mAccounts == null || mAccounts.length == 0) {
632 return;
633 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700634 // The framework is happy to save and restore the selection but only if it also saves and
635 // restores the contents of the edit text. That's a lot of text to put in a bundle so we do
636 // this manually.
637 View focus = getCurrentFocus();
638 if (focus != null && focus instanceof EditText) {
639 EditText focusEditText = (EditText) focus;
640 state.putInt(EXTRA_FOCUS_SELECTION_START, focusEditText.getSelectionStart());
641 state.putInt(EXTRA_FOCUS_SELECTION_END, focusEditText.getSelectionEnd());
642 }
Paul Westbrook6273e962012-04-23 10:44:15 -0700643
644 final List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
Paul Westbrook151f1ad2012-04-24 09:13:00 -0700645 final int selectedPos = mFromSpinner.getSelectedItemPosition();
Mindy Pereirad90f7ac2012-06-27 10:31:06 -0700646 final ReplyFromAccount selectedReplyFromAccount = (replyFromAccounts != null
647 && replyFromAccounts.size() > 0 && replyFromAccounts.size() > selectedPos) ?
648 replyFromAccounts.get(selectedPos) : null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700649 if (selectedReplyFromAccount != null) {
650 state.putString(EXTRA_SELECTED_REPLY_FROM_ACCOUNT, selectedReplyFromAccount.serialize()
651 .toString());
652 state.putParcelable(Utils.EXTRA_ACCOUNT, selectedReplyFromAccount.account);
653 } else {
654 state.putParcelable(Utils.EXTRA_ACCOUNT, mAccount);
655 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800656
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700657 if (mDraftId == UIProvider.INVALID_MESSAGE_ID && mRequestId !=0) {
658 // We don't have a draft id, and we have a request id,
659 // save the request id.
660 state.putInt(EXTRA_REQUEST_ID, mRequestId);
661 }
662
663 // We want to restore the current mode after a pause
664 // or rotation.
665 int mode = getMode();
666 state.putInt(EXTRA_ACTION, mode);
667
mindype7b76aa2012-11-14 16:19:13 -0800668 final Message message = createMessage(selectedReplyFromAccount, mode);
Andy Huang1f8f4dd2012-10-25 21:35:35 -0700669 if (mDraft != null) {
mindype7b76aa2012-11-14 16:19:13 -0800670 message.id = mDraft.id;
671 message.serverId = mDraft.serverId;
672 message.uri = mDraft.uri;
Andy Huang1f8f4dd2012-10-25 21:35:35 -0700673 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700674 state.putParcelable(EXTRA_MESSAGE, message);
675
676 if (mRefMessage != null) {
677 state.putParcelable(EXTRA_IN_REFERENCE_TO_MESSAGE, mRefMessage);
678 }
Mindy Pereira326689d2012-05-17 10:14:14 -0700679 state.putBoolean(EXTRA_SHOW_CC, mCcBccView.isCcVisible());
680 state.putBoolean(EXTRA_SHOW_BCC, mCcBccView.isBccVisible());
Mark Wei62066e42012-09-13 12:07:02 -0700681
682 state.putParcelableArrayList(
683 EXTRA_ATTACHMENT_PREVIEWS, mAttachmentsView.getAttachmentPreviews());
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700684 }
685
686 private int getMode() {
687 int mode = ComposeActivity.COMPOSE;
688 ActionBar actionBar = getActionBar();
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700689 if (actionBar != null
690 && actionBar.getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700691 mode = actionBar.getSelectedNavigationIndex();
692 }
693 return mode;
694 }
695
696 private Message createMessage(ReplyFromAccount selectedReplyFromAccount, int mode) {
697 Message message = new Message();
698 message.id = UIProvider.INVALID_MESSAGE_ID;
Andy Huangd47877e2012-08-09 19:31:24 -0700699 message.serverId = null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700700 message.uri = null;
701 message.conversationUri = null;
702 message.subject = mSubject.getText().toString();
703 message.snippet = null;
Scott Kennedy8960f0a2012-11-07 15:35:50 -0800704 message.setTo(formatSenders(mTo.getText().toString()));
705 message.setCc(formatSenders(mCc.getText().toString()));
706 message.setBcc(formatSenders(mBcc.getText().toString()));
707 message.setReplyTo(null);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700708 message.dateReceivedMs = 0;
mindyped9c2f02012-10-12 10:02:08 -0700709 String htmlBody = Html.toHtml(new SpannableString(mBodyView.getText().toString()));
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700710 StringBuilder fullBody = new StringBuilder(htmlBody);
711 message.bodyHtml = fullBody.toString();
712 message.bodyText = mBodyView.getText().toString();
713 message.embedsExternalResources = false;
714 message.refMessageId = mRefMessage != null ? mRefMessage.uri.toString() : null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700715 message.appendRefMessageContent = mQuotedTextView.getQuotedTextIfIncluded() != null;
716 ArrayList<Attachment> attachments = mAttachmentsView.getAttachments();
717 message.hasAttachments = attachments != null && attachments.size() > 0;
718 message.attachmentListUri = null;
719 message.messageFlags = 0;
720 message.saveUri = null;
721 message.sendUri = null;
722 message.alwaysShowImages = false;
723 message.attachmentsJson = Attachment.toJSONArray(attachments);
724 CharSequence quotedText = mQuotedTextView.getQuotedText();
725 message.quotedTextOffset = !TextUtils.isEmpty(quotedText) ? QuotedTextView
726 .getQuotedTextOffset(quotedText.toString()) : -1;
727 message.accountUri = null;
Scott Kennedy8960f0a2012-11-07 15:35:50 -0800728 message.setFrom(selectedReplyFromAccount != null ? selectedReplyFromAccount.address
729 : mAccount != null ? mAccount.name : null);
Andy Huang1f8f4dd2012-10-25 21:35:35 -0700730 message.draftType = getDraftType(mode);
Scott Kennedy8960f0a2012-11-07 15:35:50 -0800731 message.setTo(formatSenders(mTo.getText().toString()));
732 message.setCc(formatSenders(mCc.getText().toString()));
733 message.setBcc(formatSenders(mBcc.getText().toString()));
mindype7b76aa2012-11-14 16:19:13 -0800734 return message;
Andy Huang1f8f4dd2012-10-25 21:35:35 -0700735 }
736
Mindy Pereira3c911582012-08-09 16:59:09 -0700737 private String formatSenders(String string) {
738 if (!TextUtils.isEmpty(string) && string.charAt(string.length() - 1) == ',') {
739 return string.substring(0, string.length() - 1);
740 }
741 return string;
742 }
743
Mindy Pereira818143e2012-01-11 13:59:49 -0800744 @VisibleForTesting
745 void setAccount(Account account) {
Mindy Pereirabb5217e2012-04-17 11:08:29 -0700746 if (account == null) {
747 return;
748 }
Mindy Pereira23e9fde2012-03-20 15:08:24 -0700749 if (!account.equals(mAccount)) {
750 mAccount = account;
Paul Westbrookb1f573c2012-04-06 11:38:28 -0700751 mCachedSettings = mAccount.settings;
752 appendSignature();
Mindy Pereira23e9fde2012-03-20 15:08:24 -0700753 }
Mindy Pereirafa20c1a2012-07-23 13:00:02 -0700754 if (mAccount != null) {
755 MailActivity.setForegroundNdef(MailActivity.getMailtoNdef(mAccount.name));
756 }
Mindy Pereira818143e2012-01-11 13:59:49 -0800757 }
758
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700759 private void initFromSpinner(Bundle bundle, int action) {
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700760 String accountString = null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700761 if (action == EDIT_DRAFT && mDraft.draftType == UIProvider.DraftType.COMPOSE) {
Mindy Pereira62de1b12012-04-06 12:17:56 -0700762 action = COMPOSE;
763 }
Mindy Pereirab199d172012-08-13 11:04:03 -0700764 mFromSpinner.asyncInitFromSpinner(action, mAccount, mAccounts);
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700765 if (bundle != null) {
766 if (bundle.containsKey(EXTRA_SELECTED_REPLY_FROM_ACCOUNT)) {
767 mReplyFromAccount = ReplyFromAccount.deserialize(mAccount,
768 bundle.getString(EXTRA_SELECTED_REPLY_FROM_ACCOUNT));
769 } else if (bundle.containsKey(EXTRA_FROM_ACCOUNT_STRING)) {
770 accountString = bundle.getString(EXTRA_FROM_ACCOUNT_STRING);
771 mReplyFromAccount = mFromSpinner.getMatchingReplyFromAccount(accountString);
772 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700773 }
774 if (mReplyFromAccount == null) {
775 if (mDraft != null) {
776 mReplyFromAccount = getReplyFromAccountFromDraft(mAccount, mDraft);
777 } else if (mRefMessage != null) {
778 mReplyFromAccount = getReplyFromAccountForReply(mAccount, mRefMessage);
779 }
Mindy Pereira62de1b12012-04-06 12:17:56 -0700780 }
781 if (mReplyFromAccount == null) {
Andy Huang238aa472012-10-30 17:45:17 -0700782 mReplyFromAccount = getDefaultReplyFromAccount(mAccount);
Mindy Pereira62de1b12012-04-06 12:17:56 -0700783 }
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700784
Mindy Pereira62de1b12012-04-06 12:17:56 -0700785 mFromSpinner.setCurrentAccount(mReplyFromAccount);
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700786
Mindy Pereira62de1b12012-04-06 12:17:56 -0700787 if (mFromSpinner.getCount() > 1) {
Mindy Pereiraa83e7082012-03-30 08:53:11 -0700788 // If there is only 1 account, just show that account.
789 // Otherwise, give the user the ability to choose which account to
Mindy Pereira62de1b12012-04-06 12:17:56 -0700790 // send mail from / save drafts to.
791 mFromStatic.setVisibility(View.GONE);
Mindy Pereiraa83e7082012-03-30 08:53:11 -0700792 mFromStaticText.setText(mAccount.name);
Mindy Pereira62de1b12012-04-06 12:17:56 -0700793 mFromSpinnerWrapper.setVisibility(View.VISIBLE);
Mindy Pereiraa83e7082012-03-30 08:53:11 -0700794 } else {
795 mFromStatic.setVisibility(View.VISIBLE);
796 mFromStaticText.setText(mAccount.name);
797 mFromSpinnerWrapper.setVisibility(View.GONE);
Mindy Pereiraa83e7082012-03-30 08:53:11 -0700798 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800799 }
800
Mindy Pereira62de1b12012-04-06 12:17:56 -0700801 private ReplyFromAccount getReplyFromAccountForReply(Account account, Message refMessage) {
802 if (refMessage.accountUri != null) {
803 // This must be from combined inbox.
804 List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
805 for (ReplyFromAccount from : replyFromAccounts) {
806 if (from.account.uri.equals(refMessage.accountUri)) {
807 return from;
808 }
809 }
810 return null;
811 } else {
812 return getReplyFromAccount(account, refMessage);
813 }
814 }
815
816 /**
817 * Given an account and which email address the message was sent to,
818 * return who the message should be sent from.
819 * @param account Account in which the message arrived.
820 * @param sentTo Email address to which the message was sent.
821 * @return the address from which to reply.
822 */
823 public ReplyFromAccount getReplyFromAccount(Account account, Message refMessage) {
824 // First see if we are supposed to use the default address or
825 // the address it was sentTo.
Mindy Pereira326689d2012-05-17 10:14:14 -0700826 if (mCachedSettings.forceReplyFromDefault) {
Mindy Pereira62de1b12012-04-06 12:17:56 -0700827 return getDefaultReplyFromAccount(account);
828 } else {
Mindy Pereira89bae572012-06-18 11:34:36 -0700829 // If we aren't explicitly told which account to look for, look at
Mindy Pereira62de1b12012-04-06 12:17:56 -0700830 // all the message recipients and find one that matches
831 // a custom from or account.
832 List<String> allRecipients = new ArrayList<String>();
mindyp5ed63112012-09-17 17:31:45 -0700833 allRecipients.addAll(Arrays.asList(refMessage.getToAddresses()));
834 allRecipients.addAll(Arrays.asList(refMessage.getCcAddresses()));
Mindy Pereira62de1b12012-04-06 12:17:56 -0700835 return getMatchingRecipient(account, allRecipients);
836 }
837 }
838
839 /**
840 * Compare all the recipients of an email to the current account and all
841 * custom addresses associated with that account. Return the match if there
842 * is one, or the default account if there isn't.
843 */
844 protected ReplyFromAccount getMatchingRecipient(Account account, List<String> sentTo) {
845 // Tokenize the list and place in a hashmap.
846 ReplyFromAccount matchingReplyFrom = null;
847 Rfc822Token[] tokens;
848 HashSet<String> recipientsMap = new HashSet<String>();
849 for (String address : sentTo) {
850 tokens = Rfc822Tokenizer.tokenize(address);
851 for (int i = 0; i < tokens.length; i++) {
852 recipientsMap.add(tokens[i].getAddress());
853 }
854 }
855
856 int matchingAddressCount = 0;
857 List<ReplyFromAccount> customFroms;
Andy Huang16174812012-08-16 16:40:35 -0700858 customFroms = account.getReplyFroms();
859 if (customFroms != null) {
860 for (ReplyFromAccount entry : customFroms) {
861 if (recipientsMap.contains(entry.address)) {
862 matchingReplyFrom = entry;
863 matchingAddressCount++;
Mindy Pereira62de1b12012-04-06 12:17:56 -0700864 }
865 }
Mindy Pereira62de1b12012-04-06 12:17:56 -0700866 }
867 if (matchingAddressCount > 1) {
868 matchingReplyFrom = getDefaultReplyFromAccount(account);
869 }
870 return matchingReplyFrom;
871 }
872
873 private ReplyFromAccount getDefaultReplyFromAccount(Account account) {
Andy Huang238aa472012-10-30 17:45:17 -0700874 for (ReplyFromAccount from : account.getReplyFroms()) {
Mindy Pereira62de1b12012-04-06 12:17:56 -0700875 if (from.isDefault) {
876 return from;
877 }
878 }
Mindy Pereiracd970dd2012-05-31 10:07:47 -0700879 return new ReplyFromAccount(account, account.uri, account.name, account.name, account.name,
880 true, false);
Mindy Pereira62de1b12012-04-06 12:17:56 -0700881 }
882
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700883 private ReplyFromAccount getReplyFromAccountFromDraft(Account account, Message msg) {
Scott Kennedy8960f0a2012-11-07 15:35:50 -0800884 String sender = msg.getFrom();
Mindy Pereira62de1b12012-04-06 12:17:56 -0700885 ReplyFromAccount replyFromAccount = null;
886 List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
887 if (TextUtils.equals(account.name, sender)) {
888 replyFromAccount = new ReplyFromAccount(mAccount, mAccount.uri, mAccount.name,
Mindy Pereiracd970dd2012-05-31 10:07:47 -0700889 mAccount.name, mAccount.name, true, false);
Mindy Pereira62de1b12012-04-06 12:17:56 -0700890 } else {
891 for (ReplyFromAccount fromAccount : replyFromAccounts) {
892 if (TextUtils.equals(fromAccount.name, sender)) {
893 replyFromAccount = fromAccount;
894 break;
895 }
896 }
897 }
898 return replyFromAccount;
899 }
900
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800901 private void findViews() {
Mindy Pereirab199d172012-08-13 11:04:03 -0700902 findViewById(R.id.compose).setVisibility(View.VISIBLE);
Mindy Pereiraa26b54e2012-01-06 12:54:33 -0800903 mCcBccButton = (Button) findViewById(R.id.add_cc_bcc);
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800904 if (mCcBccButton != null) {
905 mCcBccButton.setOnClickListener(this);
906 }
907 mCcBccView = (CcBccView) findViewById(R.id.cc_bcc_wrapper);
Mindy Pereira7b56a612011-12-14 12:32:28 -0800908 mAttachmentsView = (AttachmentsView)findViewById(R.id.attachments);
mindyp93b079b2012-08-29 16:32:15 -0700909 mPhotoAttachmentsButton = findViewById(R.id.add_photo_attachment);
mindypcd0b0b92012-08-23 14:33:17 -0700910 if (mPhotoAttachmentsButton != null) {
911 mPhotoAttachmentsButton.setOnClickListener(this);
912 }
mindyp93b079b2012-08-29 16:32:15 -0700913 mVideoAttachmentsButton = findViewById(R.id.add_video_attachment);
mindypcd0b0b92012-08-23 14:33:17 -0700914 if (mVideoAttachmentsButton != null) {
915 mVideoAttachmentsButton.setOnClickListener(this);
916 }
Mindy Pereira818143e2012-01-11 13:59:49 -0800917 mTo = (RecipientEditTextView) findViewById(R.id.to);
918 mCc = (RecipientEditTextView) findViewById(R.id.cc);
919 mBcc = (RecipientEditTextView) findViewById(R.id.bcc);
Mindy Pereira82cc5662012-01-09 17:29:30 -0800920 // TODO: add special chips text change watchers before adding
921 // this as a text changed watcher to the to, cc, bcc fields.
Mindy Pereira6349a042012-01-04 11:25:01 -0800922 mSubject = (TextView) findViewById(R.id.subject);
mindyp62d3ec72012-08-24 13:04:09 -0700923 mSubject.setOnEditorActionListener(this);
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800924 mQuotedTextView = (QuotedTextView) findViewById(R.id.quoted_text_view);
925 mQuotedTextView.setRespondInlineListener(this);
Mindy Pereira433b1982012-04-03 11:53:07 -0700926 mBodyView = (EditText) findViewById(R.id.body);
Mindy Pereira1a95a572012-01-05 12:21:29 -0800927 mFromStatic = findViewById(R.id.static_from_content);
Mindy Pereira2eb17322012-03-07 10:07:34 -0800928 mFromStaticText = (TextView) findViewById(R.id.from_account_name);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800929 mFromSpinnerWrapper = findViewById(R.id.spinner_from_content);
Mindy Pereira5a85e2b2012-01-11 09:53:32 -0800930 mFromSpinner = (FromAddressSpinner) findViewById(R.id.from_picker);
Mindy Pereira6349a042012-01-04 11:25:01 -0800931 }
932
mindyp62d3ec72012-08-24 13:04:09 -0700933 @Override
934 public boolean onEditorAction(TextView view, int action, KeyEvent keyEvent) {
935 if (action == EditorInfo.IME_ACTION_DONE) {
936 focusBody();
937 return true;
938 }
939 return false;
940 }
941
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700942 protected TextView getBody() {
943 return mBodyView;
944 }
945
946 @VisibleForTesting
947 public Account getFromAccount() {
948 return mReplyFromAccount != null && mReplyFromAccount.account != null ?
949 mReplyFromAccount.account : mAccount;
950 }
951
Mindy Pereiracbfb75a2012-06-25 14:52:23 -0700952 private void clearChangeListeners() {
953 mSubject.removeTextChangedListener(this);
954 mBodyView.removeTextChangedListener(this);
955 mTo.removeTextChangedListener(mToListener);
956 mCc.removeTextChangedListener(mCcListener);
957 mBcc.removeTextChangedListener(mBccListener);
958 mFromSpinner.setOnAccountChangedListener(null);
959 mAttachmentsView.setAttachmentChangesListener(null);
960 }
961
Mindy Pereira75f66632012-01-11 11:42:02 -0800962 // Now that the message has been initialized from any existing draft or
963 // ref message data, set up listeners for any changes that occur to the
964 // message.
965 private void initChangeListeners() {
966 mSubject.addTextChangedListener(this);
967 mBodyView.addTextChangedListener(this);
Mindy Pereiracbfb75a2012-06-25 14:52:23 -0700968 if (mToListener == null) {
969 mToListener = new RecipientTextWatcher(mTo, this);
970 }
971 mTo.addTextChangedListener(mToListener);
972 if (mCcListener == null) {
973 mCcListener = new RecipientTextWatcher(mCc, this);
974 }
975 mCc.addTextChangedListener(mCcListener);
976 if (mBccListener == null) {
977 mBccListener = new RecipientTextWatcher(mBcc, this);
978 }
979 mBcc.addTextChangedListener(mBccListener);
Mindy Pereira75f66632012-01-11 11:42:02 -0800980 mFromSpinner.setOnAccountChangedListener(this);
Mindy Pereira818143e2012-01-11 13:59:49 -0800981 mAttachmentsView.setAttachmentChangesListener(this);
Mindy Pereira75f66632012-01-11 11:42:02 -0800982 }
983
Mindy Pereira326c6602012-01-04 15:32:42 -0800984 private void initActionBar(int action) {
985 mComposeMode = action;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800986 ActionBar actionBar = getActionBar();
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700987 if (actionBar == null) {
988 return;
989 }
Mindy Pereira326c6602012-01-04 15:32:42 -0800990 if (action == ComposeActivity.COMPOSE) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800991 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
992 actionBar.setTitle(R.string.compose);
Mindy Pereira326c6602012-01-04 15:32:42 -0800993 } else {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800994 actionBar.setTitle(null);
Mindy Pereira326c6602012-01-04 15:32:42 -0800995 if (mComposeModeAdapter == null) {
996 mComposeModeAdapter = new ComposeModeAdapter(this);
997 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800998 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
999 actionBar.setListNavigationCallbacks(mComposeModeAdapter, this);
Mindy Pereira326c6602012-01-04 15:32:42 -08001000 switch (action) {
1001 case ComposeActivity.REPLY:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001002 actionBar.setSelectedNavigationItem(0);
Mindy Pereira326c6602012-01-04 15:32:42 -08001003 break;
1004 case ComposeActivity.REPLY_ALL:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001005 actionBar.setSelectedNavigationItem(1);
Mindy Pereira326c6602012-01-04 15:32:42 -08001006 break;
1007 case ComposeActivity.FORWARD:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001008 actionBar.setSelectedNavigationItem(2);
Mindy Pereira326c6602012-01-04 15:32:42 -08001009 break;
1010 }
1011 }
Mindy Pereirafbe40192012-03-20 10:40:45 -07001012 actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME,
1013 ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME);
1014 actionBar.setHomeButtonEnabled(true);
Mindy Pereira326c6602012-01-04 15:32:42 -08001015 }
1016
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001017 private void initFromRefMessage(int action, String recipientAddress) {
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07001018 setFieldsFromRefMessage(action, recipientAddress);
1019 if (mRefMessage != null) {
1020 // CC field only gets populated when doing REPLY_ALL.
1021 // BCC never gets auto-populated, unless the user is editing
1022 // a draft with one.
Mindy Pereira29a717e2012-07-25 18:05:48 -07001023 if (!TextUtils.isEmpty(mCc.getText()) && action == REPLY_ALL) {
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07001024 mCcBccView.show(false, true, false);
1025 }
1026 }
1027 updateHideOrShowCcBcc();
1028 }
1029
1030 private void setFieldsFromRefMessage(int action, String recipientAddress) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001031 setSubject(mRefMessage, action);
1032 // Setup recipients
1033 if (action == FORWARD) {
1034 mForward = true;
Mindy Pereira6349a042012-01-04 11:25:01 -08001035 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001036 initRecipientsFromRefMessage(recipientAddress, mRefMessage, action);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001037 initQuotedTextFromRefMessage(mRefMessage, action);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001038 if (action == ComposeActivity.FORWARD || mAttachmentsChanged) {
1039 initAttachments(mRefMessage);
1040 }
Mindy Pereirac17d0732011-12-29 10:46:19 -08001041 }
1042
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001043 private void initFromDraftMessage(Message message) {
Andy Huang1f8f4dd2012-10-25 21:35:35 -07001044 LogUtils.d(LOG_TAG, "Intializing draft from previous draft message: %s", message);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001045
1046 mDraft = message;
1047 mDraftId = message.id;
1048 mSubject.setText(message.subject);
1049 mForward = message.draftType == UIProvider.DraftType.FORWARD;
1050 final List<String> toAddresses = Arrays.asList(message.getToAddresses());
1051 addToAddresses(toAddresses);
1052 addCcAddresses(Arrays.asList(message.getCcAddresses()), toAddresses);
1053 addBccAddresses(Arrays.asList(message.getBccAddresses()));
Mindy Pereira2421dc82012-03-27 13:32:31 -07001054 if (message.hasAttachments) {
1055 List<Attachment> attachments = message.getAttachments();
1056 for (Attachment a : attachments) {
Andy Huang5c5fd572012-04-08 18:19:29 -07001057 addAttachmentAndUpdateView(a);
Mindy Pereira2421dc82012-03-27 13:32:31 -07001058 }
1059 }
Mindy Pereiracc8e7db2012-05-30 12:57:42 -07001060 int quotedTextIndex = message.appendRefMessageContent ?
Mindy Pereira002ff522012-05-30 10:31:26 -07001061 message.quotedTextOffset : -1;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001062 // Set the body
Mindy Pereira002ff522012-05-30 10:31:26 -07001063 CharSequence quotedText = null;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001064 if (!TextUtils.isEmpty(message.bodyHtml)) {
Mindy Pereira752222d2012-07-19 09:58:53 -07001065 CharSequence htmlText = "";
Mindy Pereira002ff522012-05-30 10:31:26 -07001066 if (quotedTextIndex > -1) {
Mindy Pereira752222d2012-07-19 09:58:53 -07001067 // Find the offset in the htmltext of the actual quoted text and strip it out.
1068 quotedTextIndex = QuotedTextView.findQuotedTextIndex(message.bodyHtml);
1069 if (quotedTextIndex > -1) {
mindypc59dd822012-11-13 10:56:21 -08001070 htmlText = Utils.convertHtmlToPlainText(message.bodyHtml.substring(0,
1071 quotedTextIndex));
Mindy Pereira752222d2012-07-19 09:58:53 -07001072 quotedText = message.bodyHtml.subSequence(quotedTextIndex,
1073 message.bodyHtml.length());
1074 }
Mindy Pereira1a6e9382012-08-14 15:51:22 -07001075 } else {
mindypc59dd822012-11-13 10:56:21 -08001076 htmlText = Utils.convertHtmlToPlainText(message.bodyHtml);
Mindy Pereira002ff522012-05-30 10:31:26 -07001077 }
1078 mBodyView.setText(htmlText);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001079 } else {
Mindy Pereira752222d2012-07-19 09:58:53 -07001080 final String body = message.bodyText;
1081 final CharSequence bodyText = !TextUtils.isEmpty(body) ?
1082 (quotedTextIndex > -1 ?
1083 message.bodyText.substring(0, quotedTextIndex) : message.bodyText)
1084 : "";
Mindy Pereira002ff522012-05-30 10:31:26 -07001085 if (quotedTextIndex > -1) {
Mindy Pereira752222d2012-07-19 09:58:53 -07001086 quotedText = !TextUtils.isEmpty(body) ? message.bodyText.substring(quotedTextIndex)
1087 : null;
Mindy Pereira002ff522012-05-30 10:31:26 -07001088 }
1089 mBodyView.setText(bodyText);
1090 }
1091 if (quotedTextIndex > -1 && quotedText != null) {
Mindy Pereira39713232012-05-30 11:48:41 -07001092 mQuotedTextView.setQuotedTextFromDraft(quotedText, mForward);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001093 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001094 }
1095
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001096 /**
1097 * Fill all the widgets with the content found in the Intent Extra, if any.
1098 * Also apply the same style to all widgets. Note: if initFromExtras is
1099 * called as a result of switching between reply, reply all, and forward per
1100 * the latest revision of Gmail, and the user has already made changes to
1101 * attachments on a previous incarnation of the message (as a reply, reply
1102 * all, or forward), the original attachments from the message will not be
1103 * re-instantiated. The user's changes will be respected. This follows the
1104 * web gmail interaction.
1105 */
1106 public void initFromExtras(Intent intent) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001107 // If we were invoked with a SENDTO intent, the value
1108 // should take precedence
1109 final Uri dataUri = intent.getData();
1110 if (dataUri != null) {
1111 if (MAIL_TO.equals(dataUri.getScheme())) {
1112 initFromMailTo(dataUri.toString());
1113 } else {
Mindy Pereira0b4f28e2012-03-28 14:12:21 -07001114 if (!mAccount.composeIntentUri.equals(dataUri)) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001115 String toText = dataUri.getSchemeSpecificPart();
1116 if (toText != null) {
1117 mTo.setText("");
Mindy Pereiradbe89962012-04-13 09:42:38 -07001118 addToAddresses(Arrays.asList(TextUtils.split(toText, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001119 }
1120 }
1121 }
1122 }
1123
1124 String[] extraStrings = intent.getStringArrayExtra(Intent.EXTRA_EMAIL);
1125 if (extraStrings != null) {
1126 addToAddresses(Arrays.asList(extraStrings));
1127 }
1128 extraStrings = intent.getStringArrayExtra(Intent.EXTRA_CC);
1129 if (extraStrings != null) {
1130 addCcAddresses(Arrays.asList(extraStrings), null);
1131 }
1132 extraStrings = intent.getStringArrayExtra(Intent.EXTRA_BCC);
1133 if (extraStrings != null) {
1134 addBccAddresses(Arrays.asList(extraStrings));
1135 }
1136
1137 String extraString = intent.getStringExtra(Intent.EXTRA_SUBJECT);
1138 if (extraString != null) {
1139 mSubject.setText(extraString);
1140 }
1141
1142 for (String extra : ALL_EXTRAS) {
1143 if (intent.hasExtra(extra)) {
1144 String value = intent.getStringExtra(extra);
1145 if (EXTRA_TO.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001146 addToAddresses(Arrays.asList(TextUtils.split(value, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001147 } else if (EXTRA_CC.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001148 addCcAddresses(Arrays.asList(TextUtils.split(value, ",")), null);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001149 } else if (EXTRA_BCC.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001150 addBccAddresses(Arrays.asList(TextUtils.split(value, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001151 } else if (EXTRA_SUBJECT.equals(extra)) {
1152 mSubject.setText(value);
1153 } else if (EXTRA_BODY.equals(extra)) {
1154 setBody(value, true /* with signature */);
1155 }
1156 }
1157 }
1158
1159 Bundle extras = intent.getExtras();
1160 if (extras != null) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001161 CharSequence text = extras.getCharSequence(Intent.EXTRA_TEXT);
1162 if (text != null) {
1163 setBody(text, true /* with signature */);
1164 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001165 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001166 }
1167
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001168 @VisibleForTesting
1169 protected String decodeEmailInUri(String s) throws UnsupportedEncodingException {
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001170 // TODO: handle the case where there are spaces in the display name as
1171 // well as the email such as "Guy with spaces <guy+with+spaces@gmail.com>"
1172 // as they could be encoded ambiguously.
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001173 // Since URLDecode.decode changes + into ' ', and + is a valid
1174 // email character, we need to find/ replace these ourselves before
1175 // decoding.
1176 String replacePlus = s.replace("+", "%2B");
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001177 try {
1178 return URLDecoder.decode(replacePlus, UTF8_ENCODING_NAME);
1179 } catch (IllegalArgumentException e) {
1180 if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
1181 LogUtils.e(LOG_TAG, "%s while decoding '%s'", e.getMessage(), s);
1182 } else {
1183 LogUtils.e(LOG_TAG, e, "Exception while decoding mailto address");
1184 }
1185 return null;
1186 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001187 }
1188
1189 /**
1190 * Initialize the compose view from a String representing a mailTo uri.
1191 * @param mailToString The uri as a string.
1192 */
1193 public void initFromMailTo(String mailToString) {
1194 // We need to disguise this string as a URI in order to parse it
1195 // TODO: Remove this hack when http://b/issue?id=1445295 gets fixed
1196 Uri uri = Uri.parse("foo://" + mailToString);
1197 int index = mailToString.indexOf("?");
1198 int length = "mailto".length() + 1;
1199 String to;
1200 try {
1201 // Extract the recipient after mailto:
1202 if (index == -1) {
1203 to = decodeEmailInUri(mailToString.substring(length));
1204 } else {
1205 to = decodeEmailInUri(mailToString.substring(length, index));
1206 }
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001207 if (!TextUtils.isEmpty(to)) {
1208 addToAddresses(Arrays.asList(TextUtils.split(to, ",")));
1209 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001210 } catch (UnsupportedEncodingException e) {
1211 if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
1212 LogUtils.e(LOG_TAG, "%s while decoding '%s'", e.getMessage(), mailToString);
1213 } else {
1214 LogUtils.e(LOG_TAG, e, "Exception while decoding mailto address");
1215 }
1216 }
1217
1218 List<String> cc = uri.getQueryParameters("cc");
1219 addCcAddresses(Arrays.asList(cc.toArray(new String[cc.size()])), null);
1220
1221 List<String> otherTo = uri.getQueryParameters("to");
1222 addToAddresses(Arrays.asList(otherTo.toArray(new String[otherTo.size()])));
1223
1224 List<String> bcc = uri.getQueryParameters("bcc");
1225 addBccAddresses(Arrays.asList(bcc.toArray(new String[bcc.size()])));
1226
1227 List<String> subject = uri.getQueryParameters("subject");
1228 if (subject.size() > 0) {
1229 try {
1230 mSubject.setText(URLDecoder.decode(subject.get(0), UTF8_ENCODING_NAME));
1231 } catch (UnsupportedEncodingException e) {
1232 LogUtils.e(LOG_TAG, "%s while decoding subject '%s'",
1233 e.getMessage(), subject);
1234 }
1235 }
1236
1237 List<String> body = uri.getQueryParameters("body");
1238 if (body.size() > 0) {
1239 try {
1240 setBody(URLDecoder.decode(body.get(0), UTF8_ENCODING_NAME),
1241 true /* with signature */);
1242 } catch (UnsupportedEncodingException e) {
1243 LogUtils.e(LOG_TAG, "%s while decoding body '%s'", e.getMessage(), body);
1244 }
1245 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001246 }
1247
Mindy Pereirabddd6f32012-06-20 12:10:03 -07001248 @VisibleForTesting
1249 protected void initAttachments(Message refMessage) {
Mark Wei434f2942012-08-24 11:54:02 -07001250 addAttachments(refMessage.getAttachments());
1251 }
1252
1253 public long addAttachments(List<Attachment> attachments) {
1254 long size = 0;
1255 AttachmentFailureException error = null;
1256 for (Attachment a : attachments) {
1257 try {
1258 size += mAttachmentsView.addAttachment(mAccount, a);
1259 } catch (AttachmentFailureException e) {
1260 error = e;
1261 }
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001262 }
Mark Wei434f2942012-08-24 11:54:02 -07001263 if (error != null) {
1264 LogUtils.e(LOG_TAG, error, "Error adding attachment");
1265 if (attachments.size() > 1) {
1266 showAttachmentTooBigToast(R.string.too_large_to_attach_multiple);
1267 } else {
1268 showAttachmentTooBigToast(error.getErrorRes());
1269 }
1270 }
1271 return size;
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001272 }
1273
1274 /**
1275 * When an attachment is too large to be added to a message, show a toast.
1276 * This method also updates the position of the toast so that it is shown
1277 * clearly above they keyboard if it happens to be open.
1278 */
Mark Wei434f2942012-08-24 11:54:02 -07001279 private void showAttachmentTooBigToast(int errorRes) {
1280 String maxSize = AttachmentUtils.convertToHumanReadableSize(
1281 getApplicationContext(), mAccount.settings.getMaxAttachmentSize());
1282 showErrorToast(getString(errorRes, maxSize));
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001283 }
1284
Mark Wei434f2942012-08-24 11:54:02 -07001285 private void showErrorToast(String message) {
1286 Toast t = Toast.makeText(this, message, Toast.LENGTH_LONG);
1287 t.setText(message);
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001288 t.setGravity(Gravity.CENTER_HORIZONTAL, 0,
1289 getResources().getDimensionPixelSize(R.dimen.attachment_toast_yoffset));
1290 t.show();
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001291 }
1292
Paul Westbrookf97588b2012-03-20 11:11:37 -07001293 private void initAttachmentsFromIntent(Intent intent) {
Paul Westbrook03ee9712012-04-02 09:51:51 -07001294 Bundle extras = intent.getExtras();
1295 if (extras == null) {
1296 extras = Bundle.EMPTY;
1297 }
Paul Westbrookf97588b2012-03-20 11:11:37 -07001298 final String action = intent.getAction();
1299 if (!mAttachmentsChanged) {
1300 long totalSize = 0;
1301 if (extras.containsKey(EXTRA_ATTACHMENTS)) {
1302 String[] uris = (String[]) extras.getSerializable(EXTRA_ATTACHMENTS);
1303 for (String uriString : uris) {
1304 final Uri uri = Uri.parse(uriString);
1305 long size = 0;
1306 try {
Andy Huang5c5fd572012-04-08 18:19:29 -07001307 size = mAttachmentsView.addAttachment(mAccount, uri);
Paul Westbrookf97588b2012-03-20 11:11:37 -07001308 } catch (AttachmentFailureException e) {
Paul Westbrookf97588b2012-03-20 11:11:37 -07001309 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Mark Wei434f2942012-08-24 11:54:02 -07001310 showAttachmentTooBigToast(e.getErrorRes());
Paul Westbrookf97588b2012-03-20 11:11:37 -07001311 }
1312 totalSize += size;
1313 }
1314 }
mindyp9a9e8d62012-10-03 12:24:07 -07001315 if (extras.containsKey(Intent.EXTRA_STREAM)) {
1316 if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
1317 ArrayList<Parcelable> uris = extras
1318 .getParcelableArrayList(Intent.EXTRA_STREAM);
1319 ArrayList<Attachment> attachments = new ArrayList<Attachment>();
1320 for (Parcelable uri : uris) {
1321 try {
1322 attachments.add(mAttachmentsView.generateLocalAttachment((Uri) uri));
1323 } catch (AttachmentFailureException e) {
1324 LogUtils.e(LOG_TAG, e, "Error adding attachment");
1325 String maxSize = AttachmentUtils.convertToHumanReadableSize(
1326 getApplicationContext(),
1327 mAccount.settings.getMaxAttachmentSize());
1328 showErrorToast(getString
1329 (R.string.generic_attachment_problem, maxSize));
1330 }
1331 }
1332 totalSize += addAttachments(attachments);
1333 } else {
1334 final Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
1335 long size = 0;
Paul Westbrookf97588b2012-03-20 11:11:37 -07001336 try {
mindyp9a9e8d62012-10-03 12:24:07 -07001337 size = mAttachmentsView.addAttachment(mAccount, uri);
Paul Westbrookf97588b2012-03-20 11:11:37 -07001338 } catch (AttachmentFailureException e) {
Paul Westbrookf97588b2012-03-20 11:11:37 -07001339 LogUtils.e(LOG_TAG, e, "Error adding attachment");
mindyp9a9e8d62012-10-03 12:24:07 -07001340 showAttachmentTooBigToast(e.getErrorRes());
Paul Westbrookf97588b2012-03-20 11:11:37 -07001341 }
mindyp9a9e8d62012-10-03 12:24:07 -07001342 totalSize += size;
Paul Westbrookf97588b2012-03-20 11:11:37 -07001343 }
1344 }
1345
1346 if (totalSize > 0) {
1347 mAttachmentsChanged = true;
1348 updateSaveUi();
1349 }
1350 }
1351 }
1352
1353
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001354 private void initQuotedTextFromRefMessage(Message refMessage, int action) {
1355 if (mRefMessage != null && (action == REPLY || action == REPLY_ALL || action == FORWARD)) {
Mindy Pereira9932dee2012-01-10 16:09:50 -08001356 mQuotedTextView.setQuotedText(action, refMessage, action != FORWARD);
1357 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001358 }
1359
1360 private void updateHideOrShowCcBcc() {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001361 // Its possible there is a menu item OR a button.
Mindy Pereira326689d2012-05-17 10:14:14 -07001362 boolean ccVisible = mCcBccView.isCcVisible();
1363 boolean bccVisible = mCcBccView.isBccVisible();
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001364 if (mCcBccButton != null) {
Mindy Pereira326689d2012-05-17 10:14:14 -07001365 if (!ccVisible || !bccVisible) {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001366 mCcBccButton.setVisibility(View.VISIBLE);
Mindy Pereira326689d2012-05-17 10:14:14 -07001367 mCcBccButton.setText(getString(!ccVisible ? R.string.add_cc_label
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001368 : R.string.add_bcc_label));
1369 } else {
mindypcd0b0b92012-08-23 14:33:17 -07001370 mCcBccButton.setVisibility(View.INVISIBLE);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001371 }
1372 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001373 }
1374
Mindy Pereiraa34c9a02012-04-17 14:10:53 -07001375 private void showCcBcc(Bundle state) {
Mindy Pereira326689d2012-05-17 10:14:14 -07001376 if (state != null && state.containsKey(EXTRA_SHOW_CC)) {
1377 boolean showCc = state.getBoolean(EXTRA_SHOW_CC);
1378 boolean showBcc = state.getBoolean(EXTRA_SHOW_BCC);
1379 if (showCc || showBcc) {
1380 mCcBccView.show(false, showCc, showBcc);
Mindy Pereira6faeedf2012-04-18 16:11:39 -07001381 }
Mindy Pereiraa34c9a02012-04-17 14:10:53 -07001382 }
1383 }
1384
Mindy Pereira013194c2012-01-06 15:09:33 -08001385 /**
1386 * Add attachment and update the compose area appropriately.
1387 * @param data
1388 */
1389 public void addAttachmentAndUpdateView(Intent data) {
Mindy Pereira2421dc82012-03-27 13:32:31 -07001390 addAttachmentAndUpdateView(data != null ? data.getData() : (Uri) null);
1391 }
1392
Andy Huang5c5fd572012-04-08 18:19:29 -07001393 public void addAttachmentAndUpdateView(Uri contentUri) {
1394 if (contentUri == null) {
Mindy Pereira2421dc82012-03-27 13:32:31 -07001395 return;
1396 }
Mindy Pereira013194c2012-01-06 15:09:33 -08001397 try {
Andy Huang5c5fd572012-04-08 18:19:29 -07001398 addAttachmentAndUpdateView(mAttachmentsView.generateLocalAttachment(contentUri));
1399 } catch (AttachmentFailureException e) {
Andy Huang5c5fd572012-04-08 18:19:29 -07001400 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Mark Wei434f2942012-08-24 11:54:02 -07001401 showErrorToast(getResources().getString(
1402 e.getErrorRes(),
1403 AttachmentUtils.convertToHumanReadableSize(
1404 getApplicationContext(), mAccount.settings.getMaxAttachmentSize())));
Andy Huang5c5fd572012-04-08 18:19:29 -07001405 }
1406 }
1407
1408 public void addAttachmentAndUpdateView(Attachment attachment) {
1409 try {
Mark Wei434f2942012-08-24 11:54:02 -07001410 long size = mAttachmentsView.addAttachment(mAccount, attachment);
Mindy Pereira9932dee2012-01-10 16:09:50 -08001411 if (size > 0) {
1412 mAttachmentsChanged = true;
1413 updateSaveUi();
Mindy Pereira013194c2012-01-06 15:09:33 -08001414 }
Mindy Pereira9932dee2012-01-10 16:09:50 -08001415 } catch (AttachmentFailureException e) {
Mindy Pereira9932dee2012-01-10 16:09:50 -08001416 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Mark Wei434f2942012-08-24 11:54:02 -07001417 showAttachmentTooBigToast(e.getErrorRes());
Mindy Pereira013194c2012-01-06 15:09:33 -08001418 }
1419 }
1420
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001421 void initRecipientsFromRefMessage(String recipientAddress, Message refMessage,
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001422 int action) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001423 // Don't populate the address if this is a forward.
1424 if (action == ComposeActivity.FORWARD) {
1425 return;
1426 }
Mindy Pereira33fe9082012-01-09 16:24:30 -08001427 initReplyRecipients(mAccount.name, refMessage, action);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001428 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001429
Mindy Pereira818143e2012-01-11 13:59:49 -08001430 @VisibleForTesting
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001431 void initReplyRecipients(String account, Message refMessage, int action) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001432 // This is the email address of the current user, i.e. the one composing
1433 // the reply.
Mindy Pereira4a20b702012-01-05 16:24:24 -08001434 final String accountEmail = Address.getEmailAddress(account).getAddress();
mindyp5ed63112012-09-17 17:31:45 -07001435 String[] sentToAddresses = refMessage.getToAddresses();
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001436 String replytoAddress = refMessage.getReplyTo();
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001437 final Collection<String> toAddresses;
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001438
1439 // If this is a reply, the Cc list is empty. If this is a reply-all, the
1440 // Cc list is the union of the To and Cc recipients of the original
1441 // message, excluding the current user's email address and any addresses
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001442 // already on the To list.
1443 if (action == ComposeActivity.REPLY) {
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001444 toAddresses = initToRecipients(account, accountEmail, refMessage.getFrom(),
1445 replytoAddress, sentToAddresses);
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001446 addToAddresses(toAddresses);
1447 } else if (action == ComposeActivity.REPLY_ALL) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001448 final Set<String> ccAddresses = Sets.newHashSet();
Scott Kennedy8960f0a2012-11-07 15:35:50 -08001449 toAddresses = initToRecipients(account, accountEmail, refMessage.getFrom(),
1450 replytoAddress, sentToAddresses);
Mindy Pereira154386a2012-01-11 13:02:33 -08001451 addToAddresses(toAddresses);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001452 addRecipients(accountEmail, ccAddresses, sentToAddresses);
mindyp5ed63112012-09-17 17:31:45 -07001453 addRecipients(accountEmail, ccAddresses, refMessage.getCcAddresses());
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001454 addCcAddresses(ccAddresses, toAddresses);
1455 }
1456 }
1457
Mindy Pereira1469b4e2012-06-19 19:18:54 -07001458 private String getAddress(String toParse) {
1459 if (!TextUtils.isEmpty(toParse)) {
1460 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(toParse);
1461 if (tokens.length > 0) {
1462 return tokens[0].getAddress();
1463 }
1464 }
1465 return "";
1466 }
1467
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001468 private void addToAddresses(Collection<String> addresses) {
1469 addAddressesToList(addresses, mTo);
1470 }
1471
1472 private void addCcAddresses(Collection<String> addresses, Collection<String> toAddresses) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001473 addCcAddressesToList(tokenizeAddressList(addresses),
1474 toAddresses != null ? tokenizeAddressList(toAddresses) : null, mCc);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001475 }
1476
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001477 private void addBccAddresses(Collection<String> addresses) {
1478 addAddressesToList(addresses, mBcc);
1479 }
1480
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001481 @VisibleForTesting
1482 protected void addCcAddressesToList(List<Rfc822Token[]> addresses,
1483 List<Rfc822Token[]> compareToList, RecipientEditTextView list) {
1484 String address;
1485
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001486 if (compareToList == null) {
1487 for (Rfc822Token[] tokens : addresses) {
1488 for (int i = 0; i < tokens.length; i++) {
1489 address = tokens[i].toString();
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001490 list.append(address + END_TOKEN);
1491 }
1492 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001493 } else {
1494 HashSet<String> compareTo = convertToHashSet(compareToList);
1495 for (Rfc822Token[] tokens : addresses) {
1496 for (int i = 0; i < tokens.length; i++) {
1497 address = tokens[i].toString();
1498 // Check if this is a duplicate:
1499 if (!compareTo.contains(tokens[i].getAddress())) {
1500 // Get the address here
1501 list.append(address + END_TOKEN);
1502 }
1503 }
1504 }
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001505 }
1506 }
1507
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001508 private HashSet<String> convertToHashSet(List<Rfc822Token[]> list) {
1509 HashSet<String> hash = new HashSet<String>();
1510 for (Rfc822Token[] tokens : list) {
1511 for (int i = 0; i < tokens.length; i++) {
1512 hash.add(tokens[i].getAddress());
1513 }
1514 }
1515 return hash;
1516 }
1517
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001518 protected List<Rfc822Token[]> tokenizeAddressList(Collection<String> addresses) {
1519 @VisibleForTesting
1520 List<Rfc822Token[]> tokenized = new ArrayList<Rfc822Token[]>();
1521
1522 for (String address: addresses) {
1523 tokenized.add(Rfc822Tokenizer.tokenize(address));
1524 }
1525 return tokenized;
1526 }
1527
1528 @VisibleForTesting
1529 void addAddressesToList(Collection<String> addresses, RecipientEditTextView list) {
1530 for (String address : addresses) {
1531 addAddressToList(address, list);
1532 }
1533 }
1534
1535 private void addAddressToList(String address, RecipientEditTextView list) {
1536 if (address == null || list == null)
1537 return;
1538
1539 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(address);
1540
1541 for (int i = 0; i < tokens.length; i++) {
1542 list.append(tokens[i] + END_TOKEN);
1543 }
1544 }
1545
1546 @VisibleForTesting
1547 protected Collection<String> initToRecipients(String account, String accountEmail,
mindyp89576472012-11-06 17:07:08 -08001548 String fullSenderAddress, String replyToAddress,
1549 String[] inToAddresses) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001550 // The To recipient is the reply-to address specified in the original
1551 // message, unless it is:
1552 // the current user OR a custom from of the current user, in which case
1553 // it's the To recipient list of the original message.
1554 // OR missing, in which case use the sender of the original message
1555 Set<String> toAddresses = Sets.newHashSet();
mindypfe8557b2012-11-05 12:05:16 -08001556 if (!TextUtils.isEmpty(replyToAddress)
1557 && !recipientMatchesThisAccount(account, replyToAddress)) {
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001558 toAddresses.add(replyToAddress);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001559 } else {
mindyp89576472012-11-06 17:07:08 -08001560 if (!recipientMatchesThisAccount(account, fullSenderAddress)) {
1561 toAddresses.add(fullSenderAddress);
Mindy Pereira1469b4e2012-06-19 19:18:54 -07001562 } else {
1563 // This happens if the user replies to a message they originally
Mindy Pereira1883b342012-06-20 08:34:56 -07001564 // wrote. In this case, "reply" really means "re-send," so we
1565 // target the original recipients. This works as expected even
1566 // if the user sent the original message to themselves.
mindypfe8557b2012-11-05 12:05:16 -08001567 for (String address : inToAddresses) {
1568 if (!recipientMatchesThisAccount(account, address)) {
1569 toAddresses.add(address);
1570 }
1571 }
Mindy Pereira1469b4e2012-06-19 19:18:54 -07001572 }
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001573 }
1574 return toAddresses;
1575 }
1576
Mindy Pereiracecc54a2012-07-31 09:38:11 -07001577 private void addRecipients(String accountAddress, Set<String> recipients, String[] addresses) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001578 for (String email : addresses) {
Mindy Pereiracecc54a2012-07-31 09:38:11 -07001579 // Do not add this account, or any of its custom from addresses, to
1580 // the list of recipients.
Mindy Pereira4a20b702012-01-05 16:24:24 -08001581 final String recipientAddress = Address.getEmailAddress(email).getAddress();
Mindy Pereiracecc54a2012-07-31 09:38:11 -07001582 if (!recipientMatchesThisAccount(accountAddress, recipientAddress)) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001583 recipients.add(email.replace("\"\"", ""));
1584 }
1585 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001586 }
1587
Mindy Pereiracecc54a2012-07-31 09:38:11 -07001588 /**
1589 * A recipient matches this account if it has the same address as the
1590 * currently selected account OR one of the custom from addresses associated
1591 * with the currently selected account.
1592 * @param accountAddress currently selected account
1593 * @param recipientAddress address we are comparing with the currently selected account
1594 * @return
1595 */
1596 protected boolean recipientMatchesThisAccount(String accountAddress, String recipientAddress) {
1597 return accountAddress.equalsIgnoreCase(recipientAddress)
1598 || ReplyFromAccount.isCustomFrom(recipientAddress,
mindypfe8557b2012-11-05 12:05:16 -08001599 mAccount.getReplyFroms());
Mindy Pereiracecc54a2012-07-31 09:38:11 -07001600 }
1601
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001602 private void setSubject(Message refMessage, int action) {
1603 String subject = refMessage.subject;
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001604 String prefix;
1605 String correctedSubject = null;
1606 if (action == ComposeActivity.COMPOSE) {
1607 prefix = "";
1608 } else if (action == ComposeActivity.FORWARD) {
1609 prefix = getString(R.string.forward_subject_label);
1610 } else {
1611 prefix = getString(R.string.reply_subject_label);
1612 }
1613
1614 // Don't duplicate the prefix
Mindy Pereirac7a36992012-07-30 14:00:37 -07001615 if (!TextUtils.isEmpty(subject)
1616 && subject.toLowerCase().startsWith(prefix.toLowerCase())) {
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001617 correctedSubject = subject;
1618 } else {
1619 correctedSubject = String
1620 .format(getString(R.string.formatted_subject), prefix, subject);
1621 }
1622 mSubject.setText(correctedSubject);
1623 }
1624
Mindy Pereira818143e2012-01-11 13:59:49 -08001625 private void initRecipients() {
1626 setupRecipients(mTo);
1627 setupRecipients(mCc);
1628 setupRecipients(mBcc);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001629 }
1630
Mindy Pereira818143e2012-01-11 13:59:49 -08001631 private void setupRecipients(RecipientEditTextView view) {
Paul Westbrook679a8cc2012-02-21 16:37:58 -08001632 view.setAdapter(new RecipientAdapter(this, mAccount));
Mindy Pereirac17d0732011-12-29 10:46:19 -08001633 view.setTokenizer(new Rfc822Tokenizer());
Mindy Pereira82cc5662012-01-09 17:29:30 -08001634 if (mValidator == null) {
Paul Westbrook679a8cc2012-02-21 16:37:58 -08001635 final String accountName = mAccount.name;
Mindy Pereira33fe9082012-01-09 16:24:30 -08001636 int offset = accountName.indexOf("@") + 1;
1637 String account = accountName;
Mindy Pereirac17d0732011-12-29 10:46:19 -08001638 if (offset > -1) {
Mindy Pereira33fe9082012-01-09 16:24:30 -08001639 account = account.substring(accountName.indexOf("@") + 1);
Mindy Pereirac17d0732011-12-29 10:46:19 -08001640 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001641 mValidator = new Rfc822Validator(account);
Mindy Pereirac17d0732011-12-29 10:46:19 -08001642 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001643 view.setValidator(mValidator);
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001644 }
1645
1646 @Override
1647 public void onClick(View v) {
1648 int id = v.getId();
1649 switch (id) {
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001650 case R.id.add_cc_bcc:
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001651 // Verify that cc/ bcc aren't showing.
1652 // Animate in cc/bcc.
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001653 showCcBccViews();
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001654 break;
mindypcd0b0b92012-08-23 14:33:17 -07001655 case R.id.add_photo_attachment:
1656 doAttach(MIME_TYPE_PHOTO);
1657 break;
1658 case R.id.add_video_attachment:
1659 doAttach(MIME_TYPE_VIDEO);
1660 break;
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001661 }
1662 }
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001663
1664 @Override
1665 public boolean onCreateOptionsMenu(Menu menu) {
1666 super.onCreateOptionsMenu(menu);
Mindy Pereirab199d172012-08-13 11:04:03 -07001667 // Don't render any menu items when there are no accounts.
1668 if (mAccounts == null || mAccounts.length == 0) {
1669 return true;
1670 }
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001671 MenuInflater inflater = getMenuInflater();
1672 inflater.inflate(R.menu.compose_menu, menu);
Mindy Pereira82cc5662012-01-09 17:29:30 -08001673 mSave = menu.findItem(R.id.save);
1674 mSend = menu.findItem(R.id.send);
Mindy Pereira3ca5bad2012-04-16 11:02:42 -07001675 MenuItem helpItem = menu.findItem(R.id.help_info_menu_item);
1676 MenuItem sendFeedbackItem = menu.findItem(R.id.feedback_menu_item);
1677 if (helpItem != null) {
1678 helpItem.setVisible(mAccount != null
1679 && mAccount.supportsCapability(AccountCapabilities.HELP_CONTENT));
1680 }
1681 if (sendFeedbackItem != null) {
1682 sendFeedbackItem.setVisible(mAccount != null
1683 && mAccount.supportsCapability(AccountCapabilities.SEND_FEEDBACK));
1684 }
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001685 return true;
1686 }
1687
1688 @Override
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001689 public boolean onPrepareOptionsMenu(Menu menu) {
1690 MenuItem ccBcc = menu.findItem(R.id.add_cc_bcc);
Mindy Pereira818143e2012-01-11 13:59:49 -08001691 if (ccBcc != null && mCc != null) {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001692 // Its possible there is a menu item OR a button.
1693 boolean ccFieldVisible = mCc.isShown();
1694 boolean bccFieldVisible = mBcc.isShown();
1695 if (!ccFieldVisible || !bccFieldVisible) {
1696 ccBcc.setVisible(true);
1697 ccBcc.setTitle(getString(!ccFieldVisible ? R.string.add_cc_label
1698 : R.string.add_bcc_label));
1699 } else {
1700 ccBcc.setVisible(false);
1701 }
1702 }
Mindy Pereira75f66632012-01-11 11:42:02 -08001703 if (mSave != null) {
1704 mSave.setEnabled(shouldSave());
1705 }
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001706 return true;
1707 }
1708
1709 @Override
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001710 public boolean onOptionsItemSelected(MenuItem item) {
1711 int id = item.getItemId();
Mindy Pereira75f66632012-01-11 11:42:02 -08001712 boolean handled = true;
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001713 switch (id) {
Mindy Pereira2db7d4a2012-08-15 11:00:02 -07001714 case R.id.add_photo_attachment:
1715 doAttach(MIME_TYPE_PHOTO);
1716 break;
1717 case R.id.add_video_attachment:
1718 doAttach(MIME_TYPE_VIDEO);
Mindy Pereira7b56a612011-12-14 12:32:28 -08001719 break;
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001720 case R.id.add_cc_bcc:
1721 showCcBccViews();
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001722 break;
Mindy Pereira33fe9082012-01-09 16:24:30 -08001723 case R.id.save:
Mindy Pereira48e31b02012-05-30 13:12:24 -07001724 doSave(true);
Mindy Pereira33fe9082012-01-09 16:24:30 -08001725 break;
1726 case R.id.send:
1727 doSend();
Mindy Pereira75f66632012-01-11 11:42:02 -08001728 break;
Mindy Pereiraefe3d252012-03-01 14:20:44 -08001729 case R.id.discard:
1730 doDiscard();
1731 break;
Mindy Pereira1f936682012-03-02 11:30:33 -08001732 case R.id.settings:
1733 Utils.showSettings(this, mAccount);
1734 break;
Mindy Pereirafbe40192012-03-20 10:40:45 -07001735 case android.R.id.home:
Paul Westbrookdaecb4b2012-05-31 10:21:26 -07001736 onAppUpPressed();
Mindy Pereirafbe40192012-03-20 10:40:45 -07001737 break;
1738 case R.id.help_info_menu_item:
Paul Westbrook30745b62012-08-19 14:10:32 -07001739 Utils.showHelp(this, mAccount, getString(R.string.compose_help_context));
Mindy Pereirafbe40192012-03-20 10:40:45 -07001740 break;
1741 case R.id.feedback_menu_item:
Paul Westbrook17beb0b2012-08-20 13:34:37 -07001742 Utils.sendFeedback(this, mAccount, false);
Mindy Pereirafbe40192012-03-20 10:40:45 -07001743 break;
Mindy Pereira75f66632012-01-11 11:42:02 -08001744 default:
1745 handled = false;
Mindy Pereira33fe9082012-01-09 16:24:30 -08001746 break;
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001747 }
1748 return !handled ? super.onOptionsItemSelected(item) : handled;
1749 }
Mindy Pereira326c6602012-01-04 15:32:42 -08001750
Mindy Pereirab199d172012-08-13 11:04:03 -07001751 @Override
1752 public void onBackPressed() {
1753 // If we are showing the wait fragment, just exit.
1754 if (getWaitFragment() != null) {
1755 finish();
1756 } else {
1757 super.onBackPressed();
1758 }
1759 }
1760
Vikram Aggarwal1672ff82012-09-21 10:15:22 -07001761 /**
1762 * Carries out the "up" action in the action bar.
1763 */
Paul Westbrookdaecb4b2012-05-31 10:21:26 -07001764 private void onAppUpPressed() {
1765 if (mLaunchedFromEmail) {
1766 // If this was started from Gmail, simply treat app up as the system back button, so
1767 // that the last view is restored.
1768 onBackPressed();
1769 return;
1770 }
1771
1772 // Fire the main activity to ensure it launches the "top" screen of mail.
1773 // Since the main Activity is singleTask, it should revive that task if it was already
1774 // started.
Vikram Aggarwal0c3c2052012-09-21 11:06:28 -07001775 final Intent mailIntent = Utils.createViewInboxIntent(mAccount);
Paul Westbrookdaecb4b2012-05-31 10:21:26 -07001776 mailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |
1777 Intent.FLAG_ACTIVITY_TASK_ON_HOME);
1778 startActivity(mailIntent);
1779 finish();
1780 }
1781
Mindy Pereira33fe9082012-01-09 16:24:30 -08001782 private void doSend() {
Mark Weidd19b632012-10-19 13:59:28 -07001783 sendOrSaveWithSanityChecks(false, true, false, false);
Mindy Pereira33fe9082012-01-09 16:24:30 -08001784 }
1785
Mindy Pereira48e31b02012-05-30 13:12:24 -07001786 private void doSave(boolean showToast) {
Mark Weidd19b632012-10-19 13:59:28 -07001787 sendOrSaveWithSanityChecks(true, showToast, false, false);
Mindy Pereira48e31b02012-05-30 13:12:24 -07001788 }
1789
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001790 @VisibleForTesting
1791 public interface SendOrSaveCallback {
Mindy Pereira82cc5662012-01-09 17:29:30 -08001792 public void initializeSendOrSave(SendOrSaveTask sendOrSaveTask);
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001793 public void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage, Message message);
1794 public Message getMessage();
Mindy Pereira82cc5662012-01-09 17:29:30 -08001795 public void sendOrSaveFinished(SendOrSaveTask sendOrSaveTask, boolean success);
1796 }
1797
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001798 @VisibleForTesting
1799 public static class SendOrSaveTask implements Runnable {
Mindy Pereira82cc5662012-01-09 17:29:30 -08001800 private final Context mContext;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001801 @VisibleForTesting
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001802 public final SendOrSaveCallback mSendOrSaveCallback;
1803 @VisibleForTesting
1804 public final SendOrSaveMessage mSendOrSaveMessage;
mindyp44a63392012-11-05 12:05:16 -08001805 private ReplyFromAccount mExistingDraftAccount;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001806
1807 public SendOrSaveTask(Context context, SendOrSaveMessage message,
mindyp44a63392012-11-05 12:05:16 -08001808 SendOrSaveCallback callback, ReplyFromAccount draftAccount) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08001809 mContext = context;
1810 mSendOrSaveCallback = callback;
1811 mSendOrSaveMessage = message;
mindyp44a63392012-11-05 12:05:16 -08001812 mExistingDraftAccount = draftAccount;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001813 }
1814
1815 @Override
1816 public void run() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001817 final SendOrSaveMessage sendOrSaveMessage = mSendOrSaveMessage;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001818
Mindy Pereira92551d02012-04-05 11:31:12 -07001819 final ReplyFromAccount selectedAccount = sendOrSaveMessage.mAccount;
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001820 Message message = mSendOrSaveCallback.getMessage();
1821 long messageId = message != null ? message.id : UIProvider.INVALID_MESSAGE_ID;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001822 // If a previous draft has been saved, in an account that is different
1823 // than what the user wants to send from, remove the old draft, and treat this
1824 // as a new message
mindyp44a63392012-11-05 12:05:16 -08001825 if (mExistingDraftAccount != null
1826 && !selectedAccount.account.uri.equals(mExistingDraftAccount.account.uri)) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08001827 if (messageId != UIProvider.INVALID_MESSAGE_ID) {
1828 ContentResolver resolver = mContext.getContentResolver();
1829 ContentValues values = new ContentValues();
1830 values.put(BaseColumns._ID, messageId);
mindypfebd2262012-11-13 17:45:09 -08001831 if (mExistingDraftAccount.account.expungeMessageUri != null) {
1832 new ContentProviderTask.UpdateTask()
1833 .run(resolver, mExistingDraftAccount.account.expungeMessageUri,
1834 values, null, null);
Mindy Pereiracfb7f332012-02-28 10:23:43 -08001835 } else {
1836 // TODO(mindyp) delete the conversation.
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001837 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001838 // reset messageId to 0, so a new message will be created
1839 messageId = UIProvider.INVALID_MESSAGE_ID;
1840 }
1841 }
1842
1843 final long messageIdToSave = messageId;
Paul Westbrook72e2ea82012-10-22 16:25:22 -07001844 sendOrSaveMessage(messageIdToSave, sendOrSaveMessage, selectedAccount, message);
1845
1846 if (!sendOrSaveMessage.mSave) {
1847 UIProvider.incrementRecipientsTimesContacted(mContext,
1848 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.TO));
1849 UIProvider.incrementRecipientsTimesContacted(mContext,
1850 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.CC));
1851 UIProvider.incrementRecipientsTimesContacted(mContext,
1852 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.BCC));
1853 }
1854 mSendOrSaveCallback.sendOrSaveFinished(SendOrSaveTask.this, true);
1855 }
1856
1857 /**
1858 * Send or Save a message.
1859 */
1860 private void sendOrSaveMessage(long messageIdToSave, SendOrSaveMessage sendOrSaveMessage,
1861 ReplyFromAccount selectedAccount, Message message) {
1862 final ContentResolver resolver = mContext.getContentResolver();
1863 final boolean updateExistingMessage = messageIdToSave != UIProvider.INVALID_MESSAGE_ID;
1864
1865 final String accountMethod = sendOrSaveMessage.mSave ?
1866 UIProvider.AccountCallMethods.SAVE_MESSAGE :
1867 UIProvider.AccountCallMethods.SEND_MESSAGE;
1868
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07001869 try {
1870 if (updateExistingMessage) {
1871 sendOrSaveMessage.mValues.put(BaseColumns._ID, messageIdToSave);
Paul Westbrook72e2ea82012-10-22 16:25:22 -07001872
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07001873 final Bundle result = callAccountSendSaveMethod(resolver,
1874 selectedAccount.account, accountMethod, sendOrSaveMessage);
1875 if (result == null) {
1876 // TODO(pwestbro): Once Email supports the call api, remove this block
1877 // If null was returned, then the provider didn't handle the call method
1878 final Uri updateUri = Uri.parse(sendOrSaveMessage.mSave ?
1879 message.saveUri : message.sendUri);
1880 resolver.update(updateUri, sendOrSaveMessage.mValues, null, null);
1881 }
Paul Westbrook72e2ea82012-10-22 16:25:22 -07001882 } else {
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07001883 final Uri messageUri;
1884 final Bundle result = callAccountSendSaveMethod(resolver,
1885 selectedAccount.account, accountMethod, sendOrSaveMessage);
1886 if (result != null) {
1887 // If a non-null value was returned, then the provider handled the call
1888 // method
1889 messageUri = result.getParcelable(UIProvider.MessageColumns.URI);
1890 } else {
1891 // TODO(pwestbro): Once Email supports the call api, remove this block
1892 messageUri = resolver.insert(
1893 sendOrSaveMessage.mSave ? selectedAccount.account.saveDraftUri
1894 : selectedAccount.account.sendMessageUri,
1895 sendOrSaveMessage.mValues);
1896 }
1897 if (sendOrSaveMessage.mSave && messageUri != null) {
1898 final Cursor messageCursor = resolver.query(messageUri,
1899 UIProvider.MESSAGE_PROJECTION, null, null, null);
1900 if (messageCursor != null) {
1901 try {
1902 if (messageCursor.moveToFirst()) {
1903 // Broadcast notification that a new message has
1904 // been allocated
1905 mSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage,
1906 new Message(messageCursor));
1907 }
1908 } finally {
1909 messageCursor.close();
Paul Westbrookba558482012-03-19 11:00:24 -07001910 }
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07001911 }
1912 }
1913 }
1914 } finally {
1915 // Close any opened file descriptors
1916 closeOpenedAttachmentFds(sendOrSaveMessage);
1917 }
1918 }
1919
1920 private void closeOpenedAttachmentFds(SendOrSaveMessage sendOrSaveMessage) {
1921 final Bundle openedFds = sendOrSaveMessage.attachmentFds();
1922 if (openedFds != null) {
1923 final Set<String> keys = openedFds.keySet();
1924 for (String key : keys) {
1925 final ParcelFileDescriptor fd = openedFds.getParcelable(key);
1926 if (fd != null) {
1927 try {
1928 fd.close();
1929 } catch (IOException e) {
1930 // Do nothing
Paul Westbrookba558482012-03-19 11:00:24 -07001931 }
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001932 }
1933 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001934 }
Paul Westbrook72e2ea82012-10-22 16:25:22 -07001935 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001936
Paul Westbrook72e2ea82012-10-22 16:25:22 -07001937 /**
1938 * Use the {@link ContentResolver#call()} method to send or save the message.
1939 *
1940 * If this was successful, this method will return an non-null Bundle instance
1941 */
1942 private Bundle callAccountSendSaveMethod(ContentResolver resolver, Account account,
1943 String method, SendOrSaveMessage sendOrSaveMessage) {
1944 // Copy all of the values from the content values to the bundle
1945 final Bundle methodExtras = new Bundle(sendOrSaveMessage.mValues.size());
1946 final Set<Entry<String, Object>> valueSet = sendOrSaveMessage.mValues.valueSet();
1947
1948 for (Entry<String, Object> entry : valueSet) {
1949 final Object entryValue = entry.getValue();
1950 final String key = entry.getKey();
1951 if (entryValue instanceof String) {
1952 methodExtras.putString(key, (String)entryValue);
1953 } else if (entryValue instanceof Boolean) {
1954 methodExtras.putBoolean(key, (Boolean)entryValue);
1955 } else if (entryValue instanceof Integer) {
1956 methodExtras.putInt(key, (Integer)entryValue);
1957 } else if (entryValue instanceof Long) {
1958 methodExtras.putLong(key, (Long)entryValue);
1959 } else {
1960 LogUtils.wtf(LOG_TAG, "Unexpected object type: %s",
1961 entryValue.getClass().getName());
1962 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001963 }
Paul Westbrook72e2ea82012-10-22 16:25:22 -07001964
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07001965 // If the SendOrSaveMessage has some opened fds, add them to the bundle
1966 final Bundle fdMap = sendOrSaveMessage.attachmentFds();
1967 if (fdMap != null) {
1968 methodExtras.putParcelable(
1969 UIProvider.SendOrSaveMethodParamKeys.OPENED_FD_MAP, fdMap);
1970 }
1971
Paul Westbrook72e2ea82012-10-22 16:25:22 -07001972 return resolver.call(account.uri, method, account.uri.toString(), methodExtras);
Mindy Pereira82cc5662012-01-09 17:29:30 -08001973 }
1974 }
1975
1976 // Array of the outstanding send or save tasks. Access is synchronized
1977 // with the object itself
1978 /* package for testing */
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001979 @VisibleForTesting
1980 public ArrayList<SendOrSaveTask> mActiveTasks = Lists.newArrayList();
Andy Huang1f8f4dd2012-10-25 21:35:35 -07001981 // FIXME: this variable is never read. related to sRequestMessageIdMap.
Mindy Pereira82cc5662012-01-09 17:29:30 -08001982 private int mRequestId;
Mindy Pereirabdf7a402012-03-01 15:23:26 -08001983 private String mSignature;
Mindy Pereirab199d172012-08-13 11:04:03 -07001984 private Account[] mAccounts;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001985
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001986 @VisibleForTesting
1987 public static class SendOrSaveMessage {
Mindy Pereira92551d02012-04-05 11:31:12 -07001988 final ReplyFromAccount mAccount;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001989 final ContentValues mValues;
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001990 final String mRefMessageId;
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001991 @VisibleForTesting
1992 public final boolean mSave;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001993 final int mRequestId;
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07001994 private final Bundle mAttachmentFds;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001995
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07001996 public SendOrSaveMessage(Context context, ReplyFromAccount account, ContentValues values,
1997 String refMessageId, List<Attachment> attachments, boolean save) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08001998 mAccount = account;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001999 mValues = values;
2000 mRefMessageId = refMessageId;
2001 mSave = save;
2002 mRequestId = mValues.hashCode() ^ hashCode();
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002003
2004 mAttachmentFds = initializeAttachmentFds(context, attachments);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002005 }
2006
2007 int requestId() {
2008 return mRequestId;
2009 }
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002010
2011 Bundle attachmentFds() {
2012 return mAttachmentFds;
2013 }
2014
2015 /**
2016 * Opens {@link ParcelFileDescriptor} for each of the attachments. This method must be
2017 * called before the ComposeActivity finishes.
2018 * Note: The caller is responsible for closing these file descriptors.
2019 */
2020 private Bundle initializeAttachmentFds(Context context, List<Attachment> attachments) {
2021 if (attachments == null || attachments.size() == 0) {
2022 return null;
2023 }
2024
2025 final Bundle result = new Bundle(attachments.size());
2026 final ContentResolver resolver = context.getContentResolver();
2027
2028 for (Attachment attachment : attachments) {
2029 if (attachment == null || Utils.isEmpty(attachment.contentUri)) {
2030 continue;
2031 }
2032
2033 ParcelFileDescriptor fileDescriptor;
2034 try {
2035 fileDescriptor = resolver.openFileDescriptor(attachment.contentUri, "r");
2036 } catch (FileNotFoundException e) {
2037 LogUtils.e(LOG_TAG, e, "Exception attempting to open attachment");
2038 fileDescriptor = null;
2039 }
2040
2041 if (fileDescriptor != null) {
2042 result.putParcelable(attachment.contentUri.toString(), fileDescriptor);
2043 }
2044 }
2045
2046 return result;
2047 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002048 }
2049
2050 /**
2051 * Get the to recipients.
2052 */
2053 public String[] getToAddresses() {
2054 return getAddressesFromList(mTo);
2055 }
2056
2057 /**
2058 * Get the cc recipients.
2059 */
2060 public String[] getCcAddresses() {
2061 return getAddressesFromList(mCc);
2062 }
2063
2064 /**
2065 * Get the bcc recipients.
2066 */
2067 public String[] getBccAddresses() {
2068 return getAddressesFromList(mBcc);
2069 }
2070
2071 public String[] getAddressesFromList(RecipientEditTextView list) {
2072 if (list == null) {
2073 return new String[0];
2074 }
2075 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(list.getText());
2076 int count = tokens.length;
2077 String[] result = new String[count];
2078 for (int i = 0; i < count; i++) {
2079 result[i] = tokens[i].toString();
2080 }
2081 return result;
2082 }
2083
2084 /**
2085 * Check for invalid email addresses.
2086 * @param to String array of email addresses to check.
2087 * @param wrongEmailsOut Emails addresses that were invalid.
2088 */
2089 public void checkInvalidEmails(String[] to, List<String> wrongEmailsOut) {
Mindy Pereirae5f20bf2012-06-25 14:20:40 -07002090 if (mValidator == null) {
2091 return;
2092 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002093 for (String email : to) {
2094 if (!mValidator.isValid(email)) {
2095 wrongEmailsOut.add(email);
2096 }
2097 }
2098 }
2099
2100 /**
2101 * Show an error because the user has entered an invalid recipient.
2102 * @param message
2103 */
2104 public void showRecipientErrorDialog(String message) {
2105 // Only 1 invalid recipients error dialog should be allowed up at a
2106 // time.
2107 if (mRecipientErrorDialog != null) {
2108 mRecipientErrorDialog.dismiss();
2109 }
2110 mRecipientErrorDialog = new AlertDialog.Builder(this).setMessage(message).setTitle(
2111 R.string.recipient_error_dialog_title)
2112 .setIconAttribute(android.R.attr.alertDialogIcon)
Mindy Pereira82cc5662012-01-09 17:29:30 -08002113 .setPositiveButton(
2114 R.string.ok, new Dialog.OnClickListener() {
Marc Blank0bbc8582012-04-23 15:07:57 -07002115 @Override
Mindy Pereira82cc5662012-01-09 17:29:30 -08002116 public void onClick(DialogInterface dialog, int which) {
2117 // after the user dismisses the recipient error
2118 // dialog we want to make sure to refocus the
2119 // recipient to field so they can fix the issue
2120 // easily
2121 if (mTo != null) {
2122 mTo.requestFocus();
2123 }
2124 mRecipientErrorDialog = null;
2125 }
2126 }).show();
2127 }
2128
2129 /**
2130 * Update the state of the UI based on whether or not the current draft
2131 * needs to be saved and the message is not empty.
2132 */
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002133 public void updateSaveUi() {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002134 if (mSave != null) {
2135 mSave.setEnabled((shouldSave() && !isBlank()));
2136 }
2137 }
2138
2139 /**
2140 * Returns true if we need to save the current draft.
2141 */
2142 private boolean shouldSave() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002143 synchronized (mDraftLock) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002144 // The message should only be saved if:
2145 // It hasn't been sent AND
2146 // Some text has been added to the message OR
2147 // an attachment has been added or removed
Mindy Pereiraa2148332012-07-02 13:54:14 -07002148 // AND there is actually something in the draft to save.
Andy Huangd47877e2012-08-09 19:31:24 -07002149 return (mTextChanged || mAttachmentsChanged || mReplyFromChanged)
Mindy Pereiraa2148332012-07-02 13:54:14 -07002150 && !isBlank();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002151 }
2152 }
2153
2154 /**
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002155 * Check if all fields are blank.
Mindy Pereira82cc5662012-01-09 17:29:30 -08002156 * @return boolean
2157 */
2158 public boolean isBlank() {
2159 return mSubject.getText().length() == 0
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002160 && (mBodyView.getText().length() == 0 || getSignatureStartPosition(mSignature,
2161 mBodyView.getText().toString()) == 0)
2162 && mTo.length() == 0
2163 && mCc.length() == 0 && mBcc.length() == 0
2164 && mAttachmentsView.getAttachments().size() == 0;
2165 }
2166
2167 @VisibleForTesting
2168 protected int getSignatureStartPosition(String signature, String bodyText) {
2169 int startPos = -1;
2170
2171 if (TextUtils.isEmpty(signature) || TextUtils.isEmpty(bodyText)) {
2172 return startPos;
2173 }
2174
2175 int bodyLength = bodyText.length();
2176 int signatureLength = signature.length();
2177 String printableVersion = convertToPrintableSignature(signature);
2178 int printableLength = printableVersion.length();
2179
2180 if (bodyLength >= printableLength
2181 && bodyText.substring(bodyLength - printableLength)
2182 .equals(printableVersion)) {
2183 startPos = bodyLength - printableLength;
2184 } else if (bodyLength >= signatureLength
2185 && bodyText.substring(bodyLength - signatureLength)
2186 .equals(signature)) {
2187 startPos = bodyLength - signatureLength;
2188 }
2189 return startPos;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002190 }
2191
2192 /**
2193 * Allows any changes made by the user to be ignored. Called when the user
2194 * decides to discard a draft.
2195 */
2196 private void discardChanges() {
2197 mTextChanged = false;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002198 mAttachmentsChanged = false;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002199 mReplyFromChanged = false;
2200 }
2201
2202 /**
Mindy Pereira181df782012-03-01 13:32:44 -08002203 * @param body
2204 * @param save
2205 * @param showToast
2206 * @return Whether the send or save succeeded.
2207 */
2208 protected boolean sendOrSaveWithSanityChecks(final boolean save, final boolean showToast,
Mark Weidd19b632012-10-19 13:59:28 -07002209 final boolean orientationChanged, final boolean autoSend) {
Mark Wei009b3712012-10-18 18:07:50 -07002210 if (mAccounts == null || mAccount == null) {
2211 Toast.makeText(this, R.string.send_failed, Toast.LENGTH_SHORT).show();
Mark Weidd19b632012-10-19 13:59:28 -07002212 if (autoSend) {
2213 finish();
2214 }
Mark Wei009b3712012-10-18 18:07:50 -07002215 return false;
2216 }
2217
Mindy Pereira181df782012-03-01 13:32:44 -08002218 String[] to, cc, bcc;
2219 Editable body = mBodyView.getEditableText();
Mindy Pereira181df782012-03-01 13:32:44 -08002220 if (orientationChanged) {
2221 to = cc = bcc = new String[0];
2222 } else {
2223 to = getToAddresses();
2224 cc = getCcAddresses();
2225 bcc = getBccAddresses();
2226 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002227
Mindy Pereira181df782012-03-01 13:32:44 -08002228 // Don't let the user send to nobody (but it's okay to save a message
2229 // with no recipients)
2230 if (!save && (to.length == 0 && cc.length == 0 && bcc.length == 0)) {
2231 showRecipientErrorDialog(getString(R.string.recipient_needed));
2232 return false;
2233 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002234
Mindy Pereira181df782012-03-01 13:32:44 -08002235 List<String> wrongEmails = new ArrayList<String>();
2236 if (!save) {
2237 checkInvalidEmails(to, wrongEmails);
2238 checkInvalidEmails(cc, wrongEmails);
2239 checkInvalidEmails(bcc, wrongEmails);
2240 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002241
Mindy Pereira181df782012-03-01 13:32:44 -08002242 // Don't let the user send an email with invalid recipients
2243 if (wrongEmails.size() > 0) {
2244 String errorText = String.format(getString(R.string.invalid_recipient),
2245 wrongEmails.get(0));
2246 showRecipientErrorDialog(errorText);
2247 return false;
2248 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002249
Mindy Pereira181df782012-03-01 13:32:44 -08002250 DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
Marc Blank0bbc8582012-04-23 15:07:57 -07002251 @Override
Mindy Pereira181df782012-03-01 13:32:44 -08002252 public void onClick(DialogInterface dialog, int which) {
2253 sendOrSave(mBodyView.getEditableText(), save, showToast, orientationChanged);
2254 }
2255 };
Mindy Pereira82cc5662012-01-09 17:29:30 -08002256
Mindy Pereira181df782012-03-01 13:32:44 -08002257 // Show a warning before sending only if there are no attachments.
2258 if (!save) {
2259 if (mAttachmentsView.getAttachments().isEmpty() && showEmptyTextWarnings()) {
2260 boolean warnAboutEmptySubject = isSubjectEmpty();
2261 boolean emptyBody = TextUtils.getTrimmedLength(body) == 0;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002262
Mindy Pereira181df782012-03-01 13:32:44 -08002263 // A warning about an empty body may not be warranted when
2264 // forwarding mails, since a common use case is to forward
2265 // quoted text and not append any more text.
2266 boolean warnAboutEmptyBody = emptyBody && (!mForward || isBodyEmpty());
Mindy Pereira82cc5662012-01-09 17:29:30 -08002267
Mindy Pereira181df782012-03-01 13:32:44 -08002268 // When we bring up a dialog warning the user about a send,
2269 // assume that they accept sending the message. If they do not,
2270 // the dialog listener is required to enable sending again.
2271 if (warnAboutEmptySubject) {
2272 showSendConfirmDialog(R.string.confirm_send_message_with_no_subject, listener);
2273 return true;
2274 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002275
Mindy Pereira181df782012-03-01 13:32:44 -08002276 if (warnAboutEmptyBody) {
2277 showSendConfirmDialog(R.string.confirm_send_message_with_no_body, listener);
2278 return true;
2279 }
2280 }
2281 // Ask for confirmation to send (if always required)
2282 if (showSendConfirmation()) {
2283 showSendConfirmDialog(R.string.confirm_send_message, listener);
2284 return true;
2285 }
2286 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002287
Mindy Pereira181df782012-03-01 13:32:44 -08002288 sendOrSave(body, save, showToast, false);
2289 return true;
2290 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002291
Mindy Pereira181df782012-03-01 13:32:44 -08002292 /**
2293 * Returns a boolean indicating whether warnings should be shown for empty
2294 * subject and body fields
Andy Huang5c5fd572012-04-08 18:19:29 -07002295 *
Mindy Pereira181df782012-03-01 13:32:44 -08002296 * @return True if a warning should be shown for empty text fields
2297 */
2298 protected boolean showEmptyTextWarnings() {
2299 return mAttachmentsView.getAttachments().size() == 0;
2300 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002301
Mindy Pereira181df782012-03-01 13:32:44 -08002302 /**
2303 * Returns a boolean indicating whether the user should confirm each send
2304 *
2305 * @return True if a warning should be on each send
2306 */
2307 protected boolean showSendConfirmation() {
2308 return mCachedSettings != null ? mCachedSettings.confirmSend : false;
2309 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002310
Mindy Pereira181df782012-03-01 13:32:44 -08002311 private void showSendConfirmDialog(int messageId, DialogInterface.OnClickListener listener) {
2312 if (mSendConfirmDialog != null) {
2313 mSendConfirmDialog.dismiss();
2314 mSendConfirmDialog = null;
2315 }
2316 mSendConfirmDialog = new AlertDialog.Builder(this).setMessage(messageId)
2317 .setTitle(R.string.confirm_send_title)
2318 .setIconAttribute(android.R.attr.alertDialogIcon)
2319 .setPositiveButton(R.string.send, listener)
Mindy Pereira6edd5972012-06-19 10:22:36 -07002320 .setNegativeButton(R.string.cancel, this)
2321 .show();
Mindy Pereira181df782012-03-01 13:32:44 -08002322 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002323
Mindy Pereira181df782012-03-01 13:32:44 -08002324 /**
2325 * Returns whether the ComposeArea believes there is any text in the body of
2326 * the composition. TODO: When ComposeArea controls the Body as well, add
2327 * that here.
2328 */
2329 public boolean isBodyEmpty() {
2330 return !mQuotedTextView.isTextIncluded();
2331 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002332
Mindy Pereira181df782012-03-01 13:32:44 -08002333 /**
2334 * Test to see if the subject is empty.
2335 *
2336 * @return boolean.
2337 */
2338 // TODO: this will likely go away when composeArea.focus() is implemented
2339 // after all the widget control is moved over.
2340 public boolean isSubjectEmpty() {
2341 return TextUtils.getTrimmedLength(mSubject.getText()) == 0;
2342 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002343
Mindy Pereira181df782012-03-01 13:32:44 -08002344 /* package */
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002345 static int sendOrSaveInternal(Context context, ReplyFromAccount replyFromAccount,
Paul Westbrook05b92b82012-04-20 13:29:37 -07002346 Message message, final Message refMessage, Spanned body, final CharSequence quotedText,
mindyp44a63392012-11-05 12:05:16 -08002347 SendOrSaveCallback callback, Handler handler, boolean save, int composeMode,
2348 ReplyFromAccount draftAccount) {
Mindy Pereira29ef1b82012-01-13 11:26:21 -08002349 ContentValues values = new ContentValues();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002350
Mindy Pereirac2031972012-04-03 09:38:35 -07002351 String refMessageId = refMessage != null ? refMessage.uri.toString() : "";
2352
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002353 MessageModification.putToAddresses(values, message.getToAddresses());
2354 MessageModification.putCcAddresses(values, message.getCcAddresses());
2355 MessageModification.putBccAddresses(values, message.getBccAddresses());
Mindy Pereira82cc5662012-01-09 17:29:30 -08002356
Scott Kennedy8960f0a2012-11-07 15:35:50 -08002357 MessageModification.putCustomFromAddress(values, message.getFrom());
Mindy Pereira92551d02012-04-05 11:31:12 -07002358
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002359 MessageModification.putSubject(values, message.subject);
mindyped9c2f02012-10-12 10:02:08 -07002360 String htmlBody = Html.toHtml(new SpannableString(body.toString()));
Paul Westbrook05b92b82012-04-20 13:29:37 -07002361
Mindy Pereira29ef1b82012-01-13 11:26:21 -08002362 boolean includeQuotedText = !TextUtils.isEmpty(quotedText);
2363 StringBuilder fullBody = new StringBuilder(htmlBody);
2364 if (includeQuotedText) {
Mindy Pereirae8caf122012-03-20 15:23:31 -07002365 // HTML gets converted to text for now
2366 final String text = quotedText.toString();
2367 if (QuotedTextView.containsQuotedText(text)) {
2368 int pos = QuotedTextView.getQuotedTextOffset(text);
Paul Westbrook55271cf2012-04-20 16:25:02 -07002369 final int quoteStartPos = fullBody.length() + pos;
2370 fullBody.append(text);
2371 MessageModification.putQuoteStartPos(values, quoteStartPos);
Mindy Pereira12575862012-03-21 16:30:54 -07002372 MessageModification.putForward(values, composeMode == ComposeActivity.FORWARD);
Mindy Pereirae8caf122012-03-20 15:23:31 -07002373 MessageModification.putAppendRefMessageContent(values, includeQuotedText);
Mindy Pereira29ef1b82012-01-13 11:26:21 -08002374 } else {
Mindy Pereirae8caf122012-03-20 15:23:31 -07002375 LogUtils.w(LOG_TAG, "Couldn't find quoted text");
2376 // This shouldn't happen, but just use what we have,
2377 // and don't do server-side expansion
2378 fullBody.append(text);
Mindy Pereira29ef1b82012-01-13 11:26:21 -08002379 }
2380 }
Mindy Pereira002ff522012-05-30 10:31:26 -07002381 int draftType = getDraftType(composeMode);
Mindy Pereira12575862012-03-21 16:30:54 -07002382 MessageModification.putDraftType(values, draftType);
Mindy Pereirac6f1e2a2012-04-04 10:33:45 -07002383 if (refMessage != null) {
2384 if (!TextUtils.isEmpty(refMessage.bodyHtml)) {
2385 MessageModification.putBodyHtml(values, fullBody.toString());
2386 }
2387 if (!TextUtils.isEmpty(refMessage.bodyText)) {
mindypc59dd822012-11-13 10:56:21 -08002388 MessageModification.putBody(values,
2389 Utils.convertHtmlToPlainText(fullBody.toString()).toString());
Mindy Pereirac6f1e2a2012-04-04 10:33:45 -07002390 }
2391 } else {
Mindy Pereirac2031972012-04-03 09:38:35 -07002392 MessageModification.putBodyHtml(values, fullBody.toString());
mindypc59dd822012-11-13 10:56:21 -08002393 MessageModification.putBody(values, Utils.convertHtmlToPlainText(fullBody.toString())
2394 .toString());
Mindy Pereirac2031972012-04-03 09:38:35 -07002395 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002396 MessageModification.putAttachments(values, message.getAttachments());
Mindy Pereira12575862012-03-21 16:30:54 -07002397 if (!TextUtils.isEmpty(refMessageId)) {
2398 MessageModification.putRefMessageId(values, refMessageId);
2399 }
Paul Westbrook3c7f94d2012-10-23 14:13:00 -07002400 SendOrSaveMessage sendOrSaveMessage = new SendOrSaveMessage(context, replyFromAccount,
2401 values, refMessageId, message.getAttachments(), save);
mindyp44a63392012-11-05 12:05:16 -08002402 SendOrSaveTask sendOrSaveTask = new SendOrSaveTask(context, sendOrSaveMessage, callback,
2403 draftAccount);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002404
Mindy Pereira181df782012-03-01 13:32:44 -08002405 callback.initializeSendOrSave(sendOrSaveTask);
Mindy Pereira181df782012-03-01 13:32:44 -08002406 // Do the send/save action on the specified handler to avoid possible
2407 // ANRs
2408 handler.post(sendOrSaveTask);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002409
Mindy Pereira181df782012-03-01 13:32:44 -08002410 return sendOrSaveMessage.requestId();
2411 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002412
Mindy Pereira002ff522012-05-30 10:31:26 -07002413 private static int getDraftType(int mode) {
2414 int draftType = -1;
2415 switch (mode) {
2416 case ComposeActivity.COMPOSE:
2417 draftType = DraftType.COMPOSE;
2418 break;
2419 case ComposeActivity.REPLY:
2420 draftType = DraftType.REPLY;
2421 break;
2422 case ComposeActivity.REPLY_ALL:
2423 draftType = DraftType.REPLY_ALL;
2424 break;
2425 case ComposeActivity.FORWARD:
2426 draftType = DraftType.FORWARD;
2427 break;
2428 }
2429 return draftType;
2430 }
2431
Mindy Pereira181df782012-03-01 13:32:44 -08002432 private void sendOrSave(Spanned body, boolean save, boolean showToast,
2433 boolean orientationChanged) {
2434 // Check if user is a monkey. Monkeys can compose and hit send
2435 // button but are not allowed to send anything off the device.
Paul Westbrook3ae824c2012-04-06 13:29:39 -07002436 if (ActivityManager.isUserAMonkey()) {
Mindy Pereira181df782012-03-01 13:32:44 -08002437 return;
2438 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002439
Mindy Pereira181df782012-03-01 13:32:44 -08002440 String[] to, cc, bcc;
2441 if (orientationChanged) {
2442 to = cc = bcc = new String[0];
2443 } else {
2444 to = getToAddresses();
2445 cc = getCcAddresses();
2446 bcc = getBccAddresses();
2447 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002448
Mindy Pereira181df782012-03-01 13:32:44 -08002449 SendOrSaveCallback callback = new SendOrSaveCallback() {
Andy Huang1f8f4dd2012-10-25 21:35:35 -07002450 // FIXME: unused
Mindy Pereira82cc5662012-01-09 17:29:30 -08002451 private int mRestoredRequestId;
2452
Marc Blank0bbc8582012-04-23 15:07:57 -07002453 @Override
Mindy Pereira82cc5662012-01-09 17:29:30 -08002454 public void initializeSendOrSave(SendOrSaveTask sendOrSaveTask) {
Mindy Pereira181df782012-03-01 13:32:44 -08002455 synchronized (mActiveTasks) {
2456 int numTasks = mActiveTasks.size();
2457 if (numTasks == 0) {
2458 // Start service so we won't be killed if this app is
2459 // put in the background.
2460 startService(new Intent(ComposeActivity.this, EmptyService.class));
2461 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002462
Mindy Pereira181df782012-03-01 13:32:44 -08002463 mActiveTasks.add(sendOrSaveTask);
2464 }
2465 if (sTestSendOrSaveCallback != null) {
2466 sTestSendOrSaveCallback.initializeSendOrSave(sendOrSaveTask);
2467 }
2468 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002469
Marc Blank0bbc8582012-04-23 15:07:57 -07002470 @Override
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002471 public void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage,
2472 Message message) {
Mindy Pereira181df782012-03-01 13:32:44 -08002473 synchronized (mDraftLock) {
mindyp44a63392012-11-05 12:05:16 -08002474 mDraftAccount = sendOrSaveMessage.mAccount;
Mindy Pereira181df782012-03-01 13:32:44 -08002475 mDraftId = message.id;
2476 mDraft = message;
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002477 if (sRequestMessageIdMap != null) {
2478 sRequestMessageIdMap.put(sendOrSaveMessage.requestId(), mDraftId);
2479 }
Mindy Pereira181df782012-03-01 13:32:44 -08002480 // Cache request message map, in case the process is killed
2481 saveRequestMap();
2482 }
2483 if (sTestSendOrSaveCallback != null) {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002484 sTestSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage, message);
Mindy Pereira181df782012-03-01 13:32:44 -08002485 }
2486 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002487
Marc Blank0bbc8582012-04-23 15:07:57 -07002488 @Override
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002489 public Message getMessage() {
2490 synchronized (mDraftLock) {
2491 return mDraft;
2492 }
2493 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002494
Marc Blank0bbc8582012-04-23 15:07:57 -07002495 @Override
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002496 public void sendOrSaveFinished(SendOrSaveTask task, boolean success) {
Mindy Pereira47d0e652012-07-23 09:45:07 -07002497 // Update the last sent from account.
2498 if (mAccount != null) {
2499 MailAppProvider.getInstance().setLastSentFromAccount(mAccount.uri.toString());
2500 }
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002501 if (success) {
2502 // Successfully sent or saved so reset change markers
2503 discardChanges();
2504 } else {
2505 // A failure happened with saving/sending the draft
2506 // TODO(pwestbro): add a better string that should be used
2507 // when failing to send or save
2508 Toast.makeText(ComposeActivity.this, R.string.send_failed, Toast.LENGTH_SHORT)
2509 .show();
2510 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002511
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002512 int numTasks;
2513 synchronized (mActiveTasks) {
2514 // Remove the task from the list of active tasks
2515 mActiveTasks.remove(task);
2516 numTasks = mActiveTasks.size();
2517 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002518
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002519 if (numTasks == 0) {
2520 // Stop service so we can be killed.
2521 stopService(new Intent(ComposeActivity.this, EmptyService.class));
2522 }
2523 if (sTestSendOrSaveCallback != null) {
2524 sTestSendOrSaveCallback.sendOrSaveFinished(task, success);
2525 }
2526 }
Mindy Pereira181df782012-03-01 13:32:44 -08002527 };
Mindy Pereira82cc5662012-01-09 17:29:30 -08002528
Mindy Pereira181df782012-03-01 13:32:44 -08002529 // Get the selected account if the from spinner has been setup.
Mindy Pereira92551d02012-04-05 11:31:12 -07002530 ReplyFromAccount selectedAccount = mReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -08002531 String fromAddress = selectedAccount.name;
2532 if (selectedAccount == null || fromAddress == null) {
2533 // We don't have either the selected account or from address,
2534 // use mAccount.
Mindy Pereira92551d02012-04-05 11:31:12 -07002535 selectedAccount = mReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -08002536 fromAddress = mAccount.name;
2537 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002538
Mindy Pereira181df782012-03-01 13:32:44 -08002539 if (mSendSaveTaskHandler == null) {
2540 HandlerThread handlerThread = new HandlerThread("Send Message Task Thread");
2541 handlerThread.start();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002542
Mindy Pereira181df782012-03-01 13:32:44 -08002543 mSendSaveTaskHandler = new Handler(handlerThread.getLooper());
2544 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002545
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002546 Message msg = createMessage(mReplyFromAccount, getMode());
Paul Westbrook05b92b82012-04-20 13:29:37 -07002547 mRequestId = sendOrSaveInternal(this, mReplyFromAccount, msg, mRefMessage, body,
2548 mQuotedTextView.getQuotedTextIfIncluded(), callback,
mindyp44a63392012-11-05 12:05:16 -08002549 mSendSaveTaskHandler, save, mComposeMode, mDraftAccount);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002550
Mindy Pereira181df782012-03-01 13:32:44 -08002551 if (mRecipient != null && mRecipient.equals(mAccount.name)) {
2552 mRecipient = selectedAccount.name;
2553 }
Paul Westbrookb1f573c2012-04-06 11:38:28 -07002554 setAccount(selectedAccount.account);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002555
Mindy Pereira181df782012-03-01 13:32:44 -08002556 // Don't display the toast if the user is just changing the orientation,
2557 // but we still need to save the draft to the cursor because this is how we restore
2558 // the attachments when the configuration change completes.
2559 if (showToast && (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) {
2560 Toast.makeText(this, save ? R.string.message_saved : R.string.sending_message,
2561 Toast.LENGTH_LONG).show();
2562 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002563
Mindy Pereira181df782012-03-01 13:32:44 -08002564 // Need to update variables here because the send or save completes
2565 // asynchronously even though the toast shows right away.
2566 discardChanges();
2567 updateSaveUi();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002568
Mindy Pereira181df782012-03-01 13:32:44 -08002569 // If we are sending, finish the activity
2570 if (!save) {
2571 finish();
2572 }
2573 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002574
Mindy Pereira181df782012-03-01 13:32:44 -08002575 /**
2576 * Save the state of the request messageid map. This allows for the Gmail
2577 * process to be killed, but and still allow for ComposeActivity instances
2578 * to be recreated correctly.
2579 */
2580 private void saveRequestMap() {
2581 // TODO: store the request map in user preferences.
2582 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002583
Mindy Pereira2db7d4a2012-08-15 11:00:02 -07002584 private void doAttach(String type) {
Mindy Pereira013194c2012-01-06 15:09:33 -08002585 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2586 i.addCategory(Intent.CATEGORY_OPENABLE);
Paul Westbrookd6a9a3f2012-04-26 18:47:23 -07002587 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
Mindy Pereira2db7d4a2012-08-15 11:00:02 -07002588 i.setType(type);
Mindy Pereira013194c2012-01-06 15:09:33 -08002589 mAddingAttachment = true;
Mindy Pereira181df782012-03-01 13:32:44 -08002590 startActivityForResult(Intent.createChooser(i, getText(R.string.select_attachment_type)),
2591 RESULT_PICK_ATTACHMENT);
Mindy Pereira013194c2012-01-06 15:09:33 -08002592 }
2593
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08002594 private void showCcBccViews() {
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08002595 mCcBccView.show(true, true, true);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08002596 if (mCcBccButton != null) {
mindypcd0b0b92012-08-23 14:33:17 -07002597 mCcBccButton.setVisibility(View.INVISIBLE);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08002598 }
2599 }
2600
Mindy Pereira326c6602012-01-04 15:32:42 -08002601 @Override
2602 public boolean onNavigationItemSelected(int position, long itemId) {
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08002603 int initialComposeMode = mComposeMode;
Mindy Pereira326c6602012-01-04 15:32:42 -08002604 if (position == ComposeActivity.REPLY) {
2605 mComposeMode = ComposeActivity.REPLY;
2606 } else if (position == ComposeActivity.REPLY_ALL) {
2607 mComposeMode = ComposeActivity.REPLY_ALL;
2608 } else if (position == ComposeActivity.FORWARD) {
2609 mComposeMode = ComposeActivity.FORWARD;
2610 }
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07002611 clearChangeListeners();
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08002612 if (initialComposeMode != mComposeMode) {
Mindy Pereira154386a2012-01-11 13:02:33 -08002613 resetMessageForModeChange();
Mindy Pereiraef388302012-06-18 19:07:44 -07002614 if (mDraft == null && mRefMessage != null) {
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07002615 setFieldsFromRefMessage(mComposeMode, mAccount.name);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07002616 }
Mindy Pereiraef388302012-06-18 19:07:44 -07002617 boolean showCc = false;
2618 boolean showBcc = false;
2619 if (mDraft != null) {
2620 // Following desktop behavior, if the user has added a BCC
2621 // field to a draft, we show it regardless of compose mode.
Scott Kennedy8960f0a2012-11-07 15:35:50 -08002622 showBcc = !TextUtils.isEmpty(mDraft.getBcc());
Mindy Pereiraef388302012-06-18 19:07:44 -07002623 // Use the draft to determine what to populate.
2624 // If the Bcc field is showing, show the Cc field whether it is populated or not.
Scott Kennedy8960f0a2012-11-07 15:35:50 -08002625 showCc = showBcc
2626 || (!TextUtils.isEmpty(mDraft.getCc()) && mComposeMode == REPLY_ALL);
Mindy Pereiraef388302012-06-18 19:07:44 -07002627 } else if (mRefMessage != null) {
mindyp9b1ac572012-09-27 14:12:00 -07002628 showCc = !TextUtils.isEmpty(mCc.getText());
Mindy Pereiraef388302012-06-18 19:07:44 -07002629 }
2630 mCcBccView.show(false, showCc, showBcc);
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08002631 }
Mindy Pereiraef388302012-06-18 19:07:44 -07002632 updateHideOrShowCcBcc();
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07002633 initChangeListeners();
Mindy Pereira326c6602012-01-04 15:32:42 -08002634 return true;
2635 }
2636
Mindy Pereirab3112a22012-06-20 12:10:03 -07002637 @VisibleForTesting
2638 protected void resetMessageForModeChange() {
Mindy Pereira154386a2012-01-11 13:02:33 -08002639 // When switching between reply, reply all, forward,
2640 // follow the behavior of webview.
2641 // The contents of the following fields are cleared
2642 // so that they can be populated directly from the
2643 // ref message:
2644 // 1) Any recipient fields
2645 // 2) The subject
2646 mTo.setText("");
2647 mCc.setText("");
2648 mBcc.setText("");
2649 // Any edits to the subject are replaced with the original subject.
2650 mSubject.setText("");
2651
2652 // Any changes to the contents of the following fields are kept:
2653 // 1) Body
2654 // 2) Attachments
2655 // If the user made changes to attachments, keep their changes.
2656 if (!mAttachmentsChanged) {
2657 mAttachmentsView.deleteAllAttachments();
2658 }
2659 }
2660
Mindy Pereira326c6602012-01-04 15:32:42 -08002661 private class ComposeModeAdapter extends ArrayAdapter<String> {
2662
2663 private LayoutInflater mInflater;
2664
2665 public ComposeModeAdapter(Context context) {
2666 super(context, R.layout.compose_mode_item, R.id.mode, getResources()
2667 .getStringArray(R.array.compose_modes));
2668 }
2669
2670 private LayoutInflater getInflater() {
2671 if (mInflater == null) {
2672 mInflater = LayoutInflater.from(getContext());
2673 }
2674 return mInflater;
2675 }
2676
2677 @Override
2678 public View getView(int position, View convertView, ViewGroup parent) {
2679 if (convertView == null) {
2680 convertView = getInflater().inflate(R.layout.compose_mode_display_item, null);
2681 }
2682 ((TextView) convertView.findViewById(R.id.mode)).setText(getItem(position));
2683 return super.getView(position, convertView, parent);
2684 }
2685 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002686
2687 @Override
2688 public void onRespondInline(String text) {
2689 appendToBody(text, false);
mindyp40882432012-09-06 11:07:40 -07002690 mQuotedTextView.setUpperDividerVisible(false);
2691 mTo.requestFocus();
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002692 }
2693
2694 /**
2695 * Append text to the body of the message. If there is no existing body
2696 * text, just sets the body to text.
2697 *
2698 * @param text
2699 * @param withSignature True to append a signature.
2700 */
2701 public void appendToBody(CharSequence text, boolean withSignature) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002702 Editable bodyText = mBodyView.getEditableText();
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002703 if (bodyText != null && bodyText.length() > 0) {
2704 bodyText.append(text);
2705 } else {
2706 setBody(text, withSignature);
2707 }
2708 }
2709
2710 /**
2711 * Set the body of the message.
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002712 *
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002713 * @param text
2714 * @param withSignature True to append a signature.
2715 */
2716 public void setBody(CharSequence text, boolean withSignature) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002717 mBodyView.setText(text);
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002718 if (withSignature) {
2719 appendSignature();
2720 }
2721 }
2722
2723 private void appendSignature() {
Mindy Pereirab13917c2012-03-29 08:08:19 -07002724 String newSignature = mCachedSettings != null ? mCachedSettings.signature : null;
Mindy Pereira433b1982012-04-03 11:53:07 -07002725 boolean hasFocus = mBodyView.hasFocus();
Mindy Pereirab13917c2012-03-29 08:08:19 -07002726 if (!TextUtils.equals(newSignature, mSignature)) {
2727 mSignature = newSignature;
2728 if (!TextUtils.isEmpty(mSignature)
2729 && getSignatureStartPosition(mSignature,
2730 mBodyView.getText().toString()) < 0) {
2731 // Appending a signature does not count as changing text.
2732 mBodyView.removeTextChangedListener(this);
2733 mBodyView.append(convertToPrintableSignature(mSignature));
2734 mBodyView.addTextChangedListener(this);
2735 }
Mindy Pereira433b1982012-04-03 11:53:07 -07002736 if (hasFocus) {
2737 focusBody();
2738 }
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002739 }
2740 }
2741
2742 private String convertToPrintableSignature(String signature) {
2743 String signatureResource = getResources().getString(R.string.signature);
2744 if (signature == null) {
2745 signature = "";
2746 }
2747 return String.format(signatureResource, signature);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002748 }
Mindy Pereira1a95a572012-01-05 12:21:29 -08002749
Mindy Pereira5a85e2b2012-01-11 09:53:32 -08002750 @Override
2751 public void onAccountChanged() {
Mindy Pereira92551d02012-04-05 11:31:12 -07002752 mReplyFromAccount = mFromSpinner.getCurrentAccount();
2753 if (!mAccount.equals(mReplyFromAccount.account)) {
mindypf432dbc2012-11-12 16:00:44 -08002754 // Clear a signature, if there was one.
2755 mBodyView.removeTextChangedListener(this);
2756 String oldSignature = mSignature;
2757 String bodyText = getBody().getText().toString();
2758 if (!TextUtils.isEmpty(oldSignature)) {
2759 int pos = getSignatureStartPosition(oldSignature, bodyText);
2760 if (pos > -1) {
2761 mBodyView.setText(bodyText.substring(0, pos));
2762 }
2763 }
Paul Westbrookb1f573c2012-04-06 11:38:28 -07002764 setAccount(mReplyFromAccount.account);
mindypf432dbc2012-11-12 16:00:44 -08002765 mBodyView.addTextChangedListener(this);
Mindy Pereira181df782012-03-01 13:32:44 -08002766 // TODO: handle discarding attachments when switching accounts.
2767 // Only enable save for this draft if there is any other content
2768 // in the message.
2769 if (!isBlank()) {
2770 enableSave(true);
2771 }
2772 mReplyFromChanged = true;
2773 initRecipients();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002774 }
Mindy Pereira1a95a572012-01-05 12:21:29 -08002775 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002776
2777 public void enableSave(boolean enabled) {
2778 if (mSave != null) {
2779 mSave.setEnabled(enabled);
2780 }
2781 }
2782
2783 public void enableSend(boolean enabled) {
2784 if (mSend != null) {
2785 mSend.setEnabled(enabled);
2786 }
2787 }
2788
2789 /**
2790 * Handles button clicks from any error dialogs dealing with sending
2791 * a message.
2792 */
2793 @Override
2794 public void onClick(DialogInterface dialog, int which) {
2795 switch (which) {
2796 case DialogInterface.BUTTON_POSITIVE: {
2797 doDiscardWithoutConfirmation(true /* show toast */ );
2798 break;
2799 }
2800 case DialogInterface.BUTTON_NEGATIVE: {
2801 // If the user cancels the send, re-enable the send button.
2802 enableSend(true);
2803 break;
2804 }
2805 }
2806
2807 }
2808
Mindy Pereiraefe3d252012-03-01 14:20:44 -08002809 private void doDiscard() {
2810 new AlertDialog.Builder(this).setMessage(R.string.confirm_discard_text)
2811 .setPositiveButton(R.string.ok, this)
2812 .setNegativeButton(R.string.cancel, null)
2813 .create().show();
2814 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002815 /**
2816 * Effectively discard the current message.
2817 *
2818 * This method is either invoked from the menu or from the dialog
2819 * once the user has confirmed that they want to discard the message.
2820 * @param showToast show "Message discarded" toast if true
2821 */
2822 private void doDiscardWithoutConfirmation(boolean showToast) {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002823 synchronized (mDraftLock) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002824 if (mDraftId != UIProvider.INVALID_MESSAGE_ID) {
2825 ContentValues values = new ContentValues();
Paul Westbrookb7050e62012-03-20 12:59:44 -07002826 values.put(BaseColumns._ID, mDraftId);
Marc Blank78ea8e22012-08-04 11:14:06 -07002827 if (!mAccount.expungeMessageUri.equals(Uri.EMPTY)) {
Mindy Pereiracfb7f332012-02-28 10:23:43 -08002828 getContentResolver().update(mAccount.expungeMessageUri, values, null, null);
2829 } else {
Marc Blank0bbc8582012-04-23 15:07:57 -07002830 getContentResolver().delete(mDraft.uri, null, null);
Mindy Pereiracfb7f332012-02-28 10:23:43 -08002831 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002832 // This is not strictly necessary (since we should not try to
2833 // save the draft after calling this) but it ensures that if we
2834 // do save again for some reason we make a new draft rather than
2835 // trying to resave an expunged draft.
2836 mDraftId = UIProvider.INVALID_MESSAGE_ID;
2837 }
2838 }
2839
2840 if (showToast) {
2841 // Display a toast to let the user know
2842 Toast.makeText(this, R.string.message_discarded, Toast.LENGTH_SHORT).show();
2843 }
2844
2845 // This prevents the draft from being saved in onPause().
2846 discardChanges();
2847 finish();
2848 }
2849
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002850 private void saveIfNeeded() {
2851 if (mAccount == null) {
2852 // We have not chosen an account yet so there's no way that we can save. This is ok,
2853 // though, since we are saving our state before AccountsActivity is activated. Thus, the
2854 // user has not interacted with us yet and there is no real state to save.
2855 return;
2856 }
2857
2858 if (shouldSave()) {
Mindy Pereira48e31b02012-05-30 13:12:24 -07002859 doSave(!mAddingAttachment /* show toast */);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002860 }
2861 }
2862
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002863 @Override
2864 public void onAttachmentDeleted() {
2865 mAttachmentsChanged = true;
mindyp40882432012-09-06 11:07:40 -07002866 // If we are showing any attachments, make sure we have an upper
2867 // divider.
2868 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002869 updateSaveUi();
2870 }
Mindy Pereira75f66632012-01-11 11:42:02 -08002871
mindyp40882432012-09-06 11:07:40 -07002872 @Override
2873 public void onAttachmentAdded() {
2874 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
2875 mAttachmentsView.focusLastAttachment();
2876 }
Mindy Pereira75f66632012-01-11 11:42:02 -08002877
2878 /**
2879 * This is called any time one of our text fields changes.
2880 */
Marc Blank0bbc8582012-04-23 15:07:57 -07002881 @Override
Mindy Pereira75f66632012-01-11 11:42:02 -08002882 public void afterTextChanged(Editable s) {
2883 mTextChanged = true;
2884 updateSaveUi();
2885 }
2886
2887 @Override
2888 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
2889 // Do nothing.
2890 }
2891
Marc Blank0bbc8582012-04-23 15:07:57 -07002892 @Override
Mindy Pereira75f66632012-01-11 11:42:02 -08002893 public void onTextChanged(CharSequence s, int start, int before, int count) {
2894 // Do nothing.
2895 }
2896
2897
2898 // There is a big difference between the text associated with an address changing
2899 // to add the display name or to format properly and a recipient being added or deleted.
2900 // Make sure we only notify of changes when a recipient has been added or deleted.
2901 private class RecipientTextWatcher implements TextWatcher {
2902 private HashMap<String, Integer> mContent = new HashMap<String, Integer>();
2903
2904 private RecipientEditTextView mView;
2905
2906 private TextWatcher mListener;
2907
2908 public RecipientTextWatcher(RecipientEditTextView view, TextWatcher listener) {
2909 mView = view;
2910 mListener = listener;
2911 }
2912
2913 @Override
2914 public void afterTextChanged(Editable s) {
2915 if (hasChanged()) {
2916 mListener.afterTextChanged(s);
2917 }
2918 }
2919
2920 private boolean hasChanged() {
2921 String[] currRecips = tokenizeRecips(getAddressesFromList(mView));
2922 int totalCount = currRecips.length;
2923 int totalPrevCount = 0;
2924 for (Entry<String, Integer> entry : mContent.entrySet()) {
2925 totalPrevCount += entry.getValue();
2926 }
2927 if (totalCount != totalPrevCount) {
2928 return true;
2929 }
2930
2931 for (String recip : currRecips) {
2932 if (!mContent.containsKey(recip)) {
2933 return true;
2934 } else {
2935 int count = mContent.get(recip) - 1;
2936 if (count < 0) {
2937 return true;
2938 } else {
2939 mContent.put(recip, count);
2940 }
2941 }
2942 }
2943 return false;
2944 }
2945
2946 private String[] tokenizeRecips(String[] recips) {
2947 // Tokenize them all and put them in the list.
2948 String[] recipAddresses = new String[recips.length];
2949 for (int i = 0; i < recips.length; i++) {
2950 recipAddresses[i] = Rfc822Tokenizer.tokenize(recips[i])[0].getAddress();
2951 }
2952 return recipAddresses;
2953 }
2954
2955 @Override
2956 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
2957 String[] recips = tokenizeRecips(getAddressesFromList(mView));
2958 for (String recip : recips) {
2959 if (!mContent.containsKey(recip)) {
2960 mContent.put(recip, 1);
2961 } else {
2962 mContent.put(recip, (mContent.get(recip)) + 1);
2963 }
2964 }
2965 }
2966
2967 @Override
2968 public void onTextChanged(CharSequence s, int start, int before, int count) {
2969 // Do nothing.
2970 }
2971 }
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002972
2973 public static void registerTestSendOrSaveCallback(SendOrSaveCallback testCallback) {
2974 if (sTestSendOrSaveCallback != null && testCallback != null) {
2975 throw new IllegalStateException("Attempting to register more than one test callback");
2976 }
2977 sTestSendOrSaveCallback = testCallback;
2978 }
Mindy Pereirabddd6f32012-06-20 12:10:03 -07002979
2980 @VisibleForTesting
2981 protected ArrayList<Attachment> getAttachments() {
2982 return mAttachmentsView.getAttachments();
2983 }
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07002984
2985 @Override
2986 public Loader<Cursor> onCreateLoader(int id, Bundle args) {
2987 switch (id) {
2988 case REFERENCE_MESSAGE_LOADER:
2989 return new CursorLoader(this, mRefMessageUri, UIProvider.MESSAGE_PROJECTION, null,
2990 null, null);
Mindy Pereirab199d172012-08-13 11:04:03 -07002991 case LOADER_ACCOUNT_CURSOR:
2992 return new CursorLoader(this, MailAppProvider.getAccountsUri(),
2993 UIProvider.ACCOUNTS_PROJECTION, null, null, null);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07002994 }
2995 return null;
2996 }
2997
2998 @Override
2999 public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Mindy Pereirab199d172012-08-13 11:04:03 -07003000 int id = loader.getId();
3001 switch (id) {
3002 case REFERENCE_MESSAGE_LOADER:
3003 if (data != null && data.moveToFirst()) {
3004 mRefMessage = new Message(data);
3005 // We set these based on EXTRA_TO.
Scott Kennedy8960f0a2012-11-07 15:35:50 -08003006 mRefMessage.setTo(null);
3007 mRefMessage.setFrom(null);
Mindy Pereirab199d172012-08-13 11:04:03 -07003008 Intent intent = getIntent();
3009 int action = intent.getIntExtra(EXTRA_ACTION, COMPOSE);
3010 initFromRefMessage(action, mAccount.name);
3011 finishSetup(action, intent, null, true);
3012 if (action != FORWARD) {
3013 String to = intent.getStringExtra(EXTRA_TO);
3014 if (!TextUtils.isEmpty(to)) {
3015 clearChangeListeners();
3016 mTo.append(to);
3017 initChangeListeners();
3018 }
3019 }
3020 } else {
3021 finish();
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003022 }
Mindy Pereirab199d172012-08-13 11:04:03 -07003023 break;
3024 case LOADER_ACCOUNT_CURSOR:
3025 if (data != null && data.moveToFirst()) {
3026 // there are accounts now!
3027 Account account;
Paul Westbrookfaa742f2012-11-01 09:50:16 -07003028 final ArrayList<Account> accounts = new ArrayList<Account>();
3029 final ArrayList<Account> initializedAccounts = new ArrayList<Account>();
Mindy Pereirab199d172012-08-13 11:04:03 -07003030 do {
3031 account = new Account(data);
Paul Westbrookdfa1dec2012-09-26 16:27:28 -07003032 if (account.isAccountReady()) {
Mindy Pereirab199d172012-08-13 11:04:03 -07003033 initializedAccounts.add(account);
3034 }
3035 accounts.add(account);
3036 } while (data.moveToNext());
3037 if (initializedAccounts.size() > 0) {
3038 findViewById(R.id.wait).setVisibility(View.GONE);
3039 getLoaderManager().destroyLoader(LOADER_ACCOUNT_CURSOR);
3040 findViewById(R.id.compose).setVisibility(View.VISIBLE);
Paul Westbrookfaa742f2012-11-01 09:50:16 -07003041 mAccounts = initializedAccounts.toArray(
3042 new Account[initializedAccounts.size()]);
3043
Mindy Pereirab199d172012-08-13 11:04:03 -07003044 finishCreate();
3045 invalidateOptionsMenu();
3046 } else {
3047 // Show "waiting"
3048 account = accounts.size() > 0 ? accounts.get(0) : null;
3049 showWaitFragment(account);
3050 }
3051 }
3052 break;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003053 }
3054 }
3055
Mindy Pereirab199d172012-08-13 11:04:03 -07003056 private void showWaitFragment(Account account) {
3057 WaitFragment fragment = getWaitFragment();
3058 if (fragment != null) {
3059 fragment.updateAccount(account);
3060 } else {
3061 findViewById(R.id.wait).setVisibility(View.VISIBLE);
3062 replaceFragment(WaitFragment.newInstance(account, true),
3063 FragmentTransaction.TRANSIT_FRAGMENT_OPEN, TAG_WAIT);
3064 }
3065 }
3066
3067 private WaitFragment getWaitFragment() {
3068 return (WaitFragment) getFragmentManager().findFragmentByTag(TAG_WAIT);
3069 }
3070
3071 private int replaceFragment(Fragment fragment, int transition, String tag) {
3072 FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
3073 fragmentTransaction.addToBackStack(null);
3074 fragmentTransaction.setTransition(transition);
3075 fragmentTransaction.replace(R.id.wait, fragment, tag);
3076 final int transactionId = fragmentTransaction.commitAllowingStateLoss();
3077 return transactionId;
3078 }
3079
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07003080 @Override
3081 public void onLoaderReset(Loader<Cursor> arg0) {
3082 // Do nothing.
3083 }
Andy Huang1f8f4dd2012-10-25 21:35:35 -07003084}