blob: 5b1834991d8873790431d314bcac3db43b885b80 [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 Pereira6349a042012-01-04 11:25:01 -080025import android.content.ContentResolver;
Mindy Pereira82cc5662012-01-09 17:29:30 -080026import android.content.ContentValues;
Mindy Pereira6349a042012-01-04 11:25:01 -080027import android.content.Context;
Mindy Pereira82cc5662012-01-09 17:29:30 -080028import android.content.DialogInterface;
Mindy Pereira6349a042012-01-04 11:25:01 -080029import android.content.Intent;
Mindy Pereira82cc5662012-01-09 17:29:30 -080030import android.content.pm.ActivityInfo;
Mindy Pereira7ed1c112012-01-18 10:59:25 -080031import android.database.Cursor;
Mindy Pereira6349a042012-01-04 11:25:01 -080032import android.net.Uri;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080033import android.os.Bundle;
Mindy Pereira82cc5662012-01-09 17:29:30 -080034import android.os.Handler;
35import android.os.HandlerThread;
Paul Westbrookf97588b2012-03-20 11:11:37 -070036import android.os.Parcelable;
Mindy Pereira82cc5662012-01-09 17:29:30 -080037import android.provider.BaseColumns;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080038import android.text.Editable;
Mindy Pereira82cc5662012-01-09 17:29:30 -080039import android.text.Html;
40import android.text.Spanned;
Paul Westbrookc1827622012-01-06 11:27:12 -080041import android.text.TextUtils;
Mindy Pereira82cc5662012-01-09 17:29:30 -080042import android.text.TextWatcher;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080043import android.text.util.Rfc822Token;
Mindy Pereirac17d0732011-12-29 10:46:19 -080044import android.text.util.Rfc822Tokenizer;
Mindy Pereira326c6602012-01-04 15:32:42 -080045import android.view.LayoutInflater;
Mindy Pereirab47f3e22011-12-13 14:25:04 -080046import android.view.Menu;
47import android.view.MenuInflater;
48import android.view.MenuItem;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080049import android.view.View;
50import android.view.View.OnClickListener;
Andy Huang5c5fd572012-04-08 18:19:29 -070051import android.view.ViewGroup;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -080052import android.view.inputmethod.BaseInputConnection;
Mindy Pereira326c6602012-01-04 15:32:42 -080053import android.widget.ArrayAdapter;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080054import android.widget.Button;
Mindy Pereira433b1982012-04-03 11:53:07 -070055import android.widget.EditText;
Mindy Pereira1f936682012-03-02 11:30:33 -080056import android.widget.ImageView;
Mindy Pereira6349a042012-01-04 11:25:01 -080057import android.widget.TextView;
Mindy Pereira013194c2012-01-06 15:09:33 -080058import android.widget.Toast;
Mindy Pereira7b56a612011-12-14 12:32:28 -080059
Mindy Pereirac17d0732011-12-29 10:46:19 -080060import com.android.common.Rfc822Validator;
Andy Huang5c5fd572012-04-08 18:19:29 -070061import com.android.ex.chips.RecipientEditTextView;
62import com.android.mail.R;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -080063import com.android.mail.compose.AttachmentsView.AttachmentDeletedListener;
Mindy Pereira9932dee2012-01-10 16:09:50 -080064import com.android.mail.compose.AttachmentsView.AttachmentFailureException;
Mindy Pereira5a85e2b2012-01-11 09:53:32 -080065import com.android.mail.compose.FromAddressSpinner.OnAccountChangedListener;
Andy Huang30e2c242012-01-06 18:14:30 -080066import com.android.mail.compose.QuotedTextView.RespondInlineListener;
Mindy Pereira33fe9082012-01-09 16:24:30 -080067import com.android.mail.providers.Account;
Andy Huang30e2c242012-01-06 18:14:30 -080068import com.android.mail.providers.Address;
69import com.android.mail.providers.Attachment;
Mindy Pereira3ce64e72012-01-13 14:29:45 -080070import com.android.mail.providers.Message;
Mindy Pereira82cc5662012-01-09 17:29:30 -080071import com.android.mail.providers.MessageModification;
Mindy Pereira92551d02012-04-05 11:31:12 -070072import com.android.mail.providers.ReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -080073import com.android.mail.providers.Settings;
Andy Huang30e2c242012-01-06 18:14:30 -080074import com.android.mail.providers.UIProvider;
Mindy Pereira3ca5bad2012-04-16 11:02:42 -070075import com.android.mail.providers.UIProvider.AccountCapabilities;
Mindy Pereira12575862012-03-21 16:30:54 -070076import com.android.mail.providers.UIProvider.DraftType;
Paul Westbrook92227f62012-03-20 10:32:51 -070077import com.android.mail.utils.AccountUtils;
Andy Huang30e2c242012-01-06 18:14:30 -080078import com.android.mail.utils.LogUtils;
Andy Huang30e2c242012-01-06 18:14:30 -080079import com.android.mail.utils.Utils;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080080import com.google.common.annotations.VisibleForTesting;
Mindy Pereira82cc5662012-01-09 17:29:30 -080081import com.google.common.collect.Lists;
Mindy Pereira4a27ea92012-01-05 15:55:25 -080082import com.google.common.collect.Sets;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080083
Mindy Pereira62de1b12012-04-06 12:17:56 -070084import org.json.JSONException;
85
Mindy Pereira8eca57a2012-03-20 16:42:34 -070086import java.io.UnsupportedEncodingException;
87import java.net.URLDecoder;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080088import java.util.ArrayList;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -070089import java.util.Arrays;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080090import java.util.Collection;
Mindy Pereira75f66632012-01-11 11:42:02 -080091import java.util.HashMap;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080092import java.util.HashSet;
93import java.util.List;
Paul Westbrook1c078cf2012-03-20 16:18:51 -070094import java.util.Map.Entry;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -070095import java.util.Set;
Mindy Pereira82cc5662012-01-09 17:29:30 -080096import java.util.concurrent.ConcurrentHashMap;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080097
98public class ComposeActivity extends Activity implements OnClickListener, OnNavigationListener,
Mindy Pereira5a85e2b2012-01-11 09:53:32 -080099 RespondInlineListener, DialogInterface.OnClickListener, TextWatcher,
Paul Westbrookb1f573c2012-04-06 11:38:28 -0700100 AttachmentDeletedListener, OnAccountChangedListener {
Mindy Pereira6349a042012-01-04 11:25:01 -0800101 // Identifiers for which type of composition this is
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700102 static final int COMPOSE = -1;
Mindy Pereira6349a042012-01-04 11:25:01 -0800103 static final int REPLY = 0;
104 static final int REPLY_ALL = 1;
105 static final int FORWARD = 2;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700106 static final int EDIT_DRAFT = 3;
Mindy Pereira6349a042012-01-04 11:25:01 -0800107
108 // Integer extra holding one of the above compose action
109 private static final String EXTRA_ACTION = "action";
110
Mindy Pereiraa34c9a02012-04-17 14:10:53 -0700111 private static final String EXTRA_SHOW_CC_BCC = "showCcBcc";
112
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700113 private static final String UTF8_ENCODING_NAME = "UTF-8";
114
115 private static final String MAIL_TO = "mailto";
116
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700117 private static final String EXTRA_SUBJECT = "subject";
118
119 private static final String EXTRA_BODY = "body";
120
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700121 private static final String EXTRA_FROM_ACCOUNT_STRING = "fromAccountString";
122
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700123 // Extra that we can get passed from other activities
124 private static final String EXTRA_TO = "to";
125 private static final String EXTRA_CC = "cc";
126 private static final String EXTRA_BCC = "bcc";
127
128 // List of all the fields
129 static final String[] ALL_EXTRAS = { EXTRA_SUBJECT, EXTRA_BODY, EXTRA_TO, EXTRA_CC, EXTRA_BCC };
130
Mindy Pereira82cc5662012-01-09 17:29:30 -0800131 private static SendOrSaveCallback sTestSendOrSaveCallback = null;
132 // Map containing information about requests to create new messages, and the id of the
133 // messages that were the result of those requests.
134 //
135 // This map is used when the activity that initiated the save a of a new message, is killed
136 // before the save has completed (and when we know the id of the newly created message). When
137 // a save is completed, the service that is running in the background, will update the map
138 //
139 // When a new ComposeActivity instance is created, it will attempt to use the information in
140 // the previously instantiated map. If ComposeActivity.onCreate() is called, with a bundle
141 // (restoring data from a previous instance), and the map hasn't been created, we will attempt
142 // to populate the map with data stored in shared preferences.
143 private static ConcurrentHashMap<Integer, Long> sRequestMessageIdMap = null;
144 // Key used to store the above map
145 private static final String CACHED_MESSAGE_REQUEST_IDS_KEY = "cache-message-request-ids";
Mindy Pereira6349a042012-01-04 11:25:01 -0800146 /**
147 * Notifies the {@code Activity} that the caller is an Email
148 * {@code Activity}, so that the back behavior may be modified accordingly.
149 *
150 * @see #onAppUpPressed
151 */
152 private static final String EXTRA_FROM_EMAIL_TASK = "fromemail";
153
Paul Westbrookf97588b2012-03-20 11:11:37 -0700154 static final String EXTRA_ATTACHMENTS = "attachments";
155
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800156 // If this is a reply/forward then this extra will hold the original message
157 private static final String EXTRA_IN_REFERENCE_TO_MESSAGE = "in-reference-to-message";
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700158 // If this is an action to edit an existing draft messagge, this extra will hold the
159 // draft message
160 private static final String ORIGINAL_DRAFT_MESSAGE = "original-draft-message";
Mindy Pereira4a27ea92012-01-05 15:55:25 -0800161 private static final String END_TOKEN = ", ";
Mindy Pereira013194c2012-01-06 15:09:33 -0800162 private static final String LOG_TAG = new LogUtils().getLogTag();
163 // Request numbers for activities we start
164 private static final int RESULT_PICK_ATTACHMENT = 1;
165 private static final int RESULT_CREATE_ACCOUNT = 2;
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700166 // TODO(mindyp) set mime-type for auto send?
167 private static final String AUTO_SEND_ACTION = "com.android.mail.action.AUTO_SEND";
168
169 // Max size for attachments (5 megs). Will be overridden by account settings if found.
170 // TODO(mindyp): read this from account settings?
171 private static final int DEFAULT_MAX_ATTACHMENT_SIZE = 25 * 1024 * 1024;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700172 private static final String EXTRA_SELECTED_REPLY_FROM_ACCOUNT = "replyFromAccount";
173 private static final String EXTRA_REQUEST_ID = "requestId";
174 private static final String EXTRA_FOCUS_SELECTION_START = "focusSelectionStart";
175 private static final String EXTRA_FOCUS_SELECTION_END = null;
176 private static final String EXTRA_MESSAGE = "extraMessage";
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800177
Mindy Pereira82cc5662012-01-09 17:29:30 -0800178 /**
179 * A single thread for running tasks in the background.
180 */
181 private Handler mSendSaveTaskHandler = null;
Mindy Pereirac17d0732011-12-29 10:46:19 -0800182 private RecipientEditTextView mTo;
183 private RecipientEditTextView mCc;
184 private RecipientEditTextView mBcc;
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800185 private Button mCcBccButton;
186 private CcBccView mCcBccView;
Mindy Pereira7b56a612011-12-14 12:32:28 -0800187 private AttachmentsView mAttachmentsView;
Mindy Pereira33fe9082012-01-09 16:24:30 -0800188 private Account mAccount;
Mindy Pereira92551d02012-04-05 11:31:12 -0700189 private ReplyFromAccount mReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -0800190 private Settings mCachedSettings;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800191 private Rfc822Validator mValidator;
Mindy Pereira6349a042012-01-04 11:25:01 -0800192 private TextView mSubject;
193
Mindy Pereira326c6602012-01-04 15:32:42 -0800194 private ComposeModeAdapter mComposeModeAdapter;
195 private int mComposeMode = -1;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800196 private boolean mForward;
197 private String mRecipient;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800198 private QuotedTextView mQuotedTextView;
Mindy Pereira433b1982012-04-03 11:53:07 -0700199 private EditText mBodyView;
Mindy Pereira1a95a572012-01-05 12:21:29 -0800200 private View mFromStatic;
Mindy Pereira2eb17322012-03-07 10:07:34 -0800201 private TextView mFromStaticText;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800202 private View mFromSpinnerWrapper;
Mindy Pereira5a85e2b2012-01-11 09:53:32 -0800203 private FromAddressSpinner mFromSpinner;
Mindy Pereira013194c2012-01-06 15:09:33 -0800204 private boolean mAddingAttachment;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800205 private boolean mAttachmentsChanged;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800206 private boolean mTextChanged;
207 private boolean mReplyFromChanged;
208 private MenuItem mSave;
209 private MenuItem mSend;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800210 private AlertDialog mRecipientErrorDialog;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800211 private AlertDialog mSendConfirmDialog;
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800212 private Message mRefMessage;
Mindy Pereira7ed1c112012-01-18 10:59:25 -0800213 private long mDraftId = UIProvider.INVALID_MESSAGE_ID;
214 private Message mDraft;
215 private Object mDraftLock = new Object();
Mindy Pereira1f936682012-03-02 11:30:33 -0800216 private ImageView mAttachmentsButton;
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800217
Mindy Pereira326c6602012-01-04 15:32:42 -0800218 /**
219 * Can be called from a non-UI thread.
220 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800221 public static void editDraft(Context launcher, Account account, Message message) {
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700222 launch(launcher, account, message, EDIT_DRAFT);
Mindy Pereira326c6602012-01-04 15:32:42 -0800223 }
224
Mindy Pereira6349a042012-01-04 11:25:01 -0800225 /**
226 * Can be called from a non-UI thread.
227 */
Mindy Pereira33fe9082012-01-09 16:24:30 -0800228 public static void compose(Context launcher, Account account) {
Mindy Pereira6349a042012-01-04 11:25:01 -0800229 launch(launcher, account, null, COMPOSE);
230 }
231
232 /**
233 * Can be called from a non-UI thread.
234 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800235 public static void reply(Context launcher, Account account, Message message) {
236 launch(launcher, account, message, REPLY);
Mindy Pereira6349a042012-01-04 11:25:01 -0800237 }
238
239 /**
240 * Can be called from a non-UI thread.
241 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800242 public static void replyAll(Context launcher, Account account, Message message) {
243 launch(launcher, account, message, REPLY_ALL);
Mindy Pereira6349a042012-01-04 11:25:01 -0800244 }
245
246 /**
247 * Can be called from a non-UI thread.
248 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800249 public static void forward(Context launcher, Account account, Message message) {
250 launch(launcher, account, message, FORWARD);
Mindy Pereira6349a042012-01-04 11:25:01 -0800251 }
252
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800253 private static void launch(Context launcher, Account account, Message message, int action) {
Mindy Pereira6349a042012-01-04 11:25:01 -0800254 Intent intent = new Intent(launcher, ComposeActivity.class);
255 intent.putExtra(EXTRA_FROM_EMAIL_TASK, true);
256 intent.putExtra(EXTRA_ACTION, action);
257 intent.putExtra(Utils.EXTRA_ACCOUNT, account);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700258 if (action == EDIT_DRAFT) {
259 intent.putExtra(ORIGINAL_DRAFT_MESSAGE, message);
260 } else {
261 intent.putExtra(EXTRA_IN_REFERENCE_TO_MESSAGE, message);
262 }
Mindy Pereira6349a042012-01-04 11:25:01 -0800263 launcher.startActivity(intent);
264 }
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800265
266 @Override
267 public void onCreate(Bundle savedInstanceState) {
268 super.onCreate(savedInstanceState);
Mindy Pereira3528d362012-01-05 14:39:44 -0800269 setContentView(R.layout.compose);
270 findViews();
Mindy Pereira818143e2012-01-11 13:59:49 -0800271 Intent intent = getIntent();
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700272 Account account;
273 Message message;
274 int action;
275 if (savedInstanceState != null && savedInstanceState.containsKey(EXTRA_MESSAGE)) {
276 action = savedInstanceState.getInt(EXTRA_ACTION, COMPOSE);
277 account = savedInstanceState.getParcelable(Utils.EXTRA_ACCOUNT);
278 message = (Message) savedInstanceState.getParcelable(EXTRA_MESSAGE);
279 mRefMessage = (Message) savedInstanceState.getParcelable(EXTRA_IN_REFERENCE_TO_MESSAGE);
280 } else {
281 account = (Account)intent.getParcelableExtra(Utils.EXTRA_ACCOUNT);
282 action = intent.getIntExtra(EXTRA_ACTION, COMPOSE);
283 // Initialize the message from the message in the intent
284 message = (Message) intent.getParcelableExtra(ORIGINAL_DRAFT_MESSAGE);
285 mRefMessage = (Message) intent.getParcelableExtra(EXTRA_IN_REFERENCE_TO_MESSAGE);
286 }
Paul Westbrook92227f62012-03-20 10:32:51 -0700287 if (account == null) {
288 final Account[] syncingAccounts = AccountUtils.getSyncingAccounts(this);
289 if (syncingAccounts.length > 0) {
290 account = syncingAccounts[0];
291 }
292 }
293
294 setAccount(account);
Mindy Pereira818143e2012-01-11 13:59:49 -0800295 if (mAccount == null) {
296 return;
297 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700298
299 if (message != null && action != EDIT_DRAFT) {
300 initFromDraftMessage(message);
301 initQuotedTextFromRefMessage(mRefMessage, action);
Mindy Pereiraa34c9a02012-04-17 14:10:53 -0700302 showCcBcc(savedInstanceState);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700303 } else if (action == EDIT_DRAFT) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700304 initFromDraftMessage(message);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700305 // Update the action to the draft type of the previous draft
306 switch (message.draftType) {
307 case UIProvider.DraftType.REPLY:
308 action = REPLY;
309 break;
310 case UIProvider.DraftType.REPLY_ALL:
311 action = REPLY_ALL;
312 break;
313 case UIProvider.DraftType.FORWARD:
314 action = FORWARD;
315 break;
316 case UIProvider.DraftType.COMPOSE:
317 default:
318 action = COMPOSE;
319 break;
320 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700321 initQuotedTextFromRefMessage(mRefMessage, action);
322 } else if ((action == REPLY || action == REPLY_ALL || action == FORWARD)) {
323 if (mRefMessage != null) {
324 initFromRefMessage(action, mAccount.name);
325 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700326 } else {
327 initFromExtras(intent);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700328 }
329
330 if (action == COMPOSE) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800331 mQuotedTextView.setVisibility(View.GONE);
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800332 }
Mindy Pereira818143e2012-01-11 13:59:49 -0800333 initRecipients();
Paul Westbrookf97588b2012-03-20 11:11:37 -0700334 initAttachmentsFromIntent(intent);
Mindy Pereira1a95a572012-01-05 12:21:29 -0800335 initActionBar(action);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700336 initFromSpinner(savedInstanceState != null ? savedInstanceState : intent.getExtras(),
337 action);
Mindy Pereira75f66632012-01-11 11:42:02 -0800338 initChangeListeners();
Mindy Pereira433b1982012-04-03 11:53:07 -0700339 setFocus(action);
340 }
341
342 private void setFocus(int action) {
343 if (action == EDIT_DRAFT) {
344 int type = mDraft.draftType;
345 switch (type) {
346 case UIProvider.DraftType.COMPOSE:
347 case UIProvider.DraftType.FORWARD:
348 action = COMPOSE;
349 break;
350 case UIProvider.DraftType.REPLY:
351 case UIProvider.DraftType.REPLY_ALL:
352 default:
353 action = REPLY;
354 break;
355 }
356 }
357 switch (action) {
358 case FORWARD:
359 case COMPOSE:
360 mTo.requestFocus();
361 break;
362 case REPLY:
363 case REPLY_ALL:
364 default:
365 focusBody();
366 break;
367 }
368 }
369
370 /**
371 * Focus the body of the message.
372 */
373 public void focusBody() {
374 mBodyView.requestFocus();
375 int length = mBodyView.getText().length();
376
377 int signatureStartPos = getSignatureStartPosition(
378 mSignature, mBodyView.getText().toString());
379 if (signatureStartPos > -1) {
380 // In case the user deleted the newlines...
381 mBodyView.setSelection(signatureStartPos);
382 } else if (length > 0) {
383 // Move cursor to the end.
384 mBodyView.setSelection(length);
385 }
Mindy Pereira1a95a572012-01-05 12:21:29 -0800386 }
387
388 @Override
389 protected void onResume() {
390 super.onResume();
391 // Update the from spinner as other accounts
392 // may now be available.
Mindy Pereira818143e2012-01-11 13:59:49 -0800393 if (mFromSpinner != null && mAccount != null) {
Mindy Pereira62de1b12012-04-06 12:17:56 -0700394 mFromSpinner.asyncInitFromSpinner(mComposeMode, mAccount);
Mindy Pereira818143e2012-01-11 13:59:49 -0800395 }
Mindy Pereira1a95a572012-01-05 12:21:29 -0800396 }
397
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800398 @Override
399 protected void onPause() {
400 super.onPause();
401
402 if (mSendConfirmDialog != null) {
403 mSendConfirmDialog.dismiss();
404 }
405 if (mRecipientErrorDialog != null) {
406 mRecipientErrorDialog.dismiss();
407 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800408 saveIfNeeded();
409 }
410
411 @Override
412 protected final void onActivityResult(int request, int result, Intent data) {
413 mAddingAttachment = false;
414
415 if (result == RESULT_OK && request == RESULT_PICK_ATTACHMENT) {
416 addAttachmentAndUpdateView(data);
417 }
418 }
419
420 @Override
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700421 public final void onRestoreInstanceState(Bundle savedInstanceState) {
422 super.onRestoreInstanceState(savedInstanceState);
423 if (savedInstanceState != null) {
424 if (savedInstanceState.containsKey(EXTRA_FOCUS_SELECTION_START)) {
425 int selectionStart = savedInstanceState.getInt(EXTRA_FOCUS_SELECTION_START);
426 int selectionEnd = savedInstanceState.getInt(EXTRA_FOCUS_SELECTION_END);
427 // There should be a focus and it should be an EditText since we
428 // only save these extras if these conditions are true.
429 EditText focusEditText = (EditText) getCurrentFocus();
430 final int length = focusEditText.getText().length();
431 if (selectionStart < length && selectionEnd < length) {
432 focusEditText.setSelection(selectionStart, selectionEnd);
433 }
434 }
435 }
436 }
437
438 @Override
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800439 public final void onSaveInstanceState(Bundle state) {
440 super.onSaveInstanceState(state);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700441 // The framework is happy to save and restore the selection but only if it also saves and
442 // restores the contents of the edit text. That's a lot of text to put in a bundle so we do
443 // this manually.
444 View focus = getCurrentFocus();
445 if (focus != null && focus instanceof EditText) {
446 EditText focusEditText = (EditText) focus;
447 state.putInt(EXTRA_FOCUS_SELECTION_START, focusEditText.getSelectionStart());
448 state.putInt(EXTRA_FOCUS_SELECTION_END, focusEditText.getSelectionEnd());
449 }
450 ReplyFromAccount selectedReplyFromAccount = mFromSpinner.getReplyFromAccounts().get(
451 mFromSpinner.getSelectedItemPosition());
452 if (selectedReplyFromAccount != null) {
453 state.putString(EXTRA_SELECTED_REPLY_FROM_ACCOUNT, selectedReplyFromAccount.serialize()
454 .toString());
455 state.putParcelable(Utils.EXTRA_ACCOUNT, selectedReplyFromAccount.account);
456 } else {
457 state.putParcelable(Utils.EXTRA_ACCOUNT, mAccount);
458 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800459
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700460 if (mDraftId == UIProvider.INVALID_MESSAGE_ID && mRequestId !=0) {
461 // We don't have a draft id, and we have a request id,
462 // save the request id.
463 state.putInt(EXTRA_REQUEST_ID, mRequestId);
464 }
465
466 // We want to restore the current mode after a pause
467 // or rotation.
468 int mode = getMode();
469 state.putInt(EXTRA_ACTION, mode);
470
471 Message message = createMessage(selectedReplyFromAccount, mode);
472 state.putParcelable(EXTRA_MESSAGE, message);
473
474 if (mRefMessage != null) {
475 state.putParcelable(EXTRA_IN_REFERENCE_TO_MESSAGE, mRefMessage);
476 }
Mindy Pereiraa34c9a02012-04-17 14:10:53 -0700477 state.putBoolean(EXTRA_SHOW_CC_BCC, mCcBccView.isVisible());
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700478 }
479
480 private int getMode() {
481 int mode = ComposeActivity.COMPOSE;
482 ActionBar actionBar = getActionBar();
483 if (actionBar.getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST) {
484 mode = actionBar.getSelectedNavigationIndex();
485 }
486 return mode;
487 }
488
489 private Message createMessage(ReplyFromAccount selectedReplyFromAccount, int mode) {
490 Message message = new Message();
491 message.id = UIProvider.INVALID_MESSAGE_ID;
492 message.serverId =UIProvider.INVALID_MESSAGE_ID;
493 message.uri = null;
494 message.conversationUri = null;
495 message.subject = mSubject.getText().toString();
496 message.snippet = null;
497 message.from = selectedReplyFromAccount.name;
498 message.to = mTo.getText().toString();
Mindy Pereira4b1377e2012-04-18 15:08:05 -0700499 message.cc = mCc.getText().toString();
500 message.bcc = mBcc.getText().toString();
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700501 message.replyTo = null;
502 message.dateReceivedMs = 0;
503 String htmlBody = Html.toHtml(mBodyView.getText());
504 StringBuilder fullBody = new StringBuilder(htmlBody);
505 message.bodyHtml = fullBody.toString();
506 message.bodyText = mBodyView.getText().toString();
507 message.embedsExternalResources = false;
508 message.refMessageId = mRefMessage != null ? mRefMessage.uri.toString() : null;
509 message.draftType = mode;
510 message.appendRefMessageContent = mQuotedTextView.getQuotedTextIfIncluded() != null;
511 ArrayList<Attachment> attachments = mAttachmentsView.getAttachments();
512 message.hasAttachments = attachments != null && attachments.size() > 0;
513 message.attachmentListUri = null;
514 message.messageFlags = 0;
515 message.saveUri = null;
516 message.sendUri = null;
517 message.alwaysShowImages = false;
518 message.attachmentsJson = Attachment.toJSONArray(attachments);
519 CharSequence quotedText = mQuotedTextView.getQuotedText();
520 message.quotedTextOffset = !TextUtils.isEmpty(quotedText) ? QuotedTextView
521 .getQuotedTextOffset(quotedText.toString()) : -1;
522 message.accountUri = null;
523 return message;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800524 }
525
Mindy Pereira818143e2012-01-11 13:59:49 -0800526 @VisibleForTesting
527 void setAccount(Account account) {
Mindy Pereirabb5217e2012-04-17 11:08:29 -0700528 if (account == null) {
529 return;
530 }
Mindy Pereira23e9fde2012-03-20 15:08:24 -0700531 if (!account.equals(mAccount)) {
532 mAccount = account;
Paul Westbrookb1f573c2012-04-06 11:38:28 -0700533 mCachedSettings = mAccount.settings;
534 appendSignature();
Mindy Pereira23e9fde2012-03-20 15:08:24 -0700535 }
Mindy Pereira818143e2012-01-11 13:59:49 -0800536 }
537
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700538 private void initFromSpinner(Bundle bundle, int action) {
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700539 String accountString = null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700540 if (action == EDIT_DRAFT && mDraft.draftType == UIProvider.DraftType.COMPOSE) {
Mindy Pereira62de1b12012-04-06 12:17:56 -0700541 action = COMPOSE;
542 }
543 mFromSpinner.asyncInitFromSpinner(action, mAccount);
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700544 if (bundle != null) {
545 if (bundle.containsKey(EXTRA_SELECTED_REPLY_FROM_ACCOUNT)) {
546 mReplyFromAccount = ReplyFromAccount.deserialize(mAccount,
547 bundle.getString(EXTRA_SELECTED_REPLY_FROM_ACCOUNT));
548 } else if (bundle.containsKey(EXTRA_FROM_ACCOUNT_STRING)) {
549 accountString = bundle.getString(EXTRA_FROM_ACCOUNT_STRING);
550 mReplyFromAccount = mFromSpinner.getMatchingReplyFromAccount(accountString);
551 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700552 }
553 if (mReplyFromAccount == null) {
554 if (mDraft != null) {
555 mReplyFromAccount = getReplyFromAccountFromDraft(mAccount, mDraft);
556 } else if (mRefMessage != null) {
557 mReplyFromAccount = getReplyFromAccountForReply(mAccount, mRefMessage);
558 }
Mindy Pereira62de1b12012-04-06 12:17:56 -0700559 }
560 if (mReplyFromAccount == null) {
561 mReplyFromAccount = new ReplyFromAccount(mAccount, mAccount.uri, mAccount.name,
562 mAccount.name, true, false);
563 }
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700564
Mindy Pereira62de1b12012-04-06 12:17:56 -0700565 mFromSpinner.setCurrentAccount(mReplyFromAccount);
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700566
Mindy Pereira62de1b12012-04-06 12:17:56 -0700567 if (mFromSpinner.getCount() > 1) {
Mindy Pereiraa83e7082012-03-30 08:53:11 -0700568 // If there is only 1 account, just show that account.
569 // Otherwise, give the user the ability to choose which account to
Mindy Pereira62de1b12012-04-06 12:17:56 -0700570 // send mail from / save drafts to.
571 mFromStatic.setVisibility(View.GONE);
Mindy Pereiraa83e7082012-03-30 08:53:11 -0700572 mFromStaticText.setText(mAccount.name);
Mindy Pereira62de1b12012-04-06 12:17:56 -0700573 mFromSpinnerWrapper.setVisibility(View.VISIBLE);
Mindy Pereiraa83e7082012-03-30 08:53:11 -0700574 } else {
575 mFromStatic.setVisibility(View.VISIBLE);
576 mFromStaticText.setText(mAccount.name);
577 mFromSpinnerWrapper.setVisibility(View.GONE);
Mindy Pereiraa83e7082012-03-30 08:53:11 -0700578 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800579 }
580
Mindy Pereira62de1b12012-04-06 12:17:56 -0700581 private ReplyFromAccount getReplyFromAccountForReply(Account account, Message refMessage) {
582 if (refMessage.accountUri != null) {
583 // This must be from combined inbox.
584 List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
585 for (ReplyFromAccount from : replyFromAccounts) {
586 if (from.account.uri.equals(refMessage.accountUri)) {
587 return from;
588 }
589 }
590 return null;
591 } else {
592 return getReplyFromAccount(account, refMessage);
593 }
594 }
595
596 /**
597 * Given an account and which email address the message was sent to,
598 * return who the message should be sent from.
599 * @param account Account in which the message arrived.
600 * @param sentTo Email address to which the message was sent.
601 * @return the address from which to reply.
602 */
603 public ReplyFromAccount getReplyFromAccount(Account account, Message refMessage) {
604 // First see if we are supposed to use the default address or
605 // the address it was sentTo.
606 if (false) { //mCachedSettings.forceReplyFromDefault) {
607 return getDefaultReplyFromAccount(account);
608 } else {
609 // If we aren't explicityly told which account to look for, look at
610 // all the message recipients and find one that matches
611 // a custom from or account.
612 List<String> allRecipients = new ArrayList<String>();
613 allRecipients.addAll(Arrays.asList(Utils.splitCommaSeparatedString(refMessage.to)));
614 allRecipients.addAll(Arrays.asList(Utils.splitCommaSeparatedString(refMessage.cc)));
615 return getMatchingRecipient(account, allRecipients);
616 }
617 }
618
619 /**
620 * Compare all the recipients of an email to the current account and all
621 * custom addresses associated with that account. Return the match if there
622 * is one, or the default account if there isn't.
623 */
624 protected ReplyFromAccount getMatchingRecipient(Account account, List<String> sentTo) {
625 // Tokenize the list and place in a hashmap.
626 ReplyFromAccount matchingReplyFrom = null;
627 Rfc822Token[] tokens;
628 HashSet<String> recipientsMap = new HashSet<String>();
629 for (String address : sentTo) {
630 tokens = Rfc822Tokenizer.tokenize(address);
631 for (int i = 0; i < tokens.length; i++) {
632 recipientsMap.add(tokens[i].getAddress());
633 }
634 }
635
636 int matchingAddressCount = 0;
637 List<ReplyFromAccount> customFroms;
638 try {
639 customFroms = FromAddressSpinner.getAccountSpecificFroms(account);
640 if (customFroms != null) {
641 for (ReplyFromAccount entry : customFroms) {
642 if (recipientsMap.contains(entry.address)) {
643 matchingReplyFrom = entry;
644 matchingAddressCount++;
645 }
646 }
647 }
648 } catch (JSONException e) {
649 LogUtils.wtf(LOG_TAG, "Exception parsing from addresses for account %s",
650 account.name);
651 }
652 if (matchingAddressCount > 1) {
653 matchingReplyFrom = getDefaultReplyFromAccount(account);
654 }
655 return matchingReplyFrom;
656 }
657
658 private ReplyFromAccount getDefaultReplyFromAccount(Account account) {
659 List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
660 for (ReplyFromAccount from : replyFromAccounts) {
661 if (from.isDefault) {
662 return from;
663 }
664 }
665 return new ReplyFromAccount(account, account.uri, account.name, account.name, true, false);
666 }
667
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700668 private ReplyFromAccount getReplyFromAccountFromDraft(Account account, Message msg) {
669 String sender = msg.from;
Mindy Pereira62de1b12012-04-06 12:17:56 -0700670 ReplyFromAccount replyFromAccount = null;
671 List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
672 if (TextUtils.equals(account.name, sender)) {
673 replyFromAccount = new ReplyFromAccount(mAccount, mAccount.uri, mAccount.name,
674 mAccount.name, true, false);
675 } else {
676 for (ReplyFromAccount fromAccount : replyFromAccounts) {
677 if (TextUtils.equals(fromAccount.name, sender)) {
678 replyFromAccount = fromAccount;
679 break;
680 }
681 }
682 }
683 return replyFromAccount;
684 }
685
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800686 private void findViews() {
Mindy Pereiraa26b54e2012-01-06 12:54:33 -0800687 mCcBccButton = (Button) findViewById(R.id.add_cc_bcc);
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800688 if (mCcBccButton != null) {
689 mCcBccButton.setOnClickListener(this);
690 }
691 mCcBccView = (CcBccView) findViewById(R.id.cc_bcc_wrapper);
Mindy Pereira7b56a612011-12-14 12:32:28 -0800692 mAttachmentsView = (AttachmentsView)findViewById(R.id.attachments);
Mindy Pereira1f936682012-03-02 11:30:33 -0800693 mAttachmentsButton = (ImageView) findViewById(R.id.add_attachment);
694 if (mAttachmentsButton != null) {
695 mAttachmentsButton.setOnClickListener(this);
696 }
Mindy Pereira818143e2012-01-11 13:59:49 -0800697 mTo = (RecipientEditTextView) findViewById(R.id.to);
698 mCc = (RecipientEditTextView) findViewById(R.id.cc);
699 mBcc = (RecipientEditTextView) findViewById(R.id.bcc);
Mindy Pereira82cc5662012-01-09 17:29:30 -0800700 // TODO: add special chips text change watchers before adding
701 // this as a text changed watcher to the to, cc, bcc fields.
Mindy Pereira6349a042012-01-04 11:25:01 -0800702 mSubject = (TextView) findViewById(R.id.subject);
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800703 mQuotedTextView = (QuotedTextView) findViewById(R.id.quoted_text_view);
704 mQuotedTextView.setRespondInlineListener(this);
Mindy Pereira433b1982012-04-03 11:53:07 -0700705 mBodyView = (EditText) findViewById(R.id.body);
Mindy Pereira1a95a572012-01-05 12:21:29 -0800706 mFromStatic = findViewById(R.id.static_from_content);
Mindy Pereira2eb17322012-03-07 10:07:34 -0800707 mFromStaticText = (TextView) findViewById(R.id.from_account_name);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800708 mFromSpinnerWrapper = findViewById(R.id.spinner_from_content);
Mindy Pereira5a85e2b2012-01-11 09:53:32 -0800709 mFromSpinner = (FromAddressSpinner) findViewById(R.id.from_picker);
Mindy Pereira6349a042012-01-04 11:25:01 -0800710 }
711
Mindy Pereira75f66632012-01-11 11:42:02 -0800712 // Now that the message has been initialized from any existing draft or
713 // ref message data, set up listeners for any changes that occur to the
714 // message.
715 private void initChangeListeners() {
716 mSubject.addTextChangedListener(this);
717 mBodyView.addTextChangedListener(this);
718 mTo.addTextChangedListener(new RecipientTextWatcher(mTo, this));
719 mCc.addTextChangedListener(new RecipientTextWatcher(mCc, this));
720 mBcc.addTextChangedListener(new RecipientTextWatcher(mBcc, this));
721 mFromSpinner.setOnAccountChangedListener(this);
Mindy Pereira818143e2012-01-11 13:59:49 -0800722 mAttachmentsView.setAttachmentChangesListener(this);
Mindy Pereira75f66632012-01-11 11:42:02 -0800723 }
724
Mindy Pereira326c6602012-01-04 15:32:42 -0800725 private void initActionBar(int action) {
726 mComposeMode = action;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800727 ActionBar actionBar = getActionBar();
Mindy Pereira326c6602012-01-04 15:32:42 -0800728 if (action == ComposeActivity.COMPOSE) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800729 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
730 actionBar.setTitle(R.string.compose);
Mindy Pereira326c6602012-01-04 15:32:42 -0800731 } else {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800732 actionBar.setTitle(null);
Mindy Pereira326c6602012-01-04 15:32:42 -0800733 if (mComposeModeAdapter == null) {
734 mComposeModeAdapter = new ComposeModeAdapter(this);
735 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800736 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
737 actionBar.setListNavigationCallbacks(mComposeModeAdapter, this);
Mindy Pereira326c6602012-01-04 15:32:42 -0800738 switch (action) {
739 case ComposeActivity.REPLY:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800740 actionBar.setSelectedNavigationItem(0);
Mindy Pereira326c6602012-01-04 15:32:42 -0800741 break;
742 case ComposeActivity.REPLY_ALL:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800743 actionBar.setSelectedNavigationItem(1);
Mindy Pereira326c6602012-01-04 15:32:42 -0800744 break;
745 case ComposeActivity.FORWARD:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800746 actionBar.setSelectedNavigationItem(2);
Mindy Pereira326c6602012-01-04 15:32:42 -0800747 break;
748 }
749 }
Mindy Pereirafbe40192012-03-20 10:40:45 -0700750 actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME,
751 ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME);
752 actionBar.setHomeButtonEnabled(true);
Mindy Pereira326c6602012-01-04 15:32:42 -0800753 }
754
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800755 private void initFromRefMessage(int action, String recipientAddress) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700756 setSubject(mRefMessage, action);
757 // Setup recipients
758 if (action == FORWARD) {
759 mForward = true;
Mindy Pereira6349a042012-01-04 11:25:01 -0800760 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700761 initRecipientsFromRefMessage(recipientAddress, mRefMessage, action);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700762 initQuotedTextFromRefMessage(mRefMessage, action);
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700763 if (action == ComposeActivity.FORWARD || mAttachmentsChanged) {
764 initAttachments(mRefMessage);
765 }
766 updateHideOrShowCcBcc();
Mindy Pereirac17d0732011-12-29 10:46:19 -0800767 }
768
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700769 private void initFromDraftMessage(Message message) {
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700770 LogUtils.d(LOG_TAG, "Intializing draft from previous draft message");
771
772 mDraft = message;
773 mDraftId = message.id;
774 mSubject.setText(message.subject);
775 mForward = message.draftType == UIProvider.DraftType.FORWARD;
776 final List<String> toAddresses = Arrays.asList(message.getToAddresses());
777 addToAddresses(toAddresses);
778 addCcAddresses(Arrays.asList(message.getCcAddresses()), toAddresses);
779 addBccAddresses(Arrays.asList(message.getBccAddresses()));
Mindy Pereira2421dc82012-03-27 13:32:31 -0700780 if (message.hasAttachments) {
781 List<Attachment> attachments = message.getAttachments();
782 for (Attachment a : attachments) {
Andy Huang5c5fd572012-04-08 18:19:29 -0700783 addAttachmentAndUpdateView(a);
Mindy Pereira2421dc82012-03-27 13:32:31 -0700784 }
785 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700786
787 // Set the body
788 if (!TextUtils.isEmpty(message.bodyHtml)) {
789 mBodyView.setText(Html.fromHtml(message.bodyHtml));
790 } else {
791 mBodyView.setText(message.bodyText);
792 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700793 }
794
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700795 /**
796 * Fill all the widgets with the content found in the Intent Extra, if any.
797 * Also apply the same style to all widgets. Note: if initFromExtras is
798 * called as a result of switching between reply, reply all, and forward per
799 * the latest revision of Gmail, and the user has already made changes to
800 * attachments on a previous incarnation of the message (as a reply, reply
801 * all, or forward), the original attachments from the message will not be
802 * re-instantiated. The user's changes will be respected. This follows the
803 * web gmail interaction.
804 */
805 public void initFromExtras(Intent intent) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700806 // If we were invoked with a SENDTO intent, the value
807 // should take precedence
808 final Uri dataUri = intent.getData();
809 if (dataUri != null) {
810 if (MAIL_TO.equals(dataUri.getScheme())) {
811 initFromMailTo(dataUri.toString());
812 } else {
Mindy Pereira0b4f28e2012-03-28 14:12:21 -0700813 if (!mAccount.composeIntentUri.equals(dataUri)) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700814 String toText = dataUri.getSchemeSpecificPart();
815 if (toText != null) {
816 mTo.setText("");
Mindy Pereiradbe89962012-04-13 09:42:38 -0700817 addToAddresses(Arrays.asList(TextUtils.split(toText, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700818 }
819 }
820 }
821 }
822
823 String[] extraStrings = intent.getStringArrayExtra(Intent.EXTRA_EMAIL);
824 if (extraStrings != null) {
825 addToAddresses(Arrays.asList(extraStrings));
826 }
827 extraStrings = intent.getStringArrayExtra(Intent.EXTRA_CC);
828 if (extraStrings != null) {
829 addCcAddresses(Arrays.asList(extraStrings), null);
830 }
831 extraStrings = intent.getStringArrayExtra(Intent.EXTRA_BCC);
832 if (extraStrings != null) {
833 addBccAddresses(Arrays.asList(extraStrings));
834 }
835
836 String extraString = intent.getStringExtra(Intent.EXTRA_SUBJECT);
837 if (extraString != null) {
838 mSubject.setText(extraString);
839 }
840
841 for (String extra : ALL_EXTRAS) {
842 if (intent.hasExtra(extra)) {
843 String value = intent.getStringExtra(extra);
844 if (EXTRA_TO.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -0700845 addToAddresses(Arrays.asList(TextUtils.split(value, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700846 } else if (EXTRA_CC.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -0700847 addCcAddresses(Arrays.asList(TextUtils.split(value, ",")), null);
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700848 } else if (EXTRA_BCC.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -0700849 addBccAddresses(Arrays.asList(TextUtils.split(value, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700850 } else if (EXTRA_SUBJECT.equals(extra)) {
851 mSubject.setText(value);
852 } else if (EXTRA_BODY.equals(extra)) {
853 setBody(value, true /* with signature */);
854 }
855 }
856 }
857
858 Bundle extras = intent.getExtras();
859 if (extras != null) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700860 CharSequence text = extras.getCharSequence(Intent.EXTRA_TEXT);
861 if (text != null) {
862 setBody(text, true /* with signature */);
863 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700864 }
865
866 updateHideOrShowCcBcc();
867 }
868
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700869 private void initFromMessageInIntent(Message message) {
870 mTo.append(message.to);
871 mCc.append(message.cc);
872 mBcc.append(message.bcc);
873 mBodyView.setText(message.bodyText);
874 mSubject.setText(message.subject);
875 List<Attachment> attachments = message.getAttachments();
876 for (Attachment a : attachments) {
877 mAttachmentsView.addAttachment(a);
878 }
879 mQuotedTextView.updateCheckedState(message.appendRefMessageContent);
880 }
881
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700882 @VisibleForTesting
883 protected String decodeEmailInUri(String s) throws UnsupportedEncodingException {
884 // TODO: handle the case where there are spaces in the display name as well as the email
885 // such as "Guy with spaces <guy+with+spaces@gmail.com>" as they it could be encoded
886 // ambiguously.
887
888 // Since URLDecode.decode changes + into ' ', and + is a valid
889 // email character, we need to find/ replace these ourselves before
890 // decoding.
891 String replacePlus = s.replace("+", "%2B");
892 return URLDecoder.decode(replacePlus, UTF8_ENCODING_NAME);
893 }
894
895 /**
896 * Initialize the compose view from a String representing a mailTo uri.
897 * @param mailToString The uri as a string.
898 */
899 public void initFromMailTo(String mailToString) {
900 // We need to disguise this string as a URI in order to parse it
901 // TODO: Remove this hack when http://b/issue?id=1445295 gets fixed
902 Uri uri = Uri.parse("foo://" + mailToString);
903 int index = mailToString.indexOf("?");
904 int length = "mailto".length() + 1;
905 String to;
906 try {
907 // Extract the recipient after mailto:
908 if (index == -1) {
909 to = decodeEmailInUri(mailToString.substring(length));
910 } else {
911 to = decodeEmailInUri(mailToString.substring(length, index));
912 }
Mindy Pereiradbe89962012-04-13 09:42:38 -0700913 addToAddresses(Arrays.asList(TextUtils.split(to, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700914 } catch (UnsupportedEncodingException e) {
915 if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
916 LogUtils.e(LOG_TAG, "%s while decoding '%s'", e.getMessage(), mailToString);
917 } else {
918 LogUtils.e(LOG_TAG, e, "Exception while decoding mailto address");
919 }
920 }
921
922 List<String> cc = uri.getQueryParameters("cc");
923 addCcAddresses(Arrays.asList(cc.toArray(new String[cc.size()])), null);
924
925 List<String> otherTo = uri.getQueryParameters("to");
926 addToAddresses(Arrays.asList(otherTo.toArray(new String[otherTo.size()])));
927
928 List<String> bcc = uri.getQueryParameters("bcc");
929 addBccAddresses(Arrays.asList(bcc.toArray(new String[bcc.size()])));
930
931 List<String> subject = uri.getQueryParameters("subject");
932 if (subject.size() > 0) {
933 try {
934 mSubject.setText(URLDecoder.decode(subject.get(0), UTF8_ENCODING_NAME));
935 } catch (UnsupportedEncodingException e) {
936 LogUtils.e(LOG_TAG, "%s while decoding subject '%s'",
937 e.getMessage(), subject);
938 }
939 }
940
941 List<String> body = uri.getQueryParameters("body");
942 if (body.size() > 0) {
943 try {
944 setBody(URLDecoder.decode(body.get(0), UTF8_ENCODING_NAME),
945 true /* with signature */);
946 } catch (UnsupportedEncodingException e) {
947 LogUtils.e(LOG_TAG, "%s while decoding body '%s'", e.getMessage(), body);
948 }
949 }
950
951 updateHideOrShowCcBcc();
952 }
953
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800954 private void initAttachments(Message refMessage) {
Mindy Pereira7a07fb42012-01-11 10:32:48 -0800955 mAttachmentsView.addAttachments(mAccount, refMessage);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800956 }
957
Paul Westbrookf97588b2012-03-20 11:11:37 -0700958 private void initAttachmentsFromIntent(Intent intent) {
Paul Westbrook03ee9712012-04-02 09:51:51 -0700959 Bundle extras = intent.getExtras();
960 if (extras == null) {
961 extras = Bundle.EMPTY;
962 }
Paul Westbrookf97588b2012-03-20 11:11:37 -0700963 final String action = intent.getAction();
964 if (!mAttachmentsChanged) {
965 long totalSize = 0;
966 if (extras.containsKey(EXTRA_ATTACHMENTS)) {
967 String[] uris = (String[]) extras.getSerializable(EXTRA_ATTACHMENTS);
968 for (String uriString : uris) {
969 final Uri uri = Uri.parse(uriString);
970 long size = 0;
971 try {
Andy Huang5c5fd572012-04-08 18:19:29 -0700972 size = mAttachmentsView.addAttachment(mAccount, uri);
Paul Westbrookf97588b2012-03-20 11:11:37 -0700973 } catch (AttachmentFailureException e) {
974 // A toast has already been shown to the user,
975 // just break out of the loop.
976 LogUtils.e(LOG_TAG, e, "Error adding attachment");
977 }
978 totalSize += size;
979 }
980 }
981 if (Intent.ACTION_SEND.equals(action) && extras.containsKey(Intent.EXTRA_STREAM)) {
982 final Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
983 long size = 0;
984 try {
Andy Huang5c5fd572012-04-08 18:19:29 -0700985 size = mAttachmentsView.addAttachment(mAccount, uri);
Paul Westbrookf97588b2012-03-20 11:11:37 -0700986 } catch (AttachmentFailureException e) {
987 // A toast has already been shown to the user, so just
988 // exit.
989 LogUtils.e(LOG_TAG, e, "Error adding attachment");
990 }
991 totalSize += size;
992 }
993
994 if (Intent.ACTION_SEND_MULTIPLE.equals(action)
995 && extras.containsKey(Intent.EXTRA_STREAM)) {
996 ArrayList<Parcelable> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
997 for (Parcelable uri : uris) {
998 long size = 0;
999 try {
Andy Huang5c5fd572012-04-08 18:19:29 -07001000 size = mAttachmentsView.addAttachment(mAccount, (Uri) uri);
Paul Westbrookf97588b2012-03-20 11:11:37 -07001001 } catch (AttachmentFailureException e) {
1002 // A toast has already been shown to the user,
1003 // just break out of the loop.
1004 LogUtils.e(LOG_TAG, e, "Error adding attachment");
1005 }
1006 totalSize += size;
1007 }
1008 }
1009
1010 if (totalSize > 0) {
1011 mAttachmentsChanged = true;
1012 updateSaveUi();
1013 }
1014 }
1015 }
1016
1017
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001018 private void initQuotedTextFromRefMessage(Message refMessage, int action) {
1019 if (mRefMessage != null && (action == REPLY || action == REPLY_ALL || action == FORWARD)) {
Mindy Pereira9932dee2012-01-10 16:09:50 -08001020 mQuotedTextView.setQuotedText(action, refMessage, action != FORWARD);
1021 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001022 }
1023
1024 private void updateHideOrShowCcBcc() {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001025 // Its possible there is a menu item OR a button.
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001026 boolean ccVisible = !TextUtils.isEmpty(mCc.getText());
1027 boolean bccVisible = !TextUtils.isEmpty(mBcc.getText());
1028 if (ccVisible || bccVisible) {
1029 mCcBccView.show(false, ccVisible, bccVisible);
1030 }
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001031 if (mCcBccButton != null) {
1032 if (!mCc.isShown() || !mBcc.isShown()) {
1033 mCcBccButton.setVisibility(View.VISIBLE);
1034 mCcBccButton.setText(getString(!mCc.isShown() ? R.string.add_cc_label
1035 : R.string.add_bcc_label));
1036 } else {
1037 mCcBccButton.setVisibility(View.GONE);
1038 }
1039 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001040 }
1041
Mindy Pereiraa34c9a02012-04-17 14:10:53 -07001042 private void showCcBcc(Bundle state) {
1043 if (state != null && state.containsKey(EXTRA_SHOW_CC_BCC)) {
1044 boolean show = state.getBoolean(EXTRA_SHOW_CC_BCC);
1045 mCcBccView.show(false, show, show);
1046 }
1047 }
1048
Mindy Pereira013194c2012-01-06 15:09:33 -08001049 /**
1050 * Add attachment and update the compose area appropriately.
1051 * @param data
1052 */
1053 public void addAttachmentAndUpdateView(Intent data) {
Mindy Pereira2421dc82012-03-27 13:32:31 -07001054 addAttachmentAndUpdateView(data != null ? data.getData() : (Uri) null);
1055 }
1056
Andy Huang5c5fd572012-04-08 18:19:29 -07001057 public void addAttachmentAndUpdateView(Uri contentUri) {
1058 if (contentUri == null) {
Mindy Pereira2421dc82012-03-27 13:32:31 -07001059 return;
1060 }
Mindy Pereira013194c2012-01-06 15:09:33 -08001061 try {
Andy Huang5c5fd572012-04-08 18:19:29 -07001062 addAttachmentAndUpdateView(mAttachmentsView.generateLocalAttachment(contentUri));
1063 } catch (AttachmentFailureException e) {
1064 // A toast has already been shown to the user, no need to do
1065 // anything.
1066 LogUtils.e(LOG_TAG, e, "Error adding attachment");
1067 }
1068 }
1069
1070 public void addAttachmentAndUpdateView(Attachment attachment) {
1071 try {
1072 long size = mAttachmentsView.addAttachment(mAccount, attachment);
Mindy Pereira9932dee2012-01-10 16:09:50 -08001073 if (size > 0) {
1074 mAttachmentsChanged = true;
1075 updateSaveUi();
Mindy Pereira013194c2012-01-06 15:09:33 -08001076 }
Mindy Pereira9932dee2012-01-10 16:09:50 -08001077 } catch (AttachmentFailureException e) {
1078 // A toast has already been shown to the user, no need to do
1079 // anything.
1080 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Mindy Pereira013194c2012-01-06 15:09:33 -08001081 }
1082 }
1083
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001084 void initRecipientsFromRefMessage(String recipientAddress, Message refMessage,
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001085 int action) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001086 // Don't populate the address if this is a forward.
1087 if (action == ComposeActivity.FORWARD) {
1088 return;
1089 }
Mindy Pereira33fe9082012-01-09 16:24:30 -08001090 initReplyRecipients(mAccount.name, refMessage, action);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001091 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001092
Mindy Pereira818143e2012-01-11 13:59:49 -08001093 @VisibleForTesting
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001094 void initReplyRecipients(String account, Message refMessage, int action) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001095 // This is the email address of the current user, i.e. the one composing
1096 // the reply.
Mindy Pereira4a20b702012-01-05 16:24:24 -08001097 final String accountEmail = Address.getEmailAddress(account).getAddress();
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001098 String fromAddress = refMessage.from;
1099 String[] sentToAddresses = Utils.splitCommaSeparatedString(refMessage.to);
1100 String replytoAddress = refMessage.replyTo;
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001101 final Collection<String> toAddresses;
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001102
1103 // If this is a reply, the Cc list is empty. If this is a reply-all, the
1104 // Cc list is the union of the To and Cc recipients of the original
1105 // message, excluding the current user's email address and any addresses
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001106 // already on the To list.
1107 if (action == ComposeActivity.REPLY) {
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001108 toAddresses = initToRecipients(account, accountEmail, fromAddress, replytoAddress,
1109 new String[0]);
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001110 addToAddresses(toAddresses);
1111 } else if (action == ComposeActivity.REPLY_ALL) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001112 final Set<String> ccAddresses = Sets.newHashSet();
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001113 toAddresses = initToRecipients(account, accountEmail, fromAddress, replytoAddress,
1114 new String[0]);
Mindy Pereira154386a2012-01-11 13:02:33 -08001115 addToAddresses(toAddresses);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001116 addRecipients(accountEmail, ccAddresses, sentToAddresses);
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001117 addRecipients(accountEmail, ccAddresses,
1118 Utils.splitCommaSeparatedString(refMessage.cc));
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001119 addCcAddresses(ccAddresses, toAddresses);
1120 }
1121 }
1122
1123 private void addToAddresses(Collection<String> addresses) {
1124 addAddressesToList(addresses, mTo);
1125 }
1126
1127 private void addCcAddresses(Collection<String> addresses, Collection<String> toAddresses) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001128 addCcAddressesToList(tokenizeAddressList(addresses),
1129 toAddresses != null ? tokenizeAddressList(toAddresses) : null, mCc);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001130 }
1131
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001132 private void addBccAddresses(Collection<String> addresses) {
1133 addAddressesToList(addresses, mBcc);
1134 }
1135
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001136 @VisibleForTesting
1137 protected void addCcAddressesToList(List<Rfc822Token[]> addresses,
1138 List<Rfc822Token[]> compareToList, RecipientEditTextView list) {
1139 String address;
1140
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001141 if (compareToList == null) {
1142 for (Rfc822Token[] tokens : addresses) {
1143 for (int i = 0; i < tokens.length; i++) {
1144 address = tokens[i].toString();
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001145 list.append(address + END_TOKEN);
1146 }
1147 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001148 } else {
1149 HashSet<String> compareTo = convertToHashSet(compareToList);
1150 for (Rfc822Token[] tokens : addresses) {
1151 for (int i = 0; i < tokens.length; i++) {
1152 address = tokens[i].toString();
1153 // Check if this is a duplicate:
1154 if (!compareTo.contains(tokens[i].getAddress())) {
1155 // Get the address here
1156 list.append(address + END_TOKEN);
1157 }
1158 }
1159 }
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001160 }
1161 }
1162
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001163 private HashSet<String> convertToHashSet(List<Rfc822Token[]> list) {
1164 HashSet<String> hash = new HashSet<String>();
1165 for (Rfc822Token[] tokens : list) {
1166 for (int i = 0; i < tokens.length; i++) {
1167 hash.add(tokens[i].getAddress());
1168 }
1169 }
1170 return hash;
1171 }
1172
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001173 protected List<Rfc822Token[]> tokenizeAddressList(Collection<String> addresses) {
1174 @VisibleForTesting
1175 List<Rfc822Token[]> tokenized = new ArrayList<Rfc822Token[]>();
1176
1177 for (String address: addresses) {
1178 tokenized.add(Rfc822Tokenizer.tokenize(address));
1179 }
1180 return tokenized;
1181 }
1182
1183 @VisibleForTesting
1184 void addAddressesToList(Collection<String> addresses, RecipientEditTextView list) {
1185 for (String address : addresses) {
1186 addAddressToList(address, list);
1187 }
1188 }
1189
1190 private void addAddressToList(String address, RecipientEditTextView list) {
1191 if (address == null || list == null)
1192 return;
1193
1194 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(address);
1195
1196 for (int i = 0; i < tokens.length; i++) {
1197 list.append(tokens[i] + END_TOKEN);
1198 }
1199 }
1200
1201 @VisibleForTesting
1202 protected Collection<String> initToRecipients(String account, String accountEmail,
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001203 String senderAddress, String replyToAddress, String[] inToAddresses) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001204 // The To recipient is the reply-to address specified in the original
1205 // message, unless it is:
1206 // the current user OR a custom from of the current user, in which case
1207 // it's the To recipient list of the original message.
1208 // OR missing, in which case use the sender of the original message
1209 Set<String> toAddresses = Sets.newHashSet();
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001210 if (!TextUtils.isEmpty(replyToAddress)) {
1211 toAddresses.add(replyToAddress);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001212 } else {
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001213 toAddresses.add(senderAddress);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001214 }
1215 return toAddresses;
1216 }
1217
1218 private static void addRecipients(String account, Set<String> recipients, String[] addresses) {
1219 for (String email : addresses) {
1220 // Do not add this account, or any of the custom froms, to the list
1221 // of recipients.
Mindy Pereira4a20b702012-01-05 16:24:24 -08001222 final String recipientAddress = Address.getEmailAddress(email).getAddress();
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001223 if (!account.equalsIgnoreCase(recipientAddress)) {
1224 recipients.add(email.replace("\"\"", ""));
1225 }
1226 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001227 }
1228
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001229 private void setSubject(Message refMessage, int action) {
1230 String subject = refMessage.subject;
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001231 String prefix;
1232 String correctedSubject = null;
1233 if (action == ComposeActivity.COMPOSE) {
1234 prefix = "";
1235 } else if (action == ComposeActivity.FORWARD) {
1236 prefix = getString(R.string.forward_subject_label);
1237 } else {
1238 prefix = getString(R.string.reply_subject_label);
1239 }
1240
1241 // Don't duplicate the prefix
1242 if (subject.toLowerCase().startsWith(prefix.toLowerCase())) {
1243 correctedSubject = subject;
1244 } else {
1245 correctedSubject = String
1246 .format(getString(R.string.formatted_subject), prefix, subject);
1247 }
1248 mSubject.setText(correctedSubject);
1249 }
1250
Mindy Pereira818143e2012-01-11 13:59:49 -08001251 private void initRecipients() {
1252 setupRecipients(mTo);
1253 setupRecipients(mCc);
1254 setupRecipients(mBcc);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001255 }
1256
Mindy Pereira818143e2012-01-11 13:59:49 -08001257 private void setupRecipients(RecipientEditTextView view) {
Paul Westbrook679a8cc2012-02-21 16:37:58 -08001258 view.setAdapter(new RecipientAdapter(this, mAccount));
Mindy Pereirac17d0732011-12-29 10:46:19 -08001259 view.setTokenizer(new Rfc822Tokenizer());
Mindy Pereira82cc5662012-01-09 17:29:30 -08001260 if (mValidator == null) {
Paul Westbrook679a8cc2012-02-21 16:37:58 -08001261 final String accountName = mAccount.name;
Mindy Pereira33fe9082012-01-09 16:24:30 -08001262 int offset = accountName.indexOf("@") + 1;
1263 String account = accountName;
Mindy Pereirac17d0732011-12-29 10:46:19 -08001264 if (offset > -1) {
Mindy Pereira33fe9082012-01-09 16:24:30 -08001265 account = account.substring(accountName.indexOf("@") + 1);
Mindy Pereirac17d0732011-12-29 10:46:19 -08001266 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001267 mValidator = new Rfc822Validator(account);
Mindy Pereirac17d0732011-12-29 10:46:19 -08001268 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001269 view.setValidator(mValidator);
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001270 }
1271
1272 @Override
1273 public void onClick(View v) {
1274 int id = v.getId();
1275 switch (id) {
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001276 case R.id.add_cc_bcc:
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001277 // Verify that cc/ bcc aren't showing.
1278 // Animate in cc/bcc.
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001279 showCcBccViews();
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001280 break;
Mindy Pereira1f936682012-03-02 11:30:33 -08001281 case R.id.add_attachment:
1282 doAttach();
1283 break;
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001284 }
1285 }
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001286
1287 @Override
1288 public boolean onCreateOptionsMenu(Menu menu) {
1289 super.onCreateOptionsMenu(menu);
1290 MenuInflater inflater = getMenuInflater();
1291 inflater.inflate(R.menu.compose_menu, menu);
Mindy Pereira82cc5662012-01-09 17:29:30 -08001292 mSave = menu.findItem(R.id.save);
1293 mSend = menu.findItem(R.id.send);
Mindy Pereira3ca5bad2012-04-16 11:02:42 -07001294 MenuItem helpItem = menu.findItem(R.id.help_info_menu_item);
1295 MenuItem sendFeedbackItem = menu.findItem(R.id.feedback_menu_item);
1296 if (helpItem != null) {
1297 helpItem.setVisible(mAccount != null
1298 && mAccount.supportsCapability(AccountCapabilities.HELP_CONTENT));
1299 }
1300 if (sendFeedbackItem != null) {
1301 sendFeedbackItem.setVisible(mAccount != null
1302 && mAccount.supportsCapability(AccountCapabilities.SEND_FEEDBACK));
1303 }
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001304 return true;
1305 }
1306
1307 @Override
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001308 public boolean onPrepareOptionsMenu(Menu menu) {
1309 MenuItem ccBcc = menu.findItem(R.id.add_cc_bcc);
Mindy Pereira818143e2012-01-11 13:59:49 -08001310 if (ccBcc != null && mCc != null) {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001311 // Its possible there is a menu item OR a button.
1312 boolean ccFieldVisible = mCc.isShown();
1313 boolean bccFieldVisible = mBcc.isShown();
1314 if (!ccFieldVisible || !bccFieldVisible) {
1315 ccBcc.setVisible(true);
1316 ccBcc.setTitle(getString(!ccFieldVisible ? R.string.add_cc_label
1317 : R.string.add_bcc_label));
1318 } else {
1319 ccBcc.setVisible(false);
1320 }
1321 }
Mindy Pereira75f66632012-01-11 11:42:02 -08001322 if (mSave != null) {
1323 mSave.setEnabled(shouldSave());
1324 }
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001325 return true;
1326 }
1327
1328 @Override
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001329 public boolean onOptionsItemSelected(MenuItem item) {
1330 int id = item.getItemId();
Mindy Pereira75f66632012-01-11 11:42:02 -08001331 boolean handled = true;
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001332 switch (id) {
Mindy Pereira7b56a612011-12-14 12:32:28 -08001333 case R.id.add_attachment:
Mindy Pereira013194c2012-01-06 15:09:33 -08001334 doAttach();
Mindy Pereira7b56a612011-12-14 12:32:28 -08001335 break;
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001336 case R.id.add_cc_bcc:
1337 showCcBccViews();
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001338 break;
Mindy Pereira33fe9082012-01-09 16:24:30 -08001339 case R.id.save:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001340 doSave(true, false);
Mindy Pereira33fe9082012-01-09 16:24:30 -08001341 break;
1342 case R.id.send:
1343 doSend();
Mindy Pereira75f66632012-01-11 11:42:02 -08001344 break;
Mindy Pereiraefe3d252012-03-01 14:20:44 -08001345 case R.id.discard:
1346 doDiscard();
1347 break;
Mindy Pereira1f936682012-03-02 11:30:33 -08001348 case R.id.settings:
1349 Utils.showSettings(this, mAccount);
1350 break;
Mindy Pereirafbe40192012-03-20 10:40:45 -07001351 case android.R.id.home:
1352 finish();
1353 break;
1354 case R.id.help_info_menu_item:
1355 // TODO: enable context sensitive help
Paul Westbrook498e76d2012-04-12 16:33:02 -07001356 Utils.showHelp(this, mAccount, null);
Mindy Pereirafbe40192012-03-20 10:40:45 -07001357 break;
1358 case R.id.feedback_menu_item:
1359 Utils.sendFeedback(this, mAccount);
1360 break;
Mindy Pereira75f66632012-01-11 11:42:02 -08001361 default:
1362 handled = false;
Mindy Pereira33fe9082012-01-09 16:24:30 -08001363 break;
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001364 }
1365 return !handled ? super.onOptionsItemSelected(item) : handled;
1366 }
Mindy Pereira326c6602012-01-04 15:32:42 -08001367
Mindy Pereira33fe9082012-01-09 16:24:30 -08001368 private void doSend() {
Mindy Pereira82cc5662012-01-09 17:29:30 -08001369 sendOrSaveWithSanityChecks(false, true, false);
Mindy Pereira33fe9082012-01-09 16:24:30 -08001370 }
1371
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001372 private void doSave(boolean showToast, boolean resetIME) {
1373 sendOrSaveWithSanityChecks(true, showToast, false);
1374 if (resetIME) {
1375 // Clear the IME composing suggestions from the body.
1376 BaseInputConnection.removeComposingSpans(mBodyView.getEditableText());
1377 }
Mindy Pereira33fe9082012-01-09 16:24:30 -08001378 }
1379
Mindy Pereira82cc5662012-01-09 17:29:30 -08001380 /*package*/ interface SendOrSaveCallback {
1381 public void initializeSendOrSave(SendOrSaveTask sendOrSaveTask);
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001382 public void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage, Message message);
1383 public Message getMessage();
Mindy Pereira82cc5662012-01-09 17:29:30 -08001384 public void sendOrSaveFinished(SendOrSaveTask sendOrSaveTask, boolean success);
1385 }
1386
1387 /*package*/ static class SendOrSaveTask implements Runnable {
1388 private final Context mContext;
1389 private final SendOrSaveCallback mSendOrSaveCallback;
1390 @VisibleForTesting
1391 final SendOrSaveMessage mSendOrSaveMessage;
1392
1393 public SendOrSaveTask(Context context, SendOrSaveMessage message,
1394 SendOrSaveCallback callback) {
1395 mContext = context;
1396 mSendOrSaveCallback = callback;
1397 mSendOrSaveMessage = message;
1398 }
1399
1400 @Override
1401 public void run() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001402 final SendOrSaveMessage sendOrSaveMessage = mSendOrSaveMessage;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001403
Mindy Pereira92551d02012-04-05 11:31:12 -07001404 final ReplyFromAccount selectedAccount = sendOrSaveMessage.mAccount;
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001405 Message message = mSendOrSaveCallback.getMessage();
1406 long messageId = message != null ? message.id : UIProvider.INVALID_MESSAGE_ID;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001407 // If a previous draft has been saved, in an account that is different
1408 // than what the user wants to send from, remove the old draft, and treat this
1409 // as a new message
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001410 if (!selectedAccount.equals(sendOrSaveMessage.mAccount)) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08001411 if (messageId != UIProvider.INVALID_MESSAGE_ID) {
1412 ContentResolver resolver = mContext.getContentResolver();
1413 ContentValues values = new ContentValues();
1414 values.put(BaseColumns._ID, messageId);
Mindy Pereira92551d02012-04-05 11:31:12 -07001415 if (selectedAccount.account.expungeMessageUri != null) {
1416 resolver.update(selectedAccount.account.expungeMessageUri, values, null,
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001417 null);
Mindy Pereiracfb7f332012-02-28 10:23:43 -08001418 } else {
1419 // TODO(mindyp) delete the conversation.
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001420 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001421 // reset messageId to 0, so a new message will be created
1422 messageId = UIProvider.INVALID_MESSAGE_ID;
1423 }
1424 }
1425
1426 final long messageIdToSave = messageId;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001427 if (messageIdToSave != UIProvider.INVALID_MESSAGE_ID) {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001428 sendOrSaveMessage.mValues.put(BaseColumns._ID, messageIdToSave);
Mindy Pereira82cc5662012-01-09 17:29:30 -08001429 mContext.getContentResolver().update(
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001430 Uri.parse(sendOrSaveMessage.mSave ? message.saveUri : message.sendUri),
1431 sendOrSaveMessage.mValues, null, null);
Mindy Pereira82cc5662012-01-09 17:29:30 -08001432 } else {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001433 ContentResolver resolver = mContext.getContentResolver();
Mindy Pereira92551d02012-04-05 11:31:12 -07001434 Uri messageUri = resolver
1435 .insert(sendOrSaveMessage.mSave ? selectedAccount.account.saveDraftUri
1436 : selectedAccount.account.sendMessageUri,
1437 sendOrSaveMessage.mValues);
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001438 if (sendOrSaveMessage.mSave && messageUri != null) {
1439 Cursor messageCursor = resolver.query(messageUri,
1440 UIProvider.MESSAGE_PROJECTION, null, null, null);
Paul Westbrookba558482012-03-19 11:00:24 -07001441 if (messageCursor != null) {
1442 try {
1443 if (messageCursor.moveToFirst()) {
1444 // Broadcast notification that a new message has
1445 // been allocated
1446 mSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage,
1447 new Message(messageCursor));
1448 }
1449 } finally {
1450 messageCursor.close();
1451 }
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001452 }
1453 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001454 }
1455
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001456 if (!sendOrSaveMessage.mSave) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08001457 UIProvider.incrementRecipientsTimesContacted(mContext,
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001458 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.TO));
Mindy Pereira82cc5662012-01-09 17:29:30 -08001459 UIProvider.incrementRecipientsTimesContacted(mContext,
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001460 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.CC));
Mindy Pereira82cc5662012-01-09 17:29:30 -08001461 UIProvider.incrementRecipientsTimesContacted(mContext,
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001462 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.BCC));
Mindy Pereira82cc5662012-01-09 17:29:30 -08001463 }
1464 mSendOrSaveCallback.sendOrSaveFinished(SendOrSaveTask.this, true);
1465 }
1466 }
1467
1468 // Array of the outstanding send or save tasks. Access is synchronized
1469 // with the object itself
1470 /* package for testing */
1471 ArrayList<SendOrSaveTask> mActiveTasks = Lists.newArrayList();
1472 private int mRequestId;
Mindy Pereirabdf7a402012-03-01 15:23:26 -08001473 private String mSignature;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001474
1475 /*package*/ static class SendOrSaveMessage {
Mindy Pereira92551d02012-04-05 11:31:12 -07001476 final ReplyFromAccount mAccount;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001477 final ContentValues mValues;
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001478 final String mRefMessageId;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001479 final boolean mSave;
1480 final int mRequestId;
1481
Mindy Pereira92551d02012-04-05 11:31:12 -07001482 public SendOrSaveMessage(ReplyFromAccount account, ContentValues values,
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001483 String refMessageId, boolean save) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08001484 mAccount = account;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001485 mValues = values;
1486 mRefMessageId = refMessageId;
1487 mSave = save;
1488 mRequestId = mValues.hashCode() ^ hashCode();
1489 }
1490
1491 int requestId() {
1492 return mRequestId;
1493 }
1494 }
1495
1496 /**
1497 * Get the to recipients.
1498 */
1499 public String[] getToAddresses() {
1500 return getAddressesFromList(mTo);
1501 }
1502
1503 /**
1504 * Get the cc recipients.
1505 */
1506 public String[] getCcAddresses() {
1507 return getAddressesFromList(mCc);
1508 }
1509
1510 /**
1511 * Get the bcc recipients.
1512 */
1513 public String[] getBccAddresses() {
1514 return getAddressesFromList(mBcc);
1515 }
1516
1517 public String[] getAddressesFromList(RecipientEditTextView list) {
1518 if (list == null) {
1519 return new String[0];
1520 }
1521 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(list.getText());
1522 int count = tokens.length;
1523 String[] result = new String[count];
1524 for (int i = 0; i < count; i++) {
1525 result[i] = tokens[i].toString();
1526 }
1527 return result;
1528 }
1529
1530 /**
1531 * Check for invalid email addresses.
1532 * @param to String array of email addresses to check.
1533 * @param wrongEmailsOut Emails addresses that were invalid.
1534 */
1535 public void checkInvalidEmails(String[] to, List<String> wrongEmailsOut) {
1536 for (String email : to) {
1537 if (!mValidator.isValid(email)) {
1538 wrongEmailsOut.add(email);
1539 }
1540 }
1541 }
1542
1543 /**
1544 * Show an error because the user has entered an invalid recipient.
1545 * @param message
1546 */
1547 public void showRecipientErrorDialog(String message) {
1548 // Only 1 invalid recipients error dialog should be allowed up at a
1549 // time.
1550 if (mRecipientErrorDialog != null) {
1551 mRecipientErrorDialog.dismiss();
1552 }
1553 mRecipientErrorDialog = new AlertDialog.Builder(this).setMessage(message).setTitle(
1554 R.string.recipient_error_dialog_title)
1555 .setIconAttribute(android.R.attr.alertDialogIcon)
1556 .setCancelable(false)
1557 .setPositiveButton(
1558 R.string.ok, new Dialog.OnClickListener() {
1559 public void onClick(DialogInterface dialog, int which) {
1560 // after the user dismisses the recipient error
1561 // dialog we want to make sure to refocus the
1562 // recipient to field so they can fix the issue
1563 // easily
1564 if (mTo != null) {
1565 mTo.requestFocus();
1566 }
1567 mRecipientErrorDialog = null;
1568 }
1569 }).show();
1570 }
1571
1572 /**
1573 * Update the state of the UI based on whether or not the current draft
1574 * needs to be saved and the message is not empty.
1575 */
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001576 public void updateSaveUi() {
Mindy Pereira82cc5662012-01-09 17:29:30 -08001577 if (mSave != null) {
1578 mSave.setEnabled((shouldSave() && !isBlank()));
1579 }
1580 }
1581
1582 /**
1583 * Returns true if we need to save the current draft.
1584 */
1585 private boolean shouldSave() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001586 synchronized (mDraftLock) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08001587 // The message should only be saved if:
1588 // It hasn't been sent AND
1589 // Some text has been added to the message OR
1590 // an attachment has been added or removed
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001591 return (mTextChanged || mAttachmentsChanged ||
Mindy Pereira82cc5662012-01-09 17:29:30 -08001592 (mReplyFromChanged && !isBlank()));
1593 }
1594 }
1595
1596 /**
Mindy Pereirabdf7a402012-03-01 15:23:26 -08001597 * Check if all fields are blank.
Mindy Pereira82cc5662012-01-09 17:29:30 -08001598 * @return boolean
1599 */
1600 public boolean isBlank() {
1601 return mSubject.getText().length() == 0
Mindy Pereirabdf7a402012-03-01 15:23:26 -08001602 && (mBodyView.getText().length() == 0 || getSignatureStartPosition(mSignature,
1603 mBodyView.getText().toString()) == 0)
1604 && mTo.length() == 0
1605 && mCc.length() == 0 && mBcc.length() == 0
1606 && mAttachmentsView.getAttachments().size() == 0;
1607 }
1608
1609 @VisibleForTesting
1610 protected int getSignatureStartPosition(String signature, String bodyText) {
1611 int startPos = -1;
1612
1613 if (TextUtils.isEmpty(signature) || TextUtils.isEmpty(bodyText)) {
1614 return startPos;
1615 }
1616
1617 int bodyLength = bodyText.length();
1618 int signatureLength = signature.length();
1619 String printableVersion = convertToPrintableSignature(signature);
1620 int printableLength = printableVersion.length();
1621
1622 if (bodyLength >= printableLength
1623 && bodyText.substring(bodyLength - printableLength)
1624 .equals(printableVersion)) {
1625 startPos = bodyLength - printableLength;
1626 } else if (bodyLength >= signatureLength
1627 && bodyText.substring(bodyLength - signatureLength)
1628 .equals(signature)) {
1629 startPos = bodyLength - signatureLength;
1630 }
1631 return startPos;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001632 }
1633
1634 /**
1635 * Allows any changes made by the user to be ignored. Called when the user
1636 * decides to discard a draft.
1637 */
1638 private void discardChanges() {
1639 mTextChanged = false;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001640 mAttachmentsChanged = false;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001641 mReplyFromChanged = false;
1642 }
1643
1644 /**
Mindy Pereira181df782012-03-01 13:32:44 -08001645 * @param body
1646 * @param save
1647 * @param showToast
1648 * @return Whether the send or save succeeded.
1649 */
1650 protected boolean sendOrSaveWithSanityChecks(final boolean save, final boolean showToast,
1651 final boolean orientationChanged) {
1652 String[] to, cc, bcc;
1653 Editable body = mBodyView.getEditableText();
Mindy Pereira82cc5662012-01-09 17:29:30 -08001654
Mindy Pereira181df782012-03-01 13:32:44 -08001655 if (orientationChanged) {
1656 to = cc = bcc = new String[0];
1657 } else {
1658 to = getToAddresses();
1659 cc = getCcAddresses();
1660 bcc = getBccAddresses();
1661 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001662
Mindy Pereira181df782012-03-01 13:32:44 -08001663 // Don't let the user send to nobody (but it's okay to save a message
1664 // with no recipients)
1665 if (!save && (to.length == 0 && cc.length == 0 && bcc.length == 0)) {
1666 showRecipientErrorDialog(getString(R.string.recipient_needed));
1667 return false;
1668 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001669
Mindy Pereira181df782012-03-01 13:32:44 -08001670 List<String> wrongEmails = new ArrayList<String>();
1671 if (!save) {
1672 checkInvalidEmails(to, wrongEmails);
1673 checkInvalidEmails(cc, wrongEmails);
1674 checkInvalidEmails(bcc, wrongEmails);
1675 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001676
Mindy Pereira181df782012-03-01 13:32:44 -08001677 // Don't let the user send an email with invalid recipients
1678 if (wrongEmails.size() > 0) {
1679 String errorText = String.format(getString(R.string.invalid_recipient),
1680 wrongEmails.get(0));
1681 showRecipientErrorDialog(errorText);
1682 return false;
1683 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001684
Mindy Pereira181df782012-03-01 13:32:44 -08001685 DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
1686 public void onClick(DialogInterface dialog, int which) {
1687 sendOrSave(mBodyView.getEditableText(), save, showToast, orientationChanged);
1688 }
1689 };
Mindy Pereira82cc5662012-01-09 17:29:30 -08001690
Mindy Pereira181df782012-03-01 13:32:44 -08001691 // Show a warning before sending only if there are no attachments.
1692 if (!save) {
1693 if (mAttachmentsView.getAttachments().isEmpty() && showEmptyTextWarnings()) {
1694 boolean warnAboutEmptySubject = isSubjectEmpty();
1695 boolean emptyBody = TextUtils.getTrimmedLength(body) == 0;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001696
Mindy Pereira181df782012-03-01 13:32:44 -08001697 // A warning about an empty body may not be warranted when
1698 // forwarding mails, since a common use case is to forward
1699 // quoted text and not append any more text.
1700 boolean warnAboutEmptyBody = emptyBody && (!mForward || isBodyEmpty());
Mindy Pereira82cc5662012-01-09 17:29:30 -08001701
Mindy Pereira181df782012-03-01 13:32:44 -08001702 // When we bring up a dialog warning the user about a send,
1703 // assume that they accept sending the message. If they do not,
1704 // the dialog listener is required to enable sending again.
1705 if (warnAboutEmptySubject) {
1706 showSendConfirmDialog(R.string.confirm_send_message_with_no_subject, listener);
1707 return true;
1708 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001709
Mindy Pereira181df782012-03-01 13:32:44 -08001710 if (warnAboutEmptyBody) {
1711 showSendConfirmDialog(R.string.confirm_send_message_with_no_body, listener);
1712 return true;
1713 }
1714 }
1715 // Ask for confirmation to send (if always required)
1716 if (showSendConfirmation()) {
1717 showSendConfirmDialog(R.string.confirm_send_message, listener);
1718 return true;
1719 }
1720 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001721
Mindy Pereira181df782012-03-01 13:32:44 -08001722 sendOrSave(body, save, showToast, false);
1723 return true;
1724 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001725
Mindy Pereira181df782012-03-01 13:32:44 -08001726 /**
1727 * Returns a boolean indicating whether warnings should be shown for empty
1728 * subject and body fields
Andy Huang5c5fd572012-04-08 18:19:29 -07001729 *
Mindy Pereira181df782012-03-01 13:32:44 -08001730 * @return True if a warning should be shown for empty text fields
1731 */
1732 protected boolean showEmptyTextWarnings() {
1733 return mAttachmentsView.getAttachments().size() == 0;
1734 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001735
Mindy Pereira181df782012-03-01 13:32:44 -08001736 /**
1737 * Returns a boolean indicating whether the user should confirm each send
1738 *
1739 * @return True if a warning should be on each send
1740 */
1741 protected boolean showSendConfirmation() {
1742 return mCachedSettings != null ? mCachedSettings.confirmSend : false;
1743 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001744
Mindy Pereira181df782012-03-01 13:32:44 -08001745 private void showSendConfirmDialog(int messageId, DialogInterface.OnClickListener listener) {
1746 if (mSendConfirmDialog != null) {
1747 mSendConfirmDialog.dismiss();
1748 mSendConfirmDialog = null;
1749 }
1750 mSendConfirmDialog = new AlertDialog.Builder(this).setMessage(messageId)
1751 .setTitle(R.string.confirm_send_title)
1752 .setIconAttribute(android.R.attr.alertDialogIcon)
1753 .setPositiveButton(R.string.send, listener)
1754 .setNegativeButton(R.string.cancel, this).setCancelable(false).show();
1755 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001756
Mindy Pereira181df782012-03-01 13:32:44 -08001757 /**
1758 * Returns whether the ComposeArea believes there is any text in the body of
1759 * the composition. TODO: When ComposeArea controls the Body as well, add
1760 * that here.
1761 */
1762 public boolean isBodyEmpty() {
1763 return !mQuotedTextView.isTextIncluded();
1764 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001765
Mindy Pereira181df782012-03-01 13:32:44 -08001766 /**
1767 * Test to see if the subject is empty.
1768 *
1769 * @return boolean.
1770 */
1771 // TODO: this will likely go away when composeArea.focus() is implemented
1772 // after all the widget control is moved over.
1773 public boolean isSubjectEmpty() {
1774 return TextUtils.getTrimmedLength(mSubject.getText()) == 0;
1775 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001776
Mindy Pereira181df782012-03-01 13:32:44 -08001777 /* package */
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001778 static int sendOrSaveInternal(Context context, ReplyFromAccount replyFromAccount,
1779 Message message, final Message refMessage, Spanned body, SendOrSaveCallback callback,
1780 Handler handler, boolean save, int composeMode) {
Mindy Pereira29ef1b82012-01-13 11:26:21 -08001781 ContentValues values = new ContentValues();
Mindy Pereira82cc5662012-01-09 17:29:30 -08001782
Mindy Pereirac2031972012-04-03 09:38:35 -07001783 String refMessageId = refMessage != null ? refMessage.uri.toString() : "";
1784
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001785 MessageModification.putToAddresses(values, message.getToAddresses());
1786 MessageModification.putCcAddresses(values, message.getCcAddresses());
1787 MessageModification.putBccAddresses(values, message.getBccAddresses());
Mindy Pereira82cc5662012-01-09 17:29:30 -08001788
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001789 MessageModification.putCustomFromAddress(values, message.from);
Mindy Pereira92551d02012-04-05 11:31:12 -07001790
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001791 MessageModification.putSubject(values, message.subject);
Mindy Pereira29ef1b82012-01-13 11:26:21 -08001792 String htmlBody = Html.toHtml(body);
Mindy Pereiraa544d942012-04-18 10:23:14 -07001793 String quotedText = !TextUtils.isEmpty(message.bodyText) && message.quotedTextOffset > -1
1794 && message.quotedTextOffset < message.bodyText.length() ? message.bodyText
1795 .substring(message.quotedTextOffset) : null;
Mindy Pereira29ef1b82012-01-13 11:26:21 -08001796 boolean includeQuotedText = !TextUtils.isEmpty(quotedText);
1797 StringBuilder fullBody = new StringBuilder(htmlBody);
1798 if (includeQuotedText) {
Mindy Pereirae8caf122012-03-20 15:23:31 -07001799 // HTML gets converted to text for now
1800 final String text = quotedText.toString();
1801 if (QuotedTextView.containsQuotedText(text)) {
1802 int pos = QuotedTextView.getQuotedTextOffset(text);
1803 fullBody.append(text.substring(0, pos));
Paul Westbrookffe6bb02012-03-27 11:50:12 -07001804 MessageModification.putQuoteStartPos(values, fullBody.length());
Mindy Pereira12575862012-03-21 16:30:54 -07001805 MessageModification.putForward(values, composeMode == ComposeActivity.FORWARD);
Mindy Pereirae8caf122012-03-20 15:23:31 -07001806 MessageModification.putAppendRefMessageContent(values, includeQuotedText);
Mindy Pereira29ef1b82012-01-13 11:26:21 -08001807 } else {
Mindy Pereirae8caf122012-03-20 15:23:31 -07001808 LogUtils.w(LOG_TAG, "Couldn't find quoted text");
1809 // This shouldn't happen, but just use what we have,
1810 // and don't do server-side expansion
1811 fullBody.append(text);
Mindy Pereira29ef1b82012-01-13 11:26:21 -08001812 }
1813 }
Mindy Pereira12575862012-03-21 16:30:54 -07001814 int draftType = -1;
1815 switch (composeMode) {
1816 case ComposeActivity.COMPOSE:
1817 draftType = DraftType.COMPOSE;
1818 break;
1819 case ComposeActivity.REPLY:
1820 draftType = DraftType.REPLY;
1821 break;
1822 case ComposeActivity.REPLY_ALL:
1823 draftType = DraftType.REPLY_ALL;
1824 break;
1825 case ComposeActivity.FORWARD:
1826 draftType = DraftType.FORWARD;
1827 break;
1828 }
1829 MessageModification.putDraftType(values, draftType);
Mindy Pereirac6f1e2a2012-04-04 10:33:45 -07001830 if (refMessage != null) {
1831 if (!TextUtils.isEmpty(refMessage.bodyHtml)) {
1832 MessageModification.putBodyHtml(values, fullBody.toString());
1833 }
1834 if (!TextUtils.isEmpty(refMessage.bodyText)) {
1835 MessageModification.putBody(values, Html.fromHtml(fullBody.toString()).toString());
1836 }
1837 } else {
Mindy Pereirac2031972012-04-03 09:38:35 -07001838 MessageModification.putBodyHtml(values, fullBody.toString());
Mindy Pereirac2031972012-04-03 09:38:35 -07001839 MessageModification.putBody(values, Html.fromHtml(fullBody.toString()).toString());
1840 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001841 MessageModification.putAttachments(values, message.getAttachments());
Mindy Pereira12575862012-03-21 16:30:54 -07001842 if (!TextUtils.isEmpty(refMessageId)) {
1843 MessageModification.putRefMessageId(values, refMessageId);
1844 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001845
Mindy Pereira92551d02012-04-05 11:31:12 -07001846 SendOrSaveMessage sendOrSaveMessage = new SendOrSaveMessage(replyFromAccount,
Mindy Pereira181df782012-03-01 13:32:44 -08001847 values, refMessageId, save);
1848 SendOrSaveTask sendOrSaveTask = new SendOrSaveTask(context, sendOrSaveMessage, callback);
Mindy Pereira82cc5662012-01-09 17:29:30 -08001849
Mindy Pereira181df782012-03-01 13:32:44 -08001850 callback.initializeSendOrSave(sendOrSaveTask);
Mindy Pereira82cc5662012-01-09 17:29:30 -08001851
Mindy Pereira181df782012-03-01 13:32:44 -08001852 // Do the send/save action on the specified handler to avoid possible
1853 // ANRs
1854 handler.post(sendOrSaveTask);
Mindy Pereira82cc5662012-01-09 17:29:30 -08001855
Mindy Pereira181df782012-03-01 13:32:44 -08001856 return sendOrSaveMessage.requestId();
1857 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001858
Mindy Pereira181df782012-03-01 13:32:44 -08001859 private void sendOrSave(Spanned body, boolean save, boolean showToast,
1860 boolean orientationChanged) {
1861 // Check if user is a monkey. Monkeys can compose and hit send
1862 // button but are not allowed to send anything off the device.
Paul Westbrook3ae824c2012-04-06 13:29:39 -07001863 if (ActivityManager.isUserAMonkey()) {
Mindy Pereira181df782012-03-01 13:32:44 -08001864 return;
1865 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001866
Mindy Pereira181df782012-03-01 13:32:44 -08001867 String[] to, cc, bcc;
1868 if (orientationChanged) {
1869 to = cc = bcc = new String[0];
1870 } else {
1871 to = getToAddresses();
1872 cc = getCcAddresses();
1873 bcc = getBccAddresses();
1874 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001875
Mindy Pereira181df782012-03-01 13:32:44 -08001876 SendOrSaveCallback callback = new SendOrSaveCallback() {
Mindy Pereira82cc5662012-01-09 17:29:30 -08001877 private int mRestoredRequestId;
1878
1879 public void initializeSendOrSave(SendOrSaveTask sendOrSaveTask) {
Mindy Pereira181df782012-03-01 13:32:44 -08001880 synchronized (mActiveTasks) {
1881 int numTasks = mActiveTasks.size();
1882 if (numTasks == 0) {
1883 // Start service so we won't be killed if this app is
1884 // put in the background.
1885 startService(new Intent(ComposeActivity.this, EmptyService.class));
1886 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001887
Mindy Pereira181df782012-03-01 13:32:44 -08001888 mActiveTasks.add(sendOrSaveTask);
1889 }
1890 if (sTestSendOrSaveCallback != null) {
1891 sTestSendOrSaveCallback.initializeSendOrSave(sendOrSaveTask);
1892 }
1893 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001894
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001895 public void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage,
1896 Message message) {
Mindy Pereira181df782012-03-01 13:32:44 -08001897 synchronized (mDraftLock) {
1898 mDraftId = message.id;
1899 mDraft = message;
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001900 if (sRequestMessageIdMap != null) {
1901 sRequestMessageIdMap.put(sendOrSaveMessage.requestId(), mDraftId);
1902 }
Mindy Pereira181df782012-03-01 13:32:44 -08001903 // Cache request message map, in case the process is killed
1904 saveRequestMap();
1905 }
1906 if (sTestSendOrSaveCallback != null) {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001907 sTestSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage, message);
Mindy Pereira181df782012-03-01 13:32:44 -08001908 }
1909 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001910
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001911 public Message getMessage() {
1912 synchronized (mDraftLock) {
1913 return mDraft;
1914 }
1915 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001916
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001917 public void sendOrSaveFinished(SendOrSaveTask task, boolean success) {
1918 if (success) {
1919 // Successfully sent or saved so reset change markers
1920 discardChanges();
1921 } else {
1922 // A failure happened with saving/sending the draft
1923 // TODO(pwestbro): add a better string that should be used
1924 // when failing to send or save
1925 Toast.makeText(ComposeActivity.this, R.string.send_failed, Toast.LENGTH_SHORT)
1926 .show();
1927 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001928
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001929 int numTasks;
1930 synchronized (mActiveTasks) {
1931 // Remove the task from the list of active tasks
1932 mActiveTasks.remove(task);
1933 numTasks = mActiveTasks.size();
1934 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001935
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001936 if (numTasks == 0) {
1937 // Stop service so we can be killed.
1938 stopService(new Intent(ComposeActivity.this, EmptyService.class));
1939 }
1940 if (sTestSendOrSaveCallback != null) {
1941 sTestSendOrSaveCallback.sendOrSaveFinished(task, success);
1942 }
1943 }
Mindy Pereira181df782012-03-01 13:32:44 -08001944 };
Mindy Pereira82cc5662012-01-09 17:29:30 -08001945
Mindy Pereira181df782012-03-01 13:32:44 -08001946 // Get the selected account if the from spinner has been setup.
Mindy Pereira92551d02012-04-05 11:31:12 -07001947 ReplyFromAccount selectedAccount = mReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -08001948 String fromAddress = selectedAccount.name;
1949 if (selectedAccount == null || fromAddress == null) {
1950 // We don't have either the selected account or from address,
1951 // use mAccount.
Mindy Pereira92551d02012-04-05 11:31:12 -07001952 selectedAccount = mReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -08001953 fromAddress = mAccount.name;
1954 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001955
Mindy Pereira181df782012-03-01 13:32:44 -08001956 if (mSendSaveTaskHandler == null) {
1957 HandlerThread handlerThread = new HandlerThread("Send Message Task Thread");
1958 handlerThread.start();
Mindy Pereira82cc5662012-01-09 17:29:30 -08001959
Mindy Pereira181df782012-03-01 13:32:44 -08001960 mSendSaveTaskHandler = new Handler(handlerThread.getLooper());
1961 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001962
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001963 Message msg = createMessage(mReplyFromAccount, getMode());
1964 mRequestId = sendOrSaveInternal(this, mReplyFromAccount, msg, mRefMessage, body, callback,
Mindy Pereira12575862012-03-21 16:30:54 -07001965 mSendSaveTaskHandler, save, mComposeMode);
Mindy Pereira82cc5662012-01-09 17:29:30 -08001966
Mindy Pereira181df782012-03-01 13:32:44 -08001967 if (mRecipient != null && mRecipient.equals(mAccount.name)) {
1968 mRecipient = selectedAccount.name;
1969 }
Paul Westbrookb1f573c2012-04-06 11:38:28 -07001970 setAccount(selectedAccount.account);
Mindy Pereira82cc5662012-01-09 17:29:30 -08001971
Mindy Pereira181df782012-03-01 13:32:44 -08001972 // Don't display the toast if the user is just changing the orientation,
1973 // but we still need to save the draft to the cursor because this is how we restore
1974 // the attachments when the configuration change completes.
1975 if (showToast && (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) {
1976 Toast.makeText(this, save ? R.string.message_saved : R.string.sending_message,
1977 Toast.LENGTH_LONG).show();
1978 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001979
Mindy Pereira181df782012-03-01 13:32:44 -08001980 // Need to update variables here because the send or save completes
1981 // asynchronously even though the toast shows right away.
1982 discardChanges();
1983 updateSaveUi();
Mindy Pereira82cc5662012-01-09 17:29:30 -08001984
Mindy Pereira181df782012-03-01 13:32:44 -08001985 // If we are sending, finish the activity
1986 if (!save) {
1987 finish();
1988 }
1989 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001990
Mindy Pereira181df782012-03-01 13:32:44 -08001991 /**
1992 * Save the state of the request messageid map. This allows for the Gmail
1993 * process to be killed, but and still allow for ComposeActivity instances
1994 * to be recreated correctly.
1995 */
1996 private void saveRequestMap() {
1997 // TODO: store the request map in user preferences.
1998 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001999
Mindy Pereira013194c2012-01-06 15:09:33 -08002000 public void doAttach() {
2001 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2002 i.addCategory(Intent.CATEGORY_OPENABLE);
Mindy Pereira181df782012-03-01 13:32:44 -08002003 if (android.provider.Settings.System.getInt(getContentResolver(),
2004 UIProvider.getAttachmentTypeSetting(), 0) != 0) {
Mindy Pereira013194c2012-01-06 15:09:33 -08002005 i.setType("*/*");
2006 } else {
2007 i.setType("image/*");
2008 }
2009 mAddingAttachment = true;
Mindy Pereira181df782012-03-01 13:32:44 -08002010 startActivityForResult(Intent.createChooser(i, getText(R.string.select_attachment_type)),
2011 RESULT_PICK_ATTACHMENT);
Mindy Pereira013194c2012-01-06 15:09:33 -08002012 }
2013
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08002014 private void showCcBccViews() {
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08002015 mCcBccView.show(true, true, true);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08002016 if (mCcBccButton != null) {
2017 mCcBccButton.setVisibility(View.GONE);
2018 }
2019 }
2020
Mindy Pereira326c6602012-01-04 15:32:42 -08002021 @Override
2022 public boolean onNavigationItemSelected(int position, long itemId) {
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08002023 int initialComposeMode = mComposeMode;
Mindy Pereira326c6602012-01-04 15:32:42 -08002024 if (position == ComposeActivity.REPLY) {
2025 mComposeMode = ComposeActivity.REPLY;
2026 } else if (position == ComposeActivity.REPLY_ALL) {
2027 mComposeMode = ComposeActivity.REPLY_ALL;
2028 } else if (position == ComposeActivity.FORWARD) {
2029 mComposeMode = ComposeActivity.FORWARD;
2030 }
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08002031 if (initialComposeMode != mComposeMode) {
Mindy Pereira154386a2012-01-11 13:02:33 -08002032 resetMessageForModeChange();
Mindy Pereira8eca57a2012-03-20 16:42:34 -07002033 if (mRefMessage != null) {
2034 initFromRefMessage(mComposeMode, mAccount.name);
2035 }
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08002036 }
Mindy Pereira326c6602012-01-04 15:32:42 -08002037 return true;
2038 }
2039
Mindy Pereira154386a2012-01-11 13:02:33 -08002040 private void resetMessageForModeChange() {
2041 // When switching between reply, reply all, forward,
2042 // follow the behavior of webview.
2043 // The contents of the following fields are cleared
2044 // so that they can be populated directly from the
2045 // ref message:
2046 // 1) Any recipient fields
2047 // 2) The subject
2048 mTo.setText("");
2049 mCc.setText("");
2050 mBcc.setText("");
2051 // Any edits to the subject are replaced with the original subject.
2052 mSubject.setText("");
2053
2054 // Any changes to the contents of the following fields are kept:
2055 // 1) Body
2056 // 2) Attachments
2057 // If the user made changes to attachments, keep their changes.
2058 if (!mAttachmentsChanged) {
2059 mAttachmentsView.deleteAllAttachments();
2060 }
2061 }
2062
Mindy Pereira326c6602012-01-04 15:32:42 -08002063 private class ComposeModeAdapter extends ArrayAdapter<String> {
2064
2065 private LayoutInflater mInflater;
2066
2067 public ComposeModeAdapter(Context context) {
2068 super(context, R.layout.compose_mode_item, R.id.mode, getResources()
2069 .getStringArray(R.array.compose_modes));
2070 }
2071
2072 private LayoutInflater getInflater() {
2073 if (mInflater == null) {
2074 mInflater = LayoutInflater.from(getContext());
2075 }
2076 return mInflater;
2077 }
2078
2079 @Override
2080 public View getView(int position, View convertView, ViewGroup parent) {
2081 if (convertView == null) {
2082 convertView = getInflater().inflate(R.layout.compose_mode_display_item, null);
2083 }
2084 ((TextView) convertView.findViewById(R.id.mode)).setText(getItem(position));
2085 return super.getView(position, convertView, parent);
2086 }
2087 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002088
2089 @Override
2090 public void onRespondInline(String text) {
2091 appendToBody(text, false);
2092 }
2093
2094 /**
2095 * Append text to the body of the message. If there is no existing body
2096 * text, just sets the body to text.
2097 *
2098 * @param text
2099 * @param withSignature True to append a signature.
2100 */
2101 public void appendToBody(CharSequence text, boolean withSignature) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002102 Editable bodyText = mBodyView.getEditableText();
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002103 if (bodyText != null && bodyText.length() > 0) {
2104 bodyText.append(text);
2105 } else {
2106 setBody(text, withSignature);
2107 }
2108 }
2109
2110 /**
2111 * Set the body of the message.
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002112 *
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002113 * @param text
2114 * @param withSignature True to append a signature.
2115 */
2116 public void setBody(CharSequence text, boolean withSignature) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002117 mBodyView.setText(text);
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002118 if (withSignature) {
2119 appendSignature();
2120 }
2121 }
2122
2123 private void appendSignature() {
Mindy Pereirab13917c2012-03-29 08:08:19 -07002124 String newSignature = mCachedSettings != null ? mCachedSettings.signature : null;
Mindy Pereira433b1982012-04-03 11:53:07 -07002125 boolean hasFocus = mBodyView.hasFocus();
Mindy Pereirab13917c2012-03-29 08:08:19 -07002126 if (!TextUtils.equals(newSignature, mSignature)) {
2127 mSignature = newSignature;
2128 if (!TextUtils.isEmpty(mSignature)
2129 && getSignatureStartPosition(mSignature,
2130 mBodyView.getText().toString()) < 0) {
2131 // Appending a signature does not count as changing text.
2132 mBodyView.removeTextChangedListener(this);
2133 mBodyView.append(convertToPrintableSignature(mSignature));
2134 mBodyView.addTextChangedListener(this);
2135 }
Mindy Pereira433b1982012-04-03 11:53:07 -07002136 if (hasFocus) {
2137 focusBody();
2138 }
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002139 }
2140 }
2141
2142 private String convertToPrintableSignature(String signature) {
2143 String signatureResource = getResources().getString(R.string.signature);
2144 if (signature == null) {
2145 signature = "";
2146 }
2147 return String.format(signatureResource, signature);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002148 }
Mindy Pereira1a95a572012-01-05 12:21:29 -08002149
Mindy Pereira5a85e2b2012-01-11 09:53:32 -08002150 @Override
2151 public void onAccountChanged() {
Mindy Pereira92551d02012-04-05 11:31:12 -07002152 mReplyFromAccount = mFromSpinner.getCurrentAccount();
2153 if (!mAccount.equals(mReplyFromAccount.account)) {
Paul Westbrookb1f573c2012-04-06 11:38:28 -07002154 setAccount(mReplyFromAccount.account);
2155
Mindy Pereira181df782012-03-01 13:32:44 -08002156 // TODO: handle discarding attachments when switching accounts.
2157 // Only enable save for this draft if there is any other content
2158 // in the message.
2159 if (!isBlank()) {
2160 enableSave(true);
2161 }
2162 mReplyFromChanged = true;
2163 initRecipients();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002164 }
Mindy Pereira1a95a572012-01-05 12:21:29 -08002165 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002166
2167 public void enableSave(boolean enabled) {
2168 if (mSave != null) {
2169 mSave.setEnabled(enabled);
2170 }
2171 }
2172
2173 public void enableSend(boolean enabled) {
2174 if (mSend != null) {
2175 mSend.setEnabled(enabled);
2176 }
2177 }
2178
2179 /**
2180 * Handles button clicks from any error dialogs dealing with sending
2181 * a message.
2182 */
2183 @Override
2184 public void onClick(DialogInterface dialog, int which) {
2185 switch (which) {
2186 case DialogInterface.BUTTON_POSITIVE: {
2187 doDiscardWithoutConfirmation(true /* show toast */ );
2188 break;
2189 }
2190 case DialogInterface.BUTTON_NEGATIVE: {
2191 // If the user cancels the send, re-enable the send button.
2192 enableSend(true);
2193 break;
2194 }
2195 }
2196
2197 }
2198
Mindy Pereiraefe3d252012-03-01 14:20:44 -08002199 private void doDiscard() {
2200 new AlertDialog.Builder(this).setMessage(R.string.confirm_discard_text)
2201 .setPositiveButton(R.string.ok, this)
2202 .setNegativeButton(R.string.cancel, null)
2203 .create().show();
2204 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002205 /**
2206 * Effectively discard the current message.
2207 *
2208 * This method is either invoked from the menu or from the dialog
2209 * once the user has confirmed that they want to discard the message.
2210 * @param showToast show "Message discarded" toast if true
2211 */
2212 private void doDiscardWithoutConfirmation(boolean showToast) {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002213 synchronized (mDraftLock) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002214 if (mDraftId != UIProvider.INVALID_MESSAGE_ID) {
2215 ContentValues values = new ContentValues();
Paul Westbrookb7050e62012-03-20 12:59:44 -07002216 values.put(BaseColumns._ID, mDraftId);
Mindy Pereiracfb7f332012-02-28 10:23:43 -08002217 if (mAccount.expungeMessageUri != null) {
2218 getContentResolver().update(mAccount.expungeMessageUri, values, null, null);
2219 } else {
2220 // TODO(mindyp): call delete on this conversation instead.
2221 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002222 // This is not strictly necessary (since we should not try to
2223 // save the draft after calling this) but it ensures that if we
2224 // do save again for some reason we make a new draft rather than
2225 // trying to resave an expunged draft.
2226 mDraftId = UIProvider.INVALID_MESSAGE_ID;
2227 }
2228 }
2229
2230 if (showToast) {
2231 // Display a toast to let the user know
2232 Toast.makeText(this, R.string.message_discarded, Toast.LENGTH_SHORT).show();
2233 }
2234
2235 // This prevents the draft from being saved in onPause().
2236 discardChanges();
2237 finish();
2238 }
2239
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002240 private void saveIfNeeded() {
2241 if (mAccount == null) {
2242 // We have not chosen an account yet so there's no way that we can save. This is ok,
2243 // though, since we are saving our state before AccountsActivity is activated. Thus, the
2244 // user has not interacted with us yet and there is no real state to save.
2245 return;
2246 }
2247
2248 if (shouldSave()) {
2249 doSave(!mAddingAttachment /* show toast */, true /* reset IME */);
2250 }
2251 }
2252
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002253 @Override
2254 public void onAttachmentDeleted() {
2255 mAttachmentsChanged = true;
2256 updateSaveUi();
2257 }
Mindy Pereira75f66632012-01-11 11:42:02 -08002258
2259
2260 /**
2261 * This is called any time one of our text fields changes.
2262 */
2263 public void afterTextChanged(Editable s) {
2264 mTextChanged = true;
2265 updateSaveUi();
2266 }
2267
2268 @Override
2269 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
2270 // Do nothing.
2271 }
2272
2273 public void onTextChanged(CharSequence s, int start, int before, int count) {
2274 // Do nothing.
2275 }
2276
2277
2278 // There is a big difference between the text associated with an address changing
2279 // to add the display name or to format properly and a recipient being added or deleted.
2280 // Make sure we only notify of changes when a recipient has been added or deleted.
2281 private class RecipientTextWatcher implements TextWatcher {
2282 private HashMap<String, Integer> mContent = new HashMap<String, Integer>();
2283
2284 private RecipientEditTextView mView;
2285
2286 private TextWatcher mListener;
2287
2288 public RecipientTextWatcher(RecipientEditTextView view, TextWatcher listener) {
2289 mView = view;
2290 mListener = listener;
2291 }
2292
2293 @Override
2294 public void afterTextChanged(Editable s) {
2295 if (hasChanged()) {
2296 mListener.afterTextChanged(s);
2297 }
2298 }
2299
2300 private boolean hasChanged() {
2301 String[] currRecips = tokenizeRecips(getAddressesFromList(mView));
2302 int totalCount = currRecips.length;
2303 int totalPrevCount = 0;
2304 for (Entry<String, Integer> entry : mContent.entrySet()) {
2305 totalPrevCount += entry.getValue();
2306 }
2307 if (totalCount != totalPrevCount) {
2308 return true;
2309 }
2310
2311 for (String recip : currRecips) {
2312 if (!mContent.containsKey(recip)) {
2313 return true;
2314 } else {
2315 int count = mContent.get(recip) - 1;
2316 if (count < 0) {
2317 return true;
2318 } else {
2319 mContent.put(recip, count);
2320 }
2321 }
2322 }
2323 return false;
2324 }
2325
2326 private String[] tokenizeRecips(String[] recips) {
2327 // Tokenize them all and put them in the list.
2328 String[] recipAddresses = new String[recips.length];
2329 for (int i = 0; i < recips.length; i++) {
2330 recipAddresses[i] = Rfc822Tokenizer.tokenize(recips[i])[0].getAddress();
2331 }
2332 return recipAddresses;
2333 }
2334
2335 @Override
2336 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
2337 String[] recips = tokenizeRecips(getAddressesFromList(mView));
2338 for (String recip : recips) {
2339 if (!mContent.containsKey(recip)) {
2340 mContent.put(recip, 1);
2341 } else {
2342 mContent.put(recip, (mContent.get(recip)) + 1);
2343 }
2344 }
2345 }
2346
2347 @Override
2348 public void onTextChanged(CharSequence s, int start, int before, int count) {
2349 // Do nothing.
2350 }
2351 }
Vikram Aggarwal8183d452012-04-17 09:13:29 -07002352}