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