ActionBarController.java revision 899e481fd11053a8496d58ca45432c59c094af9a
1/*
2 * Copyright (C) 2011 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 android.app.ActionBar;
20import android.app.LoaderManager;
21import android.app.LoaderManager.LoaderCallbacks;
22import android.content.Context;
23import android.content.Loader;
24import android.database.Cursor;
25import android.graphics.drawable.Drawable;
26import android.os.Bundle;
27import android.text.TextUtils;
28import android.view.LayoutInflater;
29import android.view.View;
30import android.view.ViewGroup;
31import android.widget.AdapterView;
32import android.widget.AdapterView.OnItemClickListener;
33import android.widget.ListPopupWindow;
34import android.widget.ListView;
35import android.widget.SearchView;
36import android.widget.TextView;
37
38import com.android.email.R;
39import com.android.emailcommon.provider.Account;
40import com.android.emailcommon.provider.Mailbox;
41import com.android.emailcommon.utility.DelayedOperations;
42import com.android.emailcommon.utility.Utility;
43
44/**
45 * Manages the account name and the custom view part on the action bar.
46 */
47public class ActionBarController {
48    private static final String BUNDLE_KEY_MODE = "ActionBarController.BUNDLE_KEY_MODE";
49
50    /**
51     * Constants for {@link #mSearchMode}.
52     *
53     * In {@link #MODE_NORMAL} mode, we don't show the search box.
54     * In {@link #MODE_SEARCH} mode, we do show the search box.
55     * The action bar doesn't really care if the activity is showing search results.
56     * If the activity is showing search results, and the {@link Callback#onSearchExit} is called,
57     * the activity probably wants to close itself, but this class doesn't make the desision.
58     */
59    private static final int MODE_NORMAL = 0;
60    private static final int MODE_SEARCH = 1;
61
62    private static final int LOADER_ID_ACCOUNT_LIST
63            = EmailActivity.ACTION_BAR_CONTROLLER_LOADER_ID_BASE + 0;
64
65    private final Context mContext;
66    private final LoaderManager mLoaderManager;
67    private final ActionBar mActionBar;
68    private final DelayedOperations mDelayedOperations;
69
70    /** "Folders" label shown with account name on 1-pane mailbox list */
71    private final String mAllFoldersLabel;
72
73    private final ViewGroup mActionBarCustomView;
74    private final ViewGroup mAccountSpinnerContainer;
75    private final View mAccountSpinner;
76    private final Drawable mAccountSpinnerDefaultBackground;
77    private final TextView mAccountSpinnerLine1View;
78    private final TextView mAccountSpinnerLine2View;
79    private final TextView mAccountSpinnerCountView;
80
81    private View mSearchContainer;
82    private SearchView mSearchView;
83
84    private final AccountDropdownPopup mAccountDropdown;
85
86    private final AccountSelectorAdapter mAccountsSelectorAdapter;
87
88    private AccountSelectorAdapter.CursorWithExtras mCursor;
89
90    /** The current account ID; used to determine if the account has changed. */
91    private long mLastAccountIdForDirtyCheck = Account.NO_ACCOUNT;
92
93    /** The current mailbox ID; used to determine if the mailbox has changed. */
94    private long mLastMailboxIdForDirtyCheck = Mailbox.NO_MAILBOX;
95
96    /** Either {@link #MODE_NORMAL} or {@link #MODE_SEARCH}. */
97    private int mSearchMode = MODE_NORMAL;
98
99    /** The current title mode, which should be one of {@code Callback TITLE_MODE_*} */
100    private int mTitleMode;
101
102    public final Callback mCallback;
103
104    public interface SearchContext {
105        public long getTargetMailboxId();
106    }
107
108    private static final int TITLE_MODE_SPINNER_ENABLED = 0x10;
109
110    public interface Callback {
111        /** Values for {@link #getTitleMode}.  Show only account name */
112        public static final int TITLE_MODE_ACCOUNT_NAME_ONLY = 0 | TITLE_MODE_SPINNER_ENABLED;
113
114        /**
115         * Show the current account name with "Folders"
116         * The account spinner will be disabled in this mode.
117         */
118        public static final int TITLE_MODE_ACCOUNT_WITH_ALL_FOLDERS_LABEL = 1;
119
120        /**
121         * Show the current account name and the current mailbox name.
122         */
123        public static final int TITLE_MODE_ACCOUNT_WITH_MAILBOX = 2 | TITLE_MODE_SPINNER_ENABLED;
124        /**
125         * Show the current message subject.  Actual subject is obtained via
126         * {@link #getMessageSubject()}.
127         *
128         * The account spinner will be disabled in this mode.
129         */
130        public static final int TITLE_MODE_MESSAGE_SUBJECT = 3;
131
132        /** @return true if an account is selected. */
133        public boolean isAccountSelected();
134
135        /**
136         * @return currently selected account ID, {@link Account#ACCOUNT_ID_COMBINED_VIEW},
137         * or -1 if no account is selected.
138         */
139        public long getUIAccountId();
140
141        /**
142         * @return currently selected mailbox ID, or {@link Mailbox#NO_MAILBOX} if no mailbox is
143         * selected.
144         */
145        public long getMailboxId();
146
147        /**
148         * @return constants such as {@link #TITLE_MODE_ACCOUNT_NAME_ONLY}.
149         */
150        public int getTitleMode();
151
152        /** @see #TITLE_MODE_MESSAGE_SUBJECT */
153        public String getMessageSubject();
154
155        /** @return the "UP" arrow should be shown. */
156        public boolean shouldShowUp();
157
158        /**
159         * Called when an account is selected on the account spinner.
160         * @param accountId ID of the selected account, or {@link Account#ACCOUNT_ID_COMBINED_VIEW}.
161         */
162        public void onAccountSelected(long accountId);
163
164        /**
165         * Invoked when a recent mailbox is selected on the account spinner.
166         *
167         * @param accountId ID of the selected account, or {@link Account#ACCOUNT_ID_COMBINED_VIEW}.
168         * @param mailboxId The ID of the selected mailbox, or {@link Mailbox#NO_MAILBOX} if the
169         *          special option "show all mailboxes" was selected.
170         */
171        public void onMailboxSelected(long accountId, long mailboxId);
172
173        /** Called when no accounts are found in the database. */
174        public void onNoAccountsFound();
175
176        /**
177         * Retrieves the hint text to be shown for when a search entry is being made.
178         */
179        public String getSearchHint();
180
181        /**
182         * Called when a search is submitted.
183         *
184         * @param queryTerm query string
185         */
186        public void onSearchSubmit(String queryTerm);
187
188        /**
189         * Called when the search box is closed.
190         */
191        public void onSearchExit();
192    }
193
194    public ActionBarController(Context context, LoaderManager loaderManager,
195            ActionBar actionBar, Callback callback) {
196        mContext = context;
197        mLoaderManager = loaderManager;
198        mActionBar = actionBar;
199        mCallback = callback;
200        mDelayedOperations = new DelayedOperations(Utility.getMainThreadHandler());
201        mAllFoldersLabel = mContext.getResources().getString(
202                R.string.action_bar_mailbox_list_title);
203        mAccountsSelectorAdapter = new AccountSelectorAdapter(mContext);
204
205        // Configure action bar.
206        mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_CUSTOM);
207
208        // Prepare the custom view
209        mActionBar.setCustomView(R.layout.action_bar_custom_view);
210        mActionBarCustomView = (ViewGroup) mActionBar.getCustomView();
211
212        // Account spinner
213        mAccountSpinnerContainer =
214                UiUtilities.getView(mActionBarCustomView, R.id.account_spinner_container);
215        mAccountSpinner = UiUtilities.getView(mActionBarCustomView, R.id.account_spinner);
216        mAccountSpinnerDefaultBackground = mAccountSpinner.getBackground();
217
218        mAccountSpinnerLine1View = UiUtilities.getView(mActionBarCustomView, R.id.spinner_line_1);
219        mAccountSpinnerLine2View = UiUtilities.getView(mActionBarCustomView, R.id.spinner_line_2);
220        mAccountSpinnerCountView = UiUtilities.getView(mActionBarCustomView, R.id.spinner_count);
221
222        // Account dropdown
223        mAccountDropdown = new AccountDropdownPopup(mContext);
224        mAccountDropdown.setAdapter(mAccountsSelectorAdapter);
225
226        mAccountSpinner.setOnClickListener(new View.OnClickListener() {
227            @Override public void onClick(View v) {
228                if (mAccountsSelectorAdapter.getCount() > 0) {
229                    mAccountDropdown.show();
230                }
231            }
232        });
233    }
234
235    private void initSearchViews() {
236        if (mSearchContainer == null) {
237            final LayoutInflater inflater = LayoutInflater.from(mContext);
238            mSearchContainer = inflater.inflate(R.layout.action_bar_search, null);
239            mSearchView = UiUtilities.getView(mSearchContainer, R.id.search_view);
240            mSearchView.setSubmitButtonEnabled(false);
241            mSearchView.setOnQueryTextListener(mOnQueryText);
242            mSearchView.onActionViewExpanded();
243            mActionBarCustomView.addView(mSearchContainer);
244        }
245    }
246
247
248    /** Must be called from {@link UIControllerBase#onActivityCreated()} */
249    public void onActivityCreated() {
250        refresh();
251    }
252
253    /** Must be called from {@link UIControllerBase#onActivityDestroy()} */
254    public void onActivityDestroy() {
255        if (mAccountDropdown.isShowing()) {
256            mAccountDropdown.dismiss();
257        }
258    }
259
260    /** Must be called from {@link UIControllerBase#onSaveInstanceState} */
261    public void onSaveInstanceState(Bundle outState) {
262        mDelayedOperations.removeCallbacks(); // Remove all pending operations
263        outState.putInt(BUNDLE_KEY_MODE, mSearchMode);
264    }
265
266    /** Must be called from {@link UIControllerBase#onRestoreInstanceState} */
267    public void onRestoreInstanceState(Bundle savedState) {
268        int mode = savedState.getInt(BUNDLE_KEY_MODE);
269        if (mode == MODE_SEARCH) {
270            // No need to re-set the initial query, as the View tree restoration does that
271            enterSearchMode(null);
272        }
273    }
274
275    /**
276     * @return true if the search box is shown.
277     */
278    private boolean isInSearchMode() {
279        return mSearchMode == MODE_SEARCH;
280    }
281
282    /**
283     * @return Whether or not the search bar should be shown. This is a function of whether or not a
284     *     search is active, and if the current layout supports it.
285     */
286    private boolean shouldShowSearchBar() {
287        return isInSearchMode() && (mTitleMode != Callback.TITLE_MODE_MESSAGE_SUBJECT);
288    }
289
290    /**
291     * Show the search box.
292     *
293     * @param initialQueryTerm if non-empty, set to the search box.
294     */
295    public void enterSearchMode(String initialQueryTerm) {
296        initSearchViews();
297        if (isInSearchMode()) {
298            return;
299        }
300        if (!TextUtils.isEmpty(initialQueryTerm)) {
301            mSearchView.setQuery(initialQueryTerm, false);
302        } else {
303            mSearchView.setQuery("", false);
304        }
305        mSearchView.setQueryHint(mCallback.getSearchHint());
306
307        mSearchMode = MODE_SEARCH;
308
309        // Focus on the search input box and throw up the IME if specified.
310        // TODO: HACK. this is a workaround IME not popping up.
311        mSearchView.setIconified(false);
312
313        refresh();
314    }
315
316    public void exitSearchMode() {
317        if (!isInSearchMode()) {
318            return;
319        }
320        mSearchMode = MODE_NORMAL;
321
322        refresh();
323        mCallback.onSearchExit();
324    }
325
326    /**
327     * Performs the back action.
328     *
329     * @param isSystemBackKey <code>true</code> if the system back key was pressed.
330     * <code>false</code> if it's caused by the "home" icon click on the action bar.
331     */
332    public boolean onBackPressed(boolean isSystemBackKey) {
333        if (shouldShowSearchBar()) {
334            exitSearchMode();
335            return true;
336        }
337        return false;
338    }
339
340    /** Refreshes the action bar display. */
341    public void refresh() {
342        // The actual work is in refreshInernal(), but we don't call it directly here, because:
343        // 1. refresh() is called very often.
344        // 2. to avoid nested fragment transaction.
345        //    refresh is often called during a fragment transaction, but updateTitle() may call
346        //    a callback which would initiate another fragment transaction.
347        mDelayedOperations.removeCallbacks(mRefreshRunnable);
348        mDelayedOperations.post(mRefreshRunnable);
349    }
350
351    private final Runnable mRefreshRunnable = new Runnable() {
352        @Override public void run() {
353            refreshInernal();
354        }
355    };
356    private void refreshInernal() {
357        final boolean showUp = isInSearchMode() || mCallback.shouldShowUp();
358        mActionBar.setDisplayOptions(showUp
359                ? ActionBar.DISPLAY_HOME_AS_UP : 0, ActionBar.DISPLAY_HOME_AS_UP);
360
361        final long accountId = mCallback.getUIAccountId();
362        final long mailboxId = mCallback.getMailboxId();
363        if ((mLastAccountIdForDirtyCheck != accountId)
364                || (mLastMailboxIdForDirtyCheck != mailboxId)) {
365            mLastAccountIdForDirtyCheck = accountId;
366            mLastMailboxIdForDirtyCheck = mailboxId;
367
368            if (accountId != Account.NO_ACCOUNT) {
369                loadAccountMailboxInfo(accountId, mailboxId);
370            }
371        }
372
373        updateTitle();
374    }
375
376    /**
377     * Load account/mailbox info, and account/recent mailbox list.
378     */
379    private void loadAccountMailboxInfo(final long accountId, final long mailboxId) {
380        mLoaderManager.restartLoader(LOADER_ID_ACCOUNT_LIST, null,
381                new LoaderCallbacks<Cursor>() {
382            @Override
383            public Loader<Cursor> onCreateLoader(int id, Bundle args) {
384                return AccountSelectorAdapter.createLoader(mContext, accountId, mailboxId);
385            }
386
387            @Override
388            public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
389                mCursor = (AccountSelectorAdapter.CursorWithExtras) data;
390                updateTitle();
391            }
392
393            @Override
394            public void onLoaderReset(Loader<Cursor> loader) {
395                mCursor = null;
396                updateTitle();
397            }
398        });
399    }
400
401    /**
402     * Update the "title" part.
403     */
404    private void updateTitle() {
405        mAccountsSelectorAdapter.swapCursor(mCursor);
406
407        if (mCursor == null) {
408            // Initial load not finished.
409            mActionBarCustomView.setVisibility(View.GONE);
410            return;
411        }
412        mActionBarCustomView.setVisibility(View.VISIBLE);
413
414        if (mCursor.getAccountCount() == 0) {
415            mCallback.onNoAccountsFound();
416            return;
417        }
418
419        if ((mCursor.getAccountId() != Account.NO_ACCOUNT) && !mCursor.accountExists()) {
420            // Account specified, but does not exist.
421            if (isInSearchMode()) {
422                exitSearchMode();
423            }
424
425            // Switch to the default account.
426            mCallback.onAccountSelected(Account.getDefaultAccountId(mContext));
427            return;
428        }
429
430        mTitleMode = mCallback.getTitleMode();
431
432        if (shouldShowSearchBar()) {
433            initSearchViews();
434            // In search mode, the search box is a replacement of the account spinner, so ignore
435            // the work needed to update that. It will get updated when it goes visible again.
436            mAccountSpinnerContainer.setVisibility(View.GONE);
437            mSearchContainer.setVisibility(View.VISIBLE);
438            return;
439        }
440
441        // Account spinner visible.
442        mAccountSpinnerContainer.setVisibility(View.VISIBLE);
443        UiUtilities.setVisibilitySafe(mSearchContainer, View.GONE);
444
445        if (mTitleMode == Callback.TITLE_MODE_MESSAGE_SUBJECT) {
446            mAccountSpinnerLine1View.setSingleLine(false);
447            mAccountSpinnerLine1View.setMaxLines(2);
448            mAccountSpinnerLine1View.setText(mCallback.getMessageSubject());
449            mAccountSpinnerLine2View.setVisibility(View.GONE);
450
451            mAccountSpinnerCountView.setVisibility(View.GONE);
452
453        } else {
454            // Get mailbox name
455            final String mailboxName;
456            if (mTitleMode == Callback.TITLE_MODE_ACCOUNT_WITH_ALL_FOLDERS_LABEL) {
457                mailboxName = mAllFoldersLabel;
458            } else if (mTitleMode == Callback.TITLE_MODE_ACCOUNT_WITH_MAILBOX) {
459                mailboxName = mCursor.getMailboxDisplayName();
460            } else {
461                mailboxName = null;
462            }
463
464            // Note - setSingleLine is needed as well as setMaxLines since they set different
465            // flags on the view.
466            mAccountSpinnerLine1View.setSingleLine();
467            mAccountSpinnerLine1View.setMaxLines(1);
468            if (TextUtils.isEmpty(mailboxName)) {
469                mAccountSpinnerLine1View.setText(mCursor.getAccountDisplayName());
470
471                // Change the visibility of line 2, so line 1 will be vertically-centered.
472                mAccountSpinnerLine2View.setVisibility(View.GONE);
473            } else {
474                mAccountSpinnerLine1View.setText(mailboxName);
475                mAccountSpinnerLine2View.setVisibility(View.VISIBLE);
476                mAccountSpinnerLine2View.setText(mCursor.getAccountDisplayName());
477            }
478
479            mAccountSpinnerCountView.setVisibility(View.VISIBLE);
480            mAccountSpinnerCountView.setText(UiUtilities.getMessageCountForUi(
481                    mContext, mCursor.getMailboxMessageCount(), true));
482        }
483
484        boolean spinnerEnabled =
485            ((mTitleMode & TITLE_MODE_SPINNER_ENABLED) != 0) && mCursor.shouldEnableSpinner();
486
487
488        setSpinnerEnabled(spinnerEnabled);
489    }
490
491    private void setSpinnerEnabled(boolean enabled) {
492        if (enabled == mAccountSpinner.isEnabled()) {
493            return;
494        }
495
496        mAccountSpinner.setEnabled(enabled);
497        if (enabled) {
498            mAccountSpinner.setBackgroundDrawable(mAccountSpinnerDefaultBackground);
499        } else {
500            mAccountSpinner.setBackgroundDrawable(null);
501        }
502
503        // For some reason, changing the background mucks with the padding so we have to manually
504        // reset vertical padding here (also specified in XML, but it seems to be ignored for
505        // some reason.
506        mAccountSpinner.setPadding(
507                mAccountSpinner.getPaddingLeft(),
508                0,
509                mAccountSpinner.getPaddingRight(),
510                0);
511    }
512
513
514    private final SearchView.OnQueryTextListener mOnQueryText
515            = new SearchView.OnQueryTextListener() {
516        @Override
517        public boolean onQueryTextChange(String newText) {
518            // Event not handled.  Let the search do the default action.
519            return false;
520        }
521
522        @Override
523        public boolean onQueryTextSubmit(String query) {
524            mCallback.onSearchSubmit(mSearchView.getQuery().toString());
525            return true; // Event handled.
526        }
527    };
528
529    private void onAccountSpinnerItemClicked(int position) {
530        if (mAccountsSelectorAdapter == null) { // just in case...
531            return;
532        }
533        final long accountId = mAccountsSelectorAdapter.getAccountId(position);
534
535        if (mAccountsSelectorAdapter.isAccountItem(position)) {
536            mCallback.onAccountSelected(accountId);
537        } else if (mAccountsSelectorAdapter.isMailboxItem(position)) {
538            mCallback.onMailboxSelected(accountId,
539                    mAccountsSelectorAdapter.getId(position));
540        }
541    }
542
543    // Based on Spinner.DropdownPopup
544    private class AccountDropdownPopup extends ListPopupWindow {
545        public AccountDropdownPopup(Context context) {
546            super(context);
547
548            setAnchorView(mAccountSpinner);
549            setModal(true);
550            setPromptPosition(POSITION_PROMPT_ABOVE);
551            setOnItemClickListener(new OnItemClickListener() {
552                public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
553                    onAccountSpinnerItemClicked(position);
554                    dismiss();
555                }
556            });
557        }
558
559        @Override
560        public void show() {
561            setWidth(mContext.getResources().getDimensionPixelSize(
562                    R.dimen.account_spinner_dropdown_width));
563            setInputMethodMode(ListPopupWindow.INPUT_METHOD_NOT_NEEDED);
564            super.show();
565            // List view is instantiated in super.show(), so we need to do this after...
566            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
567        }
568    }
569}
570