blob: 1106e309335e1f36478addd882d32a2a063a8bc3 [file] [log] [blame]
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001/**
2 * Copyright (c) 2011, Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Andy Huang30e2c242012-01-06 18:14:30 -080017package com.android.mail.compose;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080018
Mindy Pereira326c6602012-01-04 15:32:42 -080019import android.app.ActionBar;
Andy Huang5c5fd572012-04-08 18:19:29 -070020import android.app.ActionBar.OnNavigationListener;
21import android.app.Activity;
Mindy Pereira82cc5662012-01-09 17:29:30 -080022import android.app.ActivityManager;
23import android.app.AlertDialog;
24import android.app.Dialog;
Mindy Pereirab199d172012-08-13 11:04:03 -070025import android.app.Fragment;
Mindy Pereirab199d172012-08-13 11:04:03 -070026import android.app.FragmentTransaction;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -070027import android.app.LoaderManager;
Mindy Pereira6349a042012-01-04 11:25:01 -080028import android.content.ContentResolver;
Mindy Pereira82cc5662012-01-09 17:29:30 -080029import android.content.ContentValues;
Mindy Pereira6349a042012-01-04 11:25:01 -080030import android.content.Context;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -070031import android.content.CursorLoader;
Mindy Pereira82cc5662012-01-09 17:29:30 -080032import android.content.DialogInterface;
Mindy Pereira6349a042012-01-04 11:25:01 -080033import android.content.Intent;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -070034import android.content.Loader;
Mindy Pereira82cc5662012-01-09 17:29:30 -080035import android.content.pm.ActivityInfo;
Mindy Pereira7ed1c112012-01-18 10:59:25 -080036import android.database.Cursor;
Mindy Pereira6349a042012-01-04 11:25:01 -080037import android.net.Uri;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080038import android.os.Bundle;
Mindy Pereira82cc5662012-01-09 17:29:30 -080039import android.os.Handler;
40import android.os.HandlerThread;
Paul Westbrookf97588b2012-03-20 11:11:37 -070041import android.os.Parcelable;
Mindy Pereira82cc5662012-01-09 17:29:30 -080042import android.provider.BaseColumns;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080043import android.text.Editable;
Mindy Pereira82cc5662012-01-09 17:29:30 -080044import android.text.Html;
mindyped9c2f02012-10-12 10:02:08 -070045import android.text.SpannableString;
Mindy Pereira82cc5662012-01-09 17:29:30 -080046import android.text.Spanned;
Paul Westbrookc1827622012-01-06 11:27:12 -080047import android.text.TextUtils;
Mindy Pereira82cc5662012-01-09 17:29:30 -080048import android.text.TextWatcher;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080049import android.text.util.Rfc822Token;
Mindy Pereirac17d0732011-12-29 10:46:19 -080050import android.text.util.Rfc822Tokenizer;
Mindy Pereira3cd4f402012-07-17 11:16:18 -070051import android.view.Gravity;
mindyp62d3ec72012-08-24 13:04:09 -070052import android.view.KeyEvent;
Mindy Pereira326c6602012-01-04 15:32:42 -080053import android.view.LayoutInflater;
Mindy Pereirab47f3e22011-12-13 14:25:04 -080054import android.view.Menu;
55import android.view.MenuInflater;
56import android.view.MenuItem;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080057import android.view.View;
58import android.view.View.OnClickListener;
Andy Huang5c5fd572012-04-08 18:19:29 -070059import android.view.ViewGroup;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -080060import android.view.inputmethod.BaseInputConnection;
mindyp62d3ec72012-08-24 13:04:09 -070061import android.view.inputmethod.EditorInfo;
Mindy Pereira326c6602012-01-04 15:32:42 -080062import android.widget.ArrayAdapter;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080063import android.widget.Button;
Mindy Pereira433b1982012-04-03 11:53:07 -070064import android.widget.EditText;
Mindy Pereira6349a042012-01-04 11:25:01 -080065import android.widget.TextView;
Mindy Pereira013194c2012-01-06 15:09:33 -080066import android.widget.Toast;
Mindy Pereira7b56a612011-12-14 12:32:28 -080067
Mindy Pereirac17d0732011-12-29 10:46:19 -080068import com.android.common.Rfc822Validator;
Andy Huang5c5fd572012-04-08 18:19:29 -070069import com.android.ex.chips.RecipientEditTextView;
70import com.android.mail.R;
mindyp40882432012-09-06 11:07:40 -070071import com.android.mail.compose.AttachmentsView.AttachmentAddedOrDeletedListener;
Mindy Pereira9932dee2012-01-10 16:09:50 -080072import com.android.mail.compose.AttachmentsView.AttachmentFailureException;
Mindy Pereira5a85e2b2012-01-11 09:53:32 -080073import com.android.mail.compose.FromAddressSpinner.OnAccountChangedListener;
Andy Huang30e2c242012-01-06 18:14:30 -080074import com.android.mail.compose.QuotedTextView.RespondInlineListener;
Mindy Pereira33fe9082012-01-09 16:24:30 -080075import com.android.mail.providers.Account;
Andy Huang30e2c242012-01-06 18:14:30 -080076import com.android.mail.providers.Address;
77import com.android.mail.providers.Attachment;
Mindy Pereira47d0e652012-07-23 09:45:07 -070078import com.android.mail.providers.MailAppProvider;
Mindy Pereira3ce64e72012-01-13 14:29:45 -080079import com.android.mail.providers.Message;
Mindy Pereira82cc5662012-01-09 17:29:30 -080080import com.android.mail.providers.MessageModification;
Mindy Pereira92551d02012-04-05 11:31:12 -070081import com.android.mail.providers.ReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -080082import com.android.mail.providers.Settings;
Andy Huang30e2c242012-01-06 18:14:30 -080083import com.android.mail.providers.UIProvider;
Mindy Pereira3ca5bad2012-04-16 11:02:42 -070084import com.android.mail.providers.UIProvider.AccountCapabilities;
Mindy Pereira12575862012-03-21 16:30:54 -070085import com.android.mail.providers.UIProvider.DraftType;
Mindy Pereirafa20c1a2012-07-23 13:00:02 -070086import com.android.mail.ui.MailActivity;
Mindy Pereirab199d172012-08-13 11:04:03 -070087import com.android.mail.ui.WaitFragment;
Mark Wei62066e42012-09-13 12:07:02 -070088import com.android.mail.ui.AttachmentTile.AttachmentPreview;
Paul Westbrook92227f62012-03-20 10:32:51 -070089import com.android.mail.utils.AccountUtils;
Mark Wei434f2942012-08-24 11:54:02 -070090import com.android.mail.utils.AttachmentUtils;
Paul Westbrookb334c902012-06-25 11:42:46 -070091import com.android.mail.utils.LogTag;
Andy Huang30e2c242012-01-06 18:14:30 -080092import com.android.mail.utils.LogUtils;
Andy Huang30e2c242012-01-06 18:14:30 -080093import com.android.mail.utils.Utils;
Mindy Pereira46ce0b12012-01-05 10:32:15 -080094import com.google.common.annotations.VisibleForTesting;
Mindy Pereira82cc5662012-01-09 17:29:30 -080095import com.google.common.collect.Lists;
Mindy Pereira4a27ea92012-01-05 15:55:25 -080096import com.google.common.collect.Sets;
Mindy Pereira8e9305e2011-12-13 14:25:04 -080097
Mindy Pereira8eca57a2012-03-20 16:42:34 -070098import java.io.UnsupportedEncodingException;
99import java.net.URLDecoder;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800100import java.util.ArrayList;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700101import java.util.Arrays;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800102import java.util.Collection;
Mindy Pereira75f66632012-01-11 11:42:02 -0800103import java.util.HashMap;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800104import java.util.HashSet;
105import java.util.List;
Paul Westbrook1c078cf2012-03-20 16:18:51 -0700106import java.util.Map.Entry;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700107import java.util.Set;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800108import java.util.concurrent.ConcurrentHashMap;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800109
110public class ComposeActivity extends Activity implements OnClickListener, OnNavigationListener,
Mindy Pereira5a85e2b2012-01-11 09:53:32 -0800111 RespondInlineListener, DialogInterface.OnClickListener, TextWatcher,
mindyp40882432012-09-06 11:07:40 -0700112 AttachmentAddedOrDeletedListener, OnAccountChangedListener, LoaderManager.LoaderCallbacks<Cursor>,
mindyp62d3ec72012-08-24 13:04:09 -0700113 TextView.OnEditorActionListener {
Mindy Pereira6349a042012-01-04 11:25:01 -0800114 // Identifiers for which type of composition this is
Mindy Pereira36bbcae2012-04-25 09:27:04 -0700115 static final int COMPOSE = -1;
116 static final int REPLY = 0;
117 static final int REPLY_ALL = 1;
118 static final int FORWARD = 2;
119 static final int EDIT_DRAFT = 3;
Mindy Pereira6349a042012-01-04 11:25:01 -0800120
121 // Integer extra holding one of the above compose action
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700122 protected static final String EXTRA_ACTION = "action";
Mindy Pereira6349a042012-01-04 11:25:01 -0800123
Mindy Pereira326689d2012-05-17 10:14:14 -0700124 private static final String EXTRA_SHOW_CC = "showCc";
125 private static final String EXTRA_SHOW_BCC = "showBcc";
Mindy Pereiraa34c9a02012-04-17 14:10:53 -0700126
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700127 private static final String UTF8_ENCODING_NAME = "UTF-8";
128
129 private static final String MAIL_TO = "mailto";
130
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700131 private static final String EXTRA_SUBJECT = "subject";
132
133 private static final String EXTRA_BODY = "body";
134
mindypd27b6ea2012-10-05 09:43:49 -0700135 protected static final String EXTRA_FROM_ACCOUNT_STRING = "fromAccountString";
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700136
Mark Wei62066e42012-09-13 12:07:02 -0700137 private static final String EXTRA_ATTACHMENT_PREVIEWS = "attachmentPreviews";
138
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700139 // Extra that we can get passed from other activities
140 private static final String EXTRA_TO = "to";
141 private static final String EXTRA_CC = "cc";
142 private static final String EXTRA_BCC = "bcc";
143
144 // List of all the fields
145 static final String[] ALL_EXTRAS = { EXTRA_SUBJECT, EXTRA_BODY, EXTRA_TO, EXTRA_CC, EXTRA_BCC };
146
Mindy Pereira82cc5662012-01-09 17:29:30 -0800147 private static SendOrSaveCallback sTestSendOrSaveCallback = null;
148 // Map containing information about requests to create new messages, and the id of the
149 // messages that were the result of those requests.
150 //
151 // This map is used when the activity that initiated the save a of a new message, is killed
152 // before the save has completed (and when we know the id of the newly created message). When
153 // a save is completed, the service that is running in the background, will update the map
154 //
155 // When a new ComposeActivity instance is created, it will attempt to use the information in
156 // the previously instantiated map. If ComposeActivity.onCreate() is called, with a bundle
157 // (restoring data from a previous instance), and the map hasn't been created, we will attempt
158 // to populate the map with data stored in shared preferences.
159 private static ConcurrentHashMap<Integer, Long> sRequestMessageIdMap = null;
160 // Key used to store the above map
161 private static final String CACHED_MESSAGE_REQUEST_IDS_KEY = "cache-message-request-ids";
Mindy Pereira6349a042012-01-04 11:25:01 -0800162 /**
163 * Notifies the {@code Activity} that the caller is an Email
164 * {@code Activity}, so that the back behavior may be modified accordingly.
165 *
166 * @see #onAppUpPressed
167 */
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700168 public static final String EXTRA_FROM_EMAIL_TASK = "fromemail";
Mindy Pereira6349a042012-01-04 11:25:01 -0800169
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700170 public static final String EXTRA_ATTACHMENTS = "attachments";
Paul Westbrookf97588b2012-03-20 11:11:37 -0700171
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800172 // If this is a reply/forward then this extra will hold the original message
Mindy Pereira36bbcae2012-04-25 09:27:04 -0700173 private static final String EXTRA_IN_REFERENCE_TO_MESSAGE = "in-reference-to-message";
Mindy Pereirab18e5a92012-07-10 11:47:21 -0700174 // If this is a reply/forward then this extra will hold a uri we must query
175 // to get the original message.
176 protected static final String EXTRA_IN_REFERENCE_TO_MESSAGE_URI = "in-reference-to-message-uri";
Mark Wei434f2942012-08-24 11:54:02 -0700177 // If this is an action to edit an existing draft message, this extra will hold the
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700178 // draft message
179 private static final String ORIGINAL_DRAFT_MESSAGE = "original-draft-message";
Mindy Pereira4a27ea92012-01-05 15:55:25 -0800180 private static final String END_TOKEN = ", ";
Paul Westbrookb334c902012-06-25 11:42:46 -0700181 private static final String LOG_TAG = LogTag.getLogTag();
Mindy Pereira013194c2012-01-06 15:09:33 -0800182 // Request numbers for activities we start
183 private static final int RESULT_PICK_ATTACHMENT = 1;
184 private static final int RESULT_CREATE_ACCOUNT = 2;
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700185 // TODO(mindyp) set mime-type for auto send?
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700186 public static final String AUTO_SEND_ACTION = "com.android.mail.action.AUTO_SEND";
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700187
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700188 private static final String EXTRA_SELECTED_REPLY_FROM_ACCOUNT = "replyFromAccount";
189 private static final String EXTRA_REQUEST_ID = "requestId";
190 private static final String EXTRA_FOCUS_SELECTION_START = "focusSelectionStart";
191 private static final String EXTRA_FOCUS_SELECTION_END = null;
192 private static final String EXTRA_MESSAGE = "extraMessage";
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700193 private static final int REFERENCE_MESSAGE_LOADER = 0;
Mindy Pereirab199d172012-08-13 11:04:03 -0700194 private static final int LOADER_ACCOUNT_CURSOR = 1;
Mindy Pereira47d0e652012-07-23 09:45:07 -0700195 private static final String EXTRA_SELECTED_ACCOUNT = "selectedAccount";
Mindy Pereirab199d172012-08-13 11:04:03 -0700196 private static final String TAG_WAIT = "wait-fragment";
Mindy Pereira2db7d4a2012-08-15 11:00:02 -0700197 private static final String MIME_TYPE_PHOTO = "image/*";
198 private static final String MIME_TYPE_VIDEO = "video/*";
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800199
Mindy Pereira82cc5662012-01-09 17:29:30 -0800200 /**
201 * A single thread for running tasks in the background.
202 */
203 private Handler mSendSaveTaskHandler = null;
Mindy Pereirac17d0732011-12-29 10:46:19 -0800204 private RecipientEditTextView mTo;
205 private RecipientEditTextView mCc;
206 private RecipientEditTextView mBcc;
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800207 private Button mCcBccButton;
208 private CcBccView mCcBccView;
Mindy Pereira7b56a612011-12-14 12:32:28 -0800209 private AttachmentsView mAttachmentsView;
Mindy Pereira33fe9082012-01-09 16:24:30 -0800210 private Account mAccount;
Mindy Pereira92551d02012-04-05 11:31:12 -0700211 private ReplyFromAccount mReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -0800212 private Settings mCachedSettings;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800213 private Rfc822Validator mValidator;
Mindy Pereira6349a042012-01-04 11:25:01 -0800214 private TextView mSubject;
215
Mindy Pereira326c6602012-01-04 15:32:42 -0800216 private ComposeModeAdapter mComposeModeAdapter;
217 private int mComposeMode = -1;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800218 private boolean mForward;
219 private String mRecipient;
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800220 private QuotedTextView mQuotedTextView;
Mindy Pereira433b1982012-04-03 11:53:07 -0700221 private EditText mBodyView;
Mindy Pereira1a95a572012-01-05 12:21:29 -0800222 private View mFromStatic;
Mindy Pereira2eb17322012-03-07 10:07:34 -0800223 private TextView mFromStaticText;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800224 private View mFromSpinnerWrapper;
Mindy Pereira1883b342012-06-20 08:34:56 -0700225 @VisibleForTesting
226 protected FromAddressSpinner mFromSpinner;
Mindy Pereira013194c2012-01-06 15:09:33 -0800227 private boolean mAddingAttachment;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800228 private boolean mAttachmentsChanged;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800229 private boolean mTextChanged;
230 private boolean mReplyFromChanged;
231 private MenuItem mSave;
232 private MenuItem mSend;
Mindy Pereira82cc5662012-01-09 17:29:30 -0800233 private AlertDialog mRecipientErrorDialog;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800234 private AlertDialog mSendConfirmDialog;
Mindy Pereirab3112a22012-06-20 12:10:03 -0700235 @VisibleForTesting
236 protected Message mRefMessage;
Mindy Pereira7ed1c112012-01-18 10:59:25 -0800237 private long mDraftId = UIProvider.INVALID_MESSAGE_ID;
238 private Message mDraft;
239 private Object mDraftLock = new Object();
mindyp93b079b2012-08-29 16:32:15 -0700240 private View mPhotoAttachmentsButton;
241 private View mVideoAttachmentsButton;
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800242
Mindy Pereira326c6602012-01-04 15:32:42 -0800243 /**
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700244 * Boolean indicating whether ComposeActivity was launched from a Gmail controlled view.
245 */
246 private boolean mLaunchedFromEmail = false;
Mindy Pereiracbfb75a2012-06-25 14:52:23 -0700247 private RecipientTextWatcher mToListener;
248 private RecipientTextWatcher mCcListener;
249 private RecipientTextWatcher mBccListener;
Mindy Pereirab18e5a92012-07-10 11:47:21 -0700250 private Uri mRefMessageUri;
Mindy Pereirab199d172012-08-13 11:04:03 -0700251 private Bundle mSavedInstanceState;
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700252
253
254 /**
Mindy Pereira326c6602012-01-04 15:32:42 -0800255 * Can be called from a non-UI thread.
256 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800257 public static void editDraft(Context launcher, Account account, Message message) {
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700258 launch(launcher, account, message, EDIT_DRAFT);
Mindy Pereira326c6602012-01-04 15:32:42 -0800259 }
260
Mindy Pereira6349a042012-01-04 11:25:01 -0800261 /**
262 * Can be called from a non-UI thread.
263 */
Mindy Pereira33fe9082012-01-09 16:24:30 -0800264 public static void compose(Context launcher, Account account) {
Mindy Pereira6349a042012-01-04 11:25:01 -0800265 launch(launcher, account, null, COMPOSE);
266 }
267
268 /**
269 * Can be called from a non-UI thread.
270 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800271 public static void reply(Context launcher, Account account, Message message) {
272 launch(launcher, account, message, REPLY);
Mindy Pereira6349a042012-01-04 11:25:01 -0800273 }
274
275 /**
276 * Can be called from a non-UI thread.
277 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800278 public static void replyAll(Context launcher, Account account, Message message) {
279 launch(launcher, account, message, REPLY_ALL);
Mindy Pereira6349a042012-01-04 11:25:01 -0800280 }
281
282 /**
283 * Can be called from a non-UI thread.
284 */
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800285 public static void forward(Context launcher, Account account, Message message) {
286 launch(launcher, account, message, FORWARD);
Mindy Pereira6349a042012-01-04 11:25:01 -0800287 }
288
Mindy Pereira3ce64e72012-01-13 14:29:45 -0800289 private static void launch(Context launcher, Account account, Message message, int action) {
Mindy Pereira6349a042012-01-04 11:25:01 -0800290 Intent intent = new Intent(launcher, ComposeActivity.class);
291 intent.putExtra(EXTRA_FROM_EMAIL_TASK, true);
292 intent.putExtra(EXTRA_ACTION, action);
293 intent.putExtra(Utils.EXTRA_ACCOUNT, account);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700294 if (action == EDIT_DRAFT) {
295 intent.putExtra(ORIGINAL_DRAFT_MESSAGE, message);
296 } else {
297 intent.putExtra(EXTRA_IN_REFERENCE_TO_MESSAGE, message);
298 }
Mindy Pereira6349a042012-01-04 11:25:01 -0800299 launcher.startActivity(intent);
300 }
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800301
302 @Override
303 public void onCreate(Bundle savedInstanceState) {
304 super.onCreate(savedInstanceState);
Mindy Pereira3528d362012-01-05 14:39:44 -0800305 setContentView(R.layout.compose);
Mindy Pereirab199d172012-08-13 11:04:03 -0700306 mSavedInstanceState = savedInstanceState;
307 checkValidAccounts();
308 }
309
310 private void finishCreate() {
311 Bundle savedInstanceState = mSavedInstanceState;
Mindy Pereira3528d362012-01-05 14:39:44 -0800312 findViews();
Mindy Pereira818143e2012-01-11 13:59:49 -0800313 Intent intent = getIntent();
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700314 Message message;
Mark Wei62066e42012-09-13 12:07:02 -0700315 ArrayList<AttachmentPreview> previews;
Mindy Pereira71c9e562012-05-17 11:01:02 -0700316 boolean showQuotedText = false;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700317 int action;
Mindy Pereira47d0e652012-07-23 09:45:07 -0700318 // Check for any of the possibly supplied accounts.;
319 Account account = null;
Mindy Pereiraf7fc6c32012-06-19 15:18:33 -0700320 if (hadSavedInstanceStateMessage(savedInstanceState)) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700321 action = savedInstanceState.getInt(EXTRA_ACTION, COMPOSE);
322 account = savedInstanceState.getParcelable(Utils.EXTRA_ACCOUNT);
323 message = (Message) savedInstanceState.getParcelable(EXTRA_MESSAGE);
Mark Wei62066e42012-09-13 12:07:02 -0700324
325 previews = savedInstanceState.getParcelableArrayList(EXTRA_ATTACHMENT_PREVIEWS);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700326 mRefMessage = (Message) savedInstanceState.getParcelable(EXTRA_IN_REFERENCE_TO_MESSAGE);
327 } else {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700328 account = obtainAccount(intent);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700329 action = intent.getIntExtra(EXTRA_ACTION, COMPOSE);
330 // Initialize the message from the message in the intent
331 message = (Message) intent.getParcelableExtra(ORIGINAL_DRAFT_MESSAGE);
Mark Wei62066e42012-09-13 12:07:02 -0700332 previews = intent.getParcelableArrayListExtra(EXTRA_ATTACHMENT_PREVIEWS);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700333 mRefMessage = (Message) intent.getParcelableExtra(EXTRA_IN_REFERENCE_TO_MESSAGE);
Mindy Pereirab18e5a92012-07-10 11:47:21 -0700334 mRefMessageUri = (Uri) intent.getParcelableExtra(EXTRA_IN_REFERENCE_TO_MESSAGE_URI);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700335 }
Mark Wei62066e42012-09-13 12:07:02 -0700336 mAttachmentsView.setAttachmentPreviews(previews);
Paul Westbrook92227f62012-03-20 10:32:51 -0700337
338 setAccount(account);
Mindy Pereira818143e2012-01-11 13:59:49 -0800339 if (mAccount == null) {
340 return;
341 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700342
Paul Westbrookdaecb4b2012-05-31 10:21:26 -0700343 if (intent.getBooleanExtra(EXTRA_FROM_EMAIL_TASK, false)) {
344 mLaunchedFromEmail = true;
345 } else if (Intent.ACTION_SEND.equals(intent.getAction())) {
346 final Uri dataUri = intent.getData();
347 if (dataUri != null) {
348 final String dataScheme = intent.getData().getScheme();
349 final String accountScheme = mAccount.composeIntentUri.getScheme();
350 mLaunchedFromEmail = TextUtils.equals(dataScheme, accountScheme);
351 }
352 }
353
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700354 if (mRefMessageUri != null) {
355 // We have a referenced message that we must look up.
356 getLoaderManager().initLoader(REFERENCE_MESSAGE_LOADER, null, this);
357 return;
358 } else if (message != null && action != EDIT_DRAFT) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700359 initFromDraftMessage(message);
360 initQuotedTextFromRefMessage(mRefMessage, action);
Mindy Pereiraa34c9a02012-04-17 14:10:53 -0700361 showCcBcc(savedInstanceState);
Mindy Pereira71c9e562012-05-17 11:01:02 -0700362 showQuotedText = message.appendRefMessageContent;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700363 } else if (action == EDIT_DRAFT) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700364 initFromDraftMessage(message);
Mindy Pereiraef388302012-06-18 19:07:44 -0700365 boolean showBcc = !TextUtils.isEmpty(message.bcc);
366 boolean showCc = showBcc || !TextUtils.isEmpty(message.cc);
367 mCcBccView.show(false, showCc, showBcc);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700368 // Update the action to the draft type of the previous draft
369 switch (message.draftType) {
370 case UIProvider.DraftType.REPLY:
371 action = REPLY;
372 break;
373 case UIProvider.DraftType.REPLY_ALL:
374 action = REPLY_ALL;
375 break;
376 case UIProvider.DraftType.FORWARD:
377 action = FORWARD;
378 break;
379 case UIProvider.DraftType.COMPOSE:
380 default:
381 action = COMPOSE;
382 break;
383 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700384 initQuotedTextFromRefMessage(mRefMessage, action);
Mindy Pereira71c9e562012-05-17 11:01:02 -0700385 showQuotedText = message.appendRefMessageContent;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700386 } else if ((action == REPLY || action == REPLY_ALL || action == FORWARD)) {
387 if (mRefMessage != null) {
388 initFromRefMessage(action, mAccount.name);
Mindy Pereira71c9e562012-05-17 11:01:02 -0700389 showQuotedText = true;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700390 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -0700391 } else {
392 initFromExtras(intent);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700393 }
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700394 finishSetup(action, intent, savedInstanceState, showQuotedText);
395 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700396
Mindy Pereirab199d172012-08-13 11:04:03 -0700397 private void checkValidAccounts() {
398 mAccounts = AccountUtils.getAccounts(this);
399 if (mAccounts == null || mAccounts.length == 0) {
400 final Intent noAccountIntent = MailAppProvider.getNoAccountIntent(this);
401 if (noAccountIntent != null) {
402 startActivityForResult(noAccountIntent, RESULT_CREATE_ACCOUNT);
403 }
404 } else {
mindyp26d4d2d2012-09-18 17:30:32 -0700405 // If none of the accounts are syncing, setup a watcher.
Mindy Pereirab199d172012-08-13 11:04:03 -0700406 boolean anySyncing = false;
407 for (Account a : mAccounts) {
Paul Westbrookdfa1dec2012-09-26 16:27:28 -0700408 if (a.isAccountReady()) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700409 anySyncing = true;
410 break;
411 }
412 }
413 if (!anySyncing) {
414 // There are accounts, but none are sync'd, which is just like having no accounts.
415 mAccounts = null;
416 getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, null, this);
417 return;
418 }
419 finishCreate();
420 }
421 }
422
Mindy Pereira47d0e652012-07-23 09:45:07 -0700423 private Account obtainAccount(Intent intent) {
424 Account account = null;
425 Object accountExtra = null;
426 if (intent != null && intent.getExtras() != null) {
427 accountExtra = intent.getExtras().get(Utils.EXTRA_ACCOUNT);
428 if (accountExtra instanceof Account) {
429 return (Account) accountExtra;
mindyp7ae042e2012-08-27 13:27:37 -0700430 } else if (accountExtra instanceof String) {
431 // This is the Account attached to the widget compose intent.
432 account = Account.newinstance((String)accountExtra);
433 if (account != null) {
434 return account;
435 }
Mindy Pereira47d0e652012-07-23 09:45:07 -0700436 }
437 accountExtra = intent.getStringExtra(EXTRA_SELECTED_ACCOUNT);
438 }
439 if (account == null) {
mindyp06174462012-10-12 09:11:27 -0700440 MailAppProvider provider = MailAppProvider.getInstance();
441 String lastAccountUri = provider.getLastSentFromAccount();
442 if (TextUtils.isEmpty(lastAccountUri)) {
443 lastAccountUri = provider.getLastViewedAccount();
444 }
Mindy Pereira47d0e652012-07-23 09:45:07 -0700445 if (!TextUtils.isEmpty(lastAccountUri)) {
446 accountExtra = Uri.parse(lastAccountUri);
447 }
448 }
Mindy Pereirab199d172012-08-13 11:04:03 -0700449 if (mAccounts != null && mAccounts.length > 0) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700450 if (accountExtra instanceof String && !TextUtils.isEmpty((String) accountExtra)) {
451 // For backwards compatibility, we need to check account
452 // names.
Mindy Pereirab199d172012-08-13 11:04:03 -0700453 for (Account a : mAccounts) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700454 if (a.name.equals(accountExtra)) {
455 account = a;
456 }
457 }
458 } else if (accountExtra instanceof Uri) {
459 // The uri of the last viewed account is what is stored in
460 // the current code base.
Mindy Pereirab199d172012-08-13 11:04:03 -0700461 for (Account a : mAccounts) {
Mindy Pereira47d0e652012-07-23 09:45:07 -0700462 if (a.uri.equals(accountExtra)) {
463 account = a;
464 }
465 }
Mindy Pereirab199d172012-08-13 11:04:03 -0700466 }
467 if (account == null) {
468 account = mAccounts[0];
Mindy Pereira47d0e652012-07-23 09:45:07 -0700469 }
470 }
471 return account;
472 }
473
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700474 private void finishSetup(int action, Intent intent, Bundle savedInstanceState,
475 boolean showQuotedText) {
Paul Westbrookbb87b7f2012-03-20 16:20:07 -0700476 if (action == COMPOSE) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800477 mQuotedTextView.setVisibility(View.GONE);
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800478 }
Mindy Pereira818143e2012-01-11 13:59:49 -0800479 initRecipients();
Mindy Pereiraf7fc6c32012-06-19 15:18:33 -0700480 // Don't bother with the intent if we have procured a message from the
481 // intent already.
482 if (!hadSavedInstanceStateMessage(savedInstanceState)) {
483 initAttachmentsFromIntent(intent);
484 }
Mindy Pereira1a95a572012-01-05 12:21:29 -0800485 initActionBar(action);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700486 initFromSpinner(savedInstanceState != null ? savedInstanceState : intent.getExtras(),
487 action);
Mindy Pereira75f66632012-01-11 11:42:02 -0800488 initChangeListeners();
Mindy Pereira433b1982012-04-03 11:53:07 -0700489 setFocus(action);
Mindy Pereira326689d2012-05-17 10:14:14 -0700490 updateHideOrShowCcBcc();
Mindy Pereira71c9e562012-05-17 11:01:02 -0700491 updateHideOrShowQuotedText(showQuotedText);
492 }
493
Mindy Pereiraf7fc6c32012-06-19 15:18:33 -0700494 private boolean hadSavedInstanceStateMessage(Bundle savedInstanceState) {
495 return savedInstanceState != null && savedInstanceState.containsKey(EXTRA_MESSAGE);
496 }
497
Mindy Pereira71c9e562012-05-17 11:01:02 -0700498 private void updateHideOrShowQuotedText(boolean showQuotedText) {
499 mQuotedTextView.updateCheckedState(showQuotedText);
mindyp40882432012-09-06 11:07:40 -0700500 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
Mindy Pereira433b1982012-04-03 11:53:07 -0700501 }
502
503 private void setFocus(int action) {
504 if (action == EDIT_DRAFT) {
505 int type = mDraft.draftType;
506 switch (type) {
507 case UIProvider.DraftType.COMPOSE:
508 case UIProvider.DraftType.FORWARD:
509 action = COMPOSE;
510 break;
511 case UIProvider.DraftType.REPLY:
512 case UIProvider.DraftType.REPLY_ALL:
513 default:
514 action = REPLY;
515 break;
516 }
517 }
518 switch (action) {
519 case FORWARD:
520 case COMPOSE:
521 mTo.requestFocus();
522 break;
523 case REPLY:
524 case REPLY_ALL:
525 default:
526 focusBody();
527 break;
528 }
529 }
530
531 /**
532 * Focus the body of the message.
533 */
534 public void focusBody() {
535 mBodyView.requestFocus();
536 int length = mBodyView.getText().length();
537
538 int signatureStartPos = getSignatureStartPosition(
539 mSignature, mBodyView.getText().toString());
540 if (signatureStartPos > -1) {
541 // In case the user deleted the newlines...
542 mBodyView.setSelection(signatureStartPos);
mindyp8743cfc2012-09-18 13:29:08 -0700543 } else if (length >= 0) {
Mindy Pereira433b1982012-04-03 11:53:07 -0700544 // Move cursor to the end.
545 mBodyView.setSelection(length);
546 }
Mindy Pereira1a95a572012-01-05 12:21:29 -0800547 }
548
549 @Override
550 protected void onResume() {
551 super.onResume();
552 // Update the from spinner as other accounts
553 // may now be available.
Mindy Pereira818143e2012-01-11 13:59:49 -0800554 if (mFromSpinner != null && mAccount != null) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700555 mFromSpinner.asyncInitFromSpinner(mComposeMode, mAccount, mAccounts);
Mindy Pereira818143e2012-01-11 13:59:49 -0800556 }
Mindy Pereira1a95a572012-01-05 12:21:29 -0800557 }
558
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800559 @Override
560 protected void onPause() {
561 super.onPause();
562
563 if (mSendConfirmDialog != null) {
564 mSendConfirmDialog.dismiss();
565 }
566 if (mRecipientErrorDialog != null) {
567 mRecipientErrorDialog.dismiss();
568 }
Mindy Pereiraa2148332012-07-02 13:54:14 -0700569 // When the user exits the compose view, see if this draft needs saving.
Yorke Lee3d7048e2012-09-19 14:19:25 -0700570 // Don't save unnecessary drafts if we are only changing the orientation.
571 if (!isChangingConfigurations()) {
Mindy Pereiraa2148332012-07-02 13:54:14 -0700572 saveIfNeeded();
573 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800574 }
575
576 @Override
577 protected final void onActivityResult(int request, int result, Intent data) {
Mindy Pereirab199d172012-08-13 11:04:03 -0700578 if (request == RESULT_PICK_ATTACHMENT && result == RESULT_OK) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800579 addAttachmentAndUpdateView(data);
Mindy Pereirab199d172012-08-13 11:04:03 -0700580 mAddingAttachment = false;
581 } else if (request == RESULT_CREATE_ACCOUNT) {
582 // We were waiting for the user to create an account
583 if (result != RESULT_OK) {
584 finish();
585 } else {
586 // Watch for accounts to show up!
587 // restart the loader to get the updated list of accounts
588 getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, null, this);
589 showWaitFragment(null);
590 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800591 }
592 }
593
594 @Override
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700595 public final void onRestoreInstanceState(Bundle savedInstanceState) {
596 super.onRestoreInstanceState(savedInstanceState);
597 if (savedInstanceState != null) {
598 if (savedInstanceState.containsKey(EXTRA_FOCUS_SELECTION_START)) {
599 int selectionStart = savedInstanceState.getInt(EXTRA_FOCUS_SELECTION_START);
600 int selectionEnd = savedInstanceState.getInt(EXTRA_FOCUS_SELECTION_END);
601 // There should be a focus and it should be an EditText since we
602 // only save these extras if these conditions are true.
603 EditText focusEditText = (EditText) getCurrentFocus();
604 final int length = focusEditText.getText().length();
605 if (selectionStart < length && selectionEnd < length) {
606 focusEditText.setSelection(selectionStart, selectionEnd);
607 }
608 }
609 }
610 }
611
612 @Override
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800613 public final void onSaveInstanceState(Bundle state) {
614 super.onSaveInstanceState(state);
Mindy Pereirab199d172012-08-13 11:04:03 -0700615 // We have no accounts so there is nothing to compose, and therefore, nothing to save.
616 if (mAccounts == null || mAccounts.length == 0) {
617 return;
618 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700619 // The framework is happy to save and restore the selection but only if it also saves and
620 // restores the contents of the edit text. That's a lot of text to put in a bundle so we do
621 // this manually.
622 View focus = getCurrentFocus();
623 if (focus != null && focus instanceof EditText) {
624 EditText focusEditText = (EditText) focus;
625 state.putInt(EXTRA_FOCUS_SELECTION_START, focusEditText.getSelectionStart());
626 state.putInt(EXTRA_FOCUS_SELECTION_END, focusEditText.getSelectionEnd());
627 }
Paul Westbrook6273e962012-04-23 10:44:15 -0700628
629 final List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
Paul Westbrook151f1ad2012-04-24 09:13:00 -0700630 final int selectedPos = mFromSpinner.getSelectedItemPosition();
Mindy Pereirad90f7ac2012-06-27 10:31:06 -0700631 final ReplyFromAccount selectedReplyFromAccount = (replyFromAccounts != null
632 && replyFromAccounts.size() > 0 && replyFromAccounts.size() > selectedPos) ?
633 replyFromAccounts.get(selectedPos) : null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700634 if (selectedReplyFromAccount != null) {
635 state.putString(EXTRA_SELECTED_REPLY_FROM_ACCOUNT, selectedReplyFromAccount.serialize()
636 .toString());
637 state.putParcelable(Utils.EXTRA_ACCOUNT, selectedReplyFromAccount.account);
638 } else {
639 state.putParcelable(Utils.EXTRA_ACCOUNT, mAccount);
640 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800641
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700642 if (mDraftId == UIProvider.INVALID_MESSAGE_ID && mRequestId !=0) {
643 // We don't have a draft id, and we have a request id,
644 // save the request id.
645 state.putInt(EXTRA_REQUEST_ID, mRequestId);
646 }
647
648 // We want to restore the current mode after a pause
649 // or rotation.
650 int mode = getMode();
651 state.putInt(EXTRA_ACTION, mode);
652
653 Message message = createMessage(selectedReplyFromAccount, mode);
654 state.putParcelable(EXTRA_MESSAGE, message);
655
656 if (mRefMessage != null) {
657 state.putParcelable(EXTRA_IN_REFERENCE_TO_MESSAGE, mRefMessage);
658 }
Mindy Pereira326689d2012-05-17 10:14:14 -0700659 state.putBoolean(EXTRA_SHOW_CC, mCcBccView.isCcVisible());
660 state.putBoolean(EXTRA_SHOW_BCC, mCcBccView.isBccVisible());
Mark Wei62066e42012-09-13 12:07:02 -0700661
662 state.putParcelableArrayList(
663 EXTRA_ATTACHMENT_PREVIEWS, mAttachmentsView.getAttachmentPreviews());
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700664 }
665
666 private int getMode() {
667 int mode = ComposeActivity.COMPOSE;
668 ActionBar actionBar = getActionBar();
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700669 if (actionBar != null
670 && actionBar.getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST) {
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700671 mode = actionBar.getSelectedNavigationIndex();
672 }
673 return mode;
674 }
675
676 private Message createMessage(ReplyFromAccount selectedReplyFromAccount, int mode) {
677 Message message = new Message();
678 message.id = UIProvider.INVALID_MESSAGE_ID;
Andy Huangd47877e2012-08-09 19:31:24 -0700679 message.serverId = null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700680 message.uri = null;
681 message.conversationUri = null;
682 message.subject = mSubject.getText().toString();
683 message.snippet = null;
Mindy Pereira1eedc752012-07-16 16:34:41 -0700684 message.from = selectedReplyFromAccount != null ? selectedReplyFromAccount.address
Mindy Pereirab67aa8f2012-07-11 15:09:06 -0700685 : mAccount != null ? mAccount.name : null;
Mindy Pereira3c911582012-08-09 16:59:09 -0700686 message.to = formatSenders(mTo.getText().toString());
687 message.cc = formatSenders(mCc.getText().toString());
688 message.bcc = formatSenders(mBcc.getText().toString());
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700689 message.replyTo = null;
690 message.dateReceivedMs = 0;
mindyped9c2f02012-10-12 10:02:08 -0700691 String htmlBody = Html.toHtml(new SpannableString(mBodyView.getText().toString()));
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700692 StringBuilder fullBody = new StringBuilder(htmlBody);
693 message.bodyHtml = fullBody.toString();
694 message.bodyText = mBodyView.getText().toString();
695 message.embedsExternalResources = false;
696 message.refMessageId = mRefMessage != null ? mRefMessage.uri.toString() : null;
Mindy Pereirad2bef8b2012-05-30 12:14:52 -0700697 message.draftType = getDraftType(mode);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700698 message.appendRefMessageContent = mQuotedTextView.getQuotedTextIfIncluded() != null;
699 ArrayList<Attachment> attachments = mAttachmentsView.getAttachments();
700 message.hasAttachments = attachments != null && attachments.size() > 0;
701 message.attachmentListUri = null;
702 message.messageFlags = 0;
703 message.saveUri = null;
704 message.sendUri = null;
705 message.alwaysShowImages = false;
706 message.attachmentsJson = Attachment.toJSONArray(attachments);
707 CharSequence quotedText = mQuotedTextView.getQuotedText();
708 message.quotedTextOffset = !TextUtils.isEmpty(quotedText) ? QuotedTextView
709 .getQuotedTextOffset(quotedText.toString()) : -1;
710 message.accountUri = null;
711 return message;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800712 }
713
Mindy Pereira3c911582012-08-09 16:59:09 -0700714 private String formatSenders(String string) {
715 if (!TextUtils.isEmpty(string) && string.charAt(string.length() - 1) == ',') {
716 return string.substring(0, string.length() - 1);
717 }
718 return string;
719 }
720
Mindy Pereira818143e2012-01-11 13:59:49 -0800721 @VisibleForTesting
722 void setAccount(Account account) {
Mindy Pereirabb5217e2012-04-17 11:08:29 -0700723 if (account == null) {
724 return;
725 }
Mindy Pereira23e9fde2012-03-20 15:08:24 -0700726 if (!account.equals(mAccount)) {
727 mAccount = account;
Paul Westbrookb1f573c2012-04-06 11:38:28 -0700728 mCachedSettings = mAccount.settings;
729 appendSignature();
Mindy Pereira23e9fde2012-03-20 15:08:24 -0700730 }
Mindy Pereirafa20c1a2012-07-23 13:00:02 -0700731 if (mAccount != null) {
732 MailActivity.setForegroundNdef(MailActivity.getMailtoNdef(mAccount.name));
733 }
Mindy Pereira818143e2012-01-11 13:59:49 -0800734 }
735
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700736 private void initFromSpinner(Bundle bundle, int action) {
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700737 String accountString = null;
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700738 if (action == EDIT_DRAFT && mDraft.draftType == UIProvider.DraftType.COMPOSE) {
Mindy Pereira62de1b12012-04-06 12:17:56 -0700739 action = COMPOSE;
740 }
Mindy Pereirab199d172012-08-13 11:04:03 -0700741 mFromSpinner.asyncInitFromSpinner(action, mAccount, mAccounts);
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700742 if (bundle != null) {
743 if (bundle.containsKey(EXTRA_SELECTED_REPLY_FROM_ACCOUNT)) {
744 mReplyFromAccount = ReplyFromAccount.deserialize(mAccount,
745 bundle.getString(EXTRA_SELECTED_REPLY_FROM_ACCOUNT));
746 } else if (bundle.containsKey(EXTRA_FROM_ACCOUNT_STRING)) {
747 accountString = bundle.getString(EXTRA_FROM_ACCOUNT_STRING);
748 mReplyFromAccount = mFromSpinner.getMatchingReplyFromAccount(accountString);
749 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700750 }
751 if (mReplyFromAccount == null) {
752 if (mDraft != null) {
753 mReplyFromAccount = getReplyFromAccountFromDraft(mAccount, mDraft);
754 } else if (mRefMessage != null) {
755 mReplyFromAccount = getReplyFromAccountForReply(mAccount, mRefMessage);
756 }
Mindy Pereira62de1b12012-04-06 12:17:56 -0700757 }
758 if (mReplyFromAccount == null) {
759 mReplyFromAccount = new ReplyFromAccount(mAccount, mAccount.uri, mAccount.name,
Mindy Pereiracd970dd2012-05-31 10:07:47 -0700760 mAccount.name, mAccount.name, true, false);
Mindy Pereira62de1b12012-04-06 12:17:56 -0700761 }
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700762
Mindy Pereira62de1b12012-04-06 12:17:56 -0700763 mFromSpinner.setCurrentAccount(mReplyFromAccount);
Mindy Pereira9a42bb42012-04-18 15:21:33 -0700764
Mindy Pereira62de1b12012-04-06 12:17:56 -0700765 if (mFromSpinner.getCount() > 1) {
Mindy Pereiraa83e7082012-03-30 08:53:11 -0700766 // If there is only 1 account, just show that account.
767 // Otherwise, give the user the ability to choose which account to
Mindy Pereira62de1b12012-04-06 12:17:56 -0700768 // send mail from / save drafts to.
769 mFromStatic.setVisibility(View.GONE);
Mindy Pereiraa83e7082012-03-30 08:53:11 -0700770 mFromStaticText.setText(mAccount.name);
Mindy Pereira62de1b12012-04-06 12:17:56 -0700771 mFromSpinnerWrapper.setVisibility(View.VISIBLE);
Mindy Pereiraa83e7082012-03-30 08:53:11 -0700772 } else {
773 mFromStatic.setVisibility(View.VISIBLE);
774 mFromStaticText.setText(mAccount.name);
775 mFromSpinnerWrapper.setVisibility(View.GONE);
Mindy Pereiraa83e7082012-03-30 08:53:11 -0700776 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800777 }
778
Mindy Pereira62de1b12012-04-06 12:17:56 -0700779 private ReplyFromAccount getReplyFromAccountForReply(Account account, Message refMessage) {
780 if (refMessage.accountUri != null) {
781 // This must be from combined inbox.
782 List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
783 for (ReplyFromAccount from : replyFromAccounts) {
784 if (from.account.uri.equals(refMessage.accountUri)) {
785 return from;
786 }
787 }
788 return null;
789 } else {
790 return getReplyFromAccount(account, refMessage);
791 }
792 }
793
794 /**
795 * Given an account and which email address the message was sent to,
796 * return who the message should be sent from.
797 * @param account Account in which the message arrived.
798 * @param sentTo Email address to which the message was sent.
799 * @return the address from which to reply.
800 */
801 public ReplyFromAccount getReplyFromAccount(Account account, Message refMessage) {
802 // First see if we are supposed to use the default address or
803 // the address it was sentTo.
Mindy Pereira326689d2012-05-17 10:14:14 -0700804 if (mCachedSettings.forceReplyFromDefault) {
Mindy Pereira62de1b12012-04-06 12:17:56 -0700805 return getDefaultReplyFromAccount(account);
806 } else {
Mindy Pereira89bae572012-06-18 11:34:36 -0700807 // If we aren't explicitly told which account to look for, look at
Mindy Pereira62de1b12012-04-06 12:17:56 -0700808 // all the message recipients and find one that matches
809 // a custom from or account.
810 List<String> allRecipients = new ArrayList<String>();
mindyp5ed63112012-09-17 17:31:45 -0700811 allRecipients.addAll(Arrays.asList(refMessage.getToAddresses()));
812 allRecipients.addAll(Arrays.asList(refMessage.getCcAddresses()));
Mindy Pereira62de1b12012-04-06 12:17:56 -0700813 return getMatchingRecipient(account, allRecipients);
814 }
815 }
816
817 /**
818 * Compare all the recipients of an email to the current account and all
819 * custom addresses associated with that account. Return the match if there
820 * is one, or the default account if there isn't.
821 */
822 protected ReplyFromAccount getMatchingRecipient(Account account, List<String> sentTo) {
823 // Tokenize the list and place in a hashmap.
824 ReplyFromAccount matchingReplyFrom = null;
825 Rfc822Token[] tokens;
826 HashSet<String> recipientsMap = new HashSet<String>();
827 for (String address : sentTo) {
828 tokens = Rfc822Tokenizer.tokenize(address);
829 for (int i = 0; i < tokens.length; i++) {
830 recipientsMap.add(tokens[i].getAddress());
831 }
832 }
833
834 int matchingAddressCount = 0;
835 List<ReplyFromAccount> customFroms;
Andy Huang16174812012-08-16 16:40:35 -0700836 customFroms = account.getReplyFroms();
837 if (customFroms != null) {
838 for (ReplyFromAccount entry : customFroms) {
839 if (recipientsMap.contains(entry.address)) {
840 matchingReplyFrom = entry;
841 matchingAddressCount++;
Mindy Pereira62de1b12012-04-06 12:17:56 -0700842 }
843 }
Mindy Pereira62de1b12012-04-06 12:17:56 -0700844 }
845 if (matchingAddressCount > 1) {
846 matchingReplyFrom = getDefaultReplyFromAccount(account);
847 }
848 return matchingReplyFrom;
849 }
850
851 private ReplyFromAccount getDefaultReplyFromAccount(Account account) {
852 List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
853 for (ReplyFromAccount from : replyFromAccounts) {
854 if (from.isDefault) {
855 return from;
856 }
857 }
Mindy Pereiracd970dd2012-05-31 10:07:47 -0700858 return new ReplyFromAccount(account, account.uri, account.name, account.name, account.name,
859 true, false);
Mindy Pereira62de1b12012-04-06 12:17:56 -0700860 }
861
Mindy Pereirae8f94dc2012-04-16 11:56:21 -0700862 private ReplyFromAccount getReplyFromAccountFromDraft(Account account, Message msg) {
863 String sender = msg.from;
Mindy Pereira62de1b12012-04-06 12:17:56 -0700864 ReplyFromAccount replyFromAccount = null;
865 List<ReplyFromAccount> replyFromAccounts = mFromSpinner.getReplyFromAccounts();
866 if (TextUtils.equals(account.name, sender)) {
867 replyFromAccount = new ReplyFromAccount(mAccount, mAccount.uri, mAccount.name,
Mindy Pereiracd970dd2012-05-31 10:07:47 -0700868 mAccount.name, mAccount.name, true, false);
Mindy Pereira62de1b12012-04-06 12:17:56 -0700869 } else {
870 for (ReplyFromAccount fromAccount : replyFromAccounts) {
871 if (TextUtils.equals(fromAccount.name, sender)) {
872 replyFromAccount = fromAccount;
873 break;
874 }
875 }
876 }
877 return replyFromAccount;
878 }
879
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800880 private void findViews() {
Mindy Pereirab199d172012-08-13 11:04:03 -0700881 findViewById(R.id.compose).setVisibility(View.VISIBLE);
Mindy Pereiraa26b54e2012-01-06 12:54:33 -0800882 mCcBccButton = (Button) findViewById(R.id.add_cc_bcc);
Mindy Pereira8e9305e2011-12-13 14:25:04 -0800883 if (mCcBccButton != null) {
884 mCcBccButton.setOnClickListener(this);
885 }
886 mCcBccView = (CcBccView) findViewById(R.id.cc_bcc_wrapper);
Mindy Pereira7b56a612011-12-14 12:32:28 -0800887 mAttachmentsView = (AttachmentsView)findViewById(R.id.attachments);
mindyp93b079b2012-08-29 16:32:15 -0700888 mPhotoAttachmentsButton = findViewById(R.id.add_photo_attachment);
mindypcd0b0b92012-08-23 14:33:17 -0700889 if (mPhotoAttachmentsButton != null) {
890 mPhotoAttachmentsButton.setOnClickListener(this);
891 }
mindyp93b079b2012-08-29 16:32:15 -0700892 mVideoAttachmentsButton = findViewById(R.id.add_video_attachment);
mindypcd0b0b92012-08-23 14:33:17 -0700893 if (mVideoAttachmentsButton != null) {
894 mVideoAttachmentsButton.setOnClickListener(this);
895 }
Mindy Pereira818143e2012-01-11 13:59:49 -0800896 mTo = (RecipientEditTextView) findViewById(R.id.to);
897 mCc = (RecipientEditTextView) findViewById(R.id.cc);
898 mBcc = (RecipientEditTextView) findViewById(R.id.bcc);
Mindy Pereira82cc5662012-01-09 17:29:30 -0800899 // TODO: add special chips text change watchers before adding
900 // this as a text changed watcher to the to, cc, bcc fields.
Mindy Pereira6349a042012-01-04 11:25:01 -0800901 mSubject = (TextView) findViewById(R.id.subject);
mindyp62d3ec72012-08-24 13:04:09 -0700902 mSubject.setOnEditorActionListener(this);
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800903 mQuotedTextView = (QuotedTextView) findViewById(R.id.quoted_text_view);
904 mQuotedTextView.setRespondInlineListener(this);
Mindy Pereira433b1982012-04-03 11:53:07 -0700905 mBodyView = (EditText) findViewById(R.id.body);
Mindy Pereira1a95a572012-01-05 12:21:29 -0800906 mFromStatic = findViewById(R.id.static_from_content);
Mindy Pereira2eb17322012-03-07 10:07:34 -0800907 mFromStaticText = (TextView) findViewById(R.id.from_account_name);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800908 mFromSpinnerWrapper = findViewById(R.id.spinner_from_content);
Mindy Pereira5a85e2b2012-01-11 09:53:32 -0800909 mFromSpinner = (FromAddressSpinner) findViewById(R.id.from_picker);
Mindy Pereira6349a042012-01-04 11:25:01 -0800910 }
911
mindyp62d3ec72012-08-24 13:04:09 -0700912 @Override
913 public boolean onEditorAction(TextView view, int action, KeyEvent keyEvent) {
914 if (action == EditorInfo.IME_ACTION_DONE) {
915 focusBody();
916 return true;
917 }
918 return false;
919 }
920
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700921 protected TextView getBody() {
922 return mBodyView;
923 }
924
925 @VisibleForTesting
926 public Account getFromAccount() {
927 return mReplyFromAccount != null && mReplyFromAccount.account != null ?
928 mReplyFromAccount.account : mAccount;
929 }
930
Mindy Pereiracbfb75a2012-06-25 14:52:23 -0700931 private void clearChangeListeners() {
932 mSubject.removeTextChangedListener(this);
933 mBodyView.removeTextChangedListener(this);
934 mTo.removeTextChangedListener(mToListener);
935 mCc.removeTextChangedListener(mCcListener);
936 mBcc.removeTextChangedListener(mBccListener);
937 mFromSpinner.setOnAccountChangedListener(null);
938 mAttachmentsView.setAttachmentChangesListener(null);
939 }
940
Mindy Pereira75f66632012-01-11 11:42:02 -0800941 // Now that the message has been initialized from any existing draft or
942 // ref message data, set up listeners for any changes that occur to the
943 // message.
944 private void initChangeListeners() {
945 mSubject.addTextChangedListener(this);
946 mBodyView.addTextChangedListener(this);
Mindy Pereiracbfb75a2012-06-25 14:52:23 -0700947 if (mToListener == null) {
948 mToListener = new RecipientTextWatcher(mTo, this);
949 }
950 mTo.addTextChangedListener(mToListener);
951 if (mCcListener == null) {
952 mCcListener = new RecipientTextWatcher(mCc, this);
953 }
954 mCc.addTextChangedListener(mCcListener);
955 if (mBccListener == null) {
956 mBccListener = new RecipientTextWatcher(mBcc, this);
957 }
958 mBcc.addTextChangedListener(mBccListener);
Mindy Pereira75f66632012-01-11 11:42:02 -0800959 mFromSpinner.setOnAccountChangedListener(this);
Mindy Pereira818143e2012-01-11 13:59:49 -0800960 mAttachmentsView.setAttachmentChangesListener(this);
Mindy Pereira75f66632012-01-11 11:42:02 -0800961 }
962
Mindy Pereira326c6602012-01-04 15:32:42 -0800963 private void initActionBar(int action) {
964 mComposeMode = action;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800965 ActionBar actionBar = getActionBar();
Mindy Pereirae011b1d2012-06-18 13:45:26 -0700966 if (actionBar == null) {
967 return;
968 }
Mindy Pereira326c6602012-01-04 15:32:42 -0800969 if (action == ComposeActivity.COMPOSE) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800970 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
971 actionBar.setTitle(R.string.compose);
Mindy Pereira326c6602012-01-04 15:32:42 -0800972 } else {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800973 actionBar.setTitle(null);
Mindy Pereira326c6602012-01-04 15:32:42 -0800974 if (mComposeModeAdapter == null) {
975 mComposeModeAdapter = new ComposeModeAdapter(this);
976 }
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800977 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
978 actionBar.setListNavigationCallbacks(mComposeModeAdapter, this);
Mindy Pereira326c6602012-01-04 15:32:42 -0800979 switch (action) {
980 case ComposeActivity.REPLY:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800981 actionBar.setSelectedNavigationItem(0);
Mindy Pereira326c6602012-01-04 15:32:42 -0800982 break;
983 case ComposeActivity.REPLY_ALL:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800984 actionBar.setSelectedNavigationItem(1);
Mindy Pereira326c6602012-01-04 15:32:42 -0800985 break;
986 case ComposeActivity.FORWARD:
Mindy Pereiraeaea9f12012-01-10 15:05:27 -0800987 actionBar.setSelectedNavigationItem(2);
Mindy Pereira326c6602012-01-04 15:32:42 -0800988 break;
989 }
990 }
Mindy Pereirafbe40192012-03-20 10:40:45 -0700991 actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME,
992 ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME);
993 actionBar.setHomeButtonEnabled(true);
Mindy Pereira326c6602012-01-04 15:32:42 -0800994 }
995
Mindy Pereira46ce0b12012-01-05 10:32:15 -0800996 private void initFromRefMessage(int action, String recipientAddress) {
Mindy Pereira96a7f7a2012-07-09 16:51:06 -0700997 setFieldsFromRefMessage(action, recipientAddress);
998 if (mRefMessage != null) {
999 // CC field only gets populated when doing REPLY_ALL.
1000 // BCC never gets auto-populated, unless the user is editing
1001 // a draft with one.
Mindy Pereira29a717e2012-07-25 18:05:48 -07001002 if (!TextUtils.isEmpty(mCc.getText()) && action == REPLY_ALL) {
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07001003 mCcBccView.show(false, true, false);
1004 }
1005 }
1006 updateHideOrShowCcBcc();
1007 }
1008
1009 private void setFieldsFromRefMessage(int action, String recipientAddress) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001010 setSubject(mRefMessage, action);
1011 // Setup recipients
1012 if (action == FORWARD) {
1013 mForward = true;
Mindy Pereira6349a042012-01-04 11:25:01 -08001014 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001015 initRecipientsFromRefMessage(recipientAddress, mRefMessage, action);
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001016 initQuotedTextFromRefMessage(mRefMessage, action);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001017 if (action == ComposeActivity.FORWARD || mAttachmentsChanged) {
1018 initAttachments(mRefMessage);
1019 }
Mindy Pereirac17d0732011-12-29 10:46:19 -08001020 }
1021
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001022 private void initFromDraftMessage(Message message) {
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001023 LogUtils.d(LOG_TAG, "Intializing draft from previous draft message");
1024
1025 mDraft = message;
1026 mDraftId = message.id;
1027 mSubject.setText(message.subject);
1028 mForward = message.draftType == UIProvider.DraftType.FORWARD;
1029 final List<String> toAddresses = Arrays.asList(message.getToAddresses());
1030 addToAddresses(toAddresses);
1031 addCcAddresses(Arrays.asList(message.getCcAddresses()), toAddresses);
1032 addBccAddresses(Arrays.asList(message.getBccAddresses()));
Mindy Pereira2421dc82012-03-27 13:32:31 -07001033 if (message.hasAttachments) {
1034 List<Attachment> attachments = message.getAttachments();
1035 for (Attachment a : attachments) {
Andy Huang5c5fd572012-04-08 18:19:29 -07001036 addAttachmentAndUpdateView(a);
Mindy Pereira2421dc82012-03-27 13:32:31 -07001037 }
1038 }
Mindy Pereiracc8e7db2012-05-30 12:57:42 -07001039 int quotedTextIndex = message.appendRefMessageContent ?
Mindy Pereira002ff522012-05-30 10:31:26 -07001040 message.quotedTextOffset : -1;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001041 // Set the body
Mindy Pereira002ff522012-05-30 10:31:26 -07001042 CharSequence quotedText = null;
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001043 if (!TextUtils.isEmpty(message.bodyHtml)) {
Mindy Pereira752222d2012-07-19 09:58:53 -07001044 CharSequence htmlText = "";
Mindy Pereira002ff522012-05-30 10:31:26 -07001045 if (quotedTextIndex > -1) {
Mindy Pereira752222d2012-07-19 09:58:53 -07001046 // Find the offset in the htmltext of the actual quoted text and strip it out.
1047 quotedTextIndex = QuotedTextView.findQuotedTextIndex(message.bodyHtml);
1048 if (quotedTextIndex > -1) {
1049 htmlText = Html.fromHtml(message.bodyHtml.substring(0, quotedTextIndex));
1050 quotedText = message.bodyHtml.subSequence(quotedTextIndex,
1051 message.bodyHtml.length());
1052 }
Mindy Pereira1a6e9382012-08-14 15:51:22 -07001053 } else {
1054 htmlText = Html.fromHtml(message.bodyHtml);
Mindy Pereira002ff522012-05-30 10:31:26 -07001055 }
1056 mBodyView.setText(htmlText);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001057 } else {
Mindy Pereira752222d2012-07-19 09:58:53 -07001058 final String body = message.bodyText;
1059 final CharSequence bodyText = !TextUtils.isEmpty(body) ?
1060 (quotedTextIndex > -1 ?
1061 message.bodyText.substring(0, quotedTextIndex) : message.bodyText)
1062 : "";
Mindy Pereira002ff522012-05-30 10:31:26 -07001063 if (quotedTextIndex > -1) {
Mindy Pereira752222d2012-07-19 09:58:53 -07001064 quotedText = !TextUtils.isEmpty(body) ? message.bodyText.substring(quotedTextIndex)
1065 : null;
Mindy Pereira002ff522012-05-30 10:31:26 -07001066 }
1067 mBodyView.setText(bodyText);
1068 }
1069 if (quotedTextIndex > -1 && quotedText != null) {
Mindy Pereira39713232012-05-30 11:48:41 -07001070 mQuotedTextView.setQuotedTextFromDraft(quotedText, mForward);
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001071 }
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001072 }
1073
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001074 /**
1075 * Fill all the widgets with the content found in the Intent Extra, if any.
1076 * Also apply the same style to all widgets. Note: if initFromExtras is
1077 * called as a result of switching between reply, reply all, and forward per
1078 * the latest revision of Gmail, and the user has already made changes to
1079 * attachments on a previous incarnation of the message (as a reply, reply
1080 * all, or forward), the original attachments from the message will not be
1081 * re-instantiated. The user's changes will be respected. This follows the
1082 * web gmail interaction.
1083 */
1084 public void initFromExtras(Intent intent) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001085 // If we were invoked with a SENDTO intent, the value
1086 // should take precedence
1087 final Uri dataUri = intent.getData();
1088 if (dataUri != null) {
1089 if (MAIL_TO.equals(dataUri.getScheme())) {
1090 initFromMailTo(dataUri.toString());
1091 } else {
Mindy Pereira0b4f28e2012-03-28 14:12:21 -07001092 if (!mAccount.composeIntentUri.equals(dataUri)) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001093 String toText = dataUri.getSchemeSpecificPart();
1094 if (toText != null) {
1095 mTo.setText("");
Mindy Pereiradbe89962012-04-13 09:42:38 -07001096 addToAddresses(Arrays.asList(TextUtils.split(toText, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001097 }
1098 }
1099 }
1100 }
1101
1102 String[] extraStrings = intent.getStringArrayExtra(Intent.EXTRA_EMAIL);
1103 if (extraStrings != null) {
1104 addToAddresses(Arrays.asList(extraStrings));
1105 }
1106 extraStrings = intent.getStringArrayExtra(Intent.EXTRA_CC);
1107 if (extraStrings != null) {
1108 addCcAddresses(Arrays.asList(extraStrings), null);
1109 }
1110 extraStrings = intent.getStringArrayExtra(Intent.EXTRA_BCC);
1111 if (extraStrings != null) {
1112 addBccAddresses(Arrays.asList(extraStrings));
1113 }
1114
1115 String extraString = intent.getStringExtra(Intent.EXTRA_SUBJECT);
1116 if (extraString != null) {
1117 mSubject.setText(extraString);
1118 }
1119
1120 for (String extra : ALL_EXTRAS) {
1121 if (intent.hasExtra(extra)) {
1122 String value = intent.getStringExtra(extra);
1123 if (EXTRA_TO.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001124 addToAddresses(Arrays.asList(TextUtils.split(value, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001125 } else if (EXTRA_CC.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001126 addCcAddresses(Arrays.asList(TextUtils.split(value, ",")), null);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001127 } else if (EXTRA_BCC.equals(extra)) {
Mindy Pereiradbe89962012-04-13 09:42:38 -07001128 addBccAddresses(Arrays.asList(TextUtils.split(value, ",")));
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001129 } else if (EXTRA_SUBJECT.equals(extra)) {
1130 mSubject.setText(value);
1131 } else if (EXTRA_BODY.equals(extra)) {
1132 setBody(value, true /* with signature */);
1133 }
1134 }
1135 }
1136
1137 Bundle extras = intent.getExtras();
1138 if (extras != null) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001139 CharSequence text = extras.getCharSequence(Intent.EXTRA_TEXT);
1140 if (text != null) {
1141 setBody(text, true /* with signature */);
1142 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001143 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001144 }
1145
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001146 @VisibleForTesting
1147 protected String decodeEmailInUri(String s) throws UnsupportedEncodingException {
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001148 // TODO: handle the case where there are spaces in the display name as
1149 // well as the email such as "Guy with spaces <guy+with+spaces@gmail.com>"
1150 // as they could be encoded ambiguously.
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001151 // Since URLDecode.decode changes + into ' ', and + is a valid
1152 // email character, we need to find/ replace these ourselves before
1153 // decoding.
1154 String replacePlus = s.replace("+", "%2B");
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001155 try {
1156 return URLDecoder.decode(replacePlus, UTF8_ENCODING_NAME);
1157 } catch (IllegalArgumentException e) {
1158 if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
1159 LogUtils.e(LOG_TAG, "%s while decoding '%s'", e.getMessage(), s);
1160 } else {
1161 LogUtils.e(LOG_TAG, e, "Exception while decoding mailto address");
1162 }
1163 return null;
1164 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001165 }
1166
1167 /**
1168 * Initialize the compose view from a String representing a mailTo uri.
1169 * @param mailToString The uri as a string.
1170 */
1171 public void initFromMailTo(String mailToString) {
1172 // We need to disguise this string as a URI in order to parse it
1173 // TODO: Remove this hack when http://b/issue?id=1445295 gets fixed
1174 Uri uri = Uri.parse("foo://" + mailToString);
1175 int index = mailToString.indexOf("?");
1176 int length = "mailto".length() + 1;
1177 String to;
1178 try {
1179 // Extract the recipient after mailto:
1180 if (index == -1) {
1181 to = decodeEmailInUri(mailToString.substring(length));
1182 } else {
1183 to = decodeEmailInUri(mailToString.substring(length, index));
1184 }
Mindy Pereiraa4069f22012-05-30 15:31:45 -07001185 if (!TextUtils.isEmpty(to)) {
1186 addToAddresses(Arrays.asList(TextUtils.split(to, ",")));
1187 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001188 } catch (UnsupportedEncodingException e) {
1189 if (LogUtils.isLoggable(LOG_TAG, LogUtils.VERBOSE)) {
1190 LogUtils.e(LOG_TAG, "%s while decoding '%s'", e.getMessage(), mailToString);
1191 } else {
1192 LogUtils.e(LOG_TAG, e, "Exception while decoding mailto address");
1193 }
1194 }
1195
1196 List<String> cc = uri.getQueryParameters("cc");
1197 addCcAddresses(Arrays.asList(cc.toArray(new String[cc.size()])), null);
1198
1199 List<String> otherTo = uri.getQueryParameters("to");
1200 addToAddresses(Arrays.asList(otherTo.toArray(new String[otherTo.size()])));
1201
1202 List<String> bcc = uri.getQueryParameters("bcc");
1203 addBccAddresses(Arrays.asList(bcc.toArray(new String[bcc.size()])));
1204
1205 List<String> subject = uri.getQueryParameters("subject");
1206 if (subject.size() > 0) {
1207 try {
1208 mSubject.setText(URLDecoder.decode(subject.get(0), UTF8_ENCODING_NAME));
1209 } catch (UnsupportedEncodingException e) {
1210 LogUtils.e(LOG_TAG, "%s while decoding subject '%s'",
1211 e.getMessage(), subject);
1212 }
1213 }
1214
1215 List<String> body = uri.getQueryParameters("body");
1216 if (body.size() > 0) {
1217 try {
1218 setBody(URLDecoder.decode(body.get(0), UTF8_ENCODING_NAME),
1219 true /* with signature */);
1220 } catch (UnsupportedEncodingException e) {
1221 LogUtils.e(LOG_TAG, "%s while decoding body '%s'", e.getMessage(), body);
1222 }
1223 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001224 }
1225
Mindy Pereirabddd6f32012-06-20 12:10:03 -07001226 @VisibleForTesting
1227 protected void initAttachments(Message refMessage) {
Mark Wei434f2942012-08-24 11:54:02 -07001228 addAttachments(refMessage.getAttachments());
1229 }
1230
1231 public long addAttachments(List<Attachment> attachments) {
1232 long size = 0;
1233 AttachmentFailureException error = null;
1234 for (Attachment a : attachments) {
1235 try {
1236 size += mAttachmentsView.addAttachment(mAccount, a);
1237 } catch (AttachmentFailureException e) {
1238 error = e;
1239 }
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001240 }
Mark Wei434f2942012-08-24 11:54:02 -07001241 if (error != null) {
1242 LogUtils.e(LOG_TAG, error, "Error adding attachment");
1243 if (attachments.size() > 1) {
1244 showAttachmentTooBigToast(R.string.too_large_to_attach_multiple);
1245 } else {
1246 showAttachmentTooBigToast(error.getErrorRes());
1247 }
1248 }
1249 return size;
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001250 }
1251
1252 /**
1253 * When an attachment is too large to be added to a message, show a toast.
1254 * This method also updates the position of the toast so that it is shown
1255 * clearly above they keyboard if it happens to be open.
1256 */
Mark Wei434f2942012-08-24 11:54:02 -07001257 private void showAttachmentTooBigToast(int errorRes) {
1258 String maxSize = AttachmentUtils.convertToHumanReadableSize(
1259 getApplicationContext(), mAccount.settings.getMaxAttachmentSize());
1260 showErrorToast(getString(errorRes, maxSize));
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001261 }
1262
Mark Wei434f2942012-08-24 11:54:02 -07001263 private void showErrorToast(String message) {
1264 Toast t = Toast.makeText(this, message, Toast.LENGTH_LONG);
1265 t.setText(message);
Mindy Pereira3cd4f402012-07-17 11:16:18 -07001266 t.setGravity(Gravity.CENTER_HORIZONTAL, 0,
1267 getResources().getDimensionPixelSize(R.dimen.attachment_toast_yoffset));
1268 t.show();
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001269 }
1270
Paul Westbrookf97588b2012-03-20 11:11:37 -07001271 private void initAttachmentsFromIntent(Intent intent) {
Paul Westbrook03ee9712012-04-02 09:51:51 -07001272 Bundle extras = intent.getExtras();
1273 if (extras == null) {
1274 extras = Bundle.EMPTY;
1275 }
Paul Westbrookf97588b2012-03-20 11:11:37 -07001276 final String action = intent.getAction();
1277 if (!mAttachmentsChanged) {
1278 long totalSize = 0;
1279 if (extras.containsKey(EXTRA_ATTACHMENTS)) {
1280 String[] uris = (String[]) extras.getSerializable(EXTRA_ATTACHMENTS);
1281 for (String uriString : uris) {
1282 final Uri uri = Uri.parse(uriString);
1283 long size = 0;
1284 try {
Andy Huang5c5fd572012-04-08 18:19:29 -07001285 size = mAttachmentsView.addAttachment(mAccount, uri);
Paul Westbrookf97588b2012-03-20 11:11:37 -07001286 } catch (AttachmentFailureException e) {
Paul Westbrookf97588b2012-03-20 11:11:37 -07001287 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Mark Wei434f2942012-08-24 11:54:02 -07001288 showAttachmentTooBigToast(e.getErrorRes());
Paul Westbrookf97588b2012-03-20 11:11:37 -07001289 }
1290 totalSize += size;
1291 }
1292 }
mindyp9a9e8d62012-10-03 12:24:07 -07001293 if (extras.containsKey(Intent.EXTRA_STREAM)) {
1294 if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
1295 ArrayList<Parcelable> uris = extras
1296 .getParcelableArrayList(Intent.EXTRA_STREAM);
1297 ArrayList<Attachment> attachments = new ArrayList<Attachment>();
1298 for (Parcelable uri : uris) {
1299 try {
1300 attachments.add(mAttachmentsView.generateLocalAttachment((Uri) uri));
1301 } catch (AttachmentFailureException e) {
1302 LogUtils.e(LOG_TAG, e, "Error adding attachment");
1303 String maxSize = AttachmentUtils.convertToHumanReadableSize(
1304 getApplicationContext(),
1305 mAccount.settings.getMaxAttachmentSize());
1306 showErrorToast(getString
1307 (R.string.generic_attachment_problem, maxSize));
1308 }
1309 }
1310 totalSize += addAttachments(attachments);
1311 } else {
1312 final Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
1313 long size = 0;
Paul Westbrookf97588b2012-03-20 11:11:37 -07001314 try {
mindyp9a9e8d62012-10-03 12:24:07 -07001315 size = mAttachmentsView.addAttachment(mAccount, uri);
Paul Westbrookf97588b2012-03-20 11:11:37 -07001316 } catch (AttachmentFailureException e) {
Paul Westbrookf97588b2012-03-20 11:11:37 -07001317 LogUtils.e(LOG_TAG, e, "Error adding attachment");
mindyp9a9e8d62012-10-03 12:24:07 -07001318 showAttachmentTooBigToast(e.getErrorRes());
Paul Westbrookf97588b2012-03-20 11:11:37 -07001319 }
mindyp9a9e8d62012-10-03 12:24:07 -07001320 totalSize += size;
Paul Westbrookf97588b2012-03-20 11:11:37 -07001321 }
1322 }
1323
1324 if (totalSize > 0) {
1325 mAttachmentsChanged = true;
1326 updateSaveUi();
1327 }
1328 }
1329 }
1330
1331
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07001332 private void initQuotedTextFromRefMessage(Message refMessage, int action) {
1333 if (mRefMessage != null && (action == REPLY || action == REPLY_ALL || action == FORWARD)) {
Mindy Pereira9932dee2012-01-10 16:09:50 -08001334 mQuotedTextView.setQuotedText(action, refMessage, action != FORWARD);
1335 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001336 }
1337
1338 private void updateHideOrShowCcBcc() {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001339 // Its possible there is a menu item OR a button.
Mindy Pereira326689d2012-05-17 10:14:14 -07001340 boolean ccVisible = mCcBccView.isCcVisible();
1341 boolean bccVisible = mCcBccView.isBccVisible();
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001342 if (mCcBccButton != null) {
Mindy Pereira326689d2012-05-17 10:14:14 -07001343 if (!ccVisible || !bccVisible) {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001344 mCcBccButton.setVisibility(View.VISIBLE);
Mindy Pereira326689d2012-05-17 10:14:14 -07001345 mCcBccButton.setText(getString(!ccVisible ? R.string.add_cc_label
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001346 : R.string.add_bcc_label));
1347 } else {
mindypcd0b0b92012-08-23 14:33:17 -07001348 mCcBccButton.setVisibility(View.INVISIBLE);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001349 }
1350 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001351 }
1352
Mindy Pereiraa34c9a02012-04-17 14:10:53 -07001353 private void showCcBcc(Bundle state) {
Mindy Pereira326689d2012-05-17 10:14:14 -07001354 if (state != null && state.containsKey(EXTRA_SHOW_CC)) {
1355 boolean showCc = state.getBoolean(EXTRA_SHOW_CC);
1356 boolean showBcc = state.getBoolean(EXTRA_SHOW_BCC);
1357 if (showCc || showBcc) {
1358 mCcBccView.show(false, showCc, showBcc);
Mindy Pereira6faeedf2012-04-18 16:11:39 -07001359 }
Mindy Pereiraa34c9a02012-04-17 14:10:53 -07001360 }
1361 }
1362
Mindy Pereira013194c2012-01-06 15:09:33 -08001363 /**
1364 * Add attachment and update the compose area appropriately.
1365 * @param data
1366 */
1367 public void addAttachmentAndUpdateView(Intent data) {
Mindy Pereira2421dc82012-03-27 13:32:31 -07001368 addAttachmentAndUpdateView(data != null ? data.getData() : (Uri) null);
1369 }
1370
Andy Huang5c5fd572012-04-08 18:19:29 -07001371 public void addAttachmentAndUpdateView(Uri contentUri) {
1372 if (contentUri == null) {
Mindy Pereira2421dc82012-03-27 13:32:31 -07001373 return;
1374 }
Mindy Pereira013194c2012-01-06 15:09:33 -08001375 try {
Andy Huang5c5fd572012-04-08 18:19:29 -07001376 addAttachmentAndUpdateView(mAttachmentsView.generateLocalAttachment(contentUri));
1377 } catch (AttachmentFailureException e) {
Andy Huang5c5fd572012-04-08 18:19:29 -07001378 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Mark Wei434f2942012-08-24 11:54:02 -07001379 showErrorToast(getResources().getString(
1380 e.getErrorRes(),
1381 AttachmentUtils.convertToHumanReadableSize(
1382 getApplicationContext(), mAccount.settings.getMaxAttachmentSize())));
Andy Huang5c5fd572012-04-08 18:19:29 -07001383 }
1384 }
1385
1386 public void addAttachmentAndUpdateView(Attachment attachment) {
1387 try {
Mark Wei434f2942012-08-24 11:54:02 -07001388 long size = mAttachmentsView.addAttachment(mAccount, attachment);
Mindy Pereira9932dee2012-01-10 16:09:50 -08001389 if (size > 0) {
1390 mAttachmentsChanged = true;
1391 updateSaveUi();
Mindy Pereira013194c2012-01-06 15:09:33 -08001392 }
Mindy Pereira9932dee2012-01-10 16:09:50 -08001393 } catch (AttachmentFailureException e) {
Mindy Pereira9932dee2012-01-10 16:09:50 -08001394 LogUtils.e(LOG_TAG, e, "Error adding attachment");
Mark Wei434f2942012-08-24 11:54:02 -07001395 showAttachmentTooBigToast(e.getErrorRes());
Mindy Pereira013194c2012-01-06 15:09:33 -08001396 }
1397 }
1398
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001399 void initRecipientsFromRefMessage(String recipientAddress, Message refMessage,
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001400 int action) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001401 // Don't populate the address if this is a forward.
1402 if (action == ComposeActivity.FORWARD) {
1403 return;
1404 }
Mindy Pereira33fe9082012-01-09 16:24:30 -08001405 initReplyRecipients(mAccount.name, refMessage, action);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001406 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001407
Mindy Pereira818143e2012-01-11 13:59:49 -08001408 @VisibleForTesting
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001409 void initReplyRecipients(String account, Message refMessage, int action) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001410 // This is the email address of the current user, i.e. the one composing
1411 // the reply.
Mindy Pereira4a20b702012-01-05 16:24:24 -08001412 final String accountEmail = Address.getEmailAddress(account).getAddress();
Mindy Pereira1469b4e2012-06-19 19:18:54 -07001413 String fromAddress = getAddress(refMessage.from);
mindyp5ed63112012-09-17 17:31:45 -07001414 String[] sentToAddresses = refMessage.getToAddresses();
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001415 String replytoAddress = refMessage.replyTo;
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001416 final Collection<String> toAddresses;
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001417
1418 // If this is a reply, the Cc list is empty. If this is a reply-all, the
1419 // Cc list is the union of the To and Cc recipients of the original
1420 // message, excluding the current user's email address and any addresses
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001421 // already on the To list.
1422 if (action == ComposeActivity.REPLY) {
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001423 toAddresses = initToRecipients(account, accountEmail, fromAddress, replytoAddress,
Mindy Pereira1469b4e2012-06-19 19:18:54 -07001424 sentToAddresses);
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001425 addToAddresses(toAddresses);
1426 } else if (action == ComposeActivity.REPLY_ALL) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001427 final Set<String> ccAddresses = Sets.newHashSet();
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001428 toAddresses = initToRecipients(account, accountEmail, fromAddress, replytoAddress,
Mindy Pereira9b18a9a2012-07-25 18:13:57 -07001429 sentToAddresses);
Mindy Pereira154386a2012-01-11 13:02:33 -08001430 addToAddresses(toAddresses);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001431 addRecipients(accountEmail, ccAddresses, sentToAddresses);
mindyp5ed63112012-09-17 17:31:45 -07001432 addRecipients(accountEmail, ccAddresses, refMessage.getCcAddresses());
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001433 addCcAddresses(ccAddresses, toAddresses);
1434 }
1435 }
1436
Mindy Pereira1469b4e2012-06-19 19:18:54 -07001437 private String getAddress(String toParse) {
1438 if (!TextUtils.isEmpty(toParse)) {
1439 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(toParse);
1440 if (tokens.length > 0) {
1441 return tokens[0].getAddress();
1442 }
1443 }
1444 return "";
1445 }
1446
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001447 private void addToAddresses(Collection<String> addresses) {
1448 addAddressesToList(addresses, mTo);
1449 }
1450
1451 private void addCcAddresses(Collection<String> addresses, Collection<String> toAddresses) {
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001452 addCcAddressesToList(tokenizeAddressList(addresses),
1453 toAddresses != null ? tokenizeAddressList(toAddresses) : null, mCc);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001454 }
1455
Paul Westbrookbb87b7f2012-03-20 16:20:07 -07001456 private void addBccAddresses(Collection<String> addresses) {
1457 addAddressesToList(addresses, mBcc);
1458 }
1459
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001460 @VisibleForTesting
1461 protected void addCcAddressesToList(List<Rfc822Token[]> addresses,
1462 List<Rfc822Token[]> compareToList, RecipientEditTextView list) {
1463 String address;
1464
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001465 if (compareToList == null) {
1466 for (Rfc822Token[] tokens : addresses) {
1467 for (int i = 0; i < tokens.length; i++) {
1468 address = tokens[i].toString();
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001469 list.append(address + END_TOKEN);
1470 }
1471 }
Mindy Pereira8eca57a2012-03-20 16:42:34 -07001472 } else {
1473 HashSet<String> compareTo = convertToHashSet(compareToList);
1474 for (Rfc822Token[] tokens : addresses) {
1475 for (int i = 0; i < tokens.length; i++) {
1476 address = tokens[i].toString();
1477 // Check if this is a duplicate:
1478 if (!compareTo.contains(tokens[i].getAddress())) {
1479 // Get the address here
1480 list.append(address + END_TOKEN);
1481 }
1482 }
1483 }
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001484 }
1485 }
1486
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001487 private HashSet<String> convertToHashSet(List<Rfc822Token[]> list) {
1488 HashSet<String> hash = new HashSet<String>();
1489 for (Rfc822Token[] tokens : list) {
1490 for (int i = 0; i < tokens.length; i++) {
1491 hash.add(tokens[i].getAddress());
1492 }
1493 }
1494 return hash;
1495 }
1496
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001497 protected List<Rfc822Token[]> tokenizeAddressList(Collection<String> addresses) {
1498 @VisibleForTesting
1499 List<Rfc822Token[]> tokenized = new ArrayList<Rfc822Token[]>();
1500
1501 for (String address: addresses) {
1502 tokenized.add(Rfc822Tokenizer.tokenize(address));
1503 }
1504 return tokenized;
1505 }
1506
1507 @VisibleForTesting
1508 void addAddressesToList(Collection<String> addresses, RecipientEditTextView list) {
1509 for (String address : addresses) {
1510 addAddressToList(address, list);
1511 }
1512 }
1513
1514 private void addAddressToList(String address, RecipientEditTextView list) {
1515 if (address == null || list == null)
1516 return;
1517
1518 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(address);
1519
1520 for (int i = 0; i < tokens.length; i++) {
1521 list.append(tokens[i] + END_TOKEN);
1522 }
1523 }
1524
1525 @VisibleForTesting
1526 protected Collection<String> initToRecipients(String account, String accountEmail,
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001527 String senderAddress, String replyToAddress, String[] inToAddresses) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001528 // The To recipient is the reply-to address specified in the original
1529 // message, unless it is:
1530 // the current user OR a custom from of the current user, in which case
1531 // it's the To recipient list of the original message.
1532 // OR missing, in which case use the sender of the original message
1533 Set<String> toAddresses = Sets.newHashSet();
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001534 if (!TextUtils.isEmpty(replyToAddress)) {
1535 toAddresses.add(replyToAddress);
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001536 } else {
Mindy Pereiracecc54a2012-07-31 09:38:11 -07001537 if (!recipientMatchesThisAccount(account, senderAddress)) {
Mindy Pereira1469b4e2012-06-19 19:18:54 -07001538 toAddresses.add(senderAddress);
1539 } else {
1540 // This happens if the user replies to a message they originally
Mindy Pereira1883b342012-06-20 08:34:56 -07001541 // wrote. In this case, "reply" really means "re-send," so we
1542 // target the original recipients. This works as expected even
1543 // if the user sent the original message to themselves.
Mindy Pereira1469b4e2012-06-19 19:18:54 -07001544 toAddresses.addAll(Arrays.asList(inToAddresses));
1545 }
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001546 }
1547 return toAddresses;
1548 }
1549
Mindy Pereiracecc54a2012-07-31 09:38:11 -07001550 private void addRecipients(String accountAddress, Set<String> recipients, String[] addresses) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001551 for (String email : addresses) {
Mindy Pereiracecc54a2012-07-31 09:38:11 -07001552 // Do not add this account, or any of its custom from addresses, to
1553 // the list of recipients.
Mindy Pereira4a20b702012-01-05 16:24:24 -08001554 final String recipientAddress = Address.getEmailAddress(email).getAddress();
Mindy Pereiracecc54a2012-07-31 09:38:11 -07001555 if (!recipientMatchesThisAccount(accountAddress, recipientAddress)) {
Mindy Pereira4a27ea92012-01-05 15:55:25 -08001556 recipients.add(email.replace("\"\"", ""));
1557 }
1558 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001559 }
1560
Mindy Pereiracecc54a2012-07-31 09:38:11 -07001561 /**
1562 * A recipient matches this account if it has the same address as the
1563 * currently selected account OR one of the custom from addresses associated
1564 * with the currently selected account.
1565 * @param accountAddress currently selected account
1566 * @param recipientAddress address we are comparing with the currently selected account
1567 * @return
1568 */
1569 protected boolean recipientMatchesThisAccount(String accountAddress, String recipientAddress) {
1570 return accountAddress.equalsIgnoreCase(recipientAddress)
1571 || ReplyFromAccount.isCustomFrom(recipientAddress,
1572 mFromSpinner.getReplyFromAccounts());
1573 }
1574
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001575 private void setSubject(Message refMessage, int action) {
1576 String subject = refMessage.subject;
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001577 String prefix;
1578 String correctedSubject = null;
1579 if (action == ComposeActivity.COMPOSE) {
1580 prefix = "";
1581 } else if (action == ComposeActivity.FORWARD) {
1582 prefix = getString(R.string.forward_subject_label);
1583 } else {
1584 prefix = getString(R.string.reply_subject_label);
1585 }
1586
1587 // Don't duplicate the prefix
Mindy Pereirac7a36992012-07-30 14:00:37 -07001588 if (!TextUtils.isEmpty(subject)
1589 && subject.toLowerCase().startsWith(prefix.toLowerCase())) {
Mindy Pereira46ce0b12012-01-05 10:32:15 -08001590 correctedSubject = subject;
1591 } else {
1592 correctedSubject = String
1593 .format(getString(R.string.formatted_subject), prefix, subject);
1594 }
1595 mSubject.setText(correctedSubject);
1596 }
1597
Mindy Pereira818143e2012-01-11 13:59:49 -08001598 private void initRecipients() {
1599 setupRecipients(mTo);
1600 setupRecipients(mCc);
1601 setupRecipients(mBcc);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001602 }
1603
Mindy Pereira818143e2012-01-11 13:59:49 -08001604 private void setupRecipients(RecipientEditTextView view) {
Paul Westbrook679a8cc2012-02-21 16:37:58 -08001605 view.setAdapter(new RecipientAdapter(this, mAccount));
Mindy Pereirac17d0732011-12-29 10:46:19 -08001606 view.setTokenizer(new Rfc822Tokenizer());
Mindy Pereira82cc5662012-01-09 17:29:30 -08001607 if (mValidator == null) {
Paul Westbrook679a8cc2012-02-21 16:37:58 -08001608 final String accountName = mAccount.name;
Mindy Pereira33fe9082012-01-09 16:24:30 -08001609 int offset = accountName.indexOf("@") + 1;
1610 String account = accountName;
Mindy Pereirac17d0732011-12-29 10:46:19 -08001611 if (offset > -1) {
Mindy Pereira33fe9082012-01-09 16:24:30 -08001612 account = account.substring(accountName.indexOf("@") + 1);
Mindy Pereirac17d0732011-12-29 10:46:19 -08001613 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001614 mValidator = new Rfc822Validator(account);
Mindy Pereirac17d0732011-12-29 10:46:19 -08001615 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001616 view.setValidator(mValidator);
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001617 }
1618
1619 @Override
1620 public void onClick(View v) {
1621 int id = v.getId();
1622 switch (id) {
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001623 case R.id.add_cc_bcc:
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001624 // Verify that cc/ bcc aren't showing.
1625 // Animate in cc/bcc.
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08001626 showCcBccViews();
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001627 break;
mindypcd0b0b92012-08-23 14:33:17 -07001628 case R.id.add_photo_attachment:
1629 doAttach(MIME_TYPE_PHOTO);
1630 break;
1631 case R.id.add_video_attachment:
1632 doAttach(MIME_TYPE_VIDEO);
1633 break;
Mindy Pereira8e9305e2011-12-13 14:25:04 -08001634 }
1635 }
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001636
1637 @Override
1638 public boolean onCreateOptionsMenu(Menu menu) {
1639 super.onCreateOptionsMenu(menu);
Mindy Pereirab199d172012-08-13 11:04:03 -07001640 // Don't render any menu items when there are no accounts.
1641 if (mAccounts == null || mAccounts.length == 0) {
1642 return true;
1643 }
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001644 MenuInflater inflater = getMenuInflater();
1645 inflater.inflate(R.menu.compose_menu, menu);
Mindy Pereira82cc5662012-01-09 17:29:30 -08001646 mSave = menu.findItem(R.id.save);
1647 mSend = menu.findItem(R.id.send);
Mindy Pereira3ca5bad2012-04-16 11:02:42 -07001648 MenuItem helpItem = menu.findItem(R.id.help_info_menu_item);
1649 MenuItem sendFeedbackItem = menu.findItem(R.id.feedback_menu_item);
1650 if (helpItem != null) {
1651 helpItem.setVisible(mAccount != null
1652 && mAccount.supportsCapability(AccountCapabilities.HELP_CONTENT));
1653 }
1654 if (sendFeedbackItem != null) {
1655 sendFeedbackItem.setVisible(mAccount != null
1656 && mAccount.supportsCapability(AccountCapabilities.SEND_FEEDBACK));
1657 }
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001658 return true;
1659 }
1660
1661 @Override
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001662 public boolean onPrepareOptionsMenu(Menu menu) {
1663 MenuItem ccBcc = menu.findItem(R.id.add_cc_bcc);
Mindy Pereira818143e2012-01-11 13:59:49 -08001664 if (ccBcc != null && mCc != null) {
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001665 // Its possible there is a menu item OR a button.
1666 boolean ccFieldVisible = mCc.isShown();
1667 boolean bccFieldVisible = mBcc.isShown();
1668 if (!ccFieldVisible || !bccFieldVisible) {
1669 ccBcc.setVisible(true);
1670 ccBcc.setTitle(getString(!ccFieldVisible ? R.string.add_cc_label
1671 : R.string.add_bcc_label));
1672 } else {
1673 ccBcc.setVisible(false);
1674 }
1675 }
Mindy Pereira75f66632012-01-11 11:42:02 -08001676 if (mSave != null) {
1677 mSave.setEnabled(shouldSave());
1678 }
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001679 return true;
1680 }
1681
1682 @Override
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001683 public boolean onOptionsItemSelected(MenuItem item) {
1684 int id = item.getItemId();
Mindy Pereira75f66632012-01-11 11:42:02 -08001685 boolean handled = true;
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001686 switch (id) {
Mindy Pereira2db7d4a2012-08-15 11:00:02 -07001687 case R.id.add_photo_attachment:
1688 doAttach(MIME_TYPE_PHOTO);
1689 break;
1690 case R.id.add_video_attachment:
1691 doAttach(MIME_TYPE_VIDEO);
Mindy Pereira7b56a612011-12-14 12:32:28 -08001692 break;
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08001693 case R.id.add_cc_bcc:
1694 showCcBccViews();
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001695 break;
Mindy Pereira33fe9082012-01-09 16:24:30 -08001696 case R.id.save:
Mindy Pereira48e31b02012-05-30 13:12:24 -07001697 doSave(true);
Mindy Pereira33fe9082012-01-09 16:24:30 -08001698 break;
1699 case R.id.send:
1700 doSend();
Mindy Pereira75f66632012-01-11 11:42:02 -08001701 break;
Mindy Pereiraefe3d252012-03-01 14:20:44 -08001702 case R.id.discard:
1703 doDiscard();
1704 break;
Mindy Pereira1f936682012-03-02 11:30:33 -08001705 case R.id.settings:
1706 Utils.showSettings(this, mAccount);
1707 break;
Mindy Pereirafbe40192012-03-20 10:40:45 -07001708 case android.R.id.home:
Paul Westbrookdaecb4b2012-05-31 10:21:26 -07001709 onAppUpPressed();
Mindy Pereirafbe40192012-03-20 10:40:45 -07001710 break;
1711 case R.id.help_info_menu_item:
Paul Westbrook30745b62012-08-19 14:10:32 -07001712 Utils.showHelp(this, mAccount, getString(R.string.compose_help_context));
Mindy Pereirafbe40192012-03-20 10:40:45 -07001713 break;
1714 case R.id.feedback_menu_item:
Paul Westbrook17beb0b2012-08-20 13:34:37 -07001715 Utils.sendFeedback(this, mAccount, false);
Mindy Pereirafbe40192012-03-20 10:40:45 -07001716 break;
Mindy Pereira75f66632012-01-11 11:42:02 -08001717 default:
1718 handled = false;
Mindy Pereira33fe9082012-01-09 16:24:30 -08001719 break;
Mindy Pereirab47f3e22011-12-13 14:25:04 -08001720 }
1721 return !handled ? super.onOptionsItemSelected(item) : handled;
1722 }
Mindy Pereira326c6602012-01-04 15:32:42 -08001723
Mindy Pereirab199d172012-08-13 11:04:03 -07001724 @Override
1725 public void onBackPressed() {
1726 // If we are showing the wait fragment, just exit.
1727 if (getWaitFragment() != null) {
1728 finish();
1729 } else {
1730 super.onBackPressed();
1731 }
1732 }
1733
Vikram Aggarwal1672ff82012-09-21 10:15:22 -07001734 /**
1735 * Carries out the "up" action in the action bar.
1736 */
Paul Westbrookdaecb4b2012-05-31 10:21:26 -07001737 private void onAppUpPressed() {
1738 if (mLaunchedFromEmail) {
1739 // If this was started from Gmail, simply treat app up as the system back button, so
1740 // that the last view is restored.
1741 onBackPressed();
1742 return;
1743 }
1744
1745 // Fire the main activity to ensure it launches the "top" screen of mail.
1746 // Since the main Activity is singleTask, it should revive that task if it was already
1747 // started.
Vikram Aggarwal0c3c2052012-09-21 11:06:28 -07001748 final Intent mailIntent = Utils.createViewInboxIntent(mAccount);
Paul Westbrookdaecb4b2012-05-31 10:21:26 -07001749 mailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |
1750 Intent.FLAG_ACTIVITY_TASK_ON_HOME);
1751 startActivity(mailIntent);
1752 finish();
1753 }
1754
Mindy Pereira33fe9082012-01-09 16:24:30 -08001755 private void doSend() {
Mindy Pereira82cc5662012-01-09 17:29:30 -08001756 sendOrSaveWithSanityChecks(false, true, false);
Mindy Pereira33fe9082012-01-09 16:24:30 -08001757 }
1758
Mindy Pereira48e31b02012-05-30 13:12:24 -07001759 private void doSave(boolean showToast) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001760 sendOrSaveWithSanityChecks(true, showToast, false);
Mindy Pereira48e31b02012-05-30 13:12:24 -07001761 }
1762
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001763 @VisibleForTesting
1764 public interface SendOrSaveCallback {
Mindy Pereira82cc5662012-01-09 17:29:30 -08001765 public void initializeSendOrSave(SendOrSaveTask sendOrSaveTask);
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001766 public void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage, Message message);
1767 public Message getMessage();
Mindy Pereira82cc5662012-01-09 17:29:30 -08001768 public void sendOrSaveFinished(SendOrSaveTask sendOrSaveTask, boolean success);
1769 }
1770
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001771 @VisibleForTesting
1772 public static class SendOrSaveTask implements Runnable {
Mindy Pereira82cc5662012-01-09 17:29:30 -08001773 private final Context mContext;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001774 @VisibleForTesting
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001775 public final SendOrSaveCallback mSendOrSaveCallback;
1776 @VisibleForTesting
1777 public final SendOrSaveMessage mSendOrSaveMessage;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001778
1779 public SendOrSaveTask(Context context, SendOrSaveMessage message,
1780 SendOrSaveCallback callback) {
1781 mContext = context;
1782 mSendOrSaveCallback = callback;
1783 mSendOrSaveMessage = message;
1784 }
1785
1786 @Override
1787 public void run() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001788 final SendOrSaveMessage sendOrSaveMessage = mSendOrSaveMessage;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001789
Mindy Pereira92551d02012-04-05 11:31:12 -07001790 final ReplyFromAccount selectedAccount = sendOrSaveMessage.mAccount;
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001791 Message message = mSendOrSaveCallback.getMessage();
1792 long messageId = message != null ? message.id : UIProvider.INVALID_MESSAGE_ID;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001793 // If a previous draft has been saved, in an account that is different
1794 // than what the user wants to send from, remove the old draft, and treat this
1795 // as a new message
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001796 if (!selectedAccount.equals(sendOrSaveMessage.mAccount)) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08001797 if (messageId != UIProvider.INVALID_MESSAGE_ID) {
1798 ContentResolver resolver = mContext.getContentResolver();
1799 ContentValues values = new ContentValues();
1800 values.put(BaseColumns._ID, messageId);
Mindy Pereira92551d02012-04-05 11:31:12 -07001801 if (selectedAccount.account.expungeMessageUri != null) {
1802 resolver.update(selectedAccount.account.expungeMessageUri, values, null,
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001803 null);
Mindy Pereiracfb7f332012-02-28 10:23:43 -08001804 } else {
1805 // TODO(mindyp) delete the conversation.
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001806 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001807 // reset messageId to 0, so a new message will be created
1808 messageId = UIProvider.INVALID_MESSAGE_ID;
1809 }
1810 }
1811
1812 final long messageIdToSave = messageId;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001813 if (messageIdToSave != UIProvider.INVALID_MESSAGE_ID) {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001814 sendOrSaveMessage.mValues.put(BaseColumns._ID, messageIdToSave);
Mindy Pereira82cc5662012-01-09 17:29:30 -08001815 mContext.getContentResolver().update(
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001816 Uri.parse(sendOrSaveMessage.mSave ? message.saveUri : message.sendUri),
1817 sendOrSaveMessage.mValues, null, null);
Mindy Pereira82cc5662012-01-09 17:29:30 -08001818 } else {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001819 ContentResolver resolver = mContext.getContentResolver();
Mindy Pereira92551d02012-04-05 11:31:12 -07001820 Uri messageUri = resolver
1821 .insert(sendOrSaveMessage.mSave ? selectedAccount.account.saveDraftUri
1822 : selectedAccount.account.sendMessageUri,
1823 sendOrSaveMessage.mValues);
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001824 if (sendOrSaveMessage.mSave && messageUri != null) {
1825 Cursor messageCursor = resolver.query(messageUri,
1826 UIProvider.MESSAGE_PROJECTION, null, null, null);
Paul Westbrookba558482012-03-19 11:00:24 -07001827 if (messageCursor != null) {
1828 try {
1829 if (messageCursor.moveToFirst()) {
1830 // Broadcast notification that a new message has
1831 // been allocated
1832 mSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage,
1833 new Message(messageCursor));
1834 }
1835 } finally {
1836 messageCursor.close();
1837 }
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001838 }
1839 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001840 }
1841
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001842 if (!sendOrSaveMessage.mSave) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08001843 UIProvider.incrementRecipientsTimesContacted(mContext,
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001844 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.TO));
Mindy Pereira82cc5662012-01-09 17:29:30 -08001845 UIProvider.incrementRecipientsTimesContacted(mContext,
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001846 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.CC));
Mindy Pereira82cc5662012-01-09 17:29:30 -08001847 UIProvider.incrementRecipientsTimesContacted(mContext,
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001848 (String) sendOrSaveMessage.mValues.get(UIProvider.MessageColumns.BCC));
Mindy Pereira82cc5662012-01-09 17:29:30 -08001849 }
1850 mSendOrSaveCallback.sendOrSaveFinished(SendOrSaveTask.this, true);
1851 }
1852 }
1853
1854 // Array of the outstanding send or save tasks. Access is synchronized
1855 // with the object itself
1856 /* package for testing */
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001857 @VisibleForTesting
1858 public ArrayList<SendOrSaveTask> mActiveTasks = Lists.newArrayList();
Mindy Pereira82cc5662012-01-09 17:29:30 -08001859 private int mRequestId;
Mindy Pereirabdf7a402012-03-01 15:23:26 -08001860 private String mSignature;
Mindy Pereirab199d172012-08-13 11:04:03 -07001861 private Account[] mAccounts;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001862
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001863 @VisibleForTesting
1864 public static class SendOrSaveMessage {
Mindy Pereira92551d02012-04-05 11:31:12 -07001865 final ReplyFromAccount mAccount;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001866 final ContentValues mValues;
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001867 final String mRefMessageId;
Mindy Pereirae011b1d2012-06-18 13:45:26 -07001868 @VisibleForTesting
1869 public final boolean mSave;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001870 final int mRequestId;
1871
Mindy Pereira92551d02012-04-05 11:31:12 -07001872 public SendOrSaveMessage(ReplyFromAccount account, ContentValues values,
Mindy Pereira3ce64e72012-01-13 14:29:45 -08001873 String refMessageId, boolean save) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08001874 mAccount = account;
Mindy Pereira82cc5662012-01-09 17:29:30 -08001875 mValues = values;
1876 mRefMessageId = refMessageId;
1877 mSave = save;
1878 mRequestId = mValues.hashCode() ^ hashCode();
1879 }
1880
1881 int requestId() {
1882 return mRequestId;
1883 }
1884 }
1885
1886 /**
1887 * Get the to recipients.
1888 */
1889 public String[] getToAddresses() {
1890 return getAddressesFromList(mTo);
1891 }
1892
1893 /**
1894 * Get the cc recipients.
1895 */
1896 public String[] getCcAddresses() {
1897 return getAddressesFromList(mCc);
1898 }
1899
1900 /**
1901 * Get the bcc recipients.
1902 */
1903 public String[] getBccAddresses() {
1904 return getAddressesFromList(mBcc);
1905 }
1906
1907 public String[] getAddressesFromList(RecipientEditTextView list) {
1908 if (list == null) {
1909 return new String[0];
1910 }
1911 Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(list.getText());
1912 int count = tokens.length;
1913 String[] result = new String[count];
1914 for (int i = 0; i < count; i++) {
1915 result[i] = tokens[i].toString();
1916 }
1917 return result;
1918 }
1919
1920 /**
1921 * Check for invalid email addresses.
1922 * @param to String array of email addresses to check.
1923 * @param wrongEmailsOut Emails addresses that were invalid.
1924 */
1925 public void checkInvalidEmails(String[] to, List<String> wrongEmailsOut) {
Mindy Pereirae5f20bf2012-06-25 14:20:40 -07001926 if (mValidator == null) {
1927 return;
1928 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08001929 for (String email : to) {
1930 if (!mValidator.isValid(email)) {
1931 wrongEmailsOut.add(email);
1932 }
1933 }
1934 }
1935
1936 /**
1937 * Show an error because the user has entered an invalid recipient.
1938 * @param message
1939 */
1940 public void showRecipientErrorDialog(String message) {
1941 // Only 1 invalid recipients error dialog should be allowed up at a
1942 // time.
1943 if (mRecipientErrorDialog != null) {
1944 mRecipientErrorDialog.dismiss();
1945 }
1946 mRecipientErrorDialog = new AlertDialog.Builder(this).setMessage(message).setTitle(
1947 R.string.recipient_error_dialog_title)
1948 .setIconAttribute(android.R.attr.alertDialogIcon)
Mindy Pereira82cc5662012-01-09 17:29:30 -08001949 .setPositiveButton(
1950 R.string.ok, new Dialog.OnClickListener() {
Marc Blank0bbc8582012-04-23 15:07:57 -07001951 @Override
Mindy Pereira82cc5662012-01-09 17:29:30 -08001952 public void onClick(DialogInterface dialog, int which) {
1953 // after the user dismisses the recipient error
1954 // dialog we want to make sure to refocus the
1955 // recipient to field so they can fix the issue
1956 // easily
1957 if (mTo != null) {
1958 mTo.requestFocus();
1959 }
1960 mRecipientErrorDialog = null;
1961 }
1962 }).show();
1963 }
1964
1965 /**
1966 * Update the state of the UI based on whether or not the current draft
1967 * needs to be saved and the message is not empty.
1968 */
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08001969 public void updateSaveUi() {
Mindy Pereira82cc5662012-01-09 17:29:30 -08001970 if (mSave != null) {
1971 mSave.setEnabled((shouldSave() && !isBlank()));
1972 }
1973 }
1974
1975 /**
1976 * Returns true if we need to save the current draft.
1977 */
1978 private boolean shouldSave() {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08001979 synchronized (mDraftLock) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08001980 // The message should only be saved if:
1981 // It hasn't been sent AND
1982 // Some text has been added to the message OR
1983 // an attachment has been added or removed
Mindy Pereiraa2148332012-07-02 13:54:14 -07001984 // AND there is actually something in the draft to save.
Andy Huangd47877e2012-08-09 19:31:24 -07001985 return (mTextChanged || mAttachmentsChanged || mReplyFromChanged)
Mindy Pereiraa2148332012-07-02 13:54:14 -07001986 && !isBlank();
Mindy Pereira82cc5662012-01-09 17:29:30 -08001987 }
1988 }
1989
1990 /**
Mindy Pereirabdf7a402012-03-01 15:23:26 -08001991 * Check if all fields are blank.
Mindy Pereira82cc5662012-01-09 17:29:30 -08001992 * @return boolean
1993 */
1994 public boolean isBlank() {
1995 return mSubject.getText().length() == 0
Mindy Pereirabdf7a402012-03-01 15:23:26 -08001996 && (mBodyView.getText().length() == 0 || getSignatureStartPosition(mSignature,
1997 mBodyView.getText().toString()) == 0)
1998 && mTo.length() == 0
1999 && mCc.length() == 0 && mBcc.length() == 0
2000 && mAttachmentsView.getAttachments().size() == 0;
2001 }
2002
2003 @VisibleForTesting
2004 protected int getSignatureStartPosition(String signature, String bodyText) {
2005 int startPos = -1;
2006
2007 if (TextUtils.isEmpty(signature) || TextUtils.isEmpty(bodyText)) {
2008 return startPos;
2009 }
2010
2011 int bodyLength = bodyText.length();
2012 int signatureLength = signature.length();
2013 String printableVersion = convertToPrintableSignature(signature);
2014 int printableLength = printableVersion.length();
2015
2016 if (bodyLength >= printableLength
2017 && bodyText.substring(bodyLength - printableLength)
2018 .equals(printableVersion)) {
2019 startPos = bodyLength - printableLength;
2020 } else if (bodyLength >= signatureLength
2021 && bodyText.substring(bodyLength - signatureLength)
2022 .equals(signature)) {
2023 startPos = bodyLength - signatureLength;
2024 }
2025 return startPos;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002026 }
2027
2028 /**
2029 * Allows any changes made by the user to be ignored. Called when the user
2030 * decides to discard a draft.
2031 */
2032 private void discardChanges() {
2033 mTextChanged = false;
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002034 mAttachmentsChanged = false;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002035 mReplyFromChanged = false;
2036 }
2037
2038 /**
Mindy Pereira181df782012-03-01 13:32:44 -08002039 * @param body
2040 * @param save
2041 * @param showToast
2042 * @return Whether the send or save succeeded.
2043 */
2044 protected boolean sendOrSaveWithSanityChecks(final boolean save, final boolean showToast,
2045 final boolean orientationChanged) {
Mark Wei009b3712012-10-18 18:07:50 -07002046 if (mAccounts == null || mAccount == null) {
2047 Toast.makeText(this, R.string.send_failed, Toast.LENGTH_SHORT).show();
2048 return false;
2049 }
2050
Mindy Pereira181df782012-03-01 13:32:44 -08002051 String[] to, cc, bcc;
2052 Editable body = mBodyView.getEditableText();
Mindy Pereira181df782012-03-01 13:32:44 -08002053 if (orientationChanged) {
2054 to = cc = bcc = new String[0];
2055 } else {
2056 to = getToAddresses();
2057 cc = getCcAddresses();
2058 bcc = getBccAddresses();
2059 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002060
Mindy Pereira181df782012-03-01 13:32:44 -08002061 // Don't let the user send to nobody (but it's okay to save a message
2062 // with no recipients)
2063 if (!save && (to.length == 0 && cc.length == 0 && bcc.length == 0)) {
2064 showRecipientErrorDialog(getString(R.string.recipient_needed));
2065 return false;
2066 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002067
Mindy Pereira181df782012-03-01 13:32:44 -08002068 List<String> wrongEmails = new ArrayList<String>();
2069 if (!save) {
2070 checkInvalidEmails(to, wrongEmails);
2071 checkInvalidEmails(cc, wrongEmails);
2072 checkInvalidEmails(bcc, wrongEmails);
2073 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002074
Mindy Pereira181df782012-03-01 13:32:44 -08002075 // Don't let the user send an email with invalid recipients
2076 if (wrongEmails.size() > 0) {
2077 String errorText = String.format(getString(R.string.invalid_recipient),
2078 wrongEmails.get(0));
2079 showRecipientErrorDialog(errorText);
2080 return false;
2081 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002082
Mindy Pereira181df782012-03-01 13:32:44 -08002083 DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
Marc Blank0bbc8582012-04-23 15:07:57 -07002084 @Override
Mindy Pereira181df782012-03-01 13:32:44 -08002085 public void onClick(DialogInterface dialog, int which) {
2086 sendOrSave(mBodyView.getEditableText(), save, showToast, orientationChanged);
2087 }
2088 };
Mindy Pereira82cc5662012-01-09 17:29:30 -08002089
Mindy Pereira181df782012-03-01 13:32:44 -08002090 // Show a warning before sending only if there are no attachments.
2091 if (!save) {
2092 if (mAttachmentsView.getAttachments().isEmpty() && showEmptyTextWarnings()) {
2093 boolean warnAboutEmptySubject = isSubjectEmpty();
2094 boolean emptyBody = TextUtils.getTrimmedLength(body) == 0;
Mindy Pereira82cc5662012-01-09 17:29:30 -08002095
Mindy Pereira181df782012-03-01 13:32:44 -08002096 // A warning about an empty body may not be warranted when
2097 // forwarding mails, since a common use case is to forward
2098 // quoted text and not append any more text.
2099 boolean warnAboutEmptyBody = emptyBody && (!mForward || isBodyEmpty());
Mindy Pereira82cc5662012-01-09 17:29:30 -08002100
Mindy Pereira181df782012-03-01 13:32:44 -08002101 // When we bring up a dialog warning the user about a send,
2102 // assume that they accept sending the message. If they do not,
2103 // the dialog listener is required to enable sending again.
2104 if (warnAboutEmptySubject) {
2105 showSendConfirmDialog(R.string.confirm_send_message_with_no_subject, listener);
2106 return true;
2107 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002108
Mindy Pereira181df782012-03-01 13:32:44 -08002109 if (warnAboutEmptyBody) {
2110 showSendConfirmDialog(R.string.confirm_send_message_with_no_body, listener);
2111 return true;
2112 }
2113 }
2114 // Ask for confirmation to send (if always required)
2115 if (showSendConfirmation()) {
2116 showSendConfirmDialog(R.string.confirm_send_message, listener);
2117 return true;
2118 }
2119 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002120
Mindy Pereira181df782012-03-01 13:32:44 -08002121 sendOrSave(body, save, showToast, false);
2122 return true;
2123 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002124
Mindy Pereira181df782012-03-01 13:32:44 -08002125 /**
2126 * Returns a boolean indicating whether warnings should be shown for empty
2127 * subject and body fields
Andy Huang5c5fd572012-04-08 18:19:29 -07002128 *
Mindy Pereira181df782012-03-01 13:32:44 -08002129 * @return True if a warning should be shown for empty text fields
2130 */
2131 protected boolean showEmptyTextWarnings() {
2132 return mAttachmentsView.getAttachments().size() == 0;
2133 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002134
Mindy Pereira181df782012-03-01 13:32:44 -08002135 /**
2136 * Returns a boolean indicating whether the user should confirm each send
2137 *
2138 * @return True if a warning should be on each send
2139 */
2140 protected boolean showSendConfirmation() {
2141 return mCachedSettings != null ? mCachedSettings.confirmSend : false;
2142 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002143
Mindy Pereira181df782012-03-01 13:32:44 -08002144 private void showSendConfirmDialog(int messageId, DialogInterface.OnClickListener listener) {
2145 if (mSendConfirmDialog != null) {
2146 mSendConfirmDialog.dismiss();
2147 mSendConfirmDialog = null;
2148 }
2149 mSendConfirmDialog = new AlertDialog.Builder(this).setMessage(messageId)
2150 .setTitle(R.string.confirm_send_title)
2151 .setIconAttribute(android.R.attr.alertDialogIcon)
2152 .setPositiveButton(R.string.send, listener)
Mindy Pereira6edd5972012-06-19 10:22:36 -07002153 .setNegativeButton(R.string.cancel, this)
2154 .show();
Mindy Pereira181df782012-03-01 13:32:44 -08002155 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002156
Mindy Pereira181df782012-03-01 13:32:44 -08002157 /**
2158 * Returns whether the ComposeArea believes there is any text in the body of
2159 * the composition. TODO: When ComposeArea controls the Body as well, add
2160 * that here.
2161 */
2162 public boolean isBodyEmpty() {
2163 return !mQuotedTextView.isTextIncluded();
2164 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002165
Mindy Pereira181df782012-03-01 13:32:44 -08002166 /**
2167 * Test to see if the subject is empty.
2168 *
2169 * @return boolean.
2170 */
2171 // TODO: this will likely go away when composeArea.focus() is implemented
2172 // after all the widget control is moved over.
2173 public boolean isSubjectEmpty() {
2174 return TextUtils.getTrimmedLength(mSubject.getText()) == 0;
2175 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002176
Mindy Pereira181df782012-03-01 13:32:44 -08002177 /* package */
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002178 static int sendOrSaveInternal(Context context, ReplyFromAccount replyFromAccount,
Paul Westbrook05b92b82012-04-20 13:29:37 -07002179 Message message, final Message refMessage, Spanned body, final CharSequence quotedText,
2180 SendOrSaveCallback callback, Handler handler, boolean save, int composeMode) {
Mindy Pereira29ef1b82012-01-13 11:26:21 -08002181 ContentValues values = new ContentValues();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002182
Mindy Pereirac2031972012-04-03 09:38:35 -07002183 String refMessageId = refMessage != null ? refMessage.uri.toString() : "";
2184
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002185 MessageModification.putToAddresses(values, message.getToAddresses());
2186 MessageModification.putCcAddresses(values, message.getCcAddresses());
2187 MessageModification.putBccAddresses(values, message.getBccAddresses());
Mindy Pereira82cc5662012-01-09 17:29:30 -08002188
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002189 MessageModification.putCustomFromAddress(values, message.from);
Mindy Pereira92551d02012-04-05 11:31:12 -07002190
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002191 MessageModification.putSubject(values, message.subject);
mindyped9c2f02012-10-12 10:02:08 -07002192 String htmlBody = Html.toHtml(new SpannableString(body.toString()));
Paul Westbrook05b92b82012-04-20 13:29:37 -07002193
Mindy Pereira29ef1b82012-01-13 11:26:21 -08002194 boolean includeQuotedText = !TextUtils.isEmpty(quotedText);
2195 StringBuilder fullBody = new StringBuilder(htmlBody);
2196 if (includeQuotedText) {
Mindy Pereirae8caf122012-03-20 15:23:31 -07002197 // HTML gets converted to text for now
2198 final String text = quotedText.toString();
2199 if (QuotedTextView.containsQuotedText(text)) {
2200 int pos = QuotedTextView.getQuotedTextOffset(text);
Paul Westbrook55271cf2012-04-20 16:25:02 -07002201 final int quoteStartPos = fullBody.length() + pos;
2202 fullBody.append(text);
2203 MessageModification.putQuoteStartPos(values, quoteStartPos);
Mindy Pereira12575862012-03-21 16:30:54 -07002204 MessageModification.putForward(values, composeMode == ComposeActivity.FORWARD);
Mindy Pereirae8caf122012-03-20 15:23:31 -07002205 MessageModification.putAppendRefMessageContent(values, includeQuotedText);
Mindy Pereira29ef1b82012-01-13 11:26:21 -08002206 } else {
Mindy Pereirae8caf122012-03-20 15:23:31 -07002207 LogUtils.w(LOG_TAG, "Couldn't find quoted text");
2208 // This shouldn't happen, but just use what we have,
2209 // and don't do server-side expansion
2210 fullBody.append(text);
Mindy Pereira29ef1b82012-01-13 11:26:21 -08002211 }
2212 }
Mindy Pereira002ff522012-05-30 10:31:26 -07002213 int draftType = getDraftType(composeMode);
Mindy Pereira12575862012-03-21 16:30:54 -07002214 MessageModification.putDraftType(values, draftType);
Mindy Pereirac6f1e2a2012-04-04 10:33:45 -07002215 if (refMessage != null) {
2216 if (!TextUtils.isEmpty(refMessage.bodyHtml)) {
2217 MessageModification.putBodyHtml(values, fullBody.toString());
2218 }
2219 if (!TextUtils.isEmpty(refMessage.bodyText)) {
2220 MessageModification.putBody(values, Html.fromHtml(fullBody.toString()).toString());
2221 }
2222 } else {
Mindy Pereirac2031972012-04-03 09:38:35 -07002223 MessageModification.putBodyHtml(values, fullBody.toString());
Mindy Pereirac2031972012-04-03 09:38:35 -07002224 MessageModification.putBody(values, Html.fromHtml(fullBody.toString()).toString());
2225 }
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002226 MessageModification.putAttachments(values, message.getAttachments());
Mindy Pereira12575862012-03-21 16:30:54 -07002227 if (!TextUtils.isEmpty(refMessageId)) {
2228 MessageModification.putRefMessageId(values, refMessageId);
2229 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002230
Mindy Pereira92551d02012-04-05 11:31:12 -07002231 SendOrSaveMessage sendOrSaveMessage = new SendOrSaveMessage(replyFromAccount,
Mindy Pereira181df782012-03-01 13:32:44 -08002232 values, refMessageId, save);
2233 SendOrSaveTask sendOrSaveTask = new SendOrSaveTask(context, sendOrSaveMessage, callback);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002234
Mindy Pereira181df782012-03-01 13:32:44 -08002235 callback.initializeSendOrSave(sendOrSaveTask);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002236
Mindy Pereira181df782012-03-01 13:32:44 -08002237 // Do the send/save action on the specified handler to avoid possible
2238 // ANRs
2239 handler.post(sendOrSaveTask);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002240
Mindy Pereira181df782012-03-01 13:32:44 -08002241 return sendOrSaveMessage.requestId();
2242 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002243
Mindy Pereira002ff522012-05-30 10:31:26 -07002244 private static int getDraftType(int mode) {
2245 int draftType = -1;
2246 switch (mode) {
2247 case ComposeActivity.COMPOSE:
2248 draftType = DraftType.COMPOSE;
2249 break;
2250 case ComposeActivity.REPLY:
2251 draftType = DraftType.REPLY;
2252 break;
2253 case ComposeActivity.REPLY_ALL:
2254 draftType = DraftType.REPLY_ALL;
2255 break;
2256 case ComposeActivity.FORWARD:
2257 draftType = DraftType.FORWARD;
2258 break;
2259 }
2260 return draftType;
2261 }
2262
Mindy Pereira181df782012-03-01 13:32:44 -08002263 private void sendOrSave(Spanned body, boolean save, boolean showToast,
2264 boolean orientationChanged) {
2265 // Check if user is a monkey. Monkeys can compose and hit send
2266 // button but are not allowed to send anything off the device.
Paul Westbrook3ae824c2012-04-06 13:29:39 -07002267 if (ActivityManager.isUserAMonkey()) {
Mindy Pereira181df782012-03-01 13:32:44 -08002268 return;
2269 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002270
Mindy Pereira181df782012-03-01 13:32:44 -08002271 String[] to, cc, bcc;
2272 if (orientationChanged) {
2273 to = cc = bcc = new String[0];
2274 } else {
2275 to = getToAddresses();
2276 cc = getCcAddresses();
2277 bcc = getBccAddresses();
2278 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002279
Mindy Pereira181df782012-03-01 13:32:44 -08002280 SendOrSaveCallback callback = new SendOrSaveCallback() {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002281 private int mRestoredRequestId;
2282
Marc Blank0bbc8582012-04-23 15:07:57 -07002283 @Override
Mindy Pereira82cc5662012-01-09 17:29:30 -08002284 public void initializeSendOrSave(SendOrSaveTask sendOrSaveTask) {
Mindy Pereira181df782012-03-01 13:32:44 -08002285 synchronized (mActiveTasks) {
2286 int numTasks = mActiveTasks.size();
2287 if (numTasks == 0) {
2288 // Start service so we won't be killed if this app is
2289 // put in the background.
2290 startService(new Intent(ComposeActivity.this, EmptyService.class));
2291 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002292
Mindy Pereira181df782012-03-01 13:32:44 -08002293 mActiveTasks.add(sendOrSaveTask);
2294 }
2295 if (sTestSendOrSaveCallback != null) {
2296 sTestSendOrSaveCallback.initializeSendOrSave(sendOrSaveTask);
2297 }
2298 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002299
Marc Blank0bbc8582012-04-23 15:07:57 -07002300 @Override
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002301 public void notifyMessageIdAllocated(SendOrSaveMessage sendOrSaveMessage,
2302 Message message) {
Mindy Pereira181df782012-03-01 13:32:44 -08002303 synchronized (mDraftLock) {
2304 mDraftId = message.id;
2305 mDraft = message;
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002306 if (sRequestMessageIdMap != null) {
2307 sRequestMessageIdMap.put(sendOrSaveMessage.requestId(), mDraftId);
2308 }
Mindy Pereira181df782012-03-01 13:32:44 -08002309 // Cache request message map, in case the process is killed
2310 saveRequestMap();
2311 }
2312 if (sTestSendOrSaveCallback != null) {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002313 sTestSendOrSaveCallback.notifyMessageIdAllocated(sendOrSaveMessage, message);
Mindy Pereira181df782012-03-01 13:32:44 -08002314 }
2315 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002316
Marc Blank0bbc8582012-04-23 15:07:57 -07002317 @Override
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002318 public Message getMessage() {
2319 synchronized (mDraftLock) {
2320 return mDraft;
2321 }
2322 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002323
Marc Blank0bbc8582012-04-23 15:07:57 -07002324 @Override
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002325 public void sendOrSaveFinished(SendOrSaveTask task, boolean success) {
Mindy Pereira47d0e652012-07-23 09:45:07 -07002326 // Update the last sent from account.
2327 if (mAccount != null) {
2328 MailAppProvider.getInstance().setLastSentFromAccount(mAccount.uri.toString());
2329 }
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002330 if (success) {
2331 // Successfully sent or saved so reset change markers
2332 discardChanges();
2333 } else {
2334 // A failure happened with saving/sending the draft
2335 // TODO(pwestbro): add a better string that should be used
2336 // when failing to send or save
2337 Toast.makeText(ComposeActivity.this, R.string.send_failed, Toast.LENGTH_SHORT)
2338 .show();
2339 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002340
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002341 int numTasks;
2342 synchronized (mActiveTasks) {
2343 // Remove the task from the list of active tasks
2344 mActiveTasks.remove(task);
2345 numTasks = mActiveTasks.size();
2346 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002347
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002348 if (numTasks == 0) {
2349 // Stop service so we can be killed.
2350 stopService(new Intent(ComposeActivity.this, EmptyService.class));
2351 }
2352 if (sTestSendOrSaveCallback != null) {
2353 sTestSendOrSaveCallback.sendOrSaveFinished(task, success);
2354 }
2355 }
Mindy Pereira181df782012-03-01 13:32:44 -08002356 };
Mindy Pereira82cc5662012-01-09 17:29:30 -08002357
Mindy Pereira181df782012-03-01 13:32:44 -08002358 // Get the selected account if the from spinner has been setup.
Mindy Pereira92551d02012-04-05 11:31:12 -07002359 ReplyFromAccount selectedAccount = mReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -08002360 String fromAddress = selectedAccount.name;
2361 if (selectedAccount == null || fromAddress == null) {
2362 // We don't have either the selected account or from address,
2363 // use mAccount.
Mindy Pereira92551d02012-04-05 11:31:12 -07002364 selectedAccount = mReplyFromAccount;
Mindy Pereira181df782012-03-01 13:32:44 -08002365 fromAddress = mAccount.name;
2366 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002367
Mindy Pereira181df782012-03-01 13:32:44 -08002368 if (mSendSaveTaskHandler == null) {
2369 HandlerThread handlerThread = new HandlerThread("Send Message Task Thread");
2370 handlerThread.start();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002371
Mindy Pereira181df782012-03-01 13:32:44 -08002372 mSendSaveTaskHandler = new Handler(handlerThread.getLooper());
2373 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002374
Mindy Pereirae8f94dc2012-04-16 11:56:21 -07002375 Message msg = createMessage(mReplyFromAccount, getMode());
Paul Westbrook05b92b82012-04-20 13:29:37 -07002376 mRequestId = sendOrSaveInternal(this, mReplyFromAccount, msg, mRefMessage, body,
2377 mQuotedTextView.getQuotedTextIfIncluded(), callback,
Mindy Pereira12575862012-03-21 16:30:54 -07002378 mSendSaveTaskHandler, save, mComposeMode);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002379
Mindy Pereira181df782012-03-01 13:32:44 -08002380 if (mRecipient != null && mRecipient.equals(mAccount.name)) {
2381 mRecipient = selectedAccount.name;
2382 }
Paul Westbrookb1f573c2012-04-06 11:38:28 -07002383 setAccount(selectedAccount.account);
Mindy Pereira82cc5662012-01-09 17:29:30 -08002384
Mindy Pereira181df782012-03-01 13:32:44 -08002385 // Don't display the toast if the user is just changing the orientation,
2386 // but we still need to save the draft to the cursor because this is how we restore
2387 // the attachments when the configuration change completes.
2388 if (showToast && (getChangingConfigurations() & ActivityInfo.CONFIG_ORIENTATION) == 0) {
2389 Toast.makeText(this, save ? R.string.message_saved : R.string.sending_message,
2390 Toast.LENGTH_LONG).show();
2391 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002392
Mindy Pereira181df782012-03-01 13:32:44 -08002393 // Need to update variables here because the send or save completes
2394 // asynchronously even though the toast shows right away.
2395 discardChanges();
2396 updateSaveUi();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002397
Mindy Pereira181df782012-03-01 13:32:44 -08002398 // If we are sending, finish the activity
2399 if (!save) {
2400 finish();
2401 }
2402 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002403
Mindy Pereira181df782012-03-01 13:32:44 -08002404 /**
2405 * Save the state of the request messageid map. This allows for the Gmail
2406 * process to be killed, but and still allow for ComposeActivity instances
2407 * to be recreated correctly.
2408 */
2409 private void saveRequestMap() {
2410 // TODO: store the request map in user preferences.
2411 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002412
Mindy Pereira2db7d4a2012-08-15 11:00:02 -07002413 private void doAttach(String type) {
Mindy Pereira013194c2012-01-06 15:09:33 -08002414 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2415 i.addCategory(Intent.CATEGORY_OPENABLE);
Paul Westbrookd6a9a3f2012-04-26 18:47:23 -07002416 i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
Mindy Pereira2db7d4a2012-08-15 11:00:02 -07002417 i.setType(type);
Mindy Pereira013194c2012-01-06 15:09:33 -08002418 mAddingAttachment = true;
Mindy Pereira181df782012-03-01 13:32:44 -08002419 startActivityForResult(Intent.createChooser(i, getText(R.string.select_attachment_type)),
2420 RESULT_PICK_ATTACHMENT);
Mindy Pereira013194c2012-01-06 15:09:33 -08002421 }
2422
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08002423 private void showCcBccViews() {
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08002424 mCcBccView.show(true, true, true);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08002425 if (mCcBccButton != null) {
mindypcd0b0b92012-08-23 14:33:17 -07002426 mCcBccButton.setVisibility(View.INVISIBLE);
Mindy Pereiraec8b0ed2012-01-06 10:35:59 -08002427 }
2428 }
2429
Mindy Pereira326c6602012-01-04 15:32:42 -08002430 @Override
2431 public boolean onNavigationItemSelected(int position, long itemId) {
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08002432 int initialComposeMode = mComposeMode;
Mindy Pereira326c6602012-01-04 15:32:42 -08002433 if (position == ComposeActivity.REPLY) {
2434 mComposeMode = ComposeActivity.REPLY;
2435 } else if (position == ComposeActivity.REPLY_ALL) {
2436 mComposeMode = ComposeActivity.REPLY_ALL;
2437 } else if (position == ComposeActivity.FORWARD) {
2438 mComposeMode = ComposeActivity.FORWARD;
2439 }
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07002440 clearChangeListeners();
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08002441 if (initialComposeMode != mComposeMode) {
Mindy Pereira154386a2012-01-11 13:02:33 -08002442 resetMessageForModeChange();
Mindy Pereiraef388302012-06-18 19:07:44 -07002443 if (mDraft == null && mRefMessage != null) {
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07002444 setFieldsFromRefMessage(mComposeMode, mAccount.name);
Mindy Pereira8eca57a2012-03-20 16:42:34 -07002445 }
Mindy Pereiraef388302012-06-18 19:07:44 -07002446 boolean showCc = false;
2447 boolean showBcc = false;
2448 if (mDraft != null) {
2449 // Following desktop behavior, if the user has added a BCC
2450 // field to a draft, we show it regardless of compose mode.
2451 showBcc = !TextUtils.isEmpty(mDraft.bcc);
2452 // Use the draft to determine what to populate.
2453 // If the Bcc field is showing, show the Cc field whether it is populated or not.
2454 showCc = showBcc || (!TextUtils.isEmpty(mDraft.cc) && mComposeMode == REPLY_ALL);
2455 } else if (mRefMessage != null) {
mindyp9b1ac572012-09-27 14:12:00 -07002456 showCc = !TextUtils.isEmpty(mCc.getText());
Mindy Pereiraef388302012-06-18 19:07:44 -07002457 }
2458 mCcBccView.show(false, showCc, showBcc);
Mindy Pereiraa26b54e2012-01-06 12:54:33 -08002459 }
Mindy Pereiraef388302012-06-18 19:07:44 -07002460 updateHideOrShowCcBcc();
Mindy Pereiracbfb75a2012-06-25 14:52:23 -07002461 initChangeListeners();
Mindy Pereira326c6602012-01-04 15:32:42 -08002462 return true;
2463 }
2464
Mindy Pereirab3112a22012-06-20 12:10:03 -07002465 @VisibleForTesting
2466 protected void resetMessageForModeChange() {
Mindy Pereira154386a2012-01-11 13:02:33 -08002467 // When switching between reply, reply all, forward,
2468 // follow the behavior of webview.
2469 // The contents of the following fields are cleared
2470 // so that they can be populated directly from the
2471 // ref message:
2472 // 1) Any recipient fields
2473 // 2) The subject
2474 mTo.setText("");
2475 mCc.setText("");
2476 mBcc.setText("");
2477 // Any edits to the subject are replaced with the original subject.
2478 mSubject.setText("");
2479
2480 // Any changes to the contents of the following fields are kept:
2481 // 1) Body
2482 // 2) Attachments
2483 // If the user made changes to attachments, keep their changes.
2484 if (!mAttachmentsChanged) {
2485 mAttachmentsView.deleteAllAttachments();
2486 }
2487 }
2488
Mindy Pereira326c6602012-01-04 15:32:42 -08002489 private class ComposeModeAdapter extends ArrayAdapter<String> {
2490
2491 private LayoutInflater mInflater;
2492
2493 public ComposeModeAdapter(Context context) {
2494 super(context, R.layout.compose_mode_item, R.id.mode, getResources()
2495 .getStringArray(R.array.compose_modes));
2496 }
2497
2498 private LayoutInflater getInflater() {
2499 if (mInflater == null) {
2500 mInflater = LayoutInflater.from(getContext());
2501 }
2502 return mInflater;
2503 }
2504
2505 @Override
2506 public View getView(int position, View convertView, ViewGroup parent) {
2507 if (convertView == null) {
2508 convertView = getInflater().inflate(R.layout.compose_mode_display_item, null);
2509 }
2510 ((TextView) convertView.findViewById(R.id.mode)).setText(getItem(position));
2511 return super.getView(position, convertView, parent);
2512 }
2513 }
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002514
2515 @Override
2516 public void onRespondInline(String text) {
2517 appendToBody(text, false);
mindyp40882432012-09-06 11:07:40 -07002518 mQuotedTextView.setUpperDividerVisible(false);
2519 mTo.requestFocus();
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002520 }
2521
2522 /**
2523 * Append text to the body of the message. If there is no existing body
2524 * text, just sets the body to text.
2525 *
2526 * @param text
2527 * @param withSignature True to append a signature.
2528 */
2529 public void appendToBody(CharSequence text, boolean withSignature) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002530 Editable bodyText = mBodyView.getEditableText();
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002531 if (bodyText != null && bodyText.length() > 0) {
2532 bodyText.append(text);
2533 } else {
2534 setBody(text, withSignature);
2535 }
2536 }
2537
2538 /**
2539 * Set the body of the message.
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002540 *
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002541 * @param text
2542 * @param withSignature True to append a signature.
2543 */
2544 public void setBody(CharSequence text, boolean withSignature) {
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002545 mBodyView.setText(text);
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002546 if (withSignature) {
2547 appendSignature();
2548 }
2549 }
2550
2551 private void appendSignature() {
Mindy Pereirab13917c2012-03-29 08:08:19 -07002552 String newSignature = mCachedSettings != null ? mCachedSettings.signature : null;
Mindy Pereira433b1982012-04-03 11:53:07 -07002553 boolean hasFocus = mBodyView.hasFocus();
Mindy Pereirab13917c2012-03-29 08:08:19 -07002554 if (!TextUtils.equals(newSignature, mSignature)) {
2555 mSignature = newSignature;
2556 if (!TextUtils.isEmpty(mSignature)
2557 && getSignatureStartPosition(mSignature,
2558 mBodyView.getText().toString()) < 0) {
2559 // Appending a signature does not count as changing text.
2560 mBodyView.removeTextChangedListener(this);
2561 mBodyView.append(convertToPrintableSignature(mSignature));
2562 mBodyView.addTextChangedListener(this);
2563 }
Mindy Pereira433b1982012-04-03 11:53:07 -07002564 if (hasFocus) {
2565 focusBody();
2566 }
Mindy Pereirabdf7a402012-03-01 15:23:26 -08002567 }
2568 }
2569
2570 private String convertToPrintableSignature(String signature) {
2571 String signatureResource = getResources().getString(R.string.signature);
2572 if (signature == null) {
2573 signature = "";
2574 }
2575 return String.format(signatureResource, signature);
Mindy Pereira46ce0b12012-01-05 10:32:15 -08002576 }
Mindy Pereira1a95a572012-01-05 12:21:29 -08002577
Mindy Pereira5a85e2b2012-01-11 09:53:32 -08002578 @Override
2579 public void onAccountChanged() {
Mindy Pereira92551d02012-04-05 11:31:12 -07002580 mReplyFromAccount = mFromSpinner.getCurrentAccount();
2581 if (!mAccount.equals(mReplyFromAccount.account)) {
Paul Westbrookb1f573c2012-04-06 11:38:28 -07002582 setAccount(mReplyFromAccount.account);
2583
Mindy Pereira181df782012-03-01 13:32:44 -08002584 // TODO: handle discarding attachments when switching accounts.
2585 // Only enable save for this draft if there is any other content
2586 // in the message.
2587 if (!isBlank()) {
2588 enableSave(true);
2589 }
2590 mReplyFromChanged = true;
2591 initRecipients();
Mindy Pereira82cc5662012-01-09 17:29:30 -08002592 }
Mindy Pereira1a95a572012-01-05 12:21:29 -08002593 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002594
2595 public void enableSave(boolean enabled) {
2596 if (mSave != null) {
2597 mSave.setEnabled(enabled);
2598 }
2599 }
2600
2601 public void enableSend(boolean enabled) {
2602 if (mSend != null) {
2603 mSend.setEnabled(enabled);
2604 }
2605 }
2606
2607 /**
2608 * Handles button clicks from any error dialogs dealing with sending
2609 * a message.
2610 */
2611 @Override
2612 public void onClick(DialogInterface dialog, int which) {
2613 switch (which) {
2614 case DialogInterface.BUTTON_POSITIVE: {
2615 doDiscardWithoutConfirmation(true /* show toast */ );
2616 break;
2617 }
2618 case DialogInterface.BUTTON_NEGATIVE: {
2619 // If the user cancels the send, re-enable the send button.
2620 enableSend(true);
2621 break;
2622 }
2623 }
2624
2625 }
2626
Mindy Pereiraefe3d252012-03-01 14:20:44 -08002627 private void doDiscard() {
2628 new AlertDialog.Builder(this).setMessage(R.string.confirm_discard_text)
2629 .setPositiveButton(R.string.ok, this)
2630 .setNegativeButton(R.string.cancel, null)
2631 .create().show();
2632 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002633 /**
2634 * Effectively discard the current message.
2635 *
2636 * This method is either invoked from the menu or from the dialog
2637 * once the user has confirmed that they want to discard the message.
2638 * @param showToast show "Message discarded" toast if true
2639 */
2640 private void doDiscardWithoutConfirmation(boolean showToast) {
Mindy Pereira7ed1c112012-01-18 10:59:25 -08002641 synchronized (mDraftLock) {
Mindy Pereira82cc5662012-01-09 17:29:30 -08002642 if (mDraftId != UIProvider.INVALID_MESSAGE_ID) {
2643 ContentValues values = new ContentValues();
Paul Westbrookb7050e62012-03-20 12:59:44 -07002644 values.put(BaseColumns._ID, mDraftId);
Marc Blank78ea8e22012-08-04 11:14:06 -07002645 if (!mAccount.expungeMessageUri.equals(Uri.EMPTY)) {
Mindy Pereiracfb7f332012-02-28 10:23:43 -08002646 getContentResolver().update(mAccount.expungeMessageUri, values, null, null);
2647 } else {
Marc Blank0bbc8582012-04-23 15:07:57 -07002648 getContentResolver().delete(mDraft.uri, null, null);
Mindy Pereiracfb7f332012-02-28 10:23:43 -08002649 }
Mindy Pereira82cc5662012-01-09 17:29:30 -08002650 // This is not strictly necessary (since we should not try to
2651 // save the draft after calling this) but it ensures that if we
2652 // do save again for some reason we make a new draft rather than
2653 // trying to resave an expunged draft.
2654 mDraftId = UIProvider.INVALID_MESSAGE_ID;
2655 }
2656 }
2657
2658 if (showToast) {
2659 // Display a toast to let the user know
2660 Toast.makeText(this, R.string.message_discarded, Toast.LENGTH_SHORT).show();
2661 }
2662
2663 // This prevents the draft from being saved in onPause().
2664 discardChanges();
2665 finish();
2666 }
2667
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002668 private void saveIfNeeded() {
2669 if (mAccount == null) {
2670 // We have not chosen an account yet so there's no way that we can save. This is ok,
2671 // though, since we are saving our state before AccountsActivity is activated. Thus, the
2672 // user has not interacted with us yet and there is no real state to save.
2673 return;
2674 }
2675
2676 if (shouldSave()) {
Mindy Pereira48e31b02012-05-30 13:12:24 -07002677 doSave(!mAddingAttachment /* show toast */);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002678 }
2679 }
2680
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002681 @Override
2682 public void onAttachmentDeleted() {
2683 mAttachmentsChanged = true;
mindyp40882432012-09-06 11:07:40 -07002684 // If we are showing any attachments, make sure we have an upper
2685 // divider.
2686 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
Mindy Pereiraeaea9f12012-01-10 15:05:27 -08002687 updateSaveUi();
2688 }
Mindy Pereira75f66632012-01-11 11:42:02 -08002689
mindyp40882432012-09-06 11:07:40 -07002690 @Override
2691 public void onAttachmentAdded() {
2692 mQuotedTextView.setUpperDividerVisible(mAttachmentsView.getAttachments().size() > 0);
2693 mAttachmentsView.focusLastAttachment();
2694 }
Mindy Pereira75f66632012-01-11 11:42:02 -08002695
2696 /**
2697 * This is called any time one of our text fields changes.
2698 */
Marc Blank0bbc8582012-04-23 15:07:57 -07002699 @Override
Mindy Pereira75f66632012-01-11 11:42:02 -08002700 public void afterTextChanged(Editable s) {
2701 mTextChanged = true;
2702 updateSaveUi();
2703 }
2704
2705 @Override
2706 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
2707 // Do nothing.
2708 }
2709
Marc Blank0bbc8582012-04-23 15:07:57 -07002710 @Override
Mindy Pereira75f66632012-01-11 11:42:02 -08002711 public void onTextChanged(CharSequence s, int start, int before, int count) {
2712 // Do nothing.
2713 }
2714
2715
2716 // There is a big difference between the text associated with an address changing
2717 // to add the display name or to format properly and a recipient being added or deleted.
2718 // Make sure we only notify of changes when a recipient has been added or deleted.
2719 private class RecipientTextWatcher implements TextWatcher {
2720 private HashMap<String, Integer> mContent = new HashMap<String, Integer>();
2721
2722 private RecipientEditTextView mView;
2723
2724 private TextWatcher mListener;
2725
2726 public RecipientTextWatcher(RecipientEditTextView view, TextWatcher listener) {
2727 mView = view;
2728 mListener = listener;
2729 }
2730
2731 @Override
2732 public void afterTextChanged(Editable s) {
2733 if (hasChanged()) {
2734 mListener.afterTextChanged(s);
2735 }
2736 }
2737
2738 private boolean hasChanged() {
2739 String[] currRecips = tokenizeRecips(getAddressesFromList(mView));
2740 int totalCount = currRecips.length;
2741 int totalPrevCount = 0;
2742 for (Entry<String, Integer> entry : mContent.entrySet()) {
2743 totalPrevCount += entry.getValue();
2744 }
2745 if (totalCount != totalPrevCount) {
2746 return true;
2747 }
2748
2749 for (String recip : currRecips) {
2750 if (!mContent.containsKey(recip)) {
2751 return true;
2752 } else {
2753 int count = mContent.get(recip) - 1;
2754 if (count < 0) {
2755 return true;
2756 } else {
2757 mContent.put(recip, count);
2758 }
2759 }
2760 }
2761 return false;
2762 }
2763
2764 private String[] tokenizeRecips(String[] recips) {
2765 // Tokenize them all and put them in the list.
2766 String[] recipAddresses = new String[recips.length];
2767 for (int i = 0; i < recips.length; i++) {
2768 recipAddresses[i] = Rfc822Tokenizer.tokenize(recips[i])[0].getAddress();
2769 }
2770 return recipAddresses;
2771 }
2772
2773 @Override
2774 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
2775 String[] recips = tokenizeRecips(getAddressesFromList(mView));
2776 for (String recip : recips) {
2777 if (!mContent.containsKey(recip)) {
2778 mContent.put(recip, 1);
2779 } else {
2780 mContent.put(recip, (mContent.get(recip)) + 1);
2781 }
2782 }
2783 }
2784
2785 @Override
2786 public void onTextChanged(CharSequence s, int start, int before, int count) {
2787 // Do nothing.
2788 }
2789 }
Mindy Pereirae011b1d2012-06-18 13:45:26 -07002790
2791 public static void registerTestSendOrSaveCallback(SendOrSaveCallback testCallback) {
2792 if (sTestSendOrSaveCallback != null && testCallback != null) {
2793 throw new IllegalStateException("Attempting to register more than one test callback");
2794 }
2795 sTestSendOrSaveCallback = testCallback;
2796 }
Mindy Pereirabddd6f32012-06-20 12:10:03 -07002797
2798 @VisibleForTesting
2799 protected ArrayList<Attachment> getAttachments() {
2800 return mAttachmentsView.getAttachments();
2801 }
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07002802
2803 @Override
2804 public Loader<Cursor> onCreateLoader(int id, Bundle args) {
2805 switch (id) {
2806 case REFERENCE_MESSAGE_LOADER:
2807 return new CursorLoader(this, mRefMessageUri, UIProvider.MESSAGE_PROJECTION, null,
2808 null, null);
Mindy Pereirab199d172012-08-13 11:04:03 -07002809 case LOADER_ACCOUNT_CURSOR:
2810 return new CursorLoader(this, MailAppProvider.getAccountsUri(),
2811 UIProvider.ACCOUNTS_PROJECTION, null, null, null);
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07002812 }
2813 return null;
2814 }
2815
2816 @Override
2817 public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Mindy Pereirab199d172012-08-13 11:04:03 -07002818 int id = loader.getId();
2819 switch (id) {
2820 case REFERENCE_MESSAGE_LOADER:
2821 if (data != null && data.moveToFirst()) {
2822 mRefMessage = new Message(data);
2823 // We set these based on EXTRA_TO.
2824 mRefMessage.to = null;
2825 mRefMessage.from = null;
2826 Intent intent = getIntent();
2827 int action = intent.getIntExtra(EXTRA_ACTION, COMPOSE);
2828 initFromRefMessage(action, mAccount.name);
2829 finishSetup(action, intent, null, true);
2830 if (action != FORWARD) {
2831 String to = intent.getStringExtra(EXTRA_TO);
2832 if (!TextUtils.isEmpty(to)) {
2833 clearChangeListeners();
2834 mTo.append(to);
2835 initChangeListeners();
2836 }
2837 }
2838 } else {
2839 finish();
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07002840 }
Mindy Pereirab199d172012-08-13 11:04:03 -07002841 break;
2842 case LOADER_ACCOUNT_CURSOR:
2843 if (data != null && data.moveToFirst()) {
2844 // there are accounts now!
2845 Account account;
2846 ArrayList<Account> accounts = new ArrayList<Account>();
2847 ArrayList<Account> initializedAccounts = new ArrayList<Account>();
2848 do {
2849 account = new Account(data);
Paul Westbrookdfa1dec2012-09-26 16:27:28 -07002850 if (account.isAccountReady()) {
Mindy Pereirab199d172012-08-13 11:04:03 -07002851 initializedAccounts.add(account);
2852 }
2853 accounts.add(account);
2854 } while (data.moveToNext());
2855 if (initializedAccounts.size() > 0) {
2856 findViewById(R.id.wait).setVisibility(View.GONE);
2857 getLoaderManager().destroyLoader(LOADER_ACCOUNT_CURSOR);
2858 findViewById(R.id.compose).setVisibility(View.VISIBLE);
2859 mAccounts = accounts.toArray(new Account[initializedAccounts.size()]);
2860 finishCreate();
2861 invalidateOptionsMenu();
2862 } else {
2863 // Show "waiting"
2864 account = accounts.size() > 0 ? accounts.get(0) : null;
2865 showWaitFragment(account);
2866 }
2867 }
2868 break;
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07002869 }
2870 }
2871
Mindy Pereirab199d172012-08-13 11:04:03 -07002872 private void showWaitFragment(Account account) {
2873 WaitFragment fragment = getWaitFragment();
2874 if (fragment != null) {
2875 fragment.updateAccount(account);
2876 } else {
2877 findViewById(R.id.wait).setVisibility(View.VISIBLE);
2878 replaceFragment(WaitFragment.newInstance(account, true),
2879 FragmentTransaction.TRANSIT_FRAGMENT_OPEN, TAG_WAIT);
2880 }
2881 }
2882
2883 private WaitFragment getWaitFragment() {
2884 return (WaitFragment) getFragmentManager().findFragmentByTag(TAG_WAIT);
2885 }
2886
2887 private int replaceFragment(Fragment fragment, int transition, String tag) {
2888 FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
2889 fragmentTransaction.addToBackStack(null);
2890 fragmentTransaction.setTransition(transition);
2891 fragmentTransaction.replace(R.id.wait, fragment, tag);
2892 final int transactionId = fragmentTransaction.commitAllowingStateLoss();
2893 return transactionId;
2894 }
2895
Mindy Pereira96a7f7a2012-07-09 16:51:06 -07002896 @Override
2897 public void onLoaderReset(Loader<Cursor> arg0) {
2898 // Do nothing.
2899 }
2900}