MessageList.java revision 479b22a2f8966b63789c89e878b615ebd53708c0
1/* 2 * Copyright (C) 2009 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.email.activity; 18 19import com.android.email.Controller; 20import com.android.email.Email; 21import com.android.email.R; 22import com.android.email.Utility; 23import com.android.email.activity.setup.AccountSettings; 24import com.android.email.mail.AuthenticationFailedException; 25import com.android.email.mail.CertificateValidationException; 26import com.android.email.mail.MessagingException; 27import com.android.email.provider.EmailContent; 28import com.android.email.provider.EmailContent.Account; 29import com.android.email.provider.EmailContent.AccountColumns; 30import com.android.email.provider.EmailContent.Mailbox; 31import com.android.email.provider.EmailContent.MailboxColumns; 32import com.android.email.provider.EmailContent.MessageColumns; 33import com.android.email.service.MailService; 34 35import android.app.ListActivity; 36import android.app.NotificationManager; 37import android.content.ContentResolver; 38import android.content.ContentUris; 39import android.content.Context; 40import android.content.Intent; 41import android.content.res.ColorStateList; 42import android.content.res.Resources; 43import android.content.res.TypedArray; 44import android.content.res.Resources.Theme; 45import android.database.Cursor; 46import android.graphics.Typeface; 47import android.graphics.drawable.Drawable; 48import android.net.Uri; 49import android.os.AsyncTask; 50import android.os.Bundle; 51import android.os.Handler; 52import android.os.SystemClock; 53import android.util.Log; 54import android.view.ContextMenu; 55import android.view.LayoutInflater; 56import android.view.Menu; 57import android.view.MenuItem; 58import android.view.View; 59import android.view.ViewGroup; 60import android.view.Window; 61import android.view.ContextMenu.ContextMenuInfo; 62import android.view.View.OnClickListener; 63import android.view.animation.AnimationUtils; 64import android.widget.AdapterView; 65import android.widget.Button; 66import android.widget.CursorAdapter; 67import android.widget.ImageView; 68import android.widget.ListView; 69import android.widget.ProgressBar; 70import android.widget.TextView; 71import android.widget.Toast; 72import android.widget.AdapterView.OnItemClickListener; 73 74import java.util.Date; 75import java.util.HashSet; 76import java.util.Set; 77import java.util.Timer; 78import java.util.TimerTask; 79 80public class MessageList extends ListActivity implements OnItemClickListener, OnClickListener { 81 // Intent extras (internal to this activity) 82 private static final String EXTRA_ACCOUNT_ID = "com.android.email.activity._ACCOUNT_ID"; 83 private static final String EXTRA_MAILBOX_TYPE = "com.android.email.activity.MAILBOX_TYPE"; 84 private static final String EXTRA_MAILBOX_ID = "com.android.email.activity.MAILBOX_ID"; 85 private static final String STATE_SELECTED_ITEM_TOP = 86 "com.android.email.activity.MessageList.selectedItemTop"; 87 private static final String STATE_SELECTED_POSITION = 88 "com.android.email.activity.MessageList.selectedPosition"; 89 90 // UI support 91 private ListView mListView; 92 private View mMultiSelectPanel; 93 private Button mReadUnreadButton; 94 private Button mFavoriteButton; 95 private Button mDeleteButton; 96 private View mListFooterView; 97 private TextView mListFooterText; 98 private View mListFooterProgress; 99 private TextView mErrorBanner; 100 101 private static final int LIST_FOOTER_MODE_NONE = 0; 102 private static final int LIST_FOOTER_MODE_REFRESH = 1; 103 private static final int LIST_FOOTER_MODE_MORE = 2; 104 private static final int LIST_FOOTER_MODE_SEND = 3; 105 private int mListFooterMode; 106 107 private MessageListAdapter mListAdapter; 108 private MessageListHandler mHandler = new MessageListHandler(); 109 private Controller mController = Controller.getInstance(getApplication()); 110 private ControllerResults mControllerCallback = new ControllerResults(); 111 private TextView mLeftTitle; 112 private TextView mRightTitle; 113 private ProgressBar mProgressIcon; 114 115 private static final int[] mColorChipResIds = new int[] { 116 R.drawable.appointment_indicator_leftside_1, 117 R.drawable.appointment_indicator_leftside_2, 118 R.drawable.appointment_indicator_leftside_3, 119 R.drawable.appointment_indicator_leftside_4, 120 R.drawable.appointment_indicator_leftside_5, 121 R.drawable.appointment_indicator_leftside_6, 122 R.drawable.appointment_indicator_leftside_7, 123 R.drawable.appointment_indicator_leftside_8, 124 R.drawable.appointment_indicator_leftside_9, 125 R.drawable.appointment_indicator_leftside_10, 126 R.drawable.appointment_indicator_leftside_11, 127 R.drawable.appointment_indicator_leftside_12, 128 R.drawable.appointment_indicator_leftside_13, 129 R.drawable.appointment_indicator_leftside_14, 130 R.drawable.appointment_indicator_leftside_15, 131 R.drawable.appointment_indicator_leftside_16, 132 R.drawable.appointment_indicator_leftside_17, 133 R.drawable.appointment_indicator_leftside_18, 134 R.drawable.appointment_indicator_leftside_19, 135 R.drawable.appointment_indicator_leftside_20, 136 R.drawable.appointment_indicator_leftside_21, 137 }; 138 139 // DB access 140 private ContentResolver mResolver; 141 private long mMailboxId; 142 private LoadMessagesTask mLoadMessagesTask; 143 private FindMailboxTask mFindMailboxTask; 144 private SetTitleTask mSetTitleTask; 145 private SetFooterTask mSetFooterTask; 146 147 public final static String[] MAILBOX_FIND_INBOX_PROJECTION = new String[] { 148 EmailContent.RECORD_ID, MailboxColumns.TYPE, MailboxColumns.FLAG_VISIBLE 149 }; 150 151 private static final int MAILBOX_NAME_COLUMN_ID = 0; 152 private static final int MAILBOX_NAME_COLUMN_ACCOUNT_KEY = 1; 153 private static final int MAILBOX_NAME_COLUMN_TYPE = 2; 154 private static final String[] MAILBOX_NAME_PROJECTION = new String[] { 155 MailboxColumns.DISPLAY_NAME, MailboxColumns.ACCOUNT_KEY, 156 MailboxColumns.TYPE}; 157 158 private static final int ACCOUNT_DISPLAY_NAME_COLUMN_ID = 0; 159 private static final String[] ACCOUNT_NAME_PROJECTION = new String[] { 160 AccountColumns.DISPLAY_NAME }; 161 162 private static final String ID_SELECTION = EmailContent.RECORD_ID + "=?"; 163 164 private Boolean mPushModeMailbox = null; 165 private int mSavedItemTop = 0; 166 private int mSavedItemPosition = -1; 167 private boolean mCanAutoRefresh = false; 168 169 /** 170 * Open a specific mailbox. 171 * 172 * TODO This should just shortcut to a more generic version that can accept a list of 173 * accounts/mailboxes (e.g. merged inboxes). 174 * 175 * @param context 176 * @param id mailbox key 177 */ 178 public static void actionHandleMailbox(Context context, long id) { 179 Intent intent = new Intent(context, MessageList.class); 180 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 181 intent.putExtra(EXTRA_MAILBOX_ID, id); 182 context.startActivity(intent); 183 } 184 185 /** 186 * Open a specific mailbox by account & type 187 * 188 * @param context The caller's context (for generating an intent) 189 * @param accountId The account to open 190 * @param mailboxType the type of mailbox to open (e.g. @see EmailContent.Mailbox.TYPE_INBOX) 191 */ 192 public static void actionHandleAccount(Context context, long accountId, int mailboxType) { 193 Intent intent = new Intent(context, MessageList.class); 194 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 195 intent.putExtra(EXTRA_ACCOUNT_ID, accountId); 196 intent.putExtra(EXTRA_MAILBOX_TYPE, mailboxType); 197 context.startActivity(intent); 198 } 199 200 /** 201 * Return an intent to open a specific mailbox by account & type. It will also clear 202 * notifications. 203 * 204 * @param context The caller's context (for generating an intent) 205 * @param accountId The account to open, or -1 206 * @param mailboxId the ID of the mailbox to open, or -1 207 * @param mailboxType the type of mailbox to open (e.g. @see Mailbox.TYPE_INBOX) or -1 208 */ 209 public static Intent actionHandleAccountIntent(Context context, long accountId, 210 long mailboxId, int mailboxType) { 211 Intent intent = new Intent(context, MessageList.class); 212 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 213 intent.putExtra(EXTRA_ACCOUNT_ID, accountId); 214 intent.putExtra(EXTRA_MAILBOX_ID, mailboxId); 215 intent.putExtra(EXTRA_MAILBOX_TYPE, mailboxType); 216 return intent; 217 } 218 219 /** 220 * Used for generating lightweight (Uri-only) intents. 221 * 222 * @param context Calling context for building the intent 223 * @param accountId The account of interest 224 * @param mailboxType The folder name to open (typically Mailbox.TYPE_INBOX) 225 * @return an Intent which can be used to view that account 226 */ 227 public static Intent actionHandleAccountUriIntent(Context context, long accountId, 228 int mailboxType) { 229 Intent i = actionHandleAccountIntent(context, accountId, -1, mailboxType); 230 i.removeExtra(EXTRA_ACCOUNT_ID); 231 Uri uri = ContentUris.withAppendedId(Account.CONTENT_URI, accountId); 232 i.setData(uri); 233 return i; 234 } 235 236 @Override 237 public void onCreate(Bundle icicle) { 238 super.onCreate(icicle); 239 240 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 241 setContentView(R.layout.message_list); 242 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, 243 R.layout.list_title); 244 245 mCanAutoRefresh = true; 246 mListView = getListView(); 247 mMultiSelectPanel = findViewById(R.id.footer_organize); 248 mReadUnreadButton = (Button) findViewById(R.id.btn_read_unread); 249 mFavoriteButton = (Button) findViewById(R.id.btn_multi_favorite); 250 mDeleteButton = (Button) findViewById(R.id.btn_multi_delete); 251 mLeftTitle = (TextView) findViewById(R.id.title_left_text); 252 mRightTitle = (TextView) findViewById(R.id.title_right_text); 253 mProgressIcon = (ProgressBar) findViewById(R.id.title_progress_icon); 254 mErrorBanner = (TextView) findViewById(R.id.connection_error_text); 255 256 mReadUnreadButton.setOnClickListener(this); 257 mFavoriteButton.setOnClickListener(this); 258 mDeleteButton.setOnClickListener(this); 259 260 mListView.setOnItemClickListener(this); 261 mListView.setItemsCanFocus(false); 262 registerForContextMenu(mListView); 263 264 mListAdapter = new MessageListAdapter(this); 265 setListAdapter(mListAdapter); 266 267 mResolver = getContentResolver(); 268 269 // TODO extend this to properly deal with multiple mailboxes, cursor, etc. 270 271 // Select 'by id' or 'by type' or 'by uri' mode and launch appropriate queries 272 273 mMailboxId = getIntent().getLongExtra(EXTRA_MAILBOX_ID, -1); 274 if (mMailboxId != -1) { 275 // Specific mailbox ID was provided - go directly to it 276 mSetTitleTask = new SetTitleTask(mMailboxId); 277 mSetTitleTask.execute(); 278 mLoadMessagesTask = new LoadMessagesTask(mMailboxId, -1); 279 mLoadMessagesTask.execute(); 280 addFooterView(mMailboxId, -1, -1); 281 } else { 282 long accountId = -1; 283 int mailboxType = getIntent().getIntExtra(EXTRA_MAILBOX_TYPE, Mailbox.TYPE_INBOX); 284 Uri uri = getIntent().getData(); 285 if (uri != null 286 && "content".equals(uri.getScheme()) 287 && EmailContent.AUTHORITY.equals(uri.getAuthority())) { 288 // A content URI was provided - try to look up the account 289 String accountIdString = uri.getPathSegments().get(1); 290 if (accountIdString != null) { 291 accountId = Long.parseLong(accountIdString); 292 } 293 mFindMailboxTask = new FindMailboxTask(accountId, mailboxType, false); 294 mFindMailboxTask.execute(); 295 } else { 296 // Go by account id + type 297 accountId = getIntent().getLongExtra(EXTRA_ACCOUNT_ID, -1); 298 mFindMailboxTask = new FindMailboxTask(accountId, mailboxType, true); 299 mFindMailboxTask.execute(); 300 } 301 addFooterView(-1, accountId, mailboxType); 302 } 303 // TODO set title to "account > mailbox (#unread)" 304 } 305 306 @Override 307 public void onPause() { 308 super.onPause(); 309 mController.removeResultCallback(mControllerCallback); 310 } 311 312 @Override 313 public void onResume() { 314 super.onResume(); 315 mController.addResultCallback(mControllerCallback); 316 317 // clear notifications here 318 NotificationManager notificationManager = (NotificationManager) 319 getSystemService(Context.NOTIFICATION_SERVICE); 320 notificationManager.cancel(MailService.NEW_MESSAGE_NOTIFICATION_ID); 321 restoreListPosition(); 322 autoRefreshStaleMailbox(); 323 } 324 325 @Override 326 protected void onDestroy() { 327 super.onDestroy(); 328 329 if (mLoadMessagesTask != null && 330 mLoadMessagesTask.getStatus() != LoadMessagesTask.Status.FINISHED) { 331 mLoadMessagesTask.cancel(true); 332 mLoadMessagesTask = null; 333 } 334 if (mFindMailboxTask != null && 335 mFindMailboxTask.getStatus() != FindMailboxTask.Status.FINISHED) { 336 mFindMailboxTask.cancel(true); 337 mFindMailboxTask = null; 338 } 339 if (mSetTitleTask != null && 340 mSetTitleTask.getStatus() != SetTitleTask.Status.FINISHED) { 341 mSetTitleTask.cancel(true); 342 mSetTitleTask = null; 343 } 344 if (mSetFooterTask != null && 345 mSetFooterTask.getStatus() != SetTitleTask.Status.FINISHED) { 346 mSetFooterTask.cancel(true); 347 mSetFooterTask = null; 348 } 349 } 350 351 @Override 352 protected void onSaveInstanceState(Bundle outState) { 353 super.onSaveInstanceState(outState); 354 saveListPosition(); 355 outState.putInt(STATE_SELECTED_POSITION, mSavedItemPosition); 356 outState.putInt(STATE_SELECTED_ITEM_TOP, mSavedItemTop); 357 } 358 359 @Override 360 protected void onRestoreInstanceState(Bundle savedInstanceState) { 361 super.onRestoreInstanceState(savedInstanceState); 362 mSavedItemTop = savedInstanceState.getInt(STATE_SELECTED_ITEM_TOP, 0); 363 mSavedItemPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION, -1); 364 } 365 366 private void saveListPosition() { 367 mSavedItemPosition = getListView().getSelectedItemPosition(); 368 if (mSavedItemPosition >= 0) { 369 mSavedItemTop = getListView().getSelectedView().getTop(); 370 } else { 371 mSavedItemPosition = getListView().getFirstVisiblePosition(); 372 if (mSavedItemPosition >= 0) { 373 mSavedItemTop = 0; 374 View topChild = getListView().getChildAt(0); 375 if (topChild != null) { 376 mSavedItemTop = topChild.getTop(); 377 } 378 } 379 } 380 } 381 382 private void restoreListPosition() { 383 if (mSavedItemPosition >= 0 && mSavedItemPosition < getListView().getCount()) { 384 getListView().setSelectionFromTop(mSavedItemPosition, mSavedItemTop); 385 mSavedItemPosition = -1; 386 mSavedItemTop = 0; 387 } 388 } 389 390 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 391 if (view != mListFooterView) { 392 MessageListItem itemView = (MessageListItem) view; 393 onOpenMessage(id, itemView.mMailboxId); 394 } else { 395 doFooterClick(); 396 } 397 } 398 399 public void onClick(View v) { 400 switch (v.getId()) { 401 case R.id.btn_read_unread: 402 onMultiToggleRead(mListAdapter.getSelectedSet()); 403 break; 404 case R.id.btn_multi_favorite: 405 onMultiToggleFavorite(mListAdapter.getSelectedSet()); 406 break; 407 case R.id.btn_multi_delete: 408 onMultiDelete(mListAdapter.getSelectedSet()); 409 break; 410 } 411 } 412 413 @Override 414 public boolean onCreateOptionsMenu(Menu menu) { 415 super.onCreateOptionsMenu(menu); 416 if (mMailboxId < 0) { 417 getMenuInflater().inflate(R.menu.message_list_option_smart_folder, menu); 418 } else { 419 getMenuInflater().inflate(R.menu.message_list_option, menu); 420 } 421 return true; 422 } 423 424 @Override 425 public boolean onPrepareOptionsMenu(Menu menu) { 426 boolean showDeselect = mListAdapter.getSelectedSet().size() > 0; 427 menu.setGroupVisible(R.id.deselect_all_group, showDeselect); 428 return true; 429 } 430 431 @Override 432 public boolean onOptionsItemSelected(MenuItem item) { 433 switch (item.getItemId()) { 434 case R.id.refresh: 435 onRefresh(); 436 return true; 437 case R.id.folders: 438 onFolders(); 439 return true; 440 case R.id.accounts: 441 onAccounts(); 442 return true; 443 case R.id.compose: 444 onCompose(); 445 return true; 446 case R.id.account_settings: 447 onEditAccount(); 448 return true; 449 case R.id.deselect_all: 450 onDeselectAll(); 451 return true; 452 default: 453 return super.onOptionsItemSelected(item); 454 } 455 } 456 457 @Override 458 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { 459 super.onCreateContextMenu(menu, v, menuInfo); 460 461 AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; 462 // There is no context menu for the list footer 463 if (info.targetView == mListFooterView) { 464 return; 465 } 466 MessageListItem itemView = (MessageListItem) info.targetView; 467 468 Cursor c = (Cursor) mListView.getItemAtPosition(info.position); 469 String messageName = c.getString(MessageListAdapter.COLUMN_SUBJECT); 470 471 menu.setHeaderTitle(messageName); 472 473 // TODO: There is probably a special context menu for the trash 474 Mailbox mailbox = Mailbox.restoreMailboxWithId(this, itemView.mMailboxId); 475 476 switch (mailbox.mType) { 477 case EmailContent.Mailbox.TYPE_DRAFTS: 478 getMenuInflater().inflate(R.menu.message_list_context_drafts, menu); 479 break; 480 case EmailContent.Mailbox.TYPE_OUTBOX: 481 getMenuInflater().inflate(R.menu.message_list_context_outbox, menu); 482 break; 483 case EmailContent.Mailbox.TYPE_TRASH: 484 getMenuInflater().inflate(R.menu.message_list_context_trash, menu); 485 break; 486 default: 487 getMenuInflater().inflate(R.menu.message_list_context, menu); 488 // The default menu contains "mark as read". If the message is read, change 489 // the menu text to "mark as unread." 490 if (itemView.mRead) { 491 menu.findItem(R.id.mark_as_read).setTitle(R.string.mark_as_unread_action); 492 } 493 break; 494 } 495 } 496 497 @Override 498 public boolean onContextItemSelected(MenuItem item) { 499 AdapterView.AdapterContextMenuInfo info = 500 (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); 501 MessageListItem itemView = (MessageListItem) info.targetView; 502 503 switch (item.getItemId()) { 504 case R.id.open: 505 onOpenMessage(info.id, itemView.mMailboxId); 506 break; 507 case R.id.delete: 508 onDelete(info.id, itemView.mAccountId); 509 break; 510 case R.id.reply: 511 onReply(itemView.mMessageId); 512 break; 513 case R.id.reply_all: 514 onReplyAll(itemView.mMessageId); 515 break; 516 case R.id.forward: 517 onForward(itemView.mMessageId); 518 break; 519 case R.id.mark_as_read: 520 onSetMessageRead(info.id, !itemView.mRead); 521 break; 522 } 523 return super.onContextItemSelected(item); 524 } 525 526 private void onRefresh() { 527 // TODO: Should not be reading from DB in UI thread - need a cleaner way to get accountId 528 if (mMailboxId >= 0) { 529 Mailbox mailbox = Mailbox.restoreMailboxWithId(this, mMailboxId); 530 if (mailbox != null) { 531 mController.updateMailbox(mailbox.mAccountKey, mMailboxId, mControllerCallback); 532 } 533 } 534 } 535 536 private void onFolders() { 537 if (mMailboxId >= 0) { 538 // TODO smaller projection 539 Mailbox mailbox = Mailbox.restoreMailboxWithId(this, mMailboxId); 540 MailboxList.actionHandleAccount(this, mailbox.mAccountKey); 541 finish(); 542 } 543 } 544 545 private void onAccounts() { 546 AccountFolderList.actionShowAccounts(this); 547 finish(); 548 } 549 550 private long lookupAccountIdFromMailboxId(long mailboxId) { 551 // TODO: Select correct account to send from when there are multiple mailboxes 552 // TODO: Should not be reading from DB in UI thread 553 if (mailboxId < 0) { 554 return -1; // no info, default account 555 } 556 EmailContent.Mailbox mailbox = 557 EmailContent.Mailbox.restoreMailboxWithId(this, mailboxId); 558 return mailbox.mAccountKey; 559 } 560 561 private void onCompose() { 562 MessageCompose.actionCompose(this, lookupAccountIdFromMailboxId(mMailboxId)); 563 } 564 565 private void onEditAccount() { 566 AccountSettings.actionSettings(this, lookupAccountIdFromMailboxId(mMailboxId)); 567 } 568 569 private void onDeselectAll() { 570 mListAdapter.getSelectedSet().clear(); 571 mListView.invalidateViews(); 572 showMultiPanel(false); 573 } 574 575 private void onOpenMessage(long messageId, long mailboxId) { 576 // TODO: Should not be reading from DB in UI thread 577 EmailContent.Mailbox mailbox = EmailContent.Mailbox.restoreMailboxWithId(this, mailboxId); 578 579 if (mailbox.mType == EmailContent.Mailbox.TYPE_DRAFTS) { 580 MessageCompose.actionEditDraft(this, messageId); 581 } else { 582 // WARNING: here we pass mMailboxId, which can be the negative id of a compound 583 // mailbox, instead of the mailboxId of the particular message that is opened 584 MessageView.actionView(this, messageId, mMailboxId); 585 } 586 } 587 588 private void onReply(long messageId) { 589 MessageCompose.actionReply(this, messageId, false); 590 } 591 592 private void onReplyAll(long messageId) { 593 MessageCompose.actionReply(this, messageId, true); 594 } 595 596 private void onForward(long messageId) { 597 MessageCompose.actionForward(this, messageId); 598 } 599 600 private void onLoadMoreMessages() { 601 if (mMailboxId >= 0) { 602 mController.loadMoreMessages(mMailboxId, mControllerCallback); 603 } 604 } 605 606 private void onSendPendingMessages() { 607 long accountId = lookupAccountIdFromMailboxId(mMailboxId); 608 mController.sendPendingMessages(accountId, mControllerCallback); 609 } 610 611 private void onDelete(long messageId, long accountId) { 612 mController.deleteMessage(messageId, accountId); 613 Toast.makeText(this, R.string.message_deleted_toast, Toast.LENGTH_SHORT).show(); 614 } 615 616 private void onSetMessageRead(long messageId, boolean newRead) { 617 mController.setMessageRead(messageId, newRead); 618 } 619 620 private void onSetMessageFavorite(long messageId, boolean newFavorite) { 621 mController.setMessageFavorite(messageId, newFavorite); 622 } 623 624 /** 625 * Toggles a set read/unread states. Note, the default behavior is "mark unread", so the 626 * sense of the helper methods is "true=unread". 627 * 628 * @param selectedSet The current list of selected items 629 */ 630 private void onMultiToggleRead(Set<Long> selectedSet) { 631 toggleMultiple(selectedSet, new MultiToggleHelper() { 632 633 public boolean getField(long messageId, Cursor c) { 634 return c.getInt(MessageListAdapter.COLUMN_READ) == 0; 635 } 636 637 public boolean setField(long messageId, Cursor c, boolean newValue) { 638 boolean oldValue = getField(messageId, c); 639 if (oldValue != newValue) { 640 onSetMessageRead(messageId, !newValue); 641 return true; 642 } 643 return false; 644 } 645 }); 646 } 647 648 /** 649 * Toggles a set of favorites (stars) 650 * 651 * @param selectedSet The current list of selected items 652 */ 653 private void onMultiToggleFavorite(Set<Long> selectedSet) { 654 toggleMultiple(selectedSet, new MultiToggleHelper() { 655 656 public boolean getField(long messageId, Cursor c) { 657 return c.getInt(MessageListAdapter.COLUMN_FAVORITE) != 0; 658 } 659 660 public boolean setField(long messageId, Cursor c, boolean newValue) { 661 boolean oldValue = getField(messageId, c); 662 if (oldValue != newValue) { 663 onSetMessageFavorite(messageId, newValue); 664 return true; 665 } 666 return false; 667 } 668 }); 669 } 670 671 private void onMultiDelete(Set<Long> selectedSet) { 672 // Clone the set, because deleting is going to thrash things 673 HashSet<Long> cloneSet = new HashSet<Long>(selectedSet); 674 for (Long id : cloneSet) { 675 mController.deleteMessage(id, -1); 676 } 677 // TODO: count messages and show "n messages deleted" 678 Toast.makeText(this, R.string.message_deleted_toast, Toast.LENGTH_SHORT).show(); 679 selectedSet.clear(); 680 showMultiPanel(false); 681 } 682 683 private interface MultiToggleHelper { 684 /** 685 * Return true if the field of interest is "set". If one or more are false, then our 686 * bulk action will be to "set". If all are set, our bulk action will be to "clear". 687 * @param messageId the message id of the current message 688 * @param c the cursor, positioned to the item of interest 689 * @return true if the field at this row is "set" 690 */ 691 public boolean getField(long messageId, Cursor c); 692 693 /** 694 * Set or clear the field of interest. Return true if a change was made. 695 * @param messageId the message id of the current message 696 * @param c the cursor, positioned to the item of interest 697 * @param newValue the new value to be set at this row 698 * @return true if a change was actually made 699 */ 700 public boolean setField(long messageId, Cursor c, boolean newValue); 701 } 702 703 /** 704 * Toggle multiple fields in a message, using the following logic: If one or more fields 705 * are "clear", then "set" them. If all fields are "set", then "clear" them all. 706 * 707 * @param selectedSet the set of messages that are selected 708 * @param helper functions to implement the specific getter & setter 709 * @return the number of messages that were updated 710 */ 711 private int toggleMultiple(Set<Long> selectedSet, MultiToggleHelper helper) { 712 Cursor c = mListAdapter.getCursor(); 713 boolean anyWereFound = false; 714 boolean allWereSet = true; 715 716 c.moveToPosition(-1); 717 while (c.moveToNext()) { 718 long id = c.getInt(MessageListAdapter.COLUMN_ID); 719 if (selectedSet.contains(Long.valueOf(id))) { 720 anyWereFound = true; 721 if (!helper.getField(id, c)) { 722 allWereSet = false; 723 break; 724 } 725 } 726 } 727 728 int numChanged = 0; 729 730 if (anyWereFound) { 731 boolean newValue = !allWereSet; 732 c.moveToPosition(-1); 733 while (c.moveToNext()) { 734 long id = c.getInt(MessageListAdapter.COLUMN_ID); 735 if (selectedSet.contains(Long.valueOf(id))) { 736 if (helper.setField(id, c, newValue)) { 737 ++numChanged; 738 } 739 } 740 } 741 } 742 743 return numChanged; 744 } 745 746 /** 747 * Test selected messages for showing appropriate labels 748 * @param selectedSet 749 * @param column_id 750 * @param defaultflag 751 * @return true when the specified flagged message is selected 752 */ 753 private boolean testMultiple(Set<Long> selectedSet, int column_id, boolean defaultflag) { 754 Cursor c = mListAdapter.getCursor(); 755 c.moveToPosition(-1); 756 while (c.moveToNext()) { 757 long id = c.getInt(MessageListAdapter.COLUMN_ID); 758 if (selectedSet.contains(Long.valueOf(id))) { 759 if (c.getInt(column_id) == (defaultflag? 1 : 0)) { 760 return true; 761 } 762 } 763 } 764 return false; 765 } 766 767 /** 768 * Implements a timed refresh of "stale" mailboxes. This should only happen when 769 * multiple conditions are true, including: 770 * Only when the user explicitly opens the mailbox (not onResume, for example) 771 * Only for real, non-push mailboxes 772 * Only when the mailbox is "stale" (currently set to 5 minutes since last refresh) 773 */ 774 private void autoRefreshStaleMailbox() { 775 if (!mCanAutoRefresh 776 || (mListAdapter.getCursor() == null) // Check if messages info is loaded 777 || (mPushModeMailbox != null && mPushModeMailbox) // Check the push mode 778 || (mMailboxId < 0)) { // Check if this mailbox is synthetic/combined 779 return; 780 } 781 mCanAutoRefresh = false; 782 if (!Email.mailboxRequiresRefresh(mMailboxId)) { 783 return; 784 } 785 onRefresh(); 786 } 787 788 private void updateFooterButtonNames () { 789 // Show "unread_action" when one or more read messages are selected. 790 if (testMultiple(mListAdapter.getSelectedSet(), MessageListAdapter.COLUMN_READ, true)) { 791 mReadUnreadButton.setText(R.string.unread_action); 792 } else { 793 mReadUnreadButton.setText(R.string.read_action); 794 } 795 // Show "set_star_action" when one or more un-starred messages are selected. 796 if (testMultiple(mListAdapter.getSelectedSet(), 797 MessageListAdapter.COLUMN_FAVORITE, false)) { 798 mFavoriteButton.setText(R.string.set_star_action); 799 } else { 800 mFavoriteButton.setText(R.string.remove_star_action); 801 } 802 } 803 804 /** 805 * Show or hide the panel of multi-select options 806 */ 807 private void showMultiPanel(boolean show) { 808 if (show && mMultiSelectPanel.getVisibility() != View.VISIBLE) { 809 mMultiSelectPanel.setVisibility(View.VISIBLE); 810 mMultiSelectPanel.startAnimation( 811 AnimationUtils.loadAnimation(this, R.anim.footer_appear)); 812 } else if (!show && mMultiSelectPanel.getVisibility() != View.GONE) { 813 mMultiSelectPanel.setVisibility(View.GONE); 814 mMultiSelectPanel.startAnimation( 815 AnimationUtils.loadAnimation(this, R.anim.footer_disappear)); 816 } 817 if (show) { 818 updateFooterButtonNames(); 819 } 820 } 821 822 /** 823 * Add the fixed footer view if appropriate (not always - not all accounts & mailboxes). 824 * 825 * Here are some rules (finish this list): 826 * 827 * Any merged, synced box (except send): refresh 828 * Any push-mode account: refresh 829 * Any non-push-mode account: load more 830 * Any outbox (send again): 831 * 832 * @param mailboxId the ID of the mailbox 833 */ 834 private void addFooterView(long mailboxId, long accountId, int mailboxType) { 835 // first, look for shortcuts that don't need us to spin up a DB access task 836 if (mailboxId == Mailbox.QUERY_ALL_INBOXES 837 || mailboxId == Mailbox.QUERY_ALL_UNREAD 838 || mailboxId == Mailbox.QUERY_ALL_FAVORITES) { 839 finishFooterView(LIST_FOOTER_MODE_REFRESH); 840 return; 841 } 842 if (mailboxId == Mailbox.QUERY_ALL_DRAFTS || mailboxType == Mailbox.TYPE_DRAFTS) { 843 finishFooterView(LIST_FOOTER_MODE_NONE); 844 return; 845 } 846 if (mailboxId == Mailbox.QUERY_ALL_OUTBOX || mailboxType == Mailbox.TYPE_OUTBOX) { 847 finishFooterView(LIST_FOOTER_MODE_SEND); 848 return; 849 } 850 851 // We don't know enough to select the footer command type (yet), so we'll 852 // launch an async task to do the remaining lookups and decide what to do 853 mSetFooterTask = new SetFooterTask(); 854 mSetFooterTask.execute(mailboxId, accountId); 855 } 856 857 private final static String[] MAILBOX_ACCOUNT_AND_TYPE_PROJECTION = 858 new String[] { MailboxColumns.ACCOUNT_KEY, MailboxColumns.TYPE }; 859 860 private class SetFooterTask extends AsyncTask<Long, Void, Integer> { 861 /** 862 * There are two operational modes here, requiring different lookup. 863 * mailboxIs != -1: A specific mailbox - check its type, then look up its account 864 * accountId != -1: A specific account - look up the account 865 */ 866 @Override 867 protected Integer doInBackground(Long... params) { 868 long mailboxId = params[0]; 869 long accountId = params[1]; 870 int mailboxType = -1; 871 if (mailboxId != -1) { 872 try { 873 Uri uri = ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId); 874 Cursor c = mResolver.query(uri, MAILBOX_ACCOUNT_AND_TYPE_PROJECTION, 875 null, null, null); 876 if (c.moveToFirst()) { 877 try { 878 accountId = c.getLong(0); 879 mailboxType = c.getInt(1); 880 } finally { 881 c.close(); 882 } 883 } 884 } catch (IllegalArgumentException iae) { 885 // can't do any more here 886 return LIST_FOOTER_MODE_NONE; 887 } 888 } 889 switch (mailboxType) { 890 case Mailbox.TYPE_OUTBOX: 891 return LIST_FOOTER_MODE_SEND; 892 case Mailbox.TYPE_DRAFTS: 893 return LIST_FOOTER_MODE_NONE; 894 } 895 if (accountId != -1) { 896 // This is inefficient but the best fix is not here but in isMessagingController 897 Account account = Account.restoreAccountWithId(MessageList.this, accountId); 898 if (account != null) { 899 mPushModeMailbox = account.mSyncInterval == Account.CHECK_INTERVAL_PUSH; 900 if (MessageList.this.mController.isMessagingController(account)) { 901 return LIST_FOOTER_MODE_MORE; // IMAP or POP 902 } else { 903 return LIST_FOOTER_MODE_NONE; // EAS 904 } 905 } 906 } 907 return LIST_FOOTER_MODE_NONE; 908 } 909 910 @Override 911 protected void onPostExecute(Integer listFooterMode) { 912 if (listFooterMode == null) { 913 return; 914 } 915 finishFooterView(listFooterMode); 916 } 917 } 918 919 /** 920 * Add the fixed footer view as specified, and set up the test as well. 921 * 922 * @param listFooterMode the footer mode we've determined should be used for this list 923 */ 924 private void finishFooterView(int listFooterMode) { 925 mListFooterMode = listFooterMode; 926 if (mListFooterMode != LIST_FOOTER_MODE_NONE) { 927 mListFooterView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)) 928 .inflate(R.layout.message_list_item_footer, mListView, false); 929 mList.addFooterView(mListFooterView); 930 setListAdapter(mListAdapter); 931 932 mListFooterProgress = mListFooterView.findViewById(R.id.progress); 933 mListFooterText = (TextView) mListFooterView.findViewById(R.id.main_text); 934 setListFooterText(false); 935 } 936 } 937 938 /** 939 * Set the list footer text based on mode and "active" status 940 */ 941 private void setListFooterText(boolean active) { 942 if (mListFooterMode != LIST_FOOTER_MODE_NONE) { 943 int footerTextId = 0; 944 switch (mListFooterMode) { 945 case LIST_FOOTER_MODE_REFRESH: 946 footerTextId = active ? R.string.status_loading_more 947 : R.string.refresh_action; 948 break; 949 case LIST_FOOTER_MODE_MORE: 950 footerTextId = active ? R.string.status_loading_more 951 : R.string.message_list_load_more_messages_action; 952 break; 953 case LIST_FOOTER_MODE_SEND: 954 footerTextId = active ? R.string.status_sending_messages 955 : R.string.message_list_send_pending_messages_action; 956 break; 957 } 958 mListFooterText.setText(footerTextId); 959 } 960 } 961 962 /** 963 * Handle a click in the list footer, which changes meaning depending on what we're looking at. 964 */ 965 private void doFooterClick() { 966 switch (mListFooterMode) { 967 case LIST_FOOTER_MODE_NONE: // should never happen 968 break; 969 case LIST_FOOTER_MODE_REFRESH: 970 onRefresh(); 971 break; 972 case LIST_FOOTER_MODE_MORE: 973 onLoadMoreMessages(); 974 break; 975 case LIST_FOOTER_MODE_SEND: 976 onSendPendingMessages(); 977 break; 978 } 979 } 980 981 /** 982 * Async task for finding a single mailbox by type (possibly even going to the network). 983 * 984 * This is much too complex, as implemented. It uses this AsyncTask to check for a mailbox, 985 * then (if not found) a Controller call to refresh mailboxes from the server, and a handler 986 * to relaunch this task (a 2nd time) to read the results of the network refresh. The core 987 * problem is that we have two different non-UI-thread jobs (reading DB and reading network) 988 * and two different paradigms for dealing with them. Some unification would be needed here 989 * to make this cleaner. 990 * 991 * TODO: If this problem spreads to other operations, find a cleaner way to handle it. 992 */ 993 private class FindMailboxTask extends AsyncTask<Void, Void, Long> { 994 995 private long mAccountId; 996 private int mMailboxType; 997 private boolean mOkToRecurse; 998 999 /** 1000 * Special constructor to cache some local info 1001 */ 1002 public FindMailboxTask(long accountId, int mailboxType, boolean okToRecurse) { 1003 mAccountId = accountId; 1004 mMailboxType = mailboxType; 1005 mOkToRecurse = okToRecurse; 1006 } 1007 1008 @Override 1009 protected Long doInBackground(Void... params) { 1010 // See if we can find the requested mailbox in the DB. 1011 long mailboxId = Mailbox.findMailboxOfType(MessageList.this, mAccountId, mMailboxType); 1012 if (mailboxId == Mailbox.NO_MAILBOX && mOkToRecurse) { 1013 // Not found - launch network lookup 1014 mControllerCallback.mWaitForMailboxType = mMailboxType; 1015 mController.updateMailboxList(mAccountId, mControllerCallback); 1016 } 1017 return mailboxId; 1018 } 1019 1020 @Override 1021 protected void onPostExecute(Long mailboxId) { 1022 if (mailboxId == null) { 1023 return; 1024 } 1025 if (mailboxId != Mailbox.NO_MAILBOX) { 1026 mMailboxId = mailboxId; 1027 mSetTitleTask = new SetTitleTask(mMailboxId); 1028 mSetTitleTask.execute(); 1029 mLoadMessagesTask = new LoadMessagesTask(mMailboxId, mAccountId); 1030 mLoadMessagesTask.execute(); 1031 } 1032 } 1033 } 1034 1035 /** 1036 * Async task for loading a single folder out of the UI thread 1037 * 1038 * The code here (for merged boxes) is a placeholder/hack and should be replaced. Some 1039 * specific notes: 1040 * TODO: Move the double query into a specialized URI that returns all inbox messages 1041 * and do the dirty work in raw SQL in the provider. 1042 * TODO: Generalize the query generation so we can reuse it in MessageView (for next/prev) 1043 */ 1044 private class LoadMessagesTask extends AsyncTask<Void, Void, Cursor> { 1045 1046 private long mMailboxKey; 1047 private long mAccountKey; 1048 1049 /** 1050 * Special constructor to cache some local info 1051 */ 1052 public LoadMessagesTask(long mailboxKey, long accountKey) { 1053 mMailboxKey = mailboxKey; 1054 mAccountKey = accountKey; 1055 } 1056 1057 @Override 1058 protected Cursor doInBackground(Void... params) { 1059 String selection = 1060 Utility.buildMailboxIdSelection(MessageList.this.mResolver, mMailboxKey); 1061 Cursor c = MessageList.this.managedQuery( 1062 EmailContent.Message.CONTENT_URI, 1063 MessageList.this.mListAdapter.PROJECTION, 1064 selection, null, 1065 EmailContent.MessageColumns.TIMESTAMP + " DESC"); 1066 return c; 1067 } 1068 1069 @Override 1070 protected void onPostExecute(Cursor cursor) { 1071 if (cursor == null || cursor.isClosed()) { 1072 return; 1073 } 1074 MessageList.this.mListAdapter.changeCursor(cursor); 1075 // changeCursor occurs the jumping of position in ListView, so it's need to restore 1076 // the position; 1077 restoreListPosition(); 1078 autoRefreshStaleMailbox(); 1079 // Reset the "new messages" count in the service, since we're seeing them now 1080 if (mMailboxKey == Mailbox.QUERY_ALL_INBOXES) { 1081 MailService.resetNewMessageCount(MessageList.this, -1); 1082 } else if (mMailboxKey >= 0 && mAccountKey != -1) { 1083 MailService.resetNewMessageCount(MessageList.this, mAccountKey); 1084 } 1085 } 1086 } 1087 1088 private class SetTitleTask extends AsyncTask<Void, Void, String[]> { 1089 1090 private long mMailboxKey; 1091 1092 public SetTitleTask(long mailboxKey) { 1093 mMailboxKey = mailboxKey; 1094 } 1095 1096 @Override 1097 protected String[] doInBackground(Void... params) { 1098 // Check special Mailboxes 1099 if (mMailboxKey == Mailbox.QUERY_ALL_INBOXES) { 1100 return new String[] {null, 1101 getString(R.string.account_folder_list_summary_inbox)}; 1102 } else if (mMailboxKey == Mailbox.QUERY_ALL_FAVORITES) { 1103 return new String[] {null, 1104 getString(R.string.account_folder_list_summary_starred)}; 1105 } else if (mMailboxKey == Mailbox.QUERY_ALL_DRAFTS) { 1106 return new String[] {null, 1107 getString(R.string.account_folder_list_summary_drafts)}; 1108 } else if (mMailboxKey == Mailbox.QUERY_ALL_OUTBOX) { 1109 return new String[] {null, 1110 getString(R.string.account_folder_list_summary_outbox)}; 1111 } 1112 String accountName = null; 1113 String mailboxName = null; 1114 String accountKey = null; 1115 Cursor c = MessageList.this.mResolver.query(Mailbox.CONTENT_URI, 1116 MAILBOX_NAME_PROJECTION, ID_SELECTION, 1117 new String[] { Long.toString(mMailboxKey) }, null); 1118 try { 1119 if (c.moveToFirst()) { 1120 mailboxName = Utility.FolderProperties.getInstance(MessageList.this) 1121 .getDisplayName(c.getInt(MAILBOX_NAME_COLUMN_TYPE)); 1122 if (mailboxName == null) { 1123 mailboxName = c.getString(MAILBOX_NAME_COLUMN_ID); 1124 } 1125 accountKey = c.getString(MAILBOX_NAME_COLUMN_ACCOUNT_KEY); 1126 } 1127 } finally { 1128 c.close(); 1129 } 1130 if (accountKey != null) { 1131 c = MessageList.this.mResolver.query(Account.CONTENT_URI, 1132 ACCOUNT_NAME_PROJECTION, ID_SELECTION, new String[] { accountKey }, 1133 null); 1134 try { 1135 if (c.moveToFirst()) { 1136 accountName = c.getString(ACCOUNT_DISPLAY_NAME_COLUMN_ID); 1137 } 1138 } finally { 1139 c.close(); 1140 } 1141 } 1142 return new String[] {accountName, mailboxName}; 1143 } 1144 1145 @Override 1146 protected void onPostExecute(String[] names) { 1147 if (names == null) { 1148 return; 1149 } 1150 if (names[0] != null) { 1151 mRightTitle.setText(names[0]); 1152 } 1153 if (names[1] != null) { 1154 mLeftTitle.setText(names[1]); 1155 } 1156 } 1157 } 1158 1159 /** 1160 * Handler for UI-thread operations (when called from callbacks or any other threads) 1161 */ 1162 class MessageListHandler extends Handler { 1163 private static final int MSG_PROGRESS = 1; 1164 private static final int MSG_LOOKUP_MAILBOX_TYPE = 2; 1165 private static final int MSG_ERROR_BANNER = 3; 1166 private static final int MSG_REQUERY_LIST = 4; 1167 1168 @Override 1169 public void handleMessage(android.os.Message msg) { 1170 switch (msg.what) { 1171 case MSG_PROGRESS: 1172 boolean visible = (msg.arg1 != 0); 1173 if (visible) { 1174 mProgressIcon.setVisibility(View.VISIBLE); 1175 } else { 1176 mProgressIcon.setVisibility(View.GONE); 1177 } 1178 if (mListFooterProgress != null) { 1179 mListFooterProgress.setVisibility(visible ? View.VISIBLE : View.GONE); 1180 } 1181 setListFooterText(visible); 1182 break; 1183 case MSG_LOOKUP_MAILBOX_TYPE: 1184 // kill running async task, if any 1185 if (mFindMailboxTask != null && 1186 mFindMailboxTask.getStatus() != FindMailboxTask.Status.FINISHED) { 1187 mFindMailboxTask.cancel(true); 1188 mFindMailboxTask = null; 1189 } 1190 // start new one. do not recurse back to controller. 1191 long accountId = ((Long)msg.obj).longValue(); 1192 int mailboxType = msg.arg1; 1193 mFindMailboxTask = new FindMailboxTask(accountId, mailboxType, false); 1194 mFindMailboxTask.execute(); 1195 break; 1196 case MSG_ERROR_BANNER: 1197 String message = (String) msg.obj; 1198 boolean isVisible = mErrorBanner.getVisibility() == View.VISIBLE; 1199 if (message != null) { 1200 mErrorBanner.setText(message); 1201 if (!isVisible) { 1202 mErrorBanner.setVisibility(View.VISIBLE); 1203 mErrorBanner.startAnimation( 1204 AnimationUtils.loadAnimation( 1205 MessageList.this, R.anim.header_appear)); 1206 } 1207 } else { 1208 if (isVisible) { 1209 mErrorBanner.setVisibility(View.GONE); 1210 mErrorBanner.startAnimation( 1211 AnimationUtils.loadAnimation( 1212 MessageList.this, R.anim.header_disappear)); 1213 } 1214 } 1215 break; 1216 case MSG_REQUERY_LIST: 1217 mListAdapter.doRequery(); 1218 if (mMultiSelectPanel.getVisibility() == View.VISIBLE) { 1219 updateFooterButtonNames(); 1220 } 1221 break; 1222 default: 1223 super.handleMessage(msg); 1224 } 1225 } 1226 1227 /** 1228 * Call from any thread to start/stop progress indicator(s) 1229 * @param progress true to start, false to stop 1230 */ 1231 public void progress(boolean progress) { 1232 android.os.Message msg = android.os.Message.obtain(); 1233 msg.what = MSG_PROGRESS; 1234 msg.arg1 = progress ? 1 : 0; 1235 sendMessage(msg); 1236 } 1237 1238 /** 1239 * Called from any thread to look for a mailbox of a specific type. This is designed 1240 * to be called from the Controller's MailboxList callback; It instructs the async task 1241 * not to recurse, in case the mailbox is not found after this. 1242 * 1243 * See FindMailboxTask for more notes on this handler. 1244 */ 1245 public void lookupMailboxType(long accountId, int mailboxType) { 1246 android.os.Message msg = android.os.Message.obtain(); 1247 msg.what = MSG_LOOKUP_MAILBOX_TYPE; 1248 msg.arg1 = mailboxType; 1249 msg.obj = Long.valueOf(accountId); 1250 sendMessage(msg); 1251 } 1252 1253 /** 1254 * Called from any thread to show or hide the connection error banner. 1255 * @param message error text or null to hide the box 1256 */ 1257 public void showErrorBanner(String message) { 1258 android.os.Message msg = android.os.Message.obtain(); 1259 msg.what = MSG_ERROR_BANNER; 1260 msg.obj = message; 1261 sendMessage(msg); 1262 } 1263 1264 /** 1265 * Called from any thread to signal that the list adapter should requery and update. 1266 */ 1267 public void requeryList() { 1268 sendEmptyMessage(MSG_REQUERY_LIST); 1269 } 1270 } 1271 1272 /** 1273 * Callback for async Controller results. 1274 */ 1275 private class ControllerResults implements Controller.Result { 1276 1277 // This is used to alter the connection banner operation for sending messages 1278 MessagingException mSendMessageException; 1279 1280 // These are preset for use by updateMailboxListCallback 1281 int mWaitForMailboxType = -1; 1282 1283 // TODO check accountKey and only react to relevant notifications 1284 public void updateMailboxListCallback(MessagingException result, long accountKey, 1285 int progress) { 1286 // no updateBanner here, we are only listing a single mailbox 1287 updateProgress(result, progress); 1288 if (progress == 100) { 1289 mHandler.lookupMailboxType(accountKey, mWaitForMailboxType); 1290 } 1291 } 1292 1293 // TODO check accountKey and only react to relevant notifications 1294 public void updateMailboxCallback(MessagingException result, long accountKey, 1295 long mailboxKey, int progress, int numNewMessages) { 1296 updateBanner(result, progress, mailboxKey); 1297 if (result != null || progress == 100) { 1298 Email.updateMailboxRefreshTime(mMailboxId); 1299 } 1300 updateProgress(result, progress); 1301 } 1302 1303 public void loadMessageForViewCallback(MessagingException result, long messageId, 1304 int progress) { 1305 } 1306 1307 public void loadAttachmentCallback(MessagingException result, long messageId, 1308 long attachmentId, int progress) { 1309 } 1310 1311 public void serviceCheckMailCallback(MessagingException result, long accountId, 1312 long mailboxId, int progress, long tag) { 1313 } 1314 1315 /** 1316 * We alter the updateBanner hysteresis here to capture any failures and handle 1317 * them just once at the end. This callback is overly overloaded: 1318 * result == null, messageId == -1, progress == 0: start batch send 1319 * result == null, messageId == xx, progress == 0: start sending one message 1320 * result == xxxx, messageId == xx, progress == 0; failed sending one message 1321 * result == null, messageId == -1, progres == 100; finish sending batch 1322 */ 1323 public void sendMailCallback(MessagingException result, long accountId, long messageId, 1324 int progress) { 1325 if (mListFooterMode == LIST_FOOTER_MODE_SEND) { 1326 // reset captured error when we start sending one or more messages 1327 if (messageId == -1 && result == null && progress == 0) { 1328 mSendMessageException = null; 1329 } 1330 // capture first exception that comes along 1331 if (result != null && mSendMessageException == null) { 1332 mSendMessageException = result; 1333 } 1334 // if we're completing the sequence, change the banner state 1335 if (messageId == -1 && progress == 100) { 1336 updateBanner(mSendMessageException, progress, mMailboxId); 1337 } 1338 // always update the spinner, which has less state to worry about 1339 updateProgress(result, progress); 1340 } 1341 } 1342 1343 private void updateProgress(MessagingException result, int progress) { 1344 if (result != null || progress == 100) { 1345 mHandler.progress(false); 1346 } else if (progress == 0) { 1347 mHandler.progress(true); 1348 } 1349 } 1350 1351 /** 1352 * Show or hide the connection error banner, and convert the various MessagingException 1353 * variants into localizable text. There is hysteresis in the show/hide logic: Once shown, 1354 * the banner will remain visible until some progress is made on the connection. The 1355 * goal is to keep it from flickering during retries in a bad connection state. 1356 * 1357 * @param result 1358 * @param progress 1359 */ 1360 private void updateBanner(MessagingException result, int progress, long mailboxKey) { 1361 if (mailboxKey != mMailboxId) { 1362 return; 1363 } 1364 if (result != null) { 1365 int id = R.string.status_network_error; 1366 if (result instanceof AuthenticationFailedException) { 1367 id = R.string.account_setup_failed_dlg_auth_message; 1368 } else if (result instanceof CertificateValidationException) { 1369 id = R.string.account_setup_failed_dlg_certificate_message; 1370 } else { 1371 switch (result.getExceptionType()) { 1372 case MessagingException.IOERROR: 1373 id = R.string.account_setup_failed_ioerror; 1374 break; 1375 case MessagingException.TLS_REQUIRED: 1376 id = R.string.account_setup_failed_tls_required; 1377 break; 1378 case MessagingException.AUTH_REQUIRED: 1379 id = R.string.account_setup_failed_auth_required; 1380 break; 1381 case MessagingException.GENERAL_SECURITY: 1382 id = R.string.account_setup_failed_security; 1383 break; 1384 } 1385 } 1386 mHandler.showErrorBanner(getString(id)); 1387 } else if (progress > 0) { 1388 mHandler.showErrorBanner(null); 1389 } 1390 } 1391 } 1392 1393 /** 1394 * This class implements the adapter for displaying messages based on cursors. 1395 */ 1396 /* package */ class MessageListAdapter extends CursorAdapter { 1397 1398 public static final int COLUMN_ID = 0; 1399 public static final int COLUMN_MAILBOX_KEY = 1; 1400 public static final int COLUMN_ACCOUNT_KEY = 2; 1401 public static final int COLUMN_DISPLAY_NAME = 3; 1402 public static final int COLUMN_SUBJECT = 4; 1403 public static final int COLUMN_DATE = 5; 1404 public static final int COLUMN_READ = 6; 1405 public static final int COLUMN_FAVORITE = 7; 1406 public static final int COLUMN_ATTACHMENTS = 8; 1407 1408 public final String[] PROJECTION = new String[] { 1409 EmailContent.RECORD_ID, MessageColumns.MAILBOX_KEY, MessageColumns.ACCOUNT_KEY, 1410 MessageColumns.DISPLAY_NAME, MessageColumns.SUBJECT, MessageColumns.TIMESTAMP, 1411 MessageColumns.FLAG_READ, MessageColumns.FLAG_FAVORITE, MessageColumns.FLAG_ATTACHMENT, 1412 }; 1413 1414 Context mContext; 1415 private LayoutInflater mInflater; 1416 private Drawable mAttachmentIcon; 1417 private Drawable mFavoriteIconOn; 1418 private Drawable mFavoriteIconOff; 1419 private Drawable mSelectedIconOn; 1420 private Drawable mSelectedIconOff; 1421 1422 private ColorStateList mTextColorPrimary; 1423 private ColorStateList mTextColorSecondary; 1424 1425 // Timer to control the refresh rate of the list 1426 private final RefreshTimer mRefreshTimer = new RefreshTimer(); 1427 // Last time we allowed a refresh of the list 1428 private long mLastRefreshTime = 0; 1429 // How long we want to wait for refreshes (a good starting guess) 1430 // I suspect this could be lowered down to even 1000 or so, but this seems ok for now 1431 private static final long REFRESH_INTERVAL_MS = 2500; 1432 1433 private java.text.DateFormat mDateFormat; 1434 private java.text.DateFormat mDayFormat; 1435 private java.text.DateFormat mTimeFormat; 1436 1437 private HashSet<Long> mChecked = new HashSet<Long>(); 1438 1439 public MessageListAdapter(Context context) { 1440 super(context, null, true); 1441 mContext = context; 1442 mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 1443 1444 Resources resources = context.getResources(); 1445 mAttachmentIcon = resources.getDrawable(R.drawable.ic_mms_attachment_small); 1446 mFavoriteIconOn = resources.getDrawable(R.drawable.btn_star_big_buttonless_dark_on); 1447 mFavoriteIconOff = resources.getDrawable(R.drawable.btn_star_big_buttonless_dark_off); 1448 mSelectedIconOn = resources.getDrawable(R.drawable.btn_check_buttonless_dark_on); 1449 mSelectedIconOff = resources.getDrawable(R.drawable.btn_check_buttonless_dark_off); 1450 1451 Theme theme = context.getTheme(); 1452 TypedArray array; 1453 array = theme.obtainStyledAttributes(new int[] { android.R.attr.textColorPrimary }); 1454 mTextColorPrimary = resources.getColorStateList(array.getResourceId(0, 0)); 1455 array = theme.obtainStyledAttributes(new int[] { android.R.attr.textColorSecondary }); 1456 mTextColorSecondary = resources.getColorStateList(array.getResourceId(0, 0)); 1457 1458 mDateFormat = android.text.format.DateFormat.getDateFormat(context); // short date 1459 mDayFormat = android.text.format.DateFormat.getDateFormat(context); // TODO: day 1460 mTimeFormat = android.text.format.DateFormat.getTimeFormat(context); // 12/24 time 1461 } 1462 1463 /** 1464 * We override onContentChange to throttle the refresh, which can happen way too often 1465 * on syncing a large list (up to many times per second). This will prevent ANR's during 1466 * initial sync and potentially at other times as well. 1467 */ 1468 @Override 1469 protected synchronized void onContentChanged() { 1470 if (mCursor != null && !mCursor.isClosed()) { 1471 long sinceRefresh = SystemClock.elapsedRealtime() - mLastRefreshTime; 1472 mRefreshTimer.schedule(REFRESH_INTERVAL_MS - sinceRefresh); 1473 } 1474 } 1475 1476 /** 1477 * Called in UI thread only, from Handler, to complete the requery that we 1478 * intercepted in onContentChanged(). 1479 */ 1480 public void doRequery() { 1481 if (mCursor != null && !mCursor.isClosed()) { 1482 mDataValid = mCursor.requery(); 1483 notifyDataSetChanged(); 1484 } 1485 } 1486 1487 class RefreshTimer extends Timer { 1488 private TimerTask timerTask = null; 1489 1490 protected void clear() { 1491 timerTask = null; 1492 } 1493 1494 protected synchronized void schedule(long delay) { 1495 if (timerTask != null) return; 1496 if (delay < 0) { 1497 refreshList(); 1498 } else { 1499 timerTask = new RefreshTimerTask(); 1500 schedule(timerTask, delay); 1501 } 1502 } 1503 } 1504 1505 class RefreshTimerTask extends TimerTask { 1506 @Override 1507 public void run() { 1508 refreshList(); 1509 } 1510 } 1511 1512 /** 1513 * Do the work of requerying the list and notifying the UI of changed data 1514 * Make sure we call notifyDataSetChanged on the UI thread. 1515 */ 1516 private synchronized void refreshList() { 1517 if (Email.LOGD) { 1518 Log.d("messageList", "refresh: " 1519 + (SystemClock.elapsedRealtime() - mLastRefreshTime) + "ms"); 1520 } 1521 mHandler.requeryList(); 1522 mLastRefreshTime = SystemClock.elapsedRealtime(); 1523 mRefreshTimer.clear(); 1524 } 1525 1526 public Set<Long> getSelectedSet() { 1527 return mChecked; 1528 } 1529 1530 @Override 1531 public void bindView(View view, Context context, Cursor cursor) { 1532 // Reset the view (in case it was recycled) and prepare for binding 1533 MessageListItem itemView = (MessageListItem) view; 1534 itemView.bindViewInit(this, true); 1535 1536 // Load the public fields in the view (for later use) 1537 itemView.mMessageId = cursor.getLong(COLUMN_ID); 1538 itemView.mMailboxId = cursor.getLong(COLUMN_MAILBOX_KEY); 1539 itemView.mAccountId = cursor.getLong(COLUMN_ACCOUNT_KEY); 1540 itemView.mRead = cursor.getInt(COLUMN_READ) != 0; 1541 itemView.mFavorite = cursor.getInt(COLUMN_FAVORITE) != 0; 1542 itemView.mSelected = mChecked.contains(Long.valueOf(itemView.mMessageId)); 1543 1544 // Load the UI 1545 View chipView = view.findViewById(R.id.chip); 1546 int chipResId = mColorChipResIds[(int)itemView.mAccountId % mColorChipResIds.length]; 1547 chipView.setBackgroundResource(chipResId); 1548 1549 TextView fromView = (TextView) view.findViewById(R.id.from); 1550 String text = cursor.getString(COLUMN_DISPLAY_NAME); 1551 fromView.setText(text); 1552 1553 TextView subjectView = (TextView) view.findViewById(R.id.subject); 1554 text = cursor.getString(COLUMN_SUBJECT); 1555 subjectView.setText(text); 1556 1557 boolean hasAttachments = cursor.getInt(COLUMN_ATTACHMENTS) != 0; 1558 subjectView.setCompoundDrawablesWithIntrinsicBounds(null, null, 1559 hasAttachments ? mAttachmentIcon : null, null); 1560 1561 // TODO ui spec suggests "time", "day", "date" - implement "day" 1562 TextView dateView = (TextView) view.findViewById(R.id.date); 1563 long timestamp = cursor.getLong(COLUMN_DATE); 1564 Date date = new Date(timestamp); 1565 if (Utility.isDateToday(date)) { 1566 text = mTimeFormat.format(date); 1567 } else { 1568 text = mDateFormat.format(date); 1569 } 1570 dateView.setText(text); 1571 1572 if (itemView.mRead) { 1573 subjectView.setTypeface(Typeface.DEFAULT); 1574 fromView.setTypeface(Typeface.DEFAULT); 1575 fromView.setTextColor(mTextColorSecondary); 1576 view.setBackgroundDrawable(context.getResources().getDrawable( 1577 R.drawable.message_list_item_background_read)); 1578 } else { 1579 subjectView.setTypeface(Typeface.DEFAULT_BOLD); 1580 fromView.setTypeface(Typeface.DEFAULT_BOLD); 1581 fromView.setTextColor(mTextColorPrimary); 1582 view.setBackgroundDrawable(context.getResources().getDrawable( 1583 R.drawable.message_list_item_background_unread)); 1584 } 1585 1586 ImageView selectedView = (ImageView) view.findViewById(R.id.selected); 1587 selectedView.setImageDrawable(itemView.mSelected ? mSelectedIconOn : mSelectedIconOff); 1588 1589 ImageView favoriteView = (ImageView) view.findViewById(R.id.favorite); 1590 favoriteView.setImageDrawable(itemView.mFavorite ? mFavoriteIconOn : mFavoriteIconOff); 1591 } 1592 1593 @Override 1594 public View newView(Context context, Cursor cursor, ViewGroup parent) { 1595 return mInflater.inflate(R.layout.message_list_item, parent, false); 1596 } 1597 1598 /** 1599 * This is used as a callback from the list items, to set the selected state 1600 * 1601 * @param itemView the item being changed 1602 * @param newSelected the new value of the selected flag (checkbox state) 1603 */ 1604 public void updateSelected(MessageListItem itemView, boolean newSelected) { 1605 ImageView selectedView = (ImageView) itemView.findViewById(R.id.selected); 1606 selectedView.setImageDrawable(newSelected ? mSelectedIconOn : mSelectedIconOff); 1607 1608 // Set checkbox state in list, and show/hide panel if necessary 1609 Long id = Long.valueOf(itemView.mMessageId); 1610 if (newSelected) { 1611 mChecked.add(id); 1612 } else { 1613 mChecked.remove(id); 1614 } 1615 1616 MessageList.this.showMultiPanel(mChecked.size() > 0); 1617 } 1618 1619 /** 1620 * This is used as a callback from the list items, to set the favorite state 1621 * 1622 * @param itemView the item being changed 1623 * @param newFavorite the new value of the favorite flag (star state) 1624 */ 1625 public void updateFavorite(MessageListItem itemView, boolean newFavorite) { 1626 ImageView favoriteView = (ImageView) itemView.findViewById(R.id.favorite); 1627 favoriteView.setImageDrawable(newFavorite ? mFavoriteIconOn : mFavoriteIconOff); 1628 onSetMessageFavorite(itemView.mMessageId, newFavorite); 1629 } 1630 } 1631} 1632