MessageList.java revision dadba9949895696108b31124fc0c6aa1a297ab1c
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 // TODO: There is no context menu for the outbox 388 // TODO: There is probably a special context menu for the trash 389 // TODO: Should not be reading from DB in UI thread 390 EmailContent.Mailbox mailbox = EmailContent.Mailbox.restoreMailboxWithId(this, 391 itemView.mMailboxId); 392 393 switch (mailbox.mType) { 394 case EmailContent.Mailbox.TYPE_DRAFTS: 395 getMenuInflater().inflate(R.menu.message_list_context, menu); 396 break; 397 case EmailContent.Mailbox.TYPE_OUTBOX: 398 break; 399 default: 400 getMenuInflater().inflate(R.menu.message_list_context, menu); 401 getMenuInflater().inflate(R.menu.message_list_context_extra, menu); 402 // The default menu contains "mark as read". If the message is read, change 403 // the menu text to "mark as unread." 404 if (itemView.mRead) { 405 menu.findItem(R.id.mark_as_read).setTitle(R.string.mark_as_unread_action); 406 } 407 break; 408 } 409 } 410 411 @Override 412 public boolean onContextItemSelected(MenuItem item) { 413 AdapterView.AdapterContextMenuInfo info = 414 (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); 415 MessageListItem itemView = (MessageListItem) info.targetView; 416 417 switch (item.getItemId()) { 418 case R.id.open: 419 onOpenMessage(info.id, itemView.mMailboxId); 420 break; 421 case R.id.delete: 422 onDelete(info.id, itemView.mAccountId); 423 break; 424 case R.id.reply: 425 //onReply(holder); 426 break; 427 case R.id.reply_all: 428 //onReplyAll(holder); 429 break; 430 case R.id.forward: 431 //onForward(holder); 432 break; 433 case R.id.mark_as_read: 434 onSetMessageRead(info.id, !itemView.mRead); 435 break; 436 } 437 return super.onContextItemSelected(item); 438 } 439 440 private void onRefresh() { 441 // TODO: This needs to loop through all open mailboxes (there might be more than one) 442 // TODO: Should not be reading from DB in UI thread - need a cleaner way to get accountId 443 if (mMailboxId >= 0) { 444 Mailbox mailbox = Mailbox.restoreMailboxWithId(this, mMailboxId); 445 mController.updateMailbox(mailbox.mAccountKey, mMailboxId, mControllerCallback); 446 } 447 } 448 449 private void onAccounts() { 450 AccountFolderList.actionShowAccounts(this); 451 finish(); 452 } 453 454 private long lookupAccountIdFromMailboxId(long mailboxId) { 455 // TODO: Select correct account to send from when there are multiple mailboxes 456 // TODO: Should not be reading from DB in UI thread 457 if (mailboxId < 0) { 458 return -1; // no info, default account 459 } 460 EmailContent.Mailbox mailbox = 461 EmailContent.Mailbox.restoreMailboxWithId(this, mailboxId); 462 return mailbox.mAccountKey; 463 } 464 465 private void onCompose() { 466 MessageCompose.actionCompose(this, lookupAccountIdFromMailboxId(mMailboxId)); 467 } 468 469 private void onEditAccount() { 470 AccountSettings.actionSettings(this, lookupAccountIdFromMailboxId(mMailboxId)); 471 } 472 473 private void onOpenMessage(long messageId, long mailboxId) { 474 // TODO: Should not be reading from DB in UI thread 475 EmailContent.Mailbox mailbox = EmailContent.Mailbox.restoreMailboxWithId(this, mailboxId); 476 477 if (mailbox.mType == EmailContent.Mailbox.TYPE_DRAFTS) { 478 MessageCompose.actionEditDraft(this, messageId); 479 } else { 480 MessageView.actionView(this, messageId, mailboxId); 481 } 482 } 483 484 private void onLoadMoreMessages() { 485 if (mMailboxId >= 0) { 486 mController.loadMoreMessages(mMailboxId, mControllerCallback); 487 } 488 } 489 490 private void onSendPendingMessages() { 491 long accountId = lookupAccountIdFromMailboxId(mMailboxId); 492 mController.sendPendingMessages(accountId, mControllerCallback); 493 } 494 495 private void onDelete(long messageId, long accountId) { 496 mController.deleteMessage(messageId, accountId); 497 Toast.makeText(this, R.string.message_deleted_toast, Toast.LENGTH_SHORT).show(); 498 } 499 500 private void onSetMessageRead(long messageId, boolean newRead) { 501 mController.setMessageRead(messageId, newRead); 502 } 503 504 private void onSetMessageFavorite(long messageId, boolean newFavorite) { 505 mController.setMessageFavorite(messageId, newFavorite); 506 } 507 508 /** 509 * Toggles a set read/unread states. Note, the default behavior is "mark unread", so the 510 * sense of the helper methods is "true=unread". 511 * 512 * @param selectedSet The current list of selected items 513 */ 514 private void onMultiToggleRead(Set<Long> selectedSet) { 515 toggleMultiple(selectedSet, new MultiToggleHelper() { 516 517 public boolean getField(long messageId, Cursor c) { 518 return c.getInt(MessageListAdapter.COLUMN_READ) == 0; 519 } 520 521 public boolean setField(long messageId, Cursor c, boolean newValue) { 522 boolean oldValue = getField(messageId, c); 523 if (oldValue != newValue) { 524 onSetMessageRead(messageId, !newValue); 525 return true; 526 } 527 return false; 528 } 529 }); 530 } 531 532 /** 533 * Toggles a set of favorites (stars) 534 * 535 * @param selectedSet The current list of selected items 536 */ 537 private void onMultiToggleFavorite(Set<Long> selectedSet) { 538 toggleMultiple(selectedSet, new MultiToggleHelper() { 539 540 public boolean getField(long messageId, Cursor c) { 541 return c.getInt(MessageListAdapter.COLUMN_FAVORITE) != 0; 542 } 543 544 public boolean setField(long messageId, Cursor c, boolean newValue) { 545 boolean oldValue = getField(messageId, c); 546 if (oldValue != newValue) { 547 onSetMessageFavorite(messageId, newValue); 548 return true; 549 } 550 return false; 551 } 552 }); 553 } 554 555 private void onMultiDelete(Set<Long> selectedSet) { 556 // Clone the set, because deleting is going to thrash things 557 HashSet<Long> cloneSet = new HashSet<Long>(selectedSet); 558 for (Long id : cloneSet) { 559 mController.deleteMessage(id, -1); 560 } 561 // TODO: count messages and show "n messages deleted" 562 Toast.makeText(this, R.string.message_deleted_toast, Toast.LENGTH_SHORT).show(); 563 selectedSet.clear(); 564 showMultiPanel(false); 565 } 566 567 private interface MultiToggleHelper { 568 /** 569 * Return true if the field of interest is "set". If one or more are false, then our 570 * bulk action will be to "set". If all are set, our bulk action will be to "clear". 571 * @param messageId the message id of the current message 572 * @param c the cursor, positioned to the item of interest 573 * @return true if the field at this row is "set" 574 */ 575 public boolean getField(long messageId, Cursor c); 576 577 /** 578 * Set or clear the field of interest. Return true if a change was made. 579 * @param messageId the message id of the current message 580 * @param c the cursor, positioned to the item of interest 581 * @param newValue the new value to be set at this row 582 * @return true if a change was actually made 583 */ 584 public boolean setField(long messageId, Cursor c, boolean newValue); 585 } 586 587 /** 588 * Toggle multiple fields in a message, using the following logic: If one or more fields 589 * are "clear", then "set" them. If all fields are "set", then "clear" them all. 590 * 591 * @param selectedSet the set of messages that are selected 592 * @param helper functions to implement the specific getter & setter 593 * @return the number of messages that were updated 594 */ 595 private int toggleMultiple(Set<Long> selectedSet, MultiToggleHelper helper) { 596 Cursor c = mListAdapter.getCursor(); 597 boolean anyWereFound = false; 598 boolean allWereSet = true; 599 600 c.moveToPosition(-1); 601 while (c.moveToNext()) { 602 long id = c.getInt(MessageListAdapter.COLUMN_ID); 603 if (selectedSet.contains(Long.valueOf(id))) { 604 anyWereFound = true; 605 if (!helper.getField(id, c)) { 606 allWereSet = false; 607 break; 608 } 609 } 610 } 611 612 int numChanged = 0; 613 614 if (anyWereFound) { 615 boolean newValue = !allWereSet; 616 c.moveToPosition(-1); 617 while (c.moveToNext()) { 618 long id = c.getInt(MessageListAdapter.COLUMN_ID); 619 if (selectedSet.contains(Long.valueOf(id))) { 620 if (helper.setField(id, c, newValue)) { 621 ++numChanged; 622 } 623 } 624 } 625 } 626 627 return numChanged; 628 } 629 630 /** 631 * Show or hide the panel of multi-select options 632 */ 633 private void showMultiPanel(boolean show) { 634 if (show && mMultiSelectPanel.getVisibility() != View.VISIBLE) { 635 mMultiSelectPanel.setVisibility(View.VISIBLE); 636 mMultiSelectPanel.startAnimation( 637 AnimationUtils.loadAnimation(this, R.anim.footer_appear)); 638 639 } else if (!show && mMultiSelectPanel.getVisibility() != View.GONE) { 640 mMultiSelectPanel.setVisibility(View.GONE); 641 mMultiSelectPanel.startAnimation( 642 AnimationUtils.loadAnimation(this, R.anim.footer_disappear)); 643 } 644 } 645 646 /** 647 * Add the fixed footer view if appropriate (not always - not all accounts & mailboxes). 648 * 649 * Here are some rules (finish this list): 650 * 651 * Any merged box (except send): refresh 652 * Any push-mode account: refresh 653 * Any non-push-mode account: load more 654 * Any outbox (send again): 655 * 656 * @param mailboxId the ID of the mailbox 657 */ 658 private void addFooterView(long mailboxId, long accountId, int mailboxType) { 659 // first, look for shortcuts that don't need us to spin up a DB access task 660 if (mailboxId == Mailbox.QUERY_ALL_INBOXES 661 || mailboxId == Mailbox.QUERY_ALL_UNREAD 662 || mailboxId == Mailbox.QUERY_ALL_FAVORITES 663 || mailboxId == Mailbox.QUERY_ALL_DRAFTS) { 664 finishFooterView(LIST_FOOTER_MODE_REFRESH); 665 return; 666 } 667 if (mailboxId == Mailbox.QUERY_ALL_OUTBOX || mailboxType == Mailbox.TYPE_OUTBOX) { 668 finishFooterView(LIST_FOOTER_MODE_SEND); 669 return; 670 } 671 672 // We don't know enough to select the footer command type (yet), so we'll 673 // launch an async task to do the remaining lookups and decide what to do 674 mSetFooterTask = new SetFooterTask(); 675 mSetFooterTask.execute(mailboxId, accountId); 676 } 677 678 private final static String[] MAILBOX_ACCOUNT_AND_TYPE_PROJECTION = 679 new String[] { MailboxColumns.ACCOUNT_KEY, MailboxColumns.TYPE }; 680 681 private class SetFooterTask extends AsyncTask<Long, Void, Integer> { 682 /** 683 * There are two operational modes here, requiring different lookup. 684 * mailboxIs != -1: A specific mailbox - check its type, then look up its account 685 * accountId != -1: A specific account - look up the account 686 */ 687 @Override 688 protected Integer doInBackground(Long... params) { 689 long mailboxId = params[0]; 690 long accountId = params[1]; 691 int mailboxType = -1; 692 if (mailboxId != -1) { 693 try { 694 Uri uri = ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId); 695 Cursor c = mResolver.query(uri, MAILBOX_ACCOUNT_AND_TYPE_PROJECTION, 696 null, null, null); 697 if (c.moveToFirst()) { 698 try { 699 accountId = c.getLong(0); 700 mailboxType = c.getInt(1); 701 } finally { 702 c.close(); 703 } 704 } 705 } catch (IllegalArgumentException iae) { 706 // can't do any more here 707 return LIST_FOOTER_MODE_NONE; 708 } 709 } 710 if (mailboxType == Mailbox.TYPE_OUTBOX) { 711 return LIST_FOOTER_MODE_SEND; 712 } 713 if (accountId != -1) { 714 // This is inefficient but the best fix is not here but in isMessagingController 715 Account account = Account.restoreAccountWithId(MessageList.this, accountId); 716 if (account != null) { 717 if (MessageList.this.mController.isMessagingController(account)) { 718 return LIST_FOOTER_MODE_MORE; // IMAP or POP 719 } else { 720 return LIST_FOOTER_MODE_REFRESH; // EAS 721 } 722 } 723 } 724 return LIST_FOOTER_MODE_NONE; 725 } 726 727 @Override 728 protected void onPostExecute(Integer listFooterMode) { 729 finishFooterView(listFooterMode); 730 } 731 } 732 733 /** 734 * Add the fixed footer view as specified, and set up the test as well. 735 * 736 * @param listFooterMode the footer mode we've determined should be used for this list 737 */ 738 private void finishFooterView(int listFooterMode) { 739 mListFooterMode = listFooterMode; 740 if (mListFooterMode != LIST_FOOTER_MODE_NONE) { 741 mListFooterView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)) 742 .inflate(R.layout.message_list_item_footer, mListView, false); 743 mList.addFooterView(mListFooterView); 744 setListAdapter(mListAdapter); 745 746 mListFooterProgress = mListFooterView.findViewById(R.id.progress); 747 mListFooterText = (TextView) mListFooterView.findViewById(R.id.main_text); 748 setListFooterText(false); 749 } 750 } 751 752 /** 753 * Set the list footer text based on mode and "active" status 754 */ 755 private void setListFooterText(boolean active) { 756 if (mListFooterMode != LIST_FOOTER_MODE_NONE) { 757 int footerTextId = 0; 758 switch (mListFooterMode) { 759 case LIST_FOOTER_MODE_REFRESH: 760 footerTextId = active ? R.string.status_loading_more 761 : R.string.refresh_action; 762 break; 763 case LIST_FOOTER_MODE_MORE: 764 footerTextId = active ? R.string.status_loading_more 765 : R.string.message_list_load_more_messages_action; 766 break; 767 case LIST_FOOTER_MODE_SEND: 768 footerTextId = active ? R.string.status_sending_messages 769 : R.string.message_list_send_pending_messages_action; 770 break; 771 } 772 mListFooterText.setText(footerTextId); 773 } 774 } 775 776 /** 777 * Handle a click in the list footer, which changes meaning depending on what we're looking at. 778 */ 779 private void doFooterClick() { 780 switch (mListFooterMode) { 781 case LIST_FOOTER_MODE_NONE: // should never happen 782 break; 783 case LIST_FOOTER_MODE_REFRESH: 784 onRefresh(); 785 break; 786 case LIST_FOOTER_MODE_MORE: 787 onLoadMoreMessages(); 788 break; 789 case LIST_FOOTER_MODE_SEND: 790 onSendPendingMessages(); 791 break; 792 } 793 } 794 795 /** 796 * Async task for finding a single mailbox by type (possibly even going to the network). 797 * 798 * This is much too complex, as implemented. It uses this AsyncTask to check for a mailbox, 799 * then (if not found) a Controller call to refresh mailboxes from the server, and a handler 800 * to relaunch this task (a 2nd time) to read the results of the network refresh. The core 801 * problem is that we have two different non-UI-thread jobs (reading DB and reading network) 802 * and two different paradigms for dealing with them. Some unification would be needed here 803 * to make this cleaner. 804 * 805 * TODO: If this problem spreads to other operations, find a cleaner way to handle it. 806 */ 807 private class FindMailboxTask extends AsyncTask<Void, Void, Long> { 808 809 private long mAccountId; 810 private int mMailboxType; 811 private boolean mOkToRecurse; 812 813 /** 814 * Special constructor to cache some local info 815 */ 816 public FindMailboxTask(long accountId, int mailboxType, boolean okToRecurse) { 817 mAccountId = accountId; 818 mMailboxType = mailboxType; 819 mOkToRecurse = okToRecurse; 820 } 821 822 @Override 823 protected Long doInBackground(Void... params) { 824 // See if we can find the requested mailbox in the DB. 825 long mailboxId = Mailbox.findMailboxOfType(MessageList.this, mAccountId, mMailboxType); 826 if (mailboxId == -1 && mOkToRecurse) { 827 // Not found - launch network lookup 828 mControllerCallback.mWaitForMailboxType = mMailboxType; 829 mController.updateMailboxList(mAccountId, mControllerCallback); 830 } 831 return mailboxId; 832 } 833 834 @Override 835 protected void onPostExecute(Long mailboxId) { 836 if (mailboxId != -1) { 837 mMailboxId = mailboxId; 838 mSetTitleTask = new SetTitleTask(mMailboxId); 839 mSetTitleTask.execute(); 840 mLoadMessagesTask = new LoadMessagesTask(mMailboxId, mAccountId); 841 mLoadMessagesTask.execute(); 842 } 843 } 844 } 845 846 /** 847 * Async task for loading a single folder out of the UI thread 848 * 849 * The code here (for merged boxes) is a placeholder/hack and should be replaced. Some 850 * specific notes: 851 * TODO: Move the double query into a specialized URI that returns all inbox messages 852 * and do the dirty work in raw SQL in the provider. 853 * TODO: Generalize the query generation so we can reuse it in MessageView (for next/prev) 854 */ 855 private class LoadMessagesTask extends AsyncTask<Void, Void, Cursor> { 856 857 private long mMailboxKey; 858 private long mAccountKey; 859 860 /** 861 * Special constructor to cache some local info 862 */ 863 public LoadMessagesTask(long mailboxKey, long accountKey) { 864 mMailboxKey = mailboxKey; 865 mAccountKey = accountKey; 866 } 867 868 @Override 869 protected Cursor doInBackground(Void... params) { 870 String selection = 871 Utility.buildMailboxIdSelection(MessageList.this.mResolver, mMailboxKey); 872 Cursor c = MessageList.this.managedQuery( 873 EmailContent.Message.CONTENT_URI, 874 MessageList.this.mListAdapter.PROJECTION, 875 selection, null, 876 EmailContent.MessageColumns.TIMESTAMP + " DESC"); 877 return c; 878 } 879 880 @Override 881 protected void onPostExecute(Cursor cursor) { 882 MessageList.this.mListAdapter.changeCursor(cursor); 883 884 // TODO: remove this hack and only update at the right time 885 if (cursor != null && cursor.getCount() == 0) { 886 onRefresh(); 887 } 888 889 // Reset the "new messages" count in the service, since we're seeing them now 890 if (mMailboxKey == Mailbox.QUERY_ALL_INBOXES) { 891 MailService.resetNewMessageCount(MessageList.this, -1); 892 } else if (mMailboxKey >= 0 && mAccountKey != -1) { 893 MailService.resetNewMessageCount(MessageList.this, mAccountKey); 894 } 895 } 896 } 897 898 private class SetTitleTask extends AsyncTask<Void, Void, String[]> { 899 900 private long mMailboxKey; 901 902 public SetTitleTask(long mailboxKey) { 903 mMailboxKey = mailboxKey; 904 } 905 906 @Override 907 protected String[] doInBackground(Void... params) { 908 // Check special Mailboxes 909 if (mMailboxKey == Mailbox.QUERY_ALL_INBOXES) { 910 return new String[] {null, 911 getString(R.string.account_folder_list_summary_inbox)}; 912 } else if (mMailboxKey == Mailbox.QUERY_ALL_FAVORITES) { 913 return new String[] {null, 914 getString(R.string.account_folder_list_summary_favorite)}; 915 } else if (mMailboxKey == Mailbox.QUERY_ALL_DRAFTS) { 916 return new String[] {null, 917 getString(R.string.account_folder_list_summary_drafts)}; 918 } else if (mMailboxKey == Mailbox.QUERY_ALL_OUTBOX) { 919 return new String[] {null, 920 getString(R.string.account_folder_list_summary_outbox)}; 921 } 922 String accountName = null; 923 String mailboxName = null; 924 String accountKey = null; 925 Cursor c = MessageList.this.mResolver.query(Mailbox.CONTENT_URI, 926 MAILBOX_NAME_PROJECTION, ID_SELECTION, 927 new String[] { Long.toString(mMailboxKey) }, null); 928 try { 929 if (c.moveToFirst()) { 930 mailboxName = Utility.FolderProperties.getInstance(MessageList.this) 931 .getDisplayName(c.getInt(MAILBOX_NAME_COLUMN_TYPE)); 932 if (mailboxName == null) { 933 mailboxName = c.getString(MAILBOX_NAME_COLUMN_ID); 934 } 935 accountKey = c.getString(MAILBOX_NAME_COLUMN_ACCOUNT_KEY); 936 } 937 } finally { 938 c.close(); 939 } 940 if (accountKey != null) { 941 c = MessageList.this.mResolver.query(Account.CONTENT_URI, 942 ACCOUNT_NAME_PROJECTION, ID_SELECTION, new String[] { accountKey }, 943 null); 944 try { 945 if (c.moveToFirst()) { 946 accountName = c.getString(ACCOUNT_DISPLAY_NAME_COLUMN_ID); 947 } 948 } finally { 949 c.close(); 950 } 951 } 952 return new String[] {accountName, mailboxName}; 953 } 954 955 @Override 956 protected void onPostExecute(String[] names) { 957 Log.d("MessageList", "ACCOUNT:" + names[0] + "MAILBOX" + names[1]); 958 if (names[0] != null) { 959 mRightTitle.setText(names[0]); 960 } 961 if (names[1] != null) { 962 mLeftTitle.setText(names[1]); 963 } 964 } 965 } 966 967 /** 968 * Handler for UI-thread operations (when called from callbacks or any other threads) 969 */ 970 class MessageListHandler extends Handler { 971 private static final int MSG_PROGRESS = 1; 972 private static final int MSG_LOOKUP_MAILBOX_TYPE = 2; 973 974 @Override 975 public void handleMessage(android.os.Message msg) { 976 switch (msg.what) { 977 case MSG_PROGRESS: 978 boolean visible = (msg.arg1 != 0); 979 if (visible) { 980 mProgressIcon.setVisibility(View.VISIBLE); 981 } else { 982 mProgressIcon.setVisibility(View.GONE); 983 } 984 if (mListFooterProgress != null) { 985 mListFooterProgress.setVisibility(visible ? View.VISIBLE : View.GONE); 986 } 987 setListFooterText(visible); 988 break; 989 case MSG_LOOKUP_MAILBOX_TYPE: 990 // kill running async task, if any 991 if (mFindMailboxTask != null && 992 mFindMailboxTask.getStatus() != FindMailboxTask.Status.FINISHED) { 993 mFindMailboxTask.cancel(true); 994 mFindMailboxTask = null; 995 } 996 // start new one. do not recurse back to controller. 997 long accountId = ((Long)msg.obj).longValue(); 998 int mailboxType = msg.arg1; 999 mFindMailboxTask = new FindMailboxTask(accountId, mailboxType, false); 1000 mFindMailboxTask.execute(); 1001 break; 1002 default: 1003 super.handleMessage(msg); 1004 } 1005 } 1006 1007 /** 1008 * Call from any thread to start/stop progress indicator(s) 1009 * @param progress true to start, false to stop 1010 */ 1011 public void progress(boolean progress) { 1012 android.os.Message msg = android.os.Message.obtain(); 1013 msg.what = MSG_PROGRESS; 1014 msg.arg1 = progress ? 1 : 0; 1015 sendMessage(msg); 1016 } 1017 1018 /** 1019 * Called from any thread to look for a mailbox of a specific type. This is designed 1020 * to be called from the Controller's MailboxList callback; It instructs the async task 1021 * not to recurse, in case the mailbox is not found after this. 1022 * 1023 * See FindMailboxTask for more notes on this handler. 1024 */ 1025 public void lookupMailboxType(long accountId, int mailboxType) { 1026 android.os.Message msg = android.os.Message.obtain(); 1027 msg.what = MSG_LOOKUP_MAILBOX_TYPE; 1028 msg.arg1 = mailboxType; 1029 msg.obj = Long.valueOf(accountId); 1030 sendMessage(msg); 1031 } 1032 } 1033 1034 /** 1035 * Callback for async Controller results. 1036 */ 1037 private class ControllerResults implements Controller.Result { 1038 1039 // These are preset for use by updateMailboxListCallback 1040 int mWaitForMailboxType = -1; 1041 1042 // TODO report errors into UI 1043 // TODO check accountKey and only react to relevant notifications 1044 public void updateMailboxListCallback(MessagingException result, long accountKey, 1045 int progress) { 1046 if (progress == 0) { 1047 mHandler.progress(true); 1048 } else if (result != null || progress == 100) { 1049 mHandler.progress(false); 1050 if (mWaitForMailboxType != -1) { 1051 if (result == null) { 1052 mHandler.lookupMailboxType(accountKey, mWaitForMailboxType); 1053 } 1054 } 1055 } 1056 } 1057 1058 // TODO report errors into UI 1059 // TODO check accountKey and only react to relevant notifications 1060 public void updateMailboxCallback(MessagingException result, long accountKey, 1061 long mailboxKey, int progress, int numNewMessages) { 1062 if (progress == 0) { 1063 mHandler.progress(true); 1064 } else if (result != null || progress == 100) { 1065 mHandler.progress(false); 1066 } 1067 } 1068 1069 public void loadAttachmentCallback(MessagingException result, long messageId, 1070 long attachmentId, int progress) { 1071 } 1072 1073 public void serviceCheckMailCallback(MessagingException result, long accountId, 1074 long mailboxId, int progress, long tag) { 1075 } 1076 1077 // TODO report errors into UI 1078 public void sendMailCallback(MessagingException result, long accountId, long messageId, 1079 int progress) { 1080 if (mListFooterMode == LIST_FOOTER_MODE_SEND) { 1081 if (progress == 0) { 1082 mHandler.progress(true); 1083 } else if (result != null || progress == 100) { 1084 mHandler.progress(false); 1085 } 1086 } 1087 } 1088 } 1089 1090 /** 1091 * This class implements the adapter for displaying messages based on cursors. 1092 */ 1093 /* package */ class MessageListAdapter extends CursorAdapter { 1094 1095 public static final int COLUMN_ID = 0; 1096 public static final int COLUMN_MAILBOX_KEY = 1; 1097 public static final int COLUMN_ACCOUNT_KEY = 2; 1098 public static final int COLUMN_DISPLAY_NAME = 3; 1099 public static final int COLUMN_SUBJECT = 4; 1100 public static final int COLUMN_DATE = 5; 1101 public static final int COLUMN_READ = 6; 1102 public static final int COLUMN_FAVORITE = 7; 1103 public static final int COLUMN_ATTACHMENTS = 8; 1104 1105 public final String[] PROJECTION = new String[] { 1106 EmailContent.RECORD_ID, MessageColumns.MAILBOX_KEY, MessageColumns.ACCOUNT_KEY, 1107 MessageColumns.DISPLAY_NAME, MessageColumns.SUBJECT, MessageColumns.TIMESTAMP, 1108 MessageColumns.FLAG_READ, MessageColumns.FLAG_FAVORITE, MessageColumns.FLAG_ATTACHMENT, 1109 }; 1110 1111 Context mContext; 1112 private LayoutInflater mInflater; 1113 private Drawable mAttachmentIcon; 1114 private Drawable mFavoriteIconOn; 1115 private Drawable mFavoriteIconOff; 1116 private Drawable mSelectedIconOn; 1117 private Drawable mSelectedIconOff; 1118 1119 private java.text.DateFormat mDateFormat; 1120 private java.text.DateFormat mDayFormat; 1121 private java.text.DateFormat mTimeFormat; 1122 1123 private HashSet<Long> mChecked = new HashSet<Long>(); 1124 1125 public MessageListAdapter(Context context) { 1126 super(context, null); 1127 mContext = context; 1128 mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 1129 1130 Resources resources = context.getResources(); 1131 mAttachmentIcon = resources.getDrawable(R.drawable.ic_mms_attachment_small); 1132 mFavoriteIconOn = resources.getDrawable(android.R.drawable.star_on); 1133 mFavoriteIconOff = resources.getDrawable(android.R.drawable.star_off); 1134 mSelectedIconOn = resources.getDrawable(R.drawable.btn_check_buttonless_on); 1135 mSelectedIconOff = resources.getDrawable(R.drawable.btn_check_buttonless_off); 1136 1137 mDateFormat = android.text.format.DateFormat.getDateFormat(context); // short date 1138 mDayFormat = android.text.format.DateFormat.getDateFormat(context); // TODO: day 1139 mTimeFormat = android.text.format.DateFormat.getTimeFormat(context); // 12/24 time 1140 } 1141 1142 public Set<Long> getSelectedSet() { 1143 return mChecked; 1144 } 1145 1146 @Override 1147 public void bindView(View view, Context context, Cursor cursor) { 1148 // Reset the view (in case it was recycled) and prepare for binding 1149 MessageListItem itemView = (MessageListItem) view; 1150 itemView.bindViewInit(this, true); 1151 1152 // Load the public fields in the view (for later use) 1153 itemView.mMessageId = cursor.getLong(COLUMN_ID); 1154 itemView.mMailboxId = cursor.getLong(COLUMN_MAILBOX_KEY); 1155 itemView.mAccountId = cursor.getLong(COLUMN_ACCOUNT_KEY); 1156 itemView.mRead = cursor.getInt(COLUMN_READ) != 0; 1157 itemView.mFavorite = cursor.getInt(COLUMN_FAVORITE) != 0; 1158 itemView.mSelected = mChecked.contains(Long.valueOf(itemView.mMessageId)); 1159 1160 // Load the UI 1161 View chipView = view.findViewById(R.id.chip); 1162 int chipResId = mColorChipResIds[(int)itemView.mAccountId % mColorChipResIds.length]; 1163 chipView.setBackgroundResource(chipResId); 1164 // TODO always display chip. Use other indications (e.g. boldface) for read/unread 1165 chipView.getBackground().setAlpha(itemView.mRead ? 100 : 255); 1166 1167 TextView fromView = (TextView) view.findViewById(R.id.from); 1168 String text = cursor.getString(COLUMN_DISPLAY_NAME); 1169 if (text != null) fromView.setText(text); 1170 1171 boolean hasAttachments = cursor.getInt(COLUMN_ATTACHMENTS) != 0; 1172 fromView.setCompoundDrawablesWithIntrinsicBounds(null, null, 1173 hasAttachments ? mAttachmentIcon : null, null); 1174 1175 TextView subjectView = (TextView) view.findViewById(R.id.subject); 1176 text = cursor.getString(COLUMN_SUBJECT); 1177 if (text != null) subjectView.setText(text); 1178 1179 // TODO ui spec suggests "time", "day", "date" - implement "day" 1180 TextView dateView = (TextView) view.findViewById(R.id.date); 1181 long timestamp = cursor.getLong(COLUMN_DATE); 1182 Date date = new Date(timestamp); 1183 if (Utility.isDateToday(date)) { 1184 text = mTimeFormat.format(date); 1185 } else { 1186 text = mDateFormat.format(date); 1187 } 1188 dateView.setText(text); 1189 1190 ImageView selectedView = (ImageView) view.findViewById(R.id.selected); 1191 selectedView.setImageDrawable(itemView.mSelected ? mSelectedIconOn : mSelectedIconOff); 1192 1193 ImageView favoriteView = (ImageView) view.findViewById(R.id.favorite); 1194 favoriteView.setImageDrawable(itemView.mFavorite ? mFavoriteIconOn : mFavoriteIconOff); 1195 } 1196 1197 @Override 1198 public View newView(Context context, Cursor cursor, ViewGroup parent) { 1199 return mInflater.inflate(R.layout.message_list_item, parent, false); 1200 } 1201 1202 /** 1203 * This is used as a callback from the list items, to set the selected state 1204 * 1205 * @param itemView the item being changed 1206 * @param newSelected the new value of the selected flag (checkbox state) 1207 */ 1208 public void updateSelected(MessageListItem itemView, boolean newSelected) { 1209 ImageView selectedView = (ImageView) itemView.findViewById(R.id.selected); 1210 selectedView.setImageDrawable(newSelected ? mSelectedIconOn : mSelectedIconOff); 1211 1212 // Set checkbox state in list, and show/hide panel if necessary 1213 Long id = Long.valueOf(itemView.mMessageId); 1214 if (newSelected) { 1215 mChecked.add(id); 1216 } else { 1217 mChecked.remove(id); 1218 } 1219 1220 MessageList.this.showMultiPanel(mChecked.size() > 0); 1221 } 1222 1223 /** 1224 * This is used as a callback from the list items, to set the favorite state 1225 * 1226 * @param itemView the item being changed 1227 * @param newFavorite the new value of the favorite flag (star state) 1228 */ 1229 public void updateFavorite(MessageListItem itemView, boolean newFavorite) { 1230 ImageView favoriteView = (ImageView) itemView.findViewById(R.id.favorite); 1231 favoriteView.setImageDrawable(newFavorite ? mFavoriteIconOn : mFavoriteIconOff); 1232 onSetMessageFavorite(itemView.mMessageId, newFavorite); 1233 } 1234 } 1235} 1236