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 
322         mDefaultPitchPref.setProgress(
323                 getSeekBarProgressFromValue(KEY_DEFAULT_PITCH, mDefaultPitch));
324         mDefaultPitchPref.setOnPreferenceChangeListener(this);
325         mDefaultPitchPref.setMax(getSeekBarProgressFromValue(KEY_DEFAULT_PITCH, MAX_SPEECH_PITCH));
326 
327         if (mTts != null) {
328             mCurrentEngine = mTts.getCurrentEngine();
329             mTts.setSpeechRate(mDefaultRate / 100.0f);
330             mTts.setPitch(mDefaultPitch / 100.0f);
331         }
332 
333         SettingsActivity activity = null;
334         if (getActivity() instanceof SettingsActivity) {
335             activity = (SettingsActivity) getActivity();
336         } else {
337             throw new IllegalStateException("TextToSpeechSettings used outside a " +
338                     "Settings");
339         }
340 
341         if (mCurrentEngine != null) {
342             EngineInfo info = mEnginesHelper.getEngineInfo(mCurrentEngine);
343 
344             Preference mEnginePreference = findPreference(KEY_TTS_ENGINE_PREFERENCE);
345             ((GearPreference) mEnginePreference).setOnGearClickListener(this);
346             mEnginePreference.setSummary(info.label);
347         }
348 
349         checkVoiceData(mCurrentEngine);
350     }
351 
352     /**
353      * The minimum speech pitch/rate value should be > 0 but the minimum value of a seekbar in
354      * android is fixed at 0. Therefore, we increment the seekbar progress with MIN_SPEECH_VALUE so
355      * that the minimum seekbar progress value is MIN_SPEECH_PITCH/RATE. SPEECH_VALUE =
356      * MIN_SPEECH_VALUE + SEEKBAR_PROGRESS
357      */
getValueFromSeekBarProgress(String preferenceKey, int progress)358     private int getValueFromSeekBarProgress(String preferenceKey, int progress) {
359         if (preferenceKey.equals(KEY_DEFAULT_RATE)) {
360             return MIN_SPEECH_RATE + progress;
361         } else if (preferenceKey.equals(KEY_DEFAULT_PITCH)) {
362             return MIN_SPEECH_PITCH + progress;
363         }
364         return progress;
365     }
366 
367     /**
368      * Since we are appending the MIN_SPEECH value to the speech seekbar progress, the speech
369      * seekbar progress should be set to (speechValue - MIN_SPEECH value).
370      */
getSeekBarProgressFromValue(String preferenceKey, int value)371     private int getSeekBarProgressFromValue(String preferenceKey, int value) {
372         if (preferenceKey.equals(KEY_DEFAULT_RATE)) {
373             return value - MIN_SPEECH_RATE;
374         } else if (preferenceKey.equals(KEY_DEFAULT_PITCH)) {
375             return value - MIN_SPEECH_PITCH;
376         }
377         return value;
378     }
379 
380     /** Called when the TTS engine is initialized. */
onInitEngine(int status)381     public void onInitEngine(int status) {
382         if (status == TextToSpeech.SUCCESS) {
383             if (DBG) Log.d(TAG, "TTS engine for settings screen initialized.");
384             successSetup();
385         } else {
386             if (DBG) {
387                 Log.d(TAG,
388                         "TTS engine for settings screen failed to initialize successfully.");
389             }
390             updateWidgetState(false);
391         }
392     }
393 
394     /** Initialize TTS Settings on successful engine init. */
successSetup()395     private void successSetup() {
396         checkDefaultLocale();
397         getActivity().runOnUiThread(() -> mLocalePreference.setEnabled(true));
398     }
399 
checkDefaultLocale()400     private void checkDefaultLocale() {
401         Locale defaultLocale = mTts.getDefaultLanguage();
402         if (defaultLocale == null) {
403             Log.e(TAG, "Failed to get default language from engine " + mCurrentEngine);
404             updateWidgetState(false);
405             return;
406         }
407 
408         // ISO-3166 alpha 3 country codes are out of spec. If we won't normalize,
409         // we may end up with English (USA)and German (DEU).
410         final Locale oldDefaultLocale = mCurrentDefaultLocale;
411         mCurrentDefaultLocale = mEnginesHelper.parseLocaleString(defaultLocale.toString());
412         if (!Objects.equals(oldDefaultLocale, mCurrentDefaultLocale)) {
413             mSampleText = null;
414         }
415 
416         int defaultAvailable = mTts.setLanguage(defaultLocale);
417         if (evaluateDefaultLocale() && mSampleText == null) {
418             getSampleText();
419         }
420     }
421 
evaluateDefaultLocale()422     private boolean evaluateDefaultLocale() {
423         // Check if we are connected to the engine, and CHECK_VOICE_DATA returned list
424         // of available languages.
425         if (mCurrentDefaultLocale == null || mAvailableStrLocals == null) {
426             return false;
427         }
428 
429         boolean notInAvailableLangauges = true;
430         try {
431             // Check if language is listed in CheckVoices Action result as available voice.
432             String defaultLocaleStr = mCurrentDefaultLocale.getISO3Language();
433             if (!TextUtils.isEmpty(mCurrentDefaultLocale.getISO3Country())) {
434                 defaultLocaleStr += "-" + mCurrentDefaultLocale.getISO3Country();
435             }
436             if (!TextUtils.isEmpty(mCurrentDefaultLocale.getVariant())) {
437                 defaultLocaleStr += "-" + mCurrentDefaultLocale.getVariant();
438             }
439 
440             for (String loc : mAvailableStrLocals) {
441                 if (loc.equalsIgnoreCase(defaultLocaleStr)) {
442                     notInAvailableLangauges = false;
443                     break;
444                 }
445             }
446         } catch (MissingResourceException e) {
447             if (DBG) Log.wtf(TAG, "MissingResourceException", e);
448             updateWidgetState(false);
449             return false;
450         }
451 
452         int defaultAvailable = mTts.setLanguage(mCurrentDefaultLocale);
453         if (defaultAvailable == TextToSpeech.LANG_NOT_SUPPORTED ||
454                 defaultAvailable == TextToSpeech.LANG_MISSING_DATA ||
455                 notInAvailableLangauges) {
456             if (DBG) Log.d(TAG, "Default locale for this TTS engine is not supported.");
457             updateWidgetState(false);
458             return false;
459         } else {
460             updateWidgetState(true);
461             return true;
462         }
463     }
464 
465     /**
466      * Ask the current default engine to return a string of sample text to be
467      * spoken to the user.
468      */
getSampleText()469     private void getSampleText() {
470         String currentEngine = mTts.getCurrentEngine();
471 
472         if (TextUtils.isEmpty(currentEngine)) currentEngine = mTts.getDefaultEngine();
473 
474         // TODO: This is currently a hidden private API. The intent extras
475         // and the intent action should be made public if we intend to make this
476         // a public API. We fall back to using a canned set of strings if this
477         // doesn't work.
478         Intent intent = new Intent(TextToSpeech.Engine.ACTION_GET_SAMPLE_TEXT);
479 
480         intent.putExtra("language", mCurrentDefaultLocale.getLanguage());
481         intent.putExtra("country", mCurrentDefaultLocale.getCountry());
482         intent.putExtra("variant", mCurrentDefaultLocale.getVariant());
483         intent.setPackage(currentEngine);
484 
485         try {
486             if (DBG) Log.d(TAG, "Getting sample text: " + intent.toUri(0));
487             startActivityForResult(intent, GET_SAMPLE_TEXT);
488         } catch (ActivityNotFoundException ex) {
489             Log.e(TAG, "Failed to get sample text, no activity found for " + intent + ")");
490         }
491     }
492 
493     /**
494      * Called when voice data integrity check returns
495      */
496     @Override
onActivityResult(int requestCode, int resultCode, Intent data)497     public void onActivityResult(int requestCode, int resultCode, Intent data) {
498         if (requestCode == GET_SAMPLE_TEXT) {
499             onSampleTextReceived(resultCode, data);
500         } else if (requestCode == VOICE_DATA_INTEGRITY_CHECK) {
501             onVoiceDataIntegrityCheckDone(data);
502             if (resultCode != TextToSpeech.Engine.CHECK_VOICE_DATA_FAIL) {
503                 updateDefaultLocalePref(data);
504             }
505         }
506     }
507 
updateDefaultLocalePref(Intent data)508     private void updateDefaultLocalePref(Intent data) {
509         final ArrayList<String> availableLangs =
510                 data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES);
511 
512         final ArrayList<String> unavailableLangs =
513                 data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES);
514 
515         if (availableLangs == null || availableLangs.size() == 0) {
516             mLocalePreference.setEnabled(false);
517             return;
518         }
519         Locale currentLocale = null;
520         if (!mEnginesHelper.isLocaleSetToDefaultForEngine(mTts.getCurrentEngine())) {
521             currentLocale = mEnginesHelper.getLocalePrefForEngine(mTts.getCurrentEngine());
522         }
523 
524         ArrayList<Pair<String, Locale>> entryPairs =
525                 new ArrayList<Pair<String, Locale>>(availableLangs.size());
526         for (int i = 0; i < availableLangs.size(); i++) {
527             Locale locale = mEnginesHelper.parseLocaleString(availableLangs.get(i));
528             if (locale != null) {
529                 entryPairs.add(new Pair<String, Locale>(locale.getDisplayName(), locale));
530             }
531         }
532 
533         // Get the primary locale and create a Collator to sort the strings
534         Locale userLocale = getResources().getConfiguration().getLocales().get(0);
535         Collator collator = Collator.getInstance(userLocale);
536 
537         // Sort the list
538         Collections.sort(entryPairs, (lhs, rhs) -> collator.compare(lhs.first, rhs.first));
539 
540         // Get two arrays out of one of pairs
541         mSelectedLocaleIndex = 0; // Will point to the R.string.tts_lang_use_system value
542         CharSequence[] entries = new CharSequence[availableLangs.size() + 1];
543         CharSequence[] entryValues = new CharSequence[availableLangs.size() + 1];
544 
545         entries[0] = getActivity().getString(R.string.tts_lang_use_system);
546         entryValues[0] = "";
547 
548         int i = 1;
549         for (Pair<String, Locale> entry : entryPairs) {
550             if (entry.second.equals(currentLocale)) {
551                 mSelectedLocaleIndex = i;
552             }
553             entries[i] = entry.first;
554             entryValues[i++] = entry.second.toString();
555         }
556 
557         mLocalePreference.setEntries(entries);
558         mLocalePreference.setEntryValues(entryValues);
559         mLocalePreference.setEnabled(true);
560         setLocalePreference(mSelectedLocaleIndex);
561     }
562 
563     /** Set entry from entry table in mLocalePreference */
setLocalePreference(int index)564     private void setLocalePreference(int index) {
565         if (index < 0) {
566             mLocalePreference.setValue("");
567             mLocalePreference.setSummary(R.string.tts_lang_not_selected);
568         } else {
569             mLocalePreference.setValueIndex(index);
570             mLocalePreference.setSummary(mLocalePreference.getEntries()[index]);
571         }
572     }
573 
574 
getDefaultSampleString()575     private String getDefaultSampleString() {
576         if (mTts != null && mTts.getLanguage() != null) {
577             try {
578                 final String currentLang = mTts.getLanguage().getISO3Language();
579                 String[] strings = getActivity().getResources().getStringArray(
580                         R.array.tts_demo_strings);
581                 String[] langs = getActivity().getResources().getStringArray(
582                         R.array.tts_demo_string_langs);
583 
584                 for (int i = 0; i < strings.length; ++i) {
585                     if (langs[i].equals(currentLang)) {
586                         return strings[i];
587                     }
588                 }
589             } catch (MissingResourceException e) {
590                 if (DBG) Log.wtf(TAG, "MissingResourceException", e);
591                 // Ignore and fall back to default sample string
592             }
593         }
594         return getString(R.string.tts_default_sample_string);
595     }
596 
isNetworkRequiredForSynthesis()597     private boolean isNetworkRequiredForSynthesis() {
598         Set<String> features = mTts.getFeatures(mCurrentDefaultLocale);
599         if (features == null) {
600             return false;
601         }
602         return features.contains(TextToSpeech.Engine.KEY_FEATURE_NETWORK_SYNTHESIS) &&
603                 !features.contains(TextToSpeech.Engine.KEY_FEATURE_EMBEDDED_SYNTHESIS);
604     }
605 
onSampleTextReceived(int resultCode, Intent data)606     private void onSampleTextReceived(int resultCode, Intent data) {
607         String sample = getDefaultSampleString();
608 
609         if (resultCode == TextToSpeech.LANG_AVAILABLE && data != null) {
610             if (data != null && data.getStringExtra("sampleText") != null) {
611                 sample = data.getStringExtra("sampleText");
612             }
613             if (DBG) Log.d(TAG, "Got sample text: " + sample);
614         } else {
615             if (DBG) Log.d(TAG, "Using default sample text :" + sample);
616         }
617 
618         mSampleText = sample;
619         if (mSampleText != null) {
620             updateWidgetState(true);
621         } else {
622             Log.e(TAG, "Did not have a sample string for the requested language. Using default");
623         }
624     }
625 
speakSampleText()626     private void speakSampleText() {
627         final boolean networkRequired = isNetworkRequiredForSynthesis();
628         if (!networkRequired || networkRequired &&
629                 (mTts.isLanguageAvailable(mCurrentDefaultLocale) >= TextToSpeech.LANG_AVAILABLE)) {
630             HashMap<String, String> params = new HashMap<String, String>();
631             params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "Sample");
632 
633             mTts.speak(mSampleText, TextToSpeech.QUEUE_FLUSH, params);
634         } else {
635             Log.w(TAG, "Network required for sample synthesis for requested language");
636             displayNetworkAlert();
637         }
638     }
639 
640     @Override
onPreferenceChange(Preference preference, Object objValue)641     public boolean onPreferenceChange(Preference preference, Object objValue) {
642         if (KEY_DEFAULT_RATE.equals(preference.getKey())) {
643             updateSpeechRate((Integer) objValue);
644         } else if (KEY_DEFAULT_PITCH.equals(preference.getKey())) {
645             updateSpeechPitchValue((Integer) objValue);
646         } else if (preference == mLocalePreference) {
647             String localeString = (String) objValue;
648             updateLanguageTo(
649                     (!TextUtils.isEmpty(localeString)
650                             ? mEnginesHelper.parseLocaleString(localeString)
651                             : null));
652             checkDefaultLocale();
653             return true;
654         }
655         return true;
656     }
657 
updateLanguageTo(Locale locale)658     private void updateLanguageTo(Locale locale) {
659         int selectedLocaleIndex = -1;
660         String localeString = (locale != null) ? locale.toString() : "";
661         for (int i = 0; i < mLocalePreference.getEntryValues().length; i++) {
662             if (localeString.equalsIgnoreCase(mLocalePreference.getEntryValues()[i].toString())) {
663                 selectedLocaleIndex = i;
664                 break;
665             }
666         }
667 
668         if (selectedLocaleIndex == -1) {
669             Log.w(TAG, "updateLanguageTo called with unknown locale argument");
670             return;
671         }
672         mLocalePreference.setSummary(mLocalePreference.getEntries()[selectedLocaleIndex]);
673         mSelectedLocaleIndex = selectedLocaleIndex;
674 
675         mEnginesHelper.updateLocalePrefForEngine(mTts.getCurrentEngine(), locale);
676 
677         // Null locale means "use system default"
678         mTts.setLanguage((locale != null) ? locale : Locale.getDefault());
679     }
680 
resetTts()681     private void resetTts() {
682         // Reset button.
683         int speechRateSeekbarProgress =
684                 getSeekBarProgressFromValue(
685                         KEY_DEFAULT_RATE, TextToSpeech.Engine.DEFAULT_RATE);
686         mDefaultRatePref.setProgress(speechRateSeekbarProgress);
687         updateSpeechRate(speechRateSeekbarProgress);
688         int pitchSeekbarProgress =
689                 getSeekBarProgressFromValue(
690                         KEY_DEFAULT_PITCH, TextToSpeech.Engine.DEFAULT_PITCH);
691         mDefaultPitchPref.setProgress(pitchSeekbarProgress);
692         updateSpeechPitchValue(pitchSeekbarProgress);
693     }
694 
updateSpeechRate(int speechRateSeekBarProgress)695     private void updateSpeechRate(int speechRateSeekBarProgress) {
696         mDefaultRate = getValueFromSeekBarProgress(KEY_DEFAULT_RATE, speechRateSeekBarProgress);
697         try {
698             updateTTSSetting(TTS_DEFAULT_RATE, mDefaultRate);
699             if (mTts != null) {
700                 mTts.setSpeechRate(mDefaultRate / 100.0f);
701             }
702             if (DBG) Log.d(TAG, "TTS default rate changed, now " + mDefaultRate);
703         } catch (NumberFormatException e) {
704             Log.e(TAG, "could not persist default TTS rate setting", e);
705         }
706         return;
707     }
708 
updateSpeechPitchValue(int speechPitchSeekBarProgress)709     private void updateSpeechPitchValue(int speechPitchSeekBarProgress) {
710         mDefaultPitch = getValueFromSeekBarProgress(KEY_DEFAULT_PITCH, speechPitchSeekBarProgress);
711         try {
712             updateTTSSetting(TTS_DEFAULT_PITCH, mDefaultPitch);
713             if (mTts != null) {
714                 mTts.setPitch(mDefaultPitch / 100.0f);
715             }
716             if (DBG) Log.d(TAG, "TTS default pitch changed, now" + mDefaultPitch);
717         } catch (NumberFormatException e) {
718             Log.e(TAG, "could not persist default TTS pitch setting", e);
719         }
720         return;
721     }
722 
updateTTSSetting(String key, int value)723     private void updateTTSSetting(String key, int value) {
724         Secure.putInt(getContentResolver(), key, value);
725         final int managedProfileUserId =
726                 Utils.getManagedProfileId(mUserManager, UserHandle.myUserId());
727         if (managedProfileUserId != UserHandle.USER_NULL) {
728             Secure.putIntForUser(getContentResolver(), key, value, managedProfileUserId);
729         }
730     }
731 
updateWidgetState(boolean enable)732     private void updateWidgetState(boolean enable) {
733         getActivity().runOnUiThread(() -> {
734             mActionButtons.setButton1Enabled(enable);
735             mDefaultRatePref.setEnabled(enable);
736             mDefaultPitchPref.setEnabled(enable);
737         });
738     }
739 
displayNetworkAlert()740     private void displayNetworkAlert() {
741         AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
742         builder.setTitle(android.R.string.dialog_alert_title)
743                 .setMessage(getActivity().getString(R.string.tts_engine_network_required))
744                 .setCancelable(false)
745                 .setPositiveButton(android.R.string.ok, null);
746 
747         AlertDialog dialog = builder.create();
748         dialog.show();
749     }
750 
751     /** Check whether the voice data for the engine is ok. */
checkVoiceData(String engine)752     private void checkVoiceData(String engine) {
753         Intent intent = new Intent(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
754         intent.setPackage(engine);
755         try {
756             if (DBG) Log.d(TAG, "Updating engine: Checking voice data: " + intent.toUri(0));
757             startActivityForResult(intent, VOICE_DATA_INTEGRITY_CHECK);
758         } catch (ActivityNotFoundException ex) {
759             Log.e(TAG, "Failed to check TTS data, no activity found for " + intent + ")");
760         }
761     }
762 
763     /** The voice data check is complete. */
onVoiceDataIntegrityCheckDone(Intent data)764     private void onVoiceDataIntegrityCheckDone(Intent data) {
765         final String engine = mTts.getCurrentEngine();
766 
767         if (engine == null) {
768             Log.e(TAG, "Voice data check complete, but no engine bound");
769             return;
770         }
771 
772         if (data == null) {
773             Log.e(TAG, "Engine failed voice data integrity check (null return)" +
774                     mTts.getCurrentEngine());
775             return;
776         }
777 
778         android.provider.Settings.Secure.putString(getContentResolver(), TTS_DEFAULT_SYNTH, engine);
779 
780         mAvailableStrLocals = data.getStringArrayListExtra(
781                 TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES);
782         if (mAvailableStrLocals == null) {
783             Log.e(TAG, "Voice data check complete, but no available voices found");
784             // Set mAvailableStrLocals to empty list
785             mAvailableStrLocals = new ArrayList<String>();
786         }
787         if (evaluateDefaultLocale()) {
788             getSampleText();
789         }
790     }
791 
792     @Override
onGearClick(GearPreference p)793     public void onGearClick(GearPreference p) {
794         if (KEY_TTS_ENGINE_PREFERENCE.equals(p.getKey())) {
795             EngineInfo info = mEnginesHelper.getEngineInfo(mCurrentEngine);
796             final Intent settingsIntent = mEnginesHelper.getSettingsIntent(info.name);
797             if (settingsIntent != null) {
798                 startActivity(settingsIntent);
799             } else {
800                 Log.e(TAG, "settingsIntent is null");
801             }
802             FeatureFactory.getFactory(getContext()).getMetricsFeatureProvider()
803                     .logClickedPreference(p, getMetricsCategory());
804         }
805     }
806 
807     public static final BaseSearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
808             new BaseSearchIndexProvider(R.xml.tts_settings);
809 
810 }
811