MessageList.java revision 754240bcf3ccc8492a50ba9ee8056b34f6e4e8d0
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 if (c == null || c.isClosed()) { 756 return false; 757 } 758 c.moveToPosition(-1); 759 while (c.moveToNext()) { 760 long id = c.getInt(MessageListAdapter.COLUMN_ID); 761 if (selectedSet.contains(Long.valueOf(id))) { 762 if (c.getInt(column_id) == (defaultflag? 1 : 0)) { 763 return true; 764 } 765 } 766 } 767 return false; 768 } 769 770 /** 771 * Implements a timed refresh of "stale" mailboxes. This should only happen when 772 * multiple conditions are true, including: 773 * Only when the user explicitly opens the mailbox (not onResume, for example) 774 * Only for real, non-push mailboxes 775 * Only when the mailbox is "stale" (currently set to 5 minutes since last refresh) 776 */ 777 private void autoRefreshStaleMailbox() { 778 if (!mCanAutoRefresh 779 || (mListAdapter.getCursor() == null) // Check if messages info is loaded 780 || (mPushModeMailbox != null && mPushModeMailbox) // Check the push mode 781 || (mMailboxId < 0)) { // Check if this mailbox is synthetic/combined 782 return; 783 } 784 mCanAutoRefresh = false; 785 if (!Email.mailboxRequiresRefresh(mMailboxId)) { 786 return; 787 } 788 onRefresh(); 789 } 790 791 private void updateFooterButtonNames () { 792 // Show "unread_action" when one or more read messages are selected. 793 if (testMultiple(mListAdapter.getSelectedSet(), MessageListAdapter.COLUMN_READ, true)) { 794 mReadUnreadButton.setText(R.string.unread_action); 795 } else { 796 mReadUnreadButton.setText(R.string.read_action); 797 } 798 // Show "set_star_action" when one or more un-starred messages are selected. 799 if (testMultiple(mListAdapter.getSelectedSet(), 800 MessageListAdapter.COLUMN_FAVORITE, false)) { 801 mFavoriteButton.setText(R.string.set_star_action); 802 } else { 803 mFavoriteButton.setText(R.string.remove_star_action); 804 } 805 } 806 807 /** 808 * Show or hide the panel of multi-select options 809 */ 810 private void showMultiPanel(boolean show) { 811 if (show && mMultiSelectPanel.getVisibility() != View.VISIBLE) { 812 mMultiSelectPanel.setVisibility(View.VISIBLE); 813 mMultiSelectPanel.startAnimation( 814 AnimationUtils.loadAnimation(this, R.anim.footer_appear)); 815 } else if (!show && mMultiSelectPanel.getVisibility() != View.GONE) { 816 mMultiSelectPanel.setVisibility(View.GONE); 817 mMultiSelectPanel.startAnimation( 818 AnimationUtils.loadAnimation(this, R.anim.footer_disappear)); 819 } 820 if (show) { 821 updateFooterButtonNames(); 822 } 823 } 824 825 /** 826 * Add the fixed footer view if appropriate (not always - not all accounts & mailboxes). 827 * 828 * Here are some rules (finish this list): 829 * 830 * Any merged, synced box (except send): refresh 831 * Any push-mode account: refresh 832 * Any non-push-mode account: load more 833 * Any outbox (send again): 834 * 835 * @param mailboxId the ID of the mailbox 836 */ 837 private void addFooterView(long mailboxId, long accountId, int mailboxType) { 838 // first, look for shortcuts that don't need us to spin up a DB access task 839 if (mailboxId == Mailbox.QUERY_ALL_INBOXES 840 || mailboxId == Mailbox.QUERY_ALL_UNREAD 841 || mailboxId == Mailbox.QUERY_ALL_FAVORITES) { 842 finishFooterView(LIST_FOOTER_MODE_REFRESH); 843 return; 844 } 845 if (mailboxId == Mailbox.QUERY_ALL_DRAFTS || mailboxType == Mailbox.TYPE_DRAFTS) { 846 finishFooterView(LIST_FOOTER_MODE_NONE); 847 return; 848 } 849 if (mailboxId == Mailbox.QUERY_ALL_OUTBOX || mailboxType == Mailbox.TYPE_OUTBOX) { 850 finishFooterView(LIST_FOOTER_MODE_SEND); 851 return; 852 } 853 854 // We don't know enough to select the footer command type (yet), so we'll 855 // launch an async task to do the remaining lookups and decide what to do 856 mSetFooterTask = new SetFooterTask(); 857 mSetFooterTask.execute(mailboxId, accountId); 858 } 859 860 private final static String[] MAILBOX_ACCOUNT_AND_TYPE_PROJECTION = 861 new String[] { MailboxColumns.ACCOUNT_KEY, MailboxColumns.TYPE }; 862 863 private class SetFooterTask extends AsyncTask<Long, Void, Integer> { 864 /** 865 * There are two operational modes here, requiring different lookup. 866 * mailboxIs != -1: A specific mailbox - check its type, then look up its account 867 * accountId != -1: A specific account - look up the account 868 */ 869 @Override 870 protected Integer doInBackground(Long... params) { 871 long mailboxId = params[0]; 872 long accountId = params[1]; 873 int mailboxType = -1; 874 if (mailboxId != -1) { 875 try { 876 Uri uri = ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId); 877 Cursor c = mResolver.query(uri, MAILBOX_ACCOUNT_AND_TYPE_PROJECTION, 878 null, null, null); 879 if (c.moveToFirst()) { 880 try { 881 accountId = c.getLong(0); 882 mailboxType = c.getInt(1); 883 } finally { 884 c.close(); 885 } 886 } 887 } catch (IllegalArgumentException iae) { 888 // can't do any more here 889 return LIST_FOOTER_MODE_NONE; 890 } 891 } 892 switch (mailboxType) { 893 case Mailbox.TYPE_OUTBOX: 894 return LIST_FOOTER_MODE_SEND; 895 case Mailbox.TYPE_DRAFTS: 896 return LIST_FOOTER_MODE_NONE; 897 } 898 if (accountId != -1) { 899 // This is inefficient but the best fix is not here but in isMessagingController 900 Account account = Account.restoreAccountWithId(MessageList.this, accountId); 901 if (account != null) { 902 mPushModeMailbox = account.mSyncInterval == Account.CHECK_INTERVAL_PUSH; 903 if (MessageList.this.mController.isMessagingController(account)) { 904 return LIST_FOOTER_MODE_MORE; // IMAP or POP 905 } else { 906 return LIST_FOOTER_MODE_NONE; // EAS 907 } 908 } 909 } 910 return LIST_FOOTER_MODE_NONE; 911 } 912 913 @Override 914 protected void onPostExecute(Integer listFooterMode) { 915 if (listFooterMode == null) { 916 return; 917 } 918 finishFooterView(listFooterMode); 919 } 920 } 921 922 /** 923 * Add the fixed footer view as specified, and set up the test as well. 924 * 925 * @param listFooterMode the footer mode we've determined should be used for this list 926 */ 927 private void finishFooterView(int listFooterMode) { 928 mListFooterMode = listFooterMode; 929 if (mListFooterMode != LIST_FOOTER_MODE_NONE) { 930 mListFooterView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)) 931 .inflate(R.layout.message_list_item_footer, mListView, false); 932 mList.addFooterView(mListFooterView); 933 setListAdapter(mListAdapter); 934 935 mListFooterProgress = mListFooterView.findViewById(R.id.progress); 936 mListFooterText = (TextView) mListFooterView.findViewById(R.id.main_text); 937 setListFooterText(false); 938 } 939 } 940 941 /** 942 * Set the list footer text based on mode and "active" status 943 */ 944 private void setListFooterText(boolean active) { 945 if (mListFooterMode != LIST_FOOTER_MODE_NONE) { 946 int footerTextId = 0; 947 switch (mListFooterMode) { 948 case LIST_FOOTER_MODE_REFRESH: 949 footerTextId = active ? R.string.status_loading_more 950 : R.string.refresh_action; 951 break; 952 case LIST_FOOTER_MODE_MORE: 953 footerTextId = active ? R.string.status_loading_more 954 : R.string.message_list_load_more_messages_action; 955 break; 956 case LIST_FOOTER_MODE_SEND: 957 footerTextId = active ? R.string.status_sending_messages 958 : R.string.message_list_send_pending_messages_action; 959 break; 960 } 961 mListFooterText.setText(footerTextId); 962 } 963 } 964 965 /** 966 * Handle a click in the list footer, which changes meaning depending on what we're looking at. 967 */ 968 private void doFooterClick() { 969 switch (mListFooterMode) { 970 case LIST_FOOTER_MODE_NONE: // should never happen 971 break; 972 case LIST_FOOTER_MODE_REFRESH: 973 onRefresh(); 974 break; 975 case LIST_FOOTER_MODE_MORE: 976 onLoadMoreMessages(); 977 break; 978 case LIST_FOOTER_MODE_SEND: 979 onSendPendingMessages(); 980 break; 981 } 982 } 983 984 /** 985 * Async task for finding a single mailbox by type (possibly even going to the network). 986 * 987 * This is much too complex, as implemented. It uses this AsyncTask to check for a mailbox, 988 * then (if not found) a Controller call to refresh mailboxes from the server, and a handler 989 * to relaunch this task (a 2nd time) to read the results of the network refresh. The core 990 * problem is that we have two different non-UI-thread jobs (reading DB and reading network) 991 * and two different paradigms for dealing with them. Some unification would be needed here 992 * to make this cleaner. 993 * 994 * TODO: If this problem spreads to other operations, find a cleaner way to handle it. 995 */ 996 private class FindMailboxTask extends AsyncTask<Void, Void, Long> { 997 998 private long mAccountId; 999 private int mMailboxType; 1000 private boolean mOkToRecurse; 1001 1002 /** 1003 * Special constructor to cache some local info 1004 */ 1005 public FindMailboxTask(long accountId, int mailboxType, boolean okToRecurse) { 1006 mAccountId = accountId; 1007 mMailboxType = mailboxType; 1008 mOkToRecurse = okToRecurse; 1009 } 1010 1011 @Override 1012 protected Long doInBackground(Void... params) { 1013 // See if we can find the requested mailbox in the DB. 1014 long mailboxId = Mailbox.findMailboxOfType(MessageList.this, mAccountId, mMailboxType); 1015 if (mailboxId == Mailbox.NO_MAILBOX && mOkToRecurse) { 1016 // Not found - launch network lookup 1017 mControllerCallback.mWaitForMailboxType = mMailboxType; 1018 mController.updateMailboxList(mAccountId, mControllerCallback); 1019 } 1020 return mailboxId; 1021 } 1022 1023 @Override 1024 protected void onPostExecute(Long mailboxId) { 1025 if (mailboxId == null) { 1026 return; 1027 } 1028 if (mailboxId != Mailbox.NO_MAILBOX) { 1029 mMailboxId = mailboxId; 1030 mSetTitleTask = new SetTitleTask(mMailboxId); 1031 mSetTitleTask.execute(); 1032 mLoadMessagesTask = new LoadMessagesTask(mMailboxId, mAccountId); 1033 mLoadMessagesTask.execute(); 1034 } 1035 } 1036 } 1037 1038 /** 1039 * Async task for loading a single folder out of the UI thread 1040 * 1041 * The code here (for merged boxes) is a placeholder/hack and should be replaced. Some 1042 * specific notes: 1043 * TODO: Move the double query into a specialized URI that returns all inbox messages 1044 * and do the dirty work in raw SQL in the provider. 1045 * TODO: Generalize the query generation so we can reuse it in MessageView (for next/prev) 1046 */ 1047 private class LoadMessagesTask extends AsyncTask<Void, Void, Cursor> { 1048 1049 private long mMailboxKey; 1050 private long mAccountKey; 1051 1052 /** 1053 * Special constructor to cache some local info 1054 */ 1055 public LoadMessagesTask(long mailboxKey, long accountKey) { 1056 mMailboxKey = mailboxKey; 1057 mAccountKey = accountKey; 1058 } 1059 1060 @Override 1061 protected Cursor doInBackground(Void... params) { 1062 String selection = 1063 Utility.buildMailboxIdSelection(MessageList.this.mResolver, mMailboxKey); 1064 Cursor c = MessageList.this.managedQuery( 1065 EmailContent.Message.CONTENT_URI, 1066 MessageList.this.mListAdapter.PROJECTION, 1067 selection, null, 1068 EmailContent.MessageColumns.TIMESTAMP + " DESC"); 1069 return c; 1070 } 1071 1072 @Override 1073 protected void onPostExecute(Cursor cursor) { 1074 if (cursor == null || cursor.isClosed()) { 1075 return; 1076 } 1077 MessageList.this.mListAdapter.changeCursor(cursor); 1078 // changeCursor occurs the jumping of position in ListView, so it's need to restore 1079 // the position; 1080 restoreListPosition(); 1081 autoRefreshStaleMailbox(); 1082 // Reset the "new messages" count in the service, since we're seeing them now 1083 if (mMailboxKey == Mailbox.QUERY_ALL_INBOXES) { 1084 MailService.resetNewMessageCount(MessageList.this, -1); 1085 } else if (mMailboxKey >= 0 && mAccountKey != -1) { 1086 MailService.resetNewMessageCount(MessageList.this, mAccountKey); 1087 } 1088 } 1089 } 1090 1091 private class SetTitleTask extends AsyncTask<Void, Void, String[]> { 1092 1093 private long mMailboxKey; 1094 1095 public SetTitleTask(long mailboxKey) { 1096 mMailboxKey = mailboxKey; 1097 } 1098 1099 @Override 1100 protected String[] doInBackground(Void... params) { 1101 // Check special Mailboxes 1102 if (mMailboxKey == Mailbox.QUERY_ALL_INBOXES) { 1103 return new String[] {null, 1104 getString(R.string.account_folder_list_summary_inbox)}; 1105 } else if (mMailboxKey == Mailbox.QUERY_ALL_FAVORITES) { 1106 return new String[] {null, 1107 getString(R.string.account_folder_list_summary_starred)}; 1108 } else if (mMailboxKey == Mailbox.QUERY_ALL_DRAFTS) { 1109 return new String[] {null, 1110 getString(R.string.account_folder_list_summary_drafts)}; 1111 } else if (mMailboxKey == Mailbox.QUERY_ALL_OUTBOX) { 1112 return new String[] {null, 1113 getString(R.string.account_folder_list_summary_outbox)}; 1114 } 1115 String accountName = null; 1116 String mailboxName = null; 1117 String accountKey = null; 1118 Cursor c = MessageList.this.mResolver.query(Mailbox.CONTENT_URI, 1119 MAILBOX_NAME_PROJECTION, ID_SELECTION, 1120 new String[] { Long.toString(mMailboxKey) }, null); 1121 try { 1122 if (c.moveToFirst()) { 1123 mailboxName = Utility.FolderProperties.getInstance(MessageList.this) 1124 .getDisplayName(c.getInt(MAILBOX_NAME_COLUMN_TYPE)); 1125 if (mailboxName == null) { 1126 mailboxName = c.getString(MAILBOX_NAME_COLUMN_ID); 1127 } 1128 accountKey = c.getString(MAILBOX_NAME_COLUMN_ACCOUNT_KEY); 1129 } 1130 } finally { 1131 c.close(); 1132 } 1133 if (accountKey != null) { 1134 c = MessageList.this.mResolver.query(Account.CONTENT_URI, 1135 ACCOUNT_NAME_PROJECTION, ID_SELECTION, new String[] { accountKey }, 1136 null); 1137 try { 1138 if (c.moveToFirst()) { 1139 accountName = c.getString(ACCOUNT_DISPLAY_NAME_COLUMN_ID); 1140 } 1141 } finally { 1142 c.close(); 1143 } 1144 } 1145 return new String[] {accountName, mailboxName}; 1146 } 1147 1148 @Override 1149 protected void onPostExecute(String[] names) { 1150 if (names == null) { 1151 return; 1152 } 1153 if (names[0] != null) { 1154 mRightTitle.setText(names[0]); 1155 } 1156 if (names[1] != null) { 1157 mLeftTitle.setText(names[1]); 1158 } 1159 } 1160 } 1161 1162 /** 1163 * Handler for UI-thread operations (when called from callbacks or any other threads) 1164 */ 1165 class MessageListHandler extends Handler { 1166 private static final int MSG_PROGRESS = 1; 1167 private static final int MSG_LOOKUP_MAILBOX_TYPE = 2; 1168 private static final int MSG_ERROR_BANNER = 3; 1169 private static final int MSG_REQUERY_LIST = 4; 1170 1171 @Override 1172 public void handleMessage(android.os.Message msg) { 1173 switch (msg.what) { 1174 case MSG_PROGRESS: 1175 boolean visible = (msg.arg1 != 0); 1176 if (visible) { 1177 mProgressIcon.setVisibility(View.VISIBLE); 1178 } else { 1179 mProgressIcon.setVisibility(View.GONE); 1180 } 1181 if (mListFooterProgress != null) { 1182 mListFooterProgress.setVisibility(visible ? View.VISIBLE : View.GONE); 1183 } 1184 setListFooterText(visible); 1185 break; 1186 case MSG_LOOKUP_MAILBOX_TYPE: 1187 // kill running async task, if any 1188 if (mFindMailboxTask != null && 1189 mFindMailboxTask.getStatus() != FindMailboxTask.Status.FINISHED) { 1190 mFindMailboxTask.cancel(true); 1191 mFindMailboxTask = null; 1192 } 1193 // start new one. do not recurse back to controller. 1194 long accountId = ((Long)msg.obj).longValue(); 1195 int mailboxType = msg.arg1; 1196 mFindMailboxTask = new FindMailboxTask(accountId, mailboxType, false); 1197 mFindMailboxTask.execute(); 1198 break; 1199 case MSG_ERROR_BANNER: 1200 String message = (String) msg.obj; 1201 boolean isVisible = mErrorBanner.getVisibility() == View.VISIBLE; 1202 if (message != null) { 1203 mErrorBanner.setText(message); 1204 if (!isVisible) { 1205 mErrorBanner.setVisibility(View.VISIBLE); 1206 mErrorBanner.startAnimation( 1207 AnimationUtils.loadAnimation( 1208 MessageList.this, R.anim.header_appear)); 1209 } 1210 } else { 1211 if (isVisible) { 1212 mErrorBanner.setVisibility(View.GONE); 1213 mErrorBanner.startAnimation( 1214 AnimationUtils.loadAnimation( 1215 MessageList.this, R.anim.header_disappear)); 1216 } 1217 } 1218 break; 1219 case MSG_REQUERY_LIST: 1220 mListAdapter.doRequery(); 1221 if (mMultiSelectPanel.getVisibility() == View.VISIBLE) { 1222 updateFooterButtonNames(); 1223 } 1224 break; 1225 default: 1226 super.handleMessage(msg); 1227 } 1228 } 1229 1230 /** 1231 * Call from any thread to start/stop progress indicator(s) 1232 * @param progress true to start, false to stop 1233 */ 1234 public void progress(boolean progress) { 1235 android.os.Message msg = android.os.Message.obtain(); 1236 msg.what = MSG_PROGRESS; 1237 msg.arg1 = progress ? 1 : 0; 1238 sendMessage(msg); 1239 } 1240 1241 /** 1242 * Called from any thread to look for a mailbox of a specific type. This is designed 1243 * to be called from the Controller's MailboxList callback; It instructs the async task 1244 * not to recurse, in case the mailbox is not found after this. 1245 * 1246 * See FindMailboxTask for more notes on this handler. 1247 */ 1248 public void lookupMailboxType(long accountId, int mailboxType) { 1249 android.os.Message msg = android.os.Message.obtain(); 1250 msg.what = MSG_LOOKUP_MAILBOX_TYPE; 1251 msg.arg1 = mailboxType; 1252 msg.obj = Long.valueOf(accountId); 1253 sendMessage(msg); 1254 } 1255 1256 /** 1257 * Called from any thread to show or hide the connection error banner. 1258 * @param message error text or null to hide the box 1259 */ 1260 public void showErrorBanner(String message) { 1261 android.os.Message msg = android.os.Message.obtain(); 1262 msg.what = MSG_ERROR_BANNER; 1263 msg.obj = message; 1264 sendMessage(msg); 1265 } 1266 1267 /** 1268 * Called from any thread to signal that the list adapter should requery and update. 1269 */ 1270 public void requeryList() { 1271 sendEmptyMessage(MSG_REQUERY_LIST); 1272 } 1273 } 1274 1275 /** 1276 * Callback for async Controller results. 1277 */ 1278 private class ControllerResults implements Controller.Result { 1279 1280 // This is used to alter the connection banner operation for sending messages 1281 MessagingException mSendMessageException; 1282 1283 // These are preset for use by updateMailboxListCallback 1284 int mWaitForMailboxType = -1; 1285 1286 // TODO check accountKey and only react to relevant notifications 1287 public void updateMailboxListCallback(MessagingException result, long accountKey, 1288 int progress) { 1289 // no updateBanner here, we are only listing a single mailbox 1290 updateProgress(result, progress); 1291 if (progress == 100) { 1292 mHandler.lookupMailboxType(accountKey, mWaitForMailboxType); 1293 } 1294 } 1295 1296 // TODO check accountKey and only react to relevant notifications 1297 public void updateMailboxCallback(MessagingException result, long accountKey, 1298 long mailboxKey, int progress, int numNewMessages) { 1299 updateBanner(result, progress, mailboxKey); 1300 if (result != null || progress == 100) { 1301 Email.updateMailboxRefreshTime(mMailboxId); 1302 } 1303 updateProgress(result, progress); 1304 } 1305 1306 public void loadMessageForViewCallback(MessagingException result, long messageId, 1307 int progress) { 1308 } 1309 1310 public void loadAttachmentCallback(MessagingException result, long messageId, 1311 long attachmentId, int progress) { 1312 } 1313 1314 public void serviceCheckMailCallback(MessagingException result, long accountId, 1315 long mailboxId, int progress, long tag) { 1316 } 1317 1318 /** 1319 * We alter the updateBanner hysteresis here to capture any failures and handle 1320 * them just once at the end. This callback is overly overloaded: 1321 * result == null, messageId == -1, progress == 0: start batch send 1322 * result == null, messageId == xx, progress == 0: start sending one message 1323 * result == xxxx, messageId == xx, progress == 0; failed sending one message 1324 * result == null, messageId == -1, progres == 100; finish sending batch 1325 */ 1326 public void sendMailCallback(MessagingException result, long accountId, long messageId, 1327 int progress) { 1328 if (mListFooterMode == LIST_FOOTER_MODE_SEND) { 1329 // reset captured error when we start sending one or more messages 1330 if (messageId == -1 && result == null && progress == 0) { 1331 mSendMessageException = null; 1332 } 1333 // capture first exception that comes along 1334 if (result != null && mSendMessageException == null) { 1335 mSendMessageException = result; 1336 } 1337 // if we're completing the sequence, change the banner state 1338 if (messageId == -1 && progress == 100) { 1339 updateBanner(mSendMessageException, progress, mMailboxId); 1340 } 1341 // always update the spinner, which has less state to worry about 1342 updateProgress(result, progress); 1343 } 1344 } 1345 1346 private void updateProgress(MessagingException result, int progress) { 1347 if (result != null || progress == 100) { 1348 mHandler.progress(false); 1349 } else if (progress == 0) { 1350 mHandler.progress(true); 1351 } 1352 } 1353 1354 /** 1355 * Show or hide the connection error banner, and convert the various MessagingException 1356 * variants into localizable text. There is hysteresis in the show/hide logic: Once shown, 1357 * the banner will remain visible until some progress is made on the connection. The 1358 * goal is to keep it from flickering during retries in a bad connection state. 1359 * 1360 * @param result 1361 * @param progress 1362 */ 1363 private void updateBanner(MessagingException result, int progress, long mailboxKey) { 1364 if (mailboxKey != mMailboxId) { 1365 return; 1366 } 1367 if (result != null) { 1368 int id = R.string.status_network_error; 1369 if (result instanceof AuthenticationFailedException) { 1370 id = R.string.account_setup_failed_dlg_auth_message; 1371 } else if (result instanceof CertificateValidationException) { 1372 id = R.string.account_setup_failed_dlg_certificate_message; 1373 } else { 1374 switch (result.getExceptionType()) { 1375 case MessagingException.IOERROR: 1376 id = R.string.account_setup_failed_ioerror; 1377 break; 1378 case MessagingException.TLS_REQUIRED: 1379 id = R.string.account_setup_failed_tls_required; 1380 break; 1381 case MessagingException.AUTH_REQUIRED: 1382 id = R.string.account_setup_failed_auth_required; 1383 break; 1384 case MessagingException.GENERAL_SECURITY: 1385 id = R.string.account_setup_failed_security; 1386 break; 1387 } 1388 } 1389 mHandler.showErrorBanner(getString(id)); 1390 } else if (progress > 0) { 1391 mHandler.showErrorBanner(null); 1392 } 1393 } 1394 } 1395 1396 /** 1397 * This class implements the adapter for displaying messages based on cursors. 1398 */ 1399 /* package */ class MessageListAdapter extends CursorAdapter { 1400 1401 public static final int COLUMN_ID = 0; 1402 public static final int COLUMN_MAILBOX_KEY = 1; 1403 public static final int COLUMN_ACCOUNT_KEY = 2; 1404 public static final int COLUMN_DISPLAY_NAME = 3; 1405 public static final int COLUMN_SUBJECT = 4; 1406 public static final int COLUMN_DATE = 5; 1407 public static final int COLUMN_READ = 6; 1408 public static final int COLUMN_FAVORITE = 7; 1409 public static final int COLUMN_ATTACHMENTS = 8; 1410 1411 public final String[] PROJECTION = new String[] { 1412 EmailContent.RECORD_ID, MessageColumns.MAILBOX_KEY, MessageColumns.ACCOUNT_KEY, 1413 MessageColumns.DISPLAY_NAME, MessageColumns.SUBJECT, MessageColumns.TIMESTAMP, 1414 MessageColumns.FLAG_READ, MessageColumns.FLAG_FAVORITE, MessageColumns.FLAG_ATTACHMENT, 1415 }; 1416 1417 Context mContext; 1418 private LayoutInflater mInflater; 1419 private Drawable mAttachmentIcon; 1420 private Drawable mFavoriteIconOn; 1421 private Drawable mFavoriteIconOff; 1422 private Drawable mSelectedIconOn; 1423 private Drawable mSelectedIconOff; 1424 1425 private ColorStateList mTextColorPrimary; 1426 private ColorStateList mTextColorSecondary; 1427 1428 // Timer to control the refresh rate of the list 1429 private final RefreshTimer mRefreshTimer = new RefreshTimer(); 1430 // Last time we allowed a refresh of the list 1431 private long mLastRefreshTime = 0; 1432 // How long we want to wait for refreshes (a good starting guess) 1433 // I suspect this could be lowered down to even 1000 or so, but this seems ok for now 1434 private static final long REFRESH_INTERVAL_MS = 2500; 1435 1436 private java.text.DateFormat mDateFormat; 1437 private java.text.DateFormat mDayFormat; 1438 private java.text.DateFormat mTimeFormat; 1439 1440 private HashSet<Long> mChecked = new HashSet<Long>(); 1441 1442 public MessageListAdapter(Context context) { 1443 super(context, null, true); 1444 mContext = context; 1445 mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 1446 1447 Resources resources = context.getResources(); 1448 mAttachmentIcon = resources.getDrawable(R.drawable.ic_mms_attachment_small); 1449 mFavoriteIconOn = resources.getDrawable(R.drawable.btn_star_big_buttonless_dark_on); 1450 mFavoriteIconOff = resources.getDrawable(R.drawable.btn_star_big_buttonless_dark_off); 1451 mSelectedIconOn = resources.getDrawable(R.drawable.btn_check_buttonless_dark_on); 1452 mSelectedIconOff = resources.getDrawable(R.drawable.btn_check_buttonless_dark_off); 1453 1454 Theme theme = context.getTheme(); 1455 TypedArray array; 1456 array = theme.obtainStyledAttributes(new int[] { android.R.attr.textColorPrimary }); 1457 mTextColorPrimary = resources.getColorStateList(array.getResourceId(0, 0)); 1458 array = theme.obtainStyledAttributes(new int[] { android.R.attr.textColorSecondary }); 1459 mTextColorSecondary = resources.getColorStateList(array.getResourceId(0, 0)); 1460 1461 mDateFormat = android.text.format.DateFormat.getDateFormat(context); // short date 1462 mDayFormat = android.text.format.DateFormat.getDateFormat(context); // TODO: day 1463 mTimeFormat = android.text.format.DateFormat.getTimeFormat(context); // 12/24 time 1464 } 1465 1466 /** 1467 * We override onContentChange to throttle the refresh, which can happen way too often 1468 * on syncing a large list (up to many times per second). This will prevent ANR's during 1469 * initial sync and potentially at other times as well. 1470 */ 1471 @Override 1472 protected synchronized void onContentChanged() { 1473 if (mCursor != null && !mCursor.isClosed()) { 1474 long sinceRefresh = SystemClock.elapsedRealtime() - mLastRefreshTime; 1475 mRefreshTimer.schedule(REFRESH_INTERVAL_MS - sinceRefresh); 1476 } 1477 } 1478 1479 /** 1480 * Called in UI thread only, from Handler, to complete the requery that we 1481 * intercepted in onContentChanged(). 1482 */ 1483 public void doRequery() { 1484 if (mCursor != null && !mCursor.isClosed()) { 1485 mDataValid = mCursor.requery(); 1486 notifyDataSetChanged(); 1487 } 1488 } 1489 1490 class RefreshTimer extends Timer { 1491 private TimerTask timerTask = null; 1492 1493 protected void clear() { 1494 timerTask = null; 1495 } 1496 1497 protected synchronized void schedule(long delay) { 1498 if (timerTask != null) return; 1499 if (delay < 0) { 1500 refreshList(); 1501 } else { 1502 timerTask = new RefreshTimerTask(); 1503 schedule(timerTask, delay); 1504 } 1505 } 1506 } 1507 1508 class RefreshTimerTask extends TimerTask { 1509 @Override 1510 public void run() { 1511 refreshList(); 1512 } 1513 } 1514 1515 /** 1516 * Do the work of requerying the list and notifying the UI of changed data 1517 * Make sure we call notifyDataSetChanged on the UI thread. 1518 */ 1519 private synchronized void refreshList() { 1520 if (Email.LOGD) { 1521 Log.d("messageList", "refresh: " 1522 + (SystemClock.elapsedRealtime() - mLastRefreshTime) + "ms"); 1523 } 1524 mHandler.requeryList(); 1525 mLastRefreshTime = SystemClock.elapsedRealtime(); 1526 mRefreshTimer.clear(); 1527 } 1528 1529 public Set<Long> getSelectedSet() { 1530 return mChecked; 1531 } 1532 1533 @Override 1534 public void bindView(View view, Context context, Cursor cursor) { 1535 // Reset the view (in case it was recycled) and prepare for binding 1536 MessageListItem itemView = (MessageListItem) view; 1537 itemView.bindViewInit(this, true); 1538 1539 // Load the public fields in the view (for later use) 1540 itemView.mMessageId = cursor.getLong(COLUMN_ID); 1541 itemView.mMailboxId = cursor.getLong(COLUMN_MAILBOX_KEY); 1542 itemView.mAccountId = cursor.getLong(COLUMN_ACCOUNT_KEY); 1543 itemView.mRead = cursor.getInt(COLUMN_READ) != 0; 1544 itemView.mFavorite = cursor.getInt(COLUMN_FAVORITE) != 0; 1545 itemView.mSelected = mChecked.contains(Long.valueOf(itemView.mMessageId)); 1546 1547 // Load the UI 1548 View chipView = view.findViewById(R.id.chip); 1549 int chipResId = mColorChipResIds[(int)itemView.mAccountId % mColorChipResIds.length]; 1550 chipView.setBackgroundResource(chipResId); 1551 1552 TextView fromView = (TextView) view.findViewById(R.id.from); 1553 String text = cursor.getString(COLUMN_DISPLAY_NAME); 1554 fromView.setText(text); 1555 1556 TextView subjectView = (TextView) view.findViewById(R.id.subject); 1557 text = cursor.getString(COLUMN_SUBJECT); 1558 subjectView.setText(text); 1559 1560 boolean hasAttachments = cursor.getInt(COLUMN_ATTACHMENTS) != 0; 1561 subjectView.setCompoundDrawablesWithIntrinsicBounds(null, null, 1562 hasAttachments ? mAttachmentIcon : null, null); 1563 1564 // TODO ui spec suggests "time", "day", "date" - implement "day" 1565 TextView dateView = (TextView) view.findViewById(R.id.date); 1566 long timestamp = cursor.getLong(COLUMN_DATE); 1567 Date date = new Date(timestamp); 1568 if (Utility.isDateToday(date)) { 1569 text = mTimeFormat.format(date); 1570 } else { 1571 text = mDateFormat.format(date); 1572 } 1573 dateView.setText(text); 1574 1575 if (itemView.mRead) { 1576 subjectView.setTypeface(Typeface.DEFAULT); 1577 fromView.setTypeface(Typeface.DEFAULT); 1578 fromView.setTextColor(mTextColorSecondary); 1579 view.setBackgroundDrawable(context.getResources().getDrawable( 1580 R.drawable.message_list_item_background_read)); 1581 } else { 1582 subjectView.setTypeface(Typeface.DEFAULT_BOLD); 1583 fromView.setTypeface(Typeface.DEFAULT_BOLD); 1584 fromView.setTextColor(mTextColorPrimary); 1585 view.setBackgroundDrawable(context.getResources().getDrawable( 1586 R.drawable.message_list_item_background_unread)); 1587 } 1588 1589 ImageView selectedView = (ImageView) view.findViewById(R.id.selected); 1590 selectedView.setImageDrawable(itemView.mSelected ? mSelectedIconOn : mSelectedIconOff); 1591 1592 ImageView favoriteView = (ImageView) view.findViewById(R.id.favorite); 1593 favoriteView.setImageDrawable(itemView.mFavorite ? mFavoriteIconOn : mFavoriteIconOff); 1594 } 1595 1596 @Override 1597 public View newView(Context context, Cursor cursor, ViewGroup parent) { 1598 return mInflater.inflate(R.layout.message_list_item, parent, false); 1599 } 1600 1601 /** 1602 * This is used as a callback from the list items, to set the selected state 1603 * 1604 * @param itemView the item being changed 1605 * @param newSelected the new value of the selected flag (checkbox state) 1606 */ 1607 public void updateSelected(MessageListItem itemView, boolean newSelected) { 1608 ImageView selectedView = (ImageView) itemView.findViewById(R.id.selected); 1609 selectedView.setImageDrawable(newSelected ? mSelectedIconOn : mSelectedIconOff); 1610 1611 // Set checkbox state in list, and show/hide panel if necessary 1612 Long id = Long.valueOf(itemView.mMessageId); 1613 if (newSelected) { 1614 mChecked.add(id); 1615 } else { 1616 mChecked.remove(id); 1617 } 1618 1619 MessageList.this.showMultiPanel(mChecked.size() > 0); 1620 } 1621 1622 /** 1623 * This is used as a callback from the list items, to set the favorite state 1624 * 1625 * @param itemView the item being changed 1626 * @param newFavorite the new value of the favorite flag (star state) 1627 */ 1628 public void updateFavorite(MessageListItem itemView, boolean newFavorite) { 1629 ImageView favoriteView = (ImageView) itemView.findViewById(R.id.favorite); 1630 favoriteView.setImageDrawable(newFavorite ? mFavoriteIconOn : mFavoriteIconOff); 1631 onSetMessageFavorite(itemView.mMessageId, newFavorite); 1632 } 1633 } 1634} 1635