1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.settings.tts;
18
19import android.content.ActivityNotFoundException;
20import android.content.BroadcastReceiver;
21import android.content.Context;
22import android.content.Intent;
23import android.content.IntentFilter;
24import android.os.Bundle;
25import android.preference.ListPreference;
26import android.preference.Preference;
27import android.preference.Preference.OnPreferenceChangeListener;
28import android.preference.Preference.OnPreferenceClickListener;
29import android.preference.PreferenceScreen;
30import android.speech.tts.TextToSpeech;
31import android.speech.tts.TtsEngines;
32import android.text.TextUtils;
33import android.util.Log;
34import android.util.Pair;
35
36import com.android.settings.R;
37import com.android.settings.SettingsPreferenceFragment;
38
39import java.util.ArrayList;
40import java.util.Collections;
41import java.util.Comparator;
42import java.util.Locale;
43
44
45public class TtsEngineSettingsFragment extends SettingsPreferenceFragment implements
46        OnPreferenceClickListener, OnPreferenceChangeListener {
47    private static final String TAG = "TtsEngineSettings";
48    private static final boolean DBG = false;
49
50    private static final String KEY_ENGINE_LOCALE = "tts_default_lang";
51    private static final String KEY_ENGINE_SETTINGS = "tts_engine_settings";
52    private static final String KEY_INSTALL_DATA = "tts_install_data";
53
54    private static final String STATE_KEY_LOCALE_ENTRIES = "locale_entries";
55    private static final String STATE_KEY_LOCALE_ENTRY_VALUES= "locale_entry_values";
56    private static final String STATE_KEY_LOCALE_VALUE = "locale_value";
57
58    private static final int VOICE_DATA_INTEGRITY_CHECK = 1977;
59
60    private TtsEngines mEnginesHelper;
61    private ListPreference mLocalePreference;
62    private Preference mEngineSettingsPreference;
63    private Preference mInstallVoicesPreference;
64    private Intent mEngineSettingsIntent;
65    private Intent mVoiceDataDetails;
66
67    private TextToSpeech mTts;
68
69    private int mSelectedLocaleIndex = -1;
70
71    private final TextToSpeech.OnInitListener mTtsInitListener = new TextToSpeech.OnInitListener() {
72        @Override
73        public void onInit(int status) {
74            if (status != TextToSpeech.SUCCESS) {
75                finishFragment();
76            } else {
77                getActivity().runOnUiThread(new Runnable() {
78                    @Override
79                    public void run() {
80                        mLocalePreference.setEnabled(true);
81                    }
82                });
83            }
84        }
85    };
86
87    private final BroadcastReceiver mLanguagesChangedReceiver = new BroadcastReceiver() {
88        @Override
89        public void onReceive(Context context, Intent intent) {
90            // Installed or uninstalled some data packs
91            if (TextToSpeech.Engine.ACTION_TTS_DATA_INSTALLED.equals(intent.getAction())) {
92                checkTtsData();
93            }
94        }
95    };
96
97    public TtsEngineSettingsFragment() {
98        super();
99    }
100
101    @Override
102    public void onCreate(Bundle savedInstanceState) {
103        super.onCreate(savedInstanceState);
104        addPreferencesFromResource(R.xml.tts_engine_settings);
105        mEnginesHelper = new TtsEngines(getActivity());
106
107        final PreferenceScreen root = getPreferenceScreen();
108        mLocalePreference = (ListPreference) root.findPreference(KEY_ENGINE_LOCALE);
109        mLocalePreference.setOnPreferenceChangeListener(this);
110        mEngineSettingsPreference = root.findPreference(KEY_ENGINE_SETTINGS);
111        mEngineSettingsPreference.setOnPreferenceClickListener(this);
112        mInstallVoicesPreference = root.findPreference(KEY_INSTALL_DATA);
113        mInstallVoicesPreference.setOnPreferenceClickListener(this);
114
115        root.setTitle(getEngineLabel());
116        root.setKey(getEngineName());
117        mEngineSettingsPreference.setTitle(getResources().getString(
118                R.string.tts_engine_settings_title, getEngineLabel()));
119
120        mEngineSettingsIntent = mEnginesHelper.getSettingsIntent(getEngineName());
121        if (mEngineSettingsIntent == null) {
122            mEngineSettingsPreference.setEnabled(false);
123        }
124        mInstallVoicesPreference.setEnabled(false);
125
126        if (savedInstanceState == null) {
127            mLocalePreference.setEnabled(false);
128            mLocalePreference.setEntries(new CharSequence[0]);
129            mLocalePreference.setEntryValues(new CharSequence[0]);
130        } else {
131            // Repopulate mLocalePreference with saved state. Will be updated later with
132            // up-to-date values when checkTtsData() calls back with results.
133            final CharSequence[] entries =
134                    savedInstanceState.getCharSequenceArray(STATE_KEY_LOCALE_ENTRIES);
135            final CharSequence[] entryValues =
136                    savedInstanceState.getCharSequenceArray(STATE_KEY_LOCALE_ENTRY_VALUES);
137            final CharSequence value =
138                    savedInstanceState.getCharSequence(STATE_KEY_LOCALE_VALUE);
139
140            mLocalePreference.setEntries(entries);
141            mLocalePreference.setEntryValues(entryValues);
142            mLocalePreference.setValue(value != null ? value.toString() : null);
143            mLocalePreference.setEnabled(entries.length > 0);
144        }
145
146        mVoiceDataDetails = getArguments().getParcelable(TtsEnginePreference.FRAGMENT_ARGS_VOICES);
147
148        mTts = new TextToSpeech(getActivity().getApplicationContext(), mTtsInitListener,
149                getEngineName());
150
151        // Check if data packs changed
152        checkTtsData();
153
154        getActivity().registerReceiver(mLanguagesChangedReceiver,
155                new IntentFilter(TextToSpeech.Engine.ACTION_TTS_DATA_INSTALLED));
156    }
157
158    @Override
159    public void onDestroy() {
160        getActivity().unregisterReceiver(mLanguagesChangedReceiver);
161        mTts.shutdown();
162        super.onDestroy();
163    }
164
165    @Override
166    public void onSaveInstanceState(Bundle outState) {
167        super.onSaveInstanceState(outState);
168
169        // Save the mLocalePreference values, so we can repopulate it with entries.
170        outState.putCharSequenceArray(STATE_KEY_LOCALE_ENTRIES,
171                mLocalePreference.getEntries());
172        outState.putCharSequenceArray(STATE_KEY_LOCALE_ENTRY_VALUES,
173                mLocalePreference.getEntryValues());
174        outState.putCharSequence(STATE_KEY_LOCALE_VALUE,
175                mLocalePreference.getValue());
176    }
177
178    private final void checkTtsData() {
179        Intent intent = new Intent(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
180        intent.setPackage(getEngineName());
181        try {
182            if (DBG) Log.d(TAG, "Updating engine: Checking voice data: " + intent.toUri(0));
183            startActivityForResult(intent, VOICE_DATA_INTEGRITY_CHECK);
184        } catch (ActivityNotFoundException ex) {
185            Log.e(TAG, "Failed to check TTS data, no activity found for " + intent + ")");
186        }
187    }
188
189    @Override
190    public void onActivityResult(int requestCode, int resultCode, Intent data) {
191        if (requestCode == VOICE_DATA_INTEGRITY_CHECK) {
192            if (resultCode != TextToSpeech.Engine.CHECK_VOICE_DATA_FAIL) {
193                updateVoiceDetails(data);
194            } else {
195                Log.e(TAG, "CheckVoiceData activity failed");
196            }
197        }
198    }
199
200    private void updateVoiceDetails(Intent data) {
201        if (data == null){
202            Log.e(TAG, "Engine failed voice data integrity check (null return)" +
203                    mTts.getCurrentEngine());
204            return;
205        }
206        mVoiceDataDetails = data;
207
208        if (DBG) Log.d(TAG, "Parsing voice data details, data: " + mVoiceDataDetails.toUri(0));
209
210        final ArrayList<String> available = mVoiceDataDetails.getStringArrayListExtra(
211                TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES);
212        final ArrayList<String> unavailable = mVoiceDataDetails.getStringArrayListExtra(
213                TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES);
214
215        if (unavailable != null && unavailable.size() > 0) {
216            mInstallVoicesPreference.setEnabled(true);
217        } else {
218            mInstallVoicesPreference.setEnabled(false);
219        }
220
221        if (available == null){
222            Log.e(TAG, "TTS data check failed (available == null).");
223            mLocalePreference.setEnabled(false);
224            return;
225        } else {
226            updateDefaultLocalePref(available);
227        }
228    }
229
230    private void updateDefaultLocalePref(ArrayList<String> availableLangs) {
231        if (availableLangs == null || availableLangs.size() == 0) {
232            mLocalePreference.setEnabled(false);
233            return;
234        }
235        Locale currentLocale = null;
236        if (!mEnginesHelper.isLocaleSetToDefaultForEngine(getEngineName())) {
237            currentLocale = mEnginesHelper.getLocalePrefForEngine(getEngineName());
238        }
239
240        ArrayList<Pair<String, Locale>> entryPairs =
241                new ArrayList<Pair<String, Locale>>(availableLangs.size());
242        for (int i = 0; i < availableLangs.size(); i++) {
243            Locale locale = mEnginesHelper.parseLocaleString(availableLangs.get(i));
244            if (locale != null){
245                entryPairs.add(new Pair<String, Locale>(
246                        locale.getDisplayName(), locale));
247            }
248        }
249
250        // Sort it
251        Collections.sort(entryPairs, new Comparator<Pair<String, Locale>>() {
252            @Override
253            public int compare(Pair<String, Locale> lhs, Pair<String, Locale> rhs) {
254                return lhs.first.compareToIgnoreCase(rhs.first);
255            }
256        });
257
258        // Get two arrays out of one of pairs
259        mSelectedLocaleIndex = 0; // Will point to the R.string.tts_lang_use_system value
260        CharSequence[] entries = new CharSequence[availableLangs.size()+1];
261        CharSequence[] entryValues = new CharSequence[availableLangs.size()+1];
262
263        entries[0] = getActivity().getString(R.string.tts_lang_use_system);
264        entryValues[0] = "";
265
266        int i = 1;
267        for (Pair<String, Locale> entry : entryPairs) {
268            if (entry.second.equals(currentLocale)) {
269                mSelectedLocaleIndex = i;
270            }
271            entries[i] = entry.first;
272            entryValues[i++] = entry.second.toString();
273        }
274
275        mLocalePreference.setEntries(entries);
276        mLocalePreference.setEntryValues(entryValues);
277        mLocalePreference.setEnabled(true);
278        setLocalePreference(mSelectedLocaleIndex);
279    }
280
281    /** Set entry from entry table in mLocalePreference */
282    private void setLocalePreference(int index) {
283        if (index < 0) {
284            mLocalePreference.setValue("");
285            mLocalePreference.setSummary(R.string.tts_lang_not_selected);
286        } else {
287            mLocalePreference.setValueIndex(index);
288            mLocalePreference.setSummary(mLocalePreference.getEntries()[index]);
289        }
290    }
291
292    /**
293     * Ask the current default engine to launch the matching INSTALL_TTS_DATA activity
294     * so the required TTS files are properly installed.
295     */
296    private void installVoiceData() {
297        if (TextUtils.isEmpty(getEngineName())) return;
298        Intent intent = new Intent(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
299        intent.setPackage(getEngineName());
300        try {
301            Log.v(TAG, "Installing voice data: " + intent.toUri(0));
302            startActivity(intent);
303        } catch (ActivityNotFoundException ex) {
304            Log.e(TAG, "Failed to install TTS data, no acitivty found for " + intent + ")");
305        }
306    }
307
308    @Override
309    public boolean onPreferenceClick(Preference preference) {
310        if (preference == mInstallVoicesPreference) {
311            installVoiceData();
312            return true;
313        } else if (preference == mEngineSettingsPreference) {
314            startActivity(mEngineSettingsIntent);
315            return true;
316        }
317
318        return false;
319    }
320
321    @Override
322    public boolean onPreferenceChange(Preference preference, Object newValue) {
323        if (preference == mLocalePreference) {
324            String localeString = (String) newValue;
325            updateLanguageTo((!TextUtils.isEmpty(localeString) ?
326                    mEnginesHelper.parseLocaleString(localeString) : null));
327            return true;
328        }
329        return false;
330    }
331
332    private void updateLanguageTo(Locale locale) {
333        int selectedLocaleIndex = -1;
334        String localeString = (locale != null) ? locale.toString() : "";
335        for (int i=0; i < mLocalePreference.getEntryValues().length; i++) {
336            if (localeString.equalsIgnoreCase(mLocalePreference.getEntryValues()[i].toString())) {
337                selectedLocaleIndex = i;
338                break;
339            }
340        }
341
342        if (selectedLocaleIndex == -1) {
343            Log.w(TAG, "updateLanguageTo called with unknown locale argument");
344            return;
345        }
346        mLocalePreference.setSummary(mLocalePreference.getEntries()[selectedLocaleIndex]);
347        mSelectedLocaleIndex = selectedLocaleIndex;
348
349        mEnginesHelper.updateLocalePrefForEngine(getEngineName(), locale);
350
351        if (getEngineName().equals(mTts.getCurrentEngine())) {
352            // Null locale means "use system default"
353            mTts.setLanguage((locale != null) ? locale : Locale.getDefault());
354        }
355    }
356
357    private String getEngineName() {
358        return getArguments().getString(TtsEnginePreference.FRAGMENT_ARGS_NAME);
359    }
360
361    private String getEngineLabel() {
362        return getArguments().getString(TtsEnginePreference.FRAGMENT_ARGS_LABEL);
363    }
364}
365