blob: 1b63db680c6587a55f8c25e7885641f559eb5a49 [file] [log] [blame]
Vikram Aggarwal4a5c5302012-01-12 15:07:13 -08001/*******************************************************************************
2 * Copyright (C) 2012 Google Inc.
3 * Licensed to The Android Open Source Project.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *******************************************************************************/
17
18package com.android.mail.ui;
19
Andy Huang12b3ee42013-04-24 22:49:43 -070020import android.animation.ValueAnimator;
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -080021import android.app.ActionBar;
Vikram Aggarwalb9e1a352012-01-24 15:23:38 -080022import android.app.ActionBar.LayoutParams;
Vikram Aggarwala55b36c2012-01-13 11:45:02 -080023import android.app.Activity;
Vikram Aggarwal54452ae2012-03-13 15:29:00 -070024import android.app.AlertDialog;
Vikram Aggarwala55b36c2012-01-13 11:45:02 -080025import android.app.Dialog;
Andrew Sapperstein00179f12012-08-09 15:15:40 -070026import android.app.DialogFragment;
Vikram Aggarwal6902dcf2012-04-11 08:57:42 -070027import android.app.Fragment;
Paul Westbrook2d50bcd2012-04-10 11:53:47 -070028import android.app.FragmentManager;
Andy Huangf9a73482012-03-13 15:54:02 -070029import android.app.LoaderManager;
Vikram Aggarwale620a7a2012-03-28 13:16:14 -070030import android.app.SearchManager;
Andy Huang839ada22012-07-20 15:48:40 -070031import android.content.ContentProviderOperation;
Vikram Aggarwal80aeac52012-02-07 15:27:20 -080032import android.content.ContentResolver;
Mindy Pereira6c2663d2012-07-20 15:37:29 -070033import android.content.ContentValues;
Vikram Aggarwala55b36c2012-01-13 11:45:02 -080034import android.content.Context;
Vikram Aggarwal54452ae2012-03-13 15:29:00 -070035import android.content.DialogInterface;
Vikram Aggarwal6cadbfc2012-12-27 09:17:05 -080036import android.content.DialogInterface.OnClickListener;
Vikram Aggarwala55b36c2012-01-13 11:45:02 -080037import android.content.Intent;
Vikram Aggarwal7dedb952012-02-16 16:10:23 -080038import android.content.Loader;
Paul Westbrook57246a42013-04-21 09:40:22 -070039import android.content.res.Configuration;
Vikram Aggarwalbcb16b92013-01-28 18:05:03 -080040import android.content.res.Resources;
Alice Yangebeef1b2013-09-04 06:41:10 +000041import android.database.Cursor;
Andy Huang632721e2012-04-11 16:57:26 -070042import android.database.DataSetObservable;
43import android.database.DataSetObserver;
Andy Huang61f26c22014-03-13 18:24:52 -070044import android.database.Observable;
Paul Westbrook23b74b92012-02-29 11:36:12 -080045import android.net.Uri;
Vikram Aggarwal27d89ad2012-06-12 13:38:40 -070046import android.os.AsyncTask;
Vikram Aggarwala55b36c2012-01-13 11:45:02 -080047import android.os.Bundle;
Mindy Pereira21ab4902012-03-19 18:48:03 -070048import android.os.Handler;
Scott Kennedyf77806e2013-08-30 11:38:15 -070049import android.os.Parcelable;
Vikram Aggarwale620a7a2012-03-28 13:16:14 -070050import android.provider.SearchRecentSuggestions;
Andy Huang12b3ee42013-04-24 22:49:43 -070051import android.support.v4.app.ActionBarDrawerToggle;
52import android.support.v4.widget.DrawerLayout;
Mindy Pereiraacf60392012-04-06 09:11:00 -070053import android.view.DragEvent;
Andy Huang12b3ee42013-04-24 22:49:43 -070054import android.view.Gravity;
Vikram Aggarwala55b36c2012-01-13 11:45:02 -080055import android.view.KeyEvent;
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -080056import android.view.LayoutInflater;
Vikram Aggarwala55b36c2012-01-13 11:45:02 -080057import android.view.Menu;
Mindy Pereira28d5f722012-02-15 12:32:40 -080058import android.view.MenuInflater;
Vikram Aggarwala55b36c2012-01-13 11:45:02 -080059import android.view.MenuItem;
60import android.view.MotionEvent;
Mindy Pereirad33674992012-06-25 16:26:30 -070061import android.view.View;
Andy Huang12b3ee42013-04-24 22:49:43 -070062import android.widget.ListView;
Mindy Pereirafd0c2972012-03-27 13:50:39 -070063import android.widget.Toast;
Vikram Aggarwala55b36c2012-01-13 11:45:02 -080064
Vikram Aggarwalb9e1a352012-01-24 15:23:38 -080065import com.android.mail.ConversationListContext;
Vikram Aggarwal59f741f2013-03-01 15:55:40 -080066import com.android.mail.MailLogService;
Andy Huangf9a73482012-03-13 15:54:02 -070067import com.android.mail.R;
Andy Huang761522c2013-08-08 13:09:11 -070068import com.android.mail.analytics.Analytics;
69import com.android.mail.analytics.AnalyticsUtils;
Vikram Aggarwal6cadbfc2012-12-27 09:17:05 -080070import com.android.mail.browse.ConfirmDialogFragment;
Mindy Pereira967ede62012-03-22 09:29:09 -070071import com.android.mail.browse.ConversationCursor;
Yu Ping Hu7c909c72013-01-18 11:58:01 -080072import com.android.mail.browse.ConversationCursor.ConversationOperation;
mindypca87de42012-09-28 15:02:39 -070073import com.android.mail.browse.ConversationItemViewModel;
Andrew Sapperstein8812d3c2013-06-04 17:06:41 -070074import com.android.mail.browse.ConversationMessage;
Paul Westbrookbf232c32012-04-18 03:17:41 -070075import com.android.mail.browse.ConversationPagerController;
Marc Blank7c9f6ac2012-04-02 13:27:19 -070076import com.android.mail.browse.SelectedConversationsActionMenu;
Andy Huang991f4532012-08-14 13:32:55 -070077import com.android.mail.browse.SyncErrorDialogFragment;
Mindy Pereira9b875682012-02-15 18:10:54 -080078import com.android.mail.compose.ComposeActivity;
Vikram Aggarwal177097f2013-03-08 11:19:53 -080079import com.android.mail.content.CursorCreator;
80import com.android.mail.content.ObjectCursor;
81import com.android.mail.content.ObjectCursorLoader;
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -080082import com.android.mail.providers.Account;
Mindy Pereira9b875682012-02-15 18:10:54 -080083import com.android.mail.providers.Conversation;
Andy Huang839ada22012-07-20 15:48:40 -070084import com.android.mail.providers.ConversationInfo;
Vikram Aggarwal4a5c5302012-01-12 15:07:13 -080085import com.android.mail.providers.Folder;
Vikram Aggarwal7a5d95a2012-07-27 16:24:54 -070086import com.android.mail.providers.FolderWatcher;
Paul Westbrookc2074c42012-03-22 15:26:58 -070087import com.android.mail.providers.MailAppProvider;
Mindy Pereiradac00542012-03-01 10:50:33 -080088import com.android.mail.providers.Settings;
Vikram Aggarwale620a7a2012-03-28 13:16:14 -070089import com.android.mail.providers.SuggestionsProvider;
Vikram Aggarwal80aeac52012-02-07 15:27:20 -080090import com.android.mail.providers.UIProvider;
Mindy Pereira3cb28b52012-05-24 15:26:39 -070091import com.android.mail.providers.UIProvider.AccountCapabilities;
Scott Kennedy0d0f8b02012-10-12 15:18:18 -070092import com.android.mail.providers.UIProvider.AccountColumns;
Paul Westbrook2388c5d2012-03-25 12:29:11 -070093import com.android.mail.providers.UIProvider.AccountCursorExtraKeys;
Scott Kennedy0d0f8b02012-10-12 15:18:18 -070094import com.android.mail.providers.UIProvider.AutoAdvance;
Mindy Pereirac9d59182012-03-22 16:06:46 -070095import com.android.mail.providers.UIProvider.ConversationColumns;
Paul Westbrook5109c512012-11-05 11:00:30 -080096import com.android.mail.providers.UIProvider.ConversationOperations;
Vikram Aggarwal54452ae2012-03-13 15:29:00 -070097import com.android.mail.providers.UIProvider.FolderCapabilities;
Scott Kennedya158ac82013-09-04 13:48:13 -070098import com.android.mail.providers.UIProvider.FolderType;
Andrew Sappersteinc2c9dc12012-07-02 18:17:32 -070099import com.android.mail.ui.ActionableToastBar.ActionClickedListener;
Andy Huang839ada22012-07-20 15:48:40 -0700100import com.android.mail.utils.ContentProviderTask;
Andy Huang144bfe72013-06-11 13:27:52 -0700101import com.android.mail.utils.DrawIdler;
Paul Westbrookb334c902012-06-25 11:42:46 -0700102import com.android.mail.utils.LogTag;
Mindy Pereira5cb0c3e2012-02-22 15:22:47 -0800103import com.android.mail.utils.LogUtils;
Andy Huang61f26c22014-03-13 18:24:52 -0700104import com.android.mail.utils.MailObservable;
Scott Kennedycb85aea2013-02-25 13:08:32 -0800105import com.android.mail.utils.NotificationActionUtils;
Vikram Aggarwalfa131a22012-02-02 13:56:22 -0800106import com.android.mail.utils.Utils;
Vikram Aggarwal69a6cdf2013-01-08 16:05:17 -0800107import com.android.mail.utils.VeiledAddressMatcher;
Paul Westbrookca08fc12012-07-31 12:01:15 -0700108import com.google.common.base.Objects;
Paul Westbrook77eee622012-07-10 13:41:57 -0700109import com.google.common.collect.ImmutableList;
Mindy Pereiraacf60392012-04-06 09:11:00 -0700110import com.google.common.collect.Lists;
Marc Blank167faa82012-03-21 13:11:53 -0700111import com.google.common.collect.Sets;
Vikram Aggarwal4a5c5302012-01-12 15:07:13 -0800112
Marc Blank167faa82012-03-21 13:11:53 -0700113import java.util.ArrayList;
Andy Huang9e4ca792013-02-28 14:33:43 -0800114import java.util.Arrays;
Mindy Pereirafbe40192012-03-20 10:40:45 -0700115import java.util.Collection;
Andy Huang839ada22012-07-20 15:48:40 -0700116import java.util.Collections;
Andy Huangc1fb9a92013-02-11 13:09:12 -0800117import java.util.Deque;
Mindy Pereira8db7e402012-07-13 10:32:47 -0700118import java.util.HashMap;
Vikram Aggarwalcc754b12012-08-30 14:04:21 -0700119import java.util.List;
Paul Westbrook23b74b92012-02-29 11:36:12 -0800120import java.util.Set;
Marc Blankbf128eb2012-04-18 15:58:45 -0700121import java.util.TimerTask;
Paul Westbrook23b74b92012-02-29 11:36:12 -0800122
123
Vikram Aggarwal4a5c5302012-01-12 15:07:13 -0800124/**
Mindy Pereira161f50d2012-02-28 15:47:19 -0800125 * This is an abstract implementation of the Activity Controller. This class
126 * knows how to respond to menu items, state changes, layout changes, etc. It
127 * weaves together the views and listeners, dispatching actions to the
128 * respective underlying classes.
Vikram Aggarwala55b36c2012-01-13 11:45:02 -0800129 * <p>
Mindy Pereira161f50d2012-02-28 15:47:19 -0800130 * Even though this class is abstract, it should provide default implementations
131 * for most, if not all the methods in the ActivityController interface. This
132 * makes the task of the subclasses easier: OnePaneActivityController and
133 * TwoPaneActivityController can be concise when the common functionality is in
134 * AbstractActivityController.
135 * </p>
136 * <p>
137 * In the Gmail codebase, this was called BaseActivityController
138 * </p>
Vikram Aggarwal4a5c5302012-01-12 15:07:13 -0800139 */
Andrew Sappersteined5b52d2013-04-30 13:40:18 -0700140public abstract class AbstractActivityController implements ActivityController,
141 EmptyFolderDialogFragment.EmptyFolderDialogFragmentListener {
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -0800142 // Keys for serialization of various information in Bundles.
Vikram Aggarwalcabd3f22012-04-19 10:14:41 -0700143 /** Tag for {@link #mAccount} */
Vikram Aggarwal6c511582012-02-27 10:59:47 -0800144 private static final String SAVED_ACCOUNT = "saved-account";
Vikram Aggarwalcabd3f22012-04-19 10:14:41 -0700145 /** Tag for {@link #mFolder} */
Mindy Pereira5e478d22012-03-26 18:04:58 -0700146 private static final String SAVED_FOLDER = "saved-folder";
Vikram Aggarwalcabd3f22012-04-19 10:14:41 -0700147 /** Tag for {@link #mCurrentConversation} */
Mindy Pereira26f23fc2012-03-27 10:26:04 -0700148 private static final String SAVED_CONVERSATION = "saved-conversation";
Vikram Aggarwalcabd3f22012-04-19 10:14:41 -0700149 /** Tag for {@link #mSelectedSet} */
150 private static final String SAVED_SELECTED_SET = "saved-selected-set";
Vikram Aggarwal649b9ea2012-08-27 12:15:20 -0700151 /** Tag for {@link ActionableToastBar#getOperation()} */
Mindy Pereirad33674992012-06-25 16:26:30 -0700152 private static final String SAVED_TOAST_BAR_OP = "saved-toast-bar-op";
Vikram Aggarwal649b9ea2012-08-27 12:15:20 -0700153 /** Tag for {@link #mFolderListFolder} */
154 private static final String SAVED_HIERARCHICAL_FOLDER = "saved-hierarchical-folder";
Vikram Aggarwalf3341402012-08-07 10:09:38 -0700155 /** Tag for {@link ConversationListContext#searchQuery} */
156 private static final String SAVED_QUERY = "saved-query";
Vikram Aggarwal6cadbfc2012-12-27 09:17:05 -0800157 /** Tag for {@link #mDialogAction} */
158 private static final String SAVED_ACTION = "saved-action";
Vikram Aggarwalb8c31712013-01-03 17:03:19 -0800159 /** Tag for {@link #mDialogFromSelectedSet} */
160 private static final String SAVED_ACTION_FROM_SELECTED = "saved-action-from-selected";
Vikram Aggarwala91d00b2013-01-18 12:00:37 -0800161 /** Tag for {@link #mDetachedConvUri} */
162 private static final String SAVED_DETACHED_CONV_URI = "saved-detached-conv-uri";
Alice Yangebeef1b2013-09-04 06:41:10 +0000163 /** Key to store {@link #mInbox}. */
Scott Kennedyf77806e2013-08-30 11:38:15 -0700164 private static final String SAVED_INBOX_KEY = "m-inbox";
165 /** Key to store {@link #mConversationListScrollPositions} */
166 private static final String SAVED_CONVERSATION_LIST_SCROLL_POSITIONS =
167 "saved-conversation-list-scroll-positions";
Mindy Pereira5cb0c3e2012-02-22 15:22:47 -0800168
Vikram Aggarwal6902dcf2012-04-11 08:57:42 -0700169 /** Tag used when loading a wait fragment */
170 protected static final String TAG_WAIT = "wait-fragment";
171 /** Tag used when loading a conversation list fragment. */
Paul Westbrookbf232c32012-04-18 03:17:41 -0700172 public static final String TAG_CONVERSATION_LIST = "tag-conversation-list";
Scott Kennedy103319a2013-07-26 13:35:35 -0700173 /** Tag used when loading a custom fragment. */
174 protected static final String TAG_CUSTOM_FRAGMENT = "tag-custom-fragment";
Vikram Aggarwal6902dcf2012-04-11 08:57:42 -0700175
Vikram Aggarwala1b59dc2013-04-30 15:45:49 -0700176 /** Key to store an account in a bundle */
177 private final String BUNDLE_ACCOUNT_KEY = "account";
178 /** Key to store a folder in a bundle */
179 private final String BUNDLE_FOLDER_KEY = "folder";
Andrew Sapperstein5bb4d052014-03-31 16:22:31 -0700180 /**
181 * Key to set a flag for the ConversationCursorLoader to ignore any
182 * initial load limit that may be set by the Account. Instead,
183 * perform a full load instead of the full-stage load.
184 */
185 private final String BUNDLE_IGNORE_INITIAL_CONVERSATION_LIMIT_KEY =
186 "ignore-initial-conversation-limit";
Vikram Aggarwala1b59dc2013-04-30 15:45:49 -0700187
Vikram Aggarwald7a12cd2012-02-03 09:36:20 -0800188 protected Account mAccount;
Mindy Pereira12a4d802012-06-22 09:24:43 -0700189 protected Folder mFolder;
Alice Yangebeef1b2013-09-04 06:41:10 +0000190 protected Folder mInbox;
Vikram Aggarwal69b5c302012-09-05 11:11:13 -0700191 /** True when {@link #mFolder} is first shown to the user. */
192 private boolean mFolderChanged = false;
Andy Huang6681e542012-06-14 14:36:45 -0700193 protected MailActionBarView mActionBarView;
James Lemieux10fcd642014-03-03 13:01:04 -0800194 protected final MailActivity mActivity;
Vikram Aggarwala55b36c2012-01-13 11:45:02 -0800195 protected final Context mContext;
Vikram Aggarwal6902dcf2012-04-11 08:57:42 -0700196 private final FragmentManager mFragmentManager;
Vikram Aggarwalec5cbf72012-03-08 15:10:35 -0800197 protected final RecentFolderList mRecentFolderList;
Vikram Aggarwal80aeac52012-02-07 15:27:20 -0800198 protected ConversationListContext mConvListContext;
Mindy Pereira9b875682012-02-15 18:10:54 -0800199 protected Conversation mCurrentConversation;
Vikram Aggarwala91d00b2013-01-18 12:00:37 -0800200 /**
201 * The hash of {@link #mCurrentConversation} in detached mode. 0 if we are not in detached mode.
202 */
203 private Uri mDetachedConvUri;
Vikram Aggarwald7a12cd2012-02-03 09:36:20 -0800204
Scott Kennedyf77806e2013-08-30 11:38:15 -0700205 /** A map of {@link Folder} {@link Uri} to scroll position in the conversation list. */
206 private final Bundle mConversationListScrollPositions = new Bundle();
207
Paul Westbrook6ead20d2012-03-19 14:48:14 -0700208 /** A {@link android.content.BroadcastReceiver} that suppresses new e-mail notifications. */
209 private SuppressNotificationReceiver mNewEmailReceiver = null;
210
Vikram Aggarwal59f741f2013-03-01 15:55:40 -0800211 /** Handler for all our local runnables. */
Mindy Pereirafbe40192012-03-20 10:40:45 -0700212 protected Handler mHandler = new Handler();
Mindy Pereirafa995b42012-07-25 12:06:13 -0700213
Vikram Aggarwalfa131a22012-02-02 13:56:22 -0800214 /**
Mindy Pereira161f50d2012-02-28 15:47:19 -0800215 * The current mode of the application. All changes in mode are initiated by
216 * the activity controller. View mode changes are propagated to classes that
217 * attach themselves as listeners of view mode changes.
Vikram Aggarwalfa131a22012-02-02 13:56:22 -0800218 */
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -0800219 protected final ViewMode mViewMode;
Vikram Aggarwal80aeac52012-02-07 15:27:20 -0800220 protected ContentResolver mResolver;
Vikram Aggarwalc04cf7e2013-05-13 15:38:42 -0700221 protected boolean mHaveAccountList = false;
Mindy Pereirab7b33e02012-02-21 15:32:19 -0800222 private AsyncRefreshTask mAsyncRefreshTask;
Mindy Pereira5cb0c3e2012-02-22 15:22:47 -0800223
Andy Huang4e0158f2012-08-07 21:06:01 -0700224 private boolean mDestroyed;
225
Vikram Aggarwalbcb16b92013-01-28 18:05:03 -0800226 /** True if running on tablet */
227 private final boolean mIsTablet;
228
Andy Huang1ee96b22012-08-24 20:19:53 -0700229 /**
230 * Are we in a point in the Activity/Fragment lifecycle where it's safe to execute fragment
231 * transactions? (including back stack manipulation)
232 * <p>
233 * Per docs in {@link FragmentManager#beginTransaction()}, this flag starts out true, switches
234 * to false after {@link Activity#onSaveInstanceState}, and becomes true again in both onStart
235 * and onResume.
236 */
237 private boolean mSafeToModifyFragments = true;
238
Paul Westbrook23b74b92012-02-29 11:36:12 -0800239 private final Set<Uri> mCurrentAccountUris = Sets.newHashSet();
Mindy Pereira967ede62012-03-22 09:29:09 -0700240 protected ConversationCursor mConversationListCursor;
Andy Huang61f26c22014-03-13 18:24:52 -0700241 private final DataSetObservable mConversationListObservable = new MailObservable("List");
Marc Blankbf128eb2012-04-18 15:58:45 -0700242
Vikram Aggarwal59f741f2013-03-01 15:55:40 -0800243 /** Runnable that checks the logging level to enable/disable the logging service. */
244 private Runnable mLogServiceChecker = null;
Vikram Aggarwalde60c9d2013-04-10 12:58:56 -0700245 /** List of all accounts currently known to the controller. This is never null. */
246 private Account[] mAllAccounts = new Account[0];
Vikram Aggarwal59f741f2013-03-01 15:55:40 -0800247
Vikram Aggarwal77ee0ce2013-04-28 15:32:36 -0700248 private FolderWatcher mFolderWatcher;
249
Andrew Sapperstein5bb4d052014-03-31 16:22:31 -0700250 private boolean mIgnoreInitialConversationLimit;
251
Yu Ping Hu7c909c72013-01-18 11:58:01 -0800252 /**
253 * Interface for actions that are deferred until after a load completes. This is for handling
254 * user actions which affect cursors (e.g. marking messages read or unread) that happen before
255 * that cursor is loaded.
256 */
257 private interface LoadFinishedCallback {
258 void onLoadFinished();
259 }
260
261 /** The deferred actions to execute when mConversationListCursor load completes. */
262 private final ArrayList<LoadFinishedCallback> mConversationListLoadFinishedCallbacks =
263 new ArrayList<LoadFinishedCallback>();
264
Marc Blankbf128eb2012-04-18 15:58:45 -0700265 private RefreshTimerTask mConversationListRefreshTask;
Marc Blanke1d1b072012-04-13 17:29:16 -0700266
Vikram Aggarwal7c401b72012-08-13 16:43:47 -0700267 /** Listeners that are interested in changes to the current account. */
Andy Huang61f26c22014-03-13 18:24:52 -0700268 private final DataSetObservable mAccountObservers = new MailObservable("Account");
Vikram Aggarwal58cad2e2012-08-28 16:18:23 -0700269 /** Listeners that are interested in changes to the recent folders. */
Andy Huang61f26c22014-03-13 18:24:52 -0700270 private final DataSetObservable mRecentFolderObservers = new MailObservable("RecentFolder");
Vikram Aggarwal07dbaa62013-03-12 15:21:04 -0700271 /** Listeners that are interested in changes to the list of all accounts. */
Andy Huang61f26c22014-03-13 18:24:52 -0700272 private final DataSetObservable mAllAccountObservers = new MailObservable("AllAccounts");
Vikram Aggarwal50ff0e52013-03-14 13:58:02 -0700273 /** Listeners that are interested in changes to the current folder. */
Andy Huang61f26c22014-03-13 18:24:52 -0700274 private final DataSetObservable mFolderObservable = new MailObservable("CurrentFolder");
Rohan Shah0f73d902013-04-19 17:06:37 -0700275 /** Listeners that are interested in changes to the drawer state. */
Andy Huang61f26c22014-03-13 18:24:52 -0700276 private final DataSetObservable mDrawerObservers = new MailObservable("Drawer");
Vikram Aggarwal58cad2e2012-08-28 16:18:23 -0700277
Mindy Pereira967ede62012-03-22 09:29:09 -0700278 /**
279 * Selected conversations, if any.
280 */
Andy Huang4556a442012-03-30 16:42:05 -0700281 private final ConversationSelectionSet mSelectedSet = new ConversationSelectionSet();
Mindy Pereiradac00542012-03-01 10:50:33 -0800282
Paul Westbrookc7a070f2012-04-12 01:46:41 -0700283 private final int mFolderItemUpdateDelayMs;
284
Vikram Aggarwal135fd022012-04-11 14:44:15 -0700285 /** Keeps track of selected and unselected conversations */
Paul Westbrook937c94f2012-08-16 13:01:18 -0700286 final protected ConversationPositionTracker mTracker;
Vikram Aggarwalaf1ee0c2012-04-12 17:13:13 -0700287
Vikram Aggarwale128fc22012-04-04 12:33:34 -0700288 /**
289 * Action menu associated with the selected set.
290 */
291 SelectedConversationsActionMenu mCabActionMenu;
Andrew Sappersteinc2c9dc12012-07-02 18:17:32 -0700292 protected ActionableToastBar mToastBar;
Andy Huang632721e2012-04-11 16:57:26 -0700293 protected ConversationPagerController mPagerController;
Mindy Pereiraab486362012-03-21 18:18:53 -0700294
Vikram Aggarwald70fe492013-06-04 12:52:07 -0700295 // This is split out from the general loader dispatcher because its loader doesn't return a
Andy Huangb1c34dc2012-04-17 16:36:19 -0700296 // basic Cursor
Vikram Aggarwald70fe492013-06-04 12:52:07 -0700297 /** Handles loader callbacks to create a convesation cursor. */
Andy Huangb1c34dc2012-04-17 16:36:19 -0700298 private final ConversationListLoaderCallbacks mListCursorCallbacks =
299 new ConversationListLoaderCallbacks();
300
Vikram Aggarwal177097f2013-03-08 11:19:53 -0800301 /** Object that listens to all LoaderCallbacks that result in {@link Folder} creation. */
302 private final FolderLoads mFolderCallbacks = new FolderLoads();
303 /** Object that listens to all LoaderCallbacks that result in {@link Account} creation. */
304 private final AccountLoads mAccountCallbacks = new AccountLoads();
305
Vikram Aggarwal69a6cdf2013-01-08 16:05:17 -0800306 /**
307 * Matched addresses that must be shielded from users because they are temporary. Even though
308 * this is instantiated from settings, this matcher is valid for all accounts, and is expected
309 * to live past the life of an account.
310 */
311 private final VeiledAddressMatcher mVeiledMatcher;
312
Paul Westbrookb334c902012-06-25 11:42:46 -0700313 protected static final String LOG_TAG = LogTag.getLogTag();
Vikram Aggarwald70fe492013-06-04 12:52:07 -0700314
Vikram Aggarwalaa941d72013-06-04 15:34:28 -0700315 // Loader constants: Accounts
316 /**
317 * The list of accounts. This loader is started early in the application life-cycle since
318 * the list of accounts is central to all other data the application needs: unread counts for
319 * folders, critical UI settings like show/hide checkboxes, ...
320 * The loader is started when the application is created: both in
321 * {@link #onCreate(Bundle)} and in {@link #onActivityResult(int, int, Intent)}. It is never
322 * destroyed since the cursor is needed through the life of the application. When the list of
323 * accounts changes, we notify {@link #mAllAccountObservers}.
324 */
Vikram Aggarwalfa4b47e2012-03-09 13:02:46 -0800325 private static final int LOADER_ACCOUNT_CURSOR = 0;
Vikram Aggarwalaa941d72013-06-04 15:34:28 -0700326
327 /**
328 * The current account. This loader is started when we have an account. The mail application
329 * <b>needs</b> a valid account to function. As soon as we set {@link #mAccount},
330 * we start a loader to observe for changes on the current account.
331 * The loader is always restarted when an account is set in {@link #setAccount(Account)}.
332 * When the current account object changes, we notify {@link #mAccountObservers}.
333 * A possible performance improvement would be to listen purely on
334 * {@link #LOADER_ACCOUNT_CURSOR}. The current account is guaranteed to be in the list,
335 * and would avoid two updates when a single setting on the current account changes.
336 */
Paul Westbrook2d50bcd2012-04-10 11:53:47 -0700337 private static final int LOADER_ACCOUNT_UPDATE_CURSOR = 7;
Vikram Aggarwald70fe492013-06-04 12:52:07 -0700338
Vikram Aggarwalaa941d72013-06-04 15:34:28 -0700339 // Loader constants: Folders
340 /** The current folder. This loader watches for updates to the current folder in a manner
341 * analogous to the {@link #LOADER_ACCOUNT_UPDATE_CURSOR}. Updates to the current folder
342 * might be due to server-side changes (unread count), or local changes (sync window or sync
343 * status change).
344 * The change of current folder calls {@link #updateFolder(Folder)}.
345 * This is responsible for restarting a loader using the URI of the provided folder. When the
346 * loader returns, the current folder is updated and consumers, if any, are notified.
347 * When the current folder changes, we notify {@link #mFolderObservable}
348 */
Vikram Aggarwald70fe492013-06-04 12:52:07 -0700349 private static final int LOADER_FOLDER_CURSOR = 2;
Vikram Aggarwalaa941d72013-06-04 15:34:28 -0700350 /**
351 * The list of recent folders. Recent folders are shown in the DrawerFragment. The recent
352 * folders are tied to the current account being viewed. When the account is changed,
353 * we restart this loader to retrieve the recent accounts. Recents are pre-populated for
354 * phones historically, when they were displayed in the spinner. On the tablet,
355 * they showed in the {@link FolderListFragment} and were not-populated. The code to
356 * pre-populate the recents is somewhat convoluted: when the loader returns a short list of
357 * recent folders, it issues an update on the Recent Folder URI. The underlying provider then
358 * does the appropriate thing to populate recent folders, and notify of a change on the cursor.
359 * Recent folders are needed for the life of the current account.
360 * When the recent folders change, we notify {@link #mRecentFolderObservers}.
361 */
Vikram Aggarwald70fe492013-06-04 12:52:07 -0700362 private static final int LOADER_RECENT_FOLDERS = 3;
Vikram Aggarwalaa941d72013-06-04 15:34:28 -0700363 /**
364 * The primary inbox for the current account. The mechanism to load the default inbox for the
365 * current account is (sadly) different from loading other folders. The method
366 * {@link #loadAccountInbox()} is called, and it restarts this loader. When the loader returns
367 * a valid cursor, we create a folder, call {@link #onFolderChanged{Folder)} eventually
368 * calling {@link #updateFolder(Folder)} which starts a loader {@link #LOADER_FOLDER_CURSOR}
369 * over the current folder.
370 * When we have a valid cursor, we destroy this loader, This convoluted flow is historical.
371 */
Vikram Aggarwald70fe492013-06-04 12:52:07 -0700372 private static final int LOADER_ACCOUNT_INBOX = 5;
Vikram Aggarwalaa941d72013-06-04 15:34:28 -0700373 /**
374 * The fake folder of search results for a term. When we search for a term,
375 * a new activity is created with {@link Intent#ACTION_SEARCH}. For this new activity,
376 * we start a loader which returns conversations that match the user-provided query.
377 * We destroy the loader when we obtain a valid cursor since subsequent searches will create
378 * a new activity.
379 */
Vikram Aggarwald70fe492013-06-04 12:52:07 -0700380 private static final int LOADER_SEARCH = 6;
Vikram Aggarwalaa941d72013-06-04 15:34:28 -0700381 /**
382 * The initial folder at app start. When the application is launched from an intent that
383 * specifies the initial folder (notifications/widgets/shortcuts),
384 * then we extract the folder URI from the intent, but we cannot trust the folder object. Since
385 * shortcuts and widgets persist past application update, they might have incorrect
386 * information encoded in them. So, to obtain a {@link Folder} object from a {@link Uri},
387 * we need to start another loader. Upon obtaining a valid cursor, the loader is destroyed.
388 * An additional complication arises if we have to view a specific conversation within this
389 * folder. This is the case when launching the app from a single conversation notification
390 * or tapping on a specific conversation in the widget. In these cases, the conversation is
391 * saved in {@link #mConversationToShow} and is retrieved when the loader returns.
392 */
Vikram Aggarwal177097f2013-03-08 11:19:53 -0800393 public static final int LOADER_FIRST_FOLDER = 8;
394
Vikram Aggarwalaa941d72013-06-04 15:34:28 -0700395 // Loader constants: Conversations
396 /** The conversation cursor over the current conversation list. This loader provides
397 * a cursor over conversation entries from a folder to display a conversation
398 * list.
399 * This loader is started when the user switches folders (in {@link #updateFolder(Folder)},
400 * or when the controller is told that a folder/account change is imminent
401 * (in {@link #preloadConvList(Account, Folder)}. The loader is maintained for the life of
402 * the current folder. When the user switches folders, the old loader is destroyed and a new
403 * one is created.
404 *
405 * When the conversation list changes, we notify {@link #mConversationListObservable}.
406 */
Vikram Aggarwald70fe492013-06-04 12:52:07 -0700407 private static final int LOADER_CONVERSATION_LIST = 4;
408
Vikram Aggarwal7a5d95a2012-07-27 16:24:54 -0700409 /**
410 * Guaranteed to be the last loader ID used by the activity. Loaders are owned by Activity or
411 * fragments, and within an activity, loader IDs need to be unique. A hack to ensure that the
412 * {@link FolderWatcher} can create its folder loaders without clashing with the IDs of those
413 * of the {@link AbstractActivityController}. Currently, the {@link FolderWatcher} is the only
414 * other class that uses this activity's LoaderManager. If another class needs activity-level
415 * loaders, consider consolidating the loaders in a central location: a UI-less fragment
416 * perhaps.
417 */
418 public static final int LAST_LOADER_ID = 100;
Scott Kennedy7c8325d2013-02-28 10:46:10 -0800419 /**
420 * Guaranteed to be the last loader ID used by the Fragment. Loaders are owned by Activity or
421 * fragments, and within an activity, loader IDs need to be unique. Currently,
422 * {@link SectionedInboxTeaserView} is the only class that uses the
423 * {@link ConversationListFragment}'s LoaderManager.
424 */
425 public static final int LAST_FRAGMENT_LOADER_ID = 1000;
Vikram Aggarwala55b36c2012-01-13 11:45:02 -0800426
Vikram Aggarwal6aca6892013-06-04 13:53:27 -0700427 /** Code returned after an account has been added. */
Paul Westbrook2388c5d2012-03-25 12:29:11 -0700428 private static final int ADD_ACCOUNT_REQUEST_CODE = 1;
Vikram Aggarwal6aca6892013-06-04 13:53:27 -0700429 /** Code returned when the user has to enter the new password on an existing account. */
Paul Westbrook122f7c22012-08-20 17:50:31 -0700430 private static final int REAUTHENTICATE_REQUEST_CODE = 2;
Martin Hibdon371a71c2014-02-19 13:55:28 -0800431 /** Code returned when the previous activity needs to navigate to a different folder
432 * or account */
433 private static final int CHANGE_NAVIGATION_REQUEST_CODE = 3;
434
435 public static final String EXTRA_FOLDER = "extra-folder";
436 public static final String EXTRA_ACCOUNT = "extra-account";
Paul Westbrook2388c5d2012-03-25 12:29:11 -0700437
Vikram Aggarwale8a85322012-04-24 09:01:38 -0700438 /** The pending destructive action to be carried out before swapping the conversation cursor.*/
439 private DestructiveAction mPendingDestruction;
Andrew Sappersteinc2c9dc12012-07-02 18:17:32 -0700440 protected AsyncRefreshTask mFolderSyncTask;
Mindy Pereirac975e842012-07-16 09:15:00 -0700441 private Folder mFolderListFolder;
mindyp5390fca2012-08-22 12:12:25 -0700442 private boolean mIsDragHappening;
Martin Hibdone78c40f2013-10-10 18:29:25 -0700443 private final int mShowUndoBarDelay;
mindyp6f54e1b2012-10-09 09:54:08 -0700444 private boolean mRecentsDataUpdated;
Vikram Aggarwala3f43d42012-10-25 16:21:30 -0700445 /** A wait fragment we added, if any. */
446 private WaitFragment mWaitFragment;
Vikram Aggarwalf0ef2302012-11-07 14:53:34 -0800447 /** True if we have results from a search query */
448 private boolean mHaveSearchResults = false;
Vikram Aggarwal6cadbfc2012-12-27 09:17:05 -0800449 /** If a confirmation dialog is being show, the listener for the positive action. */
450 private OnClickListener mDialogListener;
451 /**
452 * If a confirmation dialog is being show, the resource of the action: R.id.delete, etc. This
453 * is used to create a new {@link #mDialogListener} on orientation changes.
454 */
455 private int mDialogAction = -1;
Vikram Aggarwalb8c31712013-01-03 17:03:19 -0800456 /**
457 * If a confirmation dialog is being shown, this is true if the dialog acts on the selected set
458 * and false if it acts on the currently selected conversation
459 */
460 private boolean mDialogFromSelectedSet;
Vikram Aggarwal6cadbfc2012-12-27 09:17:05 -0800461
Vikram Aggarwal177097f2013-03-08 11:19:53 -0800462 /** Which conversation to show, if started from widget/notification. */
463 private Conversation mConversationToShow = null;
464
Andy Huangc94d07f2013-06-03 16:19:35 -0700465 /**
466 * A temporary reference to the pending destructive action that was deferred due to an
467 * auto-advance transition in progress.
468 * <p>
469 * In detail: when auto-advance triggers a mode change, we must wait until the transition
470 * completes before executing the destructive action to ensure a smooth mode change transition.
471 * This member variable houses the pending destructive action work to be run upon completion.
472 */
473 private Runnable mAutoAdvanceOp = null;
474
Andy Huangc1fb9a92013-02-11 13:09:12 -0800475 private final Deque<UpOrBackHandler> mUpOrBackHandlers = Lists.newLinkedList();
476
Andy Huang12b3ee42013-04-24 22:49:43 -0700477 protected DrawerLayout mDrawerContainer;
478 protected View mDrawerPullout;
479 protected ActionBarDrawerToggle mDrawerToggle;
480 protected ListView mListViewForAnimating;
481 protected boolean mHasNewAccountOrFolder;
Andrew Sappersteina3ce6782013-05-09 15:14:49 -0700482 private boolean mConversationListLoadFinishedIgnored;
Andy Huang61f26c22014-03-13 18:24:52 -0700483 private final MailDrawerListener mDrawerListener = new MailDrawerListener();
Andrew Sapperstein5747e152013-05-13 14:13:08 -0700484 private boolean mHideMenuItems;
Andy Huang12b3ee42013-04-24 22:49:43 -0700485
Andy Huang144bfe72013-06-11 13:27:52 -0700486 private final DrawIdler mDrawIdler = new DrawIdler();
487
Andrew Sapperstein00179f12012-08-09 15:15:40 -0700488 public static final String SYNC_ERROR_DIALOG_FRAGMENT_TAG = "SyncErrorDialogFragment";
Vikram Aggarwale8a85322012-04-24 09:01:38 -0700489
Scott Kennedycb85aea2013-02-25 13:08:32 -0800490 private final DataSetObserver mUndoNotificationObserver = new DataSetObserver() {
491 @Override
492 public void onChanged() {
493 super.onChanged();
494
495 if (mConversationListCursor != null) {
496 mConversationListCursor.handleNotificationActions();
497 }
498 }
499 };
500
Vikram Aggarwala55b36c2012-01-13 11:45:02 -0800501 public AbstractActivityController(MailActivity activity, ViewMode viewMode) {
502 mActivity = activity;
Vikram Aggarwal6902dcf2012-04-11 08:57:42 -0700503 mFragmentManager = mActivity.getFragmentManager();
Vikram Aggarwala55b36c2012-01-13 11:45:02 -0800504 mViewMode = viewMode;
505 mContext = activity.getApplicationContext();
Vikram Aggarwal025eba82012-05-08 10:45:30 -0700506 mRecentFolderList = new RecentFolderList(mContext);
Paul Westbrook937c94f2012-08-16 13:01:18 -0700507 mTracker = new ConversationPositionTracker(this);
Mindy Pereira967ede62012-03-22 09:29:09 -0700508 // Allow the fragment to observe changes to its own selection set. No other object is
509 // aware of the selected set.
510 mSelectedSet.addObserver(this);
Paul Westbrookc7a070f2012-04-12 01:46:41 -0700511
Vikram Aggarwalbcb16b92013-01-28 18:05:03 -0800512 final Resources r = mContext.getResources();
513 mFolderItemUpdateDelayMs = r.getInteger(R.integer.folder_item_refresh_delay_ms);
514 mShowUndoBarDelay = r.getInteger(R.integer.show_undo_bar_delay_ms);
Vikram Aggarwal69a6cdf2013-01-08 16:05:17 -0800515 mVeiledMatcher = VeiledAddressMatcher.newInstance(activity.getResources());
Vikram Aggarwalbcb16b92013-01-28 18:05:03 -0800516 mIsTablet = Utils.useTabletUI(r);
Andrew Sappersteina3ce6782013-05-09 15:14:49 -0700517 mConversationListLoadFinishedIgnored = false;
Vikram Aggarwala55b36c2012-01-13 11:45:02 -0800518 }
Vikram Aggarwal4a5c5302012-01-12 15:07:13 -0800519
520 @Override
Vikram Aggarwale9a81032012-02-22 13:15:35 -0800521 public Account getCurrentAccount() {
522 return mAccount;
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -0800523 }
524
525 @Override
526 public ConversationListContext getCurrentListContext() {
Vikram Aggarwale9a81032012-02-22 13:15:35 -0800527 return mConvListContext;
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -0800528 }
529
530 @Override
Vikram Aggarwal4a5c5302012-01-12 15:07:13 -0800531 public String getHelpContext() {
Paul Westbrook30745b62012-08-19 14:10:32 -0700532 final int mode = mViewMode.getMode();
533 final int helpContextResId;
534 switch (mode) {
535 case ViewMode.WAITING_FOR_ACCOUNT_INITIALIZATION:
536 helpContextResId = R.string.wait_help_context;
537 break;
538 default:
539 helpContextResId = R.string.main_help_context;
540 }
541 return mContext.getString(helpContextResId);
Vikram Aggarwal4a5c5302012-01-12 15:07:13 -0800542 }
543
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -0800544 @Override
Vikram Aggarwalef7c9922012-04-23 12:35:04 -0700545 public final ConversationCursor getConversationListCursor() {
Mindy Pereira967ede62012-03-22 09:29:09 -0700546 return mConversationListCursor;
547 }
548
Vikram Aggarwal6902dcf2012-04-11 08:57:42 -0700549 /**
Vikram Aggarwal34a65012012-04-17 12:39:06 -0700550 * Check if the fragment is attached to an activity and has a root view.
Vikram Aggarwal715f83d2013-03-05 17:04:56 -0800551 * @param in fragment to be checked
Vikram Aggarwal34a65012012-04-17 12:39:06 -0700552 * @return true if the fragment is valid, false otherwise
553 */
Vikram Aggarwal715f83d2013-03-05 17:04:56 -0800554 private static boolean isValidFragment(Fragment in) {
555 return !(in == null || in.getActivity() == null || in.getView() == null);
Vikram Aggarwal34a65012012-04-17 12:39:06 -0700556 }
557
558 /**
Vikram Aggarwal49e0e992012-09-21 13:53:15 -0700559 * Get the conversation list fragment for this activity. If the conversation list fragment is
560 * not attached, this method returns null.
Andy Huang839ada22012-07-20 15:48:40 -0700561 *
Vikram Aggarwal49e0e992012-09-21 13:53:15 -0700562 * Caution! This method returns the {@link ConversationListFragment} after the fragment has been
563 * added, <b>and</b> after the {@link FragmentManager} has run through its queue to add the
564 * fragment. There is a non-trivial amount of time after the fragment is instantiated and before
565 * this call returns a non-null value, depending on the {@link FragmentManager}. If you
566 * need the fragment immediately after adding it, consider making the fragment an observer of
567 * the controller and perform the task immediately on {@link Fragment#onActivityCreated(Bundle)}
Vikram Aggarwal6902dcf2012-04-11 08:57:42 -0700568 */
569 protected ConversationListFragment getConversationListFragment() {
570 final Fragment fragment = mFragmentManager.findFragmentByTag(TAG_CONVERSATION_LIST);
Vikram Aggarwal34a65012012-04-17 12:39:06 -0700571 if (isValidFragment(fragment)) {
572 return (ConversationListFragment) fragment;
Andy Huang9585d782012-04-16 19:45:04 -0700573 }
Vikram Aggarwal34a65012012-04-17 12:39:06 -0700574 return null;
Vikram Aggarwal6902dcf2012-04-11 08:57:42 -0700575 }
576
577 /**
Vikram Aggarwal6902dcf2012-04-11 08:57:42 -0700578 * Returns the folder list fragment attached with this activity. If no such fragment is attached
579 * this method returns null.
Andy Huang839ada22012-07-20 15:48:40 -0700580 *
Vikram Aggarwal49e0e992012-09-21 13:53:15 -0700581 * Caution! This method returns the {@link FolderListFragment} after the fragment has been
582 * added, <b>and</b> after the {@link FragmentManager} has run through its queue to add the
583 * fragment. There is a non-trivial amount of time after the fragment is instantiated and before
584 * this call returns a non-null value, depending on the {@link FragmentManager}. If you
585 * need the fragment immediately after adding it, consider making the fragment an observer of
586 * the controller and perform the task immediately on {@link Fragment#onActivityCreated(Bundle)}
Vikram Aggarwal6902dcf2012-04-11 08:57:42 -0700587 */
588 protected FolderListFragment getFolderListFragment() {
James Lemieux10fcd642014-03-03 13:01:04 -0800589 final String drawerPulloutTag = mActivity.getString(R.string.drawer_pullout_tag);
590 final Fragment fragment = mFragmentManager.findFragmentByTag(drawerPulloutTag);
Vikram Aggarwal34a65012012-04-17 12:39:06 -0700591 if (isValidFragment(fragment)) {
592 return (FolderListFragment) fragment;
Andy Huang9585d782012-04-16 19:45:04 -0700593 }
Vikram Aggarwal34a65012012-04-17 12:39:06 -0700594 return null;
Vikram Aggarwal6902dcf2012-04-11 08:57:42 -0700595 }
596
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -0800597 /**
Mindy Pereira161f50d2012-02-28 15:47:19 -0800598 * Initialize the action bar. This is not visible to OnePaneController and
599 * TwoPaneController so they cannot override this behavior.
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -0800600 */
Vikram Aggarwalabd24d82012-04-26 13:23:14 -0700601 private void initializeActionBar() {
602 final ActionBar actionBar = mActivity.getActionBar();
Andy Huang5895f7b2012-06-01 17:07:20 -0700603 if (actionBar == null) {
604 return;
Vikram Aggarwalabd24d82012-04-26 13:23:14 -0700605 }
Andy Huang5895f7b2012-06-01 17:07:20 -0700606
607 // be sure to inherit from the ActionBar theme when inflating
608 final LayoutInflater inflater = LayoutInflater.from(actionBar.getThemedContext());
Mindy Pereira82faec72012-06-14 17:21:50 -0700609 final boolean isSearch = mActivity.getIntent() != null
610 && Intent.ACTION_SEARCH.equals(mActivity.getIntent().getAction());
611 mActionBarView = (MailActionBarView) inflater.inflate(
612 isSearch ? R.layout.search_actionbar_view : R.layout.actionbar_view, null);
Vikram Aggarwaldac89fa2013-03-05 16:43:09 -0800613 mActionBarView.initialize(mActivity, this, actionBar);
Rohan Shah1dd054f2013-04-01 11:23:44 -0700614
Andy Huang12b3ee42013-04-24 22:49:43 -0700615 // init the action bar to allow the 'up' affordance.
616 // any configurations that disallow 'up' should do that later.
617 mActionBarView.setBackButton();
Vikram Aggarwalabd24d82012-04-26 13:23:14 -0700618 }
619
620 /**
621 * Attach the action bar to the activity.
622 */
623 private void attachActionBar() {
624 final ActionBar actionBar = mActivity.getActionBar();
Tony Mantlerbd091502013-09-16 13:59:47 -0700625 if (actionBar != null) {
Vikram Aggarwalec5cbf72012-03-08 15:10:35 -0800626 actionBar.setCustomView(mActionBarView, new ActionBar.LayoutParams(
Vikram Aggarwal26b0bfd2013-03-29 13:05:08 -0700627 LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
Vikram Aggarwalbc462ca2013-03-15 10:41:03 -0700628 // Show a custom view and home icon, keep the title and subttitle
Vikram Aggarwal649b9ea2012-08-27 12:15:20 -0700629 final int mask = ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_TITLE
630 | ActionBar.DISPLAY_SHOW_HOME;
Vikram Aggarwalbc462ca2013-03-15 10:41:03 -0700631 actionBar.setDisplayOptions(mask, mask);
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -0800632 }
Tony Mantlerbd091502013-09-16 13:59:47 -0700633 mActionBarView.setViewModeController(mViewMode);
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -0800634 }
635
636 /**
Mindy Pereira161f50d2012-02-28 15:47:19 -0800637 * Returns whether the conversation list fragment is visible or not.
638 * Different layouts will have their own notion on the visibility of
639 * fragments, so this method needs to be overriden.
640 *
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -0800641 */
642 protected abstract boolean isConversationListVisible();
643
Vikram Aggarwaleb7d3292012-04-20 17:07:20 -0700644 /**
Vikram Aggarwal34f7b232012-10-17 13:32:23 -0700645 * If required, starts wait mode for the current account.
Vikram Aggarwal34f7b232012-10-17 13:32:23 -0700646 */
647 final void perhapsEnterWaitMode() {
648 // If the account is not initialized, then show the wait fragment, since nothing can be
649 // shown.
650 if (mAccount.isAccountInitializationRequired()) {
651 showWaitForInitialization();
652 return;
653 }
654
655 final boolean inWaitingMode = inWaitMode();
656 final boolean isSyncRequired = mAccount.isAccountSyncRequired();
657 if (isSyncRequired) {
658 if (inWaitingMode) {
659 // Update the WaitFragment's account object
660 updateWaitMode();
661 } else {
662 // Transition to waiting mode
663 showWaitForInitialization();
664 }
665 } else if (inWaitingMode) {
666 // Dismiss waiting mode
667 hideWaitForInitialization();
668 }
669 }
670
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -0800671 @Override
Andrew Sapperstein4cbb0da2013-04-19 11:28:02 -0700672 public void switchToDefaultInboxOrChangeAccount(Account account) {
673 LogUtils.d(LOG_TAG, "AAC.switchToDefaultAccount(%s)", account);
Andy Huange764cfd2014-02-26 11:55:03 -0800674 if (mViewMode.isSearchMode()) {
Martin Hibdon371a71c2014-02-19 13:55:28 -0800675 // We are in an activity on top of the main navigation activity.
676 // We need to return to it with a result code that indicates it should navigate to
677 // a different folder.
678 final Intent intent = new Intent();
679 intent.putExtra(AbstractActivityController.EXTRA_ACCOUNT, account);
680 mActivity.setResult(Activity.RESULT_OK, intent);
681 mActivity.finish();
682 return;
683 }
Vikram Aggarwal66bc6ed2012-07-31 09:59:55 -0700684 final boolean firstLoad = mAccount == null;
Andrew Sapperstein252684a2013-04-17 14:43:26 -0700685 final boolean switchToDefaultInbox = !firstLoad && account.uri.equals(mAccount.uri);
Vikram Aggarwald70fe492013-06-04 12:52:07 -0700686 // If the active account has been clicked in the drawer, go to default inbox
Andrew Sapperstein252684a2013-04-17 14:43:26 -0700687 if (switchToDefaultInbox) {
688 loadAccountInbox();
689 return;
690 }
Andrew Sapperstein4cbb0da2013-04-19 11:28:02 -0700691 changeAccount(account);
692 }
693
694 @Override
695 public void changeAccount(Account account) {
696 LogUtils.d(LOG_TAG, "AAC.changeAccount(%s)", account);
697 // Is the account or account settings different from the existing account?
698 final boolean firstLoad = mAccount == null;
699 final boolean accountChanged = firstLoad || !account.uri.equals(mAccount.uri);
700
Vikram Aggarwal472e5362012-11-05 14:17:23 -0800701 // If nothing has changed, return early without wasting any more time.
702 if (!accountChanged && !account.settingsDiffer(mAccount)) {
703 return;
704 }
705 // We also don't want to do anything if the new account is null
706 if (account == null) {
Vikram Aggarwal5fd8afd2013-03-13 15:28:47 -0700707 LogUtils.e(LOG_TAG, "AAC.changeAccount(null) called.");
Vikram Aggarwal472e5362012-11-05 14:17:23 -0800708 return;
709 }
Tony Mantler79b11562013-10-09 15:31:50 -0700710 final String emailAddress = account.getEmailAddress();
Vikram Aggarwal472e5362012-11-05 14:17:23 -0800711 mHandler.post(new Runnable() {
712 @Override
713 public void run() {
Tony Mantler79b11562013-10-09 15:31:50 -0700714 MailActivity.setNfcMessage(emailAddress);
Mindy Pereirafa20c1a2012-07-23 13:00:02 -0700715 }
Vikram Aggarwal472e5362012-11-05 14:17:23 -0800716 });
717 if (accountChanged) {
718 commitDestructiveActions(false);
719 }
Andy Huang761522c2013-08-08 13:09:11 -0700720 Analytics.getInstance().setCustomDimension(Analytics.CD_INDEX_ACCOUNT_TYPE,
Tony Mantler79b11562013-10-09 15:31:50 -0700721 AnalyticsUtils.getAccountTypeForAccount(emailAddress));
Vikram Aggarwal472e5362012-11-05 14:17:23 -0800722 // Change the account here
723 setAccount(account);
724 // And carry out associated actions.
725 cancelRefreshTask();
726 if (accountChanged) {
727 loadAccountInbox();
728 }
729 // Check if we need to force setting up an account before proceeding.
730 if (mAccount != null && !Uri.EMPTY.equals(mAccount.settings.setupIntentUri)) {
731 // Launch the intent!
732 final Intent intent = new Intent(Intent.ACTION_EDIT);
733 intent.setData(mAccount.settings.setupIntentUri);
734 mActivity.startActivity(intent);
Mindy Pereira28d5f722012-02-15 12:32:40 -0800735 }
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -0800736 }
737
Vikram Aggarwale6340bc2012-03-26 15:57:09 -0700738 /**
Vikram Aggarwal7c401b72012-08-13 16:43:47 -0700739 * Adds a listener interested in change in the current account. If a class is storing a
740 * reference to the current account, it should listen on changes, so it can receive updates to
741 * settings. Must happen in the UI thread.
742 */
Mindy Pereiraefe3d252012-03-01 14:20:44 -0800743 @Override
Vikram Aggarwal7c401b72012-08-13 16:43:47 -0700744 public void registerAccountObserver(DataSetObserver obs) {
745 mAccountObservers.registerObserver(obs);
Mindy Pereiraefe3d252012-03-01 14:20:44 -0800746 }
747
Vikram Aggarwal7d816002012-04-17 17:06:41 -0700748 /**
Vikram Aggarwal7c401b72012-08-13 16:43:47 -0700749 * Removes a listener from receiving current account changes.
Vikram Aggarwal7d816002012-04-17 17:06:41 -0700750 * Must happen in the UI thread.
751 */
Vikram Aggarwal7c401b72012-08-13 16:43:47 -0700752 @Override
753 public void unregisterAccountObserver(DataSetObserver obs) {
754 mAccountObservers.unregisterObserver(obs);
Vikram Aggarwal7d816002012-04-17 17:06:41 -0700755 }
756
Vikram Aggarwal7c401b72012-08-13 16:43:47 -0700757 @Override
Vikram Aggarwal07dbaa62013-03-12 15:21:04 -0700758 public void registerAllAccountObserver(DataSetObserver observer) {
759 mAllAccountObservers.registerObserver(observer);
760 }
761
762 @Override
763 public void unregisterAllAccountObserver(DataSetObserver observer) {
764 mAllAccountObservers.unregisterObserver(observer);
765 }
766
767 @Override
768 public Account[] getAllAccounts() {
769 return mAllAccounts;
770 }
771
772 @Override
Vikram Aggarwal7c401b72012-08-13 16:43:47 -0700773 public Account getAccount() {
774 return mAccount;
Vikram Aggarwal7d816002012-04-17 17:06:41 -0700775 }
776
Rohan Shah0f73d902013-04-19 17:06:37 -0700777 @Override
778 public void registerDrawerClosedObserver(final DataSetObserver observer) {
779 mDrawerObservers.registerObserver(observer);
780 }
781
782 @Override
783 public void unregisterDrawerClosedObserver(final DataSetObserver observer) {
784 mDrawerObservers.unregisterObserver(observer);
785 }
786
787 /**
Andy Huang12b3ee42013-04-24 22:49:43 -0700788 * If the drawer is open, the function locks the drawer to the closed, thereby sliding in
789 * the drawer to the left edge, disabling events, and refreshing it once it's either closed
790 * or put in an idle state.
Rohan Shah0f73d902013-04-19 17:06:37 -0700791 */
792 @Override
Vikram Aggarwala1b59dc2013-04-30 15:45:49 -0700793 public void closeDrawer(final boolean hasNewFolderOrAccount, Account nextAccount,
794 Folder nextFolder) {
Andy Huang12b3ee42013-04-24 22:49:43 -0700795 if (!isDrawerEnabled()) {
796 mDrawerObservers.notifyChanged();
797 return;
798 }
Andy Huang12b3ee42013-04-24 22:49:43 -0700799 // If there are no new folders or accounts to switch to, just close the drawer
800 if (!hasNewFolderOrAccount) {
801 mDrawerContainer.closeDrawers();
802 return;
803 }
Vikram Aggarwal2f9d3942013-05-03 12:31:39 -0700804 // Otherwise, start preloading the conversation list for the new folder.
805 if (nextFolder != null) {
806 preloadConvList(nextAccount, nextFolder);
807 }
808 // Remember if the conversation list view is animating
Andy Huang12b3ee42013-04-24 22:49:43 -0700809 final ConversationListFragment conversationList = getConversationListFragment();
810 if (conversationList != null) {
811 mListViewForAnimating = conversationList.getListView();
812 } else {
813 // There is no conversation list to animate, so just set it to null
814 mListViewForAnimating = null;
815 }
816
817 if (mDrawerContainer.isDrawerOpen(mDrawerPullout)) {
818 // Lets the drawer listener update the drawer contents and notify the FolderListFragment
819 mHasNewAccountOrFolder = true;
820 mDrawerContainer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
821 } else {
822 // Drawer is already closed, notify observers that is the case.
823 mDrawerObservers.notifyChanged();
824 }
Rohan Shah0f73d902013-04-19 17:06:37 -0700825 }
826
Vikram Aggarwala1b59dc2013-04-30 15:45:49 -0700827 /**
Vikram Aggarwalaa941d72013-06-04 15:34:28 -0700828 * Load the conversation list early for the given folder. This happens when some UI element
829 * (usually the drawer) instructs the controller that an account change or folder change is
830 * imminent. While the UI element is animating, the controller can preload the conversation
831 * list for the default inbox of the account provided here or to the folder provided here.
832 *
833 * @param nextAccount The account which the app will switch to shortly, possibly null.
834 * @param nextFolder The folder which the app will switch to shortly, possibly null.
Vikram Aggarwala1b59dc2013-04-30 15:45:49 -0700835 */
836 protected void preloadConvList(Account nextAccount, Folder nextFolder) {
837 // Fire off the conversation list loader for this account already with a fake
838 // listener.
Paul Westbrooke2be97a2013-05-21 02:12:09 -0700839 final Bundle args = new Bundle(2);
Vikram Aggarwala1b59dc2013-04-30 15:45:49 -0700840 if (nextAccount != null) {
841 args.putParcelable(BUNDLE_ACCOUNT_KEY, nextAccount);
842 } else {
843 args.putParcelable(BUNDLE_ACCOUNT_KEY, mAccount);
844 }
845 if (nextFolder != null) {
846 args.putParcelable(BUNDLE_FOLDER_KEY, nextFolder);
Vikram Aggarwal2dc85042013-05-01 13:57:09 -0700847 } else {
848 LogUtils.e(LOG_TAG, new Error(), "AAC.preloadConvList(): Got an empty folder");
Vikram Aggarwala1b59dc2013-04-30 15:45:49 -0700849 }
850 mFolder = null;
851 final LoaderManager lm = mActivity.getLoaderManager();
852 lm.destroyLoader(LOADER_CONVERSATION_LIST);
853 lm.initLoader(LOADER_CONVERSATION_LIST, args, mListCursorCallbacks);
854 }
855
Vikram Aggarwalaa941d72013-06-04 15:34:28 -0700856 /**
857 * Initiates the async request to create a fake search folder, which returns conversations that
858 * match the query term provided by the user. Returns immediately.
859 * @param intent Intent that the app was started with. This intent contains the search query.
860 */
Mindy Pereirae0828392012-03-08 10:38:40 -0800861 private void fetchSearchFolder(Intent intent) {
Paul Westbrooke2be97a2013-05-21 02:12:09 -0700862 final Bundle args = new Bundle(1);
Mindy Pereiraab486362012-03-21 18:18:53 -0700863 args.putString(ConversationListContext.EXTRA_SEARCH_QUERY, intent
Mindy Pereirae0828392012-03-08 10:38:40 -0800864 .getStringExtra(ConversationListContext.EXTRA_SEARCH_QUERY));
Vikram Aggarwal177097f2013-03-08 11:19:53 -0800865 mActivity.getLoaderManager().restartLoader(LOADER_SEARCH, args, mFolderCallbacks);
Mindy Pereirae0828392012-03-08 10:38:40 -0800866 }
867
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -0800868 @Override
Alice Yangebeef1b2013-09-04 06:41:10 +0000869 public void onFolderChanged(Folder folder, final boolean force) {
Vikram Aggarwaldfbc6982013-07-03 14:39:31 -0700870 /** If the folder doesn't exist, or its parent URI is empty,
871 * this is not a child folder */
872 final boolean isTopLevel = (folder == null) || (folder.parent == Uri.EMPTY);
873 final int mode = mViewMode.getMode();
874 mDrawerToggle.setDrawerIndicatorEnabled(
875 getShouldShowDrawerIndicator(mode, isTopLevel));
Martin Hibdon371a71c2014-02-19 13:55:28 -0800876 mDrawerContainer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
Vikram Aggarwaldfbc6982013-07-03 14:39:31 -0700877
Andy Huang12b3ee42013-04-24 22:49:43 -0700878 mDrawerContainer.closeDrawers();
Alice Yang7dd0e1c2013-09-04 06:43:16 +0000879
880 if (mFolder == null || !mFolder.equals(folder)) {
881 // We are actually changing the folder, so exit cab mode
882 exitCabMode();
883 }
884
Scott Kennedya158ac82013-09-04 13:48:13 -0700885 final String query;
886 if (folder != null && folder.isType(FolderType.SEARCH)) {
887 query = mConvListContext.searchQuery;
888 } else {
889 query = null;
890 }
891
892 changeFolder(folder, query, force);
Vikram Aggarwalf3341402012-08-07 10:09:38 -0700893 }
894
895 /**
Vikram Aggarwal203dc002012-08-23 13:59:04 -0700896 * Sets the folder state without changing view mode and without creating a list fragment, if
897 * possible.
Vikram Aggarwal715f83d2013-03-05 17:04:56 -0800898 * @param folder the folder whose list of conversations are to be shown
899 * @param query the query string for a list of conversations matching a search
Vikram Aggarwal203dc002012-08-23 13:59:04 -0700900 */
901 private void setListContext(Folder folder, String query) {
902 updateFolder(folder);
903 if (query != null) {
904 mConvListContext = ConversationListContext.forSearchQuery(mAccount, mFolder, query);
905 } else {
906 mConvListContext = ConversationListContext.forFolder(mAccount, mFolder);
907 }
Vikram Aggarwal203dc002012-08-23 13:59:04 -0700908 cancelRefreshTask();
909 }
910
911 /**
Vikram Aggarwalf3341402012-08-07 10:09:38 -0700912 * Changes the folder to the value provided here. This causes the view mode to change.
913 * @param folder the folder to change to
914 * @param query if non-null, this represents the search string that the folder represents.
Alice Yangebeef1b2013-09-04 06:41:10 +0000915 * @param force <code>true</code> to force a folder change, <code>false</code> to disallow
916 * changing to the current folder
Vikram Aggarwalf3341402012-08-07 10:09:38 -0700917 */
Alice Yangebeef1b2013-09-04 06:41:10 +0000918 private void changeFolder(Folder folder, String query, final boolean force) {
Vikram Aggarwal203dc002012-08-23 13:59:04 -0700919 if (!Objects.equal(mFolder, folder)) {
920 commitDestructiveActions(false);
921 }
Alice Yangebeef1b2013-09-04 06:41:10 +0000922 if (folder != null && (!folder.equals(mFolder) || force)
Mindy Pereiraa1f99982012-07-16 16:32:15 -0700923 || (mViewMode.getMode() != ViewMode.CONVERSATION_LIST)) {
Vikram Aggarwal203dc002012-08-23 13:59:04 -0700924 setListContext(folder, query);
Mindy Pereira28e0c342012-02-17 15:05:13 -0800925 showConversationList(mConvListContext);
Vikram Aggarwal58ccd692013-03-28 11:29:22 -0700926 // Touch the current folder: it is different, and it has been accessed.
927 mRecentFolderList.touchFolder(mFolder, mAccount);
Mindy Pereira28e0c342012-02-17 15:05:13 -0800928 }
Vikram Aggarwal93dc2022012-11-05 13:36:57 -0800929 resetActionBarIcon();
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -0800930 }
931
Mindy Pereira13c12a62012-05-31 15:41:08 -0700932 @Override
Mindy Pereira505df5f2012-06-19 17:57:17 -0700933 public void onFolderSelected(Folder folder) {
Alice Yangebeef1b2013-09-04 06:41:10 +0000934 onFolderChanged(folder, false /* force */);
Mindy Pereira13c12a62012-05-31 15:41:08 -0700935 }
936
Vikram Aggarwal792ccba2012-03-27 13:46:57 -0700937 /**
Vikram Aggarwal58cad2e2012-08-28 16:18:23 -0700938 * Adds a listener interested in change in the recent folders. If a class is storing a
939 * reference to the recent folders, it should listen on changes, so it can receive updates.
940 * Must happen in the UI thread.
941 */
942 @Override
943 public void registerRecentFolderObserver(DataSetObserver obs) {
944 mRecentFolderObservers.registerObserver(obs);
945 }
946
947 /**
948 * Removes a listener from receiving recent folder changes.
949 * Must happen in the UI thread.
950 */
951 @Override
952 public void unregisterRecentFolderObserver(DataSetObserver obs) {
953 mRecentFolderObservers.unregisterObserver(obs);
954 }
955
956 @Override
957 public RecentFolderList getRecentFolders() {
958 return mRecentFolderList;
959 }
960
Vikram Aggarwaleb7d3292012-04-20 17:07:20 -0700961 @Override
962 public void loadAccountInbox() {
Vikram Aggarwal77ee0ce2013-04-28 15:32:36 -0700963 boolean handled = false;
964 if (mFolderWatcher != null) {
965 final Folder inbox = mFolderWatcher.getDefaultInbox(mAccount);
966 if (inbox != null) {
Alice Yangebeef1b2013-09-04 06:41:10 +0000967 onFolderChanged(inbox, false /* force */);
Vikram Aggarwal77ee0ce2013-04-28 15:32:36 -0700968 handled = true;
969 }
970 }
971 if (!handled) {
Paul Westbrook1bf20e02014-02-26 12:48:54 -0800972 LogUtils.d(LOG_TAG, "Starting a LOADER_ACCOUNT_INBOX for %s", mAccount);
Vikram Aggarwal77ee0ce2013-04-28 15:32:36 -0700973 restartOptionalLoader(LOADER_ACCOUNT_INBOX, mFolderCallbacks, Bundle.EMPTY);
974 }
Vikram Aggarwal8cbf2812013-04-11 17:23:45 -0700975 final int mode = mViewMode.getMode();
976 if (mode == ViewMode.UNKNOWN || mode == ViewMode.WAITING_FOR_ACCOUNT_INITIALIZATION) {
Andy Huange6459422013-04-01 16:32:18 -0700977 mViewMode.enterConversationListMode();
978 }
Mindy Pereiraf6acdad2012-03-15 11:21:13 -0700979 }
980
Vikram Aggarwal77ee0ce2013-04-28 15:32:36 -0700981 @Override
982 public void setFolderWatcher(FolderWatcher watcher) {
983 mFolderWatcher = watcher;
984 }
985
Vikram Aggarwal69b5c302012-09-05 11:11:13 -0700986 /**
Vikram Aggarwald00229d2012-09-20 12:31:44 -0700987 * Marks the {@link #mFolderChanged} value if the newFolder is different from the existing
988 * {@link #mFolder}. This should be called immediately <b>before</b> assigning newFolder to
989 * mFolder.
Vikram Aggarwal715f83d2013-03-05 17:04:56 -0800990 * @param newFolder the new folder we are switching to.
Vikram Aggarwald00229d2012-09-20 12:31:44 -0700991 */
Vikram Aggarwal715f83d2013-03-05 17:04:56 -0800992 private void setHasFolderChanged(final Folder newFolder) {
Vikram Aggarwald00229d2012-09-20 12:31:44 -0700993 // We should never try to assign a null folder. But in the rare event that we do, we should
994 // only set the bit when we have a valid folder, and null is not valid.
995 if (newFolder == null) {
996 return;
997 }
998 // If the previous folder was null, or if the two folders represent different data, then we
999 // consider that the folder has changed.
Scott Kennedy259df5b2013-07-11 13:24:01 -07001000 if (mFolder == null || !newFolder.equals(mFolder)) {
Vikram Aggarwald00229d2012-09-20 12:31:44 -07001001 mFolderChanged = true;
1002 }
1003 }
1004
1005 /**
Vikram Aggarwal69b5c302012-09-05 11:11:13 -07001006 * Sets the current folder if it is different from the object provided here. This method does
1007 * NOT notify the folder observers that a change has happened. Observers are notified when we
1008 * get an updated folder from the loaders, which will happen as a consequence of this method
1009 * (since this method starts/restarts the loaders).
1010 * @param folder The folder to assign
1011 */
Mindy Pereira11e35962012-06-01 14:49:46 -07001012 private void updateFolder(Folder folder) {
Vikram Aggarwal1672ff82012-09-21 10:15:22 -07001013 if (folder == null || !folder.isInitialized()) {
1014 LogUtils.e(LOG_TAG, new Error(), "AAC.setFolder(%s): Bad input", folder);
1015 return;
1016 }
1017 if (folder.equals(mFolder)) {
1018 LogUtils.d(LOG_TAG, "AAC.setFolder(%s): Input matches mFolder", folder);
1019 return;
1020 }
1021 final boolean wasNull = mFolder == null;
1022 LogUtils.d(LOG_TAG, "AbstractActivityController.setFolder(%s)", folder.name);
1023 final LoaderManager lm = mActivity.getLoaderManager();
1024 // updateFolder is called from AAC.onLoadFinished() on folder changes. We need to
1025 // ensure that the folder is different from the previous folder before marking the
1026 // folder changed.
1027 setHasFolderChanged(folder);
1028 mFolder = folder;
Vikram Aggarwal69b5c302012-09-05 11:11:13 -07001029
Vikram Aggarwal1672ff82012-09-21 10:15:22 -07001030 // We do not need to notify folder observers yet. Instead we start the loaders and
1031 // when the load finishes, we will get an updated folder. Then, we notify the
1032 // folderObservers in onLoadFinished.
1033 mActionBarView.setFolder(mFolder);
Andy Huangb1c34dc2012-04-17 16:36:19 -07001034
Vikram Aggarwal1672ff82012-09-21 10:15:22 -07001035 // Only when we switch from one folder to another do we want to restart the
1036 // folder and conversation list loaders (to trigger onCreateLoader).
1037 // The first time this runs when the activity is [re-]initialized, we want to re-use the
1038 // previous loader's instance and data upon configuration change (e.g. rotation).
1039 // If there was not already an instance of the loader, init it.
1040 if (lm.getLoader(LOADER_FOLDER_CURSOR) == null) {
Vikram Aggarwal177097f2013-03-08 11:19:53 -08001041 lm.initLoader(LOADER_FOLDER_CURSOR, Bundle.EMPTY, mFolderCallbacks);
Vikram Aggarwal1672ff82012-09-21 10:15:22 -07001042 } else {
Vikram Aggarwal177097f2013-03-08 11:19:53 -08001043 lm.restartLoader(LOADER_FOLDER_CURSOR, Bundle.EMPTY, mFolderCallbacks);
Vikram Aggarwal1672ff82012-09-21 10:15:22 -07001044 }
Vikram Aggarwala1b59dc2013-04-30 15:45:49 -07001045 if (!wasNull && lm.getLoader(LOADER_CONVERSATION_LIST) != null) {
1046 // If there was an existing folder AND we have changed
Vikram Aggarwal1672ff82012-09-21 10:15:22 -07001047 // folders, we want to restart the loader to get the information
1048 // for the newly selected folder
1049 lm.destroyLoader(LOADER_CONVERSATION_LIST);
Mindy Pereira5cb0c3e2012-02-22 15:22:47 -08001050 }
Paul Westbrooke2be97a2013-05-21 02:12:09 -07001051 final Bundle args = new Bundle(2);
Vikram Aggarwal2dc85042013-05-01 13:57:09 -07001052 args.putParcelable(BUNDLE_ACCOUNT_KEY, mAccount);
Vikram Aggarwala1b59dc2013-04-30 15:45:49 -07001053 args.putParcelable(BUNDLE_FOLDER_KEY, mFolder);
Andrew Sapperstein5bb4d052014-03-31 16:22:31 -07001054 args.putBoolean(BUNDLE_IGNORE_INITIAL_CONVERSATION_LIMIT_KEY,
1055 mIgnoreInitialConversationLimit);
1056 mIgnoreInitialConversationLimit = false;
Vikram Aggarwala1b59dc2013-04-30 15:45:49 -07001057 lm.initLoader(LOADER_CONVERSATION_LIST, args, mListCursorCallbacks);
Mindy Pereira5cb0c3e2012-02-22 15:22:47 -08001058 }
1059
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08001060 @Override
Andy Huang090db1e2012-07-25 13:25:28 -07001061 public Folder getFolder() {
1062 return mFolder;
1063 }
1064
1065 @Override
Mindy Pereirac975e842012-07-16 09:15:00 -07001066 public Folder getHierarchyFolder() {
1067 return mFolderListFolder;
1068 }
1069
1070 @Override
1071 public void setHierarchyFolder(Folder folder) {
1072 mFolderListFolder = folder;
Mindy Pereira23aadfd2012-05-25 11:24:33 -07001073 }
1074
Vikram Aggarwal6aca6892013-06-04 13:53:27 -07001075 /**
1076 * The mail activity calls other activities for two specific reasons:
1077 * <ul>
1078 * <li>To add an account. And receives the result {@link #ADD_ACCOUNT_REQUEST_CODE}</li>
1079 * <li>To update the password on a current account. The result {@link
1080 * #REAUTHENTICATE_REQUEST_CODE} is received.</li>
1081 * </ul>
1082 * @param requestCode
1083 * @param resultCode
1084 * @param data
1085 */
Mindy Pereira23aadfd2012-05-25 11:24:33 -07001086 @Override
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08001087 public void onActivityResult(int requestCode, int resultCode, Intent data) {
Paul Westbrook122f7c22012-08-20 17:50:31 -07001088 switch (requestCode) {
1089 case ADD_ACCOUNT_REQUEST_CODE:
1090 // We were waiting for the user to create an account
1091 if (resultCode == Activity.RESULT_OK) {
1092 // restart the loader to get the updated list of accounts
Vikram Aggarwal177097f2013-03-08 11:19:53 -08001093 mActivity.getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, Bundle.EMPTY,
1094 mAccountCallbacks);
Paul Westbrook122f7c22012-08-20 17:50:31 -07001095 } else {
1096 // The user failed to create an account, just exit the app
1097 mActivity.finish();
1098 }
1099 break;
1100 case REAUTHENTICATE_REQUEST_CODE:
1101 if (resultCode == Activity.RESULT_OK) {
1102 // The user successfully authenticated, attempt to refresh the list
1103 final Uri refreshUri = mFolder != null ? mFolder.refreshUri : null;
1104 if (refreshUri != null) {
1105 startAsyncRefreshTask(refreshUri);
1106 }
1107 }
1108 break;
Martin Hibdon371a71c2014-02-19 13:55:28 -08001109 case CHANGE_NAVIGATION_REQUEST_CODE:
1110 if (resultCode == Activity.RESULT_OK && data != null) {
1111 // We have have received a result that indicates we need to navigate to a
1112 // different folder or account. This happens if someone navigates using the
1113 // drawer on the search results activity.
1114 final Folder folder = data.getParcelableExtra(EXTRA_FOLDER);
1115 final Account account = data.getParcelableExtra(EXTRA_ACCOUNT);
1116 if (folder != null) {
1117 onFolderSelected(folder);
1118 mViewMode.enterConversationListMode();
1119 } else if (account != null) {
1120 switchToDefaultInboxOrChangeAccount(account);
1121 mViewMode.enterConversationListMode();
1122 }
1123 }
1124 break;
Paul Westbrook2388c5d2012-03-25 12:29:11 -07001125 }
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08001126 }
1127
Vikram Aggarwal69b5c302012-09-05 11:11:13 -07001128 /**
1129 * Inform the conversation cursor that there has been a visibility change.
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08001130 * @param visible true if the conversation list is visible, false otherwise.
Vikram Aggarwal69b5c302012-09-05 11:11:13 -07001131 */
1132 protected synchronized void informCursorVisiblity(boolean visible) {
1133 if (mConversationListCursor != null) {
1134 Utils.setConversationCursorVisibility(mConversationListCursor, visible, mFolderChanged);
1135 // We have informed the cursor. Subsequent visibility changes should not tell it that
1136 // the folder has changed.
1137 mFolderChanged = false;
1138 }
1139 }
1140
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08001141 @Override
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08001142 public void onConversationListVisibilityChanged(boolean visible) {
Vikram Aggarwal69b5c302012-09-05 11:11:13 -07001143 informCursorVisiblity(visible);
Andy Huangc94d07f2013-06-03 16:19:35 -07001144 commitAutoAdvanceOperation();
Scott Kennedy32ddb842013-08-28 17:38:22 -07001145
1146 // Notify special views
1147 final ConversationListFragment convListFragment = getConversationListFragment();
1148 if (convListFragment != null && convListFragment.getAnimatedAdapter() != null) {
1149 convListFragment.getAnimatedAdapter().onConversationListVisibilityChanged(visible);
1150 }
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08001151 }
1152
Vikram Aggarwal4a5c5302012-01-12 15:07:13 -08001153 /**
Vikram Aggarwal7dd054e2012-05-21 14:43:10 -07001154 * Called when a conversation is visible. Child classes must call the super class implementation
1155 * before performing local computation.
Vikram Aggarwal4a5c5302012-01-12 15:07:13 -08001156 */
1157 @Override
1158 public void onConversationVisibilityChanged(boolean visible) {
Andy Huangc94d07f2013-06-03 16:19:35 -07001159 commitAutoAdvanceOperation();
1160 }
1161
1162 /**
1163 * Commits any pending destructive action that was earlier deferred by an auto-advance
1164 * mode-change transition.
1165 */
1166 private void commitAutoAdvanceOperation() {
1167 if (mAutoAdvanceOp != null) {
1168 mAutoAdvanceOp.run();
1169 mAutoAdvanceOp = null;
1170 }
Vikram Aggarwal4a5c5302012-01-12 15:07:13 -08001171 }
1172
Vikram Aggarwal59f741f2013-03-01 15:55:40 -08001173 /**
1174 * Initialize development time logging. This can potentially log a lot of PII, and we don't want
1175 * to turn it on for shipped versions.
1176 */
1177 private void initializeDevLoggingService() {
1178 if (!MailLogService.DEBUG_ENABLED) {
1179 return;
1180 }
1181 // Check every 5 minutes.
1182 final int WAIT_TIME = 5 * 60 * 1000;
1183 // Start a runnable that periodically checks the log level and starts/stops the service.
1184 mLogServiceChecker = new Runnable() {
1185 /** True if currently logging. */
1186 private boolean mCurrentlyLogging = false;
1187
1188 /**
1189 * If the logging level has been changed since the previous run, start or stop the
1190 * service.
1191 */
1192 private void startOrStopService() {
1193 // If the log level is already high, start the service.
1194 final Intent i = new Intent(mContext, MailLogService.class);
1195 final boolean loggingEnabled = MailLogService.isLoggingLevelHighEnough();
1196 if (mCurrentlyLogging == loggingEnabled) {
1197 // No change since previous run, just return;
1198 return;
1199 }
1200 if (loggingEnabled) {
1201 LogUtils.e(LOG_TAG, "Starting MailLogService");
1202 mContext.startService(i);
1203 } else {
1204 LogUtils.e(LOG_TAG, "Stopping MailLogService");
1205 mContext.stopService(i);
1206 }
1207 mCurrentlyLogging = loggingEnabled;
1208 }
1209
1210 @Override
1211 public void run() {
1212 startOrStopService();
1213 mHandler.postDelayed(this, WAIT_TIME);
1214 }
1215 };
1216 // Start the runnable right away.
1217 mHandler.post(mLogServiceChecker);
1218 }
1219
Vikram Aggarwal6aca6892013-06-04 13:53:27 -07001220 /**
1221 * The application can be started from the following entry points:
1222 * <ul>
1223 * <li>Launcher: you tap on the Gmail icon in the launcher. This is what most users think of
1224 * as “Starting the app”.</li>
1225 * <li>Shortcut: Users can make a shortcut to take them directly to a label.</li>
1226 * <li>Widget: Shows the contents of a synced label, and allows:
1227 * <ul>
1228 * <li>Viewing the list (tapping on the title)</li>
1229 * <li>Composing a new message (tapping on the new message icon in the title. This
1230 * launches the {@link ComposeActivity}.
1231 * </li>
1232 * <li>Viewing a single message (tapping on a list element)</li>
1233 * </ul>
1234 *
1235 * </li>
1236 * <li>Tapping on a notification:
1237 * <ul>
1238 * <li>Shows message list if more than one message</li>
1239 * <li>Shows the conversation if the notification is for a single message</li>
1240 * </ul>
1241 * </li>
1242 * <li>...and most importantly, the activity life cycle can tear down the application and
1243 * restart it:
1244 * <ul>
1245 * <li>Rotate the application: it is destroyed and recreated.</li>
1246 * <li>Navigate away, and return from recent applications.</li>
1247 * </ul>
1248 * </li>
1249 * <li>Add a new account: fires off an intent to add an account,
1250 * and returns in {@link #onActivityResult(int, int, android.content.Intent)} .</li>
1251 * <li>Re-authenticate your account: again returns in onActivityResult().</li>
1252 * <li>Composing can happen from many entry points: third party applications fire off an
1253 * intent to compose email, and launch directly into the {@link ComposeActivity}
1254 * .</li>
1255 * </ul>
1256 * {@inheritDoc}
1257 */
Vikram Aggarwal4a5c5302012-01-12 15:07:13 -08001258 @Override
Vikram Aggarwald7a12cd2012-02-03 09:36:20 -08001259 public boolean onCreate(Bundle savedState) {
Vikram Aggarwalabd24d82012-04-26 13:23:14 -07001260 initializeActionBar();
Vikram Aggarwal59f741f2013-03-01 15:55:40 -08001261 initializeDevLoggingService();
Vikram Aggarwala55b36c2012-01-13 11:45:02 -08001262 // Allow shortcut keys to function for the ActionBar and menus.
1263 mActivity.setDefaultKeyMode(Activity.DEFAULT_KEYS_SHORTCUT);
Vikram Aggarwal80aeac52012-02-07 15:27:20 -08001264 mResolver = mActivity.getContentResolver();
Paul Westbrook6ead20d2012-03-19 14:48:14 -07001265 mNewEmailReceiver = new SuppressNotificationReceiver();
Vikram Aggarwal7c401b72012-08-13 16:43:47 -07001266 mRecentFolderList.initialize(mActivity);
Vikram Aggarwal69a6cdf2013-01-08 16:05:17 -08001267 mVeiledMatcher.initialize(this);
Paul Westbrook6ead20d2012-03-19 14:48:14 -07001268
Andy Huang12b3ee42013-04-24 22:49:43 -07001269 mDrawerToggle = new ActionBarDrawerToggle((Activity) mActivity, mDrawerContainer,
Tony Mantlera9a9b9f2014-01-13 19:29:07 +00001270 R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close);
Andrew Sappersteina3ce6782013-05-09 15:14:49 -07001271 mDrawerContainer.setDrawerListener(mDrawerListener);
Andy Huang12b3ee42013-04-24 22:49:43 -07001272 mDrawerContainer.setDrawerShadow(
1273 mContext.getResources().getDrawable(R.drawable.drawer_shadow), Gravity.START);
1274
1275 mDrawerToggle.setDrawerIndicatorEnabled(isDrawerEnabled());
1276
Mindy Pereira161f50d2012-02-28 15:47:19 -08001277 // All the individual UI components listen for ViewMode changes. This
Mindy Pereirab849dfb2012-03-07 18:13:15 -08001278 // simplifies the amount of logic in the AbstractActivityController, but increases the
1279 // possibility of timing-related bugs.
Vikram Aggarwala55b36c2012-01-13 11:45:02 -08001280 mViewMode.addListener(this);
Andy Huang632721e2012-04-11 16:57:26 -07001281 mPagerController = new ConversationPagerController(mActivity, this);
Andrew Sappersteinc2c9dc12012-07-02 18:17:32 -07001282 mToastBar = (ActionableToastBar) mActivity.findViewById(R.id.toast_bar);
Vikram Aggarwalada51782012-04-26 14:18:31 -07001283 attachActionBar();
Andy Huang632721e2012-04-11 16:57:26 -07001284
Andy Huang144bfe72013-06-11 13:27:52 -07001285 mDrawIdler.setRootView(mActivity.getWindow().getDecorView());
1286
Andy Huang632721e2012-04-11 16:57:26 -07001287 final Intent intent = mActivity.getIntent();
Andy Huang4fe0af82013-08-20 17:24:51 -07001288
Vikram Aggarwalabd24d82012-04-26 13:23:14 -07001289 // Immediately handle a clean launch with intent, and any state restoration
Andy Huang632721e2012-04-11 16:57:26 -07001290 // that does not rely on restored fragments or loader data
1291 // any state restoration that relies on those can be done later in
1292 // onRestoreInstanceState, once fragments are up and loader data is re-delivered
1293 if (savedState != null) {
1294 if (savedState.containsKey(SAVED_ACCOUNT)) {
1295 setAccount((Account) savedState.getParcelable(SAVED_ACCOUNT));
Andy Huang632721e2012-04-11 16:57:26 -07001296 }
1297 if (savedState.containsKey(SAVED_FOLDER)) {
Andy Huang2bc8bc12012-11-12 17:24:25 -08001298 final Folder folder = savedState.getParcelable(SAVED_FOLDER);
Vikram Aggarwal203dc002012-08-23 13:59:04 -07001299 final String query = savedState.getString(SAVED_QUERY, null);
Vikram Aggarwal649b9ea2012-08-27 12:15:20 -07001300 setListContext(folder, query);
Andy Huang632721e2012-04-11 16:57:26 -07001301 }
Vikram Aggarwal6cadbfc2012-12-27 09:17:05 -08001302 if (savedState.containsKey(SAVED_ACTION)) {
1303 mDialogAction = savedState.getInt(SAVED_ACTION);
1304 }
Vikram Aggarwala91d00b2013-01-18 12:00:37 -08001305 mDialogFromSelectedSet = savedState.getBoolean(SAVED_ACTION_FROM_SELECTED, false);
Vikram Aggarwal649b9ea2012-08-27 12:15:20 -07001306 mViewMode.handleRestore(savedState);
Andy Huang632721e2012-04-11 16:57:26 -07001307 } else if (intent != null) {
1308 handleIntent(intent);
1309 }
Andy Huang632721e2012-04-11 16:57:26 -07001310 // Create the accounts loader; this loads the account switch spinner.
Vikram Aggarwal177097f2013-03-08 11:19:53 -08001311 mActivity.getLoaderManager().initLoader(LOADER_ACCOUNT_CURSOR, Bundle.EMPTY,
1312 mAccountCallbacks);
Andy Huang632721e2012-04-11 16:57:26 -07001313 return true;
Andy Huangb1c34dc2012-04-17 16:36:19 -07001314 }
1315
1316 @Override
Paul Westbrook57246a42013-04-21 09:40:22 -07001317 public void onPostCreate(Bundle savedState) {
Andy Huang12b3ee42013-04-24 22:49:43 -07001318 // Sync the toggle state after onRestoreInstanceState has occurred.
1319 mDrawerToggle.syncState();
Andrew Sapperstein5747e152013-05-13 14:13:08 -07001320
Vikram Aggarwald70fe492013-06-04 12:52:07 -07001321 mHideMenuItems = isDrawerEnabled() && mDrawerContainer.isDrawerOpen(mDrawerPullout);
Paul Westbrook57246a42013-04-21 09:40:22 -07001322 }
1323
1324 @Override
1325 public void onConfigurationChanged(Configuration newConfig) {
Andy Huang12b3ee42013-04-24 22:49:43 -07001326 mDrawerToggle.onConfigurationChanged(newConfig);
1327 }
1328
1329 /**
1330 * If drawer is open/visible (even partially), close it.
1331 */
1332 protected void closeDrawerIfOpen() {
1333 if (!isDrawerEnabled()) {
1334 return;
1335 }
1336 if(mDrawerContainer.isDrawerOpen(mDrawerPullout)) {
1337 mDrawerContainer.closeDrawers();
1338 }
Paul Westbrook57246a42013-04-21 09:40:22 -07001339 }
1340
1341 @Override
Andy Huang1ee96b22012-08-24 20:19:53 -07001342 public void onStart() {
1343 mSafeToModifyFragments = true;
Scott Kennedycb85aea2013-02-25 13:08:32 -08001344
1345 NotificationActionUtils.registerUndoNotificationObserver(mUndoNotificationObserver);
Andy Huang761522c2013-08-08 13:09:11 -07001346
1347 if (mViewMode.getMode() != ViewMode.UNKNOWN) {
1348 Analytics.getInstance().sendView("MainActivity" + mViewMode.toString());
1349 }
Andy Huang1ee96b22012-08-24 20:19:53 -07001350 }
1351
1352 @Override
Andrew Sapperstein00179f12012-08-09 15:15:40 -07001353 public void onRestart() {
Vikram Aggarwal177097f2013-03-08 11:19:53 -08001354 final DialogFragment fragment = (DialogFragment)
Andrew Sapperstein00179f12012-08-09 15:15:40 -07001355 mFragmentManager.findFragmentByTag(SYNC_ERROR_DIALOG_FRAGMENT_TAG);
1356 if (fragment != null) {
1357 fragment.dismiss();
1358 }
mindypea04f932012-08-27 14:17:59 -07001359 // When the user places the app in the background by pressing "home",
1360 // dismiss the toast bar. However, since there is no way to determine if
1361 // home was pressed, just dismiss any existing toast bar when restarting
1362 // the app.
1363 if (mToastBar != null) {
Andrew Sappersteinf8ccdcf2013-08-08 19:30:38 -07001364 mToastBar.hide(false, false /* actionClicked */);
mindypea04f932012-08-27 14:17:59 -07001365 }
Andrew Sapperstein00179f12012-08-09 15:15:40 -07001366 }
1367
1368 @Override
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08001369 public Dialog onCreateDialog(int id, Bundle bundle) {
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08001370 return null;
Vikram Aggarwala55b36c2012-01-13 11:45:02 -08001371 }
1372
1373 @Override
Vikram Aggarwal4eb52712012-06-19 16:24:50 -07001374 public final boolean onCreateOptionsMenu(Menu menu) {
Andrew Sapperstein0fa9efd2013-08-07 14:09:31 -07001375 if (mViewMode.isAdMode()) {
1376 return false;
1377 }
Vikram Aggarwale5e917c2012-09-20 16:27:41 -07001378 final MenuInflater inflater = mActivity.getMenuInflater();
Mindy Pereiraf5acda42012-02-15 20:13:59 -08001379 inflater.inflate(mActionBarView.getOptionsMenuId(), menu);
Mindy Pereira68f2e222012-03-07 10:36:54 -08001380 mActionBarView.onCreateOptionsMenu(menu);
Mindy Pereira28d5f722012-02-15 12:32:40 -08001381 return true;
Vikram Aggarwala55b36c2012-01-13 11:45:02 -08001382 }
1383
1384 @Override
Vikram Aggarwal4eb52712012-06-19 16:24:50 -07001385 public final boolean onKeyDown(int keyCode, KeyEvent event) {
Vikram Aggarwalb9e1a352012-01-24 15:23:38 -08001386 return false;
1387 }
1388
mindyp17a8e782012-11-29 14:56:17 -08001389 public abstract boolean doesActionChangeConversationListVisibility(int action);
1390
Vikram Aggarwalb9e1a352012-01-24 15:23:38 -08001391 @Override
Paul Westbrook57246a42013-04-21 09:40:22 -07001392 public boolean onOptionsItemSelected(MenuItem item) {
Andy Huang761522c2013-08-08 13:09:11 -07001393
Andy Huang12b3ee42013-04-24 22:49:43 -07001394 /*
1395 * The action bar home/up action should open or close the drawer.
1396 * mDrawerToggle will take care of this.
1397 */
1398 if (mDrawerToggle.onOptionsItemSelected(item)) {
Andy Huang042a5302013-08-13 12:39:08 -07001399 Analytics.getInstance().sendEvent(Analytics.EVENT_CATEGORY_MENU_ITEM, "drawer_toggle",
1400 null, 0);
Andy Huang12b3ee42013-04-24 22:49:43 -07001401 return true;
1402 }
1403
Andy Huang2b555492013-08-14 21:06:21 -07001404 Analytics.getInstance().sendMenuItemEvent(Analytics.EVENT_CATEGORY_MENU_ITEM,
Andy Huangf8c59b02014-03-19 20:00:53 -07001405 item.getItemId(), "action_bar/" + mViewMode.getModeString(), 0);
Andy Huang042a5302013-08-13 12:39:08 -07001406
Vikram Aggarwal54452ae2012-03-13 15:29:00 -07001407 final int id = item.getItemId();
Vikram Aggarwal7dd054e2012-05-21 14:43:10 -07001408 LogUtils.d(LOG_TAG, "AbstractController.onOptionsItemSelected(%d) called.", id);
Mindy Pereira9b875682012-02-15 18:10:54 -08001409 boolean handled = true;
Vikram Aggarwal84fe9942013-04-17 11:20:58 -07001410 /** This is NOT a batch action. */
1411 final boolean isBatch = false;
Mindy Pereiraba68fda2012-05-24 15:53:06 -07001412 final Collection<Conversation> target = Conversation.listOf(mCurrentConversation);
Vikram Aggarwal112cd162012-06-18 10:51:13 -07001413 final Settings settings = (mAccount == null) ? null : mAccount.settings;
mindyp84f7d322012-10-01 17:14:40 -07001414 // The user is choosing a new action; commit whatever they had been
mindyp17a8e782012-11-29 14:56:17 -08001415 // doing before. Don't animate if we are launching a new screen.
1416 commitDestructiveActions(!doesActionChangeConversationListVisibility(id));
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07001417 if (id == R.id.archive) {
1418 final boolean showDialog = (settings != null && settings.confirmArchive);
1419 confirmAndDelete(id, target, showDialog, R.plurals.confirm_archive_conversation);
1420 } else if (id == R.id.remove_folder) {
1421 delete(R.id.remove_folder, target,
1422 getDeferredRemoveFolder(target, mFolder, true, isBatch, true), isBatch);
1423 } else if (id == R.id.delete) {
1424 final boolean showDialog = (settings != null && settings.confirmDelete);
1425 confirmAndDelete(id, target, showDialog, R.plurals.confirm_delete_conversation);
1426 } else if (id == R.id.discard_drafts) {
Andy Huang121c8b82013-08-05 11:52:55 -07001427 // drafts are lost forever, so always confirm
1428 confirmAndDelete(id, target, true /* showDialog */,
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07001429 R.plurals.confirm_discard_drafts_conversation);
1430 } else if (id == R.id.mark_important) {
1431 updateConversation(Conversation.listOf(mCurrentConversation),
1432 ConversationColumns.PRIORITY, UIProvider.ConversationPriority.HIGH);
1433 } else if (id == R.id.mark_not_important) {
1434 if (mFolder != null && mFolder.isImportantOnly()) {
1435 delete(R.id.mark_not_important, target,
1436 getDeferredAction(R.id.mark_not_important, target, isBatch), isBatch);
1437 } else {
Vikram Aggarwal531488e2012-05-29 16:36:52 -07001438 updateConversation(Conversation.listOf(mCurrentConversation),
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07001439 ConversationColumns.PRIORITY, UIProvider.ConversationPriority.LOW);
1440 }
1441 } else if (id == R.id.mute) {
1442 delete(R.id.mute, target, getDeferredAction(R.id.mute, target, isBatch), isBatch);
1443 } else if (id == R.id.report_spam) {
1444 delete(R.id.report_spam, target,
1445 getDeferredAction(R.id.report_spam, target, isBatch), isBatch);
1446 } else if (id == R.id.mark_not_spam) {
1447 // Currently, since spam messages are only shown in list with
1448 // other spam messages,
1449 // marking a message not as spam is a destructive action
1450 delete(R.id.mark_not_spam, target,
1451 getDeferredAction(R.id.mark_not_spam, target, isBatch), isBatch);
1452 } else if (id == R.id.report_phishing) {
1453 delete(R.id.report_phishing, target,
1454 getDeferredAction(R.id.report_phishing, target, isBatch), isBatch);
1455 } else if (id == android.R.id.home) {
1456 onUpPressed();
1457 } else if (id == R.id.compose) {
1458 ComposeActivity.compose(mActivity.getActivityContext(), mAccount);
1459 } else if (id == R.id.refresh) {
1460 requestFolderRefresh();
1461 } else if (id == R.id.settings) {
1462 Utils.showSettings(mActivity.getActivityContext(), mAccount);
1463 } else if (id == R.id.folder_options) {
1464 Utils.showFolderSettings(mActivity.getActivityContext(), mAccount, mFolder);
1465 } else if (id == R.id.help_info_menu_item) {
1466 Utils.showHelp(mActivity.getActivityContext(), mAccount, getHelpContext());
1467 } else if (id == R.id.feedback_menu_item) {
1468 Utils.sendFeedback(mActivity, mAccount, false);
1469 } else if (id == R.id.manage_folders_item) {
1470 Utils.showManageFolder(mActivity.getActivityContext(), mAccount);
Andrew Sapperstein6c570db2013-08-06 17:21:36 -07001471 } else if (id == R.id.move_to || id == R.id.change_folders) {
Tony Mantler2a4be242013-12-11 15:30:53 -08001472 final FolderSelectionDialog dialog = FolderSelectionDialog.getInstance(mAccount,
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07001473 Conversation.listOf(mCurrentConversation), isBatch, mFolder,
1474 id == R.id.move_to);
1475 if (dialog != null) {
Tony Mantler2a4be242013-12-11 15:30:53 -08001476 dialog.show(mActivity.getFragmentManager(), null);
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07001477 }
1478 } else if (id == R.id.move_to_inbox) {
1479 new AsyncTask<Void, Void, Folder>() {
1480 @Override
1481 protected Folder doInBackground(final Void... params) {
1482 // Get the "move to" inbox
1483 return Utils.getFolder(mContext, mAccount.settings.moveToInbox,
1484 true /* allowHidden */);
Mindy Pereira0d03ef82012-08-15 09:05:48 -07001485 }
Scott Kennedydd2ec682013-06-03 19:16:13 -07001486
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07001487 @Override
1488 protected void onPostExecute(final Folder moveToInbox) {
1489 final List<FolderOperation> ops = Lists.newArrayListWithCapacity(1);
1490 // Add inbox
1491 ops.add(new FolderOperation(moveToInbox, true));
1492 assignFolder(ops, Conversation.listOf(mCurrentConversation), true,
1493 true /* showUndo */, false /* isMoveTo */);
1494 }
1495 }.execute((Void[]) null);
1496 } else if (id == R.id.empty_trash) {
1497 showEmptyDialog();
1498 } else if (id == R.id.empty_spam) {
1499 showEmptyDialog();
1500 } else {
1501 handled = false;
Mindy Pereira28d5f722012-02-15 12:32:40 -08001502 }
Mindy Pereira9b875682012-02-15 18:10:54 -08001503 return handled;
Vikram Aggarwala55b36c2012-01-13 11:45:02 -08001504 }
1505
Andrew Sappersteined5b52d2013-04-30 13:40:18 -07001506 /**
1507 * Opens an {@link EmptyFolderDialogFragment} for the current folder.
1508 */
1509 private void showEmptyDialog() {
1510 if (mFolder != null) {
1511 final EmptyFolderDialogFragment fragment =
1512 EmptyFolderDialogFragment.newInstance(mFolder.totalCount, mFolder.type);
1513 fragment.setListener(this);
1514 fragment.show(mActivity.getFragmentManager(), EmptyFolderDialogFragment.FRAGMENT_TAG);
1515 }
1516 }
1517
1518 @Override
1519 public void onFolderEmptied() {
1520 emptyFolder();
1521 }
1522
1523 /**
1524 * Performs the work of emptying the currently visible folder.
1525 */
Scott Kennedy7ee089e2013-03-25 17:05:44 -04001526 private void emptyFolder() {
Yorke Lee1d0f1f82013-04-26 14:10:27 -07001527 if (mConversationListCursor != null) {
1528 mConversationListCursor.emptyFolder();
1529 }
Scott Kennedy7ee089e2013-03-25 17:05:44 -04001530 }
1531
Andrew Sappersteined5b52d2013-04-30 13:40:18 -07001532 private void attachEmptyFolderDialogFragmentListener() {
1533 final EmptyFolderDialogFragment fragment =
1534 (EmptyFolderDialogFragment) mActivity.getFragmentManager()
1535 .findFragmentByTag(EmptyFolderDialogFragment.FRAGMENT_TAG);
1536
1537 if (fragment != null) {
1538 fragment.setListener(this);
1539 }
1540 }
1541
Rohan Shah8e65c6d2013-03-07 16:47:25 -08001542 /**
Andy Huang12b3ee42013-04-24 22:49:43 -07001543 * Toggles the drawer pullout. If it was open (Fully extended), the
1544 * drawer will be closed. Otherwise, the drawer will be opened. This should
1545 * only be called when used with a toggle item. Other cases should be handled
1546 * explicitly with just closeDrawers() or openDrawer(View drawerView);
Rohan Shah8e65c6d2013-03-07 16:47:25 -08001547 */
Tony Mantlerd9eaca82013-08-05 11:42:29 -07001548 protected void toggleDrawerState() {
Andy Huang12b3ee42013-04-24 22:49:43 -07001549 if (!isDrawerEnabled()) {
1550 return;
1551 }
1552 if(mDrawerContainer.isDrawerOpen(mDrawerPullout)) {
1553 mDrawerContainer.closeDrawers();
1554 } else {
1555 mDrawerContainer.openDrawer(mDrawerPullout);
1556 }
Rohan Shah8e65c6d2013-03-07 16:47:25 -08001557 }
1558
Vikram Aggarwal531488e2012-05-29 16:36:52 -07001559 @Override
Andy Huangc1fb9a92013-02-11 13:09:12 -08001560 public final boolean onUpPressed() {
1561 for (UpOrBackHandler h : mUpOrBackHandlers) {
1562 if (h.onUpPressed()) {
1563 return true;
1564 }
1565 }
1566 return handleUpPress();
1567 }
1568
1569 @Override
1570 public final boolean onBackPressed() {
1571 for (UpOrBackHandler h : mUpOrBackHandlers) {
1572 if (h.onBackPressed()) {
1573 return true;
1574 }
1575 }
Andy Huang12b3ee42013-04-24 22:49:43 -07001576
1577 if (isDrawerEnabled() && mDrawerContainer.isDrawerVisible(mDrawerPullout)) {
1578 mDrawerContainer.closeDrawers();
1579 return true;
1580 }
1581
Andy Huangc1fb9a92013-02-11 13:09:12 -08001582 return handleBackPress();
1583 }
1584
1585 protected abstract boolean handleBackPress();
1586 protected abstract boolean handleUpPress();
1587
1588 @Override
1589 public void addUpOrBackHandler(UpOrBackHandler handler) {
1590 if (mUpOrBackHandlers.contains(handler)) {
1591 return;
1592 }
1593 mUpOrBackHandlers.addFirst(handler);
1594 }
1595
1596 @Override
1597 public void removeUpOrBackHandler(UpOrBackHandler handler) {
1598 mUpOrBackHandlers.remove(handler);
1599 }
1600
1601 @Override
Mindy Pereira6c2663d2012-07-20 15:37:29 -07001602 public void updateConversation(Collection<Conversation> target, ContentValues values) {
Scott Kennedy9e2d4072013-03-21 21:46:01 -07001603 mConversationListCursor.updateValues(target, values);
Mindy Pereira6c2663d2012-07-20 15:37:29 -07001604 refreshConversationList();
1605 }
1606
1607 @Override
Vikram Aggarwal531488e2012-05-29 16:36:52 -07001608 public void updateConversation(Collection <Conversation> target, String columnName,
1609 boolean value) {
Scott Kennedy9e2d4072013-03-21 21:46:01 -07001610 mConversationListCursor.updateBoolean(target, columnName, value);
Vikram Aggarwal75daee52012-04-30 11:13:09 -07001611 refreshConversationList();
Vikram Aggarwal54452ae2012-03-13 15:29:00 -07001612 }
1613
Vikram Aggarwal531488e2012-05-29 16:36:52 -07001614 @Override
Mindy Pereira6c2663d2012-07-20 15:37:29 -07001615 public void updateConversation(Collection <Conversation> target, String columnName,
1616 int value) {
Scott Kennedy9e2d4072013-03-21 21:46:01 -07001617 mConversationListCursor.updateInt(target, columnName, value);
Vikram Aggarwal75daee52012-04-30 11:13:09 -07001618 refreshConversationList();
Mindy Pereirac9d59182012-03-22 16:06:46 -07001619 }
1620
Vikram Aggarwal531488e2012-05-29 16:36:52 -07001621 @Override
1622 public void updateConversation(Collection <Conversation> target, String columnName,
1623 String value) {
Scott Kennedy9e2d4072013-03-21 21:46:01 -07001624 mConversationListCursor.updateString(target, columnName, value);
Vikram Aggarwal75daee52012-04-30 11:13:09 -07001625 refreshConversationList();
Vikram Aggarwal54452ae2012-03-13 15:29:00 -07001626 }
1627
Andy Huang839ada22012-07-20 15:48:40 -07001628 @Override
Yu Ping Hu7c909c72013-01-18 11:58:01 -08001629 public void markConversationMessagesUnread(final Conversation conv,
1630 final Set<Uri> unreadMessageUris, final byte[] originalConversationInfo) {
Andy Huang8f6b0062012-07-31 15:36:31 -07001631 // The only caller of this method is the conversation view, from where marking unread should
1632 // *always* take you back to list mode.
1633 showConversation(null);
1634
Andy Huang839ada22012-07-20 15:48:40 -07001635 // locally mark conversation unread (the provider is supposed to propagate message unread
1636 // to conversation unread)
1637 conv.read = false;
Paul Westbrook1faf93d2012-10-16 08:58:07 -07001638 if (mConversationListCursor == null) {
Vikram Aggarwal81230ee2013-02-26 15:26:44 -08001639 LogUtils.d(LOG_TAG, "markConversationMessagesUnread(id=%d), deferring", conv.id);
Paul Westbrook1faf93d2012-10-16 08:58:07 -07001640
Yu Ping Hu7c909c72013-01-18 11:58:01 -08001641 mConversationListLoadFinishedCallbacks.add(new LoadFinishedCallback() {
1642 @Override
1643 public void onLoadFinished() {
1644 doMarkConversationMessagesUnread(conv, unreadMessageUris,
1645 originalConversationInfo);
1646 }
1647 });
1648 } else {
Vikram Aggarwal81230ee2013-02-26 15:26:44 -08001649 LogUtils.d(LOG_TAG, "markConversationMessagesUnread(id=%d), performing", conv.id);
Yu Ping Hu7c909c72013-01-18 11:58:01 -08001650 doMarkConversationMessagesUnread(conv, unreadMessageUris, originalConversationInfo);
1651 }
1652 }
1653
1654 private void doMarkConversationMessagesUnread(Conversation conv, Set<Uri> unreadMessageUris,
1655 byte[] originalConversationInfo) {
Vikram Aggarwal81230ee2013-02-26 15:26:44 -08001656 // Only do a granular 'mark unread' if a subset of messages are unread
Andy Huang28e31e22012-07-26 16:33:15 -07001657 final int unreadCount = (unreadMessageUris == null) ? 0 : unreadMessageUris.size();
Mindy Pereira0972e072012-08-01 17:43:06 -07001658 final int numMessages = conv.getNumMessages();
1659 final boolean subsetIsUnread = (numMessages > 1 && unreadCount > 0
1660 && unreadCount < numMessages);
Andy Huang28e31e22012-07-26 16:33:15 -07001661
Andy Huang9e4ca792013-02-28 14:33:43 -08001662 LogUtils.d(LOG_TAG, "markConversationMessagesUnread(conv=%s)"
Vikram Aggarwal81230ee2013-02-26 15:26:44 -08001663 + ", numMessages=%d, unreadCount=%d, subsetIsUnread=%b",
Andy Huang9e4ca792013-02-28 14:33:43 -08001664 conv, numMessages, unreadCount, subsetIsUnread);
Andy Huang28e31e22012-07-26 16:33:15 -07001665 if (!subsetIsUnread) {
Vikram Aggarwal66bc2aa2012-08-02 10:47:03 -07001666 // Conversations are neither marked read, nor viewed, and we don't want to show
1667 // the next conversation.
Vikram Aggarwal81230ee2013-02-26 15:26:44 -08001668 LogUtils.d(LOG_TAG, ". . doing full mark unread");
Scott Kennedycaaeed32013-06-12 13:39:16 -07001669 markConversationsRead(Collections.singletonList(conv), false, false, false);
Andy Huang839ada22012-07-20 15:48:40 -07001670 } else {
Vikram Aggarwal81230ee2013-02-26 15:26:44 -08001671 if (LogUtils.isLoggable(LOG_TAG, LogUtils.DEBUG)) {
1672 final ConversationInfo info = ConversationInfo.fromBlob(originalConversationInfo);
1673 LogUtils.d(LOG_TAG, ". . doing subset mark unread, originalConversationInfo = %s",
1674 info);
1675 }
Andy Huangdaa06ab2012-07-24 10:46:44 -07001676 mConversationListCursor.setConversationColumn(conv.uri, ConversationColumns.READ, 0);
Andy Huang839ada22012-07-20 15:48:40 -07001677
Vikram Aggarwal81230ee2013-02-26 15:26:44 -08001678 // Locally update conversation's conversationInfo to revert to original version
Andy Huang28e31e22012-07-26 16:33:15 -07001679 if (originalConversationInfo != null) {
1680 mConversationListCursor.setConversationColumn(conv.uri,
1681 ConversationColumns.CONVERSATION_INFO, originalConversationInfo);
1682 }
Andy Huang839ada22012-07-20 15:48:40 -07001683
1684 // applyBatch with each CPO as an UPDATE op on each affected message uri
1685 final ArrayList<ContentProviderOperation> ops = Lists.newArrayList();
1686 String authority = null;
1687 for (Uri messageUri : unreadMessageUris) {
1688 if (authority == null) {
1689 authority = messageUri.getAuthority();
1690 }
1691 ops.add(ContentProviderOperation.newUpdate(messageUri)
1692 .withValue(UIProvider.MessageColumns.READ, 0)
1693 .build());
Vikram Aggarwal81230ee2013-02-26 15:26:44 -08001694 LogUtils.d(LOG_TAG, ". . Adding op: read=0, uri=%s", messageUri);
Andy Huang839ada22012-07-20 15:48:40 -07001695 }
Vikram Aggarwal81230ee2013-02-26 15:26:44 -08001696 LogUtils.d(LOG_TAG, ". . operations = %s", ops);
Andy Huang839ada22012-07-20 15:48:40 -07001697 new ContentProviderTask() {
1698 @Override
1699 protected void onPostExecute(Result result) {
Vikram Aggarwald9895b62013-02-27 16:52:27 -08001700 if (result.exception != null) {
1701 LogUtils.e(LOG_TAG, result.exception, "ContentProviderTask() ERROR.");
1702 } else {
Andy Huang9e4ca792013-02-28 14:33:43 -08001703 LogUtils.d(LOG_TAG, "ContentProviderTask(): success %s",
1704 Arrays.toString(result.results));
Vikram Aggarwald9895b62013-02-27 16:52:27 -08001705 }
Andy Huang839ada22012-07-20 15:48:40 -07001706 }
1707 }.run(mResolver, authority, ops);
Andy Huang839ada22012-07-20 15:48:40 -07001708 }
Andy Huang839ada22012-07-20 15:48:40 -07001709 }
1710
1711 @Override
Yu Ping Hu7c909c72013-01-18 11:58:01 -08001712 public void markConversationsRead(final Collection<Conversation> targets, final boolean read,
1713 final boolean viewed) {
Scott Kennedy919d01a2013-05-07 16:13:29 -07001714 LogUtils.d(LOG_TAG, "markConversationsRead(targets=%s)", targets.toArray());
1715
Yu Ping Hu7c909c72013-01-18 11:58:01 -08001716 if (mConversationListCursor == null) {
Vikram Aggarwal81230ee2013-02-26 15:26:44 -08001717 if (LogUtils.isLoggable(LOG_TAG, LogUtils.DEBUG)) {
1718 LogUtils.d(LOG_TAG, "markConversationsRead(targets=%s), deferring",
1719 targets.toArray());
1720 }
Yu Ping Hu7c909c72013-01-18 11:58:01 -08001721 mConversationListLoadFinishedCallbacks.add(new LoadFinishedCallback() {
1722 @Override
1723 public void onLoadFinished() {
Scott Kennedycaaeed32013-06-12 13:39:16 -07001724 markConversationsRead(targets, read, viewed, true);
Yu Ping Hu7c909c72013-01-18 11:58:01 -08001725 }
1726 });
1727 } else {
1728 // We want to show the next conversation if we are marking unread.
Scott Kennedycaaeed32013-06-12 13:39:16 -07001729 markConversationsRead(targets, read, viewed, true);
Yu Ping Hu7c909c72013-01-18 11:58:01 -08001730 }
Andy Huang8f6b0062012-07-31 15:36:31 -07001731 }
1732
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001733 private void markConversationsRead(final Collection<Conversation> targets, final boolean read,
Scott Kennedycaaeed32013-06-12 13:39:16 -07001734 final boolean markViewed, final boolean showNext) {
Yu Ping Hu7c909c72013-01-18 11:58:01 -08001735 LogUtils.d(LOG_TAG, "performing markConversationsRead");
Vikram Aggarwalcc754b12012-08-30 14:04:21 -07001736 // Auto-advance if requested and the current conversation is being marked unread
Andy Huang8f6b0062012-07-31 15:36:31 -07001737 if (showNext && !read) {
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001738 final Runnable operation = new Runnable() {
1739 @Override
1740 public void run() {
Scott Kennedycaaeed32013-06-12 13:39:16 -07001741 markConversationsRead(targets, read, markViewed, showNext);
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001742 }
1743 };
1744
Scott Kennedycaaeed32013-06-12 13:39:16 -07001745 if (!showNextConversation(targets, operation)) {
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001746 // This method will be called again if the user selects an autoadvance option
1747 return;
1748 }
Andy Huang8f6b0062012-07-31 15:36:31 -07001749 }
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001750
Vikram Aggarwalcc754b12012-08-30 14:04:21 -07001751 final int size = targets.size();
1752 final List<ConversationOperation> opList = new ArrayList<ConversationOperation>(size);
1753 for (final Conversation target : targets) {
Paul Westbrooke2be97a2013-05-21 02:12:09 -07001754 final ContentValues value = new ContentValues(4);
Vikram Aggarwalcc754b12012-08-30 14:04:21 -07001755 value.put(ConversationColumns.READ, read);
Paul Westbrook5109c512012-11-05 11:00:30 -08001756
Scott Kennedyd5edd2d2012-12-05 11:11:32 -08001757 // We never want to mark unseen here, but we do want to mark it seen
1758 if (read || markViewed) {
1759 value.put(ConversationColumns.SEEN, Boolean.TRUE);
1760 }
1761
Paul Westbrook5109c512012-11-05 11:00:30 -08001762 // The mark read/unread/viewed operations do not show an undo bar
1763 value.put(ConversationOperations.Parameters.SUPPRESS_UNDO, true);
Vikram Aggarwal66bc2aa2012-08-02 10:47:03 -07001764 if (markViewed) {
Vikram Aggarwalcc754b12012-08-30 14:04:21 -07001765 value.put(ConversationColumns.VIEWED, true);
Vikram Aggarwal66bc2aa2012-08-02 10:47:03 -07001766 }
Vikram Aggarwal192fac12012-07-25 16:44:55 -07001767 final ConversationInfo info = target.conversationInfo;
Tony Mantleredd6c1a2013-10-08 14:47:43 -07001768 final boolean changed = info.markRead(read);
1769 if (changed) {
1770 value.put(ConversationColumns.CONVERSATION_INFO, info.toBlob());
Andy Huang839ada22012-07-20 15:48:40 -07001771 }
Vikram Aggarwalcc754b12012-08-30 14:04:21 -07001772 opList.add(mConversationListCursor.getOperationForConversation(
1773 target, ConversationOperation.UPDATE, value));
1774 // Update the local conversation objects so they immediately change state.
1775 target.read = read;
Andy Huangcd5c5ee2012-08-12 19:03:51 -07001776 if (markViewed) {
Vikram Aggarwalcc754b12012-08-30 14:04:21 -07001777 target.markViewed();
Andy Huangcd5c5ee2012-08-12 19:03:51 -07001778 }
Andy Huang839ada22012-07-20 15:48:40 -07001779 }
Scott Kennedy9e2d4072013-03-21 21:46:01 -07001780 mConversationListCursor.updateBulkValues(opList);
Andy Huang839ada22012-07-20 15:48:40 -07001781 }
1782
Andy Huang8f6b0062012-07-31 15:36:31 -07001783 /**
1784 * Auto-advance to a different conversation if the currently visible conversation in
1785 * conversation mode is affected (deleted, marked unread, etc.).
1786 *
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001787 * <p>Does nothing if outside of conversation mode.</p>
Andy Huang8f6b0062012-07-31 15:36:31 -07001788 *
1789 * @param target the set of conversations being deleted/marked unread
1790 */
mindyp9365a822012-09-12 09:09:09 -07001791 @Override
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001792 public void showNextConversation(final Collection<Conversation> target) {
Scott Kennedycaaeed32013-06-12 13:39:16 -07001793 showNextConversation(target, null);
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001794 }
1795
1796 /**
1797 * Auto-advance to a different conversation if the currently visible conversation in
1798 * conversation mode is affected (deleted, marked unread, etc.).
1799 *
1800 * <p>Does nothing if outside of conversation mode.</p>
Andy Huangc94d07f2013-06-03 16:19:35 -07001801 * <p>
1802 * Clients may pass an operation to execute on the target that this method will run after
1803 * auto-advance is complete. The operation, if provided, may run immediately, or it may run
1804 * later, or not at all. Reasons it may run later include:
1805 * <ul>
1806 * <li>the auto-advance setting is uninitialized and we need to wait for the user to set it</li>
1807 * <li>auto-advance in this configuration requires a mode change, and we need to wait for the
1808 * mode change transition to finish</li>
1809 * </ul>
1810 * <p>If the current conversation is not in the target collection, this method will do nothing,
1811 * and will not execute the operation.
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001812 *
1813 * @param target the set of conversations being deleted/marked unread
Andy Huangc94d07f2013-06-03 16:19:35 -07001814 * @param operation (optional) the operation to execute after advancing
1815 * @return <code>false</code> if this method handled or will execute the operation,
1816 * <code>true</code> otherwise.
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001817 */
1818 private boolean showNextConversation(final Collection<Conversation> target,
Scott Kennedycaaeed32013-06-12 13:39:16 -07001819 final Runnable operation) {
Scott Kennedy8fb8e262012-11-28 15:48:03 -08001820 final int viewMode = mViewMode.getMode();
1821 final boolean currentConversationInView = (viewMode == ViewMode.CONVERSATION
1822 || viewMode == ViewMode.SEARCH_RESULTS_CONVERSATION)
Andy Huang8f6b0062012-07-31 15:36:31 -07001823 && Conversation.contains(target, mCurrentConversation);
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001824
Andy Huang8f6b0062012-07-31 15:36:31 -07001825 if (currentConversationInView) {
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001826 final int autoAdvanceSetting = mAccount.settings.getAutoAdvanceSetting();
1827
Scott Kennedycaaeed32013-06-12 13:39:16 -07001828 if (autoAdvanceSetting == AutoAdvance.UNSET && mIsTablet) {
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001829 displayAutoAdvanceDialogAndPerformAction(operation);
1830 return false;
1831 } else {
1832 // If we don't have one set, but we're here, just take the default
Vikram Aggarwal82d37502013-01-10 16:18:49 -08001833 final int autoAdvance = (autoAdvanceSetting == AutoAdvance.UNSET) ?
1834 AutoAdvance.DEFAULT : autoAdvanceSetting;
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001835
1836 final Conversation next = mTracker.getNextConversation(autoAdvance, target);
1837 LogUtils.d(LOG_TAG, "showNextConversation: showing %s next.", next);
Andy Huangc94d07f2013-06-03 16:19:35 -07001838 // Set mAutoAdvanceOp *before* showConversation() to ensure that it runs when the
1839 // transition doesn't run (i.e. it "completes" immediately).
1840 mAutoAdvanceOp = operation;
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001841 showConversation(next);
Andy Huangc94d07f2013-06-03 16:19:35 -07001842 return (mAutoAdvanceOp == null);
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001843 }
Andy Huang8f6b0062012-07-31 15:36:31 -07001844 }
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001845
1846 return true;
1847 }
1848
1849 /**
1850 * Displays a the auto-advance dialog, and when the user makes a selection, the preference is
1851 * stored, and the specified operation is run.
1852 */
1853 private void displayAutoAdvanceDialogAndPerformAction(final Runnable operation) {
1854 final String[] autoAdvanceDisplayOptions =
1855 mContext.getResources().getStringArray(R.array.prefEntries_autoAdvance);
1856 final String[] autoAdvanceOptionValues =
1857 mContext.getResources().getStringArray(R.array.prefValues_autoAdvance);
1858
1859 final String defaultValue = mContext.getString(R.string.prefDefault_autoAdvance);
1860 int initialIndex = 0;
1861 for (int i = 0; i < autoAdvanceOptionValues.length; i++) {
1862 if (defaultValue.equals(autoAdvanceOptionValues[i])) {
1863 initialIndex = i;
1864 break;
1865 }
1866 }
1867
1868 final DialogInterface.OnClickListener listClickListener =
1869 new DialogInterface.OnClickListener() {
1870 @Override
1871 public void onClick(DialogInterface dialog, int whichItem) {
1872 final String autoAdvanceValue = autoAdvanceOptionValues[whichItem];
1873 final int autoAdvanceValueInt =
1874 UIProvider.AutoAdvance.getAutoAdvanceInt(autoAdvanceValue);
1875 mAccount.settings.setAutoAdvanceSetting(autoAdvanceValueInt);
1876
1877 // Save the user's setting
1878 final ContentValues values = new ContentValues(1);
1879 values.put(AccountColumns.SettingsColumns.AUTO_ADVANCE, autoAdvanceValue);
1880
1881 final ContentResolver resolver = mContext.getContentResolver();
1882 resolver.update(mAccount.updateSettingsUri, values, null, null);
1883
1884 // Dismiss the dialog, as clicking the items in the list doesn't close the
1885 // dialog.
1886 dialog.dismiss();
1887 if (operation != null) {
1888 operation.run();
1889 }
1890 }
1891 };
1892
1893 new AlertDialog.Builder(mActivity.getActivityContext()).setTitle(
1894 R.string.auto_advance_help_title)
1895 .setSingleChoiceItems(autoAdvanceDisplayOptions, initialIndex, listClickListener)
1896 .setPositiveButton(null, null)
1897 .create()
1898 .show();
Andy Huang8f6b0062012-07-31 15:36:31 -07001899 }
1900
Andy Huang839ada22012-07-20 15:48:40 -07001901 @Override
1902 public void starMessage(ConversationMessage msg, boolean starred) {
1903 if (msg.starred == starred) {
1904 return;
1905 }
1906
1907 msg.starred = starred;
1908
1909 // locally propagate the change to the owning conversation
1910 // (figure the provider will properly propagate the change when it commits it)
1911 //
1912 // when unstarring, only propagate the change if this was the only message starred
1913 final boolean conversationStarred = starred || msg.isConversationStarred();
Andy Huangcd12e822012-11-08 19:50:57 -08001914 final Conversation conv = msg.getConversation();
1915 if (conversationStarred != conv.starred) {
1916 conv.starred = conversationStarred;
1917 mConversationListCursor.setConversationColumn(conv.uri,
Andy Huang839ada22012-07-20 15:48:40 -07001918 ConversationColumns.STARRED, conversationStarred);
1919 }
1920
1921 final ContentValues values = new ContentValues(1);
1922 values.put(UIProvider.MessageColumns.STARRED, starred ? 1 : 0);
1923
1924 new ContentProviderTask.UpdateTask() {
1925 @Override
1926 protected void onPostExecute(Result result) {
1927 // TODO: handle errors?
1928 }
1929 }.run(mResolver, msg.uri, values, null /* selection*/, null /* selectionArgs */);
1930 }
1931
Andy Huang12b3ee42013-04-24 22:49:43 -07001932 @Override
Alice Yang486e63e2013-04-05 13:01:50 -07001933 public void requestFolderRefresh() {
Alice Yang37dda442013-03-26 22:48:53 -07001934 if (mFolder == null) {
1935 return;
Mindy Pereira28e0c342012-02-17 15:05:13 -08001936 }
Alice Yang37dda442013-03-26 22:48:53 -07001937 final ConversationListFragment convList = getConversationListFragment();
1938 if (convList == null) {
1939 // This could happen if this account is in initial sync (user
1940 // is seeing the "your mail will appear shortly" message)
1941 return;
1942 }
1943 convList.showSyncStatusBar();
1944
1945 if (mAsyncRefreshTask != null) {
1946 mAsyncRefreshTask.cancel(true);
1947 }
1948 mAsyncRefreshTask = new AsyncRefreshTask(mContext, mFolder.refreshUri);
1949 mAsyncRefreshTask.execute();
Mindy Pereira28e0c342012-02-17 15:05:13 -08001950 }
1951
Mindy Pereirafbe40192012-03-20 10:40:45 -07001952 /**
1953 * Confirm (based on user's settings) and delete a conversation from the conversation list and
1954 * from the database.
Vikram Aggarwalb8c31712013-01-03 17:03:19 -08001955 * @param actionId the ID of the menu item that caused the delete: R.id.delete, R.id.archive...
Vikram Aggarwal3d7ca9d2012-05-11 14:40:36 -07001956 * @param target the conversations to act upon
1957 * @param showDialog true if a confirmation dialog is to be shown, false otherwise.
1958 * @param confirmResource the resource ID of the string that is shown in the confirmation dialog
Mindy Pereirafbe40192012-03-20 10:40:45 -07001959 */
Vikram Aggarwalb8c31712013-01-03 17:03:19 -08001960 private void confirmAndDelete(int actionId, final Collection<Conversation> target,
1961 boolean showDialog, int confirmResource) {
Vikram Aggarwal84fe9942013-04-17 11:20:58 -07001962 final boolean isBatch = false;
Mindy Pereirafbe40192012-03-20 10:40:45 -07001963 if (showDialog) {
Vikram Aggarwal84fe9942013-04-17 11:20:58 -07001964 makeDialogListener(actionId, isBatch);
Vikram Aggarwal3d7ca9d2012-05-11 14:40:36 -07001965 final CharSequence message = Utils.formatPlural(mContext, confirmResource,
1966 target.size());
Vikram Aggarwalb8c31712013-01-03 17:03:19 -08001967 final ConfirmDialogFragment c = ConfirmDialogFragment.newInstance(message);
1968 c.displayDialog(mActivity.getFragmentManager());
Mindy Pereirafbe40192012-03-20 10:40:45 -07001969 } else {
Scott Kennedycaaeed32013-06-12 13:39:16 -07001970 delete(0, target, getDeferredAction(actionId, target, isBatch), isBatch);
Mindy Pereirafbe40192012-03-20 10:40:45 -07001971 }
1972 }
1973
Vikram Aggarwal4f4782b2012-05-30 08:39:09 -07001974 @Override
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001975 public void delete(final int actionId, final Collection<Conversation> target,
Scott Kennedycaaeed32013-06-12 13:39:16 -07001976 final DestructiveAction action, final boolean isBatch) {
mindyp84f7d322012-10-01 17:14:40 -07001977 // Order of events is critical! The Conversation View Fragment must be
1978 // notified of the next conversation with showConversation(next) *before* the
1979 // conversation list
Vikram Aggarwal192fac12012-07-25 16:44:55 -07001980 // fragment has a chance to delete the conversation, animating it away.
1981
mindyp84f7d322012-10-01 17:14:40 -07001982 // Update the conversation fragment if the current conversation is
1983 // deleted.
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001984 final Runnable operation = new Runnable() {
1985 @Override
1986 public void run() {
Scott Kennedycaaeed32013-06-12 13:39:16 -07001987 delete(actionId, target, action, isBatch);
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001988 }
1989 };
1990
Scott Kennedycaaeed32013-06-12 13:39:16 -07001991 if (!showNextConversation(target, operation)) {
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07001992 // This method will be called again if the user selects an autoadvance option
Andrew Sapperstein1165d292014-03-25 16:00:43 -07001993
1994 // HACKFIX around b/9904716. We were not properly performing the last
1995 // DestructiveAction. A proper fix probably involves rewriting
1996 // the logic for animating changes in the list as well as undo
1997 // and probably batch DestructiveActions. The change is limited to
1998 // tablets where the issue occurs.
1999 final ConversationListFragment convListFragment = getConversationListFragment();
2000 if (mIsTablet && convListFragment != null) {
2001 convListFragment.getAnimatedAdapter().setNextAction(
2002 new SwipeableListView.ListItemsRemovedListener() {
2003 @Override
2004 public void onListItemsRemoved() {
2005 action.performAction();
2006 }
2007 }
2008 );
2009 }
Scott Kennedy0d0f8b02012-10-12 15:18:18 -07002010 return;
2011 }
Vikram Aggarwalab1b5b62013-04-16 15:45:50 -07002012 // If the conversation is in the selected set, remove it from the set.
Vikram Aggarwal84fe9942013-04-17 11:20:58 -07002013 // Batch selections are cleared in the end of the action, so not done for batch actions.
2014 if (!isBatch) {
2015 for (final Conversation conv : target) {
2016 if (mSelectedSet.contains(conv)) {
Vikram Aggarwal97ae7842013-04-22 16:29:12 -07002017 mSelectedSet.toggle(conv);
Vikram Aggarwal84fe9942013-04-17 11:20:58 -07002018 }
Vikram Aggarwalab1b5b62013-04-16 15:45:50 -07002019 }
2020 }
Vikram Aggarwal192fac12012-07-25 16:44:55 -07002021 // The conversation list deletes and performs the action if it exists.
2022 final ConversationListFragment convListFragment = getConversationListFragment();
2023 if (convListFragment != null) {
Alice Yang193e05a2013-05-05 14:12:08 -07002024 LogUtils.i(LOG_TAG, "AAC.requestDelete: ListFragment is handling delete.");
Vikram Aggarwal669947b2013-01-10 17:05:56 -08002025 convListFragment.requestDelete(actionId, target, action);
Vikram Aggarwal192fac12012-07-25 16:44:55 -07002026 return;
2027 }
mindyp84f7d322012-10-01 17:14:40 -07002028 // No visible UI element handled it on our behalf. Perform the action
2029 // ourself.
Alice Yang193e05a2013-05-05 14:12:08 -07002030 LogUtils.i(LOG_TAG, "ACC.requestDelete: performing remove action ourselves");
Vikram Aggarwald503df42012-05-11 10:13:35 -07002031 action.performAction();
2032 }
2033
2034 /**
2035 * Requests that the action be performed and the UI state is updated to reflect the new change.
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08002036 * @param action the action to be performed, specified as a menu id: R.id.archive, ...
Vikram Aggarwald503df42012-05-11 10:13:35 -07002037 */
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08002038 private void requestUpdate(final DestructiveAction action) {
Vikram Aggarwald503df42012-05-11 10:13:35 -07002039 action.performAction();
2040 refreshConversationList();
Vikram Aggarwal75daee52012-04-30 11:13:09 -07002041 }
Vikram Aggarwal6fbc87a2012-03-15 15:24:00 -07002042
2043 @Override
Vikram Aggarwala55b36c2012-01-13 11:45:02 -08002044 public void onPrepareDialog(int id, Dialog dialog, Bundle bundle) {
2045 // TODO(viki): Auto-generated method stub
Vikram Aggarwala55b36c2012-01-13 11:45:02 -08002046 }
2047
2048 @Override
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08002049 public boolean onPrepareOptionsMenu(Menu menu) {
Andy Huangd736a382012-08-29 13:08:58 -07002050 return mActionBarView.onPrepareOptionsMenu(menu);
Vikram Aggarwala55b36c2012-01-13 11:45:02 -08002051 }
2052
Mindy Pereira68f2e222012-03-07 10:36:54 -08002053 @Override
2054 public void onPause() {
Vikram Aggarwalc04cf7e2013-05-13 15:38:42 -07002055 mHaveAccountList = false;
Paul Westbrook6ead20d2012-03-19 14:48:14 -07002056 enableNotifications();
Paul Westbrook94e440d2012-02-24 11:03:47 -08002057 }
2058
Vikram Aggarwala55b36c2012-01-13 11:45:02 -08002059 @Override
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08002060 public void onResume() {
Paul Westbrook6ead20d2012-03-19 14:48:14 -07002061 // Register the receiver that will prevent the status receiver from
2062 // displaying its notification icon as long as we're running.
2063 // The SupressNotificationReceiver will block the broadcast if we're looking at the folder
2064 // that the notification was received for.
2065 disableNotifications();
Andy Huang1ee96b22012-08-24 20:19:53 -07002066
2067 mSafeToModifyFragments = true;
Andrew Sappersteined5b52d2013-04-30 13:40:18 -07002068
2069 attachEmptyFolderDialogFragmentListener();
Andrew Sapperstein23e33132013-05-07 18:26:49 -07002070
2071 // Invalidating the options menu so that when we make changes in settings,
2072 // the changes will always be updated in the action bar/options menu/
2073 mActivity.invalidateOptionsMenu();
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08002074 }
2075
2076 @Override
2077 public void onSaveInstanceState(Bundle outState) {
Vikram Aggarwal649b9ea2012-08-27 12:15:20 -07002078 mViewMode.handleSaveInstanceState(outState);
Vikram Aggarwal6c511582012-02-27 10:59:47 -08002079 if (mAccount != null) {
Vikram Aggarwal6c511582012-02-27 10:59:47 -08002080 outState.putParcelable(SAVED_ACCOUNT, mAccount);
2081 }
Mindy Pereira5e478d22012-03-26 18:04:58 -07002082 if (mFolder != null) {
2083 outState.putParcelable(SAVED_FOLDER, mFolder);
Vikram Aggarwal8b152632012-02-03 14:58:45 -08002084 }
Vikram Aggarwalf3341402012-08-07 10:09:38 -07002085 // If this is a search activity, let's store the search query term as well.
2086 if (ConversationListContext.isSearchResult(mConvListContext)) {
2087 outState.putString(SAVED_QUERY, mConvListContext.searchQuery);
2088 }
Vikram Aggarwal49e0e992012-09-21 13:53:15 -07002089 if (mCurrentConversation != null && mViewMode.isConversationMode()) {
Mindy Pereira26f23fc2012-03-27 10:26:04 -07002090 outState.putParcelable(SAVED_CONVERSATION, mCurrentConversation);
2091 }
Andy Huang4556a442012-03-30 16:42:05 -07002092 if (!mSelectedSet.isEmpty()) {
Vikram Aggarwalcabd3f22012-04-19 10:14:41 -07002093 outState.putParcelable(SAVED_SELECTED_SET, mSelectedSet);
Andy Huang4556a442012-03-30 16:42:05 -07002094 }
Mindy Pereirad33674992012-06-25 16:26:30 -07002095 if (mToastBar.getVisibility() == View.VISIBLE) {
2096 outState.putParcelable(SAVED_TOAST_BAR_OP, mToastBar.getOperation());
2097 }
Vikram Aggarwal649b9ea2012-08-27 12:15:20 -07002098 final ConversationListFragment convListFragment = getConversationListFragment();
Mindy Pereirad33674992012-06-25 16:26:30 -07002099 if (convListFragment != null) {
Vikram Aggarwal649b9ea2012-08-27 12:15:20 -07002100 convListFragment.getAnimatedAdapter().onSaveInstanceState(outState);
Mindy Pereirad33674992012-06-25 16:26:30 -07002101 }
Vikram Aggarwalb8c31712013-01-03 17:03:19 -08002102 // If there is a dialog being shown, save the state so we can create a listener for it.
Vikram Aggarwal6cadbfc2012-12-27 09:17:05 -08002103 if (mDialogAction != -1) {
2104 outState.putInt(SAVED_ACTION, mDialogAction);
Vikram Aggarwalb8c31712013-01-03 17:03:19 -08002105 outState.putBoolean(SAVED_ACTION_FROM_SELECTED, mDialogFromSelectedSet);
Vikram Aggarwal6cadbfc2012-12-27 09:17:05 -08002106 }
Vikram Aggarwala91d00b2013-01-18 12:00:37 -08002107 if (mDetachedConvUri != null) {
2108 outState.putParcelable(SAVED_DETACHED_CONV_URI, mDetachedConvUri);
2109 }
Andrew Sapperstein5747e152013-05-13 14:13:08 -07002110
Scott Kennedyb10212e2013-02-22 16:27:00 -08002111 outState.putParcelable(SAVED_HIERARCHICAL_FOLDER, mFolderListFolder);
Andrew Sapperstein5747e152013-05-13 14:13:08 -07002112 mSafeToModifyFragments = false;
Alice Yangebeef1b2013-09-04 06:41:10 +00002113
2114 outState.putParcelable(SAVED_INBOX_KEY, mInbox);
Scott Kennedyf77806e2013-08-30 11:38:15 -07002115
2116 outState.putBundle(SAVED_CONVERSATION_LIST_SCROLL_POSITIONS,
2117 mConversationListScrollPositions);
Andy Huang1ee96b22012-08-24 20:19:53 -07002118 }
2119
2120 /**
2121 * @see #mSafeToModifyFragments
2122 */
2123 protected boolean safeToModifyFragments() {
2124 return mSafeToModifyFragments;
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08002125 }
2126
2127 @Override
Andy Huang313ac132013-03-04 23:40:58 -08002128 public void executeSearch(String query) {
Mindy Pereira68f2e222012-03-07 10:36:54 -08002129 Intent intent = new Intent();
2130 intent.setAction(Intent.ACTION_SEARCH);
2131 intent.putExtra(ConversationListContext.EXTRA_SEARCH_QUERY, query);
2132 intent.putExtra(Utils.EXTRA_ACCOUNT, mAccount);
2133 intent.setComponent(mActivity.getComponentName());
Vikram Aggarwalb17cbc02012-04-06 15:41:46 -07002134 mActionBarView.collapseSearch();
Martin Hibdon371a71c2014-02-19 13:55:28 -08002135 // Call startActivityForResult here so we can tell if we have navigated to a different folder
2136 // or account from search results.
2137 mActivity.startActivityForResult(intent, CHANGE_NAVIGATION_REQUEST_CODE);
Vikram Aggarwala55b36c2012-01-13 11:45:02 -08002138 }
2139
2140 @Override
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08002141 public void onStop() {
Scott Kennedycb85aea2013-02-25 13:08:32 -08002142 NotificationActionUtils.unregisterUndoNotificationObserver(mUndoNotificationObserver);
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08002143 }
2144
Andy Huang632721e2012-04-11 16:57:26 -07002145 @Override
2146 public void onDestroy() {
Andy Huangb2ef9c12012-12-18 12:58:41 -06002147 // stop listening to the cursor on e.g. configuration changes
2148 if (mConversationListCursor != null) {
2149 mConversationListCursor.removeListener(this);
2150 }
Andy Huang144bfe72013-06-11 13:27:52 -07002151 mDrawIdler.setListener(null);
2152 mDrawIdler.setRootView(null);
Andy Huang632721e2012-04-11 16:57:26 -07002153 // unregister the ViewPager's observer on the conversation cursor
2154 mPagerController.onDestroy();
Mindy Pereira641de652012-08-02 15:21:50 -07002155 mActionBarView.onDestroy();
Vikram Aggarwal7c401b72012-08-13 16:43:47 -07002156 mRecentFolderList.destroy();
Andy Huang4e0158f2012-08-07 21:06:01 -07002157 mDestroyed = true;
Vikram Aggarwal59f741f2013-03-01 15:55:40 -08002158 mHandler.removeCallbacks(mLogServiceChecker);
2159 mLogServiceChecker = null;
Andy Huang632721e2012-04-11 16:57:26 -07002160 }
2161
Vikram Aggarwalfa131a22012-02-02 13:56:22 -08002162 /**
Vikram Aggarwal93dc2022012-11-05 13:36:57 -08002163 * Set the Action Bar icon according to the mode. The Action Bar icon can contain a back button
2164 * or not. The individual controller is responsible for changing the icon based on the mode.
2165 */
2166 protected abstract void resetActionBarIcon();
2167
2168 /**
Mindy Pereira161f50d2012-02-28 15:47:19 -08002169 * {@inheritDoc} Subclasses must override this to listen to mode changes
2170 * from the ViewMode. Subclasses <b>must</b> call the parent's
2171 * onViewModeChanged since the parent will handle common state changes.
Vikram Aggarwalfa131a22012-02-02 13:56:22 -08002172 */
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08002173 @Override
Vikram Aggarwalfa131a22012-02-02 13:56:22 -08002174 public void onViewModeChanged(int newMode) {
Vikram Aggarwal49e0e992012-09-21 13:53:15 -07002175 // When we step away from the conversation mode, we don't have a current conversation
2176 // anymore. Let's blank it out so clients calling getCurrentConversation are not misled.
2177 if (!ViewMode.isConversationMode(newMode)) {
2178 setCurrentConversation(null);
2179 }
Andrew Sapperstein6c570db2013-08-06 17:21:36 -07002180
Vikram Aggarwal93dc2022012-11-05 13:36:57 -08002181 // If the viewmode is not set, preserve existing icon.
2182 if (newMode != ViewMode.UNKNOWN) {
2183 resetActionBarIcon();
2184 }
Andy Huang12b3ee42013-04-24 22:49:43 -07002185
2186 if (isDrawerEnabled()) {
Vikram Aggarwaldfbc6982013-07-03 14:39:31 -07002187 /** If the folder doesn't exist, or its parent URI is empty,
2188 * this is not a child folder */
2189 final boolean isTopLevel = (mFolder == null) || (mFolder.parent == Uri.EMPTY);
2190 mDrawerToggle.setDrawerIndicatorEnabled(
2191 getShouldShowDrawerIndicator(newMode, isTopLevel));
Martin Hibdon371a71c2014-02-19 13:55:28 -08002192 mDrawerContainer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
Andy Huang12b3ee42013-04-24 22:49:43 -07002193 closeDrawerIfOpen();
2194 }
Vikram Aggarwala55b36c2012-01-13 11:45:02 -08002195 }
2196
Vikram Aggarwaldfbc6982013-07-03 14:39:31 -07002197 /**
2198 * Returns true if the drawer icon is shown
2199 * @param viewMode the current view mode
2200 * @param isTopLevel true if the current folder is not a child
2201 * @return whether the drawer indicator is shown
2202 */
Scott Kennedy81b5fa02013-07-11 14:39:18 -07002203 private boolean getShouldShowDrawerIndicator(final int viewMode,
Vikram Aggarwaldfbc6982013-07-03 14:39:31 -07002204 final boolean isTopLevel) {
2205 // If search list/conv mode: disable indicator
2206 // Indicator is enabled either in conversation list or folder list mode.
Scott Kennedy81b5fa02013-07-11 14:39:18 -07002207 return isDrawerEnabled() && !ViewMode.isSearchMode(viewMode)
Scott Kennedyaded5782013-07-16 14:21:53 -07002208 && (viewMode == ViewMode.CONVERSATION_LIST && isTopLevel);
Scott Kennedy8a72b852013-05-02 14:18:50 -07002209 }
2210
Andy Huang3825f3d2012-08-29 16:44:12 -07002211 public void disablePagerUpdates() {
2212 mPagerController.stopListening();
2213 }
2214
Andy Huang4e0158f2012-08-07 21:06:01 -07002215 public boolean isDestroyed() {
2216 return mDestroyed;
2217 }
2218
mindyp54f120f2012-08-28 13:10:33 -07002219 @Override
2220 public void commitDestructiveActions(boolean animate) {
mindypc6adce32012-08-22 18:46:42 -07002221 ConversationListFragment fragment = getConversationListFragment();
Mindy Pereira1e2573b2012-04-17 14:34:36 -07002222 if (fragment != null) {
mindypc6adce32012-08-22 18:46:42 -07002223 fragment.commitDestructiveActions(animate);
Mindy Pereira1e2573b2012-04-17 14:34:36 -07002224 }
2225 }
2226
Vikram Aggarwala55b36c2012-01-13 11:45:02 -08002227 @Override
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08002228 public void onWindowFocusChanged(boolean hasFocus) {
Vikram Aggarwal69b5c302012-09-05 11:11:13 -07002229 final ConversationListFragment convList = getConversationListFragment();
Vikram Aggarwal6422b8d2013-01-14 10:47:41 -08002230 // hasFocus already ensures that the window is in focus, so we don't need to call
2231 // AAC.isFragmentVisible(convList) here.
Paul Westbrook9f119c72012-04-24 16:10:59 -07002232 if (hasFocus && convList != null && convList.isVisible()) {
2233 // The conversation list is visible.
Vikram Aggarwal69b5c302012-09-05 11:11:13 -07002234 informCursorVisiblity(true);
Paul Westbrook9f119c72012-04-24 16:10:59 -07002235 }
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08002236 }
2237
Vikram Aggarwalca716f12012-08-20 11:11:48 -07002238 /**
2239 * Set the account, and carry out all the account-related changes that rely on this.
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08002240 * @param account new account to set to.
Vikram Aggarwalca716f12012-08-20 11:11:48 -07002241 */
Mindy Pereira75181e82012-04-18 08:17:13 -07002242 private void setAccount(Account account) {
Andy Huangb9ca9792012-05-18 15:31:49 -07002243 if (account == null) {
2244 LogUtils.w(LOG_TAG, new Error(),
2245 "AAC ignoring null (presumably invalid) account restoration");
2246 return;
2247 }
Andy Huangb1148412012-05-19 00:16:30 -07002248 LogUtils.d(LOG_TAG, "AbstractActivityController.setAccount(): account = %s", account.uri);
Vikram Aggarwal91e87372012-05-18 15:36:04 -07002249 mAccount = account;
Vikram Aggarwalca716f12012-08-20 11:11:48 -07002250 // Only change AAC state here. Do *not* modify any other object's state. The object
2251 // should listen on account changes.
Vikram Aggarwal177097f2013-03-08 11:19:53 -08002252 restartOptionalLoader(LOADER_RECENT_FOLDERS, mFolderCallbacks, Bundle.EMPTY);
Vikram Aggarwalca716f12012-08-20 11:11:48 -07002253 mActivity.invalidateOptionsMenu();
2254 disableNotificationsOnAccountChange(mAccount);
Vikram Aggarwal177097f2013-03-08 11:19:53 -08002255 restartOptionalLoader(LOADER_ACCOUNT_UPDATE_CURSOR, mAccountCallbacks, Bundle.EMPTY);
Vikram Aggarwal2fe343f2013-01-14 09:00:25 -08002256 // The Mail instance can be null during test runs.
2257 final MailAppProvider instance = MailAppProvider.getInstance();
2258 if (instance != null) {
2259 instance.setLastViewedAccount(mAccount.uri.toString());
2260 }
Vikram Aggarwal91e87372012-05-18 15:36:04 -07002261 if (account.settings == null) {
2262 LogUtils.w(LOG_TAG, new Error(), "AAC ignoring account with null settings.");
2263 return;
2264 }
Vikram Aggarwal7c401b72012-08-13 16:43:47 -07002265 mAccountObservers.notifyChanged();
Vikram Aggarwal34f7b232012-10-17 13:32:23 -07002266 perhapsEnterWaitMode();
Mindy Pereira75181e82012-04-18 08:17:13 -07002267 }
2268
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08002269 /**
Mindy Pereira161f50d2012-02-28 15:47:19 -08002270 * Restore the state from the previous bundle. Subclasses should call this
2271 * method from the parent class, since it performs important UI
2272 * initialization.
2273 *
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08002274 * @param savedState previous state
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08002275 */
Andy Huang632721e2012-04-11 16:57:26 -07002276 @Override
2277 public void onRestoreInstanceState(Bundle savedState) {
Vikram Aggarwala91d00b2013-01-18 12:00:37 -08002278 mDetachedConvUri = savedState.getParcelable(SAVED_DETACHED_CONV_URI);
Andy Huang632721e2012-04-11 16:57:26 -07002279 if (savedState.containsKey(SAVED_CONVERSATION)) {
2280 // Open the conversation.
Andy Huang2bc8bc12012-11-12 17:24:25 -08002281 final Conversation conversation = savedState.getParcelable(SAVED_CONVERSATION);
Paul Westbrook534e4a22012-04-25 03:46:29 -07002282 if (conversation != null && conversation.position < 0) {
2283 // Set the position to 0 on this conversation, as we don't know where it is
2284 // in the list
2285 conversation.position = 0;
2286 }
Andy Huanged4fdf02012-07-26 17:12:50 -07002287 showConversation(conversation);
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08002288 }
Mindy Pereira967ede62012-03-22 09:29:09 -07002289
Mindy Pereirad33674992012-06-25 16:26:30 -07002290 if (savedState.containsKey(SAVED_TOAST_BAR_OP)) {
Andy Huang2bc8bc12012-11-12 17:24:25 -08002291 ToastBarOperation op = savedState.getParcelable(SAVED_TOAST_BAR_OP);
Mindy Pereirad33674992012-06-25 16:26:30 -07002292 if (op != null) {
2293 if (op.getType() == ToastBarOperation.UNDO) {
2294 onUndoAvailable(op);
Andrew Sapperstein9d7519d2012-07-16 14:03:53 -07002295 } else if (op.getType() == ToastBarOperation.ERROR) {
2296 onError(mFolder, true);
Mindy Pereirad33674992012-06-25 16:26:30 -07002297 }
2298 }
2299 }
Scott Kennedyb10212e2013-02-22 16:27:00 -08002300 mFolderListFolder = savedState.getParcelable(SAVED_HIERARCHICAL_FOLDER);
Vikram Aggarwal649b9ea2012-08-27 12:15:20 -07002301 final ConversationListFragment convListFragment = getConversationListFragment();
Mindy Pereirad33674992012-06-25 16:26:30 -07002302 if (convListFragment != null) {
Vikram Aggarwal649b9ea2012-08-27 12:15:20 -07002303 convListFragment.getAnimatedAdapter().onRestoreInstanceState(savedState);
Mindy Pereirad33674992012-06-25 16:26:30 -07002304 }
Vikram Aggarwalb8c31712013-01-03 17:03:19 -08002305 /*
Mindy Pereira967ede62012-03-22 09:29:09 -07002306 * Restore the state of selected conversations. This needs to be done after the correct mode
2307 * is set and the action bar is fully initialized. If not, several key pieces of state
2308 * information will be missing, and the split views may not be initialized correctly.
Mindy Pereira967ede62012-03-22 09:29:09 -07002309 */
Andy Huang4556a442012-03-30 16:42:05 -07002310 restoreSelectedConversations(savedState);
Vikram Aggarwalb8c31712013-01-03 17:03:19 -08002311 // Order is important!!!
2312 // The dialog listener needs to happen *after* the selected set is restored.
2313
2314 // If there has been an orientation change, and we need to recreate the listener for the
2315 // confirm dialog fragment (delete/archive/...), then do it here.
2316 if (mDialogAction != -1) {
2317 makeDialogListener(mDialogAction, mDialogFromSelectedSet);
2318 }
Alice Yangebeef1b2013-09-04 06:41:10 +00002319
2320 mInbox = savedState.getParcelable(SAVED_INBOX_KEY);
Scott Kennedyf77806e2013-08-30 11:38:15 -07002321
2322 mConversationListScrollPositions.clear();
2323 mConversationListScrollPositions.putAll(
2324 savedState.getBundle(SAVED_CONVERSATION_LIST_SCROLL_POSITIONS));
Andy Huang632721e2012-04-11 16:57:26 -07002325 }
2326
Vikram Aggarwal649b9ea2012-08-27 12:15:20 -07002327 /**
2328 * Handle an intent to open the app. This method is called only when there is no saved state,
2329 * so we need to set state that wasn't set before. It is correct to change the viewmode here
2330 * since it has not been previously set.
Vikram Aggarwal6aca6892013-06-04 13:53:27 -07002331 *
2332 * This method is called for a subset of the reasons mentioned in
2333 * {@link #onCreate(android.os.Bundle)}. Notably, this is called when launching the app from
2334 * notifications, widgets, and shortcuts.
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08002335 * @param intent intent passed to the activity.
Vikram Aggarwal649b9ea2012-08-27 12:15:20 -07002336 */
Andy Huang632721e2012-04-11 16:57:26 -07002337 private void handleIntent(Intent intent) {
Andy Huange6459422013-04-01 16:32:18 -07002338 LogUtils.d(LOG_TAG, "IN AAC.handleIntent. action=%s", intent.getAction());
Andy Huang632721e2012-04-11 16:57:26 -07002339 if (Intent.ACTION_VIEW.equals(intent.getAction())) {
2340 if (intent.hasExtra(Utils.EXTRA_ACCOUNT)) {
Tony Mantler26a20752014-02-28 16:44:24 -08002341 setAccount(Account.newInstance(intent.getStringExtra(Utils.EXTRA_ACCOUNT)));
Andy Huang632721e2012-04-11 16:57:26 -07002342 }
Andy Huangb9ca9792012-05-18 15:31:49 -07002343 if (mAccount == null) {
2344 return;
Andy Huang632721e2012-04-11 16:57:26 -07002345 }
Vikram Aggarwal1a249e02012-08-03 16:19:33 -07002346 final boolean isConversationMode = intent.hasExtra(Utils.EXTRA_CONVERSATION);
Andy Huang4fe0af82013-08-20 17:24:51 -07002347
2348 if (intent.getBooleanExtra(Utils.EXTRA_FROM_NOTIFICATION, false)) {
2349 Analytics.getInstance().setCustomDimension(Analytics.CD_INDEX_ACCOUNT_TYPE,
Tony Mantler79b11562013-10-09 15:31:50 -07002350 AnalyticsUtils.getAccountTypeForAccount(mAccount.getEmailAddress()));
Andy Huang4fe0af82013-08-20 17:24:51 -07002351 Analytics.getInstance().sendEvent("notification_click",
2352 isConversationMode ? "conversation" : "conversation_list", null, 0);
2353 }
2354
Vikram Aggarwal649b9ea2012-08-27 12:15:20 -07002355 if (isConversationMode && mViewMode.getMode() == ViewMode.UNKNOWN) {
Vikram Aggarwal1a249e02012-08-03 16:19:33 -07002356 mViewMode.enterConversationMode();
2357 } else {
2358 mViewMode.enterConversationListMode();
2359 }
Vikram Aggarwal177097f2013-03-08 11:19:53 -08002360 // Put the folder and conversation, and ask the loader to create this folder.
2361 final Bundle args = new Bundle();
Scott Kennedy48cfe462013-04-10 11:32:02 -07002362
2363 final Uri folderUri;
2364 if (intent.hasExtra(Utils.EXTRA_FOLDER_URI)) {
Andrew Sapperstein5bb4d052014-03-31 16:22:31 -07002365 folderUri = intent.getParcelableExtra(Utils.EXTRA_FOLDER_URI);
Scott Kennedy48cfe462013-04-10 11:32:02 -07002366 } else if (intent.hasExtra(Utils.EXTRA_FOLDER)) {
2367 final Folder folder =
2368 Folder.fromString(intent.getStringExtra(Utils.EXTRA_FOLDER));
Scott Kennedy259df5b2013-07-11 13:24:01 -07002369 folderUri = folder.folderUri.fullUri;
Scott Kennedy48cfe462013-04-10 11:32:02 -07002370 } else {
Scott Kennedy72727ef2013-05-01 18:10:55 -07002371 final Bundle extras = intent.getExtras();
2372 LogUtils.d(LOG_TAG, "Couldn't find a folder URI in the extras: %s",
2373 extras == null ? "null" : extras.toString());
Scott Kennedy48cfe462013-04-10 11:32:02 -07002374 folderUri = mAccount.settings.defaultInbox;
2375 }
2376
Andrew Sapperstein5bb4d052014-03-31 16:22:31 -07002377 // Check if we should load all conversations instead of using
2378 // the default behavior which loads an initial subset.
2379 mIgnoreInitialConversationLimit =
2380 intent.getBooleanExtra(Utils.EXTRA_IGNORE_INITIAL_CONVERSATION_LIMIT, false);
2381
Scott Kennedy60593352013-03-13 13:45:30 -07002382 args.putParcelable(Utils.EXTRA_FOLDER_URI, folderUri);
Vikram Aggarwal177097f2013-03-08 11:19:53 -08002383 args.putParcelable(Utils.EXTRA_CONVERSATION,
2384 intent.getParcelableExtra(Utils.EXTRA_CONVERSATION));
2385 restartOptionalLoader(LOADER_FIRST_FOLDER, mFolderCallbacks, args);
Andy Huang632721e2012-04-11 16:57:26 -07002386 } else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
2387 if (intent.hasExtra(Utils.EXTRA_ACCOUNT)) {
Vikram Aggarwalf0ef2302012-11-07 14:53:34 -08002388 mHaveSearchResults = false;
Andy Huang632721e2012-04-11 16:57:26 -07002389 // Save this search query for future suggestions.
2390 final String query = intent.getStringExtra(SearchManager.QUERY);
2391 final String authority = mContext.getString(R.string.suggestions_authority);
Vikram Aggarwal2b703c62012-09-18 13:54:15 -07002392 final SearchRecentSuggestions suggestions = new SearchRecentSuggestions(
Andy Huang632721e2012-04-11 16:57:26 -07002393 mContext, authority, SuggestionsProvider.MODE);
2394 suggestions.saveRecentQuery(query, null);
Vikram Aggarwalf0ef2302012-11-07 14:53:34 -08002395 setAccount((Account) intent.getParcelableExtra(Utils.EXTRA_ACCOUNT));
2396 fetchSearchFolder(intent);
2397 if (shouldEnterSearchConvMode()) {
Mindy Pereiraac254822012-06-18 10:46:43 -07002398 mViewMode.enterSearchResultsConversationMode();
2399 } else {
2400 mViewMode.enterSearchResultsListMode();
2401 }
Andy Huang632721e2012-04-11 16:57:26 -07002402 } else {
2403 LogUtils.e(LOG_TAG, "Missing account extra from search intent. Finishing");
2404 mActivity.finish();
2405 }
2406 }
2407 if (mAccount != null) {
Vikram Aggarwal177097f2013-03-08 11:19:53 -08002408 restartOptionalLoader(LOADER_ACCOUNT_UPDATE_CURSOR, mAccountCallbacks, Bundle.EMPTY);
Scott Kennedyb39aaf52013-03-06 19:17:22 -08002409 }
2410 }
2411
Andy Huang4556a442012-03-30 16:42:05 -07002412 /**
Vikram Aggarwalf0ef2302012-11-07 14:53:34 -08002413 * Returns true if we should enter conversation mode with search.
2414 */
2415 protected final boolean shouldEnterSearchConvMode() {
2416 return mHaveSearchResults && Utils.showTwoPaneSearchResults(mActivity.getActivityContext());
2417 }
2418
2419 /**
Andy Huang4556a442012-03-30 16:42:05 -07002420 * Copy any selected conversations stored in the saved bundle into our selection set,
2421 * triggering {@link ConversationSetObserver} callbacks as our selection set changes.
2422 *
2423 */
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08002424 private void restoreSelectedConversations(Bundle savedState) {
Mindy Pereira967ede62012-03-22 09:29:09 -07002425 if (savedState == null) {
Andy Huang4556a442012-03-30 16:42:05 -07002426 mSelectedSet.clear();
Mindy Pereira967ede62012-03-22 09:29:09 -07002427 return;
2428 }
Vikram Aggarwalcabd3f22012-04-19 10:14:41 -07002429 final ConversationSelectionSet selectedSet = savedState.getParcelable(SAVED_SELECTED_SET);
Andy Huang4556a442012-03-30 16:42:05 -07002430 if (selectedSet == null || selectedSet.isEmpty()) {
2431 mSelectedSet.clear();
Mindy Pereira967ede62012-03-22 09:29:09 -07002432 return;
2433 }
Andy Huang632721e2012-04-11 16:57:26 -07002434
2435 // putAll will take care of calling our registered onSetPopulated method
Vikram Aggarwalcabd3f22012-04-19 10:14:41 -07002436 mSelectedSet.putAll(selectedSet);
Mindy Pereira967ede62012-03-22 09:29:09 -07002437 }
2438
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08002439 private void showConversation(Conversation conversation) {
Andy Huang1ee96b22012-08-24 20:19:53 -07002440 showConversation(conversation, false /* inLoaderCallbacks */);
2441 }
2442
Vikram Aggarwalec5cbf72012-03-08 15:10:35 -08002443 /**
Vikram Aggarwal49e0e992012-09-21 13:53:15 -07002444 * Show the conversation provided in the arguments. It is safe to pass a null conversation
2445 * object, which is a signal to back out of conversation view mode.
2446 * Child classes must call super.showConversation() <b>before</b> their own implementations.
Vikram Aggarwal59f741f2013-03-01 15:55:40 -08002447 * @param conversation the conversation to be shown, or null if we want to back out to list
2448 * mode.
Vikram Aggarwal49e0e992012-09-21 13:53:15 -07002449 * @param inLoaderCallbacks true if the method is called as a result of
Vikram Aggarwal177097f2013-03-08 11:19:53 -08002450 * onLoadFinished(Loader, Cursor) on any callback.
Vikram Aggarwalec5cbf72012-03-08 15:10:35 -08002451 */
Andy Huang1ee96b22012-08-24 20:19:53 -07002452 protected void showConversation(Conversation conversation, boolean inLoaderCallbacks) {
Andy Huang243c2362013-03-01 17:50:35 -08002453 if (conversation != null) {
2454 Utils.sConvLoadTimer.start();
2455 }
2456
Andy Huang54e925e2013-03-14 13:24:18 -07002457 MailLogService.log("AbstractActivityController", "showConversation(%s)", conversation);
Vikram Aggarwalc67182d2012-04-03 14:35:06 -07002458 // Set the current conversation just in case it wasn't already set.
2459 setCurrentConversation(conversation);
Vikram Aggarwalec5cbf72012-03-08 15:10:35 -08002460 }
2461
Vikram Aggarwale128fc22012-04-04 12:33:34 -07002462 /**
Paul Westbrook2d50bcd2012-04-10 11:53:47 -07002463 * Children can override this method, but they must call super.showWaitForInitialization().
2464 * {@inheritDoc}
2465 */
2466 @Override
2467 public void showWaitForInitialization() {
2468 mViewMode.enterWaitingForInitializationMode();
Andy Huangc96efcc2014-04-09 15:30:42 -07002469 mWaitFragment = WaitFragment.newInstance(mAccount, true /* expectingMessages */);
Paul Westbrook2d50bcd2012-04-10 11:53:47 -07002470 }
2471
Vikram Aggarwaldd6a7ce2012-10-22 15:45:57 -07002472 private void updateWaitMode() {
Paul Westbrook2d50bcd2012-04-10 11:53:47 -07002473 final FragmentManager manager = mActivity.getFragmentManager();
2474 final WaitFragment waitFragment =
Vikram Aggarwal6902dcf2012-04-11 08:57:42 -07002475 (WaitFragment)manager.findFragmentByTag(TAG_WAIT);
Paul Westbrook2d50bcd2012-04-10 11:53:47 -07002476 if (waitFragment != null) {
2477 waitFragment.updateAccount(mAccount);
2478 }
2479 }
2480
Vikram Aggarwala3f43d42012-10-25 16:21:30 -07002481 /**
2482 * Remove the "Waiting for Initialization" fragment. Child classes are free to override this
2483 * method, though they must call the parent implementation <b>after</b> they do anything.
2484 */
2485 protected void hideWaitForInitialization() {
2486 mWaitFragment = null;
2487 }
2488
2489 /**
2490 * Use the instance variable and the wait fragment's tag to get the wait fragment. This is
2491 * far superior to using the value of mWaitFragment, which might be invalid or might refer
2492 * to a fragment after it has been destroyed.
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08002493 * @return a wait fragment that is already attached to the activity, if one exists
Vikram Aggarwala3f43d42012-10-25 16:21:30 -07002494 */
2495 protected final WaitFragment getWaitFragment() {
2496 final FragmentManager manager = mActivity.getFragmentManager();
2497 final WaitFragment waitFrag = (WaitFragment) manager.findFragmentByTag(TAG_WAIT);
2498 if (waitFrag != null) {
2499 // The Fragment Manager knows better, so use its instance.
2500 mWaitFragment = waitFrag;
2501 }
2502 return mWaitFragment;
2503 }
Vikram Aggarwaldd6a7ce2012-10-22 15:45:57 -07002504
Vikram Aggarwal48b2a6c2012-05-29 14:09:27 -07002505 /**
2506 * Returns true if we are waiting for the account to sync, and cannot show any folders or
2507 * conversation for the current account yet.
Vikram Aggarwal48b2a6c2012-05-29 14:09:27 -07002508 */
Vikram Aggarwaldd6a7ce2012-10-22 15:45:57 -07002509 private boolean inWaitMode() {
Vikram Aggarwala3f43d42012-10-25 16:21:30 -07002510 final WaitFragment waitFragment = getWaitFragment();
Paul Westbrook2d50bcd2012-04-10 11:53:47 -07002511 if (waitFragment != null) {
2512 final Account fragmentAccount = waitFragment.getAccount();
Paul Westbrook339004b2012-11-05 17:13:51 -08002513 return fragmentAccount != null && fragmentAccount.uri.equals(mAccount.uri) &&
Paul Westbrook2d50bcd2012-04-10 11:53:47 -07002514 mViewMode.getMode() == ViewMode.WAITING_FOR_ACCOUNT_INITIALIZATION;
2515 }
2516 return false;
2517 }
2518
2519 /**
Vikram Aggarwale128fc22012-04-04 12:33:34 -07002520 * Children can override this method, but they must call super.showConversationList().
2521 * {@inheritDoc}
2522 */
2523 @Override
2524 public void showConversationList(ConversationListContext listContext) {
2525 }
2526
Vikram Aggarwal1ddcf0f2012-01-13 11:45:02 -08002527 @Override
Vikram Aggarwal17f373e2012-09-17 15:49:32 -07002528 public final void onConversationSelected(Conversation conversation, boolean inLoaderCallbacks) {
Alice Yangfe8e0812013-04-22 13:37:26 -07002529 final ConversationListFragment convListFragment = getConversationListFragment();
2530 if (convListFragment != null && convListFragment.getAnimatedAdapter() != null) {
2531 convListFragment.getAnimatedAdapter().onConversationSelected();
2532 }
mindypaa55bc92012-08-24 09:49:56 -07002533 // Only animate destructive actions if we are going to be showing the
2534 // conversation list when we show the next conversation.
Vikram Aggarwalbcb16b92013-01-28 18:05:03 -08002535 commitDestructiveActions(mIsTablet);
Andy Huang1ee96b22012-08-24 20:19:53 -07002536 showConversation(conversation, inLoaderCallbacks);
2537 }
2538
2539 @Override
Andrew Sapperstein2f542872013-06-11 10:48:30 -07002540 public final void onCabModeEntered() {
2541 final ConversationListFragment convListFragment = getConversationListFragment();
2542 if (convListFragment != null && convListFragment.getAnimatedAdapter() != null) {
2543 convListFragment.getAnimatedAdapter().onCabModeEntered();
2544 }
2545 }
2546
2547 @Override
Scott Kennedycc139832013-08-19 18:03:54 -07002548 public final void onCabModeExited() {
2549 final ConversationListFragment convListFragment = getConversationListFragment();
2550 if (convListFragment != null && convListFragment.getAnimatedAdapter() != null) {
2551 convListFragment.getAnimatedAdapter().onCabModeExited();
2552 }
2553 }
2554
2555 @Override
Andy Huang1ee96b22012-08-24 20:19:53 -07002556 public Conversation getCurrentConversation() {
2557 return mCurrentConversation;
Vikram Aggarwal7d602882012-02-07 15:01:20 -08002558 }
Mindy Pereira555140c2012-02-15 14:55:29 -08002559
Vikram Aggarwalc67182d2012-04-03 14:35:06 -07002560 /**
2561 * Set the current conversation. This is the conversation on which all actions are performed.
2562 * Do not modify mCurrentConversation except through this method, which makes it easy to
2563 * perform common actions associated with changing the current conversation.
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08002564 * @param conversation new conversation to view. Passing null indicates that we are backing
2565 * out to conversation list mode.
Vikram Aggarwalc67182d2012-04-03 14:35:06 -07002566 */
Andy Huang632721e2012-04-11 16:57:26 -07002567 @Override
2568 public void setCurrentConversation(Conversation conversation) {
Vikram Aggarwala91d00b2013-01-18 12:00:37 -08002569 // The controller should come out of detached mode if a new conversation is viewed, or if
Vikram Aggarwal81230ee2013-02-26 15:26:44 -08002570 // we are going back to conversation list mode.
2571 if (mDetachedConvUri != null && (conversation == null
2572 || !mDetachedConvUri.equals(conversation.uri))) {
Vikram Aggarwala91d00b2013-01-18 12:00:37 -08002573 clearDetachedMode();
2574 }
2575
2576 // Must happen *before* setting mCurrentConversation because this sets
2577 // conversation.position if a cursor is available.
Andy Huang8883f222012-11-12 19:25:00 -08002578 mTracker.initialize(conversation);
Vikram Aggarwal17f373e2012-09-17 15:49:32 -07002579 mCurrentConversation = conversation;
Andy Huang7d646122012-09-05 19:41:44 -07002580
2581 if (mCurrentConversation != null) {
Yorke Leef807ba72012-09-20 17:18:05 -07002582 mActionBarView.setCurrentConversation(mCurrentConversation);
Yorke Leef807ba72012-09-20 17:18:05 -07002583 mActivity.invalidateOptionsMenu();
Andy Huang7d646122012-09-05 19:41:44 -07002584 }
Mindy Pereira5040f1a2012-03-20 10:14:06 -07002585 }
2586
Vikram Aggarwala9b93f32012-02-23 14:51:58 -08002587 /**
Andy Huangf9a73482012-03-13 15:54:02 -07002588 * {@link LoaderManager} currently has a bug in
2589 * {@link LoaderManager#restartLoader(int, Bundle, android.app.LoaderManager.LoaderCallbacks)}
2590 * where, if a previous onCreateLoader returned a null loader, this method will NPE. Work around
2591 * this bug by destroying any loaders that may have been created as null (essentially because
2592 * they are optional loads, and may not apply to a particular account).
2593 * <p>
2594 * A simple null check before restarting a loader will not work, because that would not
2595 * give the controller a chance to invalidate UI corresponding the prior loader result.
2596 *
2597 * @param id loader ID to safely restart
Vikram Aggarwal177097f2013-03-08 11:19:53 -08002598 * @param handler the LoaderCallback which will handle this loader ID.
2599 * @param args arguments, if any, to be passed to the loader. Use {@link Bundle#EMPTY} if no
2600 * arguments need to be specified.
Andy Huangf9a73482012-03-13 15:54:02 -07002601 */
Vikram Aggarwal177097f2013-03-08 11:19:53 -08002602 private void restartOptionalLoader(int id, LoaderManager.LoaderCallbacks handler, Bundle args) {
Andy Huangf9a73482012-03-13 15:54:02 -07002603 final LoaderManager lm = mActivity.getLoaderManager();
2604 lm.destroyLoader(id);
Vikram Aggarwal177097f2013-03-08 11:19:53 -08002605 lm.restartLoader(id, args, handler);
Vikram Aggarwal94c94de2012-04-04 15:38:28 -07002606 }
2607
Andy Huang632721e2012-04-11 16:57:26 -07002608 @Override
2609 public void registerConversationListObserver(DataSetObserver observer) {
2610 mConversationListObservable.registerObserver(observer);
2611 }
2612
2613 @Override
2614 public void unregisterConversationListObserver(DataSetObserver observer) {
Alice Yang647aefb2013-03-04 19:13:11 -08002615 try {
2616 mConversationListObservable.unregisterObserver(observer);
2617 } catch (IllegalStateException e) {
2618 // Log instead of crash
2619 LogUtils.e(LOG_TAG, e, "unregisterConversationListObserver called for an observer that "
2620 + "hasn't been registered");
2621 }
Andy Huang632721e2012-04-11 16:57:26 -07002622 }
2623
Andy Huang090db1e2012-07-25 13:25:28 -07002624 @Override
2625 public void registerFolderObserver(DataSetObserver observer) {
2626 mFolderObservable.registerObserver(observer);
2627 }
2628
2629 @Override
2630 public void unregisterFolderObserver(DataSetObserver observer) {
Alice Yang647aefb2013-03-04 19:13:11 -08002631 try {
2632 mFolderObservable.unregisterObserver(observer);
2633 } catch (IllegalStateException e) {
2634 // Log instead of crash
2635 LogUtils.e(LOG_TAG, e, "unregisterFolderObserver called for an observer that "
2636 + "hasn't been registered");
2637 }
Andy Huang090db1e2012-07-25 13:25:28 -07002638 }
2639
Andy Huang9d3fd922012-09-26 22:23:58 -07002640 @Override
2641 public void registerConversationLoadedObserver(DataSetObserver observer) {
2642 mPagerController.registerConversationLoadedObserver(observer);
2643 }
2644
2645 @Override
2646 public void unregisterConversationLoadedObserver(DataSetObserver observer) {
Alice Yang647aefb2013-03-04 19:13:11 -08002647 try {
2648 mPagerController.unregisterConversationLoadedObserver(observer);
2649 } catch (IllegalStateException e) {
2650 // Log instead of crash
2651 LogUtils.e(LOG_TAG, e, "unregisterConversationLoadedObserver called for an observer "
2652 + "that hasn't been registered");
2653 }
Andy Huang9d3fd922012-09-26 22:23:58 -07002654 }
2655
Vikram Aggarwal60069912012-07-24 14:26:09 -07002656 /**
Vikram Aggarwalc04cf7e2013-05-13 15:38:42 -07002657 * Returns true if the number of accounts is different, or if the current account has
2658 * changed. This method is meant to filter frequent changes to the list of
2659 * accounts, and only return true if the new list is substantially different from the existing
2660 * list. Returning true is safe here, it leads to more work in creating the
2661 * same account list again.
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08002662 * @param accountCursor the cursor which points to all the accounts.
2663 * @return true if the number of accounts is changed or current account missing from the list.
Vikram Aggarwal60069912012-07-24 14:26:09 -07002664 */
Vikram Aggarwal177097f2013-03-08 11:19:53 -08002665 private boolean accountsUpdated(ObjectCursor<Account> accountCursor) {
Paul Westbrook23b74b92012-02-29 11:36:12 -08002666 // Check to see if the current account hasn't been set, or the account cursor is empty
2667 if (mAccount == null || !accountCursor.moveToFirst()) {
Vikram Aggarwal6c511582012-02-27 10:59:47 -08002668 return true;
Paul Westbrook23b74b92012-02-29 11:36:12 -08002669 }
2670
2671 // Check to see if the number of accounts are different, from the number we saw on the last
2672 // updated
2673 if (mCurrentAccountUris.size() != accountCursor.getCount()) {
2674 return true;
2675 }
2676
2677 // Check to see if the account list is different or if the current account is not found in
2678 // the cursor.
2679 boolean foundCurrentAccount = false;
Vikram Aggarwal7dedb952012-02-16 16:10:23 -08002680 do {
Vikram Aggarwalc04cf7e2013-05-13 15:38:42 -07002681 final Account account = accountCursor.getModel();
2682 if (!foundCurrentAccount && mAccount.uri.equals(account.uri)) {
2683 if (mAccount.settingsDiffer(account)) {
2684 // Settings changed, and we don't need to look any further.
2685 return true;
2686 }
Paul Westbrook23b74b92012-02-29 11:36:12 -08002687 foundCurrentAccount = true;
2688 }
Vikram Aggarwal60069912012-07-24 14:26:09 -07002689 // Is there a new account that we do not know about?
Vikram Aggarwalc04cf7e2013-05-13 15:38:42 -07002690 if (!mCurrentAccountUris.contains(account.uri)) {
Paul Westbrook23b74b92012-02-29 11:36:12 -08002691 return true;
2692 }
Vikram Aggarwal7dedb952012-02-16 16:10:23 -08002693 } while (accountCursor.moveToNext());
Paul Westbrook23b74b92012-02-29 11:36:12 -08002694
2695 // As long as we found the current account, the list hasn't been updated
2696 return !foundCurrentAccount;
Vikram Aggarwal7dedb952012-02-16 16:10:23 -08002697 }
2698
2699 /**
Vikram Aggarwal60069912012-07-24 14:26:09 -07002700 * Updates accounts for the app. If the current account is missing, the first
2701 * account in the list is set to the current account (we <em>have</em> to choose something).
Mindy Pereira161f50d2012-02-28 15:47:19 -08002702 *
Vikram Aggarwal6c511582012-02-27 10:59:47 -08002703 * @param accounts cursor into the AccountCache
Vikram Aggarwal7dedb952012-02-16 16:10:23 -08002704 * @return true if the update was successful, false otherwise
2705 */
Vikram Aggarwal177097f2013-03-08 11:19:53 -08002706 private boolean updateAccounts(ObjectCursor<Account> accounts) {
Vikram Aggarwal7dedb952012-02-16 16:10:23 -08002707 if (accounts == null || !accounts.moveToFirst()) {
2708 return false;
2709 }
Paul Westbrook23b74b92012-02-29 11:36:12 -08002710
Vikram Aggarwala9b93f32012-02-23 14:51:58 -08002711 final Account[] allAccounts = Account.getAllAccounts(accounts);
Vikram Aggarwal60069912012-07-24 14:26:09 -07002712 // A match for the current account's URI in the list of accounts.
2713 Account currentFromList = null;
Paul Westbrook23b74b92012-02-29 11:36:12 -08002714
Vikram Aggarwal636c1a12012-09-22 16:02:40 -07002715 // Save the uris for the accounts and find the current account in the updated cursor.
Paul Westbrook23b74b92012-02-29 11:36:12 -08002716 mCurrentAccountUris.clear();
Vikram Aggarwal636c1a12012-09-22 16:02:40 -07002717 for (final Account account : allAccounts) {
Vikram Aggarwal60069912012-07-24 14:26:09 -07002718 LogUtils.d(LOG_TAG, "updateAccounts(%s)", account);
Paul Westbrook23b74b92012-02-29 11:36:12 -08002719 mCurrentAccountUris.add(account.uri);
Vikram Aggarwal60069912012-07-24 14:26:09 -07002720 if (mAccount != null && account.uri.equals(mAccount.uri)) {
2721 currentFromList = account;
2722 }
Paul Westbrook23b74b92012-02-29 11:36:12 -08002723 }
2724
Vikram Aggarwal60069912012-07-24 14:26:09 -07002725 // 1. current account is already set and is in allAccounts:
2726 // 1a. It has changed -> load the updated account.
2727 // 2b. It is unchanged -> no-op
Andy Huang0d647352012-03-21 21:48:16 -07002728 // 2. current account is set and is not in allAccounts -> pick first (acct was deleted?)
Vikram Aggarwal60069912012-07-24 14:26:09 -07002729 // 3. saved preference has an account -> pick that one
Andy Huang0d647352012-03-21 21:48:16 -07002730 // 4. otherwise just pick first
2731
Vikram Aggarwal60069912012-07-24 14:26:09 -07002732 boolean accountChanged = false;
2733 /// Assume case 4, initialize to first account, and see if we can find anything better.
2734 Account newAccount = allAccounts[0];
2735 if (currentFromList != null) {
2736 // Case 1: Current account exists but has changed
2737 if (!currentFromList.equals(mAccount)) {
2738 newAccount = currentFromList;
2739 accountChanged = true;
Andy Huang0d647352012-03-21 21:48:16 -07002740 }
Vikram Aggarwal60069912012-07-24 14:26:09 -07002741 // Case 1b: else, current account is unchanged: nothing to do.
Paul Westbrook23b74b92012-02-29 11:36:12 -08002742 } else {
Vikram Aggarwal60069912012-07-24 14:26:09 -07002743 // Case 2: Current account is not in allAccounts, the account needs to change.
2744 accountChanged = true;
2745 if (mAccount == null) {
2746 // Case 3: Check for last viewed account, and check if it exists in the list.
2747 final String lastAccountUri = MailAppProvider.getInstance().getLastViewedAccount();
2748 if (lastAccountUri != null) {
2749 for (final Account account : allAccounts) {
2750 if (lastAccountUri.equals(account.uri.toString())) {
2751 newAccount = account;
2752 break;
2753 }
Andy Huang0d647352012-03-21 21:48:16 -07002754 }
2755 }
2756 }
Paul Westbrook23b74b92012-02-29 11:36:12 -08002757 }
Vikram Aggarwal60069912012-07-24 14:26:09 -07002758 if (accountChanged) {
Vikram Aggarwal5fd8afd2013-03-13 15:28:47 -07002759 changeAccount(newAccount);
Vikram Aggarwal60069912012-07-24 14:26:09 -07002760 }
Vikram Aggarwal07dbaa62013-03-12 15:21:04 -07002761
Vikram Aggarwal60069912012-07-24 14:26:09 -07002762 // Whether we have updated the current account or not, we need to update the list of
2763 // accounts in the ActionBar.
Rohan Shahb905f0e2013-04-26 09:17:37 -07002764 mAllAccounts = allAccounts;
Vikram Aggarwal07dbaa62013-03-12 15:21:04 -07002765 mAllAccountObservers.notifyChanged();
Vikram Aggarwala9b93f32012-02-23 14:51:58 -08002766 return (allAccounts.length > 0);
Vikram Aggarwal7dedb952012-02-16 16:10:23 -08002767 }
2768
Paul Westbrook6ead20d2012-03-19 14:48:14 -07002769 private void disableNotifications() {
2770 mNewEmailReceiver.activate(mContext, this);
2771 }
2772
2773 private void enableNotifications() {
2774 mNewEmailReceiver.deactivate();
2775 }
2776
2777 private void disableNotificationsOnAccountChange(Account account) {
2778 // If the new mail suppression receiver is activated for a different account, we want to
2779 // activate it for the new account.
2780 if (mNewEmailReceiver.activated() &&
2781 !mNewEmailReceiver.notificationsDisabledForAccount(account)) {
2782 // Deactivate the current receiver, otherwise multiple receivers may be registered.
2783 mNewEmailReceiver.deactivate();
2784 mNewEmailReceiver.activate(mContext, this);
2785 }
2786 }
2787
Vikram Aggarwala9b93f32012-02-23 14:51:58 -08002788 /**
Vikram Aggarwalc7694222012-04-23 13:37:01 -07002789 * Destructive actions on Conversations. This class should only be created by controllers, and
2790 * clients should only require {@link DestructiveAction}s, not specific implementations of the.
2791 * Only the controllers should know what kind of destructive actions are being created.
2792 */
Mindy Pereirade3e74a2012-07-24 09:43:10 -07002793 public class ConversationAction implements DestructiveAction {
Vikram Aggarwalacaa3c02012-04-24 12:45:27 -07002794 /**
2795 * The action to be performed. This is specified as the resource ID of the menu item
2796 * corresponding to this action: R.id.delete, R.id.report_spam, etc.
2797 */
Vikram Aggarwal7f602f72012-04-30 16:04:06 -07002798 private final int mAction;
Vikram Aggarwalbc67bb12012-04-30 14:05:35 -07002799 /** The action will act upon these conversations */
Paul Westbrook77eee622012-07-10 13:41:57 -07002800 private final Collection<Conversation> mTarget;
Vikram Aggarwal7f602f72012-04-30 16:04:06 -07002801 /** Whether this destructive action has already been performed */
2802 private boolean mCompleted;
Vikram Aggarwalc4113952012-05-11 14:14:56 -07002803 /** Whether this is an action on the currently selected set. */
2804 private final boolean mIsSelectedSet;
Vikram Aggarwale8a85322012-04-24 09:01:38 -07002805
Mindy Pereirafbe40192012-03-20 10:40:45 -07002806 /**
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08002807 * Create a listener object.
2808 * @param action action is one of four constants: R.id.y_button (archive),
Mindy Pereirafbe40192012-03-20 10:40:45 -07002809 * R.id.delete , R.id.mute, and R.id.report_spam.
Vikram Aggarwalbc67bb12012-04-30 14:05:35 -07002810 * @param target Conversation that we want to apply the action to.
Vikram Aggarwalc4113952012-05-11 14:14:56 -07002811 * @param isBatch whether the conversations are in the currently selected batch set.
2812 */
2813 public ConversationAction(int action, Collection<Conversation> target, boolean isBatch) {
Mindy Pereirafbe40192012-03-20 10:40:45 -07002814 mAction = action;
Paul Westbrook77eee622012-07-10 13:41:57 -07002815 mTarget = ImmutableList.copyOf(target);
Vikram Aggarwalc4113952012-05-11 14:14:56 -07002816 mIsSelectedSet = isBatch;
Mindy Pereirafbe40192012-03-20 10:40:45 -07002817 }
2818
Vikram Aggarwalacaa3c02012-04-24 12:45:27 -07002819 /**
2820 * The action common to child classes. This performs the action specified in the constructor
2821 * on the conversations given here.
Vikram Aggarwalacaa3c02012-04-24 12:45:27 -07002822 */
Vikram Aggarwalbc67bb12012-04-30 14:05:35 -07002823 @Override
2824 public void performAction() {
Vikram Aggarwal7f602f72012-04-30 16:04:06 -07002825 if (isPerformed()) {
2826 return;
2827 }
Mindy Pereira3cb28b52012-05-24 15:26:39 -07002828 boolean undoEnabled = mAccount.supportsCapability(AccountCapabilities.UNDO);
Vikram Aggarwal7dd054e2012-05-21 14:43:10 -07002829
2830 // Are we destroying the currently shown conversation? Show the next one.
2831 if (LogUtils.isLoggable(LOG_TAG, LogUtils.DEBUG)){
Vikram Aggarwal8742a612012-08-13 10:22:50 -07002832 LogUtils.d(LOG_TAG, "ConversationAction.performAction():"
2833 + "\nmTarget=%s\nCurrent=%s",
Vikram Aggarwal7dd054e2012-05-21 14:43:10 -07002834 Conversation.toString(mTarget), mCurrentConversation);
2835 }
Vikram Aggarwal7dd054e2012-05-21 14:43:10 -07002836
Paul Westbrooke1221d22012-08-19 11:09:07 -07002837 if (mConversationListCursor == null) {
2838 LogUtils.e(LOG_TAG, "null ConversationCursor in ConversationAction.performAction():"
2839 + "\nmTarget=%s\nCurrent=%s",
2840 Conversation.toString(mTarget), mCurrentConversation);
2841 return;
2842 }
2843
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002844 if (mAction == R.id.archive) {
2845 LogUtils.d(LOG_TAG, "Archiving");
2846 mConversationListCursor.archive(mTarget);
2847 } else if (mAction == R.id.delete) {
2848 LogUtils.d(LOG_TAG, "Deleting");
2849 mConversationListCursor.delete(mTarget);
2850 if (mFolder.supportsCapability(FolderCapabilities.DELETE_ACTION_FINAL)) {
Paul Westbrookef362542012-08-27 14:53:32 -07002851 undoEnabled = false;
Scott Kennedy2b9d80e2013-07-30 23:03:45 -07002852 }
2853 } else if (mAction == R.id.mute) {
2854 LogUtils.d(LOG_TAG, "Muting");
2855 if (mFolder.supportsCapability(FolderCapabilities.DESTRUCTIVE_MUTE)) {
2856 for (Conversation c : mTarget) {
2857 c.localDeleteOnUpdate = true;
2858 }
2859 }
2860 mConversationListCursor.mute(mTarget);
2861 } else if (mAction == R.id.report_spam) {
2862 LogUtils.d(LOG_TAG, "Reporting spam");
2863 mConversationListCursor.reportSpam(mTarget);
2864 } else if (mAction == R.id.mark_not_spam) {
2865 LogUtils.d(LOG_TAG, "Marking not spam");
2866 mConversationListCursor.reportNotSpam(mTarget);
2867 } else if (mAction == R.id.report_phishing) {
2868 LogUtils.d(LOG_TAG, "Reporting phishing");
2869 mConversationListCursor.reportPhishing(mTarget);
2870 } else if (mAction == R.id.remove_star) {
2871 LogUtils.d(LOG_TAG, "Removing star");
2872 // Star removal is destructive in the Starred folder.
2873 mConversationListCursor.updateBoolean(mTarget, ConversationColumns.STARRED,
2874 false);
2875 } else if (mAction == R.id.mark_not_important) {
2876 LogUtils.d(LOG_TAG, "Marking not-important");
2877 // Marking not important is destructive in a mailbox
2878 // containing only important messages
2879 if (mFolder != null && mFolder.isImportantOnly()) {
2880 for (Conversation conv : mTarget) {
2881 conv.localDeleteOnUpdate = true;
2882 }
2883 }
2884 mConversationListCursor.updateInt(mTarget, ConversationColumns.PRIORITY,
2885 UIProvider.ConversationPriority.LOW);
2886 } else if (mAction == R.id.discard_drafts) {
2887 LogUtils.d(LOG_TAG, "Discarding draft messages");
2888 // Discarding draft messages is destructive in a "draft" mailbox
2889 if (mFolder != null && mFolder.isDraft()) {
2890 for (Conversation conv : mTarget) {
2891 conv.localDeleteOnUpdate = true;
2892 }
2893 }
2894 mConversationListCursor.discardDrafts(mTarget);
2895 // We don't support undoing discarding drafts
2896 undoEnabled = false;
Vikram Aggarwal3d7ca9d2012-05-11 14:40:36 -07002897 }
2898 if (undoEnabled) {
mindypead50392012-08-23 11:03:53 -07002899 mHandler.postDelayed(new Runnable() {
2900 @Override
2901 public void run() {
2902 onUndoAvailable(new ToastBarOperation(mTarget.size(), mAction,
Scott Kennedy6a3d5ce2013-03-15 17:33:14 -07002903 ToastBarOperation.UNDO, mIsSelectedSet, mFolder));
mindypead50392012-08-23 11:03:53 -07002904 }
2905 }, mShowUndoBarDelay);
Vikram Aggarwal3d7ca9d2012-05-11 14:40:36 -07002906 }
Vikram Aggarwalbc67bb12012-04-30 14:05:35 -07002907 refreshConversationList();
Vikram Aggarwalc4113952012-05-11 14:14:56 -07002908 if (mIsSelectedSet) {
Vikram Aggarwalc4113952012-05-11 14:14:56 -07002909 mSelectedSet.clear();
2910 }
Mindy Pereirafbe40192012-03-20 10:40:45 -07002911 }
Vikram Aggarwal7f602f72012-04-30 16:04:06 -07002912
2913 /**
2914 * Returns true if this action has been performed, false otherwise.
Andy Huang839ada22012-07-20 15:48:40 -07002915 *
Vikram Aggarwal7f602f72012-04-30 16:04:06 -07002916 */
2917 private synchronized boolean isPerformed() {
2918 if (mCompleted) {
2919 return true;
2920 }
2921 mCompleted = true;
2922 return false;
2923 }
Mindy Pereirafbe40192012-03-20 10:40:45 -07002924 }
Mindy Pereirae5f4dc02012-03-21 16:08:53 -07002925
Vikram Aggarwald503df42012-05-11 10:13:35 -07002926 // Called from the FolderSelectionDialog after a user is done selecting folders to assign the
2927 // conversations to.
Mindy Pereirae5f4dc02012-03-21 16:08:53 -07002928 @Override
Mindy Pereira8db7e402012-07-13 10:32:47 -07002929 public final void assignFolder(Collection<FolderOperation> folderOps,
Scott Kennedy6a3d5ce2013-03-15 17:33:14 -07002930 Collection<Conversation> target, boolean batch, boolean showUndo,
2931 final boolean isMoveTo) {
Mindy Pereira8db7e402012-07-13 10:32:47 -07002932 // Actions are destructive only when the current folder can be assigned
2933 // to (which is the same as being able to un-assign a conversation from the folder) and
2934 // when the list of folders contains the current folder.
2935 final boolean isDestructive = mFolder
2936 .supportsCapability(FolderCapabilities.CAN_ACCEPT_MOVED_MESSAGES)
2937 && FolderOperation.isDestructive(folderOps, mFolder);
Vikram Aggarwald503df42012-05-11 10:13:35 -07002938 LogUtils.d(LOG_TAG, "onFolderChangesCommit: isDestructive = %b", isDestructive);
2939 if (isDestructive) {
2940 for (final Conversation c : target) {
2941 c.localDeleteOnUpdate = true;
Mindy Pereira6778f462012-03-23 18:01:55 -07002942 }
Mindy Pereirae5f4dc02012-03-21 16:08:53 -07002943 }
mindypc84759c2012-08-29 09:51:53 -07002944 final DestructiveAction folderChange;
Vikram Aggarwald503df42012-05-11 10:13:35 -07002945 // Update the UI elements depending no their visibility and availability
Vikram Aggarwal3d7ca9d2012-05-11 14:40:36 -07002946 // TODO(viki): Consolidate this into a single method requestDelete.
Vikram Aggarwald503df42012-05-11 10:13:35 -07002947 if (isDestructive) {
Scott Kennedy6a3d5ce2013-03-15 17:33:14 -07002948 /*
2949 * If this is a MOVE operation, we want the action folder to be the destination folder.
2950 * Otherwise, we want it to be the current folder.
2951 *
2952 * A set of folder operations is a move if there are exactly two operations: an add and
2953 * a remove.
2954 */
2955 final Folder actionFolder;
2956 if (folderOps.size() != 2) {
2957 actionFolder = mFolder;
2958 } else {
2959 Folder addedFolder = null;
2960 boolean hasRemove = false;
2961 for (final FolderOperation folderOperation : folderOps) {
2962 if (folderOperation.mAdd) {
2963 addedFolder = folderOperation.mFolder;
2964 } else {
2965 hasRemove = true;
2966 }
2967 }
2968
2969 if (hasRemove && addedFolder != null) {
2970 actionFolder = addedFolder;
2971 } else {
2972 actionFolder = mFolder;
2973 }
2974 }
2975
mindypc84759c2012-08-29 09:51:53 -07002976 folderChange = getDeferredFolderChange(target, folderOps, isDestructive,
Scott Kennedy6a3d5ce2013-03-15 17:33:14 -07002977 batch, showUndo, isMoveTo, actionFolder);
Scott Kennedycaaeed32013-06-12 13:39:16 -07002978 delete(0, target, folderChange, batch);
Vikram Aggarwal6902dcf2012-04-11 08:57:42 -07002979 } else {
mindypc84759c2012-08-29 09:51:53 -07002980 folderChange = getFolderChange(target, folderOps, isDestructive,
Scott Kennedy6a3d5ce2013-03-15 17:33:14 -07002981 batch, showUndo, false /* isMoveTo */, mFolder);
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08002982 requestUpdate(folderChange);
Mindy Pereirae5f4dc02012-03-21 16:08:53 -07002983 }
2984 }
2985
Mindy Pereira967ede62012-03-22 09:29:09 -07002986 @Override
Vikram Aggarwal3d7ca9d2012-05-11 14:40:36 -07002987 public final void onRefreshRequired() {
mindyp5390fca2012-08-22 12:12:25 -07002988 if (isAnimating() || isDragging()) {
Andy Huangc1922a92013-05-13 14:33:05 -07002989 LogUtils.i(ConversationCursor.LOG_TAG, "onRefreshRequired: delay until animating done");
Mindy Pereira69e88dd2012-08-10 09:30:18 -07002990 return;
2991 }
Marc Blankbf128eb2012-04-18 15:58:45 -07002992 // Refresh the query in the background
Paul Westbrookcff1aea2012-08-10 11:51:00 -07002993 if (mConversationListCursor.isRefreshRequired()) {
2994 mConversationListCursor.refresh();
2995 }
Marc Blankbf128eb2012-04-18 15:58:45 -07002996 }
2997
mindyp5390fca2012-08-22 12:12:25 -07002998 @Override
2999 public void startDragMode() {
3000 mIsDragHappening = true;
3001 }
3002
3003 @Override
3004 public void stopDragMode() {
3005 mIsDragHappening = false;
3006 if (mConversationListCursor.isRefreshReady()) {
Andy Huangc1922a92013-05-13 14:33:05 -07003007 LogUtils.i(ConversationCursor.LOG_TAG, "Stopped dragging: try sync");
mindyp5390fca2012-08-22 12:12:25 -07003008 onRefreshReady();
3009 }
3010
3011 if (mConversationListCursor.isRefreshRequired()) {
Andy Huangc1922a92013-05-13 14:33:05 -07003012 LogUtils.i(ConversationCursor.LOG_TAG, "Stopped dragging: refresh");
mindyp5390fca2012-08-22 12:12:25 -07003013 mConversationListCursor.refresh();
3014 }
3015 }
3016
3017 private boolean isDragging() {
3018 return mIsDragHappening;
3019 }
3020
mindyp6f54e1b2012-10-09 09:54:08 -07003021 @Override
3022 public boolean isAnimating() {
Mindy Pereira69e88dd2012-08-10 09:30:18 -07003023 boolean isAnimating = false;
3024 ConversationListFragment convListFragment = getConversationListFragment();
3025 if (convListFragment != null) {
Andy Huang48ccbc52013-06-05 20:30:47 -07003026 isAnimating = convListFragment.isAnimating();
Mindy Pereira69e88dd2012-08-10 09:30:18 -07003027 }
3028 return isAnimating;
3029 }
3030
Marc Blankbf128eb2012-04-18 15:58:45 -07003031 /**
3032 * Called when the {@link ConversationCursor} is changed or has new data in it.
3033 * <p>
3034 * {@inheritDoc}
3035 */
3036 @Override
Vikram Aggarwal3d7ca9d2012-05-11 14:40:36 -07003037 public final void onRefreshReady() {
mindyp5c1d8352012-11-05 10:12:44 -08003038 LogUtils.d(LOG_TAG, "Received refresh ready callback for folder %s",
3039 mFolder != null ? mFolder.id : "-1");
Andy Huangb2ef9c12012-12-18 12:58:41 -06003040
3041 if (mDestroyed) {
3042 LogUtils.i(LOG_TAG, "ignoring onRefreshReady on destroyed AAC");
3043 return;
3044 }
3045
Paul Westbrookcff1aea2012-08-10 11:51:00 -07003046 if (!isAnimating()) {
Marc Blankbf128eb2012-04-18 15:58:45 -07003047 // Swap cursors
3048 mConversationListCursor.sync();
Marc Blankbf128eb2012-04-18 15:58:45 -07003049 }
Paul Westbrook937c94f2012-08-16 13:01:18 -07003050 mTracker.onCursorUpdated();
Vikram Aggarwalf0ef2302012-11-07 14:53:34 -08003051 perhapsShowFirstSearchResult();
Marc Blankbf128eb2012-04-18 15:58:45 -07003052 }
3053
3054 @Override
Vikram Aggarwal3d7ca9d2012-05-11 14:40:36 -07003055 public final void onDataSetChanged() {
Paul Westbrook9f119c72012-04-24 16:10:59 -07003056 updateConversationListFragment();
Andy Huang632721e2012-04-11 16:57:26 -07003057 mConversationListObservable.notifyChanged();
Paul Westbrooka13b3742012-09-07 16:35:06 -07003058 mSelectedSet.validateAgainstCursor(mConversationListCursor);
Marc Blankbf128eb2012-04-18 15:58:45 -07003059 }
3060
Vikram Aggarwal3d7ca9d2012-05-11 14:40:36 -07003061 /**
3062 * If the Conversation List Fragment is visible, updates the fragment.
3063 */
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08003064 private void updateConversationListFragment() {
Marc Blankbf128eb2012-04-18 15:58:45 -07003065 final ConversationListFragment convList = getConversationListFragment();
3066 if (convList != null) {
Vikram Aggarwal75daee52012-04-30 11:13:09 -07003067 refreshConversationList();
Vikram Aggarwal6422b8d2013-01-14 10:47:41 -08003068 if (isFragmentVisible(convList)) {
Vikram Aggarwal69b5c302012-09-05 11:11:13 -07003069 informCursorVisiblity(true);
Paul Westbrook9f119c72012-04-24 16:10:59 -07003070 }
Marc Blankbf128eb2012-04-18 15:58:45 -07003071 }
3072 }
3073
3074 /**
3075 * This class handles throttled refresh of the conversation list
3076 */
3077 static class RefreshTimerTask extends TimerTask {
3078 final Handler mHandler;
3079 final AbstractActivityController mController;
3080
3081 RefreshTimerTask(AbstractActivityController controller, Handler handler) {
3082 mHandler = handler;
3083 mController = controller;
3084 }
3085
3086 @Override
3087 public void run() {
3088 mHandler.post(new Runnable() {
3089 @Override
3090 public void run() {
3091 LogUtils.d(LOG_TAG, "Delay done... calling onRefreshRequired");
3092 mController.onRefreshRequired();
3093 }});
3094 }
3095 }
3096
3097 /**
3098 * Cancel the refresh task, if it's running
3099 */
3100 private void cancelRefreshTask () {
3101 if (mConversationListRefreshTask != null) {
3102 mConversationListRefreshTask.cancel();
3103 mConversationListRefreshTask = null;
3104 }
3105 }
3106
3107 @Override
Paul Westbrookcff1aea2012-08-10 11:51:00 -07003108 public void onAnimationEnd(AnimatedAdapter animatedAdapter) {
Paul Westbrook026139c2012-09-19 22:35:37 -07003109 if (mConversationListCursor == null) {
3110 LogUtils.e(LOG_TAG, "null ConversationCursor in onAnimationEnd");
3111 return;
3112 }
Paul Westbrookcff1aea2012-08-10 11:51:00 -07003113 if (mConversationListCursor.isRefreshReady()) {
Andy Huangc1922a92013-05-13 14:33:05 -07003114 LogUtils.i(ConversationCursor.LOG_TAG, "Stopped animating: try sync");
Paul Westbrookcff1aea2012-08-10 11:51:00 -07003115 onRefreshReady();
Marc Blankbf128eb2012-04-18 15:58:45 -07003116 }
Marc Blankbf128eb2012-04-18 15:58:45 -07003117
Paul Westbrookcff1aea2012-08-10 11:51:00 -07003118 if (mConversationListCursor.isRefreshRequired()) {
Andy Huangc1922a92013-05-13 14:33:05 -07003119 LogUtils.i(ConversationCursor.LOG_TAG, "Stopped animating: refresh");
Paul Westbrookcff1aea2012-08-10 11:51:00 -07003120 mConversationListCursor.refresh();
3121 }
mindyp6f54e1b2012-10-09 09:54:08 -07003122 if (mRecentsDataUpdated) {
3123 mRecentsDataUpdated = false;
3124 mRecentFolderObservers.notifyChanged();
3125 }
Marc Blankbf128eb2012-04-18 15:58:45 -07003126 }
3127
3128 @Override
Mindy Pereira967ede62012-03-22 09:29:09 -07003129 public void onSetEmpty() {
Vikram Aggarwal6cadbfc2012-12-27 09:17:05 -08003130 // There are no selected conversations. Ensure that the listener and its associated actions
3131 // are blanked out.
3132 setListener(null, -1);
Mindy Pereira967ede62012-03-22 09:29:09 -07003133 }
3134
3135 @Override
3136 public void onSetPopulated(ConversationSelectionSet set) {
Vikram Aggarwal7704d792013-01-11 15:48:24 -08003137 mCabActionMenu = new SelectedConversationsActionMenu(mActivity, set, mFolder);
Vikram Aggarwal5b9ed2b2013-01-28 18:08:37 -08003138 if (mViewMode.isListMode() || (mIsTablet && mViewMode.isConversationMode())) {
Vikram Aggarwal7704d792013-01-11 15:48:24 -08003139 enableCabMode();
Vikram Aggarwal6902dcf2012-04-11 08:57:42 -07003140 }
Mindy Pereira967ede62012-03-22 09:29:09 -07003141 }
3142
Mindy Pereira967ede62012-03-22 09:29:09 -07003143 @Override
3144 public void onSetChanged(ConversationSelectionSet set) {
3145 // Do nothing. We don't care about changes to the set.
3146 }
3147
3148 @Override
3149 public ConversationSelectionSet getSelectedSet() {
3150 return mSelectedSet;
3151 }
3152
Vikram Aggarwale128fc22012-04-04 12:33:34 -07003153 /**
3154 * Disable the Contextual Action Bar (CAB). The selected set is not changed.
3155 */
3156 protected void disableCabMode() {
Mindy Pereira8937bf12012-07-23 14:05:02 -07003157 // Commit any previous destructive actions when entering/ exiting CAB mode.
mindypc6adce32012-08-22 18:46:42 -07003158 commitDestructiveActions(true);
Vikram Aggarwale128fc22012-04-04 12:33:34 -07003159 if (mCabActionMenu != null) {
3160 mCabActionMenu.deactivate();
3161 }
3162 }
3163
3164 /**
3165 * Re-enable the CAB menu if required. The selection set is not changed.
3166 */
3167 protected void enableCabMode() {
Tony Mantler3d6751a2013-08-02 11:30:59 -07003168 if (mCabActionMenu != null &&
3169 !(isDrawerEnabled() && mDrawerContainer.isDrawerOpen(mDrawerPullout))) {
Vikram Aggarwale128fc22012-04-04 12:33:34 -07003170 mCabActionMenu.activate();
3171 }
3172 }
3173
Vikram Aggarwal4eb52712012-06-19 16:24:50 -07003174 /**
Tony Mantler43fab322013-07-26 16:38:35 -07003175 * Re-enable CAB mode only if we have an active selection
3176 */
3177 protected void maybeEnableCabMode() {
3178 if (!mSelectedSet.isEmpty()) {
Tony Mantlera703d8a2013-07-31 12:00:46 -07003179 if (mCabActionMenu != null) {
3180 mCabActionMenu.activate();
3181 }
Tony Mantler43fab322013-07-26 16:38:35 -07003182 }
3183 }
3184
3185 /**
Vikram Aggarwal4eb52712012-06-19 16:24:50 -07003186 * Unselect conversations and exit CAB mode.
3187 */
3188 protected final void exitCabMode() {
3189 mSelectedSet.clear();
3190 }
3191
Mindy Pereira967ede62012-03-22 09:29:09 -07003192 @Override
Mindy Pereirafd0c2972012-03-27 13:50:39 -07003193 public void startSearch() {
Vikram Aggarwal35f19d72012-04-24 13:24:48 -07003194 if (mAccount == null) {
3195 // We cannot search if there is no account. Drop the request to the floor.
3196 LogUtils.d(LOG_TAG, "AbstractActivityController.startSearch(): null account");
3197 return;
3198 }
James Lemieux3531d7e2014-01-28 11:10:05 -08003199 if (mAccount.supportsSearch()) {
Andy Huang313ac132013-03-04 23:40:58 -08003200 mActionBarView.expandSearch();
Mindy Pereirafd0c2972012-03-27 13:50:39 -07003201 } else {
3202 Toast.makeText(mActivity.getActivityContext(), mActivity.getActivityContext()
Mindy Pereiraa46c2992012-03-27 14:12:39 -07003203 .getString(R.string.search_unsupported), Toast.LENGTH_SHORT).show();
Mindy Pereirafd0c2972012-03-27 13:50:39 -07003204 }
3205 }
Mindy Pereiraacf60392012-04-06 09:11:00 -07003206
Vikram Aggarwal0dda5732012-04-06 11:20:16 -07003207 @Override
3208 public void exitSearchMode() {
3209 if (mViewMode.getMode() == ViewMode.SEARCH_RESULTS_LIST) {
3210 mActivity.finish();
3211 }
3212 }
3213
Mindy Pereiraacf60392012-04-06 09:11:00 -07003214 /**
3215 * Supports dragging conversations to a folder.
3216 */
3217 @Override
3218 public boolean supportsDrag(DragEvent event, Folder folder) {
3219 return (folder != null
3220 && event != null
3221 && event.getClipDescription() != null
3222 && folder.supportsCapability
3223 (UIProvider.FolderCapabilities.CAN_ACCEPT_MOVED_MESSAGES)
Scott Kennedy259df5b2013-07-11 13:24:01 -07003224 && !mFolder.equals(folder));
Mindy Pereiraacf60392012-04-06 09:11:00 -07003225 }
3226
3227 /**
Mindy Pereira6c2663d2012-07-20 15:37:29 -07003228 * Handles dropping conversations to a folder.
Mindy Pereiraacf60392012-04-06 09:11:00 -07003229 */
3230 @Override
3231 public void handleDrop(DragEvent event, final Folder folder) {
Mindy Pereiraacf60392012-04-06 09:11:00 -07003232 if (!supportsDrag(event, folder)) {
3233 return;
3234 }
Scott Kennedy8c1058e2013-03-20 13:40:20 -07003235 if (folder.isType(UIProvider.FolderType.STARRED)) {
mindypae7e6a02012-11-29 13:28:10 -08003236 // Moving a conversation to the starred folder adds the star and
3237 // removes the current label
3238 handleDropInStarred(folder);
3239 return;
3240 }
Scott Kennedy8c1058e2013-03-20 13:40:20 -07003241 if (mFolder.isType(UIProvider.FolderType.STARRED)) {
mindypae7e6a02012-11-29 13:28:10 -08003242 handleDragFromStarred(folder);
3243 return;
3244 }
mindypa8492632012-09-24 09:27:54 -07003245 final ArrayList<FolderOperation> dragDropOperations = new ArrayList<FolderOperation>();
mindypae7e6a02012-11-29 13:28:10 -08003246 final Collection<Conversation> conversations = mSelectedSet.values();
mindypa8492632012-09-24 09:27:54 -07003247 // Add the drop target folder.
3248 dragDropOperations.add(new FolderOperation(folder, true));
3249 // Remove the current folder unless the user is viewing "all".
3250 // That operation should just add the new folder.
3251 boolean isDestructive = !mFolder.isViewAll()
3252 && mFolder.supportsCapability
3253 (UIProvider.FolderCapabilities.CAN_ACCEPT_MOVED_MESSAGES);
3254 if (isDestructive) {
3255 dragDropOperations.add(new FolderOperation(mFolder, false));
3256 }
Mindy Pereira8db7e402012-07-13 10:32:47 -07003257 // Drag and drop is destructive: we remove conversations from the
3258 // current folder.
Scott Kennedy6a3d5ce2013-03-15 17:33:14 -07003259 final DestructiveAction action =
3260 getFolderChange(conversations, dragDropOperations, isDestructive,
3261 true /* isBatch */, true /* showUndo */, true /* isMoveTo */, folder);
mindypa8492632012-09-24 09:27:54 -07003262 if (isDestructive) {
Scott Kennedycaaeed32013-06-12 13:39:16 -07003263 delete(0, conversations, action, true);
mindypa8492632012-09-24 09:27:54 -07003264 } else {
3265 action.performAction();
3266 }
Mindy Pereiraacf60392012-04-06 09:11:00 -07003267 }
Mindy Pereira0963ef82012-04-10 11:43:01 -07003268
mindypae7e6a02012-11-29 13:28:10 -08003269 private void handleDragFromStarred(Folder folder) {
3270 final Collection<Conversation> conversations = mSelectedSet.values();
3271 // The conversation list deletes and performs the action if it exists.
3272 final ConversationListFragment convListFragment = getConversationListFragment();
3273 // There should always be a convlistfragment, or the user could not have
3274 // dragged/ dropped conversations.
3275 if (convListFragment != null) {
3276 LogUtils.d(LOG_TAG, "AAC.requestDelete: ListFragment is handling delete.");
3277 ArrayList<ConversationOperation> ops = new ArrayList<ConversationOperation>();
mindypcb0b30e2012-11-30 10:16:35 -08003278 ArrayList<Uri> folderUris;
3279 ArrayList<Boolean> adds;
mindypae7e6a02012-11-29 13:28:10 -08003280 for (Conversation target : conversations) {
mindypcb0b30e2012-11-30 10:16:35 -08003281 folderUris = new ArrayList<Uri>();
3282 adds = new ArrayList<Boolean>();
Scott Kennedy259df5b2013-07-11 13:24:01 -07003283 folderUris.add(folder.folderUri.fullUri);
mindypcb0b30e2012-11-30 10:16:35 -08003284 adds.add(Boolean.TRUE);
Paul Westbrook26746eb2012-12-06 14:44:01 -08003285 final HashMap<Uri, Folder> targetFolders =
3286 Folder.hashMapForFolders(target.getRawFolders());
Scott Kennedy259df5b2013-07-11 13:24:01 -07003287 targetFolders.put(folder.folderUri.fullUri, folder);
Paul Westbrook26746eb2012-12-06 14:44:01 -08003288 ops.add(mConversationListCursor.getConversationFolderOperation(target,
3289 folderUris, adds, targetFolders.values()));
mindypae7e6a02012-11-29 13:28:10 -08003290 }
3291 if (mConversationListCursor != null) {
Scott Kennedy9e2d4072013-03-21 21:46:01 -07003292 mConversationListCursor.updateBulkValues(ops);
mindypae7e6a02012-11-29 13:28:10 -08003293 }
3294 refreshConversationList();
3295 mSelectedSet.clear();
mindypae7e6a02012-11-29 13:28:10 -08003296 }
3297 }
3298
3299 private void handleDropInStarred(Folder folder) {
3300 final Collection<Conversation> conversations = mSelectedSet.values();
3301 // The conversation list deletes and performs the action if it exists.
3302 final ConversationListFragment convListFragment = getConversationListFragment();
3303 // There should always be a convlistfragment, or the user could not have
3304 // dragged/ dropped conversations.
3305 if (convListFragment != null) {
3306 LogUtils.d(LOG_TAG, "AAC.requestDelete: ListFragment is handling delete.");
Andrew Sapperstein6c570db2013-08-06 17:21:36 -07003307 convListFragment.requestDelete(R.id.change_folders, conversations,
mindyp5cc0ab22012-12-11 08:47:35 -08003308 new DroppedInStarredAction(conversations, mFolder, folder));
mindypae7e6a02012-11-29 13:28:10 -08003309 }
3310 }
3311
3312 // When dragging conversations to the starred folder, remove from the
3313 // original folder and add a star
3314 private class DroppedInStarredAction implements DestructiveAction {
Martin Hibdone78c40f2013-10-10 18:29:25 -07003315 private final Collection<Conversation> mConversations;
3316 private final Folder mInitialFolder;
3317 private final Folder mStarred;
mindypae7e6a02012-11-29 13:28:10 -08003318
mindyp5cc0ab22012-12-11 08:47:35 -08003319 public DroppedInStarredAction(Collection<Conversation> conversations, Folder initialFolder,
3320 Folder starredFolder) {
mindypae7e6a02012-11-29 13:28:10 -08003321 mConversations = conversations;
mindyp5cc0ab22012-12-11 08:47:35 -08003322 mInitialFolder = initialFolder;
3323 mStarred = starredFolder;
mindypae7e6a02012-11-29 13:28:10 -08003324 }
3325
3326 @Override
3327 public void performAction() {
3328 ToastBarOperation undoOp = new ToastBarOperation(mConversations.size(),
Andrew Sapperstein6c570db2013-08-06 17:21:36 -07003329 R.id.change_folders, ToastBarOperation.UNDO, true /* batch */, mInitialFolder);
mindypae7e6a02012-11-29 13:28:10 -08003330 onUndoAvailable(undoOp);
3331 ArrayList<ConversationOperation> ops = new ArrayList<ConversationOperation>();
3332 ContentValues values = new ContentValues();
mindypcb0b30e2012-11-30 10:16:35 -08003333 ArrayList<Uri> folderUris;
3334 ArrayList<Boolean> adds;
mindyp5cc0ab22012-12-11 08:47:35 -08003335 ConversationOperation operation;
mindypae7e6a02012-11-29 13:28:10 -08003336 for (Conversation target : mConversations) {
mindypcb0b30e2012-11-30 10:16:35 -08003337 folderUris = new ArrayList<Uri>();
3338 adds = new ArrayList<Boolean>();
Scott Kennedy259df5b2013-07-11 13:24:01 -07003339 folderUris.add(mStarred.folderUri.fullUri);
mindyp5cc0ab22012-12-11 08:47:35 -08003340 adds.add(Boolean.TRUE);
Scott Kennedy259df5b2013-07-11 13:24:01 -07003341 folderUris.add(mInitialFolder.folderUri.fullUri);
mindypcb0b30e2012-11-30 10:16:35 -08003342 adds.add(Boolean.FALSE);
mindyp5cc0ab22012-12-11 08:47:35 -08003343 final HashMap<Uri, Folder> targetFolders =
3344 Folder.hashMapForFolders(target.getRawFolders());
Scott Kennedy259df5b2013-07-11 13:24:01 -07003345 targetFolders.put(mStarred.folderUri.fullUri, mStarred);
3346 targetFolders.remove(mInitialFolder.folderUri.fullUri);
mindyp5cc0ab22012-12-11 08:47:35 -08003347 values.put(ConversationColumns.STARRED, true);
3348 operation = mConversationListCursor.getConversationFolderOperation(target,
3349 folderUris, adds, targetFolders.values(), values);
3350 ops.add(operation);
mindypae7e6a02012-11-29 13:28:10 -08003351 }
3352 if (mConversationListCursor != null) {
Scott Kennedy9e2d4072013-03-21 21:46:01 -07003353 mConversationListCursor.updateBulkValues(ops);
mindypae7e6a02012-11-29 13:28:10 -08003354 }
3355 refreshConversationList();
3356 mSelectedSet.clear();
3357 }
3358 }
3359
Mindy Pereira0963ef82012-04-10 11:43:01 -07003360 @Override
Mindy Pereira0963ef82012-04-10 11:43:01 -07003361 public void onTouchEvent(MotionEvent event) {
3362 if (event.getAction() == MotionEvent.ACTION_DOWN) {
Andrew Sappersteinc2c9dc12012-07-02 18:17:32 -07003363 if (mToastBar != null && !mToastBar.isEventInToastBar(event)) {
Mark Weid243d452012-10-31 16:24:08 -07003364 hideOrRepositionToastBar(true);
Mindy Pereira0963ef82012-04-10 11:43:01 -07003365 }
3366 }
3367 }
Andy Huangb1c34dc2012-04-17 16:36:19 -07003368
Mark Weid243d452012-10-31 16:24:08 -07003369 protected abstract void hideOrRepositionToastBar(boolean animated);
3370
Andy Huang632721e2012-04-11 16:57:26 -07003371 @Override
Scott Kennedy3b965d72013-06-25 14:36:55 -07003372 public void onConversationSeen() {
3373 mPagerController.onConversationSeen();
Andy Huang632721e2012-04-11 16:57:26 -07003374 }
3375
Andy Huang9d3fd922012-09-26 22:23:58 -07003376 @Override
3377 public boolean isInitialConversationLoading() {
3378 return mPagerController.isInitialConversationLoading();
3379 }
3380
Vikram Aggarwal6422b8d2013-01-14 10:47:41 -08003381 /**
3382 * Check if the fragment given here is visible. Checking {@link Fragment#isVisible()} is
3383 * insufficient because that doesn't check if the window is currently in focus or not.
3384 */
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08003385 private boolean isFragmentVisible(Fragment in) {
Vikram Aggarwal6422b8d2013-01-14 10:47:41 -08003386 return in != null && in.isVisible() && mActivity.hasWindowFocus();
3387 }
3388
Vikram Aggarwald70fe492013-06-04 12:52:07 -07003389 /**
3390 * This class handles callbacks that create a {@link ConversationCursor}.
3391 */
Andy Huangb1c34dc2012-04-17 16:36:19 -07003392 private class ConversationListLoaderCallbacks implements
3393 LoaderManager.LoaderCallbacks<ConversationCursor> {
3394
3395 @Override
3396 public Loader<ConversationCursor> onCreateLoader(int id, Bundle args) {
Vikram Aggarwala1b59dc2013-04-30 15:45:49 -07003397 final Account account = args.getParcelable(BUNDLE_ACCOUNT_KEY);
3398 final Folder folder = args.getParcelable(BUNDLE_FOLDER_KEY);
Andrew Sapperstein5bb4d052014-03-31 16:22:31 -07003399 final boolean ignoreInitialConversationLimit =
3400 args.getBoolean(BUNDLE_IGNORE_INITIAL_CONVERSATION_LIMIT_KEY, false);
Vikram Aggarwala1b59dc2013-04-30 15:45:49 -07003401 if (account == null || folder == null) {
3402 return null;
3403 }
Andrew Sapperstein5bb4d052014-03-31 16:22:31 -07003404 return new ConversationCursorLoader(mActivity, account,
3405 folder.conversationListUri, folder.name, ignoreInitialConversationLimit);
Andy Huangb1c34dc2012-04-17 16:36:19 -07003406 }
3407
3408 @Override
3409 public void onLoadFinished(Loader<ConversationCursor> loader, ConversationCursor data) {
Andy Huang144bfe72013-06-11 13:27:52 -07003410 LogUtils.d(LOG_TAG,
3411 "IN AAC.ConversationCursor.onLoadFinished, data=%s loader=%s this=%s",
3412 data, loader, this);
Andrew Sappersteina3ce6782013-05-09 15:14:49 -07003413 if (isDrawerEnabled() && mDrawerListener.getDrawerState() != DrawerLayout.STATE_IDLE) {
Vikram Aggarwala1b59dc2013-04-30 15:45:49 -07003414 LogUtils.d(LOG_TAG, "ConversationListLoaderCallbacks.onLoadFinished: ignoring.");
Andrew Sappersteina3ce6782013-05-09 15:14:49 -07003415 mConversationListLoadFinishedIgnored = true;
Vikram Aggarwala1b59dc2013-04-30 15:45:49 -07003416 return;
3417 }
Vikram Aggarwale8a85322012-04-24 09:01:38 -07003418 // Clear our all pending destructive actions before swapping the conversation cursor
3419 destroyPending(null);
Andy Huangb1c34dc2012-04-17 16:36:19 -07003420 mConversationListCursor = data;
Paul Westbrookbf232c32012-04-18 03:17:41 -07003421 mConversationListCursor.addListener(AbstractActivityController.this);
Andy Huang144bfe72013-06-11 13:27:52 -07003422 mDrawIdler.setListener(mConversationListCursor);
Paul Westbrook937c94f2012-08-16 13:01:18 -07003423 mTracker.onCursorUpdated();
Andy Huange3df1ad2012-04-24 17:15:23 -07003424 mConversationListObservable.notifyChanged();
Yu Ping Hu7c909c72013-01-18 11:58:01 -08003425 // Handle actions that were deferred until after the conversation list was loaded.
3426 for (LoadFinishedCallback callback : mConversationListLoadFinishedCallbacks) {
3427 callback.onLoadFinished();
3428 }
3429 mConversationListLoadFinishedCallbacks.clear();
Paul Westbrook9f119c72012-04-24 16:10:59 -07003430
Vikram Aggarwal17f373e2012-09-17 15:49:32 -07003431 final ConversationListFragment convList = getConversationListFragment();
Vikram Aggarwal6422b8d2013-01-14 10:47:41 -08003432 if (isFragmentVisible(convList)) {
Vikram Aggarwal17f373e2012-09-17 15:49:32 -07003433 // The conversation list is already listening to list changes and gets notified
3434 // in the mConversationListObservable.notifyChanged() line above. We only need to
3435 // check and inform the cursor of the change in visibility here.
3436 informCursorVisiblity(true);
Andy Huangb1c34dc2012-04-17 16:36:19 -07003437 }
Vikram Aggarwalf0ef2302012-11-07 14:53:34 -08003438 perhapsShowFirstSearchResult();
Andy Huangb1c34dc2012-04-17 16:36:19 -07003439 }
3440
3441 @Override
3442 public void onLoaderReset(Loader<ConversationCursor> loader) {
Andy Huang144bfe72013-06-11 13:27:52 -07003443 LogUtils.d(LOG_TAG,
3444 "IN AAC.ConversationCursor.onLoaderReset, data=%s loader=%s this=%s",
3445 mConversationListCursor, loader, this);
Paul Westbrook9a70e912012-08-17 15:53:20 -07003446
3447 if (mConversationListCursor != null) {
3448 // Unregister the listener
3449 mConversationListCursor.removeListener(AbstractActivityController.this);
Andy Huang144bfe72013-06-11 13:27:52 -07003450 mDrawIdler.setListener(null);
Paul Westbrook9a70e912012-08-17 15:53:20 -07003451 mConversationListCursor = null;
3452
3453 // Inform anyone who is interested about the change
3454 mTracker.onCursorUpdated();
3455 mConversationListObservable.notifyChanged();
Andy Huangb1c34dc2012-04-17 16:36:19 -07003456 }
Andy Huangb1c34dc2012-04-17 16:36:19 -07003457 }
Paul Westbrookbf232c32012-04-18 03:17:41 -07003458 }
Andy Huangb1c34dc2012-04-17 16:36:19 -07003459
Vikram Aggarwale8a85322012-04-24 09:01:38 -07003460 /**
Vikram Aggarwal177097f2013-03-08 11:19:53 -08003461 * Class to perform {@link LoaderManager.LoaderCallbacks} for creating {@link Folder} objects.
3462 */
3463 private class FolderLoads implements LoaderManager.LoaderCallbacks<ObjectCursor<Folder>> {
3464 @Override
3465 public Loader<ObjectCursor<Folder>> onCreateLoader(int id, Bundle args) {
3466 final String[] everything = UIProvider.FOLDERS_PROJECTION;
3467 switch (id) {
3468 case LOADER_FOLDER_CURSOR:
3469 LogUtils.d(LOG_TAG, "LOADER_FOLDER_CURSOR created");
3470 final ObjectCursorLoader<Folder> loader = new
3471 ObjectCursorLoader<Folder>(
Scott Kennedy259df5b2013-07-11 13:24:01 -07003472 mContext, mFolder.folderUri.fullUri, everything, Folder.FACTORY);
Vikram Aggarwal177097f2013-03-08 11:19:53 -08003473 loader.setUpdateThrottle(mFolderItemUpdateDelayMs);
3474 return loader;
3475 case LOADER_RECENT_FOLDERS:
3476 LogUtils.d(LOG_TAG, "LOADER_RECENT_FOLDERS created");
Yu Ping Huf2632b92013-03-15 13:56:27 -07003477 if (mAccount != null && mAccount.recentFolderListUri != null
3478 && !mAccount.recentFolderListUri.equals(Uri.EMPTY)) {
Vikram Aggarwal177097f2013-03-08 11:19:53 -08003479 return new ObjectCursorLoader<Folder>(mContext,
3480 mAccount.recentFolderListUri, everything, Folder.FACTORY);
3481 }
3482 break;
3483 case LOADER_ACCOUNT_INBOX:
3484 LogUtils.d(LOG_TAG, "LOADER_ACCOUNT_INBOX created");
3485 final Uri defaultInbox = Settings.getDefaultInboxUri(mAccount.settings);
3486 final Uri inboxUri = defaultInbox.equals(Uri.EMPTY) ?
3487 mAccount.folderListUri : defaultInbox;
3488 LogUtils.d(LOG_TAG, "Loading the default inbox: %s", inboxUri);
3489 if (inboxUri != null) {
3490 return new ObjectCursorLoader<Folder>(mContext, inboxUri,
3491 everything, Folder.FACTORY);
3492 }
3493 break;
3494 case LOADER_SEARCH:
3495 LogUtils.d(LOG_TAG, "LOADER_SEARCH created");
3496 return Folder.forSearchResults(mAccount,
3497 args.getString(ConversationListContext.EXTRA_SEARCH_QUERY),
3498 mActivity.getActivityContext());
3499 case LOADER_FIRST_FOLDER:
3500 LogUtils.d(LOG_TAG, "LOADER_FIRST_FOLDER created");
3501 final Uri folderUri = args.getParcelable(Utils.EXTRA_FOLDER_URI);
3502 mConversationToShow = args.getParcelable(Utils.EXTRA_CONVERSATION);
3503 if (mConversationToShow != null && mConversationToShow.position < 0){
3504 mConversationToShow.position = 0;
3505 }
3506 return new ObjectCursorLoader<Folder>(mContext, folderUri,
3507 everything, Folder.FACTORY);
3508 default:
3509 LogUtils.wtf(LOG_TAG, "FolderLoads.onCreateLoader(%d) for invalid id", id);
3510 return null;
3511 }
3512 return null;
3513 }
3514
3515 @Override
3516 public void onLoadFinished(Loader<ObjectCursor<Folder>> loader, ObjectCursor<Folder> data) {
3517 if (data == null) {
3518 LogUtils.e(LOG_TAG, "Received null cursor from loader id: %d", loader.getId());
3519 }
3520 switch (loader.getId()) {
3521 case LOADER_FOLDER_CURSOR:
3522 if (data != null && data.moveToFirst()) {
3523 final Folder folder = data.getModel();
3524 setHasFolderChanged(folder);
3525 mFolder = folder;
3526 mFolderObservable.notifyChanged();
3527 } else {
3528 LogUtils.d(LOG_TAG, "Unable to get the folder %s",
Tony Mantler26a20752014-02-28 16:44:24 -08003529 mFolder != null ? mFolder.name : "");
Vikram Aggarwal177097f2013-03-08 11:19:53 -08003530 }
3531 break;
3532 case LOADER_RECENT_FOLDERS:
3533 // Few recent folders and we are running on a phone? Populate the default
3534 // recents. The number of default recent folders is at least 2: every provider
3535 // has at least two folders, and the recent folder count never decreases.
3536 // Having a single recent folder is an erroneous case, and we can gracefully
3537 // recover by populating default recents. The default recents will not stomp on
3538 // the existing value: it will be shown in addition to the default folders:
3539 // the max number of recent folders is more than 1+num(defaultRecents).
3540 if (data != null && data.getCount() <= 1 && !mIsTablet) {
3541 final class PopulateDefault extends AsyncTask<Uri, Void, Void> {
3542 @Override
3543 protected Void doInBackground(Uri... uri) {
3544 // Asking for an update on the URI and ignore the result.
3545 final ContentResolver resolver = mContext.getContentResolver();
3546 resolver.update(uri[0], null, null, null);
3547 return null;
3548 }
3549 }
3550 final Uri uri = mAccount.defaultRecentFolderListUri;
3551 LogUtils.v(LOG_TAG, "Default recents at %s", uri);
3552 new PopulateDefault().execute(uri);
3553 break;
3554 }
3555 LogUtils.v(LOG_TAG, "Reading recent folders from the cursor.");
3556 mRecentFolderList.loadFromUiProvider(data);
3557 if (isAnimating()) {
3558 mRecentsDataUpdated = true;
3559 } else {
3560 mRecentFolderObservers.notifyChanged();
3561 }
3562 break;
3563 case LOADER_ACCOUNT_INBOX:
3564 if (data != null && !data.isClosed() && data.moveToFirst()) {
3565 final Folder inbox = data.getModel();
Alice Yangebeef1b2013-09-04 06:41:10 +00003566 onFolderChanged(inbox, false /* force */);
Vikram Aggarwal177097f2013-03-08 11:19:53 -08003567 // Just want to get the inbox, don't care about updates to it
3568 // as this will be tracked by the folder change listener.
3569 mActivity.getLoaderManager().destroyLoader(LOADER_ACCOUNT_INBOX);
3570 } else {
3571 LogUtils.d(LOG_TAG, "Unable to get the account inbox for account %s",
Tony Mantler26a20752014-02-28 16:44:24 -08003572 mAccount != null ? mAccount.getEmailAddress() : "");
Vikram Aggarwal177097f2013-03-08 11:19:53 -08003573 }
3574 break;
3575 case LOADER_SEARCH:
3576 if (data != null && data.getCount() > 0) {
3577 data.moveToFirst();
3578 final Folder search = data.getModel();
3579 updateFolder(search);
3580 mConvListContext = ConversationListContext.forSearchQuery(mAccount, mFolder,
3581 mActivity.getIntent()
3582 .getStringExtra(UIProvider.SearchQueryParameters.QUERY));
3583 showConversationList(mConvListContext);
3584 mActivity.invalidateOptionsMenu();
3585 mHaveSearchResults = search.totalCount > 0;
3586 mActivity.getLoaderManager().destroyLoader(LOADER_SEARCH);
3587 } else {
3588 LogUtils.e(LOG_TAG, "Null/empty cursor returned by LOADER_SEARCH loader");
3589 }
3590 break;
3591 case LOADER_FIRST_FOLDER:
3592 if (data == null || data.getCount() <=0 || !data.moveToFirst()) {
3593 return;
3594 }
3595 final Folder folder = data.getModel();
3596 boolean handled = false;
3597 if (folder != null) {
Alice Yangebeef1b2013-09-04 06:41:10 +00003598 onFolderChanged(folder, false /* force */);
Vikram Aggarwal177097f2013-03-08 11:19:53 -08003599 handled = true;
3600 }
3601 if (mConversationToShow != null) {
3602 // Open the conversation.
3603 showConversation(mConversationToShow);
3604 handled = true;
3605 }
3606 if (!handled) {
3607 // We have an account, but nothing else: load the default inbox.
3608 loadAccountInbox();
3609 }
3610 mConversationToShow = null;
3611 // And don't run this anymore.
3612 mActivity.getLoaderManager().destroyLoader(LOADER_FIRST_FOLDER);
3613 break;
3614 }
3615 }
3616
3617 @Override
3618 public void onLoaderReset(Loader<ObjectCursor<Folder>> loader) {
3619 }
3620 }
3621
3622 /**
3623 * Class to perform {@link LoaderManager.LoaderCallbacks} for creating {@link Account} objects.
3624 */
3625 private class AccountLoads implements LoaderManager.LoaderCallbacks<ObjectCursor<Account>> {
3626 final String[] mProjection = UIProvider.ACCOUNTS_PROJECTION;
3627 final CursorCreator<Account> mFactory = Account.FACTORY;
3628
3629 @Override
3630 public Loader<ObjectCursor<Account>> onCreateLoader(int id, Bundle args) {
3631 switch (id) {
3632 case LOADER_ACCOUNT_CURSOR:
3633 LogUtils.d(LOG_TAG, "LOADER_ACCOUNT_CURSOR created");
3634 return new ObjectCursorLoader<Account>(mContext,
3635 MailAppProvider.getAccountsUri(), mProjection, mFactory);
3636 case LOADER_ACCOUNT_UPDATE_CURSOR:
3637 LogUtils.d(LOG_TAG, "LOADER_ACCOUNT_UPDATE_CURSOR created");
3638 return new ObjectCursorLoader<Account>(mContext, mAccount.uri, mProjection,
3639 mFactory);
3640 default:
3641 LogUtils.wtf(LOG_TAG, "Got an id (%d) that I cannot create!", id);
3642 break;
3643 }
3644 return null;
3645 }
3646
3647 @Override
3648 public void onLoadFinished(Loader<ObjectCursor<Account>> loader,
3649 ObjectCursor<Account> data) {
3650 if (data == null) {
3651 LogUtils.e(LOG_TAG, "Received null cursor from loader id: %d", loader.getId());
3652 }
3653 switch (loader.getId()) {
3654 case LOADER_ACCOUNT_CURSOR:
Vikram Aggarwald70fe492013-06-04 12:52:07 -07003655 // We have received an update on the list of accounts.
Vikram Aggarwal177097f2013-03-08 11:19:53 -08003656 if (data == null) {
3657 // Nothing useful to do if we have no valid data.
3658 break;
3659 }
Andy Huang761522c2013-08-08 13:09:11 -07003660 final long count = data.getCount();
3661 if (count == 0) {
Vikram Aggarwal177097f2013-03-08 11:19:53 -08003662 // If an empty cursor is returned, the MailAppProvider is indicating that
3663 // no accounts have been specified. We want to navigate to the
3664 // "add account" activity that will handle the intent returned by the
3665 // MailAppProvider
3666
3667 // If the MailAppProvider believes that all accounts have been loaded,
3668 // and the account list is still empty, we want to prompt the user to add
3669 // an account.
3670 final Bundle extras = data.getExtras();
3671 final boolean accountsLoaded =
3672 extras.getInt(AccountCursorExtraKeys.ACCOUNTS_LOADED) != 0;
3673
3674 if (accountsLoaded) {
3675 final Intent noAccountIntent = MailAppProvider.getNoAccountIntent
3676 (mContext);
3677 if (noAccountIntent != null) {
3678 mActivity.startActivityForResult(noAccountIntent,
3679 ADD_ACCOUNT_REQUEST_CODE);
3680 }
3681 }
3682 } else {
3683 final boolean accountListUpdated = accountsUpdated(data);
Vikram Aggarwalc04cf7e2013-05-13 15:38:42 -07003684 if (!mHaveAccountList || accountListUpdated) {
3685 mHaveAccountList = updateAccounts(data);
Vikram Aggarwal177097f2013-03-08 11:19:53 -08003686 }
Andy Huang761522c2013-08-08 13:09:11 -07003687 Analytics.getInstance().setCustomDimension(Analytics.CD_INDEX_ACCOUNT_COUNT,
3688 Long.toString(count));
Vikram Aggarwal177097f2013-03-08 11:19:53 -08003689 }
3690 break;
3691 case LOADER_ACCOUNT_UPDATE_CURSOR:
3692 // We have received an update for current account.
Vikram Aggarwal177097f2013-03-08 11:19:53 -08003693 if (data != null && data.moveToFirst()) {
3694 final Account updatedAccount = data.getModel();
Vikram Aggarwald70fe492013-06-04 12:52:07 -07003695 // Make sure that this is an update for the current account
Vikram Aggarwal177097f2013-03-08 11:19:53 -08003696 if (updatedAccount.uri.equals(mAccount.uri)) {
Vikram Aggarwal177097f2013-03-08 11:19:53 -08003697 final Settings previousSettings = mAccount.settings;
3698
3699 // Update the controller's reference to the current account
3700 mAccount = updatedAccount;
3701 LogUtils.d(LOG_TAG, "AbstractActivityController.onLoadFinished(): "
3702 + "mAccount = %s", mAccount.uri);
3703
3704 // Only notify about a settings change if something differs
3705 if (!Objects.equal(mAccount.settings, previousSettings)) {
3706 mAccountObservers.notifyChanged();
3707 }
3708 perhapsEnterWaitMode();
3709 } else {
3710 LogUtils.e(LOG_TAG, "Got update for account: %s with current account:"
3711 + " %s", updatedAccount.uri, mAccount.uri);
3712 // We need to restart the loader, so the correct account information
3713 // will be returned.
3714 restartOptionalLoader(LOADER_ACCOUNT_UPDATE_CURSOR, this, Bundle.EMPTY);
3715 }
3716 }
3717 break;
3718 }
3719 }
3720
3721 @Override
3722 public void onLoaderReset(Loader<ObjectCursor<Account>> loader) {
Vikram Aggarwald70fe492013-06-04 12:52:07 -07003723 // Do nothing. In onLoadFinished() we copy the relevant data from the cursor.
Vikram Aggarwal177097f2013-03-08 11:19:53 -08003724 }
3725 }
3726
3727 /**
Vikram Aggarwalf0ef2302012-11-07 14:53:34 -08003728 * Updates controller state based on search results and shows first conversation if required.
3729 */
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08003730 private void perhapsShowFirstSearchResult() {
mindypd27009a2012-11-27 11:54:18 -08003731 if (mCurrentConversation == null) {
3732 // Shown for search results in two-pane mode only.
3733 mHaveSearchResults = Intent.ACTION_SEARCH.equals(mActivity.getIntent().getAction())
3734 && mConversationListCursor.getCount() > 0;
3735 if (!shouldShowFirstConversation()) {
3736 return;
3737 }
3738 mConversationListCursor.moveToPosition(0);
3739 final Conversation conv = new Conversation(mConversationListCursor);
3740 conv.position = 0;
3741 onConversationSelected(conv, true /* checkSafeToModifyFragments */);
Vikram Aggarwalf0ef2302012-11-07 14:53:34 -08003742 }
Vikram Aggarwalf0ef2302012-11-07 14:53:34 -08003743 }
3744
3745 /**
Vikram Aggarwale8a85322012-04-24 09:01:38 -07003746 * Destroy the pending {@link DestructiveAction} till now and assign the given action as the
3747 * next destructive action..
3748 * @param nextAction the next destructive action to be performed. This can be null.
3749 */
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08003750 private void destroyPending(DestructiveAction nextAction) {
Vikram Aggarwale8a85322012-04-24 09:01:38 -07003751 // If there is a pending action, perform that first.
3752 if (mPendingDestruction != null) {
3753 mPendingDestruction.performAction();
3754 }
3755 mPendingDestruction = nextAction;
3756 }
3757
3758 /**
3759 * Register a destructive action with the controller. This performs the previous destructive
Vikram Aggarwalacaa3c02012-04-24 12:45:27 -07003760 * action as a side effect. This method is final because we don't want the child classes to
Vikram Aggarwal3d7ca9d2012-05-11 14:40:36 -07003761 * embellish this method any more.
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08003762 * @param action the action to register.
Vikram Aggarwale8a85322012-04-24 09:01:38 -07003763 */
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08003764 private void registerDestructiveAction(DestructiveAction action) {
Vikram Aggarwale8a85322012-04-24 09:01:38 -07003765 // TODO(viki): This is not a good idea. The best solution is for clients to request a
3766 // destructive action from the controller and for the controller to own the action. This is
3767 // a half-way solution while refactoring DestructiveAction.
3768 destroyPending(action);
Vikram Aggarwale8a85322012-04-24 09:01:38 -07003769 }
3770
Vikram Aggarwal531488e2012-05-29 16:36:52 -07003771 @Override
3772 public final DestructiveAction getBatchAction(int action) {
Vikram Aggarwalc4113952012-05-11 14:14:56 -07003773 final DestructiveAction da = new ConversationAction(action, mSelectedSet.values(), true);
Vikram Aggarwale8a85322012-04-24 09:01:38 -07003774 registerDestructiveAction(da);
3775 return da;
3776 }
Vikram Aggarwal41e6e712012-04-24 11:22:57 -07003777
Mindy Pereirade3e74a2012-07-24 09:43:10 -07003778 @Override
3779 public final DestructiveAction getDeferredBatchAction(int action) {
mindypf0656a12012-10-01 08:30:57 -07003780 return getDeferredAction(action, mSelectedSet.values(), true);
3781 }
3782
3783 /**
3784 * Get a destructive action for a menu action. This is a temporary method,
3785 * to control the profusion of {@link DestructiveAction} classes that are
3786 * created. Please do not copy this paradigm.
3787 * @param action the resource ID of the menu action: R.id.delete, for
3788 * example
3789 * @param target the conversations to act upon.
3790 * @return a {@link DestructiveAction} that performs the specified action.
3791 */
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08003792 private DestructiveAction getDeferredAction(int action, Collection<Conversation> target,
mindypf0656a12012-10-01 08:30:57 -07003793 boolean batch) {
Vikram Aggarwalb8c31712013-01-03 17:03:19 -08003794 return new ConversationAction(action, target, batch);
Mindy Pereirade3e74a2012-07-24 09:43:10 -07003795 }
3796
Vikram Aggarwalbc67bb12012-04-30 14:05:35 -07003797 /**
3798 * Class to change the folders that are assigned to a set of conversations. This is destructive
3799 * because the user can remove the current folder from the conversation, in which case it has
3800 * to be animated away from the current folder.
3801 */
Vikram Aggarwal41e6e712012-04-24 11:22:57 -07003802 private class FolderDestruction implements DestructiveAction {
Paul Westbrook77eee622012-07-10 13:41:57 -07003803 private final Collection<Conversation> mTarget;
Mindy Pereira8db7e402012-07-13 10:32:47 -07003804 private final ArrayList<FolderOperation> mFolderOps = new ArrayList<FolderOperation>();
Vikram Aggarwal41e6e712012-04-24 11:22:57 -07003805 private final boolean mIsDestructive;
Vikram Aggarwal7f602f72012-04-30 16:04:06 -07003806 /** Whether this destructive action has already been performed */
3807 private boolean mCompleted;
Martin Hibdone78c40f2013-10-10 18:29:25 -07003808 private final boolean mIsSelectedSet;
3809 private final boolean mShowUndo;
3810 private final int mAction;
Scott Kennedy6a3d5ce2013-03-15 17:33:14 -07003811 private final Folder mActionFolder;
Vikram Aggarwal41e6e712012-04-24 11:22:57 -07003812
3813 /**
3814 * Create a new folder destruction object to act on the given conversations.
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08003815 * @param target conversations to act upon.
Scott Kennedy6a3d5ce2013-03-15 17:33:14 -07003816 * @param actionFolder the {@link Folder} being acted upon, used for displaying the undo bar
Vikram Aggarwal41e6e712012-04-24 11:22:57 -07003817 */
Vikram Aggarwal7f602f72012-04-30 16:04:06 -07003818 private FolderDestruction(final Collection<Conversation> target,
Mindy Pereira8db7e402012-07-13 10:32:47 -07003819 final Collection<FolderOperation> folders, boolean isDestructive, boolean isBatch,
Scott Kennedy6a3d5ce2013-03-15 17:33:14 -07003820 boolean showUndo, int action, final Folder actionFolder) {
Paul Westbrook77eee622012-07-10 13:41:57 -07003821 mTarget = ImmutableList.copyOf(target);
Mindy Pereira8db7e402012-07-13 10:32:47 -07003822 mFolderOps.addAll(folders);
Vikram Aggarwal41e6e712012-04-24 11:22:57 -07003823 mIsDestructive = isDestructive;
Mindy Pereiraf3a45562012-05-24 16:30:19 -07003824 mIsSelectedSet = isBatch;
Mindy Pereira06642fa2012-07-12 16:23:27 -07003825 mShowUndo = showUndo;
Mindy Pereira01f30502012-08-14 10:30:51 -07003826 mAction = action;
Scott Kennedy6a3d5ce2013-03-15 17:33:14 -07003827 mActionFolder = actionFolder;
Vikram Aggarwal41e6e712012-04-24 11:22:57 -07003828 }
3829
Vikram Aggarwal41e6e712012-04-24 11:22:57 -07003830 @Override
3831 public void performAction() {
Vikram Aggarwal7f602f72012-04-30 16:04:06 -07003832 if (isPerformed()) {
3833 return;
3834 }
Mindy Pereira06642fa2012-07-12 16:23:27 -07003835 if (mIsDestructive && mShowUndo) {
mindypcb0b30e2012-11-30 10:16:35 -08003836 ToastBarOperation undoOp = new ToastBarOperation(mTarget.size(), mAction,
Scott Kennedy6a3d5ce2013-03-15 17:33:14 -07003837 ToastBarOperation.UNDO, mIsSelectedSet, mActionFolder);
Vikram Aggarwal41e6e712012-04-24 11:22:57 -07003838 onUndoAvailable(undoOp);
3839 }
Mindy Pereira8db7e402012-07-13 10:32:47 -07003840 // For each conversation, for each operation, add/ remove the
3841 // appropriate folders.
mindypcb0b30e2012-11-30 10:16:35 -08003842 ArrayList<ConversationOperation> ops = new ArrayList<ConversationOperation>();
3843 ArrayList<Uri> folderUris;
3844 ArrayList<Boolean> adds;
Mindy Pereira8db7e402012-07-13 10:32:47 -07003845 for (Conversation target : mTarget) {
mindypcb0b30e2012-11-30 10:16:35 -08003846 HashMap<Uri, Folder> targetFolders = Folder.hashMapForFolders(target
3847 .getRawFolders());
3848 folderUris = new ArrayList<Uri>();
mindypcb0b30e2012-11-30 10:16:35 -08003849 adds = new ArrayList<Boolean>();
Mindy Pereira01f30502012-08-14 10:30:51 -07003850 if (mIsDestructive) {
3851 target.localDeleteOnUpdate = true;
3852 }
Mindy Pereira8db7e402012-07-13 10:32:47 -07003853 for (FolderOperation op : mFolderOps) {
Scott Kennedy259df5b2013-07-11 13:24:01 -07003854 folderUris.add(op.mFolder.folderUri.fullUri);
mindypcb0b30e2012-11-30 10:16:35 -08003855 adds.add(op.mAdd ? Boolean.TRUE : Boolean.FALSE);
Mindy Pereira8db7e402012-07-13 10:32:47 -07003856 if (op.mAdd) {
Scott Kennedy259df5b2013-07-11 13:24:01 -07003857 targetFolders.put(op.mFolder.folderUri.fullUri, op.mFolder);
Mindy Pereira8db7e402012-07-13 10:32:47 -07003858 } else {
Scott Kennedy259df5b2013-07-11 13:24:01 -07003859 targetFolders.remove(op.mFolder.folderUri.fullUri);
Mindy Pereira8db7e402012-07-13 10:32:47 -07003860 }
3861 }
Paul Westbrook26746eb2012-12-06 14:44:01 -08003862 ops.add(mConversationListCursor.getConversationFolderOperation(target,
3863 folderUris, adds, targetFolders.values()));
mindyp389f0b22012-08-29 11:12:54 -07003864 }
3865 if (mConversationListCursor != null) {
Scott Kennedy9e2d4072013-03-21 21:46:01 -07003866 mConversationListCursor.updateBulkValues(ops);
Mindy Pereira8db7e402012-07-13 10:32:47 -07003867 }
Vikram Aggarwal7f602f72012-04-30 16:04:06 -07003868 refreshConversationList();
Mindy Pereiraf3a45562012-05-24 16:30:19 -07003869 if (mIsSelectedSet) {
3870 mSelectedSet.clear();
3871 }
Vikram Aggarwal7f602f72012-04-30 16:04:06 -07003872 }
Mindy Pereira8db7e402012-07-13 10:32:47 -07003873
Vikram Aggarwal7f602f72012-04-30 16:04:06 -07003874 /**
3875 * Returns true if this action has been performed, false otherwise.
Andy Huang839ada22012-07-20 15:48:40 -07003876 *
Vikram Aggarwal7f602f72012-04-30 16:04:06 -07003877 */
3878 private synchronized boolean isPerformed() {
3879 if (mCompleted) {
3880 return true;
Vikram Aggarwal41e6e712012-04-24 11:22:57 -07003881 }
Vikram Aggarwal7f602f72012-04-30 16:04:06 -07003882 mCompleted = true;
3883 return false;
Vikram Aggarwal41e6e712012-04-24 11:22:57 -07003884 }
3885 }
Vikram Aggarwal7f602f72012-04-30 16:04:06 -07003886
mindypc84759c2012-08-29 09:51:53 -07003887 public final DestructiveAction getFolderChange(Collection<Conversation> target,
3888 Collection<FolderOperation> folders, boolean isDestructive, boolean isBatch,
Scott Kennedy6a3d5ce2013-03-15 17:33:14 -07003889 boolean showUndo, final boolean isMoveTo, final Folder actionFolder) {
mindypc84759c2012-08-29 09:51:53 -07003890 final DestructiveAction da = getDeferredFolderChange(target, folders, isDestructive,
Scott Kennedy6a3d5ce2013-03-15 17:33:14 -07003891 isBatch, showUndo, isMoveTo, actionFolder);
mindypc84759c2012-08-29 09:51:53 -07003892 registerDestructiveAction(da);
3893 return da;
3894 }
3895
3896 public final DestructiveAction getDeferredFolderChange(Collection<Conversation> target,
Mindy Pereira8db7e402012-07-13 10:32:47 -07003897 Collection<FolderOperation> folders, boolean isDestructive, boolean isBatch,
Scott Kennedy6a3d5ce2013-03-15 17:33:14 -07003898 boolean showUndo, final boolean isMoveTo, final Folder actionFolder) {
3899 return new FolderDestruction(target, folders, isDestructive, isBatch, showUndo,
Andrew Sapperstein6c570db2013-08-06 17:21:36 -07003900 isMoveTo ? R.id.move_folder : R.id.change_folders, actionFolder);
Mindy Pereira01f30502012-08-14 10:30:51 -07003901 }
3902
3903 @Override
3904 public final DestructiveAction getDeferredRemoveFolder(Collection<Conversation> target,
3905 Folder toRemove, boolean isDestructive, boolean isBatch,
3906 boolean showUndo) {
3907 Collection<FolderOperation> folderOps = new ArrayList<FolderOperation>();
3908 folderOps.add(new FolderOperation(toRemove, false));
3909 return new FolderDestruction(target, folderOps, isDestructive, isBatch,
Scott Kennedy6a3d5ce2013-03-15 17:33:14 -07003910 showUndo, R.id.remove_folder, mFolder);
Mindy Pereira01f30502012-08-14 10:30:51 -07003911 }
3912
Vikram Aggarwal4f4782b2012-05-30 08:39:09 -07003913 @Override
3914 public final void refreshConversationList() {
Vikram Aggarwal75daee52012-04-30 11:13:09 -07003915 final ConversationListFragment convList = getConversationListFragment();
3916 if (convList == null) {
3917 return;
3918 }
3919 convList.requestListRefresh();
3920 }
Andrew Sappersteinc2c9dc12012-07-02 18:17:32 -07003921
3922 protected final ActionClickedListener getUndoClickedListener(
3923 final AnimatedAdapter listAdapter) {
3924 return new ActionClickedListener() {
3925 @Override
Andrew Sappersteinf8ccdcf2013-08-08 19:30:38 -07003926 public void onActionClicked(Context context) {
Andrew Sappersteinc2c9dc12012-07-02 18:17:32 -07003927 if (mAccount.undoUri != null) {
3928 // NOTE: We might want undo to return the messages affected, in which case
3929 // the resulting cursor might be interesting...
3930 // TODO: Use UIProvider.SEQUENCE_QUERY_PARAMETER to indicate the set of
3931 // commands to undo
3932 if (mConversationListCursor != null) {
3933 mConversationListCursor.undo(
3934 mActivity.getActivityContext(), mAccount.undoUri);
3935 }
3936 if (listAdapter != null) {
3937 listAdapter.setUndo(true);
3938 }
3939 }
3940 }
3941 };
3942 }
3943
Vikram Aggarwal41b9e8f2012-09-25 10:15:04 -07003944 /**
3945 * Shows an error toast in the bottom when a folder was not fetched successfully.
3946 * @param folder the folder which could not be fetched.
3947 * @param replaceVisibleToast if true, this should replace any currently visible toast.
3948 */
Andrew Sapperstein9d7519d2012-07-16 14:03:53 -07003949 protected final void showErrorToast(final Folder folder, boolean replaceVisibleToast) {
Andrew Sapperstein00179f12012-08-09 15:15:40 -07003950
Vikram Aggarwal41b9e8f2012-09-25 10:15:04 -07003951 final ActionClickedListener listener;
3952 final int actionTextResourceId;
Andrew Sapperstein00179f12012-08-09 15:15:40 -07003953 final int lastSyncResult = folder.lastSyncResult;
Vikram Aggarwal41b9e8f2012-09-25 10:15:04 -07003954 switch (lastSyncResult & 0x0f) {
Andrew Sapperstein00179f12012-08-09 15:15:40 -07003955 case UIProvider.LastSyncResult.CONNECTION_ERROR:
Vikram Aggarwal41b9e8f2012-09-25 10:15:04 -07003956 // The sync request that caused this failure.
3957 final int syncRequest = lastSyncResult >> 4;
3958 // Show: User explicitly pressed the refresh button and there is no connection
3959 // Show: The first time the user enters the app and there is no connection
3960 // TODO(viki): Implement this.
3961 // Reference: http://b/7202801
3962 final boolean showToast = (syncRequest & UIProvider.SyncStatus.USER_REFRESH) != 0;
3963 // Don't show: Already in the app; user switches to a synced label
3964 // Don't show: In a live label and a background sync fails
3965 final boolean avoidToast = !showToast && (folder.syncWindow > 0
3966 || (syncRequest & UIProvider.SyncStatus.BACKGROUND_SYNC) != 0);
3967 if (avoidToast) {
3968 return;
3969 }
Andrew Sapperstein00179f12012-08-09 15:15:40 -07003970 listener = getRetryClickedListener(folder);
3971 actionTextResourceId = R.string.retry;
3972 break;
3973 case UIProvider.LastSyncResult.AUTH_ERROR:
3974 listener = getSignInClickedListener();
3975 actionTextResourceId = R.string.signin;
3976 break;
3977 case UIProvider.LastSyncResult.SECURITY_ERROR:
3978 return; // Currently we do nothing for security errors.
3979 case UIProvider.LastSyncResult.STORAGE_ERROR:
3980 listener = getStorageErrorClickedListener();
3981 actionTextResourceId = R.string.info;
3982 break;
3983 case UIProvider.LastSyncResult.INTERNAL_ERROR:
3984 listener = getInternalErrorClickedListener();
3985 actionTextResourceId = R.string.report;
3986 break;
3987 default:
3988 return;
3989 }
Vikram Aggarwal41b9e8f2012-09-25 10:15:04 -07003990 mToastBar.show(listener,
Andrew Sapperstein5d420962012-07-12 16:43:10 -07003991 R.drawable.ic_alert_white,
Vikram Aggarwal41b9e8f2012-09-25 10:15:04 -07003992 Utils.getSyncStatusText(mActivity.getActivityContext(), lastSyncResult),
Andrew Sappersteinc2c9dc12012-07-02 18:17:32 -07003993 false, /* showActionIcon */
Andrew Sapperstein00179f12012-08-09 15:15:40 -07003994 actionTextResourceId,
Andrew Sapperstein9d7519d2012-07-16 14:03:53 -07003995 replaceVisibleToast,
Scott Kennedy6a3d5ce2013-03-15 17:33:14 -07003996 new ToastBarOperation(1, 0, ToastBarOperation.ERROR, false, folder));
Andrew Sappersteinc2c9dc12012-07-02 18:17:32 -07003997 }
3998
Andrew Sapperstein00179f12012-08-09 15:15:40 -07003999 private ActionClickedListener getRetryClickedListener(final Folder folder) {
Andrew Sappersteinc2c9dc12012-07-02 18:17:32 -07004000 return new ActionClickedListener() {
4001 @Override
Andrew Sappersteinf8ccdcf2013-08-08 19:30:38 -07004002 public void onActionClicked(Context context) {
Andrew Sappersteinc2c9dc12012-07-02 18:17:32 -07004003 final Uri uri = folder.refreshUri;
4004
4005 if (uri != null) {
Paul Westbrook4969e0c2012-08-20 14:38:39 -07004006 startAsyncRefreshTask(uri);
Andrew Sappersteinc2c9dc12012-07-02 18:17:32 -07004007 }
4008 }
4009 };
4010 }
Andrew Sapperstein00179f12012-08-09 15:15:40 -07004011
4012 private ActionClickedListener getSignInClickedListener() {
4013 return new ActionClickedListener() {
4014 @Override
Andrew Sappersteinf8ccdcf2013-08-08 19:30:38 -07004015 public void onActionClicked(Context context) {
Paul Westbrook122f7c22012-08-20 17:50:31 -07004016 promptUserForAuthentication(mAccount);
Andrew Sapperstein00179f12012-08-09 15:15:40 -07004017 }
4018 };
4019 }
4020
4021 private ActionClickedListener getStorageErrorClickedListener() {
4022 return new ActionClickedListener() {
4023 @Override
Andrew Sappersteinf8ccdcf2013-08-08 19:30:38 -07004024 public void onActionClicked(Context context) {
Paul Westbrook4969e0c2012-08-20 14:38:39 -07004025 showStorageErrorDialog();
Andrew Sapperstein00179f12012-08-09 15:15:40 -07004026 }
4027 };
4028 }
4029
Paul Westbrook4969e0c2012-08-20 14:38:39 -07004030 private void showStorageErrorDialog() {
4031 DialogFragment fragment = (DialogFragment)
4032 mFragmentManager.findFragmentByTag(SYNC_ERROR_DIALOG_FRAGMENT_TAG);
4033 if (fragment == null) {
4034 fragment = SyncErrorDialogFragment.newInstance();
4035 }
4036 fragment.show(mFragmentManager, SYNC_ERROR_DIALOG_FRAGMENT_TAG);
4037 }
4038
Andrew Sapperstein00179f12012-08-09 15:15:40 -07004039 private ActionClickedListener getInternalErrorClickedListener() {
4040 return new ActionClickedListener() {
4041 @Override
Andrew Sappersteinf8ccdcf2013-08-08 19:30:38 -07004042 public void onActionClicked(Context context) {
Paul Westbrook83e6b572013-02-05 16:22:42 -08004043 Utils.sendFeedback(mActivity, mAccount, true /* reportingProblem */);
Andrew Sapperstein00179f12012-08-09 15:15:40 -07004044 }
4045 };
4046 }
Paul Westbrook4969e0c2012-08-20 14:38:39 -07004047
4048 @Override
4049 public void onFooterViewErrorActionClick(Folder folder, int errorStatus) {
4050 Uri uri = null;
4051 switch (errorStatus) {
4052 case UIProvider.LastSyncResult.CONNECTION_ERROR:
4053 if (folder != null && folder.refreshUri != null) {
4054 uri = folder.refreshUri;
4055 }
4056 break;
4057 case UIProvider.LastSyncResult.AUTH_ERROR:
Paul Westbrook122f7c22012-08-20 17:50:31 -07004058 promptUserForAuthentication(mAccount);
Paul Westbrook4969e0c2012-08-20 14:38:39 -07004059 return;
4060 case UIProvider.LastSyncResult.SECURITY_ERROR:
4061 return; // Currently we do nothing for security errors.
4062 case UIProvider.LastSyncResult.STORAGE_ERROR:
4063 showStorageErrorDialog();
4064 return;
4065 case UIProvider.LastSyncResult.INTERNAL_ERROR:
Paul Westbrook83e6b572013-02-05 16:22:42 -08004066 Utils.sendFeedback(mActivity, mAccount, true /* reportingProblem */);
Paul Westbrook4969e0c2012-08-20 14:38:39 -07004067 return;
4068 default:
4069 return;
4070 }
4071
4072 if (uri != null) {
4073 startAsyncRefreshTask(uri);
4074 }
4075 }
4076
4077 @Override
4078 public void onFooterViewLoadMoreClick(Folder folder) {
4079 if (folder != null && folder.loadMoreUri != null) {
4080 startAsyncRefreshTask(folder.loadMoreUri);
4081 }
4082 }
4083
4084 private void startAsyncRefreshTask(Uri uri) {
4085 if (mFolderSyncTask != null) {
4086 mFolderSyncTask.cancel(true);
4087 }
4088 mFolderSyncTask = new AsyncRefreshTask(mActivity.getActivityContext(), uri);
4089 mFolderSyncTask.execute();
4090 }
Paul Westbrook122f7c22012-08-20 17:50:31 -07004091
4092 private void promptUserForAuthentication(Account account) {
Paul Westbrook429399b2012-08-24 11:19:17 -07004093 if (account != null && !Utils.isEmpty(account.reauthenticationIntentUri)) {
Paul Westbrook122f7c22012-08-20 17:50:31 -07004094 final Intent authenticationIntent =
4095 new Intent(Intent.ACTION_VIEW, account.reauthenticationIntentUri);
4096 mActivity.startActivityForResult(authenticationIntent, REAUTHENTICATE_REQUEST_CODE);
4097 }
4098 }
mindypca87de42012-09-28 15:02:39 -07004099
4100 @Override
4101 public void onAccessibilityStateChanged() {
4102 // Clear the cache of objects.
4103 ConversationItemViewModel.onAccessibilityUpdated();
4104 // Re-render the list if it exists.
Vikram Aggarwala91d00b2013-01-18 12:00:37 -08004105 final ConversationListFragment frag = getConversationListFragment();
mindypca87de42012-09-28 15:02:39 -07004106 if (frag != null) {
4107 AnimatedAdapter adapter = frag.getAnimatedAdapter();
4108 if (adapter != null) {
4109 adapter.notifyDataSetInvalidated();
4110 }
4111 }
4112 }
Vikram Aggarwal6cadbfc2012-12-27 09:17:05 -08004113
4114 @Override
Vikram Aggarwal84fe9942013-04-17 11:20:58 -07004115 public void makeDialogListener (final int action, final boolean isBatch) {
Vikram Aggarwalb8c31712013-01-03 17:03:19 -08004116 final Collection<Conversation> target;
Vikram Aggarwalb8c31712013-01-03 17:03:19 -08004117 if (isBatch) {
4118 target = mSelectedSet.values();
Vikram Aggarwalb8c31712013-01-03 17:03:19 -08004119 } else {
4120 LogUtils.d(LOG_TAG, "Will act upon %s", mCurrentConversation);
4121 target = Conversation.listOf(mCurrentConversation);
Vikram Aggarwalb8c31712013-01-03 17:03:19 -08004122 }
4123 final DestructiveAction destructiveAction = getDeferredAction(action, target, isBatch);
Vikram Aggarwal6cadbfc2012-12-27 09:17:05 -08004124 mDialogAction = action;
Vikram Aggarwalb8c31712013-01-03 17:03:19 -08004125 mDialogFromSelectedSet = isBatch;
Vikram Aggarwal6cadbfc2012-12-27 09:17:05 -08004126 mDialogListener = new AlertDialog.OnClickListener() {
4127 @Override
4128 public void onClick(DialogInterface dialog, int which) {
Scott Kennedycaaeed32013-06-12 13:39:16 -07004129 delete(action, target, destructiveAction, isBatch);
Vikram Aggarwal6cadbfc2012-12-27 09:17:05 -08004130 // Afterwards, let's remove references to the listener and the action.
4131 setListener(null, -1);
4132 }
4133 };
4134 }
4135
4136 @Override
4137 public AlertDialog.OnClickListener getListener() {
4138 return mDialogListener;
4139 }
4140
4141 /**
4142 * Sets the listener for the positive action on a confirmation dialog. Since only a single
4143 * confirmation dialog can be shown, this overwrites the previous listener. It is safe to
4144 * unset the listener; in which case action should be set to -1.
Vikram Aggarwal715f83d2013-03-05 17:04:56 -08004145 * @param listener the listener that will perform the task for this dialog's positive action.
4146 * @param action the action that created this dialog.
Vikram Aggarwal6cadbfc2012-12-27 09:17:05 -08004147 */
4148 private void setListener(AlertDialog.OnClickListener listener, final int action){
4149 mDialogListener = listener;
4150 mDialogAction = action;
4151 }
Vikram Aggarwal69a6cdf2013-01-08 16:05:17 -08004152
4153 @Override
4154 public VeiledAddressMatcher getVeiledAddressMatcher() {
4155 return mVeiledMatcher;
Vikram Aggarwala91d00b2013-01-18 12:00:37 -08004156 }
4157
4158 @Override
4159 public void setDetachedMode() {
4160 // Tell the conversation list not to select anything.
4161 final ConversationListFragment frag = getConversationListFragment();
4162 if (frag != null) {
4163 frag.setChoiceNone();
Vikram Aggarwal81230ee2013-02-26 15:26:44 -08004164 } else if (mIsTablet) {
4165 // How did we ever land here? Detached mode, and no CLF on tablet???
Vikram Aggarwala91d00b2013-01-18 12:00:37 -08004166 LogUtils.e(LOG_TAG, "AAC.setDetachedMode(): CLF = null!");
4167 }
4168 mDetachedConvUri = mCurrentConversation.uri;
4169 }
4170
4171 private void clearDetachedMode() {
4172 // Tell the conversation list to go back to its usual selection behavior.
4173 final ConversationListFragment frag = getConversationListFragment();
4174 if (frag != null) {
4175 frag.revertChoiceMode();
Vikram Aggarwal81230ee2013-02-26 15:26:44 -08004176 } else if (mIsTablet) {
4177 // How did we ever land here? Detached mode, and no CLF on tablet???
4178 LogUtils.e(LOG_TAG, "AAC.clearDetachedMode(): CLF = null on tablet!");
Vikram Aggarwala91d00b2013-01-18 12:00:37 -08004179 }
4180 mDetachedConvUri = null;
4181 }
Andy Huang12b3ee42013-04-24 22:49:43 -07004182
Andy Huang61f26c22014-03-13 18:24:52 -07004183 @Override
4184 public DrawerController getDrawerController() {
4185 return mDrawerListener;
4186 }
4187
4188 private class MailDrawerListener extends Observable<DrawerLayout.DrawerListener>
4189 implements DrawerLayout.DrawerListener, DrawerController {
Andrew Sappersteina3ce6782013-05-09 15:14:49 -07004190 private int mDrawerState;
Andrew Sappersteinfc5be1c2013-05-15 17:48:10 -07004191 private float mOldSlideOffset;
Andrew Sappersteina3ce6782013-05-09 15:14:49 -07004192
4193 public MailDrawerListener() {
4194 mDrawerState = DrawerLayout.STATE_IDLE;
Andrew Sappersteinfc5be1c2013-05-15 17:48:10 -07004195 mOldSlideOffset = 0.f;
Andrew Sappersteina3ce6782013-05-09 15:14:49 -07004196 }
4197
Andy Huang12b3ee42013-04-24 22:49:43 -07004198 @Override
Andy Huang61f26c22014-03-13 18:24:52 -07004199 public void registerDrawerListener(DrawerLayout.DrawerListener l) {
4200 registerObserver(l);
4201 }
4202
4203 @Override
4204 public void unregisterDrawerListener(DrawerLayout.DrawerListener l) {
4205 unregisterObserver(l);
4206 }
4207
4208 @Override
4209 public boolean isDrawerOpen() {
4210 return isDrawerEnabled() && mDrawerContainer.isDrawerOpen(mDrawerPullout);
4211 }
4212
4213 @Override
4214 public boolean isDrawerVisible() {
4215 return isDrawerEnabled() && mDrawerContainer.isDrawerVisible(mDrawerPullout);
4216 }
4217
4218 @Override
Andy Huang12b3ee42013-04-24 22:49:43 -07004219 public void onDrawerOpened(View drawerView) {
4220 mDrawerToggle.onDrawerOpened(drawerView);
Andy Huang61f26c22014-03-13 18:24:52 -07004221
4222 for (DrawerLayout.DrawerListener l : mObservers) {
4223 l.onDrawerOpened(drawerView);
4224 }
Andy Huang12b3ee42013-04-24 22:49:43 -07004225 }
4226
4227 @Override
4228 public void onDrawerClosed(View drawerView) {
4229 mDrawerToggle.onDrawerClosed(drawerView);
4230 if (mHasNewAccountOrFolder) {
4231 refreshDrawer();
4232 }
Scott Kennedy10c99ef2013-08-29 13:44:17 -07004233
4234 // When closed, we want to use either the burger, or up, based on where we are
4235 final int mode = mViewMode.getMode();
4236 final boolean isTopLevel = (mFolder == null) || (mFolder.parent == Uri.EMPTY);
4237 mDrawerToggle.setDrawerIndicatorEnabled(getShouldShowDrawerIndicator(mode, isTopLevel));
Andy Huang61f26c22014-03-13 18:24:52 -07004238
4239 for (DrawerLayout.DrawerListener l : mObservers) {
4240 l.onDrawerClosed(drawerView);
4241 }
Andy Huang12b3ee42013-04-24 22:49:43 -07004242 }
4243
4244 /**
4245 * As part of the overriden function, it will animate the alpha of the conversation list
4246 * view along with the drawer sliding when we're in the process of switching accounts or
4247 * folders. Note, this is the same amount of work done as {@link ValueAnimator#ofFloat}.
4248 */
4249 @Override
4250 public void onDrawerSlide(View drawerView, float slideOffset) {
4251 mDrawerToggle.onDrawerSlide(drawerView, slideOffset);
4252 if (mHasNewAccountOrFolder && mListViewForAnimating != null) {
4253 mListViewForAnimating.setAlpha(slideOffset);
4254 }
Andrew Sappersteinfc5be1c2013-05-15 17:48:10 -07004255
4256 // This code handles when to change the visibility of action items
4257 // based on drawer state. The basic logic is that right when we
4258 // open the drawer, we hide the action items. We show the action items
4259 // when the drawer closes. However, due to the animation of the drawer closing,
4260 // to make the reshowing of the action items feel right, we make the items visible
4261 // slightly sooner.
4262 //
4263 // However, to make the animating behavior work properly, we have to know whether
4264 // we're animating open or closed. Only if we're animating closed do we want to
4265 // show the action items early. We save the last slide offset so that we can compare
4266 // the current slide offset to it to determine if we're opening or closing.
4267 if (mDrawerState == DrawerLayout.STATE_SETTLING) {
4268 if (mHideMenuItems && slideOffset < 0.15f && mOldSlideOffset > slideOffset) {
4269 mHideMenuItems = false;
4270 mActivity.invalidateOptionsMenu();
Tony Mantler43fab322013-07-26 16:38:35 -07004271 maybeEnableCabMode();
Andrew Sappersteinfc5be1c2013-05-15 17:48:10 -07004272 } else if (!mHideMenuItems && slideOffset > 0.f && mOldSlideOffset < slideOffset) {
4273 mHideMenuItems = true;
4274 mActivity.invalidateOptionsMenu();
Tony Mantler43fab322013-07-26 16:38:35 -07004275 disableCabMode();
Andrew Sappersteinfc5be1c2013-05-15 17:48:10 -07004276 }
4277 } else {
4278 if (mHideMenuItems && Float.compare(slideOffset, 0.f) == 0) {
4279 mHideMenuItems = false;
4280 mActivity.invalidateOptionsMenu();
Tony Mantler43fab322013-07-26 16:38:35 -07004281 maybeEnableCabMode();
Andrew Sappersteinfc5be1c2013-05-15 17:48:10 -07004282 } else if (!mHideMenuItems && slideOffset > 0.f) {
4283 mHideMenuItems = true;
4284 mActivity.invalidateOptionsMenu();
Tony Mantler43fab322013-07-26 16:38:35 -07004285 disableCabMode();
Andrew Sappersteinfc5be1c2013-05-15 17:48:10 -07004286 }
4287 }
4288
4289 mOldSlideOffset = slideOffset;
Scott Kennedy10c99ef2013-08-29 13:44:17 -07004290
4291 // If we're sliding, we always want to show the burger
4292 mDrawerToggle.setDrawerIndicatorEnabled(true /* enable */);
Andy Huang61f26c22014-03-13 18:24:52 -07004293
4294 for (DrawerLayout.DrawerListener l : mObservers) {
4295 l.onDrawerSlide(drawerView, slideOffset);
4296 }
Andy Huang12b3ee42013-04-24 22:49:43 -07004297 }
4298
4299 /**
4300 * This condition here should only be called when the drawer is stuck in a weird state
4301 * and doesn't register the onDrawerClosed, but shows up as idle. Make sure to refresh
4302 * and, more importantly, unlock the drawer when this is the case.
4303 */
4304 @Override
4305 public void onDrawerStateChanged(int newState) {
Martin Hibdon371a71c2014-02-19 13:55:28 -08004306 LogUtils.d(LOG_TAG, "AAC onDrawerStateChanged %d", newState);
Andrew Sappersteina3ce6782013-05-09 15:14:49 -07004307 mDrawerState = newState;
4308 mDrawerToggle.onDrawerStateChanged(mDrawerState);
Andy Huang61f26c22014-03-13 18:24:52 -07004309
4310 for (DrawerLayout.DrawerListener l : mObservers) {
4311 l.onDrawerStateChanged(newState);
4312 }
4313
Andy Huange764cfd2014-02-26 11:55:03 -08004314 if (mViewMode.isSearchMode()) {
Martin Hibdon371a71c2014-02-19 13:55:28 -08004315 return;
4316 }
Andrew Sappersteina3ce6782013-05-09 15:14:49 -07004317 if (mDrawerState == DrawerLayout.STATE_IDLE) {
4318 if (mHasNewAccountOrFolder) {
4319 refreshDrawer();
4320 }
4321 if (mConversationListLoadFinishedIgnored) {
4322 mConversationListLoadFinishedIgnored = false;
4323 final Bundle args = new Bundle();
4324 args.putParcelable(BUNDLE_ACCOUNT_KEY, mAccount);
4325 args.putParcelable(BUNDLE_FOLDER_KEY, mFolder);
4326 mActivity.getLoaderManager().initLoader(
4327 LOADER_CONVERSATION_LIST, args, mListCursorCallbacks);
4328 }
Andy Huang12b3ee42013-04-24 22:49:43 -07004329 }
4330 }
4331
4332 /**
4333 * If we've reached a stable drawer state, unlock the drawer for usage, clear the
4334 * conversation list, and finish end actions. Also, make
4335 * {@link #mHasNewAccountOrFolder} false to reflect we're done changing.
4336 */
4337 public void refreshDrawer() {
4338 mHasNewAccountOrFolder = false;
4339 mDrawerContainer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
4340 ConversationListFragment conversationList = getConversationListFragment();
4341 if (conversationList != null) {
4342 conversationList.clear();
4343 }
4344 mDrawerObservers.notifyChanged();
4345 }
Andrew Sappersteina3ce6782013-05-09 15:14:49 -07004346
4347 /**
4348 * Returns the most recent update of the {@link DrawerLayout}'s state provided
4349 * by {@link #onDrawerStateChanged(int)}.
4350 * @return The {@link DrawerLayout}'s current state. One of
4351 * {@link DrawerLayout#STATE_DRAGGING}, {@link DrawerLayout#STATE_IDLE},
4352 * or {@link DrawerLayout#STATE_SETTLING}.
4353 */
4354 public int getDrawerState() {
4355 return mDrawerState;
4356 }
Andy Huang12b3ee42013-04-24 22:49:43 -07004357 }
4358
Scott Kennedy8a72b852013-05-02 14:18:50 -07004359 @Override
4360 public boolean isDrawerPullEnabled() {
Martin Hibdon371a71c2014-02-19 13:55:28 -08004361 return true;
Scott Kennedy8a72b852013-05-02 14:18:50 -07004362 }
Andrew Sapperstein5747e152013-05-13 14:13:08 -07004363
4364 @Override
4365 public boolean shouldHideMenuItems() {
4366 return mHideMenuItems;
4367 }
Alice Yangebeef1b2013-09-04 06:41:10 +00004368
4369 protected void navigateUpFolderHierarchy() {
4370 new AsyncTask<Void, Void, Folder>() {
4371 @Override
4372 protected Folder doInBackground(final Void... params) {
4373 if (mInbox == null) {
4374 // We don't have an inbox, but we need it
4375 final Cursor cursor = mContext.getContentResolver().query(
4376 mAccount.settings.defaultInbox, UIProvider.FOLDERS_PROJECTION, null,
4377 null, null);
4378
4379 if (cursor != null) {
4380 try {
4381 if (cursor.moveToFirst()) {
4382 mInbox = new Folder(cursor);
4383 }
4384 } finally {
4385 cursor.close();
4386 }
4387 }
4388 }
4389
4390 // Now try to load our parent
4391 final Folder folder;
4392
Alice Yang5ac10032013-09-04 06:41:43 +00004393 if (mFolder != null) {
Martin Hibdone78c40f2013-10-10 18:29:25 -07004394 Cursor cursor = null;
4395 try {
4396 cursor = mContext.getContentResolver().query(mFolder.parent,
4397 UIProvider.FOLDERS_PROJECTION, null, null, null);
Alice Yangebeef1b2013-09-04 06:41:10 +00004398
Martin Hibdone78c40f2013-10-10 18:29:25 -07004399 if (cursor == null || !cursor.moveToFirst()) {
4400 // We couldn't load the parent, so use the inbox
4401 folder = mInbox;
4402 } else {
Alice Yang5ac10032013-09-04 06:41:43 +00004403 folder = new Folder(cursor);
Martin Hibdone78c40f2013-10-10 18:29:25 -07004404 }
4405 } finally {
4406 if (cursor != null) {
Alice Yang5ac10032013-09-04 06:41:43 +00004407 cursor.close();
4408 }
Alice Yangebeef1b2013-09-04 06:41:10 +00004409 }
Alice Yang5ac10032013-09-04 06:41:43 +00004410 } else {
4411 folder = mInbox;
Alice Yangebeef1b2013-09-04 06:41:10 +00004412 }
4413
4414 return folder;
4415 }
4416
4417 @Override
4418 protected void onPostExecute(final Folder result) {
4419 onFolderSelected(result);
4420 }
4421 }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
4422 }
Scott Kennedyf77806e2013-08-30 11:38:15 -07004423
4424 @Override
4425 public Parcelable getConversationListScrollPosition(final String folderUri) {
4426 return mConversationListScrollPositions.getParcelable(folderUri);
4427 }
4428
4429 @Override
4430 public void setConversationListScrollPosition(final String folderUri,
4431 final Parcelable savedPosition) {
4432 mConversationListScrollPositions.putParcelable(folderUri, savedPosition);
4433 }
Vikram Aggarwal4a5c5302012-01-12 15:07:13 -08004434}