1/*
2 * Copyright (C) 2008 Esmertec AG.
3 * Copyright (C) 2008 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *      http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package com.android.mms.ui;
19
20import static android.content.res.Configuration.KEYBOARDHIDDEN_NO;
21import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_ABORT;
22import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_COMPLETE;
23import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_START;
24import static com.android.mms.transaction.ProgressCallbackEntity.PROGRESS_STATUS_ACTION;
25import static com.android.mms.ui.MessageListAdapter.COLUMN_ID;
26import static com.android.mms.ui.MessageListAdapter.COLUMN_MSG_TYPE;
27import static com.android.mms.ui.MessageListAdapter.PROJECTION;
28
29import java.io.File;
30import java.io.FileInputStream;
31import java.io.FileOutputStream;
32import java.io.IOException;
33import java.io.InputStream;
34import java.io.UnsupportedEncodingException;
35import java.net.URLDecoder;
36import java.util.ArrayList;
37import java.util.HashMap;
38import java.util.HashSet;
39import java.util.List;
40import java.util.Map;
41import java.util.regex.Pattern;
42
43import android.app.ActionBar;
44import android.app.Activity;
45import android.app.AlertDialog;
46import android.app.ProgressDialog;
47import android.content.ActivityNotFoundException;
48import android.content.BroadcastReceiver;
49import android.content.ClipData;
50import android.content.ClipboardManager;
51import android.content.ContentResolver;
52import android.content.ContentUris;
53import android.content.ContentValues;
54import android.content.Context;
55import android.content.DialogInterface;
56import android.content.DialogInterface.OnClickListener;
57import android.content.Intent;
58import android.content.IntentFilter;
59import android.content.res.Configuration;
60import android.content.res.Resources;
61import android.database.Cursor;
62import android.database.sqlite.SQLiteException;
63import android.database.sqlite.SqliteWrapper;
64import android.drm.DrmStore;
65import android.graphics.drawable.Drawable;
66import android.media.RingtoneManager;
67import android.net.Uri;
68import android.os.AsyncTask;
69import android.os.Bundle;
70import android.os.Environment;
71import android.os.Handler;
72import android.os.Message;
73import android.os.Parcelable;
74import android.os.SystemProperties;
75import android.provider.ContactsContract;
76import android.provider.ContactsContract.QuickContact;
77import android.provider.Telephony;
78import android.provider.ContactsContract.CommonDataKinds.Email;
79import android.provider.ContactsContract.CommonDataKinds.Phone;
80import android.provider.ContactsContract.Contacts;
81import android.provider.ContactsContract.Intents;
82import android.provider.MediaStore.Images;
83import android.provider.MediaStore.Video;
84import android.provider.Settings;
85import android.provider.Telephony.Mms;
86import android.provider.Telephony.Sms;
87import android.telephony.PhoneNumberUtils;
88import android.telephony.SmsMessage;
89import android.text.Editable;
90import android.text.InputFilter;
91import android.text.InputFilter.LengthFilter;
92import android.text.SpannableString;
93import android.text.Spanned;
94import android.text.TextUtils;
95import android.text.TextWatcher;
96import android.text.method.TextKeyListener;
97import android.text.style.URLSpan;
98import android.text.util.Linkify;
99import android.util.Log;
100import android.view.ContextMenu;
101import android.view.ContextMenu.ContextMenuInfo;
102import android.view.KeyEvent;
103import android.view.Menu;
104import android.view.MenuItem;
105import android.view.View;
106import android.view.View.OnCreateContextMenuListener;
107import android.view.View.OnKeyListener;
108import android.view.ViewStub;
109import android.view.WindowManager;
110import android.view.inputmethod.InputMethodManager;
111import android.webkit.MimeTypeMap;
112import android.widget.AdapterView;
113import android.widget.EditText;
114import android.widget.ImageButton;
115import android.widget.ImageView;
116import android.widget.ListView;
117import android.widget.SimpleAdapter;
118import android.widget.TextView;
119import android.widget.Toast;
120
121import com.android.internal.telephony.TelephonyIntents;
122import com.android.internal.telephony.TelephonyProperties;
123import com.android.mms.LogTag;
124import com.android.mms.MmsApp;
125import com.android.mms.MmsConfig;
126import com.android.mms.R;
127import com.android.mms.TempFileProvider;
128import com.android.mms.data.Contact;
129import com.android.mms.data.ContactList;
130import com.android.mms.data.Conversation;
131import com.android.mms.data.Conversation.ConversationQueryHandler;
132import com.android.mms.data.WorkingMessage;
133import com.android.mms.data.WorkingMessage.MessageStatusListener;
134import com.android.mms.drm.DrmUtils;
135import com.android.mms.model.SlideModel;
136import com.android.mms.model.SlideshowModel;
137import com.android.mms.transaction.MessagingNotification;
138import com.android.mms.ui.MessageListView.OnSizeChangedListener;
139import com.android.mms.ui.MessageUtils.ResizeImageResultCallback;
140import com.android.mms.ui.RecipientsEditor.RecipientContextMenuInfo;
141import com.android.mms.util.DraftCache;
142import com.android.mms.util.PhoneNumberFormatter;
143import com.android.mms.util.SendingProgressTokenManager;
144import com.android.mms.widget.MmsWidgetProvider;
145import com.google.android.mms.ContentType;
146import com.google.android.mms.MmsException;
147import com.google.android.mms.pdu.EncodedStringValue;
148import com.google.android.mms.pdu.PduBody;
149import com.google.android.mms.pdu.PduPart;
150import com.google.android.mms.pdu.PduPersister;
151import com.google.android.mms.pdu.SendReq;
152
153/**
154 * This is the main UI for:
155 * 1. Composing a new message;
156 * 2. Viewing/managing message history of a conversation.
157 *
158 * This activity can handle following parameters from the intent
159 * by which it's launched.
160 * thread_id long Identify the conversation to be viewed. When creating a
161 *         new message, this parameter shouldn't be present.
162 * msg_uri Uri The message which should be opened for editing in the editor.
163 * address String The addresses of the recipients in current conversation.
164 * exit_on_sent boolean Exit this activity after the message is sent.
165 */
166public class ComposeMessageActivity extends Activity
167        implements View.OnClickListener, TextView.OnEditorActionListener,
168        MessageStatusListener, Contact.UpdateListener {
169    public static final int REQUEST_CODE_ATTACH_IMAGE     = 100;
170    public static final int REQUEST_CODE_TAKE_PICTURE     = 101;
171    public static final int REQUEST_CODE_ATTACH_VIDEO     = 102;
172    public static final int REQUEST_CODE_TAKE_VIDEO       = 103;
173    public static final int REQUEST_CODE_ATTACH_SOUND     = 104;
174    public static final int REQUEST_CODE_RECORD_SOUND     = 105;
175    public static final int REQUEST_CODE_CREATE_SLIDESHOW = 106;
176    public static final int REQUEST_CODE_ECM_EXIT_DIALOG  = 107;
177    public static final int REQUEST_CODE_ADD_CONTACT      = 108;
178    public static final int REQUEST_CODE_PICK             = 109;
179
180    private static final String TAG = LogTag.TAG;
181
182    private static final boolean DEBUG = false;
183    private static final boolean TRACE = false;
184    private static final boolean LOCAL_LOGV = false;
185
186    // Menu ID
187    private static final int MENU_ADD_SUBJECT           = 0;
188    private static final int MENU_DELETE_THREAD         = 1;
189    private static final int MENU_ADD_ATTACHMENT        = 2;
190    private static final int MENU_DISCARD               = 3;
191    private static final int MENU_SEND                  = 4;
192    private static final int MENU_CALL_RECIPIENT        = 5;
193    private static final int MENU_CONVERSATION_LIST     = 6;
194    private static final int MENU_DEBUG_DUMP            = 7;
195
196    // Context menu ID
197    private static final int MENU_VIEW_CONTACT          = 12;
198    private static final int MENU_ADD_TO_CONTACTS       = 13;
199
200    private static final int MENU_EDIT_MESSAGE          = 14;
201    private static final int MENU_VIEW_SLIDESHOW        = 16;
202    private static final int MENU_VIEW_MESSAGE_DETAILS  = 17;
203    private static final int MENU_DELETE_MESSAGE        = 18;
204    private static final int MENU_SEARCH                = 19;
205    private static final int MENU_DELIVERY_REPORT       = 20;
206    private static final int MENU_FORWARD_MESSAGE       = 21;
207    private static final int MENU_CALL_BACK             = 22;
208    private static final int MENU_SEND_EMAIL            = 23;
209    private static final int MENU_COPY_MESSAGE_TEXT     = 24;
210    private static final int MENU_COPY_TO_SDCARD        = 25;
211    private static final int MENU_ADD_ADDRESS_TO_CONTACTS = 27;
212    private static final int MENU_LOCK_MESSAGE          = 28;
213    private static final int MENU_UNLOCK_MESSAGE        = 29;
214    private static final int MENU_SAVE_RINGTONE         = 30;
215    private static final int MENU_PREFERENCES           = 31;
216    private static final int MENU_GROUP_PARTICIPANTS    = 32;
217
218    private static final int RECIPIENTS_MAX_LENGTH = 312;
219
220    private static final int MESSAGE_LIST_QUERY_TOKEN = 9527;
221    private static final int MESSAGE_LIST_QUERY_AFTER_DELETE_TOKEN = 9528;
222
223    private static final int DELETE_MESSAGE_TOKEN  = 9700;
224
225    private static final int CHARS_REMAINING_BEFORE_COUNTER_SHOWN = 10;
226
227    private static final long NO_DATE_FOR_DIALOG = -1L;
228
229    private static final String KEY_EXIT_ON_SENT = "exit_on_sent";
230    private static final String KEY_FORWARDED_MESSAGE = "forwarded_message";
231
232    private static final String EXIT_ECM_RESULT = "exit_ecm_result";
233
234    // When the conversation has a lot of messages and a new message is sent, the list is scrolled
235    // so the user sees the just sent message. If we have to scroll the list more than 20 items,
236    // then a scroll shortcut is invoked to move the list near the end before scrolling.
237    private static final int MAX_ITEMS_TO_INVOKE_SCROLL_SHORTCUT = 20;
238
239    // Any change in height in the message list view greater than this threshold will not
240    // cause a smooth scroll. Instead, we jump the list directly to the desired position.
241    private static final int SMOOTH_SCROLL_THRESHOLD = 200;
242
243    // To reduce janky interaction when message history + draft loads and keyboard opening
244    // query the messages + draft after the keyboard opens. This controls that behavior.
245    private static final boolean DEFER_LOADING_MESSAGES_AND_DRAFT = true;
246
247    // The max amount of delay before we force load messages and draft.
248    // 500ms is determined empirically. We want keyboard to have a chance to be shown before
249    // we force loading. However, there is at least one use case where the keyboard never shows
250    // even if we tell it to (turning off and on the screen). So we need to force load the
251    // messages+draft after the max delay.
252    private static final int LOADING_MESSAGES_AND_DRAFT_MAX_DELAY_MS = 500;
253
254    private ContentResolver mContentResolver;
255
256    private BackgroundQueryHandler mBackgroundQueryHandler;
257
258    private Conversation mConversation;     // Conversation we are working in
259
260    // When mSendDiscreetMode is true, this activity only allows a user to type in and send
261    // a single sms, send the message, and then exits. The message history and menus are hidden.
262    private boolean mSendDiscreetMode;
263    private boolean mForwardMessageMode;
264
265    private View mTopPanel;                 // View containing the recipient and subject editors
266    private View mBottomPanel;              // View containing the text editor, send button, ec.
267    private EditText mTextEditor;           // Text editor to type your message into
268    private TextView mTextCounter;          // Shows the number of characters used in text editor
269    private TextView mSendButtonMms;        // Press to send mms
270    private ImageButton mSendButtonSms;     // Press to send sms
271    private EditText mSubjectTextEditor;    // Text editor for MMS subject
272
273    private AttachmentEditor mAttachmentEditor;
274    private View mAttachmentEditorScrollView;
275
276    private MessageListView mMsgListView;        // ListView for messages in this conversation
277    public MessageListAdapter mMsgListAdapter;  // and its corresponding ListAdapter
278
279    private RecipientsEditor mRecipientsEditor;  // UI control for editing recipients
280    private ImageButton mRecipientsPicker;       // UI control for recipients picker
281
282    // For HW keyboard, 'mIsKeyboardOpen' indicates if the HW keyboard is open.
283    // For SW keyboard, 'mIsKeyboardOpen' should always be true.
284    private boolean mIsKeyboardOpen;
285    private boolean mIsLandscape;                // Whether we're in landscape mode
286
287    private boolean mToastForDraftSave;   // Whether to notify the user that a draft is being saved
288
289    private boolean mSentMessage;       // true if the user has sent a message while in this
290                                        // activity. On a new compose message case, when the first
291                                        // message is sent is a MMS w/ attachment, the list blanks
292                                        // for a second before showing the sent message. But we'd
293                                        // think the message list is empty, thus show the recipients
294                                        // editor thinking it's a draft message. This flag should
295                                        // help clarify the situation.
296
297    private WorkingMessage mWorkingMessage;         // The message currently being composed.
298
299    private boolean mWaitingForSubActivity;
300    private int mLastRecipientCount;            // Used for warning the user on too many recipients.
301    private AttachmentTypeSelectorAdapter mAttachmentTypeSelectorAdapter;
302
303    private boolean mSendingMessage;    // Indicates the current message is sending, and shouldn't send again.
304
305    private Intent mAddContactIntent;   // Intent used to add a new contact
306
307    private Uri mTempMmsUri;            // Only used as a temporary to hold a slideshow uri
308    private long mTempThreadId;         // Only used as a temporary to hold a threadId
309
310    private AsyncDialog mAsyncDialog;   // Used for background tasks.
311
312    private String mDebugRecipients;
313    private int mLastSmoothScrollPosition;
314    private boolean mScrollOnSend;      // Flag that we need to scroll the list to the end.
315
316    private int mSavedScrollPosition = -1;  // we save the ListView's scroll position in onPause(),
317                                            // so we can remember it after re-entering the activity.
318                                            // If the value >= 0, then we jump to that line. If the
319                                            // value is maxint, then we jump to the end.
320    private long mLastMessageId;
321
322    /**
323     * Whether this activity is currently running (i.e. not paused)
324     */
325    private boolean mIsRunning;
326
327    // we may call loadMessageAndDraft() from a few different places. This is used to make
328    // sure we only load message+draft once.
329    private boolean mMessagesAndDraftLoaded;
330
331    // whether we should load the draft. For example, after attaching a photo and coming back
332    // in onActivityResult(), we should not load the draft because that will mess up the draft
333    // state of mWorkingMessage. Also, if we are handling a Send or Forward Message Intent,
334    // we should not load the draft.
335    private boolean mShouldLoadDraft;
336
337    // Whether or not we are currently enabled for SMS. This field is updated in onStart to make
338    // sure we notice if the user has changed the default SMS app.
339    private boolean mIsSmsEnabled;
340
341    private Handler mHandler = new Handler();
342
343    // keys for extras and icicles
344    public final static String THREAD_ID = "thread_id";
345    private final static String RECIPIENTS = "recipients";
346
347    @SuppressWarnings("unused")
348    public static void log(String logMsg) {
349        Thread current = Thread.currentThread();
350        long tid = current.getId();
351        StackTraceElement[] stack = current.getStackTrace();
352        String methodName = stack[3].getMethodName();
353        // Prepend current thread ID and name of calling method to the message.
354        logMsg = "[" + tid + "] [" + methodName + "] " + logMsg;
355        Log.d(TAG, logMsg);
356    }
357
358    //==========================================================
359    // Inner classes
360    //==========================================================
361
362    private void editSlideshow() {
363        // The user wants to edit the slideshow. That requires us to persist the slideshow to
364        // disk as a PDU in saveAsMms. This code below does that persisting in a background
365        // task. If the task takes longer than a half second, a progress dialog is displayed.
366        // Once the PDU persisting is done, another runnable on the UI thread get executed to start
367        // the SlideshowEditActivity.
368        getAsyncDialog().runAsync(new Runnable() {
369            @Override
370            public void run() {
371                // This runnable gets run in a background thread.
372                mTempMmsUri = mWorkingMessage.saveAsMms(false);
373            }
374        }, new Runnable() {
375            @Override
376            public void run() {
377                // Once the above background thread is complete, this runnable is run
378                // on the UI thread.
379                if (mTempMmsUri == null) {
380                    return;
381                }
382                Intent intent = new Intent(ComposeMessageActivity.this,
383                        SlideshowEditActivity.class);
384                intent.setData(mTempMmsUri);
385                startActivityForResult(intent, REQUEST_CODE_CREATE_SLIDESHOW);
386            }
387        }, R.string.building_slideshow_title);
388    }
389
390    private final Handler mAttachmentEditorHandler = new Handler() {
391        @Override
392        public void handleMessage(Message msg) {
393            switch (msg.what) {
394                case AttachmentEditor.MSG_EDIT_SLIDESHOW: {
395                    editSlideshow();
396                    break;
397                }
398                case AttachmentEditor.MSG_SEND_SLIDESHOW: {
399                    if (isPreparedForSending()) {
400                        ComposeMessageActivity.this.confirmSendMessageIfNeeded();
401                    }
402                    break;
403                }
404                case AttachmentEditor.MSG_VIEW_IMAGE:
405                case AttachmentEditor.MSG_PLAY_VIDEO:
406                case AttachmentEditor.MSG_PLAY_AUDIO:
407                case AttachmentEditor.MSG_PLAY_SLIDESHOW:
408                    viewMmsMessageAttachment(msg.what);
409                    break;
410
411                case AttachmentEditor.MSG_REPLACE_IMAGE:
412                case AttachmentEditor.MSG_REPLACE_VIDEO:
413                case AttachmentEditor.MSG_REPLACE_AUDIO:
414                    showAddAttachmentDialog(true);
415                    break;
416
417                case AttachmentEditor.MSG_REMOVE_ATTACHMENT:
418                    mWorkingMessage.removeAttachment(true);
419                    break;
420
421                default:
422                    break;
423            }
424        }
425    };
426
427
428    private void viewMmsMessageAttachment(final int requestCode) {
429        SlideshowModel slideshow = mWorkingMessage.getSlideshow();
430        if (slideshow == null) {
431            throw new IllegalStateException("mWorkingMessage.getSlideshow() == null");
432        }
433        if (slideshow.isSimple()) {
434            MessageUtils.viewSimpleSlideshow(this, slideshow);
435        } else {
436            // The user wants to view the slideshow. That requires us to persist the slideshow to
437            // disk as a PDU in saveAsMms. This code below does that persisting in a background
438            // task. If the task takes longer than a half second, a progress dialog is displayed.
439            // Once the PDU persisting is done, another runnable on the UI thread get executed to
440            // start the SlideshowActivity.
441            getAsyncDialog().runAsync(new Runnable() {
442                @Override
443                public void run() {
444                    // This runnable gets run in a background thread.
445                    mTempMmsUri = mWorkingMessage.saveAsMms(false);
446                }
447            }, new Runnable() {
448                @Override
449                public void run() {
450                    // Once the above background thread is complete, this runnable is run
451                    // on the UI thread.
452                    if (mTempMmsUri == null) {
453                        return;
454                    }
455                    MessageUtils.launchSlideshowActivity(ComposeMessageActivity.this, mTempMmsUri,
456                            requestCode);
457                }
458            }, R.string.building_slideshow_title);
459        }
460    }
461
462
463    private final Handler mMessageListItemHandler = new Handler() {
464        @Override
465        public void handleMessage(Message msg) {
466            MessageItem msgItem = (MessageItem) msg.obj;
467            if (msgItem != null) {
468                switch (msg.what) {
469                    case MessageListItem.MSG_LIST_DETAILS:
470                        showMessageDetails(msgItem);
471                        break;
472
473                    case MessageListItem.MSG_LIST_EDIT:
474                        editMessageItem(msgItem);
475                        drawBottomPanel();
476                        break;
477
478                    case MessageListItem.MSG_LIST_PLAY:
479                        switch (msgItem.mAttachmentType) {
480                            case WorkingMessage.IMAGE:
481                            case WorkingMessage.VIDEO:
482                            case WorkingMessage.AUDIO:
483                            case WorkingMessage.SLIDESHOW:
484                                MessageUtils.viewMmsMessageAttachment(ComposeMessageActivity.this,
485                                        msgItem.mMessageUri, msgItem.mSlideshow,
486                                        getAsyncDialog());
487                                break;
488                        }
489                        break;
490
491                    default:
492                        Log.w(TAG, "Unknown message: " + msg.what);
493                        return;
494                }
495            }
496        }
497    };
498
499    private boolean showMessageDetails(MessageItem msgItem) {
500        Cursor cursor = mMsgListAdapter.getCursorForItem(msgItem);
501        if (cursor == null) {
502            return false;
503        }
504        String messageDetails = MessageUtils.getMessageDetails(
505                ComposeMessageActivity.this, cursor, msgItem.mMessageSize);
506        new AlertDialog.Builder(ComposeMessageActivity.this)
507                .setTitle(R.string.message_details_title)
508                .setMessage(messageDetails)
509                .setCancelable(true)
510                .show();
511        return true;
512    }
513
514    private final OnKeyListener mSubjectKeyListener = new OnKeyListener() {
515        @Override
516        public boolean onKey(View v, int keyCode, KeyEvent event) {
517            if (event.getAction() != KeyEvent.ACTION_DOWN) {
518                return false;
519            }
520
521            // When the subject editor is empty, press "DEL" to hide the input field.
522            if ((keyCode == KeyEvent.KEYCODE_DEL) && (mSubjectTextEditor.length() == 0)) {
523                showSubjectEditor(false);
524                mWorkingMessage.setSubject(null, true);
525                return true;
526            }
527            return false;
528        }
529    };
530
531    /**
532     * Return the messageItem associated with the type ("mms" or "sms") and message id.
533     * @param type Type of the message: "mms" or "sms"
534     * @param msgId Message id of the message. This is the _id of the sms or pdu row and is
535     * stored in the MessageItem
536     * @param createFromCursorIfNotInCache true if the item is not found in the MessageListAdapter's
537     * cache and the code can create a new MessageItem based on the position of the current cursor.
538     * If false, the function returns null if the MessageItem isn't in the cache.
539     * @return MessageItem or null if not found and createFromCursorIfNotInCache is false
540     */
541    private MessageItem getMessageItem(String type, long msgId,
542            boolean createFromCursorIfNotInCache) {
543        return mMsgListAdapter.getCachedMessageItem(type, msgId,
544                createFromCursorIfNotInCache ? mMsgListAdapter.getCursor() : null);
545    }
546
547    private boolean isCursorValid() {
548        // Check whether the cursor is valid or not.
549        Cursor cursor = mMsgListAdapter.getCursor();
550        if (cursor.isClosed() || cursor.isBeforeFirst() || cursor.isAfterLast()) {
551            Log.e(TAG, "Bad cursor.", new RuntimeException());
552            return false;
553        }
554        return true;
555    }
556
557    private void resetCounter() {
558        mTextCounter.setText("");
559        mTextCounter.setVisibility(View.GONE);
560    }
561
562    private void updateCounter(CharSequence text, int start, int before, int count) {
563        WorkingMessage workingMessage = mWorkingMessage;
564        if (workingMessage.requiresMms()) {
565            // If we're not removing text (i.e. no chance of converting back to SMS
566            // because of this change) and we're in MMS mode, just bail out since we
567            // then won't have to calculate the length unnecessarily.
568            final boolean textRemoved = (before > count);
569            if (!textRemoved) {
570                showSmsOrMmsSendButton(workingMessage.requiresMms());
571                return;
572            }
573        }
574
575        int[] params = SmsMessage.calculateLength(text, false);
576            /* SmsMessage.calculateLength returns an int[4] with:
577             *   int[0] being the number of SMS's required,
578             *   int[1] the number of code units used,
579             *   int[2] is the number of code units remaining until the next message.
580             *   int[3] is the encoding type that should be used for the message.
581             */
582        int msgCount = params[0];
583        int remainingInCurrentMessage = params[2];
584
585        if (!MmsConfig.getMultipartSmsEnabled()) {
586            // The provider doesn't support multi-part sms's so as soon as the user types
587            // an sms longer than one segment, we have to turn the message into an mms.
588            mWorkingMessage.setLengthRequiresMms(msgCount > 1, true);
589        } else {
590            int threshold = MmsConfig.getSmsToMmsTextThreshold();
591            mWorkingMessage.setLengthRequiresMms(threshold > 0 && msgCount > threshold, true);
592        }
593
594        // Show the counter only if:
595        // - We are not in MMS mode
596        // - We are going to send more than one message OR we are getting close
597        boolean showCounter = false;
598        if (!workingMessage.requiresMms() &&
599                (msgCount > 1 ||
600                 remainingInCurrentMessage <= CHARS_REMAINING_BEFORE_COUNTER_SHOWN)) {
601            showCounter = true;
602        }
603
604        showSmsOrMmsSendButton(workingMessage.requiresMms());
605
606        if (showCounter) {
607            // Update the remaining characters and number of messages required.
608            String counterText = msgCount > 1 ? remainingInCurrentMessage + " / " + msgCount
609                    : String.valueOf(remainingInCurrentMessage);
610            mTextCounter.setText(counterText);
611            mTextCounter.setVisibility(View.VISIBLE);
612        } else {
613            mTextCounter.setVisibility(View.GONE);
614        }
615    }
616
617    @Override
618    public void startActivityForResult(Intent intent, int requestCode)
619    {
620        // requestCode >= 0 means the activity in question is a sub-activity.
621        if (requestCode >= 0) {
622            mWaitingForSubActivity = true;
623        }
624        // The camera and other activities take a long time to hide the keyboard so we pre-hide
625        // it here. However, if we're opening up the quick contact window while typing, don't
626        // mess with the keyboard.
627        if (mIsKeyboardOpen && !QuickContact.ACTION_QUICK_CONTACT.equals(intent.getAction())) {
628            hideKeyboard();
629        }
630
631        super.startActivityForResult(intent, requestCode);
632    }
633
634    private void showConvertToMmsToast() {
635        Toast.makeText(this, R.string.converting_to_picture_message, Toast.LENGTH_SHORT).show();
636    }
637
638    private class DeleteMessageListener implements OnClickListener {
639        private final MessageItem mMessageItem;
640
641        public DeleteMessageListener(MessageItem messageItem) {
642            mMessageItem = messageItem;
643        }
644
645        @Override
646        public void onClick(DialogInterface dialog, int whichButton) {
647            dialog.dismiss();
648
649            new AsyncTask<Void, Void, Void>() {
650                protected Void doInBackground(Void... none) {
651                    if (mMessageItem.isMms()) {
652                        WorkingMessage.removeThumbnailsFromCache(mMessageItem.getSlideshow());
653
654                        MmsApp.getApplication().getPduLoaderManager()
655                            .removePdu(mMessageItem.mMessageUri);
656                        // Delete the message *after* we've removed the thumbnails because we
657                        // need the pdu and slideshow for removeThumbnailsFromCache to work.
658                    }
659                    Boolean deletingLastItem = false;
660                    Cursor cursor = mMsgListAdapter != null ? mMsgListAdapter.getCursor() : null;
661                    if (cursor != null) {
662                        cursor.moveToLast();
663                        long msgId = cursor.getLong(COLUMN_ID);
664                        deletingLastItem = msgId == mMessageItem.mMsgId;
665                    }
666                    mBackgroundQueryHandler.startDelete(DELETE_MESSAGE_TOKEN,
667                            deletingLastItem, mMessageItem.mMessageUri,
668                            mMessageItem.mLocked ? null : "locked=0", null);
669                    return null;
670                }
671            }.execute();
672        }
673    }
674
675    private class DiscardDraftListener implements OnClickListener {
676        @Override
677        public void onClick(DialogInterface dialog, int whichButton) {
678            mWorkingMessage.discard();
679            dialog.dismiss();
680            finish();
681        }
682    }
683
684    private class SendIgnoreInvalidRecipientListener implements OnClickListener {
685        @Override
686        public void onClick(DialogInterface dialog, int whichButton) {
687            sendMessage(true);
688            dialog.dismiss();
689        }
690    }
691
692    private class CancelSendingListener implements OnClickListener {
693        @Override
694        public void onClick(DialogInterface dialog, int whichButton) {
695            if (isRecipientsEditorVisible()) {
696                mRecipientsEditor.requestFocus();
697            }
698            dialog.dismiss();
699        }
700    }
701
702    private void confirmSendMessageIfNeeded() {
703        if (!isRecipientsEditorVisible()) {
704            sendMessage(true);
705            return;
706        }
707
708        boolean isMms = mWorkingMessage.requiresMms();
709        if (mRecipientsEditor.hasInvalidRecipient(isMms)) {
710            if (mRecipientsEditor.hasValidRecipient(isMms)) {
711                String title = getResourcesString(R.string.has_invalid_recipient,
712                        mRecipientsEditor.formatInvalidNumbers(isMms));
713                new AlertDialog.Builder(this)
714                    .setTitle(title)
715                    .setMessage(R.string.invalid_recipient_message)
716                    .setPositiveButton(R.string.try_to_send,
717                            new SendIgnoreInvalidRecipientListener())
718                    .setNegativeButton(R.string.no, new CancelSendingListener())
719                    .show();
720            } else {
721                new AlertDialog.Builder(this)
722                    .setTitle(R.string.cannot_send_message)
723                    .setMessage(R.string.cannot_send_message_reason)
724                    .setPositiveButton(R.string.yes, new CancelSendingListener())
725                    .show();
726            }
727        } else {
728            // The recipients editor is still open. Make sure we use what's showing there
729            // as the destination.
730            ContactList contacts = mRecipientsEditor.constructContactsFromInput(false);
731            mDebugRecipients = contacts.serialize();
732            sendMessage(true);
733        }
734    }
735
736    private final TextWatcher mRecipientsWatcher = new TextWatcher() {
737        @Override
738        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
739        }
740
741        @Override
742        public void onTextChanged(CharSequence s, int start, int before, int count) {
743            // This is a workaround for bug 1609057.  Since onUserInteraction() is
744            // not called when the user touches the soft keyboard, we pretend it was
745            // called when textfields changes.  This should be removed when the bug
746            // is fixed.
747            onUserInteraction();
748        }
749
750        @Override
751        public void afterTextChanged(Editable s) {
752            // Bug 1474782 describes a situation in which we send to
753            // the wrong recipient.  We have been unable to reproduce this,
754            // but the best theory we have so far is that the contents of
755            // mRecipientList somehow become stale when entering
756            // ComposeMessageActivity via onNewIntent().  This assertion is
757            // meant to catch one possible path to that, of a non-visible
758            // mRecipientsEditor having its TextWatcher fire and refreshing
759            // mRecipientList with its stale contents.
760            if (!isRecipientsEditorVisible()) {
761                IllegalStateException e = new IllegalStateException(
762                        "afterTextChanged called with invisible mRecipientsEditor");
763                // Make sure the crash is uploaded to the service so we
764                // can see if this is happening in the field.
765                Log.w(TAG,
766                     "RecipientsWatcher: afterTextChanged called with invisible mRecipientsEditor");
767                return;
768            }
769
770            List<String> numbers = mRecipientsEditor.getNumbers();
771            mWorkingMessage.setWorkingRecipients(numbers);
772            boolean multiRecipients = numbers != null && numbers.size() > 1;
773            mMsgListAdapter.setIsGroupConversation(multiRecipients);
774            mWorkingMessage.setHasMultipleRecipients(multiRecipients, true);
775            mWorkingMessage.setHasEmail(mRecipientsEditor.containsEmail(), true);
776
777            checkForTooManyRecipients();
778
779            // Walk backwards in the text box, skipping spaces.  If the last
780            // character is a comma, update the title bar.
781            for (int pos = s.length() - 1; pos >= 0; pos--) {
782                char c = s.charAt(pos);
783                if (c == ' ')
784                    continue;
785
786                if (c == ',') {
787                    ContactList contacts = mRecipientsEditor.constructContactsFromInput(false);
788                    updateTitle(contacts);
789                }
790
791                break;
792            }
793
794            // If we have gone to zero recipients, disable send button.
795            updateSendButtonState();
796        }
797    };
798
799    private void checkForTooManyRecipients() {
800        final int recipientLimit = MmsConfig.getRecipientLimit();
801        if (recipientLimit != Integer.MAX_VALUE) {
802            final int recipientCount = recipientCount();
803            boolean tooMany = recipientCount > recipientLimit;
804
805            if (recipientCount != mLastRecipientCount) {
806                // Don't warn the user on every character they type when they're over the limit,
807                // only when the actual # of recipients changes.
808                mLastRecipientCount = recipientCount;
809                if (tooMany) {
810                    String tooManyMsg = getString(R.string.too_many_recipients, recipientCount,
811                            recipientLimit);
812                    Toast.makeText(ComposeMessageActivity.this,
813                            tooManyMsg, Toast.LENGTH_LONG).show();
814                }
815            }
816        }
817    }
818
819    private final OnCreateContextMenuListener mRecipientsMenuCreateListener =
820        new OnCreateContextMenuListener() {
821        @Override
822        public void onCreateContextMenu(ContextMenu menu, View v,
823                ContextMenuInfo menuInfo) {
824            if (menuInfo != null) {
825                Contact c = ((RecipientContextMenuInfo) menuInfo).recipient;
826                RecipientsMenuClickListener l = new RecipientsMenuClickListener(c);
827
828                menu.setHeaderTitle(c.getName());
829
830                if (c.existsInDatabase()) {
831                    menu.add(0, MENU_VIEW_CONTACT, 0, R.string.menu_view_contact)
832                            .setOnMenuItemClickListener(l);
833                } else if (canAddToContacts(c)){
834                    menu.add(0, MENU_ADD_TO_CONTACTS, 0, R.string.menu_add_to_contacts)
835                            .setOnMenuItemClickListener(l);
836                }
837            }
838        }
839    };
840
841    private final class RecipientsMenuClickListener implements MenuItem.OnMenuItemClickListener {
842        private final Contact mRecipient;
843
844        RecipientsMenuClickListener(Contact recipient) {
845            mRecipient = recipient;
846        }
847
848        @Override
849        public boolean onMenuItemClick(MenuItem item) {
850            switch (item.getItemId()) {
851                // Context menu handlers for the recipients editor.
852                case MENU_VIEW_CONTACT: {
853                    Uri contactUri = mRecipient.getUri();
854                    Intent intent = new Intent(Intent.ACTION_VIEW, contactUri);
855                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
856                    startActivity(intent);
857                    return true;
858                }
859                case MENU_ADD_TO_CONTACTS: {
860                    mAddContactIntent = ConversationList.createAddContactIntent(
861                            mRecipient.getNumber());
862                    ComposeMessageActivity.this.startActivityForResult(mAddContactIntent,
863                            REQUEST_CODE_ADD_CONTACT);
864                    return true;
865                }
866            }
867            return false;
868        }
869    }
870
871    private boolean canAddToContacts(Contact contact) {
872        // There are some kind of automated messages, like STK messages, that we don't want
873        // to add to contacts. These names begin with special characters, like, "*Info".
874        final String name = contact.getName();
875        if (!TextUtils.isEmpty(contact.getNumber())) {
876            char c = contact.getNumber().charAt(0);
877            if (isSpecialChar(c)) {
878                return false;
879            }
880        }
881        if (!TextUtils.isEmpty(name)) {
882            char c = name.charAt(0);
883            if (isSpecialChar(c)) {
884                return false;
885            }
886        }
887        if (!(Mms.isEmailAddress(name) ||
888                Telephony.Mms.isPhoneNumber(name) ||
889                contact.isMe())) {
890            return false;
891        }
892        return true;
893    }
894
895    private boolean isSpecialChar(char c) {
896        return c == '*' || c == '%' || c == '$';
897    }
898
899    private void addPositionBasedMenuItems(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
900        AdapterView.AdapterContextMenuInfo info;
901
902        try {
903            info = (AdapterView.AdapterContextMenuInfo) menuInfo;
904        } catch (ClassCastException e) {
905            Log.e(TAG, "bad menuInfo");
906            return;
907        }
908        final int position = info.position;
909
910        addUriSpecificMenuItems(menu, v, position);
911    }
912
913    private Uri getSelectedUriFromMessageList(ListView listView, int position) {
914        // If the context menu was opened over a uri, get that uri.
915        MessageListItem msglistItem = (MessageListItem) listView.getChildAt(position);
916        if (msglistItem == null) {
917            // FIXME: Should get the correct view. No such interface in ListView currently
918            // to get the view by position. The ListView.getChildAt(position) cannot
919            // get correct view since the list doesn't create one child for each item.
920            // And if setSelection(position) then getSelectedView(),
921            // cannot get corrent view when in touch mode.
922            return null;
923        }
924
925        TextView textView;
926        CharSequence text = null;
927        int selStart = -1;
928        int selEnd = -1;
929
930        //check if message sender is selected
931        textView = (TextView) msglistItem.findViewById(R.id.text_view);
932        if (textView != null) {
933            text = textView.getText();
934            selStart = textView.getSelectionStart();
935            selEnd = textView.getSelectionEnd();
936        }
937
938        // Check that some text is actually selected, rather than the cursor
939        // just being placed within the TextView.
940        if (selStart != selEnd) {
941            int min = Math.min(selStart, selEnd);
942            int max = Math.max(selStart, selEnd);
943
944            URLSpan[] urls = ((Spanned) text).getSpans(min, max,
945                                                        URLSpan.class);
946
947            if (urls.length == 1) {
948                return Uri.parse(urls[0].getURL());
949            }
950        }
951
952        //no uri was selected
953        return null;
954    }
955
956    private void addUriSpecificMenuItems(ContextMenu menu, View v, int position) {
957        Uri uri = getSelectedUriFromMessageList((ListView) v, position);
958
959        if (uri != null) {
960            Intent intent = new Intent(null, uri);
961            intent.addCategory(Intent.CATEGORY_SELECTED_ALTERNATIVE);
962            menu.addIntentOptions(0, 0, 0,
963                    new android.content.ComponentName(this, ComposeMessageActivity.class),
964                    null, intent, 0, null);
965        }
966    }
967
968    private final void addCallAndContactMenuItems(
969            ContextMenu menu, MsgListMenuClickListener l, MessageItem msgItem) {
970        if (TextUtils.isEmpty(msgItem.mBody)) {
971            return;
972        }
973        SpannableString msg = new SpannableString(msgItem.mBody);
974        Linkify.addLinks(msg, Linkify.ALL);
975        ArrayList<String> uris =
976            MessageUtils.extractUris(msg.getSpans(0, msg.length(), URLSpan.class));
977
978        // Remove any dupes so they don't get added to the menu multiple times
979        HashSet<String> collapsedUris = new HashSet<String>();
980        for (String uri : uris) {
981            collapsedUris.add(uri.toLowerCase());
982        }
983        for (String uriString : collapsedUris) {
984            String prefix = null;
985            int sep = uriString.indexOf(":");
986            if (sep >= 0) {
987                prefix = uriString.substring(0, sep);
988                uriString = uriString.substring(sep + 1);
989            }
990            Uri contactUri = null;
991            boolean knownPrefix = true;
992            if ("mailto".equalsIgnoreCase(prefix))  {
993                contactUri = getContactUriForEmail(uriString);
994            } else if ("tel".equalsIgnoreCase(prefix)) {
995                contactUri = getContactUriForPhoneNumber(uriString);
996            } else {
997                knownPrefix = false;
998            }
999            if (knownPrefix && contactUri == null) {
1000                Intent intent = ConversationList.createAddContactIntent(uriString);
1001
1002                String addContactString = getString(R.string.menu_add_address_to_contacts,
1003                        uriString);
1004                menu.add(0, MENU_ADD_ADDRESS_TO_CONTACTS, 0, addContactString)
1005                    .setOnMenuItemClickListener(l)
1006                    .setIntent(intent);
1007            }
1008        }
1009    }
1010
1011    private Uri getContactUriForEmail(String emailAddress) {
1012        Cursor cursor = SqliteWrapper.query(this, getContentResolver(),
1013                Uri.withAppendedPath(Email.CONTENT_LOOKUP_URI, Uri.encode(emailAddress)),
1014                new String[] { Email.CONTACT_ID, Contacts.DISPLAY_NAME }, null, null, null);
1015
1016        if (cursor != null) {
1017            try {
1018                while (cursor.moveToNext()) {
1019                    String name = cursor.getString(1);
1020                    if (!TextUtils.isEmpty(name)) {
1021                        return ContentUris.withAppendedId(Contacts.CONTENT_URI, cursor.getLong(0));
1022                    }
1023                }
1024            } finally {
1025                cursor.close();
1026            }
1027        }
1028        return null;
1029    }
1030
1031    private Uri getContactUriForPhoneNumber(String phoneNumber) {
1032        Contact contact = Contact.get(phoneNumber, false);
1033        if (contact.existsInDatabase()) {
1034            return contact.getUri();
1035        }
1036        return null;
1037    }
1038
1039    private final OnCreateContextMenuListener mMsgListMenuCreateListener =
1040        new OnCreateContextMenuListener() {
1041        @Override
1042        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
1043            if (!isCursorValid()) {
1044                return;
1045            }
1046            Cursor cursor = mMsgListAdapter.getCursor();
1047            String type = cursor.getString(COLUMN_MSG_TYPE);
1048            long msgId = cursor.getLong(COLUMN_ID);
1049
1050            addPositionBasedMenuItems(menu, v, menuInfo);
1051
1052            MessageItem msgItem = mMsgListAdapter.getCachedMessageItem(type, msgId, cursor);
1053            if (msgItem == null) {
1054                Log.e(TAG, "Cannot load message item for type = " + type
1055                        + ", msgId = " + msgId);
1056                return;
1057            }
1058
1059            menu.setHeaderTitle(R.string.message_options);
1060
1061            MsgListMenuClickListener l = new MsgListMenuClickListener(msgItem);
1062
1063            // It is unclear what would make most sense for copying an MMS message
1064            // to the clipboard, so we currently do SMS only.
1065            if (msgItem.isSms()) {
1066                // Message type is sms. Only allow "edit" if the message has a single recipient
1067                if (getRecipients().size() == 1 &&
1068                        (msgItem.mBoxId == Sms.MESSAGE_TYPE_OUTBOX ||
1069                                msgItem.mBoxId == Sms.MESSAGE_TYPE_FAILED)) {
1070                    menu.add(0, MENU_EDIT_MESSAGE, 0, R.string.menu_edit)
1071                    .setOnMenuItemClickListener(l);
1072                }
1073
1074                menu.add(0, MENU_COPY_MESSAGE_TEXT, 0, R.string.copy_message_text)
1075                .setOnMenuItemClickListener(l);
1076            }
1077
1078            addCallAndContactMenuItems(menu, l, msgItem);
1079
1080            // Forward is not available for undownloaded messages.
1081            if (msgItem.isDownloaded() && (msgItem.isSms() || isForwardable(msgId))
1082                    && mIsSmsEnabled) {
1083                menu.add(0, MENU_FORWARD_MESSAGE, 0, R.string.menu_forward)
1084                        .setOnMenuItemClickListener(l);
1085            }
1086
1087            if (msgItem.isMms()) {
1088                switch (msgItem.mBoxId) {
1089                    case Mms.MESSAGE_BOX_INBOX:
1090                        break;
1091                    case Mms.MESSAGE_BOX_OUTBOX:
1092                        // Since we currently break outgoing messages to multiple
1093                        // recipients into one message per recipient, only allow
1094                        // editing a message for single-recipient conversations.
1095                        if (getRecipients().size() == 1) {
1096                            menu.add(0, MENU_EDIT_MESSAGE, 0, R.string.menu_edit)
1097                                    .setOnMenuItemClickListener(l);
1098                        }
1099                        break;
1100                }
1101                switch (msgItem.mAttachmentType) {
1102                    case WorkingMessage.TEXT:
1103                        break;
1104                    case WorkingMessage.VIDEO:
1105                    case WorkingMessage.IMAGE:
1106                        if (haveSomethingToCopyToSDCard(msgItem.mMsgId)) {
1107                            menu.add(0, MENU_COPY_TO_SDCARD, 0, R.string.copy_to_sdcard)
1108                            .setOnMenuItemClickListener(l);
1109                        }
1110                        break;
1111                    case WorkingMessage.SLIDESHOW:
1112                    default:
1113                        menu.add(0, MENU_VIEW_SLIDESHOW, 0, R.string.view_slideshow)
1114                        .setOnMenuItemClickListener(l);
1115                        if (haveSomethingToCopyToSDCard(msgItem.mMsgId)) {
1116                            menu.add(0, MENU_COPY_TO_SDCARD, 0, R.string.copy_to_sdcard)
1117                            .setOnMenuItemClickListener(l);
1118                        }
1119                        if (isDrmRingtoneWithRights(msgItem.mMsgId)) {
1120                            menu.add(0, MENU_SAVE_RINGTONE, 0,
1121                                    getDrmMimeMenuStringRsrc(msgItem.mMsgId))
1122                            .setOnMenuItemClickListener(l);
1123                        }
1124                        break;
1125                }
1126            }
1127
1128            if (msgItem.mLocked && mIsSmsEnabled) {
1129                menu.add(0, MENU_UNLOCK_MESSAGE, 0, R.string.menu_unlock)
1130                    .setOnMenuItemClickListener(l);
1131            } else if (mIsSmsEnabled) {
1132                menu.add(0, MENU_LOCK_MESSAGE, 0, R.string.menu_lock)
1133                    .setOnMenuItemClickListener(l);
1134            }
1135
1136            menu.add(0, MENU_VIEW_MESSAGE_DETAILS, 0, R.string.view_message_details)
1137                .setOnMenuItemClickListener(l);
1138
1139            if (msgItem.mDeliveryStatus != MessageItem.DeliveryStatus.NONE || msgItem.mReadReport) {
1140                menu.add(0, MENU_DELIVERY_REPORT, 0, R.string.view_delivery_report)
1141                        .setOnMenuItemClickListener(l);
1142            }
1143
1144            if (mIsSmsEnabled) {
1145                menu.add(0, MENU_DELETE_MESSAGE, 0, R.string.delete_message)
1146                    .setOnMenuItemClickListener(l);
1147            }
1148        }
1149    };
1150
1151    private void editMessageItem(MessageItem msgItem) {
1152        if ("sms".equals(msgItem.mType)) {
1153            editSmsMessageItem(msgItem);
1154        } else {
1155            editMmsMessageItem(msgItem);
1156        }
1157        if (msgItem.isFailedMessage() && mMsgListAdapter.getCount() <= 1) {
1158            // For messages with bad addresses, let the user re-edit the recipients.
1159            initRecipientsEditor();
1160        }
1161    }
1162
1163    private void editSmsMessageItem(MessageItem msgItem) {
1164        // When the message being edited is the only message in the conversation, the delete
1165        // below does something subtle. The trigger "delete_obsolete_threads_pdu" sees that a
1166        // thread contains no messages and silently deletes the thread. Meanwhile, the mConversation
1167        // object still holds onto the old thread_id and code thinks there's a backing thread in
1168        // the DB when it really has been deleted. Here we try and notice that situation and
1169        // clear out the thread_id. Later on, when Conversation.ensureThreadId() is called, we'll
1170        // create a new thread if necessary.
1171        synchronized(mConversation) {
1172            if (mConversation.getMessageCount() <= 1) {
1173                mConversation.clearThreadId();
1174                MessagingNotification.setCurrentlyDisplayedThreadId(
1175                    MessagingNotification.THREAD_NONE);
1176            }
1177        }
1178        // Delete the old undelivered SMS and load its content.
1179        Uri uri = ContentUris.withAppendedId(Sms.CONTENT_URI, msgItem.mMsgId);
1180        SqliteWrapper.delete(ComposeMessageActivity.this,
1181                mContentResolver, uri, null, null);
1182
1183        mWorkingMessage.setText(msgItem.mBody);
1184    }
1185
1186    private void editMmsMessageItem(MessageItem msgItem) {
1187        // Load the selected message in as the working message.
1188        WorkingMessage newWorkingMessage = WorkingMessage.load(this, msgItem.mMessageUri);
1189        if (newWorkingMessage == null) {
1190            return;
1191        }
1192
1193        // Discard the current message in progress.
1194        mWorkingMessage.discard();
1195
1196        mWorkingMessage = newWorkingMessage;
1197        mWorkingMessage.setConversation(mConversation);
1198
1199        drawTopPanel(false);
1200
1201        // WorkingMessage.load() above only loads the slideshow. Set the
1202        // subject here because we already know what it is and avoid doing
1203        // another DB lookup in load() just to get it.
1204        mWorkingMessage.setSubject(msgItem.mSubject, false);
1205
1206        if (mWorkingMessage.hasSubject()) {
1207            showSubjectEditor(true);
1208        }
1209    }
1210
1211    private void copyToClipboard(String str) {
1212        ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
1213        clipboard.setPrimaryClip(ClipData.newPlainText(null, str));
1214    }
1215
1216    private void forwardMessage(final MessageItem msgItem) {
1217        mTempThreadId = 0;
1218        // The user wants to forward the message. If the message is an mms message, we need to
1219        // persist the pdu to disk. This is done in a background task.
1220        // If the task takes longer than a half second, a progress dialog is displayed.
1221        // Once the PDU persisting is done, another runnable on the UI thread get executed to start
1222        // the ForwardMessageActivity.
1223        getAsyncDialog().runAsync(new Runnable() {
1224            @Override
1225            public void run() {
1226                // This runnable gets run in a background thread.
1227                if (msgItem.mType.equals("mms")) {
1228                    SendReq sendReq = new SendReq();
1229                    String subject = getString(R.string.forward_prefix);
1230                    if (msgItem.mSubject != null) {
1231                        subject += msgItem.mSubject;
1232                    }
1233                    sendReq.setSubject(new EncodedStringValue(subject));
1234                    sendReq.setBody(msgItem.mSlideshow.makeCopy());
1235
1236                    mTempMmsUri = null;
1237                    try {
1238                        PduPersister persister =
1239                                PduPersister.getPduPersister(ComposeMessageActivity.this);
1240                        // Copy the parts of the message here.
1241                        mTempMmsUri = persister.persist(sendReq, Mms.Draft.CONTENT_URI, true,
1242                                MessagingPreferenceActivity
1243                                    .getIsGroupMmsEnabled(ComposeMessageActivity.this), null);
1244                        mTempThreadId = MessagingNotification.getThreadId(
1245                                ComposeMessageActivity.this, mTempMmsUri);
1246                    } catch (MmsException e) {
1247                        Log.e(TAG, "Failed to copy message: " + msgItem.mMessageUri);
1248                        Toast.makeText(ComposeMessageActivity.this,
1249                                R.string.cannot_save_message, Toast.LENGTH_SHORT).show();
1250                        return;
1251                    }
1252                }
1253            }
1254        }, new Runnable() {
1255            @Override
1256            public void run() {
1257                // Once the above background thread is complete, this runnable is run
1258                // on the UI thread.
1259                Intent intent = createIntent(ComposeMessageActivity.this, 0);
1260
1261                intent.putExtra(KEY_EXIT_ON_SENT, true);
1262                intent.putExtra(KEY_FORWARDED_MESSAGE, true);
1263                if (mTempThreadId > 0) {
1264                    intent.putExtra(THREAD_ID, mTempThreadId);
1265                }
1266
1267                if (msgItem.mType.equals("sms")) {
1268                    intent.putExtra("sms_body", msgItem.mBody);
1269                } else {
1270                    intent.putExtra("msg_uri", mTempMmsUri);
1271                    String subject = getString(R.string.forward_prefix);
1272                    if (msgItem.mSubject != null) {
1273                        subject += msgItem.mSubject;
1274                    }
1275                    intent.putExtra("subject", subject);
1276                }
1277                // ForwardMessageActivity is simply an alias in the manifest for
1278                // ComposeMessageActivity. We have to make an alias because ComposeMessageActivity
1279                // launch flags specify singleTop. When we forward a message, we want to start a
1280                // separate ComposeMessageActivity. The only way to do that is to override the
1281                // singleTop flag, which is impossible to do in code. By creating an alias to the
1282                // activity, without the singleTop flag, we can launch a separate
1283                // ComposeMessageActivity to edit the forward message.
1284                intent.setClassName(ComposeMessageActivity.this,
1285                        "com.android.mms.ui.ForwardMessageActivity");
1286                startActivity(intent);
1287            }
1288        }, R.string.building_slideshow_title);
1289    }
1290
1291    /**
1292     * Context menu handlers for the message list view.
1293     */
1294    private final class MsgListMenuClickListener implements MenuItem.OnMenuItemClickListener {
1295        private MessageItem mMsgItem;
1296
1297        public MsgListMenuClickListener(MessageItem msgItem) {
1298            mMsgItem = msgItem;
1299        }
1300
1301        @Override
1302        public boolean onMenuItemClick(MenuItem item) {
1303            if (mMsgItem == null) {
1304                return false;
1305            }
1306
1307            switch (item.getItemId()) {
1308                case MENU_EDIT_MESSAGE:
1309                    editMessageItem(mMsgItem);
1310                    drawBottomPanel();
1311                    return true;
1312
1313                case MENU_COPY_MESSAGE_TEXT:
1314                    copyToClipboard(mMsgItem.mBody);
1315                    return true;
1316
1317                case MENU_FORWARD_MESSAGE:
1318                    forwardMessage(mMsgItem);
1319                    return true;
1320
1321                case MENU_VIEW_SLIDESHOW:
1322                    MessageUtils.viewMmsMessageAttachment(ComposeMessageActivity.this,
1323                            ContentUris.withAppendedId(Mms.CONTENT_URI, mMsgItem.mMsgId), null,
1324                            getAsyncDialog());
1325                    return true;
1326
1327                case MENU_VIEW_MESSAGE_DETAILS:
1328                    return showMessageDetails(mMsgItem);
1329
1330                case MENU_DELETE_MESSAGE: {
1331                    DeleteMessageListener l = new DeleteMessageListener(mMsgItem);
1332                    confirmDeleteDialog(l, mMsgItem.mLocked);
1333                    return true;
1334                }
1335                case MENU_DELIVERY_REPORT:
1336                    showDeliveryReport(mMsgItem.mMsgId, mMsgItem.mType);
1337                    return true;
1338
1339                case MENU_COPY_TO_SDCARD: {
1340                    int resId = copyMedia(mMsgItem.mMsgId) ? R.string.copy_to_sdcard_success :
1341                        R.string.copy_to_sdcard_fail;
1342                    Toast.makeText(ComposeMessageActivity.this, resId, Toast.LENGTH_SHORT).show();
1343                    return true;
1344                }
1345
1346                case MENU_SAVE_RINGTONE: {
1347                    int resId = getDrmMimeSavedStringRsrc(mMsgItem.mMsgId,
1348                            saveRingtone(mMsgItem.mMsgId));
1349                    Toast.makeText(ComposeMessageActivity.this, resId, Toast.LENGTH_SHORT).show();
1350                    return true;
1351                }
1352
1353                case MENU_LOCK_MESSAGE: {
1354                    lockMessage(mMsgItem, true);
1355                    return true;
1356                }
1357
1358                case MENU_UNLOCK_MESSAGE: {
1359                    lockMessage(mMsgItem, false);
1360                    return true;
1361                }
1362
1363                default:
1364                    return false;
1365            }
1366        }
1367    }
1368
1369    private void lockMessage(MessageItem msgItem, boolean locked) {
1370        Uri uri;
1371        if ("sms".equals(msgItem.mType)) {
1372            uri = Sms.CONTENT_URI;
1373        } else {
1374            uri = Mms.CONTENT_URI;
1375        }
1376        final Uri lockUri = ContentUris.withAppendedId(uri, msgItem.mMsgId);
1377
1378        final ContentValues values = new ContentValues(1);
1379        values.put("locked", locked ? 1 : 0);
1380
1381        new Thread(new Runnable() {
1382            @Override
1383            public void run() {
1384                getContentResolver().update(lockUri,
1385                        values, null, null);
1386            }
1387        }, "ComposeMessageActivity.lockMessage").start();
1388    }
1389
1390    /**
1391     * Looks to see if there are any valid parts of the attachment that can be copied to a SD card.
1392     * @param msgId
1393     */
1394    private boolean haveSomethingToCopyToSDCard(long msgId) {
1395        PduBody body = null;
1396        try {
1397            body = SlideshowModel.getPduBody(this,
1398                        ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
1399        } catch (MmsException e) {
1400            Log.e(TAG, "haveSomethingToCopyToSDCard can't load pdu body: " + msgId);
1401        }
1402        if (body == null) {
1403            return false;
1404        }
1405
1406        boolean result = false;
1407        int partNum = body.getPartsNum();
1408        for(int i = 0; i < partNum; i++) {
1409            PduPart part = body.getPart(i);
1410            String type = new String(part.getContentType());
1411
1412            if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
1413                log("[CMA] haveSomethingToCopyToSDCard: part[" + i + "] contentType=" + type);
1414            }
1415
1416            if (ContentType.isImageType(type) || ContentType.isVideoType(type) ||
1417                    ContentType.isAudioType(type) || DrmUtils.isDrmType(type)) {
1418                result = true;
1419                break;
1420            }
1421        }
1422        return result;
1423    }
1424
1425    /**
1426     * Copies media from an Mms to the DrmProvider
1427     * @param msgId
1428     */
1429    private boolean saveRingtone(long msgId) {
1430        boolean result = true;
1431        PduBody body = null;
1432        try {
1433            body = SlideshowModel.getPduBody(this,
1434                        ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
1435        } catch (MmsException e) {
1436            Log.e(TAG, "copyToDrmProvider can't load pdu body: " + msgId);
1437        }
1438        if (body == null) {
1439            return false;
1440        }
1441
1442        int partNum = body.getPartsNum();
1443        for(int i = 0; i < partNum; i++) {
1444            PduPart part = body.getPart(i);
1445            String type = new String(part.getContentType());
1446
1447            if (DrmUtils.isDrmType(type)) {
1448                // All parts (but there's probably only a single one) have to be successful
1449                // for a valid result.
1450                result &= copyPart(part, Long.toHexString(msgId));
1451            }
1452        }
1453        return result;
1454    }
1455
1456    /**
1457     * Returns true if any part is drm'd audio with ringtone rights.
1458     * @param msgId
1459     * @return true if one of the parts is drm'd audio with rights to save as a ringtone.
1460     */
1461    private boolean isDrmRingtoneWithRights(long msgId) {
1462        PduBody body = null;
1463        try {
1464            body = SlideshowModel.getPduBody(this,
1465                        ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
1466        } catch (MmsException e) {
1467            Log.e(TAG, "isDrmRingtoneWithRights can't load pdu body: " + msgId);
1468        }
1469        if (body == null) {
1470            return false;
1471        }
1472
1473        int partNum = body.getPartsNum();
1474        for (int i = 0; i < partNum; i++) {
1475            PduPart part = body.getPart(i);
1476            String type = new String(part.getContentType());
1477
1478            if (DrmUtils.isDrmType(type)) {
1479                String mimeType = MmsApp.getApplication().getDrmManagerClient()
1480                        .getOriginalMimeType(part.getDataUri());
1481                if (ContentType.isAudioType(mimeType) && DrmUtils.haveRightsForAction(part.getDataUri(),
1482                        DrmStore.Action.RINGTONE)) {
1483                    return true;
1484                }
1485            }
1486        }
1487        return false;
1488    }
1489
1490    /**
1491     * Returns true if all drm'd parts are forwardable.
1492     * @param msgId
1493     * @return true if all drm'd parts are forwardable.
1494     */
1495    private boolean isForwardable(long msgId) {
1496        PduBody body = null;
1497        try {
1498            body = SlideshowModel.getPduBody(this,
1499                        ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
1500        } catch (MmsException e) {
1501            Log.e(TAG, "getDrmMimeType can't load pdu body: " + msgId);
1502        }
1503        if (body == null) {
1504            return false;
1505        }
1506
1507        int partNum = body.getPartsNum();
1508        for (int i = 0; i < partNum; i++) {
1509            PduPart part = body.getPart(i);
1510            String type = new String(part.getContentType());
1511
1512            if (DrmUtils.isDrmType(type) && !DrmUtils.haveRightsForAction(part.getDataUri(),
1513                        DrmStore.Action.TRANSFER)) {
1514                    return false;
1515            }
1516        }
1517        return true;
1518    }
1519
1520    private int getDrmMimeMenuStringRsrc(long msgId) {
1521        if (isDrmRingtoneWithRights(msgId)) {
1522            return R.string.save_ringtone;
1523        }
1524        return 0;
1525    }
1526
1527    private int getDrmMimeSavedStringRsrc(long msgId, boolean success) {
1528        if (isDrmRingtoneWithRights(msgId)) {
1529            return success ? R.string.saved_ringtone : R.string.saved_ringtone_fail;
1530        }
1531        return 0;
1532    }
1533
1534    /**
1535     * Copies media from an Mms to the "download" directory on the SD card. If any of the parts
1536     * are audio types, drm'd or not, they're copied to the "Ringtones" directory.
1537     * @param msgId
1538     */
1539    private boolean copyMedia(long msgId) {
1540        boolean result = true;
1541        PduBody body = null;
1542        try {
1543            body = SlideshowModel.getPduBody(this,
1544                        ContentUris.withAppendedId(Mms.CONTENT_URI, msgId));
1545        } catch (MmsException e) {
1546            Log.e(TAG, "copyMedia can't load pdu body: " + msgId);
1547        }
1548        if (body == null) {
1549            return false;
1550        }
1551
1552        int partNum = body.getPartsNum();
1553        for(int i = 0; i < partNum; i++) {
1554            PduPart part = body.getPart(i);
1555
1556            // all parts have to be successful for a valid result.
1557            result &= copyPart(part, Long.toHexString(msgId));
1558        }
1559        return result;
1560    }
1561
1562    private boolean copyPart(PduPart part, String fallback) {
1563        Uri uri = part.getDataUri();
1564        String type = new String(part.getContentType());
1565        boolean isDrm = DrmUtils.isDrmType(type);
1566        if (isDrm) {
1567            type = MmsApp.getApplication().getDrmManagerClient()
1568                    .getOriginalMimeType(part.getDataUri());
1569        }
1570        if (!ContentType.isImageType(type) && !ContentType.isVideoType(type) &&
1571                !ContentType.isAudioType(type)) {
1572            return true;    // we only save pictures, videos, and sounds. Skip the text parts,
1573                            // the app (smil) parts, and other type that we can't handle.
1574                            // Return true to pretend that we successfully saved the part so
1575                            // the whole save process will be counted a success.
1576        }
1577        InputStream input = null;
1578        FileOutputStream fout = null;
1579        try {
1580            input = mContentResolver.openInputStream(uri);
1581            if (input instanceof FileInputStream) {
1582                FileInputStream fin = (FileInputStream) input;
1583
1584                byte[] location = part.getName();
1585                if (location == null) {
1586                    location = part.getFilename();
1587                }
1588                if (location == null) {
1589                    location = part.getContentLocation();
1590                }
1591
1592                String fileName;
1593                if (location == null) {
1594                    // Use fallback name.
1595                    fileName = fallback;
1596                } else {
1597                    // For locally captured videos, fileName can end up being something like this:
1598                    //      /mnt/sdcard/Android/data/com.android.mms/cache/.temp1.3gp
1599                    fileName = new String(location);
1600                }
1601                File originalFile = new File(fileName);
1602                fileName = originalFile.getName();  // Strip the full path of where the "part" is
1603                                                    // stored down to just the leaf filename.
1604
1605                // Depending on the location, there may be an
1606                // extension already on the name or not. If we've got audio, put the attachment
1607                // in the Ringtones directory.
1608                String dir = Environment.getExternalStorageDirectory() + "/"
1609                                + (ContentType.isAudioType(type) ? Environment.DIRECTORY_RINGTONES :
1610                                    Environment.DIRECTORY_DOWNLOADS)  + "/";
1611                String extension;
1612                int index;
1613                if ((index = fileName.lastIndexOf('.')) == -1) {
1614                    extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(type);
1615                } else {
1616                    extension = fileName.substring(index + 1, fileName.length());
1617                    fileName = fileName.substring(0, index);
1618                }
1619                if (isDrm) {
1620                    extension += DrmUtils.getConvertExtension(type);
1621                }
1622                // Remove leading periods. The gallery ignores files starting with a period.
1623                fileName = fileName.replaceAll("^.", "");
1624
1625                File file = getUniqueDestination(dir + fileName, extension);
1626
1627                // make sure the path is valid and directories created for this file.
1628                File parentFile = file.getParentFile();
1629                if (!parentFile.exists() && !parentFile.mkdirs()) {
1630                    Log.e(TAG, "[MMS] copyPart: mkdirs for " + parentFile.getPath() + " failed!");
1631                    return false;
1632                }
1633
1634                fout = new FileOutputStream(file);
1635
1636                byte[] buffer = new byte[8000];
1637                int size = 0;
1638                while ((size=fin.read(buffer)) != -1) {
1639                    fout.write(buffer, 0, size);
1640                }
1641
1642                // Notify other applications listening to scanner events
1643                // that a media file has been added to the sd card
1644                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
1645                        Uri.fromFile(file)));
1646            }
1647        } catch (IOException e) {
1648            // Ignore
1649            Log.e(TAG, "IOException caught while opening or reading stream", e);
1650            return false;
1651        } finally {
1652            if (null != input) {
1653                try {
1654                    input.close();
1655                } catch (IOException e) {
1656                    // Ignore
1657                    Log.e(TAG, "IOException caught while closing stream", e);
1658                    return false;
1659                }
1660            }
1661            if (null != fout) {
1662                try {
1663                    fout.close();
1664                } catch (IOException e) {
1665                    // Ignore
1666                    Log.e(TAG, "IOException caught while closing stream", e);
1667                    return false;
1668                }
1669            }
1670        }
1671        return true;
1672    }
1673
1674    private File getUniqueDestination(String base, String extension) {
1675        File file = new File(base + "." + extension);
1676
1677        for (int i = 2; file.exists(); i++) {
1678            file = new File(base + "_" + i + "." + extension);
1679        }
1680        return file;
1681    }
1682
1683    private void showDeliveryReport(long messageId, String type) {
1684        Intent intent = new Intent(this, DeliveryReportActivity.class);
1685        intent.putExtra("message_id", messageId);
1686        intent.putExtra("message_type", type);
1687
1688        startActivity(intent);
1689    }
1690
1691    private final IntentFilter mHttpProgressFilter = new IntentFilter(PROGRESS_STATUS_ACTION);
1692
1693    private final BroadcastReceiver mHttpProgressReceiver = new BroadcastReceiver() {
1694        @Override
1695        public void onReceive(Context context, Intent intent) {
1696            if (PROGRESS_STATUS_ACTION.equals(intent.getAction())) {
1697                long token = intent.getLongExtra("token",
1698                                    SendingProgressTokenManager.NO_TOKEN);
1699                if (token != mConversation.getThreadId()) {
1700                    return;
1701                }
1702
1703                int progress = intent.getIntExtra("progress", 0);
1704                switch (progress) {
1705                    case PROGRESS_START:
1706                        setProgressBarVisibility(true);
1707                        break;
1708                    case PROGRESS_ABORT:
1709                    case PROGRESS_COMPLETE:
1710                        setProgressBarVisibility(false);
1711                        break;
1712                    default:
1713                        setProgress(100 * progress);
1714                }
1715            }
1716        }
1717    };
1718
1719    private static ContactList sEmptyContactList;
1720
1721    private ContactList getRecipients() {
1722        // If the recipients editor is visible, the conversation has
1723        // not really officially 'started' yet.  Recipients will be set
1724        // on the conversation once it has been saved or sent.  In the
1725        // meantime, let anyone who needs the recipient list think it
1726        // is empty rather than giving them a stale one.
1727        if (isRecipientsEditorVisible()) {
1728            if (sEmptyContactList == null) {
1729                sEmptyContactList = new ContactList();
1730            }
1731            return sEmptyContactList;
1732        }
1733        return mConversation.getRecipients();
1734    }
1735
1736    private void updateTitle(ContactList list) {
1737        String title = null;
1738        String subTitle = null;
1739        int cnt = list.size();
1740        switch (cnt) {
1741            case 0: {
1742                String recipient = null;
1743                if (mRecipientsEditor != null) {
1744                    recipient = mRecipientsEditor.getText().toString();
1745                }
1746                title = TextUtils.isEmpty(recipient) ? getString(R.string.new_message) : recipient;
1747                break;
1748            }
1749            case 1: {
1750                title = list.get(0).getName();      // get name returns the number if there's no
1751                                                    // name available.
1752                String number = list.get(0).getNumber();
1753                if (!title.equals(number)) {
1754                    subTitle = PhoneNumberUtils.formatNumber(number, number,
1755                            MmsApp.getApplication().getCurrentCountryIso());
1756                }
1757                break;
1758            }
1759            default: {
1760                // Handle multiple recipients
1761                title = list.formatNames(", ");
1762                subTitle = getResources().getQuantityString(R.plurals.recipient_count, cnt, cnt);
1763                break;
1764            }
1765        }
1766        mDebugRecipients = list.serialize();
1767
1768        ActionBar actionBar = getActionBar();
1769        actionBar.setTitle(title);
1770        actionBar.setSubtitle(subTitle);
1771    }
1772
1773    // Get the recipients editor ready to be displayed onscreen.
1774    private void initRecipientsEditor() {
1775        if (isRecipientsEditorVisible()) {
1776            return;
1777        }
1778        // Must grab the recipients before the view is made visible because getRecipients()
1779        // returns empty recipients when the editor is visible.
1780        ContactList recipients = getRecipients();
1781
1782        ViewStub stub = (ViewStub)findViewById(R.id.recipients_editor_stub);
1783        if (stub != null) {
1784            View stubView = stub.inflate();
1785            mRecipientsEditor = (RecipientsEditor) stubView.findViewById(R.id.recipients_editor);
1786            mRecipientsPicker = (ImageButton) stubView.findViewById(R.id.recipients_picker);
1787        } else {
1788            mRecipientsEditor = (RecipientsEditor)findViewById(R.id.recipients_editor);
1789            mRecipientsEditor.setVisibility(View.VISIBLE);
1790            mRecipientsPicker = (ImageButton)findViewById(R.id.recipients_picker);
1791        }
1792        mRecipientsPicker.setOnClickListener(this);
1793
1794        mRecipientsEditor.setAdapter(new ChipsRecipientAdapter(this));
1795        mRecipientsEditor.populate(recipients);
1796        mRecipientsEditor.setOnCreateContextMenuListener(mRecipientsMenuCreateListener);
1797        mRecipientsEditor.addTextChangedListener(mRecipientsWatcher);
1798        // TODO : Remove the max length limitation due to the multiple phone picker is added and the
1799        // user is able to select a large number of recipients from the Contacts. The coming
1800        // potential issue is that it is hard for user to edit a recipient from hundred of
1801        // recipients in the editor box. We may redesign the editor box UI for this use case.
1802        // mRecipientsEditor.setFilters(new InputFilter[] {
1803        //         new InputFilter.LengthFilter(RECIPIENTS_MAX_LENGTH) });
1804
1805        mRecipientsEditor.setOnSelectChipRunnable(new Runnable() {
1806            @Override
1807            public void run() {
1808                // After the user selects an item in the pop-up contacts list, move the
1809                // focus to the text editor if there is only one recipient.  This helps
1810                // the common case of selecting one recipient and then typing a message,
1811                // but avoids annoying a user who is trying to add five recipients and
1812                // keeps having focus stolen away.
1813                if (mRecipientsEditor.getRecipientCount() == 1) {
1814                    // if we're in extract mode then don't request focus
1815                    final InputMethodManager inputManager = (InputMethodManager)
1816                        getSystemService(Context.INPUT_METHOD_SERVICE);
1817                    if (inputManager == null || !inputManager.isFullscreenMode()) {
1818                        mTextEditor.requestFocus();
1819                    }
1820                }
1821            }
1822        });
1823
1824        mRecipientsEditor.setOnFocusChangeListener(new View.OnFocusChangeListener() {
1825            @Override
1826            public void onFocusChange(View v, boolean hasFocus) {
1827                if (!hasFocus) {
1828                    RecipientsEditor editor = (RecipientsEditor) v;
1829                    ContactList contacts = editor.constructContactsFromInput(false);
1830                    updateTitle(contacts);
1831                }
1832            }
1833        });
1834
1835        PhoneNumberFormatter.setPhoneNumberFormattingTextWatcher(this, mRecipientsEditor);
1836
1837        mTopPanel.setVisibility(View.VISIBLE);
1838    }
1839
1840    //==========================================================
1841    // Activity methods
1842    //==========================================================
1843
1844    public static boolean cancelFailedToDeliverNotification(Intent intent, Context context) {
1845        if (MessagingNotification.isFailedToDeliver(intent)) {
1846            // Cancel any failed message notifications
1847            MessagingNotification.cancelNotification(context,
1848                        MessagingNotification.MESSAGE_FAILED_NOTIFICATION_ID);
1849            return true;
1850        }
1851        return false;
1852    }
1853
1854    public static boolean cancelFailedDownloadNotification(Intent intent, Context context) {
1855        if (MessagingNotification.isFailedToDownload(intent)) {
1856            // Cancel any failed download notifications
1857            MessagingNotification.cancelNotification(context,
1858                        MessagingNotification.DOWNLOAD_FAILED_NOTIFICATION_ID);
1859            return true;
1860        }
1861        return false;
1862    }
1863
1864    @Override
1865    protected void onCreate(Bundle savedInstanceState) {
1866        mIsSmsEnabled = MmsConfig.isSmsEnabled(this);
1867        super.onCreate(savedInstanceState);
1868
1869        resetConfiguration(getResources().getConfiguration());
1870
1871        setContentView(R.layout.compose_message_activity);
1872        setProgressBarVisibility(false);
1873
1874        // Initialize members for UI elements.
1875        initResourceRefs();
1876
1877        mContentResolver = getContentResolver();
1878        mBackgroundQueryHandler = new BackgroundQueryHandler(mContentResolver);
1879
1880        initialize(savedInstanceState, 0);
1881
1882        if (TRACE) {
1883            android.os.Debug.startMethodTracing("compose");
1884        }
1885    }
1886
1887    private void showSubjectEditor(boolean show) {
1888        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
1889            log("" + show);
1890        }
1891
1892        if (mSubjectTextEditor == null) {
1893            // Don't bother to initialize the subject editor if
1894            // we're just going to hide it.
1895            if (show == false) {
1896                return;
1897            }
1898            mSubjectTextEditor = (EditText)findViewById(R.id.subject);
1899            mSubjectTextEditor.setFilters(new InputFilter[] {
1900                    new LengthFilter(MmsConfig.getMaxSubjectLength())});
1901        }
1902
1903        mSubjectTextEditor.setOnKeyListener(show ? mSubjectKeyListener : null);
1904
1905        if (show) {
1906            mSubjectTextEditor.addTextChangedListener(mSubjectEditorWatcher);
1907        } else {
1908            mSubjectTextEditor.removeTextChangedListener(mSubjectEditorWatcher);
1909        }
1910
1911        mSubjectTextEditor.setText(mWorkingMessage.getSubject());
1912        mSubjectTextEditor.setVisibility(show ? View.VISIBLE : View.GONE);
1913        hideOrShowTopPanel();
1914    }
1915
1916    private void hideOrShowTopPanel() {
1917        boolean anySubViewsVisible = (isSubjectEditorVisible() || isRecipientsEditorVisible());
1918        mTopPanel.setVisibility(anySubViewsVisible ? View.VISIBLE : View.GONE);
1919    }
1920
1921    public void initialize(Bundle savedInstanceState, long originalThreadId) {
1922        // Create a new empty working message.
1923        mWorkingMessage = WorkingMessage.createEmpty(this);
1924
1925        // Read parameters or previously saved state of this activity. This will load a new
1926        // mConversation
1927        initActivityState(savedInstanceState);
1928
1929        if (LogTag.SEVERE_WARNING && originalThreadId != 0 &&
1930                originalThreadId == mConversation.getThreadId()) {
1931            LogTag.warnPossibleRecipientMismatch("ComposeMessageActivity.initialize: " +
1932                    " threadId didn't change from: " + originalThreadId, this);
1933        }
1934
1935        log("savedInstanceState = " + savedInstanceState +
1936            " intent = " + getIntent() +
1937            " mConversation = " + mConversation);
1938
1939        if (cancelFailedToDeliverNotification(getIntent(), this)) {
1940            // Show a pop-up dialog to inform user the message was
1941            // failed to deliver.
1942            undeliveredMessageDialog(getMessageDate(null));
1943        }
1944        cancelFailedDownloadNotification(getIntent(), this);
1945
1946        // Set up the message history ListAdapter
1947        initMessageList();
1948
1949        mShouldLoadDraft = true;
1950
1951        // Load the draft for this thread, if we aren't already handling
1952        // existing data, such as a shared picture or forwarded message.
1953        boolean isForwardedMessage = false;
1954        // We don't attempt to handle the Intent.ACTION_SEND when saveInstanceState is non-null.
1955        // saveInstanceState is non-null when this activity is killed. In that case, we already
1956        // handled the attachment or the send, so we don't try and parse the intent again.
1957        if (savedInstanceState == null && (handleSendIntent() || handleForwardedMessage())) {
1958            mShouldLoadDraft = false;
1959        }
1960
1961        // Let the working message know what conversation it belongs to
1962        mWorkingMessage.setConversation(mConversation);
1963
1964        // Show the recipients editor if we don't have a valid thread. Hide it otherwise.
1965        if (mConversation.getThreadId() <= 0) {
1966            // Hide the recipients editor so the call to initRecipientsEditor won't get
1967            // short-circuited.
1968            hideRecipientEditor();
1969            initRecipientsEditor();
1970        } else {
1971            hideRecipientEditor();
1972        }
1973
1974        updateSendButtonState();
1975
1976        drawTopPanel(false);
1977        if (!mShouldLoadDraft) {
1978            // We're not loading a draft, so we can draw the bottom panel immediately.
1979            drawBottomPanel();
1980        }
1981
1982        onKeyboardStateChanged();
1983
1984        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
1985            log("update title, mConversation=" + mConversation.toString());
1986        }
1987
1988        updateTitle(mConversation.getRecipients());
1989
1990        if (isForwardedMessage && isRecipientsEditorVisible()) {
1991            // The user is forwarding the message to someone. Put the focus on the
1992            // recipient editor rather than in the message editor.
1993            mRecipientsEditor.requestFocus();
1994        }
1995
1996        mMsgListAdapter.setIsGroupConversation(mConversation.getRecipients().size() > 1);
1997    }
1998
1999    @Override
2000    protected void onNewIntent(Intent intent) {
2001        super.onNewIntent(intent);
2002
2003        setIntent(intent);
2004
2005        Conversation conversation = null;
2006        mSentMessage = false;
2007
2008        // If we have been passed a thread_id, use that to find our
2009        // conversation.
2010
2011        // Note that originalThreadId might be zero but if this is a draft and we save the
2012        // draft, ensureThreadId gets called async from WorkingMessage.asyncUpdateDraftSmsMessage
2013        // the thread will get a threadId behind the UI thread's back.
2014        long originalThreadId = mConversation.getThreadId();
2015        long threadId = intent.getLongExtra(THREAD_ID, 0);
2016        Uri intentUri = intent.getData();
2017
2018        boolean sameThread = false;
2019        if (threadId > 0) {
2020            conversation = Conversation.get(this, threadId, false);
2021        } else {
2022            if (mConversation.getThreadId() == 0) {
2023                // We've got a draft. Make sure the working recipients are synched
2024                // to the conversation so when we compare conversations later in this function,
2025                // the compare will work.
2026                mWorkingMessage.syncWorkingRecipients();
2027            }
2028            // Get the "real" conversation based on the intentUri. The intentUri might specify
2029            // the conversation by a phone number or by a thread id. We'll typically get a threadId
2030            // based uri when the user pulls down a notification while in ComposeMessageActivity and
2031            // we end up here in onNewIntent. mConversation can have a threadId of zero when we're
2032            // working on a draft. When a new message comes in for that same recipient, a
2033            // conversation will get created behind CMA's back when the message is inserted into
2034            // the database and the corresponding entry made in the threads table. The code should
2035            // use the real conversation as soon as it can rather than finding out the threadId
2036            // when sending with "ensureThreadId".
2037            conversation = Conversation.get(this, intentUri, false);
2038        }
2039
2040        if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
2041            log("onNewIntent: data=" + intentUri + ", thread_id extra is " + threadId +
2042                    ", new conversation=" + conversation + ", mConversation=" + mConversation);
2043        }
2044
2045        // this is probably paranoid to compare both thread_ids and recipient lists,
2046        // but we want to make double sure because this is a last minute fix for Froyo
2047        // and the previous code checked thread ids only.
2048        // (we cannot just compare thread ids because there is a case where mConversation
2049        // has a stale/obsolete thread id (=1) that could collide against the new thread_id(=1),
2050        // even though the recipient lists are different)
2051        sameThread = ((conversation.getThreadId() == mConversation.getThreadId() ||
2052                mConversation.getThreadId() == 0) &&
2053                conversation.equals(mConversation));
2054
2055        if (sameThread) {
2056            log("onNewIntent: same conversation");
2057            if (mConversation.getThreadId() == 0) {
2058                mConversation = conversation;
2059                mWorkingMessage.setConversation(mConversation);
2060                updateThreadIdIfRunning();
2061                invalidateOptionsMenu();
2062            }
2063        } else {
2064            if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
2065                log("onNewIntent: different conversation");
2066            }
2067            saveDraft(false);    // if we've got a draft, save it first
2068
2069            initialize(null, originalThreadId);
2070        }
2071        loadMessagesAndDraft(0);
2072    }
2073
2074    private void sanityCheckConversation() {
2075        if (mWorkingMessage.getConversation() != mConversation) {
2076            LogTag.warnPossibleRecipientMismatch(
2077                    "ComposeMessageActivity: mWorkingMessage.mConversation=" +
2078                    mWorkingMessage.getConversation() + ", mConversation=" +
2079                    mConversation + ", MISMATCH!", this);
2080        }
2081    }
2082
2083    @Override
2084    protected void onRestart() {
2085        super.onRestart();
2086
2087        // hide the compose panel to reduce jank when re-entering this activity.
2088        // if we don't hide it here, the compose panel will flash before the keyboard shows
2089        // (when keyboard is suppose to be shown).
2090        hideBottomPanel();
2091
2092        if (mWorkingMessage.isDiscarded()) {
2093            // If the message isn't worth saving, don't resurrect it. Doing so can lead to
2094            // a situation where a new incoming message gets the old thread id of the discarded
2095            // draft. This activity can end up displaying the recipients of the old message with
2096            // the contents of the new message. Recognize that dangerous situation and bail out
2097            // to the ConversationList where the user can enter this in a clean manner.
2098            if (mWorkingMessage.isWorthSaving()) {
2099                if (LogTag.VERBOSE) {
2100                    log("onRestart: mWorkingMessage.unDiscard()");
2101                }
2102                mWorkingMessage.unDiscard();    // it was discarded in onStop().
2103
2104                sanityCheckConversation();
2105            } else if (isRecipientsEditorVisible() && recipientCount() > 0) {
2106                if (LogTag.VERBOSE) {
2107                    log("onRestart: goToConversationList");
2108                }
2109                goToConversationList();
2110            }
2111        }
2112    }
2113
2114    @Override
2115    protected void onStart() {
2116        super.onStart();
2117        boolean isSmsEnabled = MmsConfig.isSmsEnabled(this);
2118        if (isSmsEnabled != mIsSmsEnabled) {
2119            mIsSmsEnabled = isSmsEnabled;
2120            invalidateOptionsMenu();
2121        }
2122
2123        initFocus();
2124
2125        // Register a BroadcastReceiver to listen on HTTP I/O process.
2126        registerReceiver(mHttpProgressReceiver, mHttpProgressFilter);
2127
2128        // figure out whether we need to show the keyboard or not.
2129        // if there is draft to be loaded for 'mConversation', we'll show the keyboard;
2130        // otherwise we hide the keyboard. In any event, delay loading
2131        // message history and draft (controlled by DEFER_LOADING_MESSAGES_AND_DRAFT).
2132        int mode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
2133
2134        if (DraftCache.getInstance().hasDraft(mConversation.getThreadId())) {
2135            mode |= WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE;
2136        } else if (mConversation.getThreadId() <= 0) {
2137            // For composing a new message, bring up the softkeyboard so the user can
2138            // immediately enter recipients. This call won't do anything on devices with
2139            // a hard keyboard.
2140            mode |= WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE;
2141        } else {
2142            mode |= WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN;
2143        }
2144
2145        getWindow().setSoftInputMode(mode);
2146
2147        // reset mMessagesAndDraftLoaded
2148        mMessagesAndDraftLoaded = false;
2149
2150        if (!DEFER_LOADING_MESSAGES_AND_DRAFT) {
2151            loadMessagesAndDraft(1);
2152        } else {
2153            // HACK: force load messages+draft after max delay, if it's not already loaded.
2154            // this is to work around when coming out of sleep mode. WindowManager behaves
2155            // strangely and hides the keyboard when it should be shown, or sometimes initially
2156            // shows it when we want to hide it. In that case, we never get the onSizeChanged()
2157            // callback w/ keyboard shown, so we wouldn't know to load the messages+draft.
2158            mHandler.postDelayed(new Runnable() {
2159                public void run() {
2160                    loadMessagesAndDraft(2);
2161                }
2162            }, LOADING_MESSAGES_AND_DRAFT_MAX_DELAY_MS);
2163        }
2164
2165        // Update the fasttrack info in case any of the recipients' contact info changed
2166        // while we were paused. This can happen, for example, if a user changes or adds
2167        // an avatar associated with a contact.
2168        mWorkingMessage.syncWorkingRecipients();
2169
2170        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
2171            log("update title, mConversation=" + mConversation.toString());
2172        }
2173
2174        updateTitle(mConversation.getRecipients());
2175
2176        ActionBar actionBar = getActionBar();
2177        actionBar.setDisplayHomeAsUpEnabled(true);
2178    }
2179
2180    public void loadMessageContent() {
2181        // Don't let any markAsRead DB updates occur before we've loaded the messages for
2182        // the thread. Unblocking occurs when we're done querying for the conversation
2183        // items.
2184        mConversation.blockMarkAsRead(true);
2185        mConversation.markAsRead();         // dismiss any notifications for this convo
2186        startMsgListQuery();
2187        updateSendFailedNotification();
2188    }
2189
2190    /**
2191     * Load message history and draft. This method should be called from main thread.
2192     * @param debugFlag shows where this is being called from
2193     */
2194    private void loadMessagesAndDraft(int debugFlag) {
2195        if (!mSendDiscreetMode && !mMessagesAndDraftLoaded) {
2196            if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
2197                Log.v(TAG, "### CMA.loadMessagesAndDraft: flag=" + debugFlag);
2198            }
2199            loadMessageContent();
2200            boolean drawBottomPanel = true;
2201            if (mShouldLoadDraft) {
2202                if (loadDraft()) {
2203                    drawBottomPanel = false;
2204                }
2205            }
2206            if (drawBottomPanel) {
2207                drawBottomPanel();
2208            }
2209            mMessagesAndDraftLoaded = true;
2210        }
2211    }
2212
2213    private void updateSendFailedNotification() {
2214        final long threadId = mConversation.getThreadId();
2215        if (threadId <= 0)
2216            return;
2217
2218        // updateSendFailedNotificationForThread makes a database call, so do the work off
2219        // of the ui thread.
2220        new Thread(new Runnable() {
2221            @Override
2222            public void run() {
2223                MessagingNotification.updateSendFailedNotificationForThread(
2224                        ComposeMessageActivity.this, threadId);
2225            }
2226        }, "ComposeMessageActivity.updateSendFailedNotification").start();
2227    }
2228
2229    @Override
2230    public void onSaveInstanceState(Bundle outState) {
2231        super.onSaveInstanceState(outState);
2232
2233        outState.putString(RECIPIENTS, getRecipients().serialize());
2234
2235        mWorkingMessage.writeStateToBundle(outState);
2236
2237        if (mSendDiscreetMode) {
2238            outState.putBoolean(KEY_EXIT_ON_SENT, mSendDiscreetMode);
2239        }
2240        if (mForwardMessageMode) {
2241            outState.putBoolean(KEY_FORWARDED_MESSAGE, mForwardMessageMode);
2242        }
2243    }
2244
2245    @Override
2246    protected void onResume() {
2247        super.onResume();
2248
2249        // OLD: get notified of presence updates to update the titlebar.
2250        // NEW: we are using ContactHeaderWidget which displays presence, but updating presence
2251        //      there is out of our control.
2252        //Contact.startPresenceObserver();
2253
2254        addRecipientsListeners();
2255
2256        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
2257            log("update title, mConversation=" + mConversation.toString());
2258        }
2259
2260        // There seems to be a bug in the framework such that setting the title
2261        // here gets overwritten to the original title.  Do this delayed as a
2262        // workaround.
2263        mMessageListItemHandler.postDelayed(new Runnable() {
2264            @Override
2265            public void run() {
2266                ContactList recipients = isRecipientsEditorVisible() ?
2267                        mRecipientsEditor.constructContactsFromInput(false) : getRecipients();
2268                updateTitle(recipients);
2269            }
2270        }, 100);
2271
2272        mIsRunning = true;
2273        updateThreadIdIfRunning();
2274        mConversation.markAsRead();
2275    }
2276
2277    @Override
2278    protected void onPause() {
2279        super.onPause();
2280
2281        if (DEBUG) {
2282            Log.v(TAG, "onPause: setCurrentlyDisplayedThreadId: " +
2283                        MessagingNotification.THREAD_NONE);
2284        }
2285        MessagingNotification.setCurrentlyDisplayedThreadId(MessagingNotification.THREAD_NONE);
2286
2287        // OLD: stop getting notified of presence updates to update the titlebar.
2288        // NEW: we are using ContactHeaderWidget which displays presence, but updating presence
2289        //      there is out of our control.
2290        //Contact.stopPresenceObserver();
2291
2292        removeRecipientsListeners();
2293
2294        // remove any callback to display a progress spinner
2295        if (mAsyncDialog != null) {
2296            mAsyncDialog.clearPendingProgressDialog();
2297        }
2298
2299        // Remember whether the list is scrolled to the end when we're paused so we can rescroll
2300        // to the end when resumed.
2301        if (mMsgListAdapter != null &&
2302                mMsgListView.getLastVisiblePosition() >= mMsgListAdapter.getCount() - 1) {
2303            mSavedScrollPosition = Integer.MAX_VALUE;
2304        } else {
2305            mSavedScrollPosition = mMsgListView.getFirstVisiblePosition();
2306        }
2307        if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
2308            Log.v(TAG, "onPause: mSavedScrollPosition=" + mSavedScrollPosition);
2309        }
2310
2311        mConversation.markAsRead();
2312        mIsRunning = false;
2313    }
2314
2315    @Override
2316    protected void onStop() {
2317        super.onStop();
2318
2319        // No need to do the querying when finished this activity
2320        mBackgroundQueryHandler.cancelOperation(MESSAGE_LIST_QUERY_TOKEN);
2321
2322        // Allow any blocked calls to update the thread's read status.
2323        mConversation.blockMarkAsRead(false);
2324
2325        if (mMsgListAdapter != null) {
2326            // Close the cursor in the ListAdapter if the activity stopped.
2327            Cursor cursor = mMsgListAdapter.getCursor();
2328
2329            if (cursor != null && !cursor.isClosed()) {
2330                cursor.close();
2331            }
2332
2333            mMsgListAdapter.changeCursor(null);
2334            mMsgListAdapter.cancelBackgroundLoading();
2335        }
2336
2337        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
2338            log("save draft");
2339        }
2340        saveDraft(true);
2341
2342        // set 'mShouldLoadDraft' to true, so when coming back to ComposeMessageActivity, we would
2343        // load the draft, unless we are coming back to the activity after attaching a photo, etc,
2344        // in which case we should set 'mShouldLoadDraft' to false.
2345        mShouldLoadDraft = true;
2346
2347        // Cleanup the BroadcastReceiver.
2348        unregisterReceiver(mHttpProgressReceiver);
2349    }
2350
2351    @Override
2352    protected void onDestroy() {
2353        if (TRACE) {
2354            android.os.Debug.stopMethodTracing();
2355        }
2356
2357        super.onDestroy();
2358    }
2359
2360    @Override
2361    public void onConfigurationChanged(Configuration newConfig) {
2362        super.onConfigurationChanged(newConfig);
2363
2364        if (resetConfiguration(newConfig)) {
2365            // Have to re-layout the attachment editor because we have different layouts
2366            // depending on whether we're portrait or landscape.
2367            drawTopPanel(isSubjectEditorVisible());
2368        }
2369        if (LOCAL_LOGV) {
2370            Log.v(TAG, "CMA.onConfigurationChanged: " + newConfig +
2371                    ", mIsKeyboardOpen=" + mIsKeyboardOpen);
2372        }
2373        onKeyboardStateChanged();
2374    }
2375
2376    // returns true if landscape/portrait configuration has changed
2377    private boolean resetConfiguration(Configuration config) {
2378        mIsKeyboardOpen = config.keyboardHidden == KEYBOARDHIDDEN_NO;
2379        boolean isLandscape = config.orientation == Configuration.ORIENTATION_LANDSCAPE;
2380        if (mIsLandscape != isLandscape) {
2381            mIsLandscape = isLandscape;
2382            return true;
2383        }
2384        return false;
2385    }
2386
2387    private void onKeyboardStateChanged() {
2388        // If the keyboard is hidden, don't show focus highlights for
2389        // things that cannot receive input.
2390        mTextEditor.setEnabled(mIsSmsEnabled);
2391        if (!mIsSmsEnabled) {
2392            if (mRecipientsEditor != null) {
2393                mRecipientsEditor.setFocusableInTouchMode(false);
2394            }
2395            if (mSubjectTextEditor != null) {
2396                mSubjectTextEditor.setFocusableInTouchMode(false);
2397            }
2398            mTextEditor.setFocusableInTouchMode(false);
2399            mTextEditor.setHint(R.string.sending_disabled_not_default_app);
2400        } else if (mIsKeyboardOpen) {
2401            if (mRecipientsEditor != null) {
2402                mRecipientsEditor.setFocusableInTouchMode(true);
2403            }
2404            if (mSubjectTextEditor != null) {
2405                mSubjectTextEditor.setFocusableInTouchMode(true);
2406            }
2407            mTextEditor.setFocusableInTouchMode(true);
2408            mTextEditor.setHint(R.string.type_to_compose_text_enter_to_send);
2409        } else {
2410            if (mRecipientsEditor != null) {
2411                mRecipientsEditor.setFocusable(false);
2412            }
2413            if (mSubjectTextEditor != null) {
2414                mSubjectTextEditor.setFocusable(false);
2415            }
2416            mTextEditor.setFocusable(false);
2417            mTextEditor.setHint(R.string.open_keyboard_to_compose_message);
2418        }
2419    }
2420
2421    @Override
2422    public boolean onKeyDown(int keyCode, KeyEvent event) {
2423        switch (keyCode) {
2424            case KeyEvent.KEYCODE_DEL:
2425                if ((mMsgListAdapter != null) && mMsgListView.isFocused()) {
2426                    Cursor cursor;
2427                    try {
2428                        cursor = (Cursor) mMsgListView.getSelectedItem();
2429                    } catch (ClassCastException e) {
2430                        Log.e(TAG, "Unexpected ClassCastException.", e);
2431                        return super.onKeyDown(keyCode, event);
2432                    }
2433
2434                    if (cursor != null) {
2435                        String type = cursor.getString(COLUMN_MSG_TYPE);
2436                        long msgId = cursor.getLong(COLUMN_ID);
2437                        MessageItem msgItem = mMsgListAdapter.getCachedMessageItem(type, msgId,
2438                                cursor);
2439                        if (msgItem != null) {
2440                            DeleteMessageListener l = new DeleteMessageListener(msgItem);
2441                            confirmDeleteDialog(l, msgItem.mLocked);
2442                        }
2443                        return true;
2444                    }
2445                }
2446                break;
2447            case KeyEvent.KEYCODE_DPAD_CENTER:
2448            case KeyEvent.KEYCODE_ENTER:
2449                if (isPreparedForSending()) {
2450                    confirmSendMessageIfNeeded();
2451                    return true;
2452                }
2453                break;
2454            case KeyEvent.KEYCODE_BACK:
2455                exitComposeMessageActivity(new Runnable() {
2456                    @Override
2457                    public void run() {
2458                        finish();
2459                    }
2460                });
2461                return true;
2462        }
2463
2464        return super.onKeyDown(keyCode, event);
2465    }
2466
2467    private void exitComposeMessageActivity(final Runnable exit) {
2468        // If the message is empty, just quit -- finishing the
2469        // activity will cause an empty draft to be deleted.
2470        if (!mWorkingMessage.isWorthSaving()) {
2471            exit.run();
2472            return;
2473        }
2474
2475        if (isRecipientsEditorVisible() &&
2476                !mRecipientsEditor.hasValidRecipient(mWorkingMessage.requiresMms())) {
2477            MessageUtils.showDiscardDraftConfirmDialog(this, new DiscardDraftListener());
2478            return;
2479        }
2480
2481        mToastForDraftSave = true;
2482        exit.run();
2483    }
2484
2485    private void goToConversationList() {
2486        finish();
2487        startActivity(new Intent(this, ConversationList.class));
2488    }
2489
2490    private void hideRecipientEditor() {
2491        if (mRecipientsEditor != null) {
2492            mRecipientsEditor.removeTextChangedListener(mRecipientsWatcher);
2493            mRecipientsEditor.setVisibility(View.GONE);
2494            hideOrShowTopPanel();
2495        }
2496    }
2497
2498    private boolean isRecipientsEditorVisible() {
2499        return (null != mRecipientsEditor)
2500                    && (View.VISIBLE == mRecipientsEditor.getVisibility());
2501    }
2502
2503    private boolean isSubjectEditorVisible() {
2504        return (null != mSubjectTextEditor)
2505                    && (View.VISIBLE == mSubjectTextEditor.getVisibility());
2506    }
2507
2508    @Override
2509    public void onAttachmentChanged() {
2510        // Have to make sure we're on the UI thread. This function can be called off of the UI
2511        // thread when we're adding multi-attachments
2512        runOnUiThread(new Runnable() {
2513            @Override
2514            public void run() {
2515                drawBottomPanel();
2516                updateSendButtonState();
2517                drawTopPanel(isSubjectEditorVisible());
2518            }
2519        });
2520    }
2521
2522    @Override
2523    public void onProtocolChanged(final boolean convertToMms) {
2524        // Have to make sure we're on the UI thread. This function can be called off of the UI
2525        // thread when we're adding multi-attachments
2526        runOnUiThread(new Runnable() {
2527            @Override
2528            public void run() {
2529                showSmsOrMmsSendButton(convertToMms);
2530
2531                if (convertToMms) {
2532                    // In the case we went from a long sms with a counter to an mms because
2533                    // the user added an attachment or a subject, hide the counter --
2534                    // it doesn't apply to mms.
2535                    mTextCounter.setVisibility(View.GONE);
2536
2537                    showConvertToMmsToast();
2538                }
2539            }
2540        });
2541    }
2542
2543    // Show or hide the Sms or Mms button as appropriate. Return the view so that the caller
2544    // can adjust the enableness and focusability.
2545    private View showSmsOrMmsSendButton(boolean isMms) {
2546        View showButton;
2547        View hideButton;
2548        if (isMms) {
2549            showButton = mSendButtonMms;
2550            hideButton = mSendButtonSms;
2551        } else {
2552            showButton = mSendButtonSms;
2553            hideButton = mSendButtonMms;
2554        }
2555        showButton.setVisibility(View.VISIBLE);
2556        hideButton.setVisibility(View.GONE);
2557
2558        return showButton;
2559    }
2560
2561    Runnable mResetMessageRunnable = new Runnable() {
2562        @Override
2563        public void run() {
2564            resetMessage();
2565        }
2566    };
2567
2568    @Override
2569    public void onPreMessageSent() {
2570        runOnUiThread(mResetMessageRunnable);
2571    }
2572
2573    @Override
2574    public void onMessageSent() {
2575        // This callback can come in on any thread; put it on the main thread to avoid
2576        // concurrency problems
2577        runOnUiThread(new Runnable() {
2578            @Override
2579            public void run() {
2580                // If we already have messages in the list adapter, it
2581                // will be auto-requerying; don't thrash another query in.
2582                // TODO: relying on auto-requerying seems unreliable when priming an MMS into the
2583                // outbox. Need to investigate.
2584//                if (mMsgListAdapter.getCount() == 0) {
2585                    if (LogTag.VERBOSE) {
2586                        log("onMessageSent");
2587                    }
2588                    startMsgListQuery();
2589//                }
2590
2591                // The thread ID could have changed if this is a new message that we just inserted
2592                // into the database (and looked up or created a thread for it)
2593                updateThreadIdIfRunning();
2594            }
2595        });
2596    }
2597
2598    @Override
2599    public void onMaxPendingMessagesReached() {
2600        saveDraft(false);
2601
2602        runOnUiThread(new Runnable() {
2603            @Override
2604            public void run() {
2605                Toast.makeText(ComposeMessageActivity.this, R.string.too_many_unsent_mms,
2606                        Toast.LENGTH_LONG).show();
2607            }
2608        });
2609    }
2610
2611    @Override
2612    public void onAttachmentError(final int error) {
2613        runOnUiThread(new Runnable() {
2614            @Override
2615            public void run() {
2616                handleAddAttachmentError(error, R.string.type_picture);
2617                onMessageSent();        // now requery the list of messages
2618            }
2619        });
2620    }
2621
2622    // We don't want to show the "call" option unless there is only one
2623    // recipient and it's a phone number.
2624    private boolean isRecipientCallable() {
2625        ContactList recipients = getRecipients();
2626        return (recipients.size() == 1 && !recipients.containsEmail());
2627    }
2628
2629    private void dialRecipient() {
2630        if (isRecipientCallable()) {
2631            String number = getRecipients().get(0).getNumber();
2632            Intent dialIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));
2633            startActivity(dialIntent);
2634        }
2635    }
2636
2637    @Override
2638    public boolean onPrepareOptionsMenu(Menu menu) {
2639        super.onPrepareOptionsMenu(menu) ;
2640
2641        menu.clear();
2642
2643        if (mSendDiscreetMode && !mForwardMessageMode) {
2644            // When we're in send-a-single-message mode from the lock screen, don't show
2645            // any menus.
2646            return true;
2647        }
2648
2649        // Don't show the call icon if the device don't support voice calling.
2650        boolean voiceCapable =
2651                getResources().getBoolean(com.android.internal.R.bool.config_voice_capable);
2652        if (isRecipientCallable() && voiceCapable) {
2653            MenuItem item = menu.add(0, MENU_CALL_RECIPIENT, 0, R.string.menu_call)
2654                .setIcon(R.drawable.ic_menu_call)
2655                .setTitle(R.string.menu_call);
2656            if (!isRecipientsEditorVisible()) {
2657                // If we're not composing a new message, show the call icon in the actionbar
2658                item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
2659            }
2660        }
2661
2662        if (MmsConfig.getMmsEnabled() && mIsSmsEnabled) {
2663            if (!isSubjectEditorVisible()) {
2664                menu.add(0, MENU_ADD_SUBJECT, 0, R.string.add_subject).setIcon(
2665                        R.drawable.ic_menu_edit);
2666            }
2667            if (!mWorkingMessage.hasAttachment()) {
2668                menu.add(0, MENU_ADD_ATTACHMENT, 0, R.string.add_attachment)
2669                        .setIcon(R.drawable.ic_menu_attachment)
2670                    .setTitle(R.string.add_attachment)
2671                        .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);    // add to actionbar
2672            }
2673        }
2674
2675        if (isPreparedForSending() && mIsSmsEnabled) {
2676            menu.add(0, MENU_SEND, 0, R.string.send).setIcon(android.R.drawable.ic_menu_send);
2677        }
2678
2679        if (getRecipients().size() > 1) {
2680            menu.add(0, MENU_GROUP_PARTICIPANTS, 0, R.string.menu_group_participants);
2681        }
2682
2683        if (mMsgListAdapter.getCount() > 0 && mIsSmsEnabled) {
2684            // Removed search as part of b/1205708
2685            //menu.add(0, MENU_SEARCH, 0, R.string.menu_search).setIcon(
2686            //        R.drawable.ic_menu_search);
2687            Cursor cursor = mMsgListAdapter.getCursor();
2688            if ((null != cursor) && (cursor.getCount() > 0)) {
2689                menu.add(0, MENU_DELETE_THREAD, 0, R.string.delete_thread).setIcon(
2690                    android.R.drawable.ic_menu_delete);
2691            }
2692        } else if (mIsSmsEnabled) {
2693            menu.add(0, MENU_DISCARD, 0, R.string.discard).setIcon(android.R.drawable.ic_menu_delete);
2694        }
2695
2696        buildAddAddressToContactMenuItem(menu);
2697
2698        menu.add(0, MENU_PREFERENCES, 0, R.string.menu_preferences).setIcon(
2699                android.R.drawable.ic_menu_preferences);
2700
2701        if (LogTag.DEBUG_DUMP) {
2702            menu.add(0, MENU_DEBUG_DUMP, 0, R.string.menu_debug_dump);
2703        }
2704
2705        return true;
2706    }
2707
2708    private void buildAddAddressToContactMenuItem(Menu menu) {
2709        // bug #7087793: for group of recipients, remove "Add to People" action. Rely on
2710        // individually creating contacts for unknown phone numbers by touching the individual
2711        // sender's avatars, one at a time
2712        ContactList contacts = getRecipients();
2713        if (contacts.size() != 1) {
2714            return;
2715        }
2716
2717        // if we don't have a contact for the recipient, create a menu item to add the number
2718        // to contacts.
2719        Contact c = contacts.get(0);
2720        if (!c.existsInDatabase() && canAddToContacts(c)) {
2721            Intent intent = ConversationList.createAddContactIntent(c.getNumber());
2722            menu.add(0, MENU_ADD_ADDRESS_TO_CONTACTS, 0, R.string.menu_add_to_contacts)
2723                .setIcon(android.R.drawable.ic_menu_add)
2724                .setIntent(intent);
2725        }
2726    }
2727
2728    @Override
2729    public boolean onOptionsItemSelected(MenuItem item) {
2730        switch (item.getItemId()) {
2731            case MENU_ADD_SUBJECT:
2732                showSubjectEditor(true);
2733                mWorkingMessage.setSubject("", true);
2734                updateSendButtonState();
2735                mSubjectTextEditor.requestFocus();
2736                break;
2737            case MENU_ADD_ATTACHMENT:
2738                // Launch the add-attachment list dialog
2739                showAddAttachmentDialog(false);
2740                break;
2741            case MENU_DISCARD:
2742                mWorkingMessage.discard();
2743                finish();
2744                break;
2745            case MENU_SEND:
2746                if (isPreparedForSending()) {
2747                    confirmSendMessageIfNeeded();
2748                }
2749                break;
2750            case MENU_SEARCH:
2751                onSearchRequested();
2752                break;
2753            case MENU_DELETE_THREAD:
2754                confirmDeleteThread(mConversation.getThreadId());
2755                break;
2756
2757            case android.R.id.home:
2758            case MENU_CONVERSATION_LIST:
2759                exitComposeMessageActivity(new Runnable() {
2760                    @Override
2761                    public void run() {
2762                        goToConversationList();
2763                    }
2764                });
2765                break;
2766            case MENU_CALL_RECIPIENT:
2767                dialRecipient();
2768                break;
2769            case MENU_GROUP_PARTICIPANTS:
2770            {
2771                Intent intent = new Intent(this, RecipientListActivity.class);
2772                intent.putExtra(THREAD_ID, mConversation.getThreadId());
2773                startActivity(intent);
2774                break;
2775            }
2776            case MENU_VIEW_CONTACT: {
2777                // View the contact for the first (and only) recipient.
2778                ContactList list = getRecipients();
2779                if (list.size() == 1 && list.get(0).existsInDatabase()) {
2780                    Uri contactUri = list.get(0).getUri();
2781                    Intent intent = new Intent(Intent.ACTION_VIEW, contactUri);
2782                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
2783                    startActivity(intent);
2784                }
2785                break;
2786            }
2787            case MENU_ADD_ADDRESS_TO_CONTACTS:
2788                mAddContactIntent = item.getIntent();
2789                startActivityForResult(mAddContactIntent, REQUEST_CODE_ADD_CONTACT);
2790                break;
2791            case MENU_PREFERENCES: {
2792                Intent intent = new Intent(this, MessagingPreferenceActivity.class);
2793                startActivityIfNeeded(intent, -1);
2794                break;
2795            }
2796            case MENU_DEBUG_DUMP:
2797                mWorkingMessage.dump();
2798                Conversation.dump();
2799                LogTag.dumpInternalTables(this);
2800                break;
2801        }
2802
2803        return true;
2804    }
2805
2806    private void confirmDeleteThread(long threadId) {
2807        Conversation.startQueryHaveLockedMessages(mBackgroundQueryHandler,
2808                threadId, ConversationList.HAVE_LOCKED_MESSAGES_TOKEN);
2809    }
2810
2811//    static class SystemProperties { // TODO, temp class to get unbundling working
2812//        static int getInt(String s, int value) {
2813//            return value;       // just return the default value or now
2814//        }
2815//    }
2816
2817    private void addAttachment(int type, boolean replace) {
2818        // Calculate the size of the current slide if we're doing a replace so the
2819        // slide size can optionally be used in computing how much room is left for an attachment.
2820        int currentSlideSize = 0;
2821        SlideshowModel slideShow = mWorkingMessage.getSlideshow();
2822        if (replace && slideShow != null) {
2823            WorkingMessage.removeThumbnailsFromCache(slideShow);
2824            SlideModel slide = slideShow.get(0);
2825            currentSlideSize = slide.getSlideSize();
2826        }
2827        switch (type) {
2828            case AttachmentTypeSelectorAdapter.ADD_IMAGE:
2829                MessageUtils.selectImage(this, REQUEST_CODE_ATTACH_IMAGE);
2830                break;
2831
2832            case AttachmentTypeSelectorAdapter.TAKE_PICTURE: {
2833                MessageUtils.capturePicture(this, REQUEST_CODE_TAKE_PICTURE);
2834                break;
2835            }
2836
2837            case AttachmentTypeSelectorAdapter.ADD_VIDEO:
2838                MessageUtils.selectVideo(this, REQUEST_CODE_ATTACH_VIDEO);
2839                break;
2840
2841            case AttachmentTypeSelectorAdapter.RECORD_VIDEO: {
2842                long sizeLimit = computeAttachmentSizeLimit(slideShow, currentSlideSize);
2843                if (sizeLimit > 0) {
2844                    MessageUtils.recordVideo(this, REQUEST_CODE_TAKE_VIDEO, sizeLimit);
2845                } else {
2846                    Toast.makeText(this,
2847                            getString(R.string.message_too_big_for_video),
2848                            Toast.LENGTH_SHORT).show();
2849                }
2850            }
2851            break;
2852
2853            case AttachmentTypeSelectorAdapter.ADD_SOUND:
2854                MessageUtils.selectAudio(this, REQUEST_CODE_ATTACH_SOUND);
2855                break;
2856
2857            case AttachmentTypeSelectorAdapter.RECORD_SOUND:
2858                long sizeLimit = computeAttachmentSizeLimit(slideShow, currentSlideSize);
2859                MessageUtils.recordSound(this, REQUEST_CODE_RECORD_SOUND, sizeLimit);
2860                break;
2861
2862            case AttachmentTypeSelectorAdapter.ADD_SLIDESHOW:
2863                editSlideshow();
2864                break;
2865
2866            default:
2867                break;
2868        }
2869    }
2870
2871    public static long computeAttachmentSizeLimit(SlideshowModel slideShow, int currentSlideSize) {
2872        // Computer attachment size limit. Subtract 1K for some text.
2873        long sizeLimit = MmsConfig.getMaxMessageSize() - SlideshowModel.SLIDESHOW_SLOP;
2874        if (slideShow != null) {
2875            sizeLimit -= slideShow.getCurrentMessageSize();
2876
2877            // We're about to ask the camera to capture some video (or the sound recorder
2878            // to record some audio) which will eventually replace the content on the current
2879            // slide. Since the current slide already has some content (which was subtracted
2880            // out just above) and that content is going to get replaced, we can add the size of the
2881            // current slide into the available space used to capture a video (or audio).
2882            sizeLimit += currentSlideSize;
2883        }
2884        return sizeLimit;
2885    }
2886
2887    private void showAddAttachmentDialog(final boolean replace) {
2888        AlertDialog.Builder builder = new AlertDialog.Builder(this);
2889        builder.setIcon(R.drawable.ic_dialog_attach);
2890        builder.setTitle(R.string.add_attachment);
2891
2892        if (mAttachmentTypeSelectorAdapter == null) {
2893            mAttachmentTypeSelectorAdapter = new AttachmentTypeSelectorAdapter(
2894                    this, AttachmentTypeSelectorAdapter.MODE_WITH_SLIDESHOW);
2895        }
2896        builder.setAdapter(mAttachmentTypeSelectorAdapter, new DialogInterface.OnClickListener() {
2897            @Override
2898            public void onClick(DialogInterface dialog, int which) {
2899                addAttachment(mAttachmentTypeSelectorAdapter.buttonToCommand(which), replace);
2900                dialog.dismiss();
2901            }
2902        });
2903
2904        builder.show();
2905    }
2906
2907    @Override
2908    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
2909        if (LogTag.VERBOSE) {
2910            log("onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode +
2911                    ", data=" + data);
2912        }
2913        mWaitingForSubActivity = false;          // We're back!
2914        mShouldLoadDraft = false;
2915        if (mWorkingMessage.isFakeMmsForDraft()) {
2916            // We no longer have to fake the fact we're an Mms. At this point we are or we aren't,
2917            // based on attachments and other Mms attrs.
2918            mWorkingMessage.removeFakeMmsForDraft();
2919        }
2920
2921        if (requestCode == REQUEST_CODE_PICK) {
2922            mWorkingMessage.asyncDeleteDraftSmsMessage(mConversation);
2923        }
2924
2925        if (requestCode == REQUEST_CODE_ADD_CONTACT) {
2926            // The user might have added a new contact. When we tell contacts to add a contact
2927            // and tap "Done", we're not returned to Messaging. If we back out to return to
2928            // messaging after adding a contact, the resultCode is RESULT_CANCELED. Therefore,
2929            // assume a contact was added and get the contact and force our cached contact to
2930            // get reloaded with the new info (such as contact name). After the
2931            // contact is reloaded, the function onUpdate() in this file will get called
2932            // and it will update the title bar, etc.
2933            if (mAddContactIntent != null) {
2934                String address =
2935                    mAddContactIntent.getStringExtra(ContactsContract.Intents.Insert.EMAIL);
2936                if (address == null) {
2937                    address =
2938                        mAddContactIntent.getStringExtra(ContactsContract.Intents.Insert.PHONE);
2939                }
2940                if (address != null) {
2941                    Contact contact = Contact.get(address, false);
2942                    if (contact != null) {
2943                        contact.reload();
2944                    }
2945                }
2946            }
2947        }
2948
2949        if (resultCode != RESULT_OK){
2950            if (LogTag.VERBOSE) log("bail due to resultCode=" + resultCode);
2951            return;
2952        }
2953
2954        switch (requestCode) {
2955            case REQUEST_CODE_CREATE_SLIDESHOW:
2956                if (data != null) {
2957                    WorkingMessage newMessage = WorkingMessage.load(this, data.getData());
2958                    if (newMessage != null) {
2959                        mWorkingMessage = newMessage;
2960                        mWorkingMessage.setConversation(mConversation);
2961                        updateThreadIdIfRunning();
2962                        drawTopPanel(false);
2963                        updateSendButtonState();
2964                    }
2965                }
2966                break;
2967
2968            case REQUEST_CODE_TAKE_PICTURE: {
2969                // create a file based uri and pass to addImage(). We want to read the JPEG
2970                // data directly from file (using UriImage) instead of decoding it into a Bitmap,
2971                // which takes up too much memory and could easily lead to OOM.
2972                File file = new File(TempFileProvider.getScrapPath(this));
2973                Uri uri = Uri.fromFile(file);
2974
2975                // Remove the old captured picture's thumbnail from the cache
2976                MmsApp.getApplication().getThumbnailManager().removeThumbnail(uri);
2977
2978                addImageAsync(uri, false);
2979                break;
2980            }
2981
2982            case REQUEST_CODE_ATTACH_IMAGE: {
2983                if (data != null) {
2984                    addImageAsync(data.getData(), false);
2985                }
2986                break;
2987            }
2988
2989            case REQUEST_CODE_TAKE_VIDEO:
2990                Uri videoUri = TempFileProvider.renameScrapFile(".3gp", null, this);
2991                // Remove the old captured video's thumbnail from the cache
2992                MmsApp.getApplication().getThumbnailManager().removeThumbnail(videoUri);
2993
2994                addVideoAsync(videoUri, false);      // can handle null videoUri
2995                break;
2996
2997            case REQUEST_CODE_ATTACH_VIDEO:
2998                if (data != null) {
2999                    addVideoAsync(data.getData(), false);
3000                }
3001                break;
3002
3003            case REQUEST_CODE_ATTACH_SOUND: {
3004                Uri uri = (Uri) data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
3005                if (Settings.System.DEFAULT_RINGTONE_URI.equals(uri)) {
3006                    break;
3007                }
3008                addAudio(uri);
3009                break;
3010            }
3011
3012            case REQUEST_CODE_RECORD_SOUND:
3013                if (data != null) {
3014                    addAudio(data.getData());
3015                }
3016                break;
3017
3018            case REQUEST_CODE_ECM_EXIT_DIALOG:
3019                boolean outOfEmergencyMode = data.getBooleanExtra(EXIT_ECM_RESULT, false);
3020                if (outOfEmergencyMode) {
3021                    sendMessage(false);
3022                }
3023                break;
3024
3025            case REQUEST_CODE_PICK:
3026                if (data != null) {
3027                    processPickResult(data);
3028                }
3029                break;
3030
3031            default:
3032                if (LogTag.VERBOSE) log("bail due to unknown requestCode=" + requestCode);
3033                break;
3034        }
3035    }
3036
3037    private void processPickResult(final Intent data) {
3038        // The EXTRA_PHONE_URIS stores the phone's urls that were selected by user in the
3039        // multiple phone picker.
3040        final Parcelable[] uris =
3041            data.getParcelableArrayExtra(Intents.EXTRA_PHONE_URIS);
3042
3043        final int recipientCount = uris != null ? uris.length : 0;
3044
3045        final int recipientLimit = MmsConfig.getRecipientLimit();
3046        if (recipientLimit != Integer.MAX_VALUE && recipientCount > recipientLimit) {
3047            new AlertDialog.Builder(this)
3048                    .setMessage(getString(R.string.too_many_recipients, recipientCount, recipientLimit))
3049                    .setPositiveButton(android.R.string.ok, null)
3050                    .create().show();
3051            return;
3052        }
3053
3054        final Handler handler = new Handler();
3055        final ProgressDialog progressDialog = new ProgressDialog(this);
3056        progressDialog.setTitle(getText(R.string.pick_too_many_recipients));
3057        progressDialog.setMessage(getText(R.string.adding_recipients));
3058        progressDialog.setIndeterminate(true);
3059        progressDialog.setCancelable(false);
3060
3061        final Runnable showProgress = new Runnable() {
3062            @Override
3063            public void run() {
3064                progressDialog.show();
3065            }
3066        };
3067        // Only show the progress dialog if we can not finish off parsing the return data in 1s,
3068        // otherwise the dialog could flicker.
3069        handler.postDelayed(showProgress, 1000);
3070
3071        new Thread(new Runnable() {
3072            @Override
3073            public void run() {
3074                final ContactList list;
3075                 try {
3076                    list = ContactList.blockingGetByUris(uris);
3077                } finally {
3078                    handler.removeCallbacks(showProgress);
3079                    progressDialog.dismiss();
3080                }
3081                // TODO: there is already code to update the contact header widget and recipients
3082                // editor if the contacts change. we can re-use that code.
3083                final Runnable populateWorker = new Runnable() {
3084                    @Override
3085                    public void run() {
3086                        mRecipientsEditor.populate(list);
3087                        updateTitle(list);
3088                    }
3089                };
3090                handler.post(populateWorker);
3091            }
3092        }, "ComoseMessageActivity.processPickResult").start();
3093    }
3094
3095    private final ResizeImageResultCallback mResizeImageCallback = new ResizeImageResultCallback() {
3096        // TODO: make this produce a Uri, that's what we want anyway
3097        @Override
3098        public void onResizeResult(PduPart part, boolean append) {
3099            if (part == null) {
3100                handleAddAttachmentError(WorkingMessage.UNKNOWN_ERROR, R.string.type_picture);
3101                return;
3102            }
3103
3104            Context context = ComposeMessageActivity.this;
3105            PduPersister persister = PduPersister.getPduPersister(context);
3106            int result;
3107
3108            Uri messageUri = mWorkingMessage.saveAsMms(true);
3109            if (messageUri == null) {
3110                result = WorkingMessage.UNKNOWN_ERROR;
3111            } else {
3112                try {
3113                    Uri dataUri = persister.persistPart(part,
3114                            ContentUris.parseId(messageUri), null);
3115                    result = mWorkingMessage.setAttachment(WorkingMessage.IMAGE, dataUri, append);
3116                    if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3117                        log("ResizeImageResultCallback: dataUri=" + dataUri);
3118                    }
3119                } catch (MmsException e) {
3120                    result = WorkingMessage.UNKNOWN_ERROR;
3121                }
3122            }
3123
3124            handleAddAttachmentError(result, R.string.type_picture);
3125        }
3126    };
3127
3128    private void handleAddAttachmentError(final int error, final int mediaTypeStringId) {
3129        if (error == WorkingMessage.OK) {
3130            return;
3131        }
3132        Log.d(TAG, "handleAddAttachmentError: " + error);
3133
3134        runOnUiThread(new Runnable() {
3135            @Override
3136            public void run() {
3137                Resources res = getResources();
3138                String mediaType = res.getString(mediaTypeStringId);
3139                String title, message;
3140
3141                switch(error) {
3142                case WorkingMessage.UNKNOWN_ERROR:
3143                    message = res.getString(R.string.failed_to_add_media, mediaType);
3144                    Toast.makeText(ComposeMessageActivity.this, message, Toast.LENGTH_SHORT).show();
3145                    return;
3146                case WorkingMessage.UNSUPPORTED_TYPE:
3147                    title = res.getString(R.string.unsupported_media_format, mediaType);
3148                    message = res.getString(R.string.select_different_media, mediaType);
3149                    break;
3150                case WorkingMessage.MESSAGE_SIZE_EXCEEDED:
3151                    title = res.getString(R.string.exceed_message_size_limitation, mediaType);
3152                    message = res.getString(R.string.failed_to_add_media, mediaType);
3153                    break;
3154                case WorkingMessage.IMAGE_TOO_LARGE:
3155                    title = res.getString(R.string.failed_to_resize_image);
3156                    message = res.getString(R.string.resize_image_error_information);
3157                    break;
3158                default:
3159                    throw new IllegalArgumentException("unknown error " + error);
3160                }
3161
3162                MessageUtils.showErrorDialog(ComposeMessageActivity.this, title, message);
3163            }
3164        });
3165    }
3166
3167    private void addImageAsync(final Uri uri, final boolean append) {
3168        getAsyncDialog().runAsync(new Runnable() {
3169            @Override
3170            public void run() {
3171                addImage(uri, append);
3172            }
3173        }, null, R.string.adding_attachments_title);
3174    }
3175
3176    private void addImage(Uri uri, boolean append) {
3177        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3178            log("addImage: append=" + append + ", uri=" + uri);
3179        }
3180
3181        int result = mWorkingMessage.setAttachment(WorkingMessage.IMAGE, uri, append);
3182
3183        if (result == WorkingMessage.IMAGE_TOO_LARGE ||
3184            result == WorkingMessage.MESSAGE_SIZE_EXCEEDED) {
3185            if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3186                log("resize image " + uri);
3187            }
3188            MessageUtils.resizeImageAsync(ComposeMessageActivity.this,
3189                    uri, mAttachmentEditorHandler, mResizeImageCallback, append);
3190            return;
3191        }
3192        handleAddAttachmentError(result, R.string.type_picture);
3193    }
3194
3195    private void addVideoAsync(final Uri uri, final boolean append) {
3196        getAsyncDialog().runAsync(new Runnable() {
3197            @Override
3198            public void run() {
3199                addVideo(uri, append);
3200            }
3201        }, null, R.string.adding_attachments_title);
3202    }
3203
3204    private void addVideo(Uri uri, boolean append) {
3205        if (uri != null) {
3206            int result = mWorkingMessage.setAttachment(WorkingMessage.VIDEO, uri, append);
3207            handleAddAttachmentError(result, R.string.type_video);
3208        }
3209    }
3210
3211    private void addAudio(Uri uri) {
3212        int result = mWorkingMessage.setAttachment(WorkingMessage.AUDIO, uri, false);
3213        handleAddAttachmentError(result, R.string.type_audio);
3214    }
3215
3216    AsyncDialog getAsyncDialog() {
3217        if (mAsyncDialog == null) {
3218            mAsyncDialog = new AsyncDialog(this);
3219        }
3220        return mAsyncDialog;
3221    }
3222
3223    private boolean handleForwardedMessage() {
3224        Intent intent = getIntent();
3225
3226        // If this is a forwarded message, it will have an Intent extra
3227        // indicating so.  If not, bail out.
3228        if (!mForwardMessageMode) {
3229            return false;
3230        }
3231
3232        Uri uri = intent.getParcelableExtra("msg_uri");
3233
3234        if (Log.isLoggable(LogTag.APP, Log.DEBUG)) {
3235            log("" + uri);
3236        }
3237
3238        if (uri != null) {
3239            mWorkingMessage = WorkingMessage.load(this, uri);
3240            mWorkingMessage.setSubject(intent.getStringExtra("subject"), false);
3241        } else {
3242            mWorkingMessage.setText(intent.getStringExtra("sms_body"));
3243        }
3244
3245        // let's clear the message thread for forwarded messages
3246        mMsgListAdapter.changeCursor(null);
3247
3248        return true;
3249    }
3250
3251    // Handle send actions, where we're told to send a picture(s) or text.
3252    private boolean handleSendIntent() {
3253        Intent intent = getIntent();
3254        Bundle extras = intent.getExtras();
3255        if (extras == null) {
3256            return false;
3257        }
3258
3259        final String mimeType = intent.getType();
3260        String action = intent.getAction();
3261        if (Intent.ACTION_SEND.equals(action)) {
3262            if (extras.containsKey(Intent.EXTRA_STREAM)) {
3263                final Uri uri = (Uri)extras.getParcelable(Intent.EXTRA_STREAM);
3264                getAsyncDialog().runAsync(new Runnable() {
3265                    @Override
3266                    public void run() {
3267                        addAttachment(mimeType, uri, false);
3268                    }
3269                }, null, R.string.adding_attachments_title);
3270                return true;
3271            } else if (extras.containsKey(Intent.EXTRA_TEXT)) {
3272                mWorkingMessage.setText(extras.getString(Intent.EXTRA_TEXT));
3273                return true;
3274            }
3275        } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) &&
3276                extras.containsKey(Intent.EXTRA_STREAM)) {
3277            SlideshowModel slideShow = mWorkingMessage.getSlideshow();
3278            final ArrayList<Parcelable> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
3279            int currentSlideCount = slideShow != null ? slideShow.size() : 0;
3280            int importCount = uris.size();
3281            if (importCount + currentSlideCount > SlideshowEditor.MAX_SLIDE_NUM) {
3282                importCount = Math.min(SlideshowEditor.MAX_SLIDE_NUM - currentSlideCount,
3283                        importCount);
3284                Toast.makeText(ComposeMessageActivity.this,
3285                        getString(R.string.too_many_attachments,
3286                                SlideshowEditor.MAX_SLIDE_NUM, importCount),
3287                                Toast.LENGTH_LONG).show();
3288            }
3289
3290            // Attach all the pictures/videos asynchronously off of the UI thread.
3291            // Show a progress dialog if adding all the slides hasn't finished
3292            // within half a second.
3293            final int numberToImport = importCount;
3294            getAsyncDialog().runAsync(new Runnable() {
3295                @Override
3296                public void run() {
3297                    for (int i = 0; i < numberToImport; i++) {
3298                        Parcelable uri = uris.get(i);
3299                        addAttachment(mimeType, (Uri) uri, true);
3300                    }
3301                }
3302            }, null, R.string.adding_attachments_title);
3303            return true;
3304        }
3305        return false;
3306    }
3307
3308    // mVideoUri will look like this: content://media/external/video/media
3309    private static final String mVideoUri = Video.Media.getContentUri("external").toString();
3310    // mImageUri will look like this: content://media/external/images/media
3311    private static final String mImageUri = Images.Media.getContentUri("external").toString();
3312
3313    private void addAttachment(String type, Uri uri, boolean append) {
3314        if (uri != null) {
3315            // When we're handling Intent.ACTION_SEND_MULTIPLE, the passed in items can be
3316            // videos, and/or images, and/or some other unknown types we don't handle. When
3317            // a single attachment is "shared" the type will specify an image or video. When
3318            // there are multiple types, the type passed in is "*/*". In that case, we've got
3319            // to look at the uri to figure out if it is an image or video.
3320            boolean wildcard = "*/*".equals(type);
3321            if (type.startsWith("image/") || (wildcard && uri.toString().startsWith(mImageUri))) {
3322                addImage(uri, append);
3323            } else if (type.startsWith("video/") ||
3324                    (wildcard && uri.toString().startsWith(mVideoUri))) {
3325                addVideo(uri, append);
3326            }
3327        }
3328    }
3329
3330    private String getResourcesString(int id, String mediaName) {
3331        Resources r = getResources();
3332        return r.getString(id, mediaName);
3333    }
3334
3335    /**
3336     * draw the compose view at the bottom of the screen.
3337     */
3338    private void drawBottomPanel() {
3339        // Reset the counter for text editor.
3340        resetCounter();
3341
3342        if (mWorkingMessage.hasSlideshow()) {
3343            mBottomPanel.setVisibility(View.GONE);
3344            mAttachmentEditor.requestFocus();
3345            return;
3346        }
3347
3348        if (LOCAL_LOGV) {
3349            Log.v(TAG, "CMA.drawBottomPanel");
3350        }
3351        mBottomPanel.setVisibility(View.VISIBLE);
3352
3353        CharSequence text = mWorkingMessage.getText();
3354
3355        // TextView.setTextKeepState() doesn't like null input.
3356        if (text != null && mIsSmsEnabled) {
3357            mTextEditor.setTextKeepState(text);
3358
3359            // Set the edit caret to the end of the text.
3360            mTextEditor.setSelection(mTextEditor.length());
3361        } else {
3362            mTextEditor.setText("");
3363        }
3364        onKeyboardStateChanged();
3365    }
3366
3367    private void hideBottomPanel() {
3368        if (LOCAL_LOGV) {
3369            Log.v(TAG, "CMA.hideBottomPanel");
3370        }
3371        mBottomPanel.setVisibility(View.INVISIBLE);
3372    }
3373
3374    private void drawTopPanel(boolean showSubjectEditor) {
3375        boolean showingAttachment = mAttachmentEditor.update(mWorkingMessage);
3376        mAttachmentEditorScrollView.setVisibility(showingAttachment ? View.VISIBLE : View.GONE);
3377        showSubjectEditor(showSubjectEditor || mWorkingMessage.hasSubject());
3378
3379        invalidateOptionsMenu();
3380        onKeyboardStateChanged();
3381    }
3382
3383    //==========================================================
3384    // Interface methods
3385    //==========================================================
3386
3387    @Override
3388    public void onClick(View v) {
3389        if ((v == mSendButtonSms || v == mSendButtonMms) && isPreparedForSending()) {
3390            confirmSendMessageIfNeeded();
3391        } else if ((v == mRecipientsPicker)) {
3392            launchMultiplePhonePicker();
3393        }
3394    }
3395
3396    private void launchMultiplePhonePicker() {
3397        Intent intent = new Intent(Intents.ACTION_GET_MULTIPLE_PHONES);
3398        intent.addCategory("android.intent.category.DEFAULT");
3399        intent.setType(Phone.CONTENT_TYPE);
3400        // We have to wait for the constructing complete.
3401        ContactList contacts = mRecipientsEditor.constructContactsFromInput(true);
3402        int urisCount = 0;
3403        Uri[] uris = new Uri[contacts.size()];
3404        urisCount = 0;
3405        for (Contact contact : contacts) {
3406            if (Contact.CONTACT_METHOD_TYPE_PHONE == contact.getContactMethodType()) {
3407                    uris[urisCount++] = contact.getPhoneUri();
3408            }
3409        }
3410        if (urisCount > 0) {
3411            intent.putExtra(Intents.EXTRA_PHONE_URIS, uris);
3412        }
3413        startActivityForResult(intent, REQUEST_CODE_PICK);
3414    }
3415
3416    @Override
3417    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
3418        if (event != null) {
3419            // if shift key is down, then we want to insert the '\n' char in the TextView;
3420            // otherwise, the default action is to send the message.
3421            if (!event.isShiftPressed() && event.getAction() == KeyEvent.ACTION_DOWN) {
3422                if (isPreparedForSending()) {
3423                    confirmSendMessageIfNeeded();
3424                }
3425                return true;
3426            }
3427            return false;
3428        }
3429
3430        if (isPreparedForSending()) {
3431            confirmSendMessageIfNeeded();
3432        }
3433        return true;
3434    }
3435
3436    private final TextWatcher mTextEditorWatcher = new TextWatcher() {
3437        @Override
3438        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3439        }
3440
3441        @Override
3442        public void onTextChanged(CharSequence s, int start, int before, int count) {
3443            // This is a workaround for bug 1609057.  Since onUserInteraction() is
3444            // not called when the user touches the soft keyboard, we pretend it was
3445            // called when textfields changes.  This should be removed when the bug
3446            // is fixed.
3447            onUserInteraction();
3448
3449            mWorkingMessage.setText(s);
3450
3451            updateSendButtonState();
3452
3453            updateCounter(s, start, before, count);
3454
3455            ensureCorrectButtonHeight();
3456        }
3457
3458        @Override
3459        public void afterTextChanged(Editable s) {
3460        }
3461    };
3462
3463    /**
3464     * Ensures that if the text edit box extends past two lines then the
3465     * button will be shifted up to allow enough space for the character
3466     * counter string to be placed beneath it.
3467     */
3468    private void ensureCorrectButtonHeight() {
3469        int currentTextLines = mTextEditor.getLineCount();
3470        if (currentTextLines <= 2) {
3471            mTextCounter.setVisibility(View.GONE);
3472        }
3473        else if (currentTextLines > 2 && mTextCounter.getVisibility() == View.GONE) {
3474            // Making the counter invisible ensures that it is used to correctly
3475            // calculate the position of the send button even if we choose not to
3476            // display the text.
3477            mTextCounter.setVisibility(View.INVISIBLE);
3478        }
3479    }
3480
3481    private final TextWatcher mSubjectEditorWatcher = new TextWatcher() {
3482        @Override
3483        public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
3484
3485        @Override
3486        public void onTextChanged(CharSequence s, int start, int before, int count) {
3487            mWorkingMessage.setSubject(s, true);
3488            updateSendButtonState();
3489        }
3490
3491        @Override
3492        public void afterTextChanged(Editable s) { }
3493    };
3494
3495    //==========================================================
3496    // Private methods
3497    //==========================================================
3498
3499    /**
3500     * Initialize all UI elements from resources.
3501     */
3502    private void initResourceRefs() {
3503        mMsgListView = (MessageListView) findViewById(R.id.history);
3504        mMsgListView.setDivider(null);      // no divider so we look like IM conversation.
3505
3506        // called to enable us to show some padding between the message list and the
3507        // input field but when the message list is scrolled that padding area is filled
3508        // in with message content
3509        mMsgListView.setClipToPadding(false);
3510
3511        mMsgListView.setOnSizeChangedListener(new OnSizeChangedListener() {
3512            public void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
3513                if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3514                    Log.v(TAG, "onSizeChanged: w=" + width + " h=" + height +
3515                            " oldw=" + oldWidth + " oldh=" + oldHeight);
3516                }
3517
3518                if (!mMessagesAndDraftLoaded && (oldHeight-height > SMOOTH_SCROLL_THRESHOLD)) {
3519                    // perform the delayed loading now, after keyboard opens
3520                    loadMessagesAndDraft(3);
3521                }
3522
3523
3524                // The message list view changed size, most likely because the keyboard
3525                // appeared or disappeared or the user typed/deleted chars in the message
3526                // box causing it to change its height when expanding/collapsing to hold more
3527                // lines of text.
3528                smoothScrollToEnd(false, height - oldHeight);
3529            }
3530        });
3531
3532        mBottomPanel = findViewById(R.id.bottom_panel);
3533        mTextEditor = (EditText) findViewById(R.id.embedded_text_editor);
3534        mTextEditor.setOnEditorActionListener(this);
3535        mTextEditor.addTextChangedListener(mTextEditorWatcher);
3536        mTextEditor.setFilters(new InputFilter[] {
3537                new LengthFilter(MmsConfig.getMaxTextLimit())});
3538        mTextCounter = (TextView) findViewById(R.id.text_counter);
3539        mSendButtonMms = (TextView) findViewById(R.id.send_button_mms);
3540        mSendButtonSms = (ImageButton) findViewById(R.id.send_button_sms);
3541        mSendButtonMms.setOnClickListener(this);
3542        mSendButtonSms.setOnClickListener(this);
3543        mTopPanel = findViewById(R.id.recipients_subject_linear);
3544        mTopPanel.setFocusable(false);
3545        mAttachmentEditor = (AttachmentEditor) findViewById(R.id.attachment_editor);
3546        mAttachmentEditor.setHandler(mAttachmentEditorHandler);
3547        mAttachmentEditorScrollView = findViewById(R.id.attachment_editor_scroll_view);
3548    }
3549
3550    private void confirmDeleteDialog(OnClickListener listener, boolean locked) {
3551        AlertDialog.Builder builder = new AlertDialog.Builder(this);
3552        builder.setCancelable(true);
3553        builder.setMessage(locked ? R.string.confirm_delete_locked_message :
3554                    R.string.confirm_delete_message);
3555        builder.setPositiveButton(R.string.delete, listener);
3556        builder.setNegativeButton(R.string.no, null);
3557        builder.show();
3558    }
3559
3560    void undeliveredMessageDialog(long date) {
3561        String body;
3562
3563        if (date >= 0) {
3564            body = getString(R.string.undelivered_msg_dialog_body,
3565                    MessageUtils.formatTimeStampString(this, date));
3566        } else {
3567            // FIXME: we can not get sms retry time.
3568            body = getString(R.string.undelivered_sms_dialog_body);
3569        }
3570
3571        Toast.makeText(this, body, Toast.LENGTH_LONG).show();
3572    }
3573
3574    private void startMsgListQuery() {
3575        startMsgListQuery(MESSAGE_LIST_QUERY_TOKEN);
3576    }
3577
3578    private void startMsgListQuery(int token) {
3579        if (mSendDiscreetMode) {
3580            return;
3581        }
3582        Uri conversationUri = mConversation.getUri();
3583
3584        if (conversationUri == null) {
3585            log("##### startMsgListQuery: conversationUri is null, bail!");
3586            return;
3587        }
3588
3589        long threadId = mConversation.getThreadId();
3590        if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3591            log("startMsgListQuery for " + conversationUri + ", threadId=" + threadId +
3592                    " token: " + token + " mConversation: " + mConversation);
3593        }
3594
3595        // Cancel any pending queries
3596        mBackgroundQueryHandler.cancelOperation(token);
3597        try {
3598            // Kick off the new query
3599            mBackgroundQueryHandler.startQuery(
3600                    token,
3601                    threadId /* cookie */,
3602                    conversationUri,
3603                    PROJECTION,
3604                    null, null, null);
3605        } catch (SQLiteException e) {
3606            SqliteWrapper.checkSQLiteException(this, e);
3607        }
3608    }
3609
3610    private void initMessageList() {
3611        if (mMsgListAdapter != null) {
3612            return;
3613        }
3614
3615        String highlightString = getIntent().getStringExtra("highlight");
3616        Pattern highlight = highlightString == null
3617            ? null
3618            : Pattern.compile("\\b" + Pattern.quote(highlightString), Pattern.CASE_INSENSITIVE);
3619
3620        // Initialize the list adapter with a null cursor.
3621        mMsgListAdapter = new MessageListAdapter(this, null, mMsgListView, true, highlight);
3622        mMsgListAdapter.setOnDataSetChangedListener(mDataSetChangedListener);
3623        mMsgListAdapter.setMsgListItemHandler(mMessageListItemHandler);
3624        mMsgListView.setAdapter(mMsgListAdapter);
3625        mMsgListView.setItemsCanFocus(false);
3626        mMsgListView.setVisibility(mSendDiscreetMode ? View.INVISIBLE : View.VISIBLE);
3627        mMsgListView.setOnCreateContextMenuListener(mMsgListMenuCreateListener);
3628        mMsgListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
3629            @Override
3630            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
3631                if (view != null) {
3632                    ((MessageListItem) view).onMessageListItemClick();
3633                }
3634            }
3635        });
3636    }
3637
3638    /**
3639     * Load the draft
3640     *
3641     * If mWorkingMessage has content in memory that's worth saving, return false.
3642     * Otherwise, call the async operation to load draft and return true.
3643     */
3644    private boolean loadDraft() {
3645        if (mWorkingMessage.isWorthSaving()) {
3646            Log.w(TAG, "CMA.loadDraft: called with non-empty working message, bail");
3647            return false;
3648        }
3649
3650        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3651            log("CMA.loadDraft");
3652        }
3653
3654        mWorkingMessage = WorkingMessage.loadDraft(this, mConversation,
3655                new Runnable() {
3656                    @Override
3657                    public void run() {
3658                        drawTopPanel(false);
3659                        drawBottomPanel();
3660                        updateSendButtonState();
3661                    }
3662                });
3663
3664        // WorkingMessage.loadDraft() can return a new WorkingMessage object that doesn't
3665        // have its conversation set. Make sure it is set.
3666        mWorkingMessage.setConversation(mConversation);
3667
3668        return true;
3669    }
3670
3671    private void saveDraft(boolean isStopping) {
3672        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3673            LogTag.debug("saveDraft");
3674        }
3675        // TODO: Do something better here.  Maybe make discard() legal
3676        // to call twice and make isEmpty() return true if discarded
3677        // so it is caught in the clause above this one?
3678        if (mWorkingMessage.isDiscarded()) {
3679            return;
3680        }
3681
3682        if (!mWaitingForSubActivity &&
3683                !mWorkingMessage.isWorthSaving() &&
3684                (!isRecipientsEditorVisible() || recipientCount() == 0)) {
3685            if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3686                log("not worth saving, discard WorkingMessage and bail");
3687            }
3688            mWorkingMessage.discard();
3689            return;
3690        }
3691
3692        mWorkingMessage.saveDraft(isStopping);
3693
3694        if (mToastForDraftSave) {
3695            Toast.makeText(this, R.string.message_saved_as_draft,
3696                    Toast.LENGTH_SHORT).show();
3697        }
3698    }
3699
3700    private boolean isPreparedForSending() {
3701        int recipientCount = recipientCount();
3702
3703        return recipientCount > 0 &&
3704                recipientCount <= MmsConfig.getRecipientLimit() &&
3705                mIsSmsEnabled &&
3706                (mWorkingMessage.hasAttachment() || mWorkingMessage.hasText() ||
3707                    mWorkingMessage.hasSubject());
3708    }
3709
3710    private int recipientCount() {
3711        int recipientCount;
3712
3713        // To avoid creating a bunch of invalid Contacts when the recipients
3714        // editor is in flux, we keep the recipients list empty.  So if the
3715        // recipients editor is showing, see if there is anything in it rather
3716        // than consulting the empty recipient list.
3717        if (isRecipientsEditorVisible()) {
3718            recipientCount = mRecipientsEditor.getRecipientCount();
3719        } else {
3720            recipientCount = getRecipients().size();
3721        }
3722        return recipientCount;
3723    }
3724
3725    private void sendMessage(boolean bCheckEcmMode) {
3726        if (bCheckEcmMode) {
3727            // TODO: expose this in telephony layer for SDK build
3728            String inEcm = SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE);
3729            if (Boolean.parseBoolean(inEcm)) {
3730                try {
3731                    startActivityForResult(
3732                            new Intent(TelephonyIntents.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS, null),
3733                            REQUEST_CODE_ECM_EXIT_DIALOG);
3734                    return;
3735                } catch (ActivityNotFoundException e) {
3736                    // continue to send message
3737                    Log.e(TAG, "Cannot find EmergencyCallbackModeExitDialog", e);
3738                }
3739            }
3740        }
3741
3742        if (!mSendingMessage) {
3743            if (LogTag.SEVERE_WARNING) {
3744                String sendingRecipients = mConversation.getRecipients().serialize();
3745                if (!sendingRecipients.equals(mDebugRecipients)) {
3746                    String workingRecipients = mWorkingMessage.getWorkingRecipients();
3747                    if (!mDebugRecipients.equals(workingRecipients)) {
3748                        LogTag.warnPossibleRecipientMismatch("ComposeMessageActivity.sendMessage" +
3749                                " recipients in window: \"" +
3750                                mDebugRecipients + "\" differ from recipients from conv: \"" +
3751                                sendingRecipients + "\" and working recipients: " +
3752                                workingRecipients, this);
3753                    }
3754                }
3755                sanityCheckConversation();
3756            }
3757
3758            // send can change the recipients. Make sure we remove the listeners first and then add
3759            // them back once the recipient list has settled.
3760            removeRecipientsListeners();
3761
3762            mWorkingMessage.send(mDebugRecipients);
3763
3764            mSentMessage = true;
3765            mSendingMessage = true;
3766            addRecipientsListeners();
3767
3768            mScrollOnSend = true;   // in the next onQueryComplete, scroll the list to the end.
3769        }
3770        // But bail out if we are supposed to exit after the message is sent.
3771        if (mSendDiscreetMode) {
3772            finish();
3773        }
3774    }
3775
3776    private void resetMessage() {
3777        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3778            log("resetMessage");
3779        }
3780
3781        // Make the attachment editor hide its view.
3782        mAttachmentEditor.hideView();
3783        mAttachmentEditorScrollView.setVisibility(View.GONE);
3784
3785        // Hide the subject editor.
3786        showSubjectEditor(false);
3787
3788        // Focus to the text editor.
3789        mTextEditor.requestFocus();
3790
3791        // We have to remove the text change listener while the text editor gets cleared and
3792        // we subsequently turn the message back into SMS. When the listener is listening while
3793        // doing the clearing, it's fighting to update its counts and itself try and turn
3794        // the message one way or the other.
3795        mTextEditor.removeTextChangedListener(mTextEditorWatcher);
3796
3797        // Clear the text box.
3798        TextKeyListener.clear(mTextEditor.getText());
3799
3800        mWorkingMessage.clearConversation(mConversation, false);
3801        mWorkingMessage = WorkingMessage.createEmpty(this);
3802        mWorkingMessage.setConversation(mConversation);
3803
3804        hideRecipientEditor();
3805        drawBottomPanel();
3806
3807        // "Or not", in this case.
3808        updateSendButtonState();
3809
3810        // Our changes are done. Let the listener respond to text changes once again.
3811        mTextEditor.addTextChangedListener(mTextEditorWatcher);
3812
3813        // Close the soft on-screen keyboard if we're in landscape mode so the user can see the
3814        // conversation.
3815        if (mIsLandscape) {
3816            hideKeyboard();
3817        }
3818
3819        mLastRecipientCount = 0;
3820        mSendingMessage = false;
3821        invalidateOptionsMenu();
3822   }
3823
3824    private void hideKeyboard() {
3825        InputMethodManager inputMethodManager =
3826            (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
3827        inputMethodManager.hideSoftInputFromWindow(mTextEditor.getWindowToken(), 0);
3828    }
3829
3830    private void updateSendButtonState() {
3831        boolean enable = false;
3832        if (isPreparedForSending()) {
3833            // When the type of attachment is slideshow, we should
3834            // also hide the 'Send' button since the slideshow view
3835            // already has a 'Send' button embedded.
3836            if (!mWorkingMessage.hasSlideshow()) {
3837                enable = true;
3838            } else {
3839                mAttachmentEditor.setCanSend(true);
3840            }
3841        } else if (null != mAttachmentEditor){
3842            mAttachmentEditor.setCanSend(false);
3843        }
3844
3845        boolean requiresMms = mWorkingMessage.requiresMms();
3846        View sendButton = showSmsOrMmsSendButton(requiresMms);
3847        sendButton.setEnabled(enable);
3848        sendButton.setFocusable(enable);
3849    }
3850
3851    private long getMessageDate(Uri uri) {
3852        if (uri != null) {
3853            Cursor cursor = SqliteWrapper.query(this, mContentResolver,
3854                    uri, new String[] { Mms.DATE }, null, null, null);
3855            if (cursor != null) {
3856                try {
3857                    if ((cursor.getCount() == 1) && cursor.moveToFirst()) {
3858                        return cursor.getLong(0) * 1000L;
3859                    }
3860                } finally {
3861                    cursor.close();
3862                }
3863            }
3864        }
3865        return NO_DATE_FOR_DIALOG;
3866    }
3867
3868    private void initActivityState(Bundle bundle) {
3869        Intent intent = getIntent();
3870        if (bundle != null) {
3871            setIntent(getIntent().setAction(Intent.ACTION_VIEW));
3872            String recipients = bundle.getString(RECIPIENTS);
3873            if (LogTag.VERBOSE) log("get mConversation by recipients " + recipients);
3874            mConversation = Conversation.get(this,
3875                    ContactList.getByNumbers(recipients,
3876                            false /* don't block */, true /* replace number */), false);
3877            addRecipientsListeners();
3878            mSendDiscreetMode = bundle.getBoolean(KEY_EXIT_ON_SENT, false);
3879            mForwardMessageMode = bundle.getBoolean(KEY_FORWARDED_MESSAGE, false);
3880
3881            if (mSendDiscreetMode) {
3882                mMsgListView.setVisibility(View.INVISIBLE);
3883            }
3884            mWorkingMessage.readStateFromBundle(bundle);
3885
3886            return;
3887        }
3888
3889        // If we have been passed a thread_id, use that to find our conversation.
3890        long threadId = intent.getLongExtra(THREAD_ID, 0);
3891        if (threadId > 0) {
3892            if (LogTag.VERBOSE) log("get mConversation by threadId " + threadId);
3893            mConversation = Conversation.get(this, threadId, false);
3894        } else {
3895            Uri intentData = intent.getData();
3896            if (intentData != null) {
3897                // try to get a conversation based on the data URI passed to our intent.
3898                if (LogTag.VERBOSE) log("get mConversation by intentData " + intentData);
3899                mConversation = Conversation.get(this, intentData, false);
3900                mWorkingMessage.setText(getBody(intentData));
3901            } else {
3902                // special intent extra parameter to specify the address
3903                String address = intent.getStringExtra("address");
3904                if (!TextUtils.isEmpty(address)) {
3905                    if (LogTag.VERBOSE) log("get mConversation by address " + address);
3906                    mConversation = Conversation.get(this, ContactList.getByNumbers(address,
3907                            false /* don't block */, true /* replace number */), false);
3908                } else {
3909                    if (LogTag.VERBOSE) log("create new conversation");
3910                    mConversation = Conversation.createNew(this);
3911                }
3912            }
3913        }
3914        addRecipientsListeners();
3915        updateThreadIdIfRunning();
3916
3917        mSendDiscreetMode = intent.getBooleanExtra(KEY_EXIT_ON_SENT, false);
3918        mForwardMessageMode = intent.getBooleanExtra(KEY_FORWARDED_MESSAGE, false);
3919        if (mSendDiscreetMode) {
3920            mMsgListView.setVisibility(View.INVISIBLE);
3921        }
3922        if (intent.hasExtra("sms_body")) {
3923            mWorkingMessage.setText(intent.getStringExtra("sms_body"));
3924        }
3925        mWorkingMessage.setSubject(intent.getStringExtra("subject"), false);
3926    }
3927
3928    private void initFocus() {
3929        if (!mIsKeyboardOpen) {
3930            return;
3931        }
3932
3933        // If the recipients editor is visible, there is nothing in it,
3934        // and the text editor is not already focused, focus the
3935        // recipients editor.
3936        if (isRecipientsEditorVisible()
3937                && TextUtils.isEmpty(mRecipientsEditor.getText())
3938                && !mTextEditor.isFocused()) {
3939            mRecipientsEditor.requestFocus();
3940            return;
3941        }
3942
3943        // If we decided not to focus the recipients editor, focus the text editor.
3944        mTextEditor.requestFocus();
3945    }
3946
3947    private final MessageListAdapter.OnDataSetChangedListener
3948                    mDataSetChangedListener = new MessageListAdapter.OnDataSetChangedListener() {
3949        @Override
3950        public void onDataSetChanged(MessageListAdapter adapter) {
3951        }
3952
3953        @Override
3954        public void onContentChanged(MessageListAdapter adapter) {
3955            startMsgListQuery();
3956        }
3957    };
3958
3959    /**
3960     * smoothScrollToEnd will scroll the message list to the bottom if the list is already near
3961     * the bottom. Typically this is called to smooth scroll a newly received message into view.
3962     * It's also called when sending to scroll the list to the bottom, regardless of where it is,
3963     * so the user can see the just sent message. This function is also called when the message
3964     * list view changes size because the keyboard state changed or the compose message field grew.
3965     *
3966     * @param force always scroll to the bottom regardless of current list position
3967     * @param listSizeChange the amount the message list view size has vertically changed
3968     */
3969    private void smoothScrollToEnd(boolean force, int listSizeChange) {
3970        int lastItemVisible = mMsgListView.getLastVisiblePosition();
3971        int lastItemInList = mMsgListAdapter.getCount() - 1;
3972        if (lastItemVisible < 0 || lastItemInList < 0) {
3973            if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3974                Log.v(TAG, "smoothScrollToEnd: lastItemVisible=" + lastItemVisible +
3975                        ", lastItemInList=" + lastItemInList +
3976                        ", mMsgListView not ready");
3977            }
3978            return;
3979        }
3980
3981        View lastChildVisible =
3982                mMsgListView.getChildAt(lastItemVisible - mMsgListView.getFirstVisiblePosition());
3983        int lastVisibleItemBottom = 0;
3984        int lastVisibleItemHeight = 0;
3985        if (lastChildVisible != null) {
3986            lastVisibleItemBottom = lastChildVisible.getBottom();
3987            lastVisibleItemHeight = lastChildVisible.getHeight();
3988        }
3989
3990        if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3991            Log.v(TAG, "smoothScrollToEnd newPosition: " + lastItemInList +
3992                    " mLastSmoothScrollPosition: " + mLastSmoothScrollPosition +
3993                    " first: " + mMsgListView.getFirstVisiblePosition() +
3994                    " lastItemVisible: " + lastItemVisible +
3995                    " lastVisibleItemBottom: " + lastVisibleItemBottom +
3996                    " lastVisibleItemBottom + listSizeChange: " +
3997                    (lastVisibleItemBottom + listSizeChange) +
3998                    " mMsgListView.getHeight() - mMsgListView.getPaddingBottom(): " +
3999                    (mMsgListView.getHeight() - mMsgListView.getPaddingBottom()) +
4000                    " listSizeChange: " + listSizeChange);
4001        }
4002        // Only scroll if the list if we're responding to a newly sent message (force == true) or
4003        // the list is already scrolled to the end. This code also has to handle the case where
4004        // the listview has changed size (from the keyboard coming up or down or the message entry
4005        // field growing/shrinking) and it uses that grow/shrink factor in listSizeChange to
4006        // compute whether the list was at the end before the resize took place.
4007        // For example, when the keyboard comes up, listSizeChange will be negative, something
4008        // like -524. The lastChild listitem's bottom value will be the old value before the
4009        // keyboard became visible but the size of the list will have changed. The test below
4010        // add listSizeChange to bottom to figure out if the old position was already scrolled
4011        // to the bottom. We also scroll the list if the last item is taller than the size of the
4012        // list. This happens when the keyboard is up and the last item is an mms with an
4013        // attachment thumbnail, such as picture. In this situation, we want to scroll the list so
4014        // the bottom of the thumbnail is visible and the top of the item is scroll off the screen.
4015        int listHeight = mMsgListView.getHeight();
4016        boolean lastItemTooTall = lastVisibleItemHeight > listHeight;
4017        boolean willScroll = force ||
4018                ((listSizeChange != 0 || lastItemInList != mLastSmoothScrollPosition) &&
4019                lastVisibleItemBottom + listSizeChange <=
4020                    listHeight - mMsgListView.getPaddingBottom());
4021        if (willScroll || (lastItemTooTall && lastItemInList == lastItemVisible)) {
4022            if (Math.abs(listSizeChange) > SMOOTH_SCROLL_THRESHOLD) {
4023                // When the keyboard comes up, the window manager initiates a cross fade
4024                // animation that conflicts with smooth scroll. Handle that case by jumping the
4025                // list directly to the end.
4026                if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
4027                    Log.v(TAG, "keyboard state changed. setSelection=" + lastItemInList);
4028                }
4029                if (lastItemTooTall) {
4030                    // If the height of the last item is taller than the whole height of the list,
4031                    // we need to scroll that item so that its top is negative or above the top of
4032                    // the list. That way, the bottom of the last item will be exposed above the
4033                    // keyboard.
4034                    mMsgListView.setSelectionFromTop(lastItemInList,
4035                            listHeight - lastVisibleItemHeight);
4036                } else {
4037                    mMsgListView.setSelection(lastItemInList);
4038                }
4039            } else if (lastItemInList - lastItemVisible > MAX_ITEMS_TO_INVOKE_SCROLL_SHORTCUT) {
4040                if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
4041                    Log.v(TAG, "too many to scroll, setSelection=" + lastItemInList);
4042                }
4043                mMsgListView.setSelection(lastItemInList);
4044            } else {
4045                if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
4046                    Log.v(TAG, "smooth scroll to " + lastItemInList);
4047                }
4048                if (lastItemTooTall) {
4049                    // If the height of the last item is taller than the whole height of the list,
4050                    // we need to scroll that item so that its top is negative or above the top of
4051                    // the list. That way, the bottom of the last item will be exposed above the
4052                    // keyboard. We should use smoothScrollToPositionFromTop here, but it doesn't
4053                    // seem to work -- the list ends up scrolling to a random position.
4054                    mMsgListView.setSelectionFromTop(lastItemInList,
4055                            listHeight - lastVisibleItemHeight);
4056                } else {
4057                    mMsgListView.smoothScrollToPosition(lastItemInList);
4058                }
4059                mLastSmoothScrollPosition = lastItemInList;
4060            }
4061        }
4062    }
4063
4064    private final class BackgroundQueryHandler extends ConversationQueryHandler {
4065        public BackgroundQueryHandler(ContentResolver contentResolver) {
4066            super(contentResolver);
4067        }
4068
4069        @Override
4070        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
4071            switch(token) {
4072                case MESSAGE_LIST_QUERY_TOKEN:
4073                    mConversation.blockMarkAsRead(false);
4074
4075                    // check consistency between the query result and 'mConversation'
4076                    long tid = (Long) cookie;
4077
4078                    if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
4079                        log("##### onQueryComplete: msg history result for threadId " + tid);
4080                    }
4081                    if (tid != mConversation.getThreadId()) {
4082                        log("onQueryComplete: msg history query result is for threadId " +
4083                                tid + ", but mConversation has threadId " +
4084                                mConversation.getThreadId() + " starting a new query");
4085                        if (cursor != null) {
4086                            cursor.close();
4087                        }
4088                        startMsgListQuery();
4089                        return;
4090                    }
4091
4092                    // check consistency b/t mConversation & mWorkingMessage.mConversation
4093                    ComposeMessageActivity.this.sanityCheckConversation();
4094
4095                    int newSelectionPos = -1;
4096                    long targetMsgId = getIntent().getLongExtra("select_id", -1);
4097                    if (targetMsgId != -1) {
4098                        if (cursor != null) {
4099                            cursor.moveToPosition(-1);
4100                            while (cursor.moveToNext()) {
4101                                long msgId = cursor.getLong(COLUMN_ID);
4102                                if (msgId == targetMsgId) {
4103                                    newSelectionPos = cursor.getPosition();
4104                                    break;
4105                                }
4106                            }
4107                        }
4108                    } else if (mSavedScrollPosition != -1) {
4109                        // mSavedScrollPosition is set when this activity pauses. If equals maxint,
4110                        // it means the message list was scrolled to the end. Meanwhile, messages
4111                        // could have been received. When the activity resumes and we were
4112                        // previously scrolled to the end, jump the list so any new messages are
4113                        // visible.
4114                        if (mSavedScrollPosition == Integer.MAX_VALUE) {
4115                            int cnt = mMsgListAdapter.getCount();
4116                            if (cnt > 0) {
4117                                // Have to wait until the adapter is loaded before jumping to
4118                                // the end.
4119                                newSelectionPos = cnt - 1;
4120                                mSavedScrollPosition = -1;
4121                            }
4122                        } else {
4123                            // remember the saved scroll position before the activity is paused.
4124                            // reset it after the message list query is done
4125                            newSelectionPos = mSavedScrollPosition;
4126                            mSavedScrollPosition = -1;
4127                        }
4128                    }
4129
4130                    mMsgListAdapter.changeCursor(cursor);
4131
4132                    if (newSelectionPos != -1) {
4133                        mMsgListView.setSelection(newSelectionPos);     // jump the list to the pos
4134                    } else {
4135                        int count = mMsgListAdapter.getCount();
4136                        long lastMsgId = 0;
4137                        if (cursor != null && count > 0) {
4138                            cursor.moveToLast();
4139                            lastMsgId = cursor.getLong(COLUMN_ID);
4140                        }
4141                        // mScrollOnSend is set when we send a message. We always want to scroll
4142                        // the message list to the end when we send a message, but have to wait
4143                        // until the DB has changed. We also want to scroll the list when a
4144                        // new message has arrived.
4145                        smoothScrollToEnd(mScrollOnSend || lastMsgId != mLastMessageId, 0);
4146                        mLastMessageId = lastMsgId;
4147                        mScrollOnSend = false;
4148                    }
4149                    // Adjust the conversation's message count to match reality. The
4150                    // conversation's message count is eventually used in
4151                    // WorkingMessage.clearConversation to determine whether to delete
4152                    // the conversation or not.
4153                    mConversation.setMessageCount(mMsgListAdapter.getCount());
4154
4155                    // Once we have completed the query for the message history, if
4156                    // there is nothing in the cursor and we are not composing a new
4157                    // message, we must be editing a draft in a new conversation (unless
4158                    // mSentMessage is true).
4159                    // Show the recipients editor to give the user a chance to add
4160                    // more people before the conversation begins.
4161                    if (cursor != null && cursor.getCount() == 0
4162                            && !isRecipientsEditorVisible() && !mSentMessage) {
4163                        initRecipientsEditor();
4164                    }
4165
4166                    // FIXME: freshing layout changes the focused view to an unexpected
4167                    // one, set it back to TextEditor forcely.
4168                    mTextEditor.requestFocus();
4169
4170                    invalidateOptionsMenu();    // some menu items depend on the adapter's count
4171                    return;
4172
4173                case ConversationList.HAVE_LOCKED_MESSAGES_TOKEN:
4174                    if (ComposeMessageActivity.this.isFinishing()) {
4175                        Log.w(TAG, "ComposeMessageActivity is finished, do nothing ");
4176                        if (cursor != null) {
4177                            cursor.close();
4178                        }
4179                        return ;
4180                    }
4181                    @SuppressWarnings("unchecked")
4182                    ArrayList<Long> threadIds = (ArrayList<Long>)cookie;
4183                    ConversationList.confirmDeleteThreadDialog(
4184                            new ConversationList.DeleteThreadListener(threadIds,
4185                                mBackgroundQueryHandler, ComposeMessageActivity.this),
4186                            threadIds,
4187                            cursor != null && cursor.getCount() > 0,
4188                            ComposeMessageActivity.this);
4189                    if (cursor != null) {
4190                        cursor.close();
4191                    }
4192                    break;
4193
4194                case MESSAGE_LIST_QUERY_AFTER_DELETE_TOKEN:
4195                    // check consistency between the query result and 'mConversation'
4196                    tid = (Long) cookie;
4197
4198                    if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
4199                        log("##### onQueryComplete (after delete): msg history result for threadId "
4200                                + tid);
4201                    }
4202                    if (cursor == null) {
4203                        return;
4204                    }
4205                    if (tid > 0 && cursor.getCount() == 0) {
4206                        // We just deleted the last message and the thread will get deleted
4207                        // by a trigger in the database. Clear the threadId so next time we
4208                        // need the threadId a new thread will get created.
4209                        log("##### MESSAGE_LIST_QUERY_AFTER_DELETE_TOKEN clearing thread id: "
4210                                + tid);
4211                        Conversation conv = Conversation.get(ComposeMessageActivity.this, tid,
4212                                false);
4213                        if (conv != null) {
4214                            conv.clearThreadId();
4215                            conv.setDraftState(false);
4216                        }
4217                        // The last message in this converation was just deleted. Send the user
4218                        // to the conversation list.
4219                        exitComposeMessageActivity(new Runnable() {
4220                            @Override
4221                            public void run() {
4222                                goToConversationList();
4223                            }
4224                        });
4225                    }
4226                    cursor.close();
4227            }
4228        }
4229
4230        @Override
4231        protected void onDeleteComplete(int token, Object cookie, int result) {
4232            super.onDeleteComplete(token, cookie, result);
4233            switch(token) {
4234                case ConversationList.DELETE_CONVERSATION_TOKEN:
4235                    mConversation.setMessageCount(0);
4236                    // fall through
4237                case DELETE_MESSAGE_TOKEN:
4238                    if (cookie instanceof Boolean && ((Boolean)cookie).booleanValue()) {
4239                        // If we just deleted the last message, reset the saved id.
4240                        mLastMessageId = 0;
4241                    }
4242                    // Update the notification for new messages since they
4243                    // may be deleted.
4244                    MessagingNotification.nonBlockingUpdateNewMessageIndicator(
4245                            ComposeMessageActivity.this, MessagingNotification.THREAD_NONE, false);
4246                    // Update the notification for failed messages since they
4247                    // may be deleted.
4248                    updateSendFailedNotification();
4249                    break;
4250            }
4251            // If we're deleting the whole conversation, throw away
4252            // our current working message and bail.
4253            if (token == ConversationList.DELETE_CONVERSATION_TOKEN) {
4254                ContactList recipients = mConversation.getRecipients();
4255                mWorkingMessage.discard();
4256
4257                // Remove any recipients referenced by this single thread from the
4258                // contacts cache. It's possible for two or more threads to reference
4259                // the same contact. That's ok if we remove it. We'll recreate that contact
4260                // when we init all Conversations below.
4261                if (recipients != null) {
4262                    for (Contact contact : recipients) {
4263                        contact.removeFromCache();
4264                    }
4265                }
4266
4267                // Make sure the conversation cache reflects the threads in the DB.
4268                Conversation.init(ComposeMessageActivity.this);
4269                finish();
4270            } else if (token == DELETE_MESSAGE_TOKEN) {
4271                // Check to see if we just deleted the last message
4272                startMsgListQuery(MESSAGE_LIST_QUERY_AFTER_DELETE_TOKEN);
4273            }
4274
4275            MmsWidgetProvider.notifyDatasetChanged(getApplicationContext());
4276        }
4277    }
4278
4279    @Override
4280    public void onUpdate(final Contact updated) {
4281        // Using an existing handler for the post, rather than conjuring up a new one.
4282        mMessageListItemHandler.post(new Runnable() {
4283            @Override
4284            public void run() {
4285                ContactList recipients = isRecipientsEditorVisible() ?
4286                        mRecipientsEditor.constructContactsFromInput(false) : getRecipients();
4287                if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
4288                    log("[CMA] onUpdate contact updated: " + updated);
4289                    log("[CMA] onUpdate recipients: " + recipients);
4290                }
4291                updateTitle(recipients);
4292
4293                // The contact information for one (or more) of the recipients has changed.
4294                // Rebuild the message list so each MessageItem will get the last contact info.
4295                ComposeMessageActivity.this.mMsgListAdapter.notifyDataSetChanged();
4296
4297                // Don't do this anymore. When we're showing chips, we don't want to switch from
4298                // chips to text.
4299//                if (mRecipientsEditor != null) {
4300//                    mRecipientsEditor.populate(recipients);
4301//                }
4302            }
4303        });
4304    }
4305
4306    private void addRecipientsListeners() {
4307        Contact.addListener(this);
4308    }
4309
4310    private void removeRecipientsListeners() {
4311        Contact.removeListener(this);
4312    }
4313
4314    public static Intent createIntent(Context context, long threadId) {
4315        Intent intent = new Intent(context, ComposeMessageActivity.class);
4316
4317        if (threadId > 0) {
4318            intent.setData(Conversation.getUri(threadId));
4319        }
4320
4321        return intent;
4322    }
4323
4324    private String getBody(Uri uri) {
4325        if (uri == null) {
4326            return null;
4327        }
4328        String urlStr = uri.getSchemeSpecificPart();
4329        if (!urlStr.contains("?")) {
4330            return null;
4331        }
4332        urlStr = urlStr.substring(urlStr.indexOf('?') + 1);
4333        String[] params = urlStr.split("&");
4334        for (String p : params) {
4335            if (p.startsWith("body=")) {
4336                try {
4337                    return URLDecoder.decode(p.substring(5), "UTF-8");
4338                } catch (UnsupportedEncodingException e) { }
4339            }
4340        }
4341        return null;
4342    }
4343
4344    private void updateThreadIdIfRunning() {
4345        if (mIsRunning && mConversation != null) {
4346            if (DEBUG) {
4347                Log.v(TAG, "updateThreadIdIfRunning: threadId: " +
4348                        mConversation.getThreadId());
4349            }
4350            MessagingNotification.setCurrentlyDisplayedThreadId(mConversation.getThreadId());
4351        } else {
4352            if (DEBUG) {
4353                Log.v(TAG, "updateThreadIdIfRunning: mIsRunning: " + mIsRunning +
4354                        " mConversation: " + mConversation);
4355            }
4356        }
4357        // If we're not running, but resume later, the current thread ID will be set in onResume()
4358    }
4359}
4360