ComposeMessageActivity.java revision c7c68dba4f3440f234f65eef579f9aaa82682f8c
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 = "Mms/compose";
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        super.onCreate(savedInstanceState);
1867
1868        resetConfiguration(getResources().getConfiguration());
1869
1870        setContentView(R.layout.compose_message_activity);
1871        setProgressBarVisibility(false);
1872
1873        // Initialize members for UI elements.
1874        initResourceRefs();
1875
1876        mContentResolver = getContentResolver();
1877        mBackgroundQueryHandler = new BackgroundQueryHandler(mContentResolver);
1878
1879        initialize(savedInstanceState, 0);
1880
1881        if (TRACE) {
1882            android.os.Debug.startMethodTracing("compose");
1883        }
1884    }
1885
1886    private void showSubjectEditor(boolean show) {
1887        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
1888            log("" + show);
1889        }
1890
1891        if (mSubjectTextEditor == null) {
1892            // Don't bother to initialize the subject editor if
1893            // we're just going to hide it.
1894            if (show == false) {
1895                return;
1896            }
1897            mSubjectTextEditor = (EditText)findViewById(R.id.subject);
1898            mSubjectTextEditor.setFilters(new InputFilter[] {
1899                    new LengthFilter(MmsConfig.getMaxSubjectLength())});
1900        }
1901
1902        mSubjectTextEditor.setOnKeyListener(show ? mSubjectKeyListener : null);
1903
1904        if (show) {
1905            mSubjectTextEditor.addTextChangedListener(mSubjectEditorWatcher);
1906        } else {
1907            mSubjectTextEditor.removeTextChangedListener(mSubjectEditorWatcher);
1908        }
1909
1910        mSubjectTextEditor.setText(mWorkingMessage.getSubject());
1911        mSubjectTextEditor.setVisibility(show ? View.VISIBLE : View.GONE);
1912        hideOrShowTopPanel();
1913    }
1914
1915    private void hideOrShowTopPanel() {
1916        boolean anySubViewsVisible = (isSubjectEditorVisible() || isRecipientsEditorVisible());
1917        mTopPanel.setVisibility(anySubViewsVisible ? View.VISIBLE : View.GONE);
1918    }
1919
1920    public void initialize(Bundle savedInstanceState, long originalThreadId) {
1921        // Create a new empty working message.
1922        mWorkingMessage = WorkingMessage.createEmpty(this);
1923
1924        // Read parameters or previously saved state of this activity. This will load a new
1925        // mConversation
1926        initActivityState(savedInstanceState);
1927
1928        if (LogTag.SEVERE_WARNING && originalThreadId != 0 &&
1929                originalThreadId == mConversation.getThreadId()) {
1930            LogTag.warnPossibleRecipientMismatch("ComposeMessageActivity.initialize: " +
1931                    " threadId didn't change from: " + originalThreadId, this);
1932        }
1933
1934        log("savedInstanceState = " + savedInstanceState +
1935            " intent = " + getIntent() +
1936            " mConversation = " + mConversation);
1937
1938        if (cancelFailedToDeliverNotification(getIntent(), this)) {
1939            // Show a pop-up dialog to inform user the message was
1940            // failed to deliver.
1941            undeliveredMessageDialog(getMessageDate(null));
1942        }
1943        cancelFailedDownloadNotification(getIntent(), this);
1944
1945        // Set up the message history ListAdapter
1946        initMessageList();
1947
1948        mShouldLoadDraft = true;
1949
1950        // Load the draft for this thread, if we aren't already handling
1951        // existing data, such as a shared picture or forwarded message.
1952        boolean isForwardedMessage = false;
1953        // We don't attempt to handle the Intent.ACTION_SEND when saveInstanceState is non-null.
1954        // saveInstanceState is non-null when this activity is killed. In that case, we already
1955        // handled the attachment or the send, so we don't try and parse the intent again.
1956        if (savedInstanceState == null && (handleSendIntent() || handleForwardedMessage())) {
1957            mShouldLoadDraft = false;
1958        }
1959
1960        // Let the working message know what conversation it belongs to
1961        mWorkingMessage.setConversation(mConversation);
1962
1963        // Show the recipients editor if we don't have a valid thread. Hide it otherwise.
1964        if (mConversation.getThreadId() <= 0) {
1965            // Hide the recipients editor so the call to initRecipientsEditor won't get
1966            // short-circuited.
1967            hideRecipientEditor();
1968            initRecipientsEditor();
1969        } else {
1970            hideRecipientEditor();
1971        }
1972
1973        updateSendButtonState();
1974
1975        drawTopPanel(false);
1976        if (!mShouldLoadDraft) {
1977            // We're not loading a draft, so we can draw the bottom panel immediately.
1978            drawBottomPanel();
1979        }
1980
1981        onKeyboardStateChanged(mIsKeyboardOpen);
1982
1983        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
1984            log("update title, mConversation=" + mConversation.toString());
1985        }
1986
1987        updateTitle(mConversation.getRecipients());
1988
1989        if (isForwardedMessage && isRecipientsEditorVisible()) {
1990            // The user is forwarding the message to someone. Put the focus on the
1991            // recipient editor rather than in the message editor.
1992            mRecipientsEditor.requestFocus();
1993        }
1994
1995        mMsgListAdapter.setIsGroupConversation(mConversation.getRecipients().size() > 1);
1996    }
1997
1998    @Override
1999    protected void onNewIntent(Intent intent) {
2000        super.onNewIntent(intent);
2001
2002        setIntent(intent);
2003
2004        Conversation conversation = null;
2005        mSentMessage = false;
2006
2007        // If we have been passed a thread_id, use that to find our
2008        // conversation.
2009
2010        // Note that originalThreadId might be zero but if this is a draft and we save the
2011        // draft, ensureThreadId gets called async from WorkingMessage.asyncUpdateDraftSmsMessage
2012        // the thread will get a threadId behind the UI thread's back.
2013        long originalThreadId = mConversation.getThreadId();
2014        long threadId = intent.getLongExtra(THREAD_ID, 0);
2015        Uri intentUri = intent.getData();
2016
2017        boolean sameThread = false;
2018        if (threadId > 0) {
2019            conversation = Conversation.get(this, threadId, false);
2020        } else {
2021            if (mConversation.getThreadId() == 0) {
2022                // We've got a draft. Make sure the working recipients are synched
2023                // to the conversation so when we compare conversations later in this function,
2024                // the compare will work.
2025                mWorkingMessage.syncWorkingRecipients();
2026            }
2027            // Get the "real" conversation based on the intentUri. The intentUri might specify
2028            // the conversation by a phone number or by a thread id. We'll typically get a threadId
2029            // based uri when the user pulls down a notification while in ComposeMessageActivity and
2030            // we end up here in onNewIntent. mConversation can have a threadId of zero when we're
2031            // working on a draft. When a new message comes in for that same recipient, a
2032            // conversation will get created behind CMA's back when the message is inserted into
2033            // the database and the corresponding entry made in the threads table. The code should
2034            // use the real conversation as soon as it can rather than finding out the threadId
2035            // when sending with "ensureThreadId".
2036            conversation = Conversation.get(this, intentUri, false);
2037        }
2038
2039        if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
2040            log("onNewIntent: data=" + intentUri + ", thread_id extra is " + threadId +
2041                    ", new conversation=" + conversation + ", mConversation=" + mConversation);
2042        }
2043
2044        // this is probably paranoid to compare both thread_ids and recipient lists,
2045        // but we want to make double sure because this is a last minute fix for Froyo
2046        // and the previous code checked thread ids only.
2047        // (we cannot just compare thread ids because there is a case where mConversation
2048        // has a stale/obsolete thread id (=1) that could collide against the new thread_id(=1),
2049        // even though the recipient lists are different)
2050        sameThread = ((conversation.getThreadId() == mConversation.getThreadId() ||
2051                mConversation.getThreadId() == 0) &&
2052                conversation.equals(mConversation));
2053
2054        if (sameThread) {
2055            log("onNewIntent: same conversation");
2056            if (mConversation.getThreadId() == 0) {
2057                mConversation = conversation;
2058                mWorkingMessage.setConversation(mConversation);
2059                updateThreadIdIfRunning();
2060                invalidateOptionsMenu();
2061            }
2062        } else {
2063            if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
2064                log("onNewIntent: different conversation");
2065            }
2066            saveDraft(false);    // if we've got a draft, save it first
2067
2068            initialize(null, originalThreadId);
2069        }
2070        loadMessagesAndDraft(0);
2071    }
2072
2073    private void sanityCheckConversation() {
2074        if (mWorkingMessage.getConversation() != mConversation) {
2075            LogTag.warnPossibleRecipientMismatch(
2076                    "ComposeMessageActivity: mWorkingMessage.mConversation=" +
2077                    mWorkingMessage.getConversation() + ", mConversation=" +
2078                    mConversation + ", MISMATCH!", this);
2079        }
2080    }
2081
2082    @Override
2083    protected void onRestart() {
2084        super.onRestart();
2085
2086        // hide the compose panel to reduce jank when re-entering this activity.
2087        // if we don't hide it here, the compose panel will flash before the keyboard shows
2088        // (when keyboard is suppose to be shown).
2089        hideBottomPanel();
2090
2091        if (mWorkingMessage.isDiscarded()) {
2092            // If the message isn't worth saving, don't resurrect it. Doing so can lead to
2093            // a situation where a new incoming message gets the old thread id of the discarded
2094            // draft. This activity can end up displaying the recipients of the old message with
2095            // the contents of the new message. Recognize that dangerous situation and bail out
2096            // to the ConversationList where the user can enter this in a clean manner.
2097            if (mWorkingMessage.isWorthSaving()) {
2098                if (LogTag.VERBOSE) {
2099                    log("onRestart: mWorkingMessage.unDiscard()");
2100                }
2101                mWorkingMessage.unDiscard();    // it was discarded in onStop().
2102
2103                sanityCheckConversation();
2104            } else if (isRecipientsEditorVisible() && recipientCount() > 0) {
2105                if (LogTag.VERBOSE) {
2106                    log("onRestart: goToConversationList");
2107                }
2108                goToConversationList();
2109            }
2110        }
2111    }
2112
2113    @Override
2114    protected void onStart() {
2115        super.onStart();
2116        boolean isSmsEnabled = MmsConfig.isSmsEnabled(this);
2117        if (isSmsEnabled != mIsSmsEnabled) {
2118            mIsSmsEnabled = isSmsEnabled;
2119            invalidateOptionsMenu();
2120        }
2121
2122        initFocus();
2123
2124        // Register a BroadcastReceiver to listen on HTTP I/O process.
2125        registerReceiver(mHttpProgressReceiver, mHttpProgressFilter);
2126
2127        // figure out whether we need to show the keyboard or not.
2128        // if there is draft to be loaded for 'mConversation', we'll show the keyboard;
2129        // otherwise we hide the keyboard. In any event, delay loading
2130        // message history and draft (controlled by DEFER_LOADING_MESSAGES_AND_DRAFT).
2131        int mode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
2132
2133        if (DraftCache.getInstance().hasDraft(mConversation.getThreadId())) {
2134            mode |= WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE;
2135        } else if (mConversation.getThreadId() <= 0) {
2136            // For composing a new message, bring up the softkeyboard so the user can
2137            // immediately enter recipients. This call won't do anything on devices with
2138            // a hard keyboard.
2139            mode |= WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE;
2140        } else {
2141            mode |= WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN;
2142        }
2143
2144        getWindow().setSoftInputMode(mode);
2145
2146        // reset mMessagesAndDraftLoaded
2147        mMessagesAndDraftLoaded = false;
2148
2149        if (!DEFER_LOADING_MESSAGES_AND_DRAFT) {
2150            loadMessagesAndDraft(1);
2151        } else {
2152            // HACK: force load messages+draft after max delay, if it's not already loaded.
2153            // this is to work around when coming out of sleep mode. WindowManager behaves
2154            // strangely and hides the keyboard when it should be shown, or sometimes initially
2155            // shows it when we want to hide it. In that case, we never get the onSizeChanged()
2156            // callback w/ keyboard shown, so we wouldn't know to load the messages+draft.
2157            mHandler.postDelayed(new Runnable() {
2158                public void run() {
2159                    loadMessagesAndDraft(2);
2160                }
2161            }, LOADING_MESSAGES_AND_DRAFT_MAX_DELAY_MS);
2162        }
2163
2164        // Update the fasttrack info in case any of the recipients' contact info changed
2165        // while we were paused. This can happen, for example, if a user changes or adds
2166        // an avatar associated with a contact.
2167        mWorkingMessage.syncWorkingRecipients();
2168
2169        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
2170            log("update title, mConversation=" + mConversation.toString());
2171        }
2172
2173        updateTitle(mConversation.getRecipients());
2174
2175        ActionBar actionBar = getActionBar();
2176        actionBar.setDisplayHomeAsUpEnabled(true);
2177    }
2178
2179    public void loadMessageContent() {
2180        // Don't let any markAsRead DB updates occur before we've loaded the messages for
2181        // the thread. Unblocking occurs when we're done querying for the conversation
2182        // items.
2183        mConversation.blockMarkAsRead(true);
2184        mConversation.markAsRead();         // dismiss any notifications for this convo
2185        startMsgListQuery();
2186        updateSendFailedNotification();
2187    }
2188
2189    /**
2190     * Load message history and draft. This method should be called from main thread.
2191     * @param debugFlag shows where this is being called from
2192     */
2193    private void loadMessagesAndDraft(int debugFlag) {
2194        if (!mSendDiscreetMode && !mMessagesAndDraftLoaded) {
2195            if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
2196                Log.v(TAG, "### CMA.loadMessagesAndDraft: flag=" + debugFlag);
2197            }
2198            loadMessageContent();
2199            boolean drawBottomPanel = true;
2200            if (mShouldLoadDraft) {
2201                if (loadDraft()) {
2202                    drawBottomPanel = false;
2203                }
2204            }
2205            if (drawBottomPanel) {
2206                drawBottomPanel();
2207            }
2208            mMessagesAndDraftLoaded = true;
2209        }
2210    }
2211
2212    private void updateSendFailedNotification() {
2213        final long threadId = mConversation.getThreadId();
2214        if (threadId <= 0)
2215            return;
2216
2217        // updateSendFailedNotificationForThread makes a database call, so do the work off
2218        // of the ui thread.
2219        new Thread(new Runnable() {
2220            @Override
2221            public void run() {
2222                MessagingNotification.updateSendFailedNotificationForThread(
2223                        ComposeMessageActivity.this, threadId);
2224            }
2225        }, "ComposeMessageActivity.updateSendFailedNotification").start();
2226    }
2227
2228    @Override
2229    public void onSaveInstanceState(Bundle outState) {
2230        super.onSaveInstanceState(outState);
2231
2232        outState.putString(RECIPIENTS, getRecipients().serialize());
2233
2234        mWorkingMessage.writeStateToBundle(outState);
2235
2236        if (mSendDiscreetMode) {
2237            outState.putBoolean(KEY_EXIT_ON_SENT, mSendDiscreetMode);
2238        }
2239        if (mForwardMessageMode) {
2240            outState.putBoolean(KEY_FORWARDED_MESSAGE, mForwardMessageMode);
2241        }
2242    }
2243
2244    @Override
2245    protected void onResume() {
2246        super.onResume();
2247
2248        // OLD: get notified of presence updates to update the titlebar.
2249        // NEW: we are using ContactHeaderWidget which displays presence, but updating presence
2250        //      there is out of our control.
2251        //Contact.startPresenceObserver();
2252
2253        addRecipientsListeners();
2254
2255        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
2256            log("update title, mConversation=" + mConversation.toString());
2257        }
2258
2259        // There seems to be a bug in the framework such that setting the title
2260        // here gets overwritten to the original title.  Do this delayed as a
2261        // workaround.
2262        mMessageListItemHandler.postDelayed(new Runnable() {
2263            @Override
2264            public void run() {
2265                ContactList recipients = isRecipientsEditorVisible() ?
2266                        mRecipientsEditor.constructContactsFromInput(false) : getRecipients();
2267                updateTitle(recipients);
2268            }
2269        }, 100);
2270
2271        mIsRunning = true;
2272        updateThreadIdIfRunning();
2273        mConversation.markAsRead();
2274    }
2275
2276    @Override
2277    protected void onPause() {
2278        super.onPause();
2279
2280        if (DEBUG) {
2281            Log.v(TAG, "onPause: setCurrentlyDisplayedThreadId: " +
2282                        MessagingNotification.THREAD_NONE);
2283        }
2284        MessagingNotification.setCurrentlyDisplayedThreadId(MessagingNotification.THREAD_NONE);
2285
2286        // OLD: stop getting notified of presence updates to update the titlebar.
2287        // NEW: we are using ContactHeaderWidget which displays presence, but updating presence
2288        //      there is out of our control.
2289        //Contact.stopPresenceObserver();
2290
2291        removeRecipientsListeners();
2292
2293        // remove any callback to display a progress spinner
2294        if (mAsyncDialog != null) {
2295            mAsyncDialog.clearPendingProgressDialog();
2296        }
2297
2298        // Remember whether the list is scrolled to the end when we're paused so we can rescroll
2299        // to the end when resumed.
2300        if (mMsgListAdapter != null &&
2301                mMsgListView.getLastVisiblePosition() >= mMsgListAdapter.getCount() - 1) {
2302            mSavedScrollPosition = Integer.MAX_VALUE;
2303        } else {
2304            mSavedScrollPosition = mMsgListView.getFirstVisiblePosition();
2305        }
2306        if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
2307            Log.v(TAG, "onPause: mSavedScrollPosition=" + mSavedScrollPosition);
2308        }
2309
2310        mConversation.markAsRead();
2311        mIsRunning = false;
2312    }
2313
2314    @Override
2315    protected void onStop() {
2316        super.onStop();
2317
2318        // No need to do the querying when finished this activity
2319        mBackgroundQueryHandler.cancelOperation(MESSAGE_LIST_QUERY_TOKEN);
2320
2321        // Allow any blocked calls to update the thread's read status.
2322        mConversation.blockMarkAsRead(false);
2323
2324        if (mMsgListAdapter != null) {
2325            // Close the cursor in the ListAdapter if the activity stopped.
2326            Cursor cursor = mMsgListAdapter.getCursor();
2327
2328            if (cursor != null && !cursor.isClosed()) {
2329                cursor.close();
2330            }
2331
2332            mMsgListAdapter.changeCursor(null);
2333            mMsgListAdapter.cancelBackgroundLoading();
2334        }
2335
2336        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
2337            log("save draft");
2338        }
2339        saveDraft(true);
2340
2341        // set 'mShouldLoadDraft' to true, so when coming back to ComposeMessageActivity, we would
2342        // load the draft, unless we are coming back to the activity after attaching a photo, etc,
2343        // in which case we should set 'mShouldLoadDraft' to false.
2344        mShouldLoadDraft = true;
2345
2346        // Cleanup the BroadcastReceiver.
2347        unregisterReceiver(mHttpProgressReceiver);
2348    }
2349
2350    @Override
2351    protected void onDestroy() {
2352        if (TRACE) {
2353            android.os.Debug.stopMethodTracing();
2354        }
2355
2356        super.onDestroy();
2357    }
2358
2359    @Override
2360    public void onConfigurationChanged(Configuration newConfig) {
2361        super.onConfigurationChanged(newConfig);
2362
2363        if (resetConfiguration(newConfig)) {
2364            // Have to re-layout the attachment editor because we have different layouts
2365            // depending on whether we're portrait or landscape.
2366            drawTopPanel(isSubjectEditorVisible());
2367        }
2368        if (LOCAL_LOGV) {
2369            Log.v(TAG, "CMA.onConfigurationChanged: " + newConfig +
2370                    ", mIsKeyboardOpen=" + mIsKeyboardOpen);
2371        }
2372        onKeyboardStateChanged(mIsKeyboardOpen);
2373    }
2374
2375    // returns true if landscape/portrait configuration has changed
2376    private boolean resetConfiguration(Configuration config) {
2377        mIsKeyboardOpen = config.keyboardHidden == KEYBOARDHIDDEN_NO;
2378        boolean isLandscape = config.orientation == Configuration.ORIENTATION_LANDSCAPE;
2379        if (mIsLandscape != isLandscape) {
2380            mIsLandscape = isLandscape;
2381            return true;
2382        }
2383        return false;
2384    }
2385
2386    private void onKeyboardStateChanged(boolean isKeyboardOpen) {
2387        // If the keyboard is hidden, don't show focus highlights for
2388        // things that cannot receive input.
2389        if (isKeyboardOpen) {
2390            if (mRecipientsEditor != null) {
2391                mRecipientsEditor.setFocusableInTouchMode(true);
2392            }
2393            if (mSubjectTextEditor != null) {
2394                mSubjectTextEditor.setFocusableInTouchMode(true);
2395            }
2396            mTextEditor.setFocusableInTouchMode(true);
2397            mTextEditor.setHint(R.string.type_to_compose_text_enter_to_send);
2398        } else {
2399            if (mRecipientsEditor != null) {
2400                mRecipientsEditor.setFocusable(false);
2401            }
2402            if (mSubjectTextEditor != null) {
2403                mSubjectTextEditor.setFocusable(false);
2404            }
2405            mTextEditor.setFocusable(false);
2406            mTextEditor.setHint(R.string.open_keyboard_to_compose_message);
2407        }
2408    }
2409
2410    @Override
2411    public boolean onKeyDown(int keyCode, KeyEvent event) {
2412        switch (keyCode) {
2413            case KeyEvent.KEYCODE_DEL:
2414                if ((mMsgListAdapter != null) && mMsgListView.isFocused()) {
2415                    Cursor cursor;
2416                    try {
2417                        cursor = (Cursor) mMsgListView.getSelectedItem();
2418                    } catch (ClassCastException e) {
2419                        Log.e(TAG, "Unexpected ClassCastException.", e);
2420                        return super.onKeyDown(keyCode, event);
2421                    }
2422
2423                    if (cursor != null) {
2424                        String type = cursor.getString(COLUMN_MSG_TYPE);
2425                        long msgId = cursor.getLong(COLUMN_ID);
2426                        MessageItem msgItem = mMsgListAdapter.getCachedMessageItem(type, msgId,
2427                                cursor);
2428                        if (msgItem != null) {
2429                            DeleteMessageListener l = new DeleteMessageListener(msgItem);
2430                            confirmDeleteDialog(l, msgItem.mLocked);
2431                        }
2432                        return true;
2433                    }
2434                }
2435                break;
2436            case KeyEvent.KEYCODE_DPAD_CENTER:
2437            case KeyEvent.KEYCODE_ENTER:
2438                if (isPreparedForSending()) {
2439                    confirmSendMessageIfNeeded();
2440                    return true;
2441                }
2442                break;
2443            case KeyEvent.KEYCODE_BACK:
2444                exitComposeMessageActivity(new Runnable() {
2445                    @Override
2446                    public void run() {
2447                        finish();
2448                    }
2449                });
2450                return true;
2451        }
2452
2453        return super.onKeyDown(keyCode, event);
2454    }
2455
2456    private void exitComposeMessageActivity(final Runnable exit) {
2457        // If the message is empty, just quit -- finishing the
2458        // activity will cause an empty draft to be deleted.
2459        if (!mWorkingMessage.isWorthSaving()) {
2460            exit.run();
2461            return;
2462        }
2463
2464        if (isRecipientsEditorVisible() &&
2465                !mRecipientsEditor.hasValidRecipient(mWorkingMessage.requiresMms())) {
2466            MessageUtils.showDiscardDraftConfirmDialog(this, new DiscardDraftListener());
2467            return;
2468        }
2469
2470        mToastForDraftSave = true;
2471        exit.run();
2472    }
2473
2474    private void goToConversationList() {
2475        finish();
2476        startActivity(new Intent(this, ConversationList.class));
2477    }
2478
2479    private void hideRecipientEditor() {
2480        if (mRecipientsEditor != null) {
2481            mRecipientsEditor.removeTextChangedListener(mRecipientsWatcher);
2482            mRecipientsEditor.setVisibility(View.GONE);
2483            hideOrShowTopPanel();
2484        }
2485    }
2486
2487    private boolean isRecipientsEditorVisible() {
2488        return (null != mRecipientsEditor)
2489                    && (View.VISIBLE == mRecipientsEditor.getVisibility());
2490    }
2491
2492    private boolean isSubjectEditorVisible() {
2493        return (null != mSubjectTextEditor)
2494                    && (View.VISIBLE == mSubjectTextEditor.getVisibility());
2495    }
2496
2497    @Override
2498    public void onAttachmentChanged() {
2499        // Have to make sure we're on the UI thread. This function can be called off of the UI
2500        // thread when we're adding multi-attachments
2501        runOnUiThread(new Runnable() {
2502            @Override
2503            public void run() {
2504                drawBottomPanel();
2505                updateSendButtonState();
2506                drawTopPanel(isSubjectEditorVisible());
2507            }
2508        });
2509    }
2510
2511    @Override
2512    public void onProtocolChanged(final boolean convertToMms) {
2513        // Have to make sure we're on the UI thread. This function can be called off of the UI
2514        // thread when we're adding multi-attachments
2515        runOnUiThread(new Runnable() {
2516            @Override
2517            public void run() {
2518                showSmsOrMmsSendButton(convertToMms);
2519
2520                if (convertToMms) {
2521                    // In the case we went from a long sms with a counter to an mms because
2522                    // the user added an attachment or a subject, hide the counter --
2523                    // it doesn't apply to mms.
2524                    mTextCounter.setVisibility(View.GONE);
2525
2526                    showConvertToMmsToast();
2527                }
2528            }
2529        });
2530    }
2531
2532    // Show or hide the Sms or Mms button as appropriate. Return the view so that the caller
2533    // can adjust the enableness and focusability.
2534    private View showSmsOrMmsSendButton(boolean isMms) {
2535        View showButton;
2536        View hideButton;
2537        if (isMms) {
2538            showButton = mSendButtonMms;
2539            hideButton = mSendButtonSms;
2540        } else {
2541            showButton = mSendButtonSms;
2542            hideButton = mSendButtonMms;
2543        }
2544        showButton.setVisibility(View.VISIBLE);
2545        hideButton.setVisibility(View.GONE);
2546
2547        return showButton;
2548    }
2549
2550    Runnable mResetMessageRunnable = new Runnable() {
2551        @Override
2552        public void run() {
2553            resetMessage();
2554        }
2555    };
2556
2557    @Override
2558    public void onPreMessageSent() {
2559        runOnUiThread(mResetMessageRunnable);
2560    }
2561
2562    @Override
2563    public void onMessageSent() {
2564        // This callback can come in on any thread; put it on the main thread to avoid
2565        // concurrency problems
2566        runOnUiThread(new Runnable() {
2567            @Override
2568            public void run() {
2569                // If we already have messages in the list adapter, it
2570                // will be auto-requerying; don't thrash another query in.
2571                // TODO: relying on auto-requerying seems unreliable when priming an MMS into the
2572                // outbox. Need to investigate.
2573//                if (mMsgListAdapter.getCount() == 0) {
2574                    if (LogTag.VERBOSE) {
2575                        log("onMessageSent");
2576                    }
2577                    startMsgListQuery();
2578//                }
2579
2580                // The thread ID could have changed if this is a new message that we just inserted
2581                // into the database (and looked up or created a thread for it)
2582                updateThreadIdIfRunning();
2583            }
2584        });
2585    }
2586
2587    @Override
2588    public void onMaxPendingMessagesReached() {
2589        saveDraft(false);
2590
2591        runOnUiThread(new Runnable() {
2592            @Override
2593            public void run() {
2594                Toast.makeText(ComposeMessageActivity.this, R.string.too_many_unsent_mms,
2595                        Toast.LENGTH_LONG).show();
2596            }
2597        });
2598    }
2599
2600    @Override
2601    public void onAttachmentError(final int error) {
2602        runOnUiThread(new Runnable() {
2603            @Override
2604            public void run() {
2605                handleAddAttachmentError(error, R.string.type_picture);
2606                onMessageSent();        // now requery the list of messages
2607            }
2608        });
2609    }
2610
2611    // We don't want to show the "call" option unless there is only one
2612    // recipient and it's a phone number.
2613    private boolean isRecipientCallable() {
2614        ContactList recipients = getRecipients();
2615        return (recipients.size() == 1 && !recipients.containsEmail());
2616    }
2617
2618    private void dialRecipient() {
2619        if (isRecipientCallable()) {
2620            String number = getRecipients().get(0).getNumber();
2621            Intent dialIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));
2622            startActivity(dialIntent);
2623        }
2624    }
2625
2626    @Override
2627    public boolean onPrepareOptionsMenu(Menu menu) {
2628        super.onPrepareOptionsMenu(menu) ;
2629
2630        menu.clear();
2631
2632        if (mSendDiscreetMode && !mForwardMessageMode) {
2633            // When we're in send-a-single-message mode from the lock screen, don't show
2634            // any menus.
2635            return true;
2636        }
2637
2638        if (isRecipientCallable()) {
2639            MenuItem item = menu.add(0, MENU_CALL_RECIPIENT, 0, R.string.menu_call)
2640                .setIcon(R.drawable.ic_menu_call)
2641                .setTitle(R.string.menu_call);
2642            if (!isRecipientsEditorVisible()) {
2643                // If we're not composing a new message, show the call icon in the actionbar
2644                item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
2645            }
2646        }
2647
2648        if (MmsConfig.getMmsEnabled() && mIsSmsEnabled) {
2649            if (!isSubjectEditorVisible()) {
2650                menu.add(0, MENU_ADD_SUBJECT, 0, R.string.add_subject).setIcon(
2651                        R.drawable.ic_menu_edit);
2652            }
2653            if (!mWorkingMessage.hasAttachment()) {
2654                menu.add(0, MENU_ADD_ATTACHMENT, 0, R.string.add_attachment)
2655                        .setIcon(R.drawable.ic_menu_attachment)
2656                    .setTitle(R.string.add_attachment)
2657                        .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);    // add to actionbar
2658            }
2659        }
2660
2661        if (isPreparedForSending() && mIsSmsEnabled) {
2662            menu.add(0, MENU_SEND, 0, R.string.send).setIcon(android.R.drawable.ic_menu_send);
2663        }
2664
2665        if (getRecipients().size() > 1) {
2666            menu.add(0, MENU_GROUP_PARTICIPANTS, 0, R.string.menu_group_participants);
2667        }
2668
2669        if (mMsgListAdapter.getCount() > 0 && mIsSmsEnabled) {
2670            // Removed search as part of b/1205708
2671            //menu.add(0, MENU_SEARCH, 0, R.string.menu_search).setIcon(
2672            //        R.drawable.ic_menu_search);
2673            Cursor cursor = mMsgListAdapter.getCursor();
2674            if ((null != cursor) && (cursor.getCount() > 0)) {
2675                menu.add(0, MENU_DELETE_THREAD, 0, R.string.delete_thread).setIcon(
2676                    android.R.drawable.ic_menu_delete);
2677            }
2678        } else if (mIsSmsEnabled) {
2679            menu.add(0, MENU_DISCARD, 0, R.string.discard).setIcon(android.R.drawable.ic_menu_delete);
2680        }
2681
2682        buildAddAddressToContactMenuItem(menu);
2683
2684        menu.add(0, MENU_PREFERENCES, 0, R.string.menu_preferences).setIcon(
2685                android.R.drawable.ic_menu_preferences);
2686
2687        if (LogTag.DEBUG_DUMP) {
2688            menu.add(0, MENU_DEBUG_DUMP, 0, R.string.menu_debug_dump);
2689        }
2690
2691        return true;
2692    }
2693
2694    private void buildAddAddressToContactMenuItem(Menu menu) {
2695        // bug #7087793: for group of recipients, remove "Add to People" action. Rely on
2696        // individually creating contacts for unknown phone numbers by touching the individual
2697        // sender's avatars, one at a time
2698        ContactList contacts = getRecipients();
2699        if (contacts.size() != 1) {
2700            return;
2701        }
2702
2703        // if we don't have a contact for the recipient, create a menu item to add the number
2704        // to contacts.
2705        Contact c = contacts.get(0);
2706        if (!c.existsInDatabase() && canAddToContacts(c)) {
2707            Intent intent = ConversationList.createAddContactIntent(c.getNumber());
2708            menu.add(0, MENU_ADD_ADDRESS_TO_CONTACTS, 0, R.string.menu_add_to_contacts)
2709                .setIcon(android.R.drawable.ic_menu_add)
2710                .setIntent(intent);
2711        }
2712    }
2713
2714    @Override
2715    public boolean onOptionsItemSelected(MenuItem item) {
2716        switch (item.getItemId()) {
2717            case MENU_ADD_SUBJECT:
2718                showSubjectEditor(true);
2719                mWorkingMessage.setSubject("", true);
2720                updateSendButtonState();
2721                mSubjectTextEditor.requestFocus();
2722                break;
2723            case MENU_ADD_ATTACHMENT:
2724                // Launch the add-attachment list dialog
2725                showAddAttachmentDialog(false);
2726                break;
2727            case MENU_DISCARD:
2728                mWorkingMessage.discard();
2729                finish();
2730                break;
2731            case MENU_SEND:
2732                if (isPreparedForSending()) {
2733                    confirmSendMessageIfNeeded();
2734                }
2735                break;
2736            case MENU_SEARCH:
2737                onSearchRequested();
2738                break;
2739            case MENU_DELETE_THREAD:
2740                confirmDeleteThread(mConversation.getThreadId());
2741                break;
2742
2743            case android.R.id.home:
2744            case MENU_CONVERSATION_LIST:
2745                exitComposeMessageActivity(new Runnable() {
2746                    @Override
2747                    public void run() {
2748                        goToConversationList();
2749                    }
2750                });
2751                break;
2752            case MENU_CALL_RECIPIENT:
2753                dialRecipient();
2754                break;
2755            case MENU_GROUP_PARTICIPANTS:
2756            {
2757                Intent intent = new Intent(this, RecipientListActivity.class);
2758                intent.putExtra(THREAD_ID, mConversation.getThreadId());
2759                startActivity(intent);
2760                break;
2761            }
2762            case MENU_VIEW_CONTACT: {
2763                // View the contact for the first (and only) recipient.
2764                ContactList list = getRecipients();
2765                if (list.size() == 1 && list.get(0).existsInDatabase()) {
2766                    Uri contactUri = list.get(0).getUri();
2767                    Intent intent = new Intent(Intent.ACTION_VIEW, contactUri);
2768                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
2769                    startActivity(intent);
2770                }
2771                break;
2772            }
2773            case MENU_ADD_ADDRESS_TO_CONTACTS:
2774                mAddContactIntent = item.getIntent();
2775                startActivityForResult(mAddContactIntent, REQUEST_CODE_ADD_CONTACT);
2776                break;
2777            case MENU_PREFERENCES: {
2778                Intent intent = new Intent(this, MessagingPreferenceActivity.class);
2779                startActivityIfNeeded(intent, -1);
2780                break;
2781            }
2782            case MENU_DEBUG_DUMP:
2783                mWorkingMessage.dump();
2784                Conversation.dump();
2785                LogTag.dumpInternalTables(this);
2786                break;
2787        }
2788
2789        return true;
2790    }
2791
2792    private void confirmDeleteThread(long threadId) {
2793        Conversation.startQueryHaveLockedMessages(mBackgroundQueryHandler,
2794                threadId, ConversationList.HAVE_LOCKED_MESSAGES_TOKEN);
2795    }
2796
2797//    static class SystemProperties { // TODO, temp class to get unbundling working
2798//        static int getInt(String s, int value) {
2799//            return value;       // just return the default value or now
2800//        }
2801//    }
2802
2803    private void addAttachment(int type, boolean replace) {
2804        // Calculate the size of the current slide if we're doing a replace so the
2805        // slide size can optionally be used in computing how much room is left for an attachment.
2806        int currentSlideSize = 0;
2807        SlideshowModel slideShow = mWorkingMessage.getSlideshow();
2808        if (replace && slideShow != null) {
2809            WorkingMessage.removeThumbnailsFromCache(slideShow);
2810            SlideModel slide = slideShow.get(0);
2811            currentSlideSize = slide.getSlideSize();
2812        }
2813        switch (type) {
2814            case AttachmentTypeSelectorAdapter.ADD_IMAGE:
2815                MessageUtils.selectImage(this, REQUEST_CODE_ATTACH_IMAGE);
2816                break;
2817
2818            case AttachmentTypeSelectorAdapter.TAKE_PICTURE: {
2819                MessageUtils.capturePicture(this, REQUEST_CODE_TAKE_PICTURE);
2820                break;
2821            }
2822
2823            case AttachmentTypeSelectorAdapter.ADD_VIDEO:
2824                MessageUtils.selectVideo(this, REQUEST_CODE_ATTACH_VIDEO);
2825                break;
2826
2827            case AttachmentTypeSelectorAdapter.RECORD_VIDEO: {
2828                long sizeLimit = computeAttachmentSizeLimit(slideShow, currentSlideSize);
2829                if (sizeLimit > 0) {
2830                    MessageUtils.recordVideo(this, REQUEST_CODE_TAKE_VIDEO, sizeLimit);
2831                } else {
2832                    Toast.makeText(this,
2833                            getString(R.string.message_too_big_for_video),
2834                            Toast.LENGTH_SHORT).show();
2835                }
2836            }
2837            break;
2838
2839            case AttachmentTypeSelectorAdapter.ADD_SOUND:
2840                MessageUtils.selectAudio(this, REQUEST_CODE_ATTACH_SOUND);
2841                break;
2842
2843            case AttachmentTypeSelectorAdapter.RECORD_SOUND:
2844                long sizeLimit = computeAttachmentSizeLimit(slideShow, currentSlideSize);
2845                MessageUtils.recordSound(this, REQUEST_CODE_RECORD_SOUND, sizeLimit);
2846                break;
2847
2848            case AttachmentTypeSelectorAdapter.ADD_SLIDESHOW:
2849                editSlideshow();
2850                break;
2851
2852            default:
2853                break;
2854        }
2855    }
2856
2857    public static long computeAttachmentSizeLimit(SlideshowModel slideShow, int currentSlideSize) {
2858        // Computer attachment size limit. Subtract 1K for some text.
2859        long sizeLimit = MmsConfig.getMaxMessageSize() - SlideshowModel.SLIDESHOW_SLOP;
2860        if (slideShow != null) {
2861            sizeLimit -= slideShow.getCurrentMessageSize();
2862
2863            // We're about to ask the camera to capture some video (or the sound recorder
2864            // to record some audio) which will eventually replace the content on the current
2865            // slide. Since the current slide already has some content (which was subtracted
2866            // out just above) and that content is going to get replaced, we can add the size of the
2867            // current slide into the available space used to capture a video (or audio).
2868            sizeLimit += currentSlideSize;
2869        }
2870        return sizeLimit;
2871    }
2872
2873    private void showAddAttachmentDialog(final boolean replace) {
2874        AlertDialog.Builder builder = new AlertDialog.Builder(this);
2875        builder.setIcon(R.drawable.ic_dialog_attach);
2876        builder.setTitle(R.string.add_attachment);
2877
2878        if (mAttachmentTypeSelectorAdapter == null) {
2879            mAttachmentTypeSelectorAdapter = new AttachmentTypeSelectorAdapter(
2880                    this, AttachmentTypeSelectorAdapter.MODE_WITH_SLIDESHOW);
2881        }
2882        builder.setAdapter(mAttachmentTypeSelectorAdapter, new DialogInterface.OnClickListener() {
2883            @Override
2884            public void onClick(DialogInterface dialog, int which) {
2885                addAttachment(mAttachmentTypeSelectorAdapter.buttonToCommand(which), replace);
2886                dialog.dismiss();
2887            }
2888        });
2889
2890        builder.show();
2891    }
2892
2893    @Override
2894    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
2895        if (LogTag.VERBOSE) {
2896            log("onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode +
2897                    ", data=" + data);
2898        }
2899        mWaitingForSubActivity = false;          // We're back!
2900        mShouldLoadDraft = false;
2901        if (mWorkingMessage.isFakeMmsForDraft()) {
2902            // We no longer have to fake the fact we're an Mms. At this point we are or we aren't,
2903            // based on attachments and other Mms attrs.
2904            mWorkingMessage.removeFakeMmsForDraft();
2905        }
2906
2907        if (requestCode == REQUEST_CODE_PICK) {
2908            mWorkingMessage.asyncDeleteDraftSmsMessage(mConversation);
2909        }
2910
2911        if (requestCode == REQUEST_CODE_ADD_CONTACT) {
2912            // The user might have added a new contact. When we tell contacts to add a contact
2913            // and tap "Done", we're not returned to Messaging. If we back out to return to
2914            // messaging after adding a contact, the resultCode is RESULT_CANCELED. Therefore,
2915            // assume a contact was added and get the contact and force our cached contact to
2916            // get reloaded with the new info (such as contact name). After the
2917            // contact is reloaded, the function onUpdate() in this file will get called
2918            // and it will update the title bar, etc.
2919            if (mAddContactIntent != null) {
2920                String address =
2921                    mAddContactIntent.getStringExtra(ContactsContract.Intents.Insert.EMAIL);
2922                if (address == null) {
2923                    address =
2924                        mAddContactIntent.getStringExtra(ContactsContract.Intents.Insert.PHONE);
2925                }
2926                if (address != null) {
2927                    Contact contact = Contact.get(address, false);
2928                    if (contact != null) {
2929                        contact.reload();
2930                    }
2931                }
2932            }
2933        }
2934
2935        if (resultCode != RESULT_OK){
2936            if (LogTag.VERBOSE) log("bail due to resultCode=" + resultCode);
2937            return;
2938        }
2939
2940        switch (requestCode) {
2941            case REQUEST_CODE_CREATE_SLIDESHOW:
2942                if (data != null) {
2943                    WorkingMessage newMessage = WorkingMessage.load(this, data.getData());
2944                    if (newMessage != null) {
2945                        mWorkingMessage = newMessage;
2946                        mWorkingMessage.setConversation(mConversation);
2947                        updateThreadIdIfRunning();
2948                        drawTopPanel(false);
2949                        updateSendButtonState();
2950                    }
2951                }
2952                break;
2953
2954            case REQUEST_CODE_TAKE_PICTURE: {
2955                // create a file based uri and pass to addImage(). We want to read the JPEG
2956                // data directly from file (using UriImage) instead of decoding it into a Bitmap,
2957                // which takes up too much memory and could easily lead to OOM.
2958                File file = new File(TempFileProvider.getScrapPath(this));
2959                Uri uri = Uri.fromFile(file);
2960
2961                // Remove the old captured picture's thumbnail from the cache
2962                MmsApp.getApplication().getThumbnailManager().removeThumbnail(uri);
2963
2964                addImageAsync(uri, false);
2965                break;
2966            }
2967
2968            case REQUEST_CODE_ATTACH_IMAGE: {
2969                if (data != null) {
2970                    addImageAsync(data.getData(), false);
2971                }
2972                break;
2973            }
2974
2975            case REQUEST_CODE_TAKE_VIDEO:
2976                Uri videoUri = TempFileProvider.renameScrapFile(".3gp", null, this);
2977                // Remove the old captured video's thumbnail from the cache
2978                MmsApp.getApplication().getThumbnailManager().removeThumbnail(videoUri);
2979
2980                addVideoAsync(videoUri, false);      // can handle null videoUri
2981                break;
2982
2983            case REQUEST_CODE_ATTACH_VIDEO:
2984                if (data != null) {
2985                    addVideoAsync(data.getData(), false);
2986                }
2987                break;
2988
2989            case REQUEST_CODE_ATTACH_SOUND: {
2990                Uri uri = (Uri) data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
2991                if (Settings.System.DEFAULT_RINGTONE_URI.equals(uri)) {
2992                    break;
2993                }
2994                addAudio(uri);
2995                break;
2996            }
2997
2998            case REQUEST_CODE_RECORD_SOUND:
2999                if (data != null) {
3000                    addAudio(data.getData());
3001                }
3002                break;
3003
3004            case REQUEST_CODE_ECM_EXIT_DIALOG:
3005                boolean outOfEmergencyMode = data.getBooleanExtra(EXIT_ECM_RESULT, false);
3006                if (outOfEmergencyMode) {
3007                    sendMessage(false);
3008                }
3009                break;
3010
3011            case REQUEST_CODE_PICK:
3012                if (data != null) {
3013                    processPickResult(data);
3014                }
3015                break;
3016
3017            default:
3018                if (LogTag.VERBOSE) log("bail due to unknown requestCode=" + requestCode);
3019                break;
3020        }
3021    }
3022
3023    private void processPickResult(final Intent data) {
3024        // The EXTRA_PHONE_URIS stores the phone's urls that were selected by user in the
3025        // multiple phone picker.
3026        final Parcelable[] uris =
3027            data.getParcelableArrayExtra(Intents.EXTRA_PHONE_URIS);
3028
3029        final int recipientCount = uris != null ? uris.length : 0;
3030
3031        final int recipientLimit = MmsConfig.getRecipientLimit();
3032        if (recipientLimit != Integer.MAX_VALUE && recipientCount > recipientLimit) {
3033            new AlertDialog.Builder(this)
3034                    .setMessage(getString(R.string.too_many_recipients, recipientCount, recipientLimit))
3035                    .setPositiveButton(android.R.string.ok, null)
3036                    .create().show();
3037            return;
3038        }
3039
3040        final Handler handler = new Handler();
3041        final ProgressDialog progressDialog = new ProgressDialog(this);
3042        progressDialog.setTitle(getText(R.string.pick_too_many_recipients));
3043        progressDialog.setMessage(getText(R.string.adding_recipients));
3044        progressDialog.setIndeterminate(true);
3045        progressDialog.setCancelable(false);
3046
3047        final Runnable showProgress = new Runnable() {
3048            @Override
3049            public void run() {
3050                progressDialog.show();
3051            }
3052        };
3053        // Only show the progress dialog if we can not finish off parsing the return data in 1s,
3054        // otherwise the dialog could flicker.
3055        handler.postDelayed(showProgress, 1000);
3056
3057        new Thread(new Runnable() {
3058            @Override
3059            public void run() {
3060                final ContactList list;
3061                 try {
3062                    list = ContactList.blockingGetByUris(uris);
3063                } finally {
3064                    handler.removeCallbacks(showProgress);
3065                    progressDialog.dismiss();
3066                }
3067                // TODO: there is already code to update the contact header widget and recipients
3068                // editor if the contacts change. we can re-use that code.
3069                final Runnable populateWorker = new Runnable() {
3070                    @Override
3071                    public void run() {
3072                        mRecipientsEditor.populate(list);
3073                        updateTitle(list);
3074                    }
3075                };
3076                handler.post(populateWorker);
3077            }
3078        }, "ComoseMessageActivity.processPickResult").start();
3079    }
3080
3081    private final ResizeImageResultCallback mResizeImageCallback = new ResizeImageResultCallback() {
3082        // TODO: make this produce a Uri, that's what we want anyway
3083        @Override
3084        public void onResizeResult(PduPart part, boolean append) {
3085            if (part == null) {
3086                handleAddAttachmentError(WorkingMessage.UNKNOWN_ERROR, R.string.type_picture);
3087                return;
3088            }
3089
3090            Context context = ComposeMessageActivity.this;
3091            PduPersister persister = PduPersister.getPduPersister(context);
3092            int result;
3093
3094            Uri messageUri = mWorkingMessage.saveAsMms(true);
3095            if (messageUri == null) {
3096                result = WorkingMessage.UNKNOWN_ERROR;
3097            } else {
3098                try {
3099                    Uri dataUri = persister.persistPart(part,
3100                            ContentUris.parseId(messageUri), null);
3101                    result = mWorkingMessage.setAttachment(WorkingMessage.IMAGE, dataUri, append);
3102                    if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3103                        log("ResizeImageResultCallback: dataUri=" + dataUri);
3104                    }
3105                } catch (MmsException e) {
3106                    result = WorkingMessage.UNKNOWN_ERROR;
3107                }
3108            }
3109
3110            handleAddAttachmentError(result, R.string.type_picture);
3111        }
3112    };
3113
3114    private void handleAddAttachmentError(final int error, final int mediaTypeStringId) {
3115        if (error == WorkingMessage.OK) {
3116            return;
3117        }
3118        Log.d(TAG, "handleAddAttachmentError: " + error);
3119
3120        runOnUiThread(new Runnable() {
3121            @Override
3122            public void run() {
3123                Resources res = getResources();
3124                String mediaType = res.getString(mediaTypeStringId);
3125                String title, message;
3126
3127                switch(error) {
3128                case WorkingMessage.UNKNOWN_ERROR:
3129                    message = res.getString(R.string.failed_to_add_media, mediaType);
3130                    Toast.makeText(ComposeMessageActivity.this, message, Toast.LENGTH_SHORT).show();
3131                    return;
3132                case WorkingMessage.UNSUPPORTED_TYPE:
3133                    title = res.getString(R.string.unsupported_media_format, mediaType);
3134                    message = res.getString(R.string.select_different_media, mediaType);
3135                    break;
3136                case WorkingMessage.MESSAGE_SIZE_EXCEEDED:
3137                    title = res.getString(R.string.exceed_message_size_limitation, mediaType);
3138                    message = res.getString(R.string.failed_to_add_media, mediaType);
3139                    break;
3140                case WorkingMessage.IMAGE_TOO_LARGE:
3141                    title = res.getString(R.string.failed_to_resize_image);
3142                    message = res.getString(R.string.resize_image_error_information);
3143                    break;
3144                default:
3145                    throw new IllegalArgumentException("unknown error " + error);
3146                }
3147
3148                MessageUtils.showErrorDialog(ComposeMessageActivity.this, title, message);
3149            }
3150        });
3151    }
3152
3153    private void addImageAsync(final Uri uri, final boolean append) {
3154        getAsyncDialog().runAsync(new Runnable() {
3155            @Override
3156            public void run() {
3157                addImage(uri, append);
3158            }
3159        }, null, R.string.adding_attachments_title);
3160    }
3161
3162    private void addImage(Uri uri, boolean append) {
3163        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3164            log("addImage: append=" + append + ", uri=" + uri);
3165        }
3166
3167        int result = mWorkingMessage.setAttachment(WorkingMessage.IMAGE, uri, append);
3168
3169        if (result == WorkingMessage.IMAGE_TOO_LARGE ||
3170            result == WorkingMessage.MESSAGE_SIZE_EXCEEDED) {
3171            if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3172                log("resize image " + uri);
3173            }
3174            MessageUtils.resizeImageAsync(ComposeMessageActivity.this,
3175                    uri, mAttachmentEditorHandler, mResizeImageCallback, append);
3176            return;
3177        }
3178        handleAddAttachmentError(result, R.string.type_picture);
3179    }
3180
3181    private void addVideoAsync(final Uri uri, final boolean append) {
3182        getAsyncDialog().runAsync(new Runnable() {
3183            @Override
3184            public void run() {
3185                addVideo(uri, append);
3186            }
3187        }, null, R.string.adding_attachments_title);
3188    }
3189
3190    private void addVideo(Uri uri, boolean append) {
3191        if (uri != null) {
3192            int result = mWorkingMessage.setAttachment(WorkingMessage.VIDEO, uri, append);
3193            handleAddAttachmentError(result, R.string.type_video);
3194        }
3195    }
3196
3197    private void addAudio(Uri uri) {
3198        int result = mWorkingMessage.setAttachment(WorkingMessage.AUDIO, uri, false);
3199        handleAddAttachmentError(result, R.string.type_audio);
3200    }
3201
3202    AsyncDialog getAsyncDialog() {
3203        if (mAsyncDialog == null) {
3204            mAsyncDialog = new AsyncDialog(this);
3205        }
3206        return mAsyncDialog;
3207    }
3208
3209    private boolean handleForwardedMessage() {
3210        Intent intent = getIntent();
3211
3212        // If this is a forwarded message, it will have an Intent extra
3213        // indicating so.  If not, bail out.
3214        if (!mForwardMessageMode) {
3215            return false;
3216        }
3217
3218        Uri uri = intent.getParcelableExtra("msg_uri");
3219
3220        if (Log.isLoggable(LogTag.APP, Log.DEBUG)) {
3221            log("" + uri);
3222        }
3223
3224        if (uri != null) {
3225            mWorkingMessage = WorkingMessage.load(this, uri);
3226            mWorkingMessage.setSubject(intent.getStringExtra("subject"), false);
3227        } else {
3228            mWorkingMessage.setText(intent.getStringExtra("sms_body"));
3229        }
3230
3231        // let's clear the message thread for forwarded messages
3232        mMsgListAdapter.changeCursor(null);
3233
3234        return true;
3235    }
3236
3237    // Handle send actions, where we're told to send a picture(s) or text.
3238    private boolean handleSendIntent() {
3239        Intent intent = getIntent();
3240        Bundle extras = intent.getExtras();
3241        if (extras == null) {
3242            return false;
3243        }
3244
3245        final String mimeType = intent.getType();
3246        String action = intent.getAction();
3247        if (Intent.ACTION_SEND.equals(action)) {
3248            if (extras.containsKey(Intent.EXTRA_STREAM)) {
3249                final Uri uri = (Uri)extras.getParcelable(Intent.EXTRA_STREAM);
3250                getAsyncDialog().runAsync(new Runnable() {
3251                    @Override
3252                    public void run() {
3253                        addAttachment(mimeType, uri, false);
3254                    }
3255                }, null, R.string.adding_attachments_title);
3256                return true;
3257            } else if (extras.containsKey(Intent.EXTRA_TEXT)) {
3258                mWorkingMessage.setText(extras.getString(Intent.EXTRA_TEXT));
3259                return true;
3260            }
3261        } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) &&
3262                extras.containsKey(Intent.EXTRA_STREAM)) {
3263            SlideshowModel slideShow = mWorkingMessage.getSlideshow();
3264            final ArrayList<Parcelable> uris = extras.getParcelableArrayList(Intent.EXTRA_STREAM);
3265            int currentSlideCount = slideShow != null ? slideShow.size() : 0;
3266            int importCount = uris.size();
3267            if (importCount + currentSlideCount > SlideshowEditor.MAX_SLIDE_NUM) {
3268                importCount = Math.min(SlideshowEditor.MAX_SLIDE_NUM - currentSlideCount,
3269                        importCount);
3270                Toast.makeText(ComposeMessageActivity.this,
3271                        getString(R.string.too_many_attachments,
3272                                SlideshowEditor.MAX_SLIDE_NUM, importCount),
3273                                Toast.LENGTH_LONG).show();
3274            }
3275
3276            // Attach all the pictures/videos asynchronously off of the UI thread.
3277            // Show a progress dialog if adding all the slides hasn't finished
3278            // within half a second.
3279            final int numberToImport = importCount;
3280            getAsyncDialog().runAsync(new Runnable() {
3281                @Override
3282                public void run() {
3283                    for (int i = 0; i < numberToImport; i++) {
3284                        Parcelable uri = uris.get(i);
3285                        addAttachment(mimeType, (Uri) uri, true);
3286                    }
3287                }
3288            }, null, R.string.adding_attachments_title);
3289            return true;
3290        }
3291        return false;
3292    }
3293
3294    // mVideoUri will look like this: content://media/external/video/media
3295    private static final String mVideoUri = Video.Media.getContentUri("external").toString();
3296    // mImageUri will look like this: content://media/external/images/media
3297    private static final String mImageUri = Images.Media.getContentUri("external").toString();
3298
3299    private void addAttachment(String type, Uri uri, boolean append) {
3300        if (uri != null) {
3301            // When we're handling Intent.ACTION_SEND_MULTIPLE, the passed in items can be
3302            // videos, and/or images, and/or some other unknown types we don't handle. When
3303            // a single attachment is "shared" the type will specify an image or video. When
3304            // there are multiple types, the type passed in is "*/*". In that case, we've got
3305            // to look at the uri to figure out if it is an image or video.
3306            boolean wildcard = "*/*".equals(type);
3307            if (type.startsWith("image/") || (wildcard && uri.toString().startsWith(mImageUri))) {
3308                addImage(uri, append);
3309            } else if (type.startsWith("video/") ||
3310                    (wildcard && uri.toString().startsWith(mVideoUri))) {
3311                addVideo(uri, append);
3312            }
3313        }
3314    }
3315
3316    private String getResourcesString(int id, String mediaName) {
3317        Resources r = getResources();
3318        return r.getString(id, mediaName);
3319    }
3320
3321    /**
3322     * draw the compose view at the bottom of the screen.
3323     */
3324    private void drawBottomPanel() {
3325        // If we are not the default SMS app, the bottom panel is always gone.
3326        if (!mIsSmsEnabled) {
3327            mBottomPanel.setVisibility(View.GONE);
3328            return;
3329        }
3330
3331        // Reset the counter for text editor.
3332        resetCounter();
3333
3334        if (mWorkingMessage.hasSlideshow()) {
3335            mBottomPanel.setVisibility(View.GONE);
3336            mAttachmentEditor.requestFocus();
3337            return;
3338        }
3339
3340        if (LOCAL_LOGV) {
3341            Log.v(TAG, "CMA.drawBottomPanel");
3342        }
3343        mBottomPanel.setVisibility(View.VISIBLE);
3344
3345        CharSequence text = mWorkingMessage.getText();
3346
3347        // TextView.setTextKeepState() doesn't like null input.
3348        if (text != null) {
3349            mTextEditor.setTextKeepState(text);
3350
3351            // Set the edit caret to the end of the text.
3352            mTextEditor.setSelection(mTextEditor.length());
3353        } else {
3354            mTextEditor.setText("");
3355        }
3356    }
3357
3358    private void hideBottomPanel() {
3359        // If we are not the default SMS app, the bottom panel is always gone.
3360        if (!mIsSmsEnabled) {
3361            mBottomPanel.setVisibility(View.GONE);
3362            return;
3363        }
3364
3365        if (LOCAL_LOGV) {
3366            Log.v(TAG, "CMA.hideBottomPanel");
3367        }
3368        mBottomPanel.setVisibility(View.INVISIBLE);
3369    }
3370
3371    private void drawTopPanel(boolean showSubjectEditor) {
3372        boolean showingAttachment = mAttachmentEditor.update(mWorkingMessage);
3373        mAttachmentEditorScrollView.setVisibility(showingAttachment ? View.VISIBLE : View.GONE);
3374        showSubjectEditor(showSubjectEditor || mWorkingMessage.hasSubject());
3375
3376        invalidateOptionsMenu();
3377    }
3378
3379    //==========================================================
3380    // Interface methods
3381    //==========================================================
3382
3383    @Override
3384    public void onClick(View v) {
3385        if ((v == mSendButtonSms || v == mSendButtonMms) && isPreparedForSending()) {
3386            confirmSendMessageIfNeeded();
3387        } else if ((v == mRecipientsPicker)) {
3388            launchMultiplePhonePicker();
3389        }
3390    }
3391
3392    private void launchMultiplePhonePicker() {
3393        Intent intent = new Intent(Intents.ACTION_GET_MULTIPLE_PHONES);
3394        intent.addCategory("android.intent.category.DEFAULT");
3395        intent.setType(Phone.CONTENT_TYPE);
3396        // We have to wait for the constructing complete.
3397        ContactList contacts = mRecipientsEditor.constructContactsFromInput(true);
3398        int urisCount = 0;
3399        Uri[] uris = new Uri[contacts.size()];
3400        urisCount = 0;
3401        for (Contact contact : contacts) {
3402            if (Contact.CONTACT_METHOD_TYPE_PHONE == contact.getContactMethodType()) {
3403                    uris[urisCount++] = contact.getPhoneUri();
3404            }
3405        }
3406        if (urisCount > 0) {
3407            intent.putExtra(Intents.EXTRA_PHONE_URIS, uris);
3408        }
3409        startActivityForResult(intent, REQUEST_CODE_PICK);
3410    }
3411
3412    @Override
3413    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
3414        if (event != null) {
3415            // if shift key is down, then we want to insert the '\n' char in the TextView;
3416            // otherwise, the default action is to send the message.
3417            if (!event.isShiftPressed() && event.getAction() == KeyEvent.ACTION_DOWN) {
3418                if (isPreparedForSending()) {
3419                    confirmSendMessageIfNeeded();
3420                }
3421                return true;
3422            }
3423            return false;
3424        }
3425
3426        if (isPreparedForSending()) {
3427            confirmSendMessageIfNeeded();
3428        }
3429        return true;
3430    }
3431
3432    private final TextWatcher mTextEditorWatcher = new TextWatcher() {
3433        @Override
3434        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
3435        }
3436
3437        @Override
3438        public void onTextChanged(CharSequence s, int start, int before, int count) {
3439            // This is a workaround for bug 1609057.  Since onUserInteraction() is
3440            // not called when the user touches the soft keyboard, we pretend it was
3441            // called when textfields changes.  This should be removed when the bug
3442            // is fixed.
3443            onUserInteraction();
3444
3445            mWorkingMessage.setText(s);
3446
3447            updateSendButtonState();
3448
3449            updateCounter(s, start, before, count);
3450
3451            ensureCorrectButtonHeight();
3452        }
3453
3454        @Override
3455        public void afterTextChanged(Editable s) {
3456        }
3457    };
3458
3459    /**
3460     * Ensures that if the text edit box extends past two lines then the
3461     * button will be shifted up to allow enough space for the character
3462     * counter string to be placed beneath it.
3463     */
3464    private void ensureCorrectButtonHeight() {
3465        int currentTextLines = mTextEditor.getLineCount();
3466        if (currentTextLines <= 2) {
3467            mTextCounter.setVisibility(View.GONE);
3468        }
3469        else if (currentTextLines > 2 && mTextCounter.getVisibility() == View.GONE) {
3470            // Making the counter invisible ensures that it is used to correctly
3471            // calculate the position of the send button even if we choose not to
3472            // display the text.
3473            mTextCounter.setVisibility(View.INVISIBLE);
3474        }
3475    }
3476
3477    private final TextWatcher mSubjectEditorWatcher = new TextWatcher() {
3478        @Override
3479        public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
3480
3481        @Override
3482        public void onTextChanged(CharSequence s, int start, int before, int count) {
3483            mWorkingMessage.setSubject(s, true);
3484            updateSendButtonState();
3485        }
3486
3487        @Override
3488        public void afterTextChanged(Editable s) { }
3489    };
3490
3491    //==========================================================
3492    // Private methods
3493    //==========================================================
3494
3495    /**
3496     * Initialize all UI elements from resources.
3497     */
3498    private void initResourceRefs() {
3499        mMsgListView = (MessageListView) findViewById(R.id.history);
3500        mMsgListView.setDivider(null);      // no divider so we look like IM conversation.
3501
3502        // called to enable us to show some padding between the message list and the
3503        // input field but when the message list is scrolled that padding area is filled
3504        // in with message content
3505        mMsgListView.setClipToPadding(false);
3506
3507        mMsgListView.setOnSizeChangedListener(new OnSizeChangedListener() {
3508            public void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
3509                if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3510                    Log.v(TAG, "onSizeChanged: w=" + width + " h=" + height +
3511                            " oldw=" + oldWidth + " oldh=" + oldHeight);
3512                }
3513
3514                if (!mMessagesAndDraftLoaded && (oldHeight-height > SMOOTH_SCROLL_THRESHOLD)) {
3515                    // perform the delayed loading now, after keyboard opens
3516                    loadMessagesAndDraft(3);
3517                }
3518
3519
3520                // The message list view changed size, most likely because the keyboard
3521                // appeared or disappeared or the user typed/deleted chars in the message
3522                // box causing it to change its height when expanding/collapsing to hold more
3523                // lines of text.
3524                smoothScrollToEnd(false, height - oldHeight);
3525            }
3526        });
3527
3528        mBottomPanel = findViewById(R.id.bottom_panel);
3529        mTextEditor = (EditText) findViewById(R.id.embedded_text_editor);
3530        mTextEditor.setOnEditorActionListener(this);
3531        mTextEditor.addTextChangedListener(mTextEditorWatcher);
3532        mTextEditor.setFilters(new InputFilter[] {
3533                new LengthFilter(MmsConfig.getMaxTextLimit())});
3534        mTextCounter = (TextView) findViewById(R.id.text_counter);
3535        mSendButtonMms = (TextView) findViewById(R.id.send_button_mms);
3536        mSendButtonSms = (ImageButton) findViewById(R.id.send_button_sms);
3537        mSendButtonMms.setOnClickListener(this);
3538        mSendButtonSms.setOnClickListener(this);
3539        mTopPanel = findViewById(R.id.recipients_subject_linear);
3540        mTopPanel.setFocusable(false);
3541        mAttachmentEditor = (AttachmentEditor) findViewById(R.id.attachment_editor);
3542        mAttachmentEditor.setHandler(mAttachmentEditorHandler);
3543        mAttachmentEditorScrollView = findViewById(R.id.attachment_editor_scroll_view);
3544    }
3545
3546    private void confirmDeleteDialog(OnClickListener listener, boolean locked) {
3547        AlertDialog.Builder builder = new AlertDialog.Builder(this);
3548        builder.setCancelable(true);
3549        builder.setMessage(locked ? R.string.confirm_delete_locked_message :
3550                    R.string.confirm_delete_message);
3551        builder.setPositiveButton(R.string.delete, listener);
3552        builder.setNegativeButton(R.string.no, null);
3553        builder.show();
3554    }
3555
3556    void undeliveredMessageDialog(long date) {
3557        String body;
3558
3559        if (date >= 0) {
3560            body = getString(R.string.undelivered_msg_dialog_body,
3561                    MessageUtils.formatTimeStampString(this, date));
3562        } else {
3563            // FIXME: we can not get sms retry time.
3564            body = getString(R.string.undelivered_sms_dialog_body);
3565        }
3566
3567        Toast.makeText(this, body, Toast.LENGTH_LONG).show();
3568    }
3569
3570    private void startMsgListQuery() {
3571        startMsgListQuery(MESSAGE_LIST_QUERY_TOKEN);
3572    }
3573
3574    private void startMsgListQuery(int token) {
3575        if (mSendDiscreetMode) {
3576            return;
3577        }
3578        Uri conversationUri = mConversation.getUri();
3579
3580        if (conversationUri == null) {
3581            log("##### startMsgListQuery: conversationUri is null, bail!");
3582            return;
3583        }
3584
3585        long threadId = mConversation.getThreadId();
3586        if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3587            log("startMsgListQuery for " + conversationUri + ", threadId=" + threadId +
3588                    " token: " + token + " mConversation: " + mConversation);
3589        }
3590
3591        // Cancel any pending queries
3592        mBackgroundQueryHandler.cancelOperation(token);
3593        try {
3594            // Kick off the new query
3595            mBackgroundQueryHandler.startQuery(
3596                    token,
3597                    threadId /* cookie */,
3598                    conversationUri,
3599                    PROJECTION,
3600                    null, null, null);
3601        } catch (SQLiteException e) {
3602            SqliteWrapper.checkSQLiteException(this, e);
3603        }
3604    }
3605
3606    private void initMessageList() {
3607        if (mMsgListAdapter != null) {
3608            return;
3609        }
3610
3611        String highlightString = getIntent().getStringExtra("highlight");
3612        Pattern highlight = highlightString == null
3613            ? null
3614            : Pattern.compile("\\b" + Pattern.quote(highlightString), Pattern.CASE_INSENSITIVE);
3615
3616        // Initialize the list adapter with a null cursor.
3617        mMsgListAdapter = new MessageListAdapter(this, null, mMsgListView, true, highlight);
3618        mMsgListAdapter.setOnDataSetChangedListener(mDataSetChangedListener);
3619        mMsgListAdapter.setMsgListItemHandler(mMessageListItemHandler);
3620        mMsgListView.setAdapter(mMsgListAdapter);
3621        mMsgListView.setItemsCanFocus(false);
3622        mMsgListView.setVisibility(mSendDiscreetMode ? View.INVISIBLE : View.VISIBLE);
3623        mMsgListView.setOnCreateContextMenuListener(mMsgListMenuCreateListener);
3624        mMsgListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
3625            @Override
3626            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
3627                if (view != null) {
3628                    ((MessageListItem) view).onMessageListItemClick();
3629                }
3630            }
3631        });
3632    }
3633
3634    /**
3635     * Load the draft
3636     *
3637     * If mWorkingMessage has content in memory that's worth saving, return false.
3638     * Otherwise, call the async operation to load draft and return true.
3639     */
3640    private boolean loadDraft() {
3641        if (mWorkingMessage.isWorthSaving()) {
3642            Log.w(TAG, "CMA.loadDraft: called with non-empty working message, bail");
3643            return false;
3644        }
3645
3646        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3647            log("CMA.loadDraft");
3648        }
3649
3650        mWorkingMessage = WorkingMessage.loadDraft(this, mConversation,
3651                new Runnable() {
3652                    @Override
3653                    public void run() {
3654                        drawTopPanel(false);
3655                        drawBottomPanel();
3656                        updateSendButtonState();
3657                    }
3658                });
3659
3660        // WorkingMessage.loadDraft() can return a new WorkingMessage object that doesn't
3661        // have its conversation set. Make sure it is set.
3662        mWorkingMessage.setConversation(mConversation);
3663
3664        return true;
3665    }
3666
3667    private void saveDraft(boolean isStopping) {
3668        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3669            LogTag.debug("saveDraft");
3670        }
3671        // TODO: Do something better here.  Maybe make discard() legal
3672        // to call twice and make isEmpty() return true if discarded
3673        // so it is caught in the clause above this one?
3674        if (mWorkingMessage.isDiscarded()) {
3675            return;
3676        }
3677
3678        if (!mWaitingForSubActivity &&
3679                !mWorkingMessage.isWorthSaving() &&
3680                (!isRecipientsEditorVisible() || recipientCount() == 0)) {
3681            if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3682                log("not worth saving, discard WorkingMessage and bail");
3683            }
3684            mWorkingMessage.discard();
3685            return;
3686        }
3687
3688        mWorkingMessage.saveDraft(isStopping);
3689
3690        if (mToastForDraftSave) {
3691            Toast.makeText(this, R.string.message_saved_as_draft,
3692                    Toast.LENGTH_SHORT).show();
3693        }
3694    }
3695
3696    private boolean isPreparedForSending() {
3697        int recipientCount = recipientCount();
3698
3699        return recipientCount > 0 && recipientCount <= MmsConfig.getRecipientLimit() &&
3700            (mWorkingMessage.hasAttachment() ||
3701                    mWorkingMessage.hasText() ||
3702                    mWorkingMessage.hasSubject());
3703    }
3704
3705    private int recipientCount() {
3706        int recipientCount;
3707
3708        // To avoid creating a bunch of invalid Contacts when the recipients
3709        // editor is in flux, we keep the recipients list empty.  So if the
3710        // recipients editor is showing, see if there is anything in it rather
3711        // than consulting the empty recipient list.
3712        if (isRecipientsEditorVisible()) {
3713            recipientCount = mRecipientsEditor.getRecipientCount();
3714        } else {
3715            recipientCount = getRecipients().size();
3716        }
3717        return recipientCount;
3718    }
3719
3720    private void sendMessage(boolean bCheckEcmMode) {
3721        if (bCheckEcmMode) {
3722            // TODO: expose this in telephony layer for SDK build
3723            String inEcm = SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE);
3724            if (Boolean.parseBoolean(inEcm)) {
3725                try {
3726                    startActivityForResult(
3727                            new Intent(TelephonyIntents.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS, null),
3728                            REQUEST_CODE_ECM_EXIT_DIALOG);
3729                    return;
3730                } catch (ActivityNotFoundException e) {
3731                    // continue to send message
3732                    Log.e(TAG, "Cannot find EmergencyCallbackModeExitDialog", e);
3733                }
3734            }
3735        }
3736
3737        if (!mSendingMessage) {
3738            if (LogTag.SEVERE_WARNING) {
3739                String sendingRecipients = mConversation.getRecipients().serialize();
3740                if (!sendingRecipients.equals(mDebugRecipients)) {
3741                    String workingRecipients = mWorkingMessage.getWorkingRecipients();
3742                    if (!mDebugRecipients.equals(workingRecipients)) {
3743                        LogTag.warnPossibleRecipientMismatch("ComposeMessageActivity.sendMessage" +
3744                                " recipients in window: \"" +
3745                                mDebugRecipients + "\" differ from recipients from conv: \"" +
3746                                sendingRecipients + "\" and working recipients: " +
3747                                workingRecipients, this);
3748                    }
3749                }
3750                sanityCheckConversation();
3751            }
3752
3753            // send can change the recipients. Make sure we remove the listeners first and then add
3754            // them back once the recipient list has settled.
3755            removeRecipientsListeners();
3756
3757            mWorkingMessage.send(mDebugRecipients);
3758
3759            mSentMessage = true;
3760            mSendingMessage = true;
3761            addRecipientsListeners();
3762
3763            mScrollOnSend = true;   // in the next onQueryComplete, scroll the list to the end.
3764        }
3765        // But bail out if we are supposed to exit after the message is sent.
3766        if (mSendDiscreetMode) {
3767            finish();
3768        }
3769    }
3770
3771    private void resetMessage() {
3772        if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3773            log("resetMessage");
3774        }
3775
3776        // Make the attachment editor hide its view.
3777        mAttachmentEditor.hideView();
3778        mAttachmentEditorScrollView.setVisibility(View.GONE);
3779
3780        // Hide the subject editor.
3781        showSubjectEditor(false);
3782
3783        // Focus to the text editor.
3784        mTextEditor.requestFocus();
3785
3786        // We have to remove the text change listener while the text editor gets cleared and
3787        // we subsequently turn the message back into SMS. When the listener is listening while
3788        // doing the clearing, it's fighting to update its counts and itself try and turn
3789        // the message one way or the other.
3790        mTextEditor.removeTextChangedListener(mTextEditorWatcher);
3791
3792        // Clear the text box.
3793        TextKeyListener.clear(mTextEditor.getText());
3794
3795        mWorkingMessage.clearConversation(mConversation, false);
3796        mWorkingMessage = WorkingMessage.createEmpty(this);
3797        mWorkingMessage.setConversation(mConversation);
3798
3799        hideRecipientEditor();
3800        drawBottomPanel();
3801
3802        // "Or not", in this case.
3803        updateSendButtonState();
3804
3805        // Our changes are done. Let the listener respond to text changes once again.
3806        mTextEditor.addTextChangedListener(mTextEditorWatcher);
3807
3808        // Close the soft on-screen keyboard if we're in landscape mode so the user can see the
3809        // conversation.
3810        if (mIsLandscape) {
3811            hideKeyboard();
3812        }
3813
3814        mLastRecipientCount = 0;
3815        mSendingMessage = false;
3816        invalidateOptionsMenu();
3817   }
3818
3819    private void hideKeyboard() {
3820        InputMethodManager inputMethodManager =
3821            (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
3822        inputMethodManager.hideSoftInputFromWindow(mTextEditor.getWindowToken(), 0);
3823    }
3824
3825    private void updateSendButtonState() {
3826        boolean enable = false;
3827        if (isPreparedForSending()) {
3828            // When the type of attachment is slideshow, we should
3829            // also hide the 'Send' button since the slideshow view
3830            // already has a 'Send' button embedded.
3831            if (!mWorkingMessage.hasSlideshow()) {
3832                enable = true;
3833            } else {
3834                mAttachmentEditor.setCanSend(true);
3835            }
3836        } else if (null != mAttachmentEditor){
3837            mAttachmentEditor.setCanSend(false);
3838        }
3839
3840        boolean requiresMms = mWorkingMessage.requiresMms();
3841        View sendButton = showSmsOrMmsSendButton(requiresMms);
3842        sendButton.setEnabled(enable);
3843        sendButton.setFocusable(enable);
3844    }
3845
3846    private long getMessageDate(Uri uri) {
3847        if (uri != null) {
3848            Cursor cursor = SqliteWrapper.query(this, mContentResolver,
3849                    uri, new String[] { Mms.DATE }, null, null, null);
3850            if (cursor != null) {
3851                try {
3852                    if ((cursor.getCount() == 1) && cursor.moveToFirst()) {
3853                        return cursor.getLong(0) * 1000L;
3854                    }
3855                } finally {
3856                    cursor.close();
3857                }
3858            }
3859        }
3860        return NO_DATE_FOR_DIALOG;
3861    }
3862
3863    private void initActivityState(Bundle bundle) {
3864        Intent intent = getIntent();
3865        if (bundle != null) {
3866            setIntent(getIntent().setAction(Intent.ACTION_VIEW));
3867            String recipients = bundle.getString(RECIPIENTS);
3868            if (LogTag.VERBOSE) log("get mConversation by recipients " + recipients);
3869            mConversation = Conversation.get(this,
3870                    ContactList.getByNumbers(recipients,
3871                            false /* don't block */, true /* replace number */), false);
3872            addRecipientsListeners();
3873            mSendDiscreetMode = bundle.getBoolean(KEY_EXIT_ON_SENT, false);
3874            mForwardMessageMode = bundle.getBoolean(KEY_FORWARDED_MESSAGE, false);
3875
3876            if (mSendDiscreetMode) {
3877                mMsgListView.setVisibility(View.INVISIBLE);
3878            }
3879            mWorkingMessage.readStateFromBundle(bundle);
3880
3881            return;
3882        }
3883
3884        // If we have been passed a thread_id, use that to find our conversation.
3885        long threadId = intent.getLongExtra(THREAD_ID, 0);
3886        if (threadId > 0) {
3887            if (LogTag.VERBOSE) log("get mConversation by threadId " + threadId);
3888            mConversation = Conversation.get(this, threadId, false);
3889        } else {
3890            Uri intentData = intent.getData();
3891            if (intentData != null) {
3892                // try to get a conversation based on the data URI passed to our intent.
3893                if (LogTag.VERBOSE) log("get mConversation by intentData " + intentData);
3894                mConversation = Conversation.get(this, intentData, false);
3895                mWorkingMessage.setText(getBody(intentData));
3896            } else {
3897                // special intent extra parameter to specify the address
3898                String address = intent.getStringExtra("address");
3899                if (!TextUtils.isEmpty(address)) {
3900                    if (LogTag.VERBOSE) log("get mConversation by address " + address);
3901                    mConversation = Conversation.get(this, ContactList.getByNumbers(address,
3902                            false /* don't block */, true /* replace number */), false);
3903                } else {
3904                    if (LogTag.VERBOSE) log("create new conversation");
3905                    mConversation = Conversation.createNew(this);
3906                }
3907            }
3908        }
3909        addRecipientsListeners();
3910        updateThreadIdIfRunning();
3911
3912        mSendDiscreetMode = intent.getBooleanExtra(KEY_EXIT_ON_SENT, false);
3913        mForwardMessageMode = intent.getBooleanExtra(KEY_FORWARDED_MESSAGE, false);
3914        if (mSendDiscreetMode) {
3915            mMsgListView.setVisibility(View.INVISIBLE);
3916        }
3917        if (intent.hasExtra("sms_body")) {
3918            mWorkingMessage.setText(intent.getStringExtra("sms_body"));
3919        }
3920        mWorkingMessage.setSubject(intent.getStringExtra("subject"), false);
3921    }
3922
3923    private void initFocus() {
3924        if (!mIsKeyboardOpen) {
3925            return;
3926        }
3927
3928        // If the recipients editor is visible, there is nothing in it,
3929        // and the text editor is not already focused, focus the
3930        // recipients editor.
3931        if (isRecipientsEditorVisible()
3932                && TextUtils.isEmpty(mRecipientsEditor.getText())
3933                && !mTextEditor.isFocused()) {
3934            mRecipientsEditor.requestFocus();
3935            return;
3936        }
3937
3938        // If we decided not to focus the recipients editor, focus the text editor.
3939        mTextEditor.requestFocus();
3940    }
3941
3942    private final MessageListAdapter.OnDataSetChangedListener
3943                    mDataSetChangedListener = new MessageListAdapter.OnDataSetChangedListener() {
3944        @Override
3945        public void onDataSetChanged(MessageListAdapter adapter) {
3946        }
3947
3948        @Override
3949        public void onContentChanged(MessageListAdapter adapter) {
3950            startMsgListQuery();
3951        }
3952    };
3953
3954    /**
3955     * smoothScrollToEnd will scroll the message list to the bottom if the list is already near
3956     * the bottom. Typically this is called to smooth scroll a newly received message into view.
3957     * It's also called when sending to scroll the list to the bottom, regardless of where it is,
3958     * so the user can see the just sent message. This function is also called when the message
3959     * list view changes size because the keyboard state changed or the compose message field grew.
3960     *
3961     * @param force always scroll to the bottom regardless of current list position
3962     * @param listSizeChange the amount the message list view size has vertically changed
3963     */
3964    private void smoothScrollToEnd(boolean force, int listSizeChange) {
3965        int lastItemVisible = mMsgListView.getLastVisiblePosition();
3966        int lastItemInList = mMsgListAdapter.getCount() - 1;
3967        if (lastItemVisible < 0 || lastItemInList < 0) {
3968            if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3969                Log.v(TAG, "smoothScrollToEnd: lastItemVisible=" + lastItemVisible +
3970                        ", lastItemInList=" + lastItemInList +
3971                        ", mMsgListView not ready");
3972            }
3973            return;
3974        }
3975
3976        View lastChildVisible =
3977                mMsgListView.getChildAt(lastItemVisible - mMsgListView.getFirstVisiblePosition());
3978        int lastVisibleItemBottom = 0;
3979        int lastVisibleItemHeight = 0;
3980        if (lastChildVisible != null) {
3981            lastVisibleItemBottom = lastChildVisible.getBottom();
3982            lastVisibleItemHeight = lastChildVisible.getHeight();
3983        }
3984
3985        if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
3986            Log.v(TAG, "smoothScrollToEnd newPosition: " + lastItemInList +
3987                    " mLastSmoothScrollPosition: " + mLastSmoothScrollPosition +
3988                    " first: " + mMsgListView.getFirstVisiblePosition() +
3989                    " lastItemVisible: " + lastItemVisible +
3990                    " lastVisibleItemBottom: " + lastVisibleItemBottom +
3991                    " lastVisibleItemBottom + listSizeChange: " +
3992                    (lastVisibleItemBottom + listSizeChange) +
3993                    " mMsgListView.getHeight() - mMsgListView.getPaddingBottom(): " +
3994                    (mMsgListView.getHeight() - mMsgListView.getPaddingBottom()) +
3995                    " listSizeChange: " + listSizeChange);
3996        }
3997        // Only scroll if the list if we're responding to a newly sent message (force == true) or
3998        // the list is already scrolled to the end. This code also has to handle the case where
3999        // the listview has changed size (from the keyboard coming up or down or the message entry
4000        // field growing/shrinking) and it uses that grow/shrink factor in listSizeChange to
4001        // compute whether the list was at the end before the resize took place.
4002        // For example, when the keyboard comes up, listSizeChange will be negative, something
4003        // like -524. The lastChild listitem's bottom value will be the old value before the
4004        // keyboard became visible but the size of the list will have changed. The test below
4005        // add listSizeChange to bottom to figure out if the old position was already scrolled
4006        // to the bottom. We also scroll the list if the last item is taller than the size of the
4007        // list. This happens when the keyboard is up and the last item is an mms with an
4008        // attachment thumbnail, such as picture. In this situation, we want to scroll the list so
4009        // the bottom of the thumbnail is visible and the top of the item is scroll off the screen.
4010        int listHeight = mMsgListView.getHeight();
4011        boolean lastItemTooTall = lastVisibleItemHeight > listHeight;
4012        boolean willScroll = force ||
4013                ((listSizeChange != 0 || lastItemInList != mLastSmoothScrollPosition) &&
4014                lastVisibleItemBottom + listSizeChange <=
4015                    listHeight - mMsgListView.getPaddingBottom());
4016        if (willScroll || (lastItemTooTall && lastItemInList == lastItemVisible)) {
4017            if (Math.abs(listSizeChange) > SMOOTH_SCROLL_THRESHOLD) {
4018                // When the keyboard comes up, the window manager initiates a cross fade
4019                // animation that conflicts with smooth scroll. Handle that case by jumping the
4020                // list directly to the end.
4021                if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
4022                    Log.v(TAG, "keyboard state changed. setSelection=" + lastItemInList);
4023                }
4024                if (lastItemTooTall) {
4025                    // If the height of the last item is taller than the whole height of the list,
4026                    // we need to scroll that item so that its top is negative or above the top of
4027                    // the list. That way, the bottom of the last item will be exposed above the
4028                    // keyboard.
4029                    mMsgListView.setSelectionFromTop(lastItemInList,
4030                            listHeight - lastVisibleItemHeight);
4031                } else {
4032                    mMsgListView.setSelection(lastItemInList);
4033                }
4034            } else if (lastItemInList - lastItemVisible > MAX_ITEMS_TO_INVOKE_SCROLL_SHORTCUT) {
4035                if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
4036                    Log.v(TAG, "too many to scroll, setSelection=" + lastItemInList);
4037                }
4038                mMsgListView.setSelection(lastItemInList);
4039            } else {
4040                if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
4041                    Log.v(TAG, "smooth scroll to " + lastItemInList);
4042                }
4043                if (lastItemTooTall) {
4044                    // If the height of the last item is taller than the whole height of the list,
4045                    // we need to scroll that item so that its top is negative or above the top of
4046                    // the list. That way, the bottom of the last item will be exposed above the
4047                    // keyboard. We should use smoothScrollToPositionFromTop here, but it doesn't
4048                    // seem to work -- the list ends up scrolling to a random position.
4049                    mMsgListView.setSelectionFromTop(lastItemInList,
4050                            listHeight - lastVisibleItemHeight);
4051                } else {
4052                    mMsgListView.smoothScrollToPosition(lastItemInList);
4053                }
4054                mLastSmoothScrollPosition = lastItemInList;
4055            }
4056        }
4057    }
4058
4059    private final class BackgroundQueryHandler extends ConversationQueryHandler {
4060        public BackgroundQueryHandler(ContentResolver contentResolver) {
4061            super(contentResolver);
4062        }
4063
4064        @Override
4065        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
4066            switch(token) {
4067                case MESSAGE_LIST_QUERY_TOKEN:
4068                    mConversation.blockMarkAsRead(false);
4069
4070                    // check consistency between the query result and 'mConversation'
4071                    long tid = (Long) cookie;
4072
4073                    if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
4074                        log("##### onQueryComplete: msg history result for threadId " + tid);
4075                    }
4076                    if (tid != mConversation.getThreadId()) {
4077                        log("onQueryComplete: msg history query result is for threadId " +
4078                                tid + ", but mConversation has threadId " +
4079                                mConversation.getThreadId() + " starting a new query");
4080                        if (cursor != null) {
4081                            cursor.close();
4082                        }
4083                        startMsgListQuery();
4084                        return;
4085                    }
4086
4087                    // check consistency b/t mConversation & mWorkingMessage.mConversation
4088                    ComposeMessageActivity.this.sanityCheckConversation();
4089
4090                    int newSelectionPos = -1;
4091                    long targetMsgId = getIntent().getLongExtra("select_id", -1);
4092                    if (targetMsgId != -1) {
4093                        if (cursor != null) {
4094                            cursor.moveToPosition(-1);
4095                            while (cursor.moveToNext()) {
4096                                long msgId = cursor.getLong(COLUMN_ID);
4097                                if (msgId == targetMsgId) {
4098                                    newSelectionPos = cursor.getPosition();
4099                                    break;
4100                                }
4101                            }
4102                        }
4103                    } else if (mSavedScrollPosition != -1) {
4104                        // mSavedScrollPosition is set when this activity pauses. If equals maxint,
4105                        // it means the message list was scrolled to the end. Meanwhile, messages
4106                        // could have been received. When the activity resumes and we were
4107                        // previously scrolled to the end, jump the list so any new messages are
4108                        // visible.
4109                        if (mSavedScrollPosition == Integer.MAX_VALUE) {
4110                            int cnt = mMsgListAdapter.getCount();
4111                            if (cnt > 0) {
4112                                // Have to wait until the adapter is loaded before jumping to
4113                                // the end.
4114                                newSelectionPos = cnt - 1;
4115                                mSavedScrollPosition = -1;
4116                            }
4117                        } else {
4118                            // remember the saved scroll position before the activity is paused.
4119                            // reset it after the message list query is done
4120                            newSelectionPos = mSavedScrollPosition;
4121                            mSavedScrollPosition = -1;
4122                        }
4123                    }
4124
4125                    mMsgListAdapter.changeCursor(cursor);
4126
4127                    if (newSelectionPos != -1) {
4128                        mMsgListView.setSelection(newSelectionPos);     // jump the list to the pos
4129                    } else {
4130                        int count = mMsgListAdapter.getCount();
4131                        long lastMsgId = 0;
4132                        if (cursor != null && count > 0) {
4133                            cursor.moveToLast();
4134                            lastMsgId = cursor.getLong(COLUMN_ID);
4135                        }
4136                        // mScrollOnSend is set when we send a message. We always want to scroll
4137                        // the message list to the end when we send a message, but have to wait
4138                        // until the DB has changed. We also want to scroll the list when a
4139                        // new message has arrived.
4140                        smoothScrollToEnd(mScrollOnSend || lastMsgId != mLastMessageId, 0);
4141                        mLastMessageId = lastMsgId;
4142                        mScrollOnSend = false;
4143                    }
4144                    // Adjust the conversation's message count to match reality. The
4145                    // conversation's message count is eventually used in
4146                    // WorkingMessage.clearConversation to determine whether to delete
4147                    // the conversation or not.
4148                    mConversation.setMessageCount(mMsgListAdapter.getCount());
4149
4150                    // Once we have completed the query for the message history, if
4151                    // there is nothing in the cursor and we are not composing a new
4152                    // message, we must be editing a draft in a new conversation (unless
4153                    // mSentMessage is true).
4154                    // Show the recipients editor to give the user a chance to add
4155                    // more people before the conversation begins.
4156                    if (cursor != null && cursor.getCount() == 0
4157                            && !isRecipientsEditorVisible() && !mSentMessage) {
4158                        initRecipientsEditor();
4159                    }
4160
4161                    // FIXME: freshing layout changes the focused view to an unexpected
4162                    // one, set it back to TextEditor forcely.
4163                    mTextEditor.requestFocus();
4164
4165                    invalidateOptionsMenu();    // some menu items depend on the adapter's count
4166                    return;
4167
4168                case ConversationList.HAVE_LOCKED_MESSAGES_TOKEN:
4169                    @SuppressWarnings("unchecked")
4170                    ArrayList<Long> threadIds = (ArrayList<Long>)cookie;
4171                    ConversationList.confirmDeleteThreadDialog(
4172                            new ConversationList.DeleteThreadListener(threadIds,
4173                                mBackgroundQueryHandler, ComposeMessageActivity.this),
4174                            threadIds,
4175                            cursor != null && cursor.getCount() > 0,
4176                            ComposeMessageActivity.this);
4177                    if (cursor != null) {
4178                        cursor.close();
4179                    }
4180                    break;
4181
4182                case MESSAGE_LIST_QUERY_AFTER_DELETE_TOKEN:
4183                    // check consistency between the query result and 'mConversation'
4184                    tid = (Long) cookie;
4185
4186                    if (LogTag.VERBOSE || Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
4187                        log("##### onQueryComplete (after delete): msg history result for threadId "
4188                                + tid);
4189                    }
4190                    if (cursor == null) {
4191                        return;
4192                    }
4193                    if (tid > 0 && cursor.getCount() == 0) {
4194                        // We just deleted the last message and the thread will get deleted
4195                        // by a trigger in the database. Clear the threadId so next time we
4196                        // need the threadId a new thread will get created.
4197                        log("##### MESSAGE_LIST_QUERY_AFTER_DELETE_TOKEN clearing thread id: "
4198                                + tid);
4199                        Conversation conv = Conversation.get(ComposeMessageActivity.this, tid,
4200                                false);
4201                        if (conv != null) {
4202                            conv.clearThreadId();
4203                            conv.setDraftState(false);
4204                        }
4205                        // The last message in this converation was just deleted. Send the user
4206                        // to the conversation list.
4207                        exitComposeMessageActivity(new Runnable() {
4208                            @Override
4209                            public void run() {
4210                                goToConversationList();
4211                            }
4212                        });
4213                    }
4214                    cursor.close();
4215            }
4216        }
4217
4218        @Override
4219        protected void onDeleteComplete(int token, Object cookie, int result) {
4220            super.onDeleteComplete(token, cookie, result);
4221            switch(token) {
4222                case ConversationList.DELETE_CONVERSATION_TOKEN:
4223                    mConversation.setMessageCount(0);
4224                    // fall through
4225                case DELETE_MESSAGE_TOKEN:
4226                    if (cookie instanceof Boolean && ((Boolean)cookie).booleanValue()) {
4227                        // If we just deleted the last message, reset the saved id.
4228                        mLastMessageId = 0;
4229                    }
4230                    // Update the notification for new messages since they
4231                    // may be deleted.
4232                    MessagingNotification.nonBlockingUpdateNewMessageIndicator(
4233                            ComposeMessageActivity.this, MessagingNotification.THREAD_NONE, false);
4234                    // Update the notification for failed messages since they
4235                    // may be deleted.
4236                    updateSendFailedNotification();
4237                    break;
4238            }
4239            // If we're deleting the whole conversation, throw away
4240            // our current working message and bail.
4241            if (token == ConversationList.DELETE_CONVERSATION_TOKEN) {
4242                ContactList recipients = mConversation.getRecipients();
4243                mWorkingMessage.discard();
4244
4245                // Remove any recipients referenced by this single thread from the
4246                // contacts cache. It's possible for two or more threads to reference
4247                // the same contact. That's ok if we remove it. We'll recreate that contact
4248                // when we init all Conversations below.
4249                if (recipients != null) {
4250                    for (Contact contact : recipients) {
4251                        contact.removeFromCache();
4252                    }
4253                }
4254
4255                // Make sure the conversation cache reflects the threads in the DB.
4256                Conversation.init(ComposeMessageActivity.this);
4257                finish();
4258            } else if (token == DELETE_MESSAGE_TOKEN) {
4259                // Check to see if we just deleted the last message
4260                startMsgListQuery(MESSAGE_LIST_QUERY_AFTER_DELETE_TOKEN);
4261            }
4262
4263            MmsWidgetProvider.notifyDatasetChanged(getApplicationContext());
4264        }
4265    }
4266
4267    @Override
4268    public void onUpdate(final Contact updated) {
4269        // Using an existing handler for the post, rather than conjuring up a new one.
4270        mMessageListItemHandler.post(new Runnable() {
4271            @Override
4272            public void run() {
4273                ContactList recipients = isRecipientsEditorVisible() ?
4274                        mRecipientsEditor.constructContactsFromInput(false) : getRecipients();
4275                if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
4276                    log("[CMA] onUpdate contact updated: " + updated);
4277                    log("[CMA] onUpdate recipients: " + recipients);
4278                }
4279                updateTitle(recipients);
4280
4281                // The contact information for one (or more) of the recipients has changed.
4282                // Rebuild the message list so each MessageItem will get the last contact info.
4283                ComposeMessageActivity.this.mMsgListAdapter.notifyDataSetChanged();
4284
4285                // Don't do this anymore. When we're showing chips, we don't want to switch from
4286                // chips to text.
4287//                if (mRecipientsEditor != null) {
4288//                    mRecipientsEditor.populate(recipients);
4289//                }
4290            }
4291        });
4292    }
4293
4294    private void addRecipientsListeners() {
4295        Contact.addListener(this);
4296    }
4297
4298    private void removeRecipientsListeners() {
4299        Contact.removeListener(this);
4300    }
4301
4302    public static Intent createIntent(Context context, long threadId) {
4303        Intent intent = new Intent(context, ComposeMessageActivity.class);
4304
4305        if (threadId > 0) {
4306            intent.setData(Conversation.getUri(threadId));
4307        }
4308
4309        return intent;
4310    }
4311
4312    private String getBody(Uri uri) {
4313        if (uri == null) {
4314            return null;
4315        }
4316        String urlStr = uri.getSchemeSpecificPart();
4317        if (!urlStr.contains("?")) {
4318            return null;
4319        }
4320        urlStr = urlStr.substring(urlStr.indexOf('?') + 1);
4321        String[] params = urlStr.split("&");
4322        for (String p : params) {
4323            if (p.startsWith("body=")) {
4324                try {
4325                    return URLDecoder.decode(p.substring(5), "UTF-8");
4326                } catch (UnsupportedEncodingException e) { }
4327            }
4328        }
4329        return null;
4330    }
4331
4332    private void updateThreadIdIfRunning() {
4333        if (mIsRunning && mConversation != null) {
4334            if (DEBUG) {
4335                Log.v(TAG, "updateThreadIdIfRunning: threadId: " +
4336                        mConversation.getThreadId());
4337            }
4338            MessagingNotification.setCurrentlyDisplayedThreadId(mConversation.getThreadId());
4339        } else {
4340            if (DEBUG) {
4341                Log.v(TAG, "updateThreadIdIfRunning: mIsRunning: " + mIsRunning +
4342                        " mConversation: " + mConversation);
4343            }
4344        }
4345        // If we're not running, but resume later, the current thread ID will be set in onResume()
4346    }
4347}
4348