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