summaryrefslogtreecommitdiffstats
path: root/src/com/android/mail/ui/settings/GeneralPrefsFragment.java
blob: b47100700be9bedba922251465c432dd0e911eac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/*******************************************************************************
 *      Copyright (C) 2014 Google Inc.
 *      Licensed to The Android Open Source Project.
 *
 *      Licensed under the Apache License, Version 2.0 (the "License");
 *      you may not use this file except in compliance with the License.
 *      You may obtain a copy of the License at
 *
 *           http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing, software
 *      distributed under the License is distributed on an "AS IS" BASIS,
 *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *      See the License for the specific language governing permissions and
 *      limitations under the License.
 *******************************************************************************/

package com.android.mail.ui.settings;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.provider.SearchRecentSuggestions;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.android.emailcommon.provider.SuggestedContact;
import com.android.mail.preferences.MailPrefs;
import com.android.mail.preferences.MailPrefs.PreferenceKeys;
import com.android.mail.providers.SuggestionsProvider;
import com.android.mail.providers.UIProvider.AutoAdvance;
import com.android.mail.utils.LogUtils;
import com.android.mail.R;
import com.google.common.annotations.VisibleForTesting;

/**
 * This fragment shows general app preferences.
 */
public class GeneralPrefsFragment extends MailPreferenceFragment
        implements OnClickListener, OnPreferenceChangeListener {

    // Keys used to reference pref widgets which don't map directly to preference entries
    static final String AUTO_ADVANCE_WIDGET = "auto-advance-widget";
    static final String SUGGESTED_CONTACTS_CLEAR_ALL = "suggested-contacts-clear-all";

    static final String CALLED_FROM_TEST = "called-from-test";

    // Category for removal actions
    protected static final String REMOVAL_ACTIONS_GROUP = "removal-actions-group";

    protected MailPrefs mMailPrefs;

    private AlertDialog mClearSearchHistoryDialog;
    private AlertDialog mClearSuggestedContactsDialog;

    private ListPreference mAutoAdvance;
    private Preference mClearAllSuggestedContacts;

    private static final int[] AUTO_ADVANCE_VALUES = {
            AutoAdvance.NEWER,
            AutoAdvance.OLDER,
            AutoAdvance.LIST
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setHasOptionsMenu(true);

        mMailPrefs = MailPrefs.get(getActivity());

        // Set the shared prefs name to use prefs auto-persist behavior by default.
        // Any pref more complex than the default (say, involving migration), should set
        // "persistent=false" in the XML and manually handle preference initialization and change.
        getPreferenceManager()
                .setSharedPreferencesName(mMailPrefs.getSharedPreferencesName());

        addPreferencesFromResource(R.xml.general_preferences);

        mAutoAdvance = (ListPreference) findPreference(AUTO_ADVANCE_WIDGET);

        mClearAllSuggestedContacts = findPreference(SUGGESTED_CONTACTS_CLEAR_ALL);
        mClearAllSuggestedContacts.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                clearSuggestedContacts();
                return true;
            }
        });
        mClearAllSuggestedContacts.setEnabled(false);
        computeSuggestedContacts();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        /*
         * We deliberately do not call super because our menu includes the parent's menu options to
         * allow custom ordering.
         */
        menu.clear();
        inflater.inflate(R.menu.general_prefs_fragment_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        final int itemId = item.getItemId();
        if (itemId == R.id.clear_search_history_menu_item) {
            clearSearchHistory();
            return true;
        } else if (itemId == R.id.clear_picture_approvals_menu_item) {
            clearDisplayImages();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        if (getActivity() == null) {
            // Monkeys cause bad things. This callback may be delayed if for some reason the
            // preference screen was closed really quickly - just bail then.
            return false;
        }

        final String key = preference.getKey();

        if (PreferenceKeys.REMOVAL_ACTION.equals(key)) {
            final String removalAction = newValue.toString();
            mMailPrefs.setRemovalAction(removalAction);
        } else if (AUTO_ADVANCE_WIDGET.equals(key)) {
            final int prefsAutoAdvanceMode =
                    AUTO_ADVANCE_VALUES[mAutoAdvance.findIndexOfValue((String) newValue)];
            mMailPrefs.setAutoAdvanceMode(prefsAutoAdvanceMode);
        } else if (!PreferenceKeys.CONVERSATION_LIST_SWIPE.equals(key) &&
                !PreferenceKeys.SHOW_SENDER_IMAGES.equals(key) &&
                !PreferenceKeys.DEFAULT_REPLY_ALL.equals(key) &&
                !PreferenceKeys.CONVERSATION_OVERVIEW_MODE.equals(key) &&
                !PreferenceKeys.CONFIRM_DELETE.equals(key) &&
                !PreferenceKeys.CONFIRM_ARCHIVE.equals(key) &&
                !PreferenceKeys.CONFIRM_SEND.equals(key)) {
            return false;
        }

        return true;
    }

    private void clearDisplayImages() {
        final ClearPictureApprovalsDialogFragment fragment =
                ClearPictureApprovalsDialogFragment.newInstance();
        fragment.show(getActivity().getFragmentManager(),
                ClearPictureApprovalsDialogFragment.FRAGMENT_TAG);
    }

    private void clearSearchHistory() {
        mClearSearchHistoryDialog = new AlertDialog.Builder(getActivity())
                .setMessage(R.string.clear_history_dialog_message)
                .setTitle(R.string.clear_history_dialog_title)
                .setIconAttribute(android.R.attr.alertDialogIcon)
                .setPositiveButton(R.string.clear, this)
                .setNegativeButton(R.string.cancel, this)
                .show();
    }

    private void clearSuggestedContacts() {
        mClearSuggestedContactsDialog = new AlertDialog.Builder(getActivity())
            .setMessage(R.string.clear_suggested_contacts_dialog_message)
            .setTitle(R.string.clear_suggested_contacts_dialog_title)
            .setIconAttribute(android.R.attr.alertDialogIcon)
            .setPositiveButton(R.string.clear, this)
            .setNegativeButton(R.string.cancel, this)
            .show();
    }

    private void computeSuggestedContacts() {
        final Context context = getActivity();
        new AsyncTask<Void, Void, Integer>() {
            @Override
            protected Integer doInBackground(Void... params) {
                Cursor c = context.getContentResolver().query(
                        SuggestedContact.CONTENT_URI,
                        new String[] {"count(*) AS count"},
                        null,
                        null,
                        null);
                try {
                    if (c != null && c.moveToFirst()) {
                        return c.getInt(0);
                    }
                } finally {
                    if (c != null) {
                        c.close();
                    }
                }
                return 0;
            }
            @Override
            protected void onPostExecute(Integer result) {
                mClearAllSuggestedContacts.setEnabled(result > 0);
            }
        }.execute();
    }


    @Override
    public void onClick(DialogInterface dialog, int which) {
        if (dialog.equals(mClearSearchHistoryDialog)) {
            if (which == DialogInterface.BUTTON_POSITIVE) {
                final Context context = getActivity();
                // Clear the history in the background, as it causes a disk
                // write.
                new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                        final SuggestionsProvider suggestions =
                                new SuggestionsProvider(context);
                        suggestions.clearHistory();
                        suggestions.cleanup();
                        return null;
                    }
                }.execute();
                Toast.makeText(getActivity(), R.string.search_history_cleared, Toast.LENGTH_SHORT)
                        .show();
            }
        } else if (dialog.equals(mClearSuggestedContactsDialog)) {
            if (which == DialogInterface.BUTTON_POSITIVE) {
                final Context context = getActivity();
                // Clear the suggested contacts in the background, as it causes a disk
                // write.
                new AsyncTask<Void, Void, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                        context.getContentResolver().delete(
                                SuggestedContact.CONTENT_URI, null, null);
                        computeSuggestedContacts();
                        return null;
                    }
                }.execute();
                Toast.makeText(getActivity(), R.string.suggested_contacts_cleared,
                        Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mClearSearchHistoryDialog != null && mClearSearchHistoryDialog.isShowing()) {
            mClearSearchHistoryDialog.dismiss();
        }
        if (mClearSuggestedContactsDialog != null && mClearSuggestedContactsDialog.isShowing()) {
            mClearSuggestedContactsDialog.dismiss();
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        // Manually initialize the preference views that require massaging. Prefs that require
        // massaging include:
        //  1. a prefs UI control that does not map 1:1 to storage
        //  2. a pref that must obtain its initial value from migrated storage, and for which we
        //     don't want to always persist a migrated value
        final int autoAdvanceModeIndex = prefValueToWidgetIndex(AUTO_ADVANCE_VALUES,
                mMailPrefs.getAutoAdvanceMode(), AutoAdvance.DEFAULT);
        mAutoAdvance.setValueIndex(autoAdvanceModeIndex);

        listenForPreferenceChange(
                PreferenceKeys.REMOVAL_ACTION,
                PreferenceKeys.CONVERSATION_LIST_SWIPE,
                PreferenceKeys.SHOW_SENDER_IMAGES,
                PreferenceKeys.DEFAULT_REPLY_ALL,
                PreferenceKeys.CONVERSATION_OVERVIEW_MODE,
                AUTO_ADVANCE_WIDGET,
                PreferenceKeys.CONFIRM_DELETE,
                PreferenceKeys.CONFIRM_ARCHIVE,
                PreferenceKeys.CONFIRM_SEND
        );
    }

    protected boolean supportsArchive() {
        return true;
    }

    /**
     * Converts the prefs value into an index useful for configuring the UI widget, falling back to
     * the default value if the value from the prefs can't be found for some reason. If neither can
     * be found, it throws an {@link java.lang.IllegalArgumentException}
     *
     * @param conversionArray An array of prefs values, in widget order
     * @param prefValue Value of the preference
     * @param defaultValue Default value, as a fallback if we can't map the real value
     * @return Index of the entry (or fallback) in the conversion array
     */
    @VisibleForTesting
    static int prefValueToWidgetIndex(int[] conversionArray, int prefValue, int defaultValue) {
        for (int i = 0; i < conversionArray.length; i++) {
            if (conversionArray[i] == prefValue) {
                return i;
            }
        }
        LogUtils.e(LogUtils.TAG, "Can't map preference value " + prefValue);
        for (int i = 0; i < conversionArray.length; i++) {
            if (conversionArray[i] == defaultValue) {
                return i;
            }
        }
        throw new IllegalArgumentException("Can't map default preference value " + prefValue);
    }

    private void listenForPreferenceChange(String... keys) {
        for (String key : keys) {
            Preference p = findPreference(key);
            if (p != null) {
                p.setOnPreferenceChangeListener(this);
            }
        }
    }
}