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