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