MessageList.java revision df86adf87328a439347260331592509787020420
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.R; 21import com.android.email.Utility; 22import com.android.email.activity.setup.AccountSettings; 23import com.android.email.mail.MessagingException; 24import com.android.email.provider.EmailContent; 25import com.android.email.provider.EmailContent.Account; 26import com.android.email.provider.EmailContent.AccountColumns; 27import com.android.email.provider.EmailContent.Mailbox; 28import com.android.email.provider.EmailContent.MailboxColumns; 29import com.android.email.provider.EmailContent.Message; 30import com.android.email.provider.EmailContent.MessageColumns; 31import com.android.email.service.MailService; 32 33import android.app.ListActivity; 34import android.app.NotificationManager; 35import android.content.ContentResolver; 36import android.content.ContentUris; 37import android.content.Context; 38import android.content.Intent; 39import android.content.res.Resources; 40import android.database.Cursor; 41import android.graphics.drawable.Drawable; 42import android.net.Uri; 43import android.os.AsyncTask; 44import android.os.Bundle; 45import android.os.Handler; 46import android.util.Log; 47import android.view.ContextMenu; 48import android.view.LayoutInflater; 49import android.view.Menu; 50import android.view.MenuItem; 51import android.view.View; 52import android.view.ViewGroup; 53import android.view.Window; 54import android.view.ContextMenu.ContextMenuInfo; 55import android.view.View.OnClickListener; 56import android.view.animation.AnimationUtils; 57import android.widget.AdapterView; 58import android.widget.CursorAdapter; 59import android.widget.ImageView; 60import android.widget.ListView; 61import android.widget.ProgressBar; 62import android.widget.TextView; 63import android.widget.Toast; 64import android.widget.AdapterView.OnItemClickListener; 65 66import java.util.Date; 67import java.util.HashSet; 68import java.util.Set; 69 70public class MessageList extends ListActivity implements OnItemClickListener, OnClickListener { 71 // Intent extras (internal to this activity) 72 private static final String EXTRA_ACCOUNT_ID = "com.android.email.activity._ACCOUNT_ID"; 73 private static final String EXTRA_MAILBOX_TYPE = "com.android.email.activity.MAILBOX_TYPE"; 74 private static final String EXTRA_MAILBOX_ID = "com.android.email.activity.MAILBOX_ID"; 75 76 // UI support 77 private ListView mListView; 78 private View mMultiSelectPanel; 79 private View mReadUnreadButton; 80 private View mFavoriteButton; 81 private View mDeleteButton; 82 private View mListFooterView; 83 private TextView mListFooterText; 84 private View mListFooterProgress; 85 86 private static final int LIST_FOOTER_MODE_NONE = 0; 87 private static final int LIST_FOOTER_MODE_REFRESH = 1; 88 private static final int LIST_FOOTER_MODE_MORE = 2; 89 private static final int LIST_FOOTER_MODE_SEND = 3; 90 private int mListFooterMode; 91 92 private MessageListAdapter mListAdapter; 93 private MessageListHandler mHandler = new MessageListHandler(); 94 private Controller mController = Controller.getInstance(getApplication()); 95 private ControllerResults mControllerCallback = new ControllerResults(); 96 private TextView mLeftTitle; 97 private TextView mRightTitle; 98 private ProgressBar mProgressIcon; 99 100 private static final int[] mColorChipResIds = new int[] { 101 R.drawable.appointment_indicator_leftside_1, 102 R.drawable.appointment_indicator_leftside_2, 103 R.drawable.appointment_indicator_leftside_3, 104 R.drawable.appointment_indicator_leftside_4, 105 R.drawable.appointment_indicator_leftside_5, 106 R.drawable.appointment_indicator_leftside_6, 107 R.drawable.appointment_indicator_leftside_7, 108 R.drawable.appointment_indicator_leftside_8, 109 R.drawable.appointment_indicator_leftside_9, 110 R.drawable.appointment_indicator_leftside_10, 111 R.drawable.appointment_indicator_leftside_11, 112 R.drawable.appointment_indicator_leftside_12, 113 R.drawable.appointment_indicator_leftside_13, 114 R.drawable.appointment_indicator_leftside_14, 115 R.drawable.appointment_indicator_leftside_15, 116 R.drawable.appointment_indicator_leftside_16, 117 R.drawable.appointment_indicator_leftside_17, 118 R.drawable.appointment_indicator_leftside_18, 119 R.drawable.appointment_indicator_leftside_19, 120 R.drawable.appointment_indicator_leftside_20, 121 R.drawable.appointment_indicator_leftside_21, 122 }; 123 124 // DB access 125 private ContentResolver mResolver; 126 private long mMailboxId; 127 private LoadMessagesTask mLoadMessagesTask; 128 private FindMailboxTask mFindMailboxTask; 129 private SetTitleTask mSetTitleTask; 130 private SetFooterTask mSetFooterTask; 131 132 public final static String[] MAILBOX_FIND_INBOX_PROJECTION = new String[] { 133 EmailContent.RECORD_ID, MailboxColumns.TYPE, MailboxColumns.FLAG_VISIBLE 134 }; 135 136 private static final int MAILBOX_NAME_COLUMN_ID = 0; 137 private static final int MAILBOX_NAME_COLUMN_ACCOUNT_KEY = 1; 138 private static final int MAILBOX_NAME_COLUMN_TYPE = 2; 139 private static final String[] MAILBOX_NAME_PROJECTION = new String[] { 140 MailboxColumns.DISPLAY_NAME, MailboxColumns.ACCOUNT_KEY, 141 MailboxColumns.TYPE}; 142 143 private static final int ACCOUNT_DISPLAY_NAME_COLUMN_ID = 0; 144 private static final String[] ACCOUNT_NAME_PROJECTION = new String[] { 145 AccountColumns.DISPLAY_NAME }; 146 147 private static final String ID_SELECTION = EmailContent.RECORD_ID + "=?"; 148 149 /** 150 * Open a specific mailbox. 151 * 152 * TODO This should just shortcut to a more generic version that can accept a list of 153 * accounts/mailboxes (e.g. merged inboxes). 154 * 155 * @param context 156 * @param id mailbox key 157 */ 158 public static void actionHandleMailbox(Context context, long id) { 159 Intent intent = new Intent(context, MessageList.class); 160 intent.putExtra(EXTRA_MAILBOX_ID, id); 161 context.startActivity(intent); 162 } 163 164 /** 165 * Open a specific mailbox by account & type 166 * 167 * @param context The caller's context (for generating an intent) 168 * @param accountId The account to open 169 * @param mailboxType the type of mailbox to open (e.g. @see EmailContent.Mailbox.TYPE_INBOX) 170 */ 171 public static void actionHandleAccount(Context context, long accountId, int mailboxType) { 172 Intent intent = new Intent(context, MessageList.class); 173 intent.putExtra(EXTRA_ACCOUNT_ID, accountId); 174 intent.putExtra(EXTRA_MAILBOX_TYPE, mailboxType); 175 context.startActivity(intent); 176 } 177 178 /** 179 * Return an intent to open a specific mailbox by account & type. It will also clear 180 * notifications. 181 * 182 * @param context The caller's context (for generating an intent) 183 * @param accountId The account to open, or -1 184 * @param mailboxId the ID of the mailbox to open, or -1 185 * @param mailboxType the type of mailbox to open (e.g. @see Mailbox.TYPE_INBOX) or -1 186 */ 187 public static Intent actionHandleAccountIntent(Context context, long accountId, 188 long mailboxId, int mailboxType) { 189 Intent intent = new Intent(context, MessageList.class); 190 intent.putExtra(EXTRA_ACCOUNT_ID, accountId); 191 intent.putExtra(EXTRA_MAILBOX_ID, mailboxId); 192 intent.putExtra(EXTRA_MAILBOX_TYPE, mailboxType); 193 return intent; 194 } 195 196 /** 197 * Used for generating lightweight (Uri-only) intents. 198 * 199 * @param context Calling context for building the intent 200 * @param accountId The account of interest 201 * @param mailboxType The folder name to open (typically Mailbox.TYPE_INBOX) 202 * @return an Intent which can be used to view that account 203 */ 204 public static Intent actionHandleAccountUriIntent(Context context, long accountId, 205 int mailboxType) { 206 Intent i = actionHandleAccountIntent(context, accountId, -1, mailboxType); 207 i.removeExtra(EXTRA_ACCOUNT_ID); 208 Uri uri = ContentUris.withAppendedId(Account.CONTENT_URI, accountId); 209 i.setData(uri); 210 return i; 211 } 212 213 @Override 214 public void onCreate(Bundle icicle) { 215 super.onCreate(icicle); 216 217 requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 218 setContentView(R.layout.message_list); 219 getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, 220 R.layout.list_title); 221 222 mListView = getListView(); 223 mMultiSelectPanel = findViewById(R.id.footer_organize); 224 mReadUnreadButton = findViewById(R.id.btn_read_unread); 225 mFavoriteButton = findViewById(R.id.btn_multi_favorite); 226 mDeleteButton = findViewById(R.id.btn_multi_delete); 227 228 mLeftTitle = (TextView) findViewById(R.id.title_left_text); 229 mRightTitle = (TextView) findViewById(R.id.title_right_text); 230 mProgressIcon = (ProgressBar) findViewById(R.id.title_progress_icon); 231 232 mReadUnreadButton.setOnClickListener(this); 233 mFavoriteButton.setOnClickListener(this); 234 mDeleteButton.setOnClickListener(this); 235 236 mListView.setOnItemClickListener(this); 237 mListView.setItemsCanFocus(false); 238 registerForContextMenu(mListView); 239 240 mListAdapter = new MessageListAdapter(this); 241 setListAdapter(mListAdapter); 242 243 mResolver = getContentResolver(); 244 245 // TODO extend this to properly deal with multiple mailboxes, cursor, etc. 246 247 // Select 'by id' or 'by type' or 'by uri' mode and launch appropriate queries 248 249 mMailboxId = getIntent().getLongExtra(EXTRA_MAILBOX_ID, -1); 250 if (mMailboxId != -1) { 251 // Specific mailbox ID was provided - go directly to it 252 mSetTitleTask = new SetTitleTask(mMailboxId); 253 mSetTitleTask.execute(); 254 mLoadMessagesTask = new LoadMessagesTask(mMailboxId, -1); 255 mLoadMessagesTask.execute(); 256 addFooterView(mMailboxId, -1, -1); 257 } else { 258 long accountId = -1; 259 int mailboxType = getIntent().getIntExtra(EXTRA_MAILBOX_TYPE, Mailbox.TYPE_INBOX); 260 Uri uri = getIntent().getData(); 261 if (uri != null 262 && "content".equals(uri.getScheme()) 263 && EmailContent.AUTHORITY.equals(uri.getAuthority())) { 264 // A content URI was provided - try to look up the account 265 String accountIdString = uri.getPathSegments().get(1); 266 if (accountIdString != null) { 267 accountId = Long.parseLong(accountIdString); 268 } 269 mFindMailboxTask = new FindMailboxTask(accountId, mailboxType, false); 270 mFindMailboxTask.execute(); 271 } else { 272 // Go by account id + type 273 accountId = getIntent().getLongExtra(EXTRA_ACCOUNT_ID, -1); 274 mFindMailboxTask = new FindMailboxTask(accountId, mailboxType, true); 275 mFindMailboxTask.execute(); 276 } 277 addFooterView(-1, accountId, mailboxType); 278 } 279 280 // TODO set title to "account > mailbox (#unread)" 281 } 282 283 @Override 284 public void onPause() { 285 super.onPause(); 286 mController.removeResultCallback(mControllerCallback); 287 } 288 289 @Override 290 public void onResume() { 291 super.onResume(); 292 mController.addResultCallback(mControllerCallback); 293 294 // clear notifications here 295 NotificationManager notificationManager = (NotificationManager) 296 getSystemService(Context.NOTIFICATION_SERVICE); 297 notificationManager.cancel(MailService.NEW_MESSAGE_NOTIFICATION_ID); 298 } 299 300 @Override 301 protected void onDestroy() { 302 super.onDestroy(); 303 304 if (mLoadMessagesTask != null && 305 mLoadMessagesTask.getStatus() != LoadMessagesTask.Status.FINISHED) { 306 mLoadMessagesTask.cancel(true); 307 mLoadMessagesTask = null; 308 } 309 if (mFindMailboxTask != null && 310 mFindMailboxTask.getStatus() != FindMailboxTask.Status.FINISHED) { 311 mFindMailboxTask.cancel(true); 312 mFindMailboxTask = null; 313 } 314 if (mSetTitleTask != null && 315 mSetTitleTask.getStatus() != SetTitleTask.Status.FINISHED) { 316 mSetTitleTask.cancel(true); 317 mSetTitleTask = null; 318 } 319 if (mSetFooterTask != null && 320 mSetFooterTask.getStatus() != SetTitleTask.Status.FINISHED) { 321 mSetFooterTask.cancel(true); 322 mSetFooterTask = null; 323 } 324 } 325 326 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 327 if (view != mListFooterView) { 328 MessageListItem itemView = (MessageListItem) view; 329 onOpenMessage(id, itemView.mMailboxId); 330 } else { 331 doFooterClick(); 332 } 333 } 334 335 public void onClick(View v) { 336 switch (v.getId()) { 337 case R.id.btn_read_unread: 338 onMultiToggleRead(mListAdapter.getSelectedSet()); 339 break; 340 case R.id.btn_multi_favorite: 341 onMultiToggleFavorite(mListAdapter.getSelectedSet()); 342 break; 343 case R.id.btn_multi_delete: 344 onMultiDelete(mListAdapter.getSelectedSet()); 345 break; 346 } 347 } 348 349 @Override 350 public boolean onCreateOptionsMenu(Menu menu) { 351 super.onCreateOptionsMenu(menu); 352 getMenuInflater().inflate(R.menu.message_list_option, menu); 353 return true; 354 } 355 356 @Override 357 public boolean onOptionsItemSelected(MenuItem item) { 358 switch (item.getItemId()) { 359 case R.id.refresh: 360 onRefresh(); 361 return true; 362 case R.id.accounts: 363 onAccounts(); 364 return true; 365 case R.id.compose: 366 onCompose(); 367 return true; 368 case R.id.account_settings: 369 onEditAccount(); 370 return true; 371 default: 372 return super.onOptionsItemSelected(item); 373 } 374 } 375 376 @Override 377 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { 378 super.onCreateContextMenu(menu, v, menuInfo); 379 // There is no context menu for the list footer 380 if (v == mListFooterView) { 381 return; 382 } 383 384 AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; 385 MessageListItem itemView = (MessageListItem) info.targetView; 386 387 Cursor c = (Cursor) mListView.getItemAtPosition(info.position); 388 String messageName = c.getString(MessageListAdapter.COLUMN_SUBJECT); 389 390 menu.setHeaderTitle(messageName); 391 392 // TODO: There is no context menu for the outbox 393 // TODO: There is probably a special context menu for the trash 394 // TODO: Should not be reading from DB in UI thread 395 EmailContent.Mailbox mailbox = EmailContent.Mailbox.restoreMailboxWithId(this, 396 itemView.mMailboxId); 397 398 switch (mailbox.mType) { 399 case EmailContent.Mailbox.TYPE_DRAFTS: 400 getMenuInflater().inflate(R.menu.message_list_context, menu); 401 break; 402 case EmailContent.Mailbox.TYPE_OUTBOX: 403 break; 404 default: 405 getMenuInflater().inflate(R.menu.message_list_context, menu); 406 getMenuInflater().inflate(R.menu.message_list_context_extra, menu); 407 // The default menu contains "mark as read". If the message is read, change 408 // the menu text to "mark as unread." 409 if (itemView.mRead) { 410 menu.findItem(R.id.mark_as_read).setTitle(R.string.mark_as_unread_action); 411 } 412 break; 413 } 414 } 415 416 @Override 417 public boolean onContextItemSelected(MenuItem item) { 418 AdapterView.AdapterContextMenuInfo info = 419 (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); 420 MessageListItem itemView = (MessageListItem) info.targetView; 421 422 switch (item.getItemId()) { 423 case R.id.open: 424 onOpenMessage(info.id, itemView.mMailboxId); 425 break; 426 case R.id.delete: 427 onDelete(info.id, itemView.mAccountId); 428 break; 429 case R.id.reply: 430 //onReply(holder); 431 break; 432 case R.id.reply_all: 433 //onReplyAll(holder); 434 break; 435 case R.id.forward: 436 //onForward(holder); 437 break; 438 case R.id.mark_as_read: 439 onSetMessageRead(info.id, !itemView.mRead); 440 break; 441 } 442 return super.onContextItemSelected(item); 443 } 444 445 private void onRefresh() { 446 // TODO: This needs to loop through all open mailboxes (there might be more than one) 447 // TODO: Should not be reading from DB in UI thread - need a cleaner way to get accountId 448 if (mMailboxId >= 0) { 449 Mailbox mailbox = Mailbox.restoreMailboxWithId(this, mMailboxId); 450 mController.updateMailbox(mailbox.mAccountKey, mMailboxId, mControllerCallback); 451 } 452 } 453 454 private void onAccounts() { 455 AccountFolderList.actionShowAccounts(this); 456 finish(); 457 } 458 459 private long lookupAccountIdFromMailboxId(long mailboxId) { 460 // TODO: Select correct account to send from when there are multiple mailboxes 461 // TODO: Should not be reading from DB in UI thread 462 if (mailboxId < 0) { 463 return -1; // no info, default account 464 } 465 EmailContent.Mailbox mailbox = 466 EmailContent.Mailbox.restoreMailboxWithId(this, mailboxId); 467 return mailbox.mAccountKey; 468 } 469 470 private void onCompose() { 471 MessageCompose.actionCompose(this, lookupAccountIdFromMailboxId(mMailboxId)); 472 } 473 474 private void onEditAccount() { 475 AccountSettings.actionSettings(this, lookupAccountIdFromMailboxId(mMailboxId)); 476 } 477 478 private void onOpenMessage(long messageId, long mailboxId) { 479 // TODO: Should not be reading from DB in UI thread 480 EmailContent.Mailbox mailbox = EmailContent.Mailbox.restoreMailboxWithId(this, mailboxId); 481 482 if (mailbox.mType == EmailContent.Mailbox.TYPE_DRAFTS) { 483 MessageCompose.actionEditDraft(this, messageId); 484 } else { 485 MessageView.actionView(this, messageId, mailboxId); 486 } 487 } 488 489 private void onLoadMoreMessages() { 490 if (mMailboxId >= 0) { 491 mController.loadMoreMessages(mMailboxId, mControllerCallback); 492 } 493 } 494 495 private void onSendPendingMessages() { 496 long accountId = lookupAccountIdFromMailboxId(mMailboxId); 497 mController.sendPendingMessages(accountId, mControllerCallback); 498 } 499 500 private void onDelete(long messageId, long accountId) { 501 mController.deleteMessage(messageId, accountId); 502 Toast.makeText(this, R.string.message_deleted_toast, Toast.LENGTH_SHORT).show(); 503 } 504 505 private void onSetMessageRead(long messageId, boolean newRead) { 506 mController.setMessageRead(messageId, newRead); 507 } 508 509 private void onSetMessageFavorite(long messageId, boolean newFavorite) { 510 mController.setMessageFavorite(messageId, newFavorite); 511 } 512 513 /** 514 * Toggles a set read/unread states. Note, the default behavior is "mark unread", so the 515 * sense of the helper methods is "true=unread". 516 * 517 * @param selectedSet The current list of selected items 518 */ 519 private void onMultiToggleRead(Set<Long> selectedSet) { 520 toggleMultiple(selectedSet, new MultiToggleHelper() { 521 522 public boolean getField(long messageId, Cursor c) { 523 return c.getInt(MessageListAdapter.COLUMN_READ) == 0; 524 } 525 526 public boolean setField(long messageId, Cursor c, boolean newValue) { 527 boolean oldValue = getField(messageId, c); 528 if (oldValue != newValue) { 529 onSetMessageRead(messageId, !newValue); 530 return true; 531 } 532 return false; 533 } 534 }); 535 } 536 537 /** 538 * Toggles a set of favorites (stars) 539 * 540 * @param selectedSet The current list of selected items 541 */ 542 private void onMultiToggleFavorite(Set<Long> selectedSet) { 543 toggleMultiple(selectedSet, new MultiToggleHelper() { 544 545 public boolean getField(long messageId, Cursor c) { 546 return c.getInt(MessageListAdapter.COLUMN_FAVORITE) != 0; 547 } 548 549 public boolean setField(long messageId, Cursor c, boolean newValue) { 550 boolean oldValue = getField(messageId, c); 551 if (oldValue != newValue) { 552 onSetMessageFavorite(messageId, newValue); 553 return true; 554 } 555 return false; 556 } 557 }); 558 } 559 560 private void onMultiDelete(Set<Long> selectedSet) { 561 // Clone the set, because deleting is going to thrash things 562 HashSet<Long> cloneSet = new HashSet<Long>(selectedSet); 563 for (Long id : cloneSet) { 564 mController.deleteMessage(id, -1); 565 } 566 // TODO: count messages and show "n messages deleted" 567 Toast.makeText(this, R.string.message_deleted_toast, Toast.LENGTH_SHORT).show(); 568 selectedSet.clear(); 569 showMultiPanel(false); 570 } 571 572 private interface MultiToggleHelper { 573 /** 574 * Return true if the field of interest is "set". If one or more are false, then our 575 * bulk action will be to "set". If all are set, our bulk action will be to "clear". 576 * @param messageId the message id of the current message 577 * @param c the cursor, positioned to the item of interest 578 * @return true if the field at this row is "set" 579 */ 580 public boolean getField(long messageId, Cursor c); 581 582 /** 583 * Set or clear the field of interest. Return true if a change was made. 584 * @param messageId the message id of the current message 585 * @param c the cursor, positioned to the item of interest 586 * @param newValue the new value to be set at this row 587 * @return true if a change was actually made 588 */ 589 public boolean setField(long messageId, Cursor c, boolean newValue); 590 } 591 592 /** 593 * Toggle multiple fields in a message, using the following logic: If one or more fields 594 * are "clear", then "set" them. If all fields are "set", then "clear" them all. 595 * 596 * @param selectedSet the set of messages that are selected 597 * @param helper functions to implement the specific getter & setter 598 * @return the number of messages that were updated 599 */ 600 private int toggleMultiple(Set<Long> selectedSet, MultiToggleHelper helper) { 601 Cursor c = mListAdapter.getCursor(); 602 boolean anyWereFound = false; 603 boolean allWereSet = true; 604 605 c.moveToPosition(-1); 606 while (c.moveToNext()) { 607 long id = c.getInt(MessageListAdapter.COLUMN_ID); 608 if (selectedSet.contains(Long.valueOf(id))) { 609 anyWereFound = true; 610 if (!helper.getField(id, c)) { 611 allWereSet = false; 612 break; 613 } 614 } 615 } 616 617 int numChanged = 0; 618 619 if (anyWereFound) { 620 boolean newValue = !allWereSet; 621 c.moveToPosition(-1); 622 while (c.moveToNext()) { 623 long id = c.getInt(MessageListAdapter.COLUMN_ID); 624 if (selectedSet.contains(Long.valueOf(id))) { 625 if (helper.setField(id, c, newValue)) { 626 ++numChanged; 627 } 628 } 629 } 630 } 631 632 return numChanged; 633 } 634 635 /** 636 * Show or hide the panel of multi-select options 637 */ 638 private void showMultiPanel(boolean show) { 639 if (show && mMultiSelectPanel.getVisibility() != View.VISIBLE) { 640 mMultiSelectPanel.setVisibility(View.VISIBLE); 641 mMultiSelectPanel.startAnimation( 642 AnimationUtils.loadAnimation(this, R.anim.footer_appear)); 643 644 } else if (!show && mMultiSelectPanel.getVisibility() != View.GONE) { 645 mMultiSelectPanel.setVisibility(View.GONE); 646 mMultiSelectPanel.startAnimation( 647 AnimationUtils.loadAnimation(this, R.anim.footer_disappear)); 648 } 649 } 650 651 /** 652 * Add the fixed footer view if appropriate (not always - not all accounts & mailboxes). 653 * 654 * Here are some rules (finish this list): 655 * 656 * Any merged box (except send): refresh 657 * Any push-mode account: refresh 658 * Any non-push-mode account: load more 659 * Any outbox (send again): 660 * 661 * @param mailboxId the ID of the mailbox 662 */ 663 private void addFooterView(long mailboxId, long accountId, int mailboxType) { 664 // first, look for shortcuts that don't need us to spin up a DB access task 665 if (mailboxId == Mailbox.QUERY_ALL_INBOXES 666 || mailboxId == Mailbox.QUERY_ALL_UNREAD 667 || mailboxId == Mailbox.QUERY_ALL_FAVORITES 668 || mailboxId == Mailbox.QUERY_ALL_DRAFTS) { 669 finishFooterView(LIST_FOOTER_MODE_REFRESH); 670 return; 671 } 672 if (mailboxId == Mailbox.QUERY_ALL_OUTBOX || mailboxType == Mailbox.TYPE_OUTBOX) { 673 finishFooterView(LIST_FOOTER_MODE_SEND); 674 return; 675 } 676 677 // We don't know enough to select the footer command type (yet), so we'll 678 // launch an async task to do the remaining lookups and decide what to do 679 mSetFooterTask = new SetFooterTask(); 680 mSetFooterTask.execute(mailboxId, accountId); 681 } 682 683 private final static String[] MAILBOX_ACCOUNT_AND_TYPE_PROJECTION = 684 new String[] { MailboxColumns.ACCOUNT_KEY, MailboxColumns.TYPE }; 685 686 private class SetFooterTask extends AsyncTask<Long, Void, Integer> { 687 /** 688 * There are two operational modes here, requiring different lookup. 689 * mailboxIs != -1: A specific mailbox - check its type, then look up its account 690 * accountId != -1: A specific account - look up the account 691 */ 692 @Override 693 protected Integer doInBackground(Long... params) { 694 long mailboxId = params[0]; 695 long accountId = params[1]; 696 int mailboxType = -1; 697 if (mailboxId != -1) { 698 try { 699 Uri uri = ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId); 700 Cursor c = mResolver.query(uri, MAILBOX_ACCOUNT_AND_TYPE_PROJECTION, 701 null, null, null); 702 if (c.moveToFirst()) { 703 try { 704 accountId = c.getLong(0); 705 mailboxType = c.getInt(1); 706 } finally { 707 c.close(); 708 } 709 } 710 } catch (IllegalArgumentException iae) { 711 // can't do any more here 712 return LIST_FOOTER_MODE_NONE; 713 } 714 } 715 if (mailboxType == Mailbox.TYPE_OUTBOX) { 716 return LIST_FOOTER_MODE_SEND; 717 } 718 if (accountId != -1) { 719 // This is inefficient but the best fix is not here but in isMessagingController 720 Account account = Account.restoreAccountWithId(MessageList.this, accountId); 721 if (account != null) { 722 if (MessageList.this.mController.isMessagingController(account)) { 723 return LIST_FOOTER_MODE_MORE; // IMAP or POP 724 } else { 725 return LIST_FOOTER_MODE_REFRESH; // EAS 726 } 727 } 728 } 729 return LIST_FOOTER_MODE_NONE; 730 } 731 732 @Override 733 protected void onPostExecute(Integer listFooterMode) { 734 finishFooterView(listFooterMode); 735 } 736 } 737 738 /** 739 * Add the fixed footer view as specified, and set up the test as well. 740 * 741 * @param listFooterMode the footer mode we've determined should be used for this list 742 */ 743 private void finishFooterView(int listFooterMode) { 744 mListFooterMode = listFooterMode; 745 if (mListFooterMode != LIST_FOOTER_MODE_NONE) { 746 mListFooterView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)) 747 .inflate(R.layout.message_list_item_footer, mListView, false); 748 mList.addFooterView(mListFooterView); 749 setListAdapter(mListAdapter); 750 751 mListFooterProgress = mListFooterView.findViewById(R.id.progress); 752 mListFooterText = (TextView) mListFooterView.findViewById(R.id.main_text); 753 setListFooterText(false); 754 } 755 } 756 757 /** 758 * Set the list footer text based on mode and "active" status 759 */ 760 private void setListFooterText(boolean active) { 761 if (mListFooterMode != LIST_FOOTER_MODE_NONE) { 762 int footerTextId = 0; 763 switch (mListFooterMode) { 764 case LIST_FOOTER_MODE_REFRESH: 765 footerTextId = active ? R.string.status_loading_more 766 : R.string.refresh_action; 767 break; 768 case LIST_FOOTER_MODE_MORE: 769 footerTextId = active ? R.string.status_loading_more 770 : R.string.message_list_load_more_messages_action; 771 break; 772 case LIST_FOOTER_MODE_SEND: 773 footerTextId = active ? R.string.status_sending_messages 774 : R.string.message_list_send_pending_messages_action; 775 break; 776 } 777 mListFooterText.setText(footerTextId); 778 } 779 } 780 781 /** 782 * Handle a click in the list footer, which changes meaning depending on what we're looking at. 783 */ 784 private void doFooterClick() { 785 switch (mListFooterMode) { 786 case LIST_FOOTER_MODE_NONE: // should never happen 787 break; 788 case LIST_FOOTER_MODE_REFRESH: 789 onRefresh(); 790 break; 791 case LIST_FOOTER_MODE_MORE: 792 onLoadMoreMessages(); 793 break; 794 case LIST_FOOTER_MODE_SEND: 795 onSendPendingMessages(); 796 break; 797 } 798 } 799 800 /** 801 * Async task for finding a single mailbox by type (possibly even going to the network). 802 * 803 * This is much too complex, as implemented. It uses this AsyncTask to check for a mailbox, 804 * then (if not found) a Controller call to refresh mailboxes from the server, and a handler 805 * to relaunch this task (a 2nd time) to read the results of the network refresh. The core 806 * problem is that we have two different non-UI-thread jobs (reading DB and reading network) 807 * and two different paradigms for dealing with them. Some unification would be needed here 808 * to make this cleaner. 809 * 810 * TODO: If this problem spreads to other operations, find a cleaner way to handle it. 811 */ 812 private class FindMailboxTask extends AsyncTask<Void, Void, Long> { 813 814 private long mAccountId; 815 private int mMailboxType; 816 private boolean mOkToRecurse; 817 818 /** 819 * Special constructor to cache some local info 820 */ 821 public FindMailboxTask(long accountId, int mailboxType, boolean okToRecurse) { 822 mAccountId = accountId; 823 mMailboxType = mailboxType; 824 mOkToRecurse = okToRecurse; 825 } 826 827 @Override 828 protected Long doInBackground(Void... params) { 829 // See if we can find the requested mailbox in the DB. 830 long mailboxId = Mailbox.findMailboxOfType(MessageList.this, mAccountId, mMailboxType); 831 if (mailboxId == -1 && mOkToRecurse) { 832 // Not found - launch network lookup 833 mControllerCallback.mWaitForMailboxType = mMailboxType; 834 mController.updateMailboxList(mAccountId, mControllerCallback); 835 } 836 return mailboxId; 837 } 838 839 @Override 840 protected void onPostExecute(Long mailboxId) { 841 if (mailboxId != -1) { 842 mMailboxId = mailboxId; 843 mSetTitleTask = new SetTitleTask(mMailboxId); 844 mSetTitleTask.execute(); 845 mLoadMessagesTask = new LoadMessagesTask(mMailboxId, mAccountId); 846 mLoadMessagesTask.execute(); 847 } 848 } 849 } 850 851 /** 852 * Async task for loading a single folder out of the UI thread 853 * 854 * The code here (for merged boxes) is a placeholder/hack and should be replaced. Some 855 * specific notes: 856 * TODO: Move the double query into a specialized URI that returns all inbox messages 857 * and do the dirty work in raw SQL in the provider. 858 * TODO: Generalize the query generation so we can reuse it in MessageView (for next/prev) 859 */ 860 private class LoadMessagesTask extends AsyncTask<Void, Void, Cursor> { 861 862 private long mMailboxKey; 863 private long mAccountKey; 864 865 /** 866 * Special constructor to cache some local info 867 */ 868 public LoadMessagesTask(long mailboxKey, long accountKey) { 869 mMailboxKey = mailboxKey; 870 mAccountKey = accountKey; 871 } 872 873 @Override 874 protected Cursor doInBackground(Void... params) { 875 String selection = 876 Utility.buildMailboxIdSelection(MessageList.this.mResolver, mMailboxKey); 877 Cursor c = MessageList.this.managedQuery( 878 EmailContent.Message.CONTENT_URI, 879 MessageList.this.mListAdapter.PROJECTION, 880 selection, null, 881 EmailContent.MessageColumns.TIMESTAMP + " DESC"); 882 return c; 883 } 884 885 @Override 886 protected void onPostExecute(Cursor cursor) { 887 MessageList.this.mListAdapter.changeCursor(cursor); 888 889 // TODO: remove this hack and only update at the right time 890 if (cursor != null && cursor.getCount() == 0) { 891 onRefresh(); 892 } 893 894 // Reset the "new messages" count in the service, since we're seeing them now 895 if (mMailboxKey == Mailbox.QUERY_ALL_INBOXES) { 896 MailService.resetNewMessageCount(MessageList.this, -1); 897 } else if (mMailboxKey >= 0 && mAccountKey != -1) { 898 MailService.resetNewMessageCount(MessageList.this, mAccountKey); 899 } 900 } 901 } 902 903 private class SetTitleTask extends AsyncTask<Void, Void, String[]> { 904 905 private long mMailboxKey; 906 907 public SetTitleTask(long mailboxKey) { 908 mMailboxKey = mailboxKey; 909 } 910 911 @Override 912 protected String[] doInBackground(Void... params) { 913 // Check special Mailboxes 914 if (mMailboxKey == Mailbox.QUERY_ALL_INBOXES) { 915 return new String[] {null, 916 getString(R.string.account_folder_list_summary_inbox)}; 917 } else if (mMailboxKey == Mailbox.QUERY_ALL_FAVORITES) { 918 return new String[] {null, 919 getString(R.string.account_folder_list_summary_favorite)}; 920 } else if (mMailboxKey == Mailbox.QUERY_ALL_DRAFTS) { 921 return new String[] {null, 922 getString(R.string.account_folder_list_summary_drafts)}; 923 } else if (mMailboxKey == Mailbox.QUERY_ALL_OUTBOX) { 924 return new String[] {null, 925 getString(R.string.account_folder_list_summary_outbox)}; 926 } 927 String accountName = null; 928 String mailboxName = null; 929 String accountKey = null; 930 Cursor c = MessageList.this.mResolver.query(Mailbox.CONTENT_URI, 931 MAILBOX_NAME_PROJECTION, ID_SELECTION, 932 new String[] { Long.toString(mMailboxKey) }, null); 933 try { 934 if (c.moveToFirst()) { 935 mailboxName = Utility.FolderProperties.getInstance(MessageList.this) 936 .getDisplayName(c.getInt(MAILBOX_NAME_COLUMN_TYPE)); 937 if (mailboxName == null) { 938 mailboxName = c.getString(MAILBOX_NAME_COLUMN_ID); 939 } 940 accountKey = c.getString(MAILBOX_NAME_COLUMN_ACCOUNT_KEY); 941 } 942 } finally { 943 c.close(); 944 } 945 if (accountKey != null) { 946 c = MessageList.this.mResolver.query(Account.CONTENT_URI, 947 ACCOUNT_NAME_PROJECTION, ID_SELECTION, new String[] { accountKey }, 948 null); 949 try { 950 if (c.moveToFirst()) { 951 accountName = c.getString(ACCOUNT_DISPLAY_NAME_COLUMN_ID); 952 } 953 } finally { 954 c.close(); 955 } 956 } 957 return new String[] {accountName, mailboxName}; 958 } 959 960 @Override 961 protected void onPostExecute(String[] names) { 962 Log.d("MessageList", "ACCOUNT:" + names[0] + "MAILBOX" + names[1]); 963 if (names[0] != null) { 964 mRightTitle.setText(names[0]); 965 } 966 if (names[1] != null) { 967 mLeftTitle.setText(names[1]); 968 } 969 } 970 } 971 972 /** 973 * Handler for UI-thread operations (when called from callbacks or any other threads) 974 */ 975 class MessageListHandler extends Handler { 976 private static final int MSG_PROGRESS = 1; 977 private static final int MSG_LOOKUP_MAILBOX_TYPE = 2; 978 979 @Override 980 public void handleMessage(android.os.Message msg) { 981 switch (msg.what) { 982 case MSG_PROGRESS: 983 boolean visible = (msg.arg1 != 0); 984 if (visible) { 985 mProgressIcon.setVisibility(View.VISIBLE); 986 } else { 987 mProgressIcon.setVisibility(View.GONE); 988 } 989 if (mListFooterProgress != null) { 990 mListFooterProgress.setVisibility(visible ? View.VISIBLE : View.GONE); 991 } 992 setListFooterText(visible); 993 break; 994 case MSG_LOOKUP_MAILBOX_TYPE: 995 // kill running async task, if any 996 if (mFindMailboxTask != null && 997 mFindMailboxTask.getStatus() != FindMailboxTask.Status.FINISHED) { 998 mFindMailboxTask.cancel(true); 999 mFindMailboxTask = null; 1000 } 1001 // start new one. do not recurse back to controller. 1002 long accountId = ((Long)msg.obj).longValue(); 1003 int mailboxType = msg.arg1; 1004 mFindMailboxTask = new FindMailboxTask(accountId, mailboxType, false); 1005 mFindMailboxTask.execute(); 1006 break; 1007 default: 1008 super.handleMessage(msg); 1009 } 1010 } 1011 1012 /** 1013 * Call from any thread to start/stop progress indicator(s) 1014 * @param progress true to start, false to stop 1015 */ 1016 public void progress(boolean progress) { 1017 android.os.Message msg = android.os.Message.obtain(); 1018 msg.what = MSG_PROGRESS; 1019 msg.arg1 = progress ? 1 : 0; 1020 sendMessage(msg); 1021 } 1022 1023 /** 1024 * Called from any thread to look for a mailbox of a specific type. This is designed 1025 * to be called from the Controller's MailboxList callback; It instructs the async task 1026 * not to recurse, in case the mailbox is not found after this. 1027 * 1028 * See FindMailboxTask for more notes on this handler. 1029 */ 1030 public void lookupMailboxType(long accountId, int mailboxType) { 1031 android.os.Message msg = android.os.Message.obtain(); 1032 msg.what = MSG_LOOKUP_MAILBOX_TYPE; 1033 msg.arg1 = mailboxType; 1034 msg.obj = Long.valueOf(accountId); 1035 sendMessage(msg); 1036 } 1037 } 1038 1039 /** 1040 * Callback for async Controller results. 1041 */ 1042 private class ControllerResults implements Controller.Result { 1043 1044 // These are preset for use by updateMailboxListCallback 1045 int mWaitForMailboxType = -1; 1046 1047 // TODO report errors into UI 1048 // TODO check accountKey and only react to relevant notifications 1049 public void updateMailboxListCallback(MessagingException result, long accountKey, 1050 int progress) { 1051 if (progress == 0) { 1052 mHandler.progress(true); 1053 } else if (result != null || progress == 100) { 1054 mHandler.progress(false); 1055 if (mWaitForMailboxType != -1) { 1056 if (result == null) { 1057 mHandler.lookupMailboxType(accountKey, mWaitForMailboxType); 1058 } 1059 } 1060 } 1061 } 1062 1063 // TODO report errors into UI 1064 // TODO check accountKey and only react to relevant notifications 1065 public void updateMailboxCallback(MessagingException result, long accountKey, 1066 long mailboxKey, int progress, int numNewMessages) { 1067 if (progress == 0) { 1068 mHandler.progress(true); 1069 } else if (result != null || progress == 100) { 1070 mHandler.progress(false); 1071 } 1072 } 1073 1074 public void loadMessageForViewCallback(MessagingException result, long messageId, 1075 int progress) { 1076 } 1077 1078 public void loadAttachmentCallback(MessagingException result, long messageId, 1079 long attachmentId, int progress) { 1080 } 1081 1082 public void serviceCheckMailCallback(MessagingException result, long accountId, 1083 long mailboxId, int progress, long tag) { 1084 } 1085 1086 // TODO report errors into UI 1087 public void sendMailCallback(MessagingException result, long accountId, long messageId, 1088 int progress) { 1089 if (mListFooterMode == LIST_FOOTER_MODE_SEND) { 1090 if (progress == 0) { 1091 mHandler.progress(true); 1092 } else if (result != null || progress == 100) { 1093 mHandler.progress(false); 1094 } 1095 } 1096 } 1097 } 1098 1099 /** 1100 * This class implements the adapter for displaying messages based on cursors. 1101 */ 1102 /* package */ class MessageListAdapter extends CursorAdapter { 1103 1104 public static final int COLUMN_ID = 0; 1105 public static final int COLUMN_MAILBOX_KEY = 1; 1106 public static final int COLUMN_ACCOUNT_KEY = 2; 1107 public static final int COLUMN_DISPLAY_NAME = 3; 1108 public static final int COLUMN_SUBJECT = 4; 1109 public static final int COLUMN_DATE = 5; 1110 public static final int COLUMN_READ = 6; 1111 public static final int COLUMN_FAVORITE = 7; 1112 public static final int COLUMN_ATTACHMENTS = 8; 1113 1114 public final String[] PROJECTION = new String[] { 1115 EmailContent.RECORD_ID, MessageColumns.MAILBOX_KEY, MessageColumns.ACCOUNT_KEY, 1116 MessageColumns.DISPLAY_NAME, MessageColumns.SUBJECT, MessageColumns.TIMESTAMP, 1117 MessageColumns.FLAG_READ, MessageColumns.FLAG_FAVORITE, MessageColumns.FLAG_ATTACHMENT, 1118 }; 1119 1120 Context mContext; 1121 private LayoutInflater mInflater; 1122 private Drawable mAttachmentIcon; 1123 private Drawable mFavoriteIconOn; 1124 private Drawable mFavoriteIconOff; 1125 private Drawable mSelectedIconOn; 1126 private Drawable mSelectedIconOff; 1127 1128 private java.text.DateFormat mDateFormat; 1129 private java.text.DateFormat mDayFormat; 1130 private java.text.DateFormat mTimeFormat; 1131 1132 private HashSet<Long> mChecked = new HashSet<Long>(); 1133 1134 public MessageListAdapter(Context context) { 1135 super(context, null); 1136 mContext = context; 1137 mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 1138 1139 Resources resources = context.getResources(); 1140 mAttachmentIcon = resources.getDrawable(R.drawable.ic_mms_attachment_small); 1141 mFavoriteIconOn = resources.getDrawable(android.R.drawable.star_on); 1142 mFavoriteIconOff = resources.getDrawable(android.R.drawable.star_off); 1143 mSelectedIconOn = resources.getDrawable(R.drawable.btn_check_buttonless_on); 1144 mSelectedIconOff = resources.getDrawable(R.drawable.btn_check_buttonless_off); 1145 1146 mDateFormat = android.text.format.DateFormat.getDateFormat(context); // short date 1147 mDayFormat = android.text.format.DateFormat.getDateFormat(context); // TODO: day 1148 mTimeFormat = android.text.format.DateFormat.getTimeFormat(context); // 12/24 time 1149 } 1150 1151 public Set<Long> getSelectedSet() { 1152 return mChecked; 1153 } 1154 1155 @Override 1156 public void bindView(View view, Context context, Cursor cursor) { 1157 // Reset the view (in case it was recycled) and prepare for binding 1158 MessageListItem itemView = (MessageListItem) view; 1159 itemView.bindViewInit(this, true); 1160 1161 // Load the public fields in the view (for later use) 1162 itemView.mMessageId = cursor.getLong(COLUMN_ID); 1163 itemView.mMailboxId = cursor.getLong(COLUMN_MAILBOX_KEY); 1164 itemView.mAccountId = cursor.getLong(COLUMN_ACCOUNT_KEY); 1165 itemView.mRead = cursor.getInt(COLUMN_READ) != 0; 1166 itemView.mFavorite = cursor.getInt(COLUMN_FAVORITE) != 0; 1167 itemView.mSelected = mChecked.contains(Long.valueOf(itemView.mMessageId)); 1168 1169 // Load the UI 1170 View chipView = view.findViewById(R.id.chip); 1171 int chipResId = mColorChipResIds[(int)itemView.mAccountId % mColorChipResIds.length]; 1172 chipView.setBackgroundResource(chipResId); 1173 // TODO always display chip. Use other indications (e.g. boldface) for read/unread 1174 chipView.getBackground().setAlpha(itemView.mRead ? 100 : 255); 1175 1176 TextView fromView = (TextView) view.findViewById(R.id.from); 1177 String text = cursor.getString(COLUMN_DISPLAY_NAME); 1178 if (text != null) fromView.setText(text); 1179 1180 boolean hasAttachments = cursor.getInt(COLUMN_ATTACHMENTS) != 0; 1181 fromView.setCompoundDrawablesWithIntrinsicBounds(null, null, 1182 hasAttachments ? mAttachmentIcon : null, null); 1183 1184 TextView subjectView = (TextView) view.findViewById(R.id.subject); 1185 text = cursor.getString(COLUMN_SUBJECT); 1186 if (text != null) subjectView.setText(text); 1187 1188 // TODO ui spec suggests "time", "day", "date" - implement "day" 1189 TextView dateView = (TextView) view.findViewById(R.id.date); 1190 long timestamp = cursor.getLong(COLUMN_DATE); 1191 Date date = new Date(timestamp); 1192 if (Utility.isDateToday(date)) { 1193 text = mTimeFormat.format(date); 1194 } else { 1195 text = mDateFormat.format(date); 1196 } 1197 dateView.setText(text); 1198 1199 ImageView selectedView = (ImageView) view.findViewById(R.id.selected); 1200 selectedView.setImageDrawable(itemView.mSelected ? mSelectedIconOn : mSelectedIconOff); 1201 1202 ImageView favoriteView = (ImageView) view.findViewById(R.id.favorite); 1203 favoriteView.setImageDrawable(itemView.mFavorite ? mFavoriteIconOn : mFavoriteIconOff); 1204 } 1205 1206 @Override 1207 public View newView(Context context, Cursor cursor, ViewGroup parent) { 1208 return mInflater.inflate(R.layout.message_list_item, parent, false); 1209 } 1210 1211 /** 1212 * This is used as a callback from the list items, to set the selected state 1213 * 1214 * @param itemView the item being changed 1215 * @param newSelected the new value of the selected flag (checkbox state) 1216 */ 1217 public void updateSelected(MessageListItem itemView, boolean newSelected) { 1218 ImageView selectedView = (ImageView) itemView.findViewById(R.id.selected); 1219 selectedView.setImageDrawable(newSelected ? mSelectedIconOn : mSelectedIconOff); 1220 1221 // Set checkbox state in list, and show/hide panel if necessary 1222 Long id = Long.valueOf(itemView.mMessageId); 1223 if (newSelected) { 1224 mChecked.add(id); 1225 } else { 1226 mChecked.remove(id); 1227 } 1228 1229 MessageList.this.showMultiPanel(mChecked.size() > 0); 1230 } 1231 1232 /** 1233 * This is used as a callback from the list items, to set the favorite state 1234 * 1235 * @param itemView the item being changed 1236 * @param newFavorite the new value of the favorite flag (star state) 1237 */ 1238 public void updateFavorite(MessageListItem itemView, boolean newFavorite) { 1239 ImageView favoriteView = (ImageView) itemView.findViewById(R.id.favorite); 1240 favoriteView.setImageDrawable(newFavorite ? mFavoriteIconOn : mFavoriteIconOff); 1241 onSetMessageFavorite(itemView.mMessageId, newFavorite); 1242 } 1243 } 1244} 1245