Skip to main content

settings_model/
accessibility.rs

1//! The `accessibility` section's screen-reader settings, which every toolkit app reads to run
2//! its narrator. The whole section, with the pointer, typing, hearing and vision assists
3//! Settings edits and the compositor applies, is the `accessibility-settings` crate's model; it
4//! reads these through the definitions here, so the two cannot disagree about a default or a
5//! range.
6
7use serde::Deserialize;
8use serde_json::{Map, Value};
9use std::ops::RangeInclusive;
10
11pub const SECTION: &str = "accessibility";
12
13pub const DEVICE_SECTION: &str = "accessibility_device";
14
15/// The leaf that turns the screen reader on.
16pub const SCREEN_READER_KEY: &str = "screen_reader";
17
18/// Normalised speech rate, where 100 is the engine default.
19pub const DEFAULT_SCREEN_READER_RATE: u16 = 100;
20pub const SCREEN_READER_RATE_RANGE: RangeInclusive<u16> = 50..=200;
21
22/// Backend-neutral screen-reader voice/language preset.
23#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
24#[cfg_attr(feature = "model", derive(tilo_resource::Model))]
25#[serde(rename_all = "snake_case")]
26pub enum ScreenReaderVoice {
27    #[default]
28    System,
29    EnglishUs,
30    EnglishGb,
31    German,
32    French,
33    Spanish,
34}
35
36impl ScreenReaderVoice {
37    pub const ALL: &'static [Self] = &[
38        Self::System,
39        Self::EnglishUs,
40        Self::EnglishGb,
41        Self::German,
42        Self::French,
43        Self::Spanish,
44    ];
45    pub const OPTIONS: &'static [&'static str] = &[
46        "System voice",
47        "English (US)",
48        "English (UK)",
49        "German",
50        "French",
51        "Spanish",
52    ];
53
54    #[must_use]
55    pub fn label(self) -> &'static str {
56        match self {
57            Self::System => "System voice",
58            Self::EnglishUs => "English (US)",
59            Self::EnglishGb => "English (UK)",
60            Self::German => "German",
61            Self::French => "French",
62            Self::Spanish => "Spanish",
63        }
64    }
65
66    #[must_use]
67    pub fn from_label(label: &str) -> Option<Self> {
68        Self::ALL
69            .iter()
70            .copied()
71            .find(|choice| choice.label() == label)
72    }
73
74    #[must_use]
75    pub fn engine_voice(self) -> Option<&'static str> {
76        match self {
77            Self::System => None,
78            Self::EnglishUs => Some("en-us"),
79            Self::EnglishGb => Some("en-gb"),
80            Self::German => Some("de"),
81            Self::French => Some("fr"),
82            Self::Spanish => Some("es"),
83        }
84    }
85}
86
87#[derive(Clone, Copy, Debug, PartialEq)]
88pub struct ScreenReaderSettings {
89    pub enabled: bool,
90    /// Speech rate multiplier: 1.0 is the engine default.
91    pub rate: f32,
92    pub voice: ScreenReaderVoice,
93}
94
95impl ScreenReaderSettings {
96    pub fn from_section(section: &Map<String, Value>) -> Self {
97        fn key<T: for<'de> Deserialize<'de>>(
98            section: &Map<String, Value>,
99            name: &str,
100        ) -> Option<T> {
101            section
102                .get(name)
103                .and_then(|value| T::deserialize(value).ok())
104        }
105        Self::new(
106            key(section, SCREEN_READER_KEY).unwrap_or(false),
107            key(section, "screen_reader_rate").unwrap_or(DEFAULT_SCREEN_READER_RATE),
108            key(section, "screen_reader_voice").unwrap_or_default(),
109        )
110    }
111
112    pub fn new(enabled: bool, rate_percent: u16, voice: ScreenReaderVoice) -> Self {
113        Self {
114            enabled,
115            rate: f32::from(clamped_rate(rate_percent)) / 100.0,
116            voice,
117        }
118    }
119}
120
121pub fn clamped_rate(rate_percent: u16) -> u16 {
122    rate_percent.clamp(
123        *SCREEN_READER_RATE_RANGE.start(),
124        *SCREEN_READER_RATE_RANGE.end(),
125    )
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    fn section(value: Value) -> Map<String, Value> {
133        let Value::Object(map) = value else {
134            panic!("not an object")
135        };
136        map
137    }
138
139    #[test]
140    fn screen_reader_settings_clamp_their_rate_and_name_their_voices() {
141        {
142            let settings = ScreenReaderSettings::from_section(&section(serde_json::json!({
143                "screen_reader": true,
144                "screen_reader_rate": 900,
145                "screen_reader_voice": "klingon",
146            })));
147            assert!(settings.enabled);
148            assert!((settings.rate - 2.0).abs() < f32::EPSILON);
149            assert_eq!(settings.voice, ScreenReaderVoice::System);
150            assert_eq!(settings.voice.engine_voice(), None);
151
152            let settings = ScreenReaderSettings::from_section(&section(serde_json::json!({
153                "screen_reader_rate": 65,
154                "screen_reader_voice": "english_gb",
155            })));
156            assert!(!settings.enabled);
157            assert!((settings.rate - 0.65).abs() < f32::EPSILON);
158            assert_eq!(settings.voice.engine_voice(), Some("en-gb"));
159        }
160    }
161}