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