• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
17 package com.android.settings.tts;
18 
19 import static android.provider.Settings.Secure.TTS_DEFAULT_PITCH;
20 import static android.provider.Settings.Secure.TTS_DEFAULT_RATE;
21 import static android.provider.Settings.Secure.TTS_DEFAULT_SYNTH;
22 
23 import android.app.settings.SettingsEnums;
24 import android.content.ActivityNotFoundException;
25 import android.content.ContentResolver;
26 import android.content.Context;
27 import android.content.Intent;
28 import android.os.Bundle;
29 import android.os.UserHandle;
30 import android.os.UserManager;
31 import android.provider.Settings.Secure;
32 import android.speech.tts.TextToSpeech;
33 import android.speech.tts.TextToSpeech.EngineInfo;
34 import android.speech.tts.TtsEngines;
35 import android.speech.tts.UtteranceProgressListener;
36 import android.text.TextUtils;
37 import android.util.Log;
38 import android.util.Pair;
39 
40 import androidx.appcompat.app.AlertDialog;
41 import androidx.lifecycle.ViewModelProviders;
42 import androidx.preference.ListPreference;
43 import androidx.preference.Preference;
44 
45 import com.android.settings.R;
46 import com.android.settings.SettingsActivity;
47 import com.android.settings.SettingsPreferenceFragment;
48 import com.android.settings.Utils;
49 import com.android.settings.overlay.FeatureFactory;
50 import com.android.settings.search.BaseSearchIndexProvider;
51 import com.android.settings.widget.GearPreference;
52 import com.android.settings.widget.SeekBarPreference;
53 import com.android.settingslib.search.SearchIndexable;
54 import com.android.settingslib.widget.ActionButtonsPreference;
55 
56 import java.text.Collator;
57 import java.util.ArrayList;
58 import java.util.Collections;
59 import java.util.HashMap;
60 import java.util.List;
61 import java.util.Locale;
62 import java.util.MissingResourceException;
63 import java.util.Objects;
64 import java.util.Set;
65 
66 @SearchIndexable
67 public class TextToSpeechSettings extends SettingsPreferenceFragment
68         implements Preference.OnPreferenceChangeListener,
69         GearPreference.OnGearClickListener {
70 
71     private static final String STATE_KEY_LOCALE_ENTRIES = "locale_entries";
72     private static final String STATE_KEY_LOCALE_ENTRY_VALUES = "locale_entry_values";
73     private static final String STATE_KEY_LOCALE_VALUE = "locale_value";
74 
75     private static final String TAG = "TextToSpeechSettings";
76     private static final boolean DBG = false;
77 
78     /** Preference key for the TTS pitch selection slider. */
79     private static final String KEY_DEFAULT_PITCH = "tts_default_pitch";
80 
81     /** Preference key for the TTS rate selection slider. */
82     private static final String KEY_DEFAULT_RATE = "tts_default_rate";
83 
84     /** Engine picker. */
85     private static final String KEY_TTS_ENGINE_PREFERENCE = "tts_engine_preference";
86 
87     /** Locale picker. */
88     private static final String KEY_ENGINE_LOCALE = "tts_default_lang";
89 
90     /** Play/Reset buttons container. */
91     private static final String KEY_ACTION_BUTTONS = "action_buttons";
92 
93     /**
94      * These look like birth years, but they aren't mine. I'm much younger than this.
95      */
96     private static final int GET_SAMPLE_TEXT = 1983;
97     private static final int VOICE_DATA_INTEGRITY_CHECK = 1977;
98 
99     /**
100      * Speech rate value. This value should be kept in sync with the max value set in tts_settings
101      * xml.
102      */
103     private static final int MAX_SPEECH_RATE = 600;
104 
105     private static final int MIN_SPEECH_RATE = 10;
106 
107     /**
108      * Speech pitch value. TTS pitch value varies from 25 to 400, where 100 is the value for normal
109      * pitch. The max pitch value is set to 400, based on feedback from users and the GoogleTTS
110      * pitch variation range. The range for pitch is not set in stone and should be readjusted based
111      * on user need. This value should be kept in sync with the max value set in tts_settings xml.
112      */
113     private static final int MAX_SPEECH_PITCH = 400;
114 
115     private static final int MIN_SPEECH_PITCH = 25;
116 
117     private SeekBarPreference mDefaultPitchPref;
118     private SeekBarPreference mDefaultRatePref;
119     private ActionButtonsPreference mActionButtons;
120 
121     private int mDefaultPitch = TextToSpeech.Engine.DEFAULT_PITCH;
122     private int mDefaultRate = TextToSpeech.Engine.DEFAULT_RATE;
123 
124     private int mSelectedLocaleIndex = -1;
125 
126     /** The currently selected engine. */
127     private String mCurrentEngine;
128 
129     private TextToSpeech mTts = null;
130     private TtsEngines mEnginesHelper = null;
131 
132     private String mSampleText = null;
133 
134     private ListPreference mLocalePreference;
135 
136     /**
137      * Default locale used by selected TTS engine, null if not connected to any engine.
138      */
139     private Locale mCurrentDefaultLocale;
140 
141     /**
142      * List of available locals of selected TTS engine, as returned by
143      * {@link TextToSpeech.Engine#ACTION_CHECK_TTS_DATA} activity. If empty, then activity
144      * was not yet called.
145      */
146     private List<String> mAvailableStrLocals;
147 
148     /**
149      * The initialization listener used when we are initalizing the settings
150      * screen for the first time (as opposed to when a user changes his choice
151      * of engine).
152      */
153     private final TextToSpeech.OnInitListener mInitListener = this::onInitEngine;
154 
155     /**
156      * A UserManager used to set settings for both person and work profiles for a user
157      */
158     private UserManager mUserManager;
159 
160     @Override
getMetricsCategory()161     public int getMetricsCategory() {
162         return SettingsEnums.TTS_TEXT_TO_SPEECH;
163     }
164 
165     @Override
onCreate(Bundle savedInstanceState)166     public void onCreate(Bundle savedInstanceState) {
167         super.onCreate(savedInstanceState);
168         addPreferencesFromResource(R.xml.tts_settings);
169 
170         getActivity().setVolumeControlStream(TextToSpeech.Engine.DEFAULT_STREAM);
171 
172         mEnginesHelper = new TtsEngines(getActivity().getApplicationContext());
173 
174         mLocalePreference = (ListPreference) findPreference(KEY_ENGINE_LOCALE);
175         mLocalePreference.setOnPreferenceChangeListener(this);
176 
177         mDefaultPitchPref = (SeekBarPreference) findPreference(KEY_DEFAULT_PITCH);
178         mDefaultRatePref = (SeekBarPreference) findPreference(KEY_DEFAULT_RATE);
179 
180         mActionButtons = ((ActionButtonsPreference) findPreference(KEY_ACTION_BUTTONS))
181                 .setButton1Text(R.string.tts_play)
182                 .setButton1OnClickListener(v -> speakSampleText())
183                 .setButton1Enabled(false)
184                 .setButton2Text(R.string.tts_reset)
185                 .setButton2OnClickListener(v -> resetTts())
186                 .setButton1Enabled(true);
187 
188         mUserManager = (UserManager) getActivity()
189                 .getApplicationContext().getSystemService(Context.USER_SERVICE);
190 
191         if (savedInstanceState == null) {
192             mLocalePreference.setEnabled(false);
193             mLocalePreference.setEntries(new CharSequence[0]);
194             mLocalePreference.setEntryValues(new CharSequence[0]);
195         } else {
196             // Repopulate mLocalePreference with saved state. Will be updated later with
197             // up-to-date values when checkTtsData() calls back with results.
198             final CharSequence[] entries =
199                     savedInstanceState.getCharSequenceArray(STATE_KEY_LOCALE_ENTRIES);
200             final CharSequence[] entryValues =
201                     savedInstanceState.getCharSequenceArray(STATE_KEY_LOCALE_ENTRY_VALUES);
202             final CharSequence value = savedInstanceState.getCharSequence(STATE_KEY_LOCALE_VALUE);
203 
204             mLocalePreference.setEntries(entries);
205             mLocalePreference.setEntryValues(entryValues);
206             mLocalePreference.setValue(value != null ? value.toString() : null);
207             mLocalePreference.setEnabled(entries.length > 0);
208         }
209 
210         final TextToSpeechViewModel ttsViewModel =
211                 ViewModelProviders.of(this).get(TextToSpeechViewModel.class);
212         Pair<TextToSpeech, Boolean> ttsAndNew = ttsViewModel.getTtsAndWhetherNew(mInitListener);
213         mTts = ttsAndNew.first;
214         // If the TTS object is not newly created, we need to run the setup on the settings side to
215         // ensure that we can use the TTS object.
216         if (!ttsAndNew.second) {
217             successSetup();
218         }
219 
220         setTtsUtteranceProgressListener();
221         initSettings();
222     }
223 
224     @Override
onResume()225     public void onResume() {
226         super.onResume();
227         // We tend to change the summary contents of our widgets, which at higher text sizes causes
228         // them to resize, which results in the recyclerview smoothly animating them at inopportune
229         // times. Disable the animation so widgets snap to their positions rather than sliding
230         // around while the user is interacting with it.
231         getListView().getItemAnimator().setMoveDuration(0);
232 
233         if (mTts == null || mCurrentDefaultLocale == null) {
234             return;
235         }
236         if (!mTts.getDefaultEngine().equals(mTts.getCurrentEngine())) {
237             final TextToSpeechViewModel ttsViewModel =
238                     ViewModelProviders.of(this).get(TextToSpeechViewModel.class);
239             try {
240                 // If the current engine isn't the default engine shut down the current engine in
241                 // preparation for creating the new engine.
242                 ttsViewModel.shutdownTts();
243             } catch (Exception e) {
244                 Log.e(TAG, "Error shutting down TTS engine" + e);
245             }
246             final Pair<TextToSpeech, Boolean> ttsAndNew =
247                     ttsViewModel.getTtsAndWhetherNew(mInitListener);
248             mTts = ttsAndNew.first;
249             if (!ttsAndNew.second) {
250                 successSetup();
251             }
252             setTtsUtteranceProgressListener();
253             initSettings();
254         } else {
255             // Do set pitch correctly after it may have changed, and unlike speed, it doesn't change
256             // immediately.
257             final ContentResolver resolver = getContentResolver();
258             mTts.setPitch(android.provider.Settings.Secure.getInt(resolver, TTS_DEFAULT_PITCH,
259                     TextToSpeech.Engine.DEFAULT_PITCH) / 100.0f);
260         }
261 
262         Locale ttsDefaultLocale = mTts.getDefaultLanguage();
263         if (mCurrentDefaultLocale != null && !mCurrentDefaultLocale.equals(ttsDefaultLocale)) {
264             updateWidgetState(false);
265             checkDefaultLocale();
266         }
267     }
268 
setTtsUtteranceProgressListener()269     private void setTtsUtteranceProgressListener() {
270         if (mTts == null) {
271             return;
272         }
273         mTts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
274             @Override
275             public void onStart(String utteranceId) {
276                 updateWidgetState(false);
277             }
278 
279             @Override
280             public void onDone(String utteranceId) {
281                 updateWidgetState(true);
282             }
283 
284             @Override
285             public void onError(String utteranceId) {
286                 Log.e(TAG, "Error while trying to synthesize sample text");
287                 // Re-enable just in case, although there isn't much hope that following synthesis
288                 // requests are going to succeed.
289                 updateWidgetState(true);
290             }
291         });
292     }
293 
294     @Override
onSaveInstanceState(Bundle outState)295     public void onSaveInstanceState(Bundle outState) {
296         super.onSaveInstanceState(outState);
297 
298         // Save the mLocalePreference values, so we can repopulate it with entries.
299         outState.putCharSequenceArray(STATE_KEY_LOCALE_ENTRIES,
300                 mLocalePreference.getEntries());
301         outState.putCharSequenceArray(STATE_KEY_LOCALE_ENTRY_VALUES,
302                 mLocalePreference.getEntryValues());
303         outState.putCharSequence(STATE_KEY_LOCALE_VALUE,
304                 mLocalePreference.getValue());
305     }
306 
initSettings()307     private void initSettings() {
308         final ContentResolver resolver = getContentResolver();
309 
310         // Set up the default rate and pitch.
311         mDefaultRate =
312                 android.provider.Settings.Secure.getInt(
313                         resolver, TTS_DEFAULT_RATE, TextToSpeech.Engine.DEFAULT_RATE);
314         mDefaultPitch =
315                 android.provider.Settings.Secure.getInt(
316                         resolver, TTS_DEFAULT_PITCH, TextToSpeech.Engine.DEFAULT_PITCH);
317 
318         mDefaultRatePref.setProgress(getSeekBarProgressFromValue(KEY_DEFAULT_RATE, mDefaultRate));
319         mDefaultRatePref.setOnPreferenceChangeListener(this);
320         mDefaultRatePref.setMax(getSeekBarProgressFromValue(KEY_DEFAULT_RATE, MAX_SPEECH_RATE));
321         mDefaultRatePref.setContinuousUpdates(true);
322         mDefaultRatePref.setHapticFeedbackMode(SeekBarPreference.HAPTIC_FEEDBACK_MODE_ON_ENDS);
323 
324         mDefaultPitchPref.setProgress(
325                 getSeekBarProgressFromValue(KEY_DEFAULT_PITCH, mDefaultPitch));
326         mDefaultPitchPref.setOnPreferenceChangeListener(this);
327         mDefaultPitchPref.setMax(getSeekBarProgressFromValue(KEY_DEFAULT_PITCH, MAX_SPEECH_PITCH));
328         mDefaultPitchPref.setContinuousUpdates(true);
329         mDefaultPitchPref.setHapticFeedbackMode(SeekBarPreference.HAPTIC_FEEDBACK_MODE_ON_ENDS);
330 
331         if (mTts != null) {
332             mCurrentEngine = mTts.getCurrentEngine();
333             mTts.setSpeechRate(mDefaultRate / 100.0f);
334             mTts.setPitch(mDefaultPitch / 100.0f);
335         }
336 
337         SettingsActivity activity = null;
338         if (getActivity() instanceof SettingsActivity) {
339             activity = (SettingsActivity) getActivity();
340         } else {
341             throw new IllegalStateException("TextToSpeechSettings used outside a " +
342                     "Settings");
343         }
344 
345         if (mCurrentEngine != null) {
346             EngineInfo info = mEnginesHelper.getEngineInfo(mCurrentEngine);
347 
348             Preference mEnginePreference = findPreference(KEY_TTS_ENGINE_PREFERENCE);
349             ((GearPreference) mEnginePreference).setOnGearClickListener(this);
350             mEnginePreference.setSummary(info.label);
351         }
352 
353         checkVoiceData(mCurrentEngine);
354     }
355 
356     /**
357      * The minimum speech pitch/rate value should be > 0 but the minimum value of a seekbar in
358      * android is fixed at 0. Therefore, we increment the seekbar progress with MIN_SPEECH_VALUE so
359      * that the minimum seekbar progress value is MIN_SPEECH_PITCH/RATE. SPEECH_VALUE =
360      * MIN_SPEECH_VALUE + SEEKBAR_PROGRESS
361      */
getValueFromSeekBarProgress(String preferenceKey, int progress)362     private int getValueFromSeekBarProgress(String preferenceKey, int progress) {
363         if (preferenceKey.equals(KEY_DEFAULT_RATE)) {
364             return MIN_SPEECH_RATE + progress;
365         } else if (preferenceKey.equals(KEY_DEFAULT_PITCH)) {
366             return MIN_SPEECH_PITCH + progress;
367         }
368         return progress;
369     }
370 
371     /**
372      * Since we are appending the MIN_SPEECH value to the speech seekbar progress, the speech
373      * seekbar progress should be set to (speechValue - MIN_SPEECH value).
374      */
getSeekBarProgressFromValue(String preferenceKey, int value)375     private int getSeekBarProgressFromValue(String preferenceKey, int value) {
376         if (preferenceKey.equals(KEY_DEFAULT_RATE)) {
377             return value - MIN_SPEECH_RATE;
378         } else if (preferenceKey.equals(KEY_DEFAULT_PITCH)) {
379             return value - MIN_SPEECH_PITCH;
380         }
381         return value;
382     }
383 
384     /** Called when the TTS engine is initialized. */
onInitEngine(int status)385     public void onInitEngine(int status) {
386         if (status == TextToSpeech.SUCCESS) {
387             if (DBG) Log.d(TAG, "TTS engine for settings screen initialized.");
388             successSetup();
389         } else {
390             if (DBG) {
391                 Log.d(TAG,
392                         "TTS engine for settings screen failed to initialize successfully.");
393             }
394             updateWidgetState(false);
395         }
396     }
397 
398     /** Initialize TTS Settings on successful engine init. */
successSetup()399     private void successSetup() {
400         checkDefaultLocale();
401         getActivity().runOnUiThread(() -> mLocalePreference.setEnabled(true));
402     }
403 
checkDefaultLocale()404     private void checkDefaultLocale() {
405         Locale defaultLocale = mTts.getDefaultLanguage();
406         if (defaultLocale == null) {
407             Log.e(TAG, "Failed to get default language from engine " + mCurrentEngine);
408             updateWidgetState(false);
409             return;
410         }
411 
412         // ISO-3166 alpha 3 country codes are out of spec. If we won't normalize,
413         // we may end up with English (USA)and German (DEU).
414         final Locale oldDefaultLocale = mCurrentDefaultLocale;
415         mCurrentDefaultLocale = mEnginesHelper.parseLocaleString(defaultLocale.toString());
416         if (!Objects.equals(oldDefaultLocale, mCurrentDefaultLocale)) {
417             mSampleText = null;
418         }
419 
420         int defaultAvailable = mTts.setLanguage(defaultLocale);
421         if (evaluateDefaultLocale() && mSampleText == null) {
422             getSampleText();
423         }
424     }
425 
evaluateDefaultLocale()426     private boolean evaluateDefaultLocale() {
427         // Check if we are connected to the engine, and CHECK_VOICE_DATA returned list
428         // of available languages.
429         if (mCurrentDefaultLocale == null || mAvailableStrLocals == null) {
430             return false;
431         }
432 
433         boolean notInAvailableLangauges = true;
434         try {
435             // Check if language is listed in CheckVoices Action result as available voice.
436             String defaultLocaleStr = mCurrentDefaultLocale.getISO3Language();
437             if (!TextUtils.isEmpty(mCurrentDefaultLocale.getISO3Country())) {
438                 defaultLocaleStr += "-" + mCurrentDefaultLocale.getISO3Country();
439             }
440             if (!TextUtils.isEmpty(mCurrentDefaultLocale.getVariant())) {
441                 defaultLocaleStr += "-" + mCurrentDefaultLocale.getVariant();
442             }
443 
444             for (String loc : mAvailableStrLocals) {
445                 if (loc.equalsIgnoreCase(defaultLocaleStr)) {
446                     notInAvailableLangauges = false;
447                     break;
448                 }
449             }
450         } catch (MissingResourceException e) {
451             if (DBG) Log.wtf(TAG, "MissingResourceException", e);
452             updateWidgetState(false);
453             return false;
454         }
455 
456         int defaultAvailable = mTts.setLanguage(mCurrentDefaultLocale);
457         if (defaultAvailable == TextToSpeech.LANG_NOT_SUPPORTED ||
458                 defaultAvailable == TextToSpeech.LANG_MISSING_DATA ||
459                 notInAvailableLangauges) {
460             if (DBG) Log.d(TAG, "Default locale for this TTS engine is not supported.");
461             updateWidgetState(false);
462             return false;
463         } else {
464             updateWidgetState(true);
465             return true;
466         }
467     }
468 
469     /**
470      * Ask the current default engine to return a string of sample text to be
471      * spoken to the user.
472      */
getSampleText()473     private void getSampleText() {
474         String currentEngine = mTts.getCurrentEngine();
475 
476         if (TextUtils.isEmpty(currentEngine)) currentEngine = mTts.getDefaultEngine();
477 
478         // TODO: This is currently a hidden private API. The intent extras
479         // and the intent action should be made public if we intend to make this
480         // a public API. We fall back to using a canned set of strings if this
481         // doesn't work.
482         Intent intent = new Intent(TextToSpeech.Engine.ACTION_GET_SAMPLE_TEXT);
483 
484         intent.putExtra("language", mCurrentDefaultLocale.getLanguage());
485         intent.putExtra("country", mCurrentDefaultLocale.getCountry());
486         intent.putExtra("variant", mCurrentDefaultLocale.getVariant());
487         intent.setPackage(currentEngine);
488 
489         try {
490             if (DBG) Log.d(TAG, "Getting sample text: " + intent.toUri(0));
491             startActivityForResult(intent, GET_SAMPLE_TEXT);
492         } catch (ActivityNotFoundException ex) {
493             Log.e(TAG, "Failed to get sample text, no activity found for " + intent + ")");
494         }
495     }
496 
497     /**
498      * Called when voice data integrity check returns
499      */
500     @Override
onActivityResult(int requestCode, int resultCode, Intent data)501     public void onActivityResult(int requestCode, int resultCode, Intent data) {
502         if (requestCode == GET_SAMPLE_TEXT) {
503             onSampleTextReceived(resultCode, data);
504         } else if (requestCode == VOICE_DATA_INTEGRITY_CHECK) {
505             onVoiceDataIntegrityCheckDone(data);
506             if (resultCode != TextToSpeech.Engine.CHECK_VOICE_DATA_FAIL) {
507                 updateDefaultLocalePref(data);
508             }
509         }
510     }
511 
updateDefaultLocalePref(Intent data)512     private void updateDefaultLocalePref(Intent data) {
513         final ArrayList<String> availableLangs =
514                 data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES);
515 
516         final ArrayList<String> unavailableLangs =
517                 data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES);
518 
519         if (availableLangs == null || availableLangs.size() == 0) {
520             mLocalePreference.setEnabled(false);
521             return;
522         }
523         Locale currentLocale = null;
524         if (!mEnginesHelper.isLocaleSetToDefaultForEngine(mTts.getCurrentEngine())) {
525             currentLocale = mEnginesHelper.getLocalePrefForEngine(mTts.getCurrentEngine());
526         }
527 
528         ArrayList<Pair<String, Locale>> entryPairs =
529                 new ArrayList<Pair<String, Locale>>(availableLangs.size());
530         for (int i = 0; i < availableLangs.size(); i++) {
531             Locale locale = mEnginesHelper.parseLocaleString(availableLangs.get(i));
532             if (locale != null) {
533                 entryPairs.add(new Pair<String, Locale>(locale.getDisplayName(), locale));
534             }
535         }
536 
537         // Get the primary locale and create a Collator to sort the strings
538         Locale userLocale = getResources().getConfiguration().getLocales().get(0);
539         Collator collator = Collator.getInstance(userLocale);
540 
541         // Sort the list
542         Collections.sort(entryPairs, (lhs, rhs) -> collator.compare(lhs.first, rhs.first));
543 
544         // Get two arrays out of one of pairs
545         mSelectedLocaleIndex = 0; // Will point to the R.string.tts_lang_use_system value
546         CharSequence[] entries = new CharSequence[availableLangs.size() + 1];
547         CharSequence[] entryValues = new CharSequence[availableLangs.size() + 1];
548 
549         entries[0] = getActivity().getString(R.string.tts_lang_use_system);
550         entryValues[0] = "";
551 
552         int i = 1;
553         for (Pair<String, Locale> entry : entryPairs) {
554             if (entry.second.equals(currentLocale)) {
555                 mSelectedLocaleIndex = i;
556             }
557             entries[i] = entry.first;
558             entryValues[i++] = entry.second.toString();
559         }
560 
561         mLocalePreference.setEntries(entries);
562         mLocalePreference.setEntryValues(entryValues);
563         mLocalePreference.setEnabled(true);
564         setLocalePreference(mSelectedLocaleIndex);
565     }
566 
567     /** Set entry from entry table in mLocalePreference */
setLocalePreference(int index)568     private void setLocalePreference(int index) {
569         if (index < 0) {
570             mLocalePreference.setValue("");
571             mLocalePreference.setSummary(R.string.tts_lang_not_selected);
572         } else {
573             mLocalePreference.setValueIndex(index);
574             mLocalePreference.setSummary(mLocalePreference.getEntries()[index]);
575         }
576     }
577 
578 
getDefaultSampleString()579     private String getDefaultSampleString() {
580         if (mTts != null && mTts.getLanguage() != null) {
581             try {
582                 final String currentLang = mTts.getLanguage().getISO3Language();
583                 String[] strings = getActivity().getResources().getStringArray(
584                         R.array.tts_demo_strings);
585                 String[] langs = getActivity().getResources().getStringArray(
586                         R.array.tts_demo_string_langs);
587 
588                 for (int i = 0; i < strings.length; ++i) {
589                     if (langs[i].equals(currentLang)) {
590                         return strings[i];
591                     }
592                 }
593             } catch (MissingResourceException e) {
594                 if (DBG) Log.wtf(TAG, "MissingResourceException", e);
595                 // Ignore and fall back to default sample string
596             }
597         }
598         return getString(R.string.tts_default_sample_string);
599     }
600 
isNetworkRequiredForSynthesis()601     private boolean isNetworkRequiredForSynthesis() {
602         Set<String> features = mTts.getFeatures(mCurrentDefaultLocale);
603         if (features == null) {
604             return false;
605         }
606         return features.contains(TextToSpeech.Engine.KEY_FEATURE_NETWORK_SYNTHESIS) &&
607                 !features.contains(TextToSpeech.Engine.KEY_FEATURE_EMBEDDED_SYNTHESIS);
608     }
609 
onSampleTextReceived(int resultCode, Intent data)610     private void onSampleTextReceived(int resultCode, Intent data) {
611         String sample = getDefaultSampleString();
612 
613         if (resultCode == TextToSpeech.LANG_AVAILABLE && data != null) {
614             if (data != null && data.getStringExtra("sampleText") != null) {
615                 sample = data.getStringExtra("sampleText");
616             }
617             if (DBG) Log.d(TAG, "Got sample text: " + sample);
618         } else {
619             if (DBG) Log.d(TAG, "Using default sample text :" + sample);
620         }
621 
622         mSampleText = sample;
623         if (mSampleText != null) {
624             updateWidgetState(true);
625         } else {
626             Log.e(TAG, "Did not have a sample string for the requested language. Using default");
627         }
628     }
629 
speakSampleText()630     private void speakSampleText() {
631         final boolean networkRequired = isNetworkRequiredForSynthesis();
632         if (!networkRequired || networkRequired &&
633                 (mTts.isLanguageAvailable(mCurrentDefaultLocale) >= TextToSpeech.LANG_AVAILABLE)) {
634             HashMap<String, String> params = new HashMap<String, String>();
635             params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "Sample");
636 
637             mTts.speak(mSampleText, TextToSpeech.QUEUE_FLUSH, params);
638         } else {
639             Log.w(TAG, "Network required for sample synthesis for requested language");
640             displayNetworkAlert();
641         }
642     }
643 
644     @Override
onPreferenceChange(Preference preference, Object objValue)645     public boolean onPreferenceChange(Preference preference, Object objValue) {
646         if (KEY_DEFAULT_RATE.equals(preference.getKey())) {
647             updateSpeechRate((Integer) objValue);
648         } else if (KEY_DEFAULT_PITCH.equals(preference.getKey())) {
649             updateSpeechPitchValue((Integer) objValue);
650         } else if (preference == mLocalePreference) {
651             String localeString = (String) objValue;
652             updateLanguageTo(
653                     (!TextUtils.isEmpty(localeString)
654                             ? mEnginesHelper.parseLocaleString(localeString)
655                             : null));
656             checkDefaultLocale();
657             return true;
658         }
659         return true;
660     }
661 
updateLanguageTo(Locale locale)662     private void updateLanguageTo(Locale locale) {
663         int selectedLocaleIndex = -1;
664         String localeString = (locale != null) ? locale.toString() : "";
665         for (int i = 0; i < mLocalePreference.getEntryValues().length; i++) {
666             if (localeString.equalsIgnoreCase(mLocalePreference.getEntryValues()[i].toString())) {
667                 selectedLocaleIndex = i;
668                 break;
669             }
670         }
671 
672         if (selectedLocaleIndex == -1) {
673             Log.w(TAG, "updateLanguageTo called with unknown locale argument");
674             return;
675         }
676         mLocalePreference.setSummary(mLocalePreference.getEntries()[selectedLocaleIndex]);
677         mSelectedLocaleIndex = selectedLocaleIndex;
678 
679         mEnginesHelper.updateLocalePrefForEngine(mTts.getCurrentEngine(), locale);
680 
681         // Null locale means "use system default"
682         mTts.setLanguage((locale != null) ? locale : Locale.getDefault());
683     }
684 
resetTts()685     private void resetTts() {
686         // Reset button.
687         int speechRateSeekbarProgress =
688                 getSeekBarProgressFromValue(
689                         KEY_DEFAULT_RATE, TextToSpeech.Engine.DEFAULT_RATE);
690         mDefaultRatePref.setProgress(speechRateSeekbarProgress);
691         updateSpeechRate(speechRateSeekbarProgress);
692         int pitchSeekbarProgress =
693                 getSeekBarProgressFromValue(
694                         KEY_DEFAULT_PITCH, TextToSpeech.Engine.DEFAULT_PITCH);
695         mDefaultPitchPref.setProgress(pitchSeekbarProgress);
696         updateSpeechPitchValue(pitchSeekbarProgress);
697     }
698 
updateSpeechRate(int speechRateSeekBarProgress)699     private void updateSpeechRate(int speechRateSeekBarProgress) {
700         mDefaultRate = getValueFromSeekBarProgress(KEY_DEFAULT_RATE, speechRateSeekBarProgress);
701         try {
702             updateTTSSetting(TTS_DEFAULT_RATE, mDefaultRate);
703             if (mTts != null) {
704                 mTts.setSpeechRate(mDefaultRate / 100.0f);
705             }
706             if (DBG) Log.d(TAG, "TTS default rate changed, now " + mDefaultRate);
707         } catch (NumberFormatException e) {
708             Log.e(TAG, "could not persist default TTS rate setting", e);
709         }
710         return;
711     }
712 
updateSpeechPitchValue(int speechPitchSeekBarProgress)713     private void updateSpeechPitchValue(int speechPitchSeekBarProgress) {
714         mDefaultPitch = getValueFromSeekBarProgress(KEY_DEFAULT_PITCH, speechPitchSeekBarProgress);
715         try {
716             updateTTSSetting(TTS_DEFAULT_PITCH, mDefaultPitch);
717             if (mTts != null) {
718                 mTts.setPitch(mDefaultPitch / 100.0f);
719             }
720             if (DBG) Log.d(TAG, "TTS default pitch changed, now" + mDefaultPitch);
721         } catch (NumberFormatException e) {
722             Log.e(TAG, "could not persist default TTS pitch setting", e);
723         }
724         return;
725     }
726 
updateTTSSetting(String key, int value)727     private void updateTTSSetting(String key, int value) {
728         Secure.putInt(getContentResolver(), key, value);
729         final int managedProfileUserId =
730                 Utils.getManagedProfileId(mUserManager, UserHandle.myUserId());
731         if (managedProfileUserId != UserHandle.USER_NULL) {
732             Secure.putIntForUser(getContentResolver(), key, value, managedProfileUserId);
733         }
734     }
735 
updateWidgetState(boolean enable)736     private void updateWidgetState(boolean enable) {
737         getActivity().runOnUiThread(() -> {
738             mActionButtons.setButton1Enabled(enable);
739             mDefaultRatePref.setEnabled(enable);
740             mDefaultPitchPref.setEnabled(enable);
741         });
742     }
743 
displayNetworkAlert()744     private void displayNetworkAlert() {
745         AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
746         builder.setTitle(android.R.string.dialog_alert_title)
747                 .setMessage(getActivity().getString(R.string.tts_engine_network_required))
748                 .setCancelable(false)
749                 .setPositiveButton(android.R.string.ok, null);
750 
751         AlertDialog dialog = builder.create();
752         dialog.show();
753     }
754 
755     /** Check whether the voice data for the engine is ok. */
checkVoiceData(String engine)756     private void checkVoiceData(String engine) {
757         Intent intent = new Intent(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
758         intent.setPackage(engine);
759         try {
760             if (DBG) Log.d(TAG, "Updating engine: Checking voice data: " + intent.toUri(0));
761             startActivityForResult(intent, VOICE_DATA_INTEGRITY_CHECK);
762         } catch (ActivityNotFoundException ex) {
763             Log.e(TAG, "Failed to check TTS data, no activity found for " + intent + ")");
764         }
765     }
766 
767     /** The voice data check is complete. */
onVoiceDataIntegrityCheckDone(Intent data)768     private void onVoiceDataIntegrityCheckDone(Intent data) {
769         final String engine = mTts.getCurrentEngine();
770 
771         if (engine == null) {
772             Log.e(TAG, "Voice data check complete, but no engine bound");
773             return;
774         }
775 
776         if (data == null) {
777             Log.e(TAG, "Engine failed voice data integrity check (null return)" +
778                     mTts.getCurrentEngine());
779             return;
780         }
781 
782         android.provider.Settings.Secure.putString(getContentResolver(), TTS_DEFAULT_SYNTH, engine);
783 
784         mAvailableStrLocals = data.getStringArrayListExtra(
785                 TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES);
786         if (mAvailableStrLocals == null) {
787             Log.e(TAG, "Voice data check complete, but no available voices found");
788             // Set mAvailableStrLocals to empty list
789             mAvailableStrLocals = new ArrayList<String>();
790         }
791         if (evaluateDefaultLocale()) {
792             getSampleText();
793         }
794     }
795 
796     @Override
onGearClick(GearPreference p)797     public void onGearClick(GearPreference p) {
798         if (KEY_TTS_ENGINE_PREFERENCE.equals(p.getKey())) {
799             EngineInfo info = mEnginesHelper.getEngineInfo(mCurrentEngine);
800             final Intent settingsIntent = mEnginesHelper.getSettingsIntent(info.name);
801             if (settingsIntent != null) {
802                 startActivity(settingsIntent);
803             } else {
804                 Log.e(TAG, "settingsIntent is null");
805             }
806             FeatureFactory.getFactory(getContext()).getMetricsFeatureProvider()
807                     .logClickedPreference(p, getMetricsCategory());
808         }
809     }
810 
811     public static final BaseSearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
812             new BaseSearchIndexProvider(R.xml.tts_settings);
813 
814 }
815