1/**
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package com.android.phone.settings;
18
19import android.app.Dialog;
20import android.content.DialogInterface;
21import android.content.Intent;
22import android.database.Cursor;
23import android.os.AsyncResult;
24import android.os.Bundle;
25import android.os.Handler;
26import android.os.Message;
27import android.preference.CheckBoxPreference;
28import android.preference.Preference;
29import android.preference.PreferenceActivity;
30import android.preference.PreferenceScreen;
31import android.preference.SwitchPreference;
32import android.provider.ContactsContract.CommonDataKinds;
33import android.telecom.PhoneAccountHandle;
34import android.text.BidiFormatter;
35import android.text.TextDirectionHeuristics;
36import android.text.TextUtils;
37import android.util.Log;
38import android.view.MenuItem;
39import android.widget.ListAdapter;
40import com.android.internal.telephony.CallForwardInfo;
41import com.android.internal.telephony.Phone;
42import com.android.internal.telephony.PhoneConstants;
43import com.android.phone.EditPhoneNumberPreference;
44import com.android.phone.PhoneGlobals;
45import com.android.phone.PhoneUtils;
46import com.android.phone.R;
47import com.android.phone.SubscriptionInfoHelper;
48import com.android.phone.vvm.omtp.OmtpConstants;
49import com.android.phone.vvm.omtp.OmtpVvmCarrierConfigHelper;
50import com.android.phone.vvm.omtp.VisualVoicemailPreferences;
51import java.util.Collection;
52import java.util.HashMap;
53import java.util.HashSet;
54import java.util.Iterator;
55import java.util.Map;
56
57public class VoicemailSettingsActivity extends PreferenceActivity
58        implements DialogInterface.OnClickListener,
59                Preference.OnPreferenceChangeListener,
60                EditPhoneNumberPreference.OnDialogClosedListener,
61                EditPhoneNumberPreference.GetDefaultNumberListener,
62                VoicemailRingtonePreference.VoicemailRingtoneNameChangeListener {
63    private static final String LOG_TAG = VoicemailSettingsActivity.class.getSimpleName();
64    private static final boolean DBG = (PhoneGlobals.DBG_LEVEL >= 2);
65
66    /**
67     * Intent action to bring up Voicemail Provider settings
68     * DO NOT RENAME. There are existing apps which use this intent value.
69     */
70    public static final String ACTION_ADD_VOICEMAIL =
71            "com.android.phone.CallFeaturesSetting.ADD_VOICEMAIL";
72
73    /**
74     * Intent action to bring up the {@code VoicemailSettingsActivity}.
75     * DO NOT RENAME. There are existing apps which use this intent value.
76     */
77    public static final String ACTION_CONFIGURE_VOICEMAIL =
78            "com.android.phone.CallFeaturesSetting.CONFIGURE_VOICEMAIL";
79
80    // Extra put in the return from VM provider config containing voicemail number to set
81    public static final String VM_NUMBER_EXTRA = "com.android.phone.VoicemailNumber";
82    // Extra put in the return from VM provider config containing call forwarding number to set
83    public static final String FWD_NUMBER_EXTRA = "com.android.phone.ForwardingNumber";
84    // Extra put in the return from VM provider config containing call forwarding number to set
85    public static final String FWD_NUMBER_TIME_EXTRA = "com.android.phone.ForwardingNumberTime";
86    // If the VM provider returns non null value in this extra we will force the user to
87    // choose another VM provider
88    public static final String SIGNOUT_EXTRA = "com.android.phone.Signout";
89
90    /**
91     * String Extra put into ACTION_ADD_VOICEMAIL call to indicate which provider should be hidden
92     * in the list of providers presented to the user. This allows a provider which is being
93     * disabled (e.g. GV user logging out) to force the user to pick some other provider.
94     */
95    public static final String IGNORE_PROVIDER_EXTRA = "com.android.phone.ProviderToIgnore";
96
97    /**
98     * String Extra put into ACTION_ADD_VOICEMAIL to indicate that the voicemail setup screen should
99     * be opened.
100     */
101    public static final String SETUP_VOICEMAIL_EXTRA = "com.android.phone.SetupVoicemail";
102
103    // TODO: Define these preference keys in XML.
104    private static final String BUTTON_VOICEMAIL_KEY = "button_voicemail_key";
105    private static final String BUTTON_VOICEMAIL_PROVIDER_KEY = "button_voicemail_provider_key";
106    private static final String BUTTON_VOICEMAIL_SETTING_KEY = "button_voicemail_setting_key";
107
108    /** Event for Async voicemail change call */
109    private static final int EVENT_VOICEMAIL_CHANGED        = 500;
110    private static final int EVENT_FORWARDING_CHANGED       = 501;
111    private static final int EVENT_FORWARDING_GET_COMPLETED = 502;
112
113    /** Handle to voicemail pref */
114    private static final int VOICEMAIL_PREF_ID = 1;
115    private static final int VOICEMAIL_PROVIDER_CFG_ID = 2;
116
117    /**
118     * Results of reading forwarding settings
119     */
120    private CallForwardInfo[] mForwardingReadResults = null;
121
122    /**
123     * Result of forwarding number change.
124     * Keys are reasons (eg. unconditional forwarding).
125     */
126    private Map<Integer, AsyncResult> mForwardingChangeResults = null;
127
128    /**
129     * Expected CF read result types.
130     * This set keeps track of the CF types for which we've issued change
131     * commands so we can tell when we've received all of the responses.
132     */
133    private Collection<Integer> mExpectedChangeResultReasons = null;
134
135    /**
136     * Result of vm number change
137     */
138    private AsyncResult mVoicemailChangeResult = null;
139
140    /**
141     * Previous VM provider setting so we can return to it in case of failure.
142     */
143    private String mPreviousVMProviderKey = null;
144
145    /**
146     * Id of the dialog being currently shown.
147     */
148    private int mCurrentDialogId = 0;
149
150    /**
151     * Flag indicating that we are invoking settings for the voicemail provider programmatically
152     * due to vm provider change.
153     */
154    private boolean mVMProviderSettingsForced = false;
155
156    /**
157     * Flag indicating that we are making changes to vm or fwd numbers
158     * due to vm provider change.
159     */
160    private boolean mChangingVMorFwdDueToProviderChange = false;
161
162    /**
163     * True if we are in the process of vm & fwd number change and vm has already been changed.
164     * This is used to decide what to do in case of rollback.
165     */
166    private boolean mVMChangeCompletedSuccessfully = false;
167
168    /**
169     * True if we had full or partial failure setting forwarding numbers and so need to roll them
170     * back.
171     */
172    private boolean mFwdChangesRequireRollback = false;
173
174    /**
175     * Id of error msg to display to user once we are done reverting the VM provider to the previous
176     * one.
177     */
178    private int mVMOrFwdSetError = 0;
179
180    /** string to hold old voicemail number as it is being updated. */
181    private String mOldVmNumber;
182
183    // New call forwarding settings and vm number we will be setting
184    // Need to save these since before we get to saving we need to asynchronously
185    // query the existing forwarding settings.
186    private CallForwardInfo[] mNewFwdSettings;
187    private String mNewVMNumber;
188
189    private CharSequence mOldVmRingtoneName = "";
190
191    /**
192     * Used to indicate that the voicemail preference should be shown.
193     */
194    private boolean mShowVoicemailPreference = false;
195
196    private boolean mForeground;
197    private Phone mPhone;
198    private PhoneAccountHandle mPhoneAccountHandle;
199    private SubscriptionInfoHelper mSubscriptionInfoHelper;
200    private OmtpVvmCarrierConfigHelper mOmtpVvmCarrierConfigHelper;
201
202    private EditPhoneNumberPreference mSubMenuVoicemailSettings;
203    private VoicemailProviderListPreference mVoicemailProviders;
204    private PreferenceScreen mVoicemailSettings;
205    private VoicemailRingtonePreference mVoicemailNotificationRingtone;
206    private CheckBoxPreference mVoicemailNotificationVibrate;
207    private SwitchPreference mVoicemailVisualVoicemail;
208    private Preference mVoicemailChangePinPreference;
209
210    //*********************************************************************************************
211    // Preference Activity Methods
212    //*********************************************************************************************
213
214    @Override
215    protected void onCreate(Bundle icicle) {
216        super.onCreate(icicle);
217
218        // Show the voicemail preference in onResume if the calling intent specifies the
219        // ACTION_ADD_VOICEMAIL action.
220        mShowVoicemailPreference = (icicle == null) &&
221                TextUtils.equals(getIntent().getAction(), ACTION_ADD_VOICEMAIL);
222
223        mSubscriptionInfoHelper = new SubscriptionInfoHelper(this, getIntent());
224        mSubscriptionInfoHelper.setActionBarTitle(
225                getActionBar(), getResources(), R.string.voicemail_settings_with_label);
226        mPhone = mSubscriptionInfoHelper.getPhone();
227        mPhoneAccountHandle = PhoneUtils.makePstnPhoneAccountHandle(mPhone);
228        mOmtpVvmCarrierConfigHelper = new OmtpVvmCarrierConfigHelper(
229                mPhone.getContext(), mPhone.getSubId());
230    }
231
232    @Override
233    protected void onResume() {
234        super.onResume();
235        mForeground = true;
236
237        PreferenceScreen preferenceScreen = getPreferenceScreen();
238        if (preferenceScreen != null) {
239            preferenceScreen.removeAll();
240        }
241
242        addPreferencesFromResource(R.xml.voicemail_settings);
243
244        PreferenceScreen prefSet = getPreferenceScreen();
245        mSubMenuVoicemailSettings = (EditPhoneNumberPreference) findPreference(BUTTON_VOICEMAIL_KEY);
246        mSubMenuVoicemailSettings.setParentActivity(this, VOICEMAIL_PREF_ID, this);
247        mSubMenuVoicemailSettings.setDialogOnClosedListener(this);
248        mSubMenuVoicemailSettings.setDialogTitle(R.string.voicemail_settings_number_label);
249
250        mVoicemailProviders = (VoicemailProviderListPreference) findPreference(
251                BUTTON_VOICEMAIL_PROVIDER_KEY);
252        mVoicemailProviders.init(mPhone, getIntent());
253        mVoicemailProviders.setOnPreferenceChangeListener(this);
254        mPreviousVMProviderKey = mVoicemailProviders.getValue();
255
256        mVoicemailSettings = (PreferenceScreen) findPreference(BUTTON_VOICEMAIL_SETTING_KEY);
257
258        mVoicemailNotificationRingtone = (VoicemailRingtonePreference) findPreference(
259                getResources().getString(R.string.voicemail_notification_ringtone_key));
260        mVoicemailNotificationRingtone.setVoicemailRingtoneNameChangeListener(this);
261        mVoicemailNotificationRingtone.init(mPhone, mOldVmRingtoneName);
262
263        mVoicemailNotificationVibrate = (CheckBoxPreference) findPreference(
264                getResources().getString(R.string.voicemail_notification_vibrate_key));
265        mVoicemailNotificationVibrate.setOnPreferenceChangeListener(this);
266
267        mVoicemailVisualVoicemail = (SwitchPreference) findPreference(
268                getResources().getString(R.string.voicemail_visual_voicemail_key));
269
270        mVoicemailChangePinPreference = findPreference(
271                getResources().getString(R.string.voicemail_change_pin_key));
272        Intent changePinIntent = new Intent(new Intent(this, VoicemailChangePinActivity.class));
273        changePinIntent.putExtra(VoicemailChangePinActivity.EXTRA_PHONE_ACCOUNT_HANDLE,
274                mPhoneAccountHandle);
275
276        mVoicemailChangePinPreference.setIntent(changePinIntent);
277        if (VoicemailChangePinActivity.isDefaultOldPinSet(this, mPhoneAccountHandle)) {
278            mVoicemailChangePinPreference.setTitle(R.string.voicemail_set_pin_dialog_title);
279        } else {
280            mVoicemailChangePinPreference.setTitle(R.string.voicemail_change_pin_dialog_title);
281        }
282
283        if (mOmtpVvmCarrierConfigHelper.isValid()) {
284            mVoicemailVisualVoicemail.setOnPreferenceChangeListener(this);
285            mVoicemailVisualVoicemail.setChecked(
286                    VisualVoicemailSettingsUtil.isEnabled(this, mPhoneAccountHandle));
287            if (!isVisualVoicemailActivated()) {
288                prefSet.removePreference(mVoicemailChangePinPreference);
289            }
290        } else {
291            prefSet.removePreference(mVoicemailVisualVoicemail);
292            prefSet.removePreference(mVoicemailChangePinPreference);
293        }
294
295        updateVMPreferenceWidgets(mVoicemailProviders.getValue());
296
297        // check the intent that started this activity and pop up the voicemail
298        // dialog if we've been asked to.
299        // If we have at least one non default VM provider registered then bring up
300        // the selection for the VM provider, otherwise bring up a VM number dialog.
301        // We only bring up the dialog the first time we are called (not after orientation change)
302        if (mShowVoicemailPreference) {
303            if (DBG) log("ACTION_ADD_VOICEMAIL Intent is thrown");
304            if (mVoicemailProviders.hasMoreThanOneVoicemailProvider()) {
305                if (DBG) log("Voicemail data has more than one provider.");
306                simulatePreferenceClick(mVoicemailProviders);
307            } else {
308                onPreferenceChange(mVoicemailProviders, VoicemailProviderListPreference.DEFAULT_KEY);
309                mVoicemailProviders.setValue(VoicemailProviderListPreference.DEFAULT_KEY);
310            }
311            mShowVoicemailPreference = false;
312        }
313
314        updateVoiceNumberField();
315        mVMProviderSettingsForced = false;
316
317        mVoicemailNotificationVibrate.setChecked(
318                VoicemailNotificationSettingsUtil.isVibrationEnabled(mPhone));
319    }
320
321    @Override
322    public void onPause() {
323        super.onPause();
324        mForeground = false;
325    }
326
327    @Override
328    public boolean onOptionsItemSelected(MenuItem item) {
329        if (item.getItemId() == android.R.id.home) {
330            onBackPressed();
331            return true;
332        }
333        return super.onOptionsItemSelected(item);
334    }
335
336    @Override
337    public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
338        if (preference == mSubMenuVoicemailSettings) {
339            return true;
340        } else if (preference.getKey().equals(mVoicemailSettings.getKey())) {
341            // Check key instead of comparing reference because closing the voicemail notification
342            // ringtone dialog invokes onResume(), but leaves the old preference screen up,
343            // TODO: Revert to checking reference after migrating voicemail to its own activity.
344            if (DBG) log("onPreferenceTreeClick: Voicemail Settings Preference is clicked.");
345
346            final Dialog dialog = ((PreferenceScreen) preference).getDialog();
347            if (dialog != null) {
348                dialog.getActionBar().setDisplayHomeAsUpEnabled(false);
349            }
350
351            if (preference.getIntent() != null) {
352                if (DBG) log("Invoking cfg intent " + preference.getIntent().getPackage());
353
354                // onActivityResult() will be responsible for resetting some of variables.
355                this.startActivityForResult(preference.getIntent(), VOICEMAIL_PROVIDER_CFG_ID);
356                return true;
357            } else {
358                if (DBG) log("onPreferenceTreeClick(). No intent; use default behavior in xml.");
359
360                // onActivityResult() will not be called, so reset variables here.
361                mPreviousVMProviderKey = VoicemailProviderListPreference.DEFAULT_KEY;
362                mVMProviderSettingsForced = false;
363                return false;
364            }
365        }
366        return false;
367    }
368
369    /**
370     * Implemented to support onPreferenceChangeListener to look for preference changes.
371     *
372     * @param preference is the preference to be changed
373     * @param objValue should be the value of the selection, NOT its localized
374     * display value.
375     */
376    @Override
377    public boolean onPreferenceChange(Preference preference, Object objValue) {
378        if (DBG) log("onPreferenceChange: \"" + preference + "\" changed to \"" + objValue + "\"");
379
380        if (preference == mVoicemailProviders) {
381            final String newProviderKey = (String) objValue;
382
383            // If previous provider key and the new one is same, we don't need to handle it.
384            if (mPreviousVMProviderKey.equals(newProviderKey)) {
385                if (DBG) log("No change is made to the VM provider setting.");
386                return true;
387            }
388            updateVMPreferenceWidgets(newProviderKey);
389
390            final VoicemailProviderSettings newProviderSettings =
391                    VoicemailProviderSettingsUtil.load(this, newProviderKey);
392
393            // If the user switches to a voice mail provider and we have numbers stored for it we
394            // will automatically change the phone's voice mail and forwarding number to the stored
395            // ones. Otherwise we will bring up provider's configuration UI.
396            if (newProviderSettings == null) {
397                // Force the user into a configuration of the chosen provider
398                Log.w(LOG_TAG, "Saved preferences not found - invoking config");
399                mVMProviderSettingsForced = true;
400                simulatePreferenceClick(mVoicemailSettings);
401            } else {
402                if (DBG) log("Saved preferences found - switching to them");
403                // Set this flag so if we get a failure we revert to previous provider
404                mChangingVMorFwdDueToProviderChange = true;
405                saveVoiceMailAndForwardingNumber(newProviderKey, newProviderSettings);
406            }
407        } else if (preference.getKey().equals(mVoicemailNotificationVibrate.getKey())) {
408            // Check key instead of comparing reference because closing the voicemail notification
409            // ringtone dialog invokes onResume(), but leaves the old preference screen up,
410            // TODO: Revert to checking reference after migrating voicemail to its own activity.
411            VoicemailNotificationSettingsUtil.setVibrationEnabled(
412                    mPhone, Boolean.TRUE.equals(objValue));
413        } else if (preference.getKey().equals(mVoicemailVisualVoicemail.getKey())) {
414            boolean isEnabled = (boolean) objValue;
415            VisualVoicemailSettingsUtil
416                    .setEnabled(mPhone.getContext(), mPhoneAccountHandle, isEnabled);
417            PreferenceScreen prefSet = getPreferenceScreen();
418            if (isVisualVoicemailActivated()) {
419                prefSet.addPreference(mVoicemailChangePinPreference);
420            } else {
421                prefSet.removePreference(mVoicemailChangePinPreference);
422            }
423        }
424
425        // Always let the preference setting proceed.
426        return true;
427    }
428
429    /**
430     * Implemented for EditPhoneNumberPreference.GetDefaultNumberListener.
431     * This method set the default values for the various
432     * EditPhoneNumberPreference dialogs.
433     */
434    @Override
435    public String onGetDefaultNumber(EditPhoneNumberPreference preference) {
436        if (preference == mSubMenuVoicemailSettings) {
437            // update the voicemail number field, which takes care of the
438            // mSubMenuVoicemailSettings itself, so we should return null.
439            if (DBG) log("updating default for voicemail dialog");
440            updateVoiceNumberField();
441            return null;
442        }
443
444        String vmDisplay = mPhone.getVoiceMailNumber();
445        if (TextUtils.isEmpty(vmDisplay)) {
446            // if there is no voicemail number, we just return null to
447            // indicate no contribution.
448            return null;
449        }
450
451        // Return the voicemail number prepended with "VM: "
452        if (DBG) log("updating default for call forwarding dialogs");
453        return getString(R.string.voicemail_abbreviated) + " " + vmDisplay;
454    }
455
456    @Override
457    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
458        if (DBG) {
459            log("onActivityResult: requestCode: " + requestCode
460                    + ", resultCode: " + resultCode
461                    + ", data: " + data);
462        }
463
464        // there are cases where the contact picker may end up sending us more than one
465        // request.  We want to ignore the request if we're not in the correct state.
466        if (requestCode == VOICEMAIL_PROVIDER_CFG_ID) {
467            boolean failure = false;
468
469            // No matter how the processing of result goes lets clear the flag
470            if (DBG) log("mVMProviderSettingsForced: " + mVMProviderSettingsForced);
471            final boolean isVMProviderSettingsForced = mVMProviderSettingsForced;
472            mVMProviderSettingsForced = false;
473
474            String vmNum = null;
475            if (resultCode != RESULT_OK) {
476                if (DBG) log("onActivityResult: vm provider cfg result not OK.");
477                failure = true;
478            } else {
479                if (data == null) {
480                    if (DBG) log("onActivityResult: vm provider cfg result has no data");
481                    failure = true;
482                } else {
483                    if (data.getBooleanExtra(SIGNOUT_EXTRA, false)) {
484                        if (DBG) log("Provider requested signout");
485                        if (isVMProviderSettingsForced) {
486                            if (DBG) log("Going back to previous provider on signout");
487                            switchToPreviousVoicemailProvider();
488                        } else {
489                            final String victim = mVoicemailProviders.getKey();
490                            if (DBG) log("Relaunching activity and ignoring " + victim);
491                            Intent i = new Intent(ACTION_ADD_VOICEMAIL);
492                            i.putExtra(IGNORE_PROVIDER_EXTRA, victim);
493                            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
494                            this.startActivity(i);
495                        }
496                        return;
497                    }
498                    vmNum = data.getStringExtra(VM_NUMBER_EXTRA);
499                    if (vmNum == null || vmNum.length() == 0) {
500                        if (DBG) log("onActivityResult: vm provider cfg result has no vmnum");
501                        failure = true;
502                    }
503                }
504            }
505            if (failure) {
506                if (DBG) log("Failure in return from voicemail provider.");
507                if (isVMProviderSettingsForced) {
508                    switchToPreviousVoicemailProvider();
509                }
510
511                return;
512            }
513            mChangingVMorFwdDueToProviderChange = isVMProviderSettingsForced;
514            final String fwdNum = data.getStringExtra(FWD_NUMBER_EXTRA);
515
516            // TODO: It would be nice to load the current network setting for this and
517            // send it to the provider when it's config is invoked so it can use this as default
518            final int fwdNumTime = data.getIntExtra(FWD_NUMBER_TIME_EXTRA, 20);
519
520            if (DBG) log("onActivityResult: cfg result has forwarding number " + fwdNum);
521            saveVoiceMailAndForwardingNumber(mVoicemailProviders.getKey(),
522                    new VoicemailProviderSettings(vmNum, fwdNum, fwdNumTime));
523            return;
524        }
525
526        if (requestCode == VOICEMAIL_PREF_ID) {
527            if (resultCode != RESULT_OK) {
528                if (DBG) log("onActivityResult: contact picker result not OK.");
529                return;
530            }
531
532            Cursor cursor = null;
533            try {
534                cursor = getContentResolver().query(data.getData(),
535                    new String[] { CommonDataKinds.Phone.NUMBER }, null, null, null);
536                if ((cursor == null) || (!cursor.moveToFirst())) {
537                    if (DBG) log("onActivityResult: bad contact data, no results found.");
538                    return;
539                }
540                if (mSubMenuVoicemailSettings != null) {
541                    mSubMenuVoicemailSettings.onPickActivityResult(cursor.getString(0));
542                } else {
543                    Log.w(LOG_TAG, "VoicemailSettingsActivity destroyed while setting contacts.");
544                }
545                return;
546            } finally {
547                if (cursor != null) {
548                    cursor.close();
549                }
550            }
551        }
552
553        super.onActivityResult(requestCode, resultCode, data);
554    }
555
556    @Override
557    public void onVoicemailRingtoneNameChanged(CharSequence name) {
558        mOldVmRingtoneName = name;
559    }
560
561    /**
562     * Simulates user clicking on a passed preference.
563     * Usually needed when the preference is a dialog preference and we want to invoke
564     * a dialog for this preference programmatically.
565     * TODO: figure out if there is a cleaner way to cause preference dlg to come up
566     */
567    private void simulatePreferenceClick(Preference preference) {
568        // Go through settings until we find our setting
569        // and then simulate a click on it to bring up the dialog
570        final ListAdapter adapter = getPreferenceScreen().getRootAdapter();
571        for (int idx = 0; idx < adapter.getCount(); idx++) {
572            if (adapter.getItem(idx) == preference) {
573                getPreferenceScreen().onItemClick(this.getListView(),
574                        null, idx, adapter.getItemId(idx));
575                break;
576            }
577        }
578    }
579
580
581    //*********************************************************************************************
582    // Activity Dialog Methods
583    //*********************************************************************************************
584
585    @Override
586    protected void onPrepareDialog(int id, Dialog dialog) {
587        super.onPrepareDialog(id, dialog);
588        mCurrentDialogId = id;
589    }
590
591    // dialog creation method, called by showDialog()
592    @Override
593    protected Dialog onCreateDialog(int dialogId) {
594        return VoicemailDialogUtil.getDialog(this, dialogId);
595    }
596
597    @Override
598    public void onDialogClosed(EditPhoneNumberPreference preference, int buttonClicked) {
599        if (DBG) log("onDialogClosed: Button clicked is " + buttonClicked);
600
601        if (buttonClicked == DialogInterface.BUTTON_NEGATIVE) {
602            return;
603        }
604
605        if (preference == mSubMenuVoicemailSettings) {
606            VoicemailProviderSettings newSettings = new VoicemailProviderSettings(
607                    mSubMenuVoicemailSettings.getPhoneNumber(),
608                    VoicemailProviderSettings.NO_FORWARDING);
609            saveVoiceMailAndForwardingNumber(mVoicemailProviders.getKey(), newSettings);
610        }
611    }
612
613    /**
614     * Wrapper around showDialog() that will silently do nothing if we're
615     * not in the foreground.
616     *
617     * This is useful here because most of the dialogs we display from
618     * this class are triggered by asynchronous events (like
619     * success/failure messages from the telephony layer) and it's
620     * possible for those events to come in even after the user has gone
621     * to a different screen.
622     */
623    // TODO: this is too brittle: it's still easy to accidentally add new
624    // code here that calls showDialog() directly (which will result in a
625    // WindowManager$BadTokenException if called after the activity has
626    // been stopped.)
627    //
628    // It would be cleaner to do the "if (mForeground)" check in one
629    // central place, maybe by using a single Handler for all asynchronous
630    // events (and have *that* discard events if we're not in the
631    // foreground.)
632    //
633    // Unfortunately it's not that simple, since we sometimes need to do
634    // actual work to handle these events whether or not we're in the
635    // foreground (see the Handler code in mSetOptionComplete for
636    // example.)
637    //
638    // TODO: It's a bit worrisome that we don't do anything in error cases when we're not in the
639    // foreground. Consider displaying a toast instead.
640    private void showDialogIfForeground(int id) {
641        if (mForeground) {
642            showDialog(id);
643        }
644    }
645
646    private void dismissDialogSafely(int id) {
647        try {
648            dismissDialog(id);
649        } catch (IllegalArgumentException e) {
650            // This is expected in the case where we were in the background
651            // at the time we would normally have shown the dialog, so we didn't
652            // show it.
653        }
654    }
655
656    // This is a method implemented for DialogInterface.OnClickListener.
657    // Used with the error dialog to close the app, voicemail dialog to just dismiss.
658    // Close button is mapped to BUTTON_POSITIVE for the errors that close the activity,
659    // while those that are mapped to BUTTON_NEUTRAL only move the preference focus.
660    public void onClick(DialogInterface dialog, int which) {
661        if (DBG) log("onClick: button clicked is " + which);
662
663        dialog.dismiss();
664        switch (which){
665            case DialogInterface.BUTTON_NEGATIVE:
666                if (mCurrentDialogId == VoicemailDialogUtil.FWD_GET_RESPONSE_ERROR_DIALOG) {
667                    // We failed to get current forwarding settings and the user
668                    // does not wish to continue.
669                    switchToPreviousVoicemailProvider();
670                }
671                break;
672            case DialogInterface.BUTTON_POSITIVE:
673                if (mCurrentDialogId == VoicemailDialogUtil.FWD_GET_RESPONSE_ERROR_DIALOG) {
674                    // We failed to get current forwarding settings but the user
675                    // wishes to continue changing settings to the new vm provider
676                    setVoicemailNumberWithCarrier();
677                } else {
678                    finish();
679                }
680                return;
681            default:
682                // just let the dialog close and go back to the input
683        }
684
685        // In all dialogs, all buttons except BUTTON_POSITIVE lead to the end of user interaction
686        // with settings UI. If we were called to explicitly configure voice mail then
687        // we finish the settings activity here to come back to whatever the user was doing.
688        final String action = getIntent() != null ? getIntent().getAction() : null;
689        if (ACTION_ADD_VOICEMAIL.equals(action)) {
690            finish();
691        }
692    }
693
694
695    //*********************************************************************************************
696    // Voicemail Methods
697    //*********************************************************************************************
698
699    /**
700     * TODO: Refactor to make it easier to understand what's done in the different stages.
701     */
702    private void saveVoiceMailAndForwardingNumber(
703            String key, VoicemailProviderSettings newSettings) {
704        if (DBG) log("saveVoiceMailAndForwardingNumber: " + newSettings.toString());
705        mNewVMNumber = newSettings.getVoicemailNumber();
706        mNewVMNumber = (mNewVMNumber == null) ? "" : mNewVMNumber;
707        mNewFwdSettings = newSettings.getForwardingSettings();
708
709        // Call forwarding is not suppported on CDMA.
710        if (mPhone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
711            if (DBG) log("Ignoring forwarding setting since this is CDMA phone");
712            mNewFwdSettings = VoicemailProviderSettings.NO_FORWARDING;
713        }
714
715        // Throw a warning if the voicemail is the same and we did not change forwarding.
716        if (mNewVMNumber.equals(mOldVmNumber)
717                && mNewFwdSettings == VoicemailProviderSettings.NO_FORWARDING) {
718            showDialogIfForeground(VoicemailDialogUtil.VM_NOCHANGE_ERROR_DIALOG);
719            return;
720        }
721
722        VoicemailProviderSettingsUtil.save(this, key, newSettings);
723        mVMChangeCompletedSuccessfully = false;
724        mFwdChangesRequireRollback = false;
725        mVMOrFwdSetError = 0;
726
727        if (mNewFwdSettings == VoicemailProviderSettings.NO_FORWARDING
728                || key.equals(mPreviousVMProviderKey)) {
729            if (DBG) log("Set voicemail number. No changes to forwarding number.");
730            setVoicemailNumberWithCarrier();
731        } else {
732            if (DBG) log("Reading current forwarding settings.");
733            int numSettingsReasons = VoicemailProviderSettings.FORWARDING_SETTINGS_REASONS.length;
734            mForwardingReadResults = new CallForwardInfo[numSettingsReasons];
735            for (int i = 0; i < mForwardingReadResults.length; i++) {
736                mPhone.getCallForwardingOption(
737                        VoicemailProviderSettings.FORWARDING_SETTINGS_REASONS[i],
738                        mGetOptionComplete.obtainMessage(EVENT_FORWARDING_GET_COMPLETED, i, 0));
739            }
740            showDialogIfForeground(VoicemailDialogUtil.VM_FWD_READING_DIALOG);
741        }
742    }
743
744    private final Handler mGetOptionComplete = new Handler() {
745        @Override
746        public void handleMessage(Message msg) {
747            AsyncResult result = (AsyncResult) msg.obj;
748            switch (msg.what) {
749                case EVENT_FORWARDING_GET_COMPLETED:
750                    handleForwardingSettingsReadResult(result, msg.arg1);
751                    break;
752            }
753        }
754    };
755
756    private void handleForwardingSettingsReadResult(AsyncResult ar, int idx) {
757        if (DBG) Log.d(LOG_TAG, "handleForwardingSettingsReadResult: " + idx);
758
759        Throwable error = null;
760        if (ar.exception != null) {
761            error = ar.exception;
762            if (DBG) Log.d(LOG_TAG, "FwdRead: ar.exception=" + error.getMessage());
763        }
764        if (ar.userObj instanceof Throwable) {
765            error = (Throwable) ar.userObj;
766            if (DBG) Log.d(LOG_TAG, "FwdRead: userObj=" + error.getMessage());
767        }
768
769        // We may have already gotten an error and decided to ignore the other results.
770        if (mForwardingReadResults == null) {
771            if (DBG) Log.d(LOG_TAG, "Ignoring fwd reading result: " + idx);
772            return;
773        }
774
775        // In case of error ignore other results, show an error dialog
776        if (error != null) {
777            if (DBG) Log.d(LOG_TAG, "Error discovered for fwd read : " + idx);
778            mForwardingReadResults = null;
779            dismissDialogSafely(VoicemailDialogUtil.VM_FWD_READING_DIALOG);
780            showDialogIfForeground(VoicemailDialogUtil.FWD_GET_RESPONSE_ERROR_DIALOG);
781            return;
782        }
783
784        // Get the forwarding info.
785        mForwardingReadResults[idx] = CallForwardInfoUtil.getCallForwardInfo(
786                (CallForwardInfo[]) ar.result,
787                VoicemailProviderSettings.FORWARDING_SETTINGS_REASONS[idx]);
788
789        // Check if we got all the results already
790        boolean done = true;
791        for (int i = 0; i < mForwardingReadResults.length; i++) {
792            if (mForwardingReadResults[i] == null) {
793                done = false;
794                break;
795            }
796        }
797
798        if (done) {
799            if (DBG) Log.d(LOG_TAG, "Done receiving fwd info");
800            dismissDialogSafely(VoicemailDialogUtil.VM_FWD_READING_DIALOG);
801
802            if (mPreviousVMProviderKey.equals(VoicemailProviderListPreference.DEFAULT_KEY)) {
803                VoicemailProviderSettingsUtil.save(mPhone.getContext(),
804                        VoicemailProviderListPreference.DEFAULT_KEY,
805                        new VoicemailProviderSettings(mOldVmNumber, mForwardingReadResults));
806            }
807            saveVoiceMailAndForwardingNumberStage2();
808        }
809    }
810
811    private void resetForwardingChangeState() {
812        mForwardingChangeResults = new HashMap<Integer, AsyncResult>();
813        mExpectedChangeResultReasons = new HashSet<Integer>();
814    }
815
816    // Called after we are done saving the previous forwarding settings if we needed.
817    private void saveVoiceMailAndForwardingNumberStage2() {
818        mForwardingChangeResults = null;
819        mVoicemailChangeResult = null;
820
821        resetForwardingChangeState();
822        for (int i = 0; i < mNewFwdSettings.length; i++) {
823            CallForwardInfo fi = mNewFwdSettings[i];
824            CallForwardInfo fiForReason =
825                    CallForwardInfoUtil.infoForReason(mForwardingReadResults, fi.reason);
826            final boolean doUpdate = CallForwardInfoUtil.isUpdateRequired(fiForReason, fi);
827
828            if (doUpdate) {
829                if (DBG) log("Setting fwd #: " + i + ": " + fi.toString());
830                mExpectedChangeResultReasons.add(i);
831
832                CallForwardInfoUtil.setCallForwardingOption(mPhone, fi,
833                        mSetOptionComplete.obtainMessage(
834                                EVENT_FORWARDING_CHANGED, fi.reason, 0));
835            }
836        }
837        showDialogIfForeground(VoicemailDialogUtil.VM_FWD_SAVING_DIALOG);
838    }
839
840
841    /**
842     * Callback to handle option update completions
843     */
844    private final Handler mSetOptionComplete = new Handler() {
845        @Override
846        public void handleMessage(Message msg) {
847            AsyncResult result = (AsyncResult) msg.obj;
848            boolean done = false;
849            switch (msg.what) {
850                case EVENT_VOICEMAIL_CHANGED:
851                    mVoicemailChangeResult = result;
852                    mVMChangeCompletedSuccessfully = isVmChangeSuccess();
853                    PhoneGlobals.getInstance().refreshMwiIndicator(
854                            mSubscriptionInfoHelper.getSubId());
855                    done = true;
856                    break;
857                case EVENT_FORWARDING_CHANGED:
858                    mForwardingChangeResults.put(msg.arg1, result);
859                    if (result.exception != null) {
860                        Log.w(LOG_TAG, "Error in setting fwd# " + msg.arg1 + ": " +
861                                result.exception.getMessage());
862                    }
863                    if (isForwardingCompleted()) {
864                        if (isFwdChangeSuccess()) {
865                            if (DBG) log("Overall fwd changes completed ok, starting vm change");
866                            setVoicemailNumberWithCarrier();
867                        } else {
868                            Log.w(LOG_TAG, "Overall fwd changes completed in failure. " +
869                                    "Check if we need to try rollback for some settings.");
870                            mFwdChangesRequireRollback = false;
871                            Iterator<Map.Entry<Integer,AsyncResult>> it =
872                                mForwardingChangeResults.entrySet().iterator();
873                            while (it.hasNext()) {
874                                Map.Entry<Integer,AsyncResult> entry = it.next();
875                                if (entry.getValue().exception == null) {
876                                    // If at least one succeeded we have to revert
877                                    Log.i(LOG_TAG, "Rollback will be required");
878                                    mFwdChangesRequireRollback = true;
879                                    break;
880                                }
881                            }
882                            if (!mFwdChangesRequireRollback) {
883                                Log.i(LOG_TAG, "No rollback needed.");
884                            }
885                            done = true;
886                        }
887                    }
888                    break;
889                default:
890                    // TODO: should never reach this, may want to throw exception
891            }
892
893            if (done) {
894                if (DBG) log("All VM provider related changes done");
895                if (mForwardingChangeResults != null) {
896                    dismissDialogSafely(VoicemailDialogUtil.VM_FWD_SAVING_DIALOG);
897                }
898                handleSetVmOrFwdMessage();
899            }
900        }
901    };
902
903    /**
904     * Callback to handle option revert completions
905     */
906    private final Handler mRevertOptionComplete = new Handler() {
907        @Override
908        public void handleMessage(Message msg) {
909            AsyncResult result = (AsyncResult) msg.obj;
910            switch (msg.what) {
911                case EVENT_VOICEMAIL_CHANGED:
912                    if (DBG) log("VM revert complete msg");
913                    mVoicemailChangeResult = result;
914                    break;
915
916                case EVENT_FORWARDING_CHANGED:
917                    if (DBG) log("FWD revert complete msg ");
918                    mForwardingChangeResults.put(msg.arg1, result);
919                    if (result.exception != null) {
920                        if (DBG) log("Error in reverting fwd# " + msg.arg1 + ": " +
921                                result.exception.getMessage());
922                    }
923                    break;
924
925                default:
926                    // TODO: should never reach this, may want to throw exception
927            }
928
929            final boolean done = (!mVMChangeCompletedSuccessfully || mVoicemailChangeResult != null)
930                    && (!mFwdChangesRequireRollback || isForwardingCompleted());
931            if (done) {
932                if (DBG) log("All VM reverts done");
933                dismissDialogSafely(VoicemailDialogUtil.VM_REVERTING_DIALOG);
934                onRevertDone();
935            }
936        }
937    };
938
939    private void setVoicemailNumberWithCarrier() {
940        if (DBG) log("save voicemail #: " + mNewVMNumber);
941
942        mVoicemailChangeResult = null;
943        mPhone.setVoiceMailNumber(
944                mPhone.getVoiceMailAlphaTag().toString(),
945                mNewVMNumber,
946                Message.obtain(mSetOptionComplete, EVENT_VOICEMAIL_CHANGED));
947    }
948
949    private void switchToPreviousVoicemailProvider() {
950        if (DBG) log("switchToPreviousVoicemailProvider " + mPreviousVMProviderKey);
951
952        if (mPreviousVMProviderKey == null) {
953            return;
954        }
955
956        if (mVMChangeCompletedSuccessfully || mFwdChangesRequireRollback) {
957            showDialogIfForeground(VoicemailDialogUtil.VM_REVERTING_DIALOG);
958            final VoicemailProviderSettings prevSettings =
959                    VoicemailProviderSettingsUtil.load(this, mPreviousVMProviderKey);
960            if (prevSettings == null) {
961                Log.e(LOG_TAG, "VoicemailProviderSettings for the key \""
962                        + mPreviousVMProviderKey + "\" is null but should be loaded.");
963                return;
964            }
965
966            if (mVMChangeCompletedSuccessfully) {
967                mNewVMNumber = prevSettings.getVoicemailNumber();
968                Log.i(LOG_TAG, "VM change is already completed successfully."
969                        + "Have to revert VM back to " + mNewVMNumber + " again.");
970                mPhone.setVoiceMailNumber(
971                        mPhone.getVoiceMailAlphaTag().toString(),
972                        mNewVMNumber,
973                        Message.obtain(mRevertOptionComplete, EVENT_VOICEMAIL_CHANGED));
974            }
975
976            if (mFwdChangesRequireRollback) {
977                Log.i(LOG_TAG, "Requested to rollback forwarding changes.");
978
979                final CallForwardInfo[] prevFwdSettings = prevSettings.getForwardingSettings();
980                if (prevFwdSettings != null) {
981                    Map<Integer, AsyncResult> results = mForwardingChangeResults;
982                    resetForwardingChangeState();
983                    for (int i = 0; i < prevFwdSettings.length; i++) {
984                        CallForwardInfo fi = prevFwdSettings[i];
985                        if (DBG) log("Reverting fwd #: " + i + ": " + fi.toString());
986                        // Only revert the settings for which the update succeeded.
987                        AsyncResult result = results.get(fi.reason);
988                        if (result != null && result.exception == null) {
989                            mExpectedChangeResultReasons.add(fi.reason);
990                            CallForwardInfoUtil.setCallForwardingOption(mPhone, fi,
991                                    mRevertOptionComplete.obtainMessage(
992                                            EVENT_FORWARDING_CHANGED, i, 0));
993                        }
994                    }
995                }
996            }
997        } else {
998            if (DBG) log("No need to revert");
999            onRevertDone();
1000        }
1001    }
1002
1003
1004    //*********************************************************************************************
1005    // Voicemail Handler Helpers
1006    //*********************************************************************************************
1007
1008    /**
1009     * Updates the look of the VM preference widgets based on current VM provider settings.
1010     * Note that the provider name is loaded fxrorm the found activity via loadLabel in
1011     * {@link VoicemailProviderListPreference#initVoiceMailProviders()} in order for it to be
1012     * localizable.
1013     */
1014    private void updateVMPreferenceWidgets(String currentProviderSetting) {
1015        final String key = currentProviderSetting;
1016        final VoicemailProviderListPreference.VoicemailProvider provider =
1017                mVoicemailProviders.getVoicemailProvider(key);
1018
1019        /* This is the case when we are coming up on a freshly wiped phone and there is no
1020         persisted value for the list preference mVoicemailProviders.
1021         In this case we want to show the UI asking the user to select a voicemail provider as
1022         opposed to silently falling back to default one. */
1023        if (provider == null) {
1024            if (DBG) log("updateVMPreferenceWidget: key: " + key + " -> null.");
1025
1026            mVoicemailProviders.setSummary(getString(R.string.sum_voicemail_choose_provider));
1027            mVoicemailSettings.setEnabled(false);
1028            mVoicemailSettings.setIntent(null);
1029            mVoicemailNotificationVibrate.setEnabled(false);
1030        } else {
1031            if (DBG) log("updateVMPreferenceWidget: key: " + key + " -> " + provider.toString());
1032
1033            final String providerName = provider.name;
1034            mVoicemailProviders.setSummary(providerName);
1035            mVoicemailSettings.setEnabled(true);
1036            mVoicemailSettings.setIntent(provider.intent);
1037            mVoicemailNotificationVibrate.setEnabled(true);
1038        }
1039    }
1040
1041    /**
1042     * Update the voicemail number from what we've recorded on the sim.
1043     */
1044    private void updateVoiceNumberField() {
1045        if (DBG) log("updateVoiceNumberField()");
1046
1047        mOldVmNumber = mPhone.getVoiceMailNumber();
1048        if (TextUtils.isEmpty(mOldVmNumber)) {
1049            mSubMenuVoicemailSettings.setPhoneNumber("");
1050            mSubMenuVoicemailSettings.setSummary(getString(R.string.voicemail_number_not_set));
1051        } else {
1052            mSubMenuVoicemailSettings.setPhoneNumber(mOldVmNumber);
1053            mSubMenuVoicemailSettings.setSummary(BidiFormatter.getInstance().unicodeWrap(
1054                    mOldVmNumber, TextDirectionHeuristics.LTR));
1055        }
1056    }
1057
1058    private void handleSetVmOrFwdMessage() {
1059        if (DBG) log("handleSetVMMessage: set VM request complete");
1060
1061        if (!isFwdChangeSuccess()) {
1062            handleVmOrFwdSetError(VoicemailDialogUtil.FWD_SET_RESPONSE_ERROR_DIALOG);
1063        } else if (!isVmChangeSuccess()) {
1064            handleVmOrFwdSetError(VoicemailDialogUtil.VM_RESPONSE_ERROR_DIALOG);
1065        } else {
1066            handleVmAndFwdSetSuccess(VoicemailDialogUtil.VM_CONFIRM_DIALOG);
1067        }
1068    }
1069
1070    /**
1071     * Called when Voicemail Provider or its forwarding settings failed. Rolls back partly made
1072     * changes to those settings and show "failure" dialog.
1073     *
1074     * @param dialogId ID of the dialog to show for the specific error case. Either
1075     *     {@link #FWD_SET_RESPONSE_ERROR_DIALOG} or {@link #VM_RESPONSE_ERROR_DIALOG}
1076     */
1077    private void handleVmOrFwdSetError(int dialogId) {
1078        if (mChangingVMorFwdDueToProviderChange) {
1079            mVMOrFwdSetError = dialogId;
1080            mChangingVMorFwdDueToProviderChange = false;
1081            switchToPreviousVoicemailProvider();
1082            return;
1083        }
1084        mChangingVMorFwdDueToProviderChange = false;
1085        showDialogIfForeground(dialogId);
1086        updateVoiceNumberField();
1087    }
1088
1089    /**
1090     * Called when Voicemail Provider and its forwarding settings were successfully finished.
1091     * This updates a bunch of variables and show "success" dialog.
1092     */
1093    private void handleVmAndFwdSetSuccess(int dialogId) {
1094        if (DBG) log("handleVmAndFwdSetSuccess: key is " + mVoicemailProviders.getKey());
1095
1096        mPreviousVMProviderKey = mVoicemailProviders.getKey();
1097        mChangingVMorFwdDueToProviderChange = false;
1098        showDialogIfForeground(dialogId);
1099        updateVoiceNumberField();
1100    }
1101
1102    private void onRevertDone() {
1103        if (DBG) log("onRevertDone: Changing provider key back to " + mPreviousVMProviderKey);
1104
1105        updateVMPreferenceWidgets(mPreviousVMProviderKey);
1106        updateVoiceNumberField();
1107        if (mVMOrFwdSetError != 0) {
1108            showDialogIfForeground(mVMOrFwdSetError);
1109            mVMOrFwdSetError = 0;
1110        }
1111    }
1112
1113
1114    //*********************************************************************************************
1115    // Voicemail State Helpers
1116    //*********************************************************************************************
1117
1118    /**
1119     * Return true if there is a change result for every reason for which we expect a result.
1120     */
1121    private boolean isForwardingCompleted() {
1122        if (mForwardingChangeResults == null) {
1123            return true;
1124        }
1125
1126        for (Integer reason : mExpectedChangeResultReasons) {
1127            if (mForwardingChangeResults.get(reason) == null) {
1128                return false;
1129            }
1130        }
1131
1132        return true;
1133    }
1134
1135    private boolean isFwdChangeSuccess() {
1136        if (mForwardingChangeResults == null) {
1137            return true;
1138        }
1139
1140        for (AsyncResult result : mForwardingChangeResults.values()) {
1141            Throwable exception = result.exception;
1142            if (exception != null) {
1143                String msg = exception.getMessage();
1144                msg = (msg != null) ? msg : "";
1145                Log.w(LOG_TAG, "Failed to change forwarding setting. Reason: " + msg);
1146                return false;
1147            }
1148        }
1149        return true;
1150    }
1151
1152    private boolean isVmChangeSuccess() {
1153        if (mVoicemailChangeResult.exception != null) {
1154            String msg = mVoicemailChangeResult.exception.getMessage();
1155            msg = (msg != null) ? msg : "";
1156            Log.w(LOG_TAG, "Failed to change voicemail. Reason: " + msg);
1157            return false;
1158        }
1159        return true;
1160    }
1161
1162    private boolean isVisualVoicemailActivated() {
1163        if (!VisualVoicemailSettingsUtil.isEnabled(this, mPhoneAccountHandle)) {
1164            return false;
1165        }
1166        VisualVoicemailPreferences preferences = new VisualVoicemailPreferences(this,
1167                mPhoneAccountHandle);
1168        return preferences.getString(OmtpConstants.SERVER_ADDRESS, null) != null;
1169
1170    }
1171
1172    private static void log(String msg) {
1173        Log.d(LOG_TAG, msg);
1174    }
1175}
1176