-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathlinux_settings.rs
More file actions
273 lines (248 loc) · 7.96 KB
/
Copy pathlinux_settings.rs
File metadata and controls
273 lines (248 loc) · 7.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
use std::fs::{self, File};
use std::io::Write;
use std::path::PathBuf;
use color_eyre::eyre::{Result, WrapErr, eyre};
use serde::{Deserialize, Serialize};
use x11rb::protocol::xproto::ModMask;
use x11rb::rust_connection::RustConnection;
use crate::linux_input::{Keymap, XK_ALT_L, XK_ALT_R};
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(default)]
pub struct LinuxSettings {
pub schema_version: u32,
pub dictation_hotkey: LinuxHotkey,
pub double_tap_lock: bool,
#[serde(default = "legacy_paste_with_shift")]
pub paste_with_shift: bool,
pub sound_effect_volume: f32,
pub transcription: crate::transcription_models::TranscriptionSelection,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(default)]
pub struct LinuxHotkey {
pub control: bool,
pub alt: bool,
pub shift: bool,
pub super_key: bool,
pub key: String,
}
impl Default for LinuxSettings {
fn default() -> Self {
Self {
schema_version: 1,
dictation_hotkey: LinuxHotkey::default(),
double_tap_lock: true,
paste_with_shift: false,
sound_effect_volume: 0.5,
transcription: crate::transcription_models::TranscriptionSelection::default(),
}
}
}
fn legacy_paste_with_shift() -> bool {
// Existing X11 settings predate this preference and always used Ctrl-Shift-V.
true
}
impl Default for LinuxHotkey {
fn default() -> Self {
Self {
control: false,
alt: true,
shift: false,
super_key: false,
key: "space".into(),
}
}
}
impl LinuxSettings {
pub fn load() -> Result<Self> {
let path = settings_path()?;
if !path.exists() {
return Ok(Self::default());
}
let settings: Self = serde_json::from_slice(&fs::read(&path)?)
.wrap_err_with(|| format!("could not parse {}", path.display()))?;
settings.validate()?;
Ok(settings)
}
fn validate(&self) -> Result<()> {
self.dictation_hotkey.validate()?;
crate::transcription_models::validate(&self.transcription)?;
if !(0.0..=1.0).contains(&self.sound_effect_volume) {
return Err(eyre!("Sound volume must be between zero and one"));
}
Ok(())
}
pub fn save(&self) -> Result<()> {
self.validate()?;
let path = settings_path()?;
let directory = path.parent().unwrap();
fs::create_dir_all(directory)?;
let partial = path.with_extension("json.partial");
let mut file = File::create(&partial)?;
serde_json::to_writer_pretty(&mut file, self)?;
file.write_all(b"\n")?;
file.sync_all()?;
fs::rename(partial, &path)?;
File::open(directory)?.sync_all()?;
Ok(())
}
}
impl LinuxHotkey {
pub fn validate(&self) -> Result<()> {
if self.key.trim().is_empty() {
return Err(eyre!("Linux hotkeys require a non-modifier key"));
}
Ok(())
}
pub fn label(&self) -> String {
self.keycaps().join("+")
}
pub fn keycaps(&self) -> Vec<String> {
let mut parts = Vec::new();
if self.control {
parts.push("Ctrl".to_string());
}
if self.alt {
parts.push("Alt".to_string());
}
if self.shift {
parts.push("Shift".to_string());
}
if self.super_key {
parts.push("Super".to_string());
}
let key = if self.key == "space" {
"Space".into()
} else {
self.key.to_ascii_uppercase()
};
parts.push(key);
parts
}
pub(crate) fn modifier_mask(
&self,
connection: &RustConnection,
keymap: &Keymap,
) -> Result<ModMask> {
let mut result = ModMask::default();
for (enabled, symbols) in [
(self.control, &[0xffe3, 0xffe4][..]),
(self.alt, &[XK_ALT_L, XK_ALT_R][..]),
(self.shift, &[0xffe1, 0xffe2][..]),
(self.super_key, &[0xffeb, 0xffec][..]),
] {
if enabled {
result |= keymap.modifier_for(connection, symbols)?;
}
}
Ok(result)
}
}
fn settings_path() -> Result<PathBuf> {
Ok(crate::app_paths::support_dir()?.join("linux-settings.json"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_binding_is_alt_space() {
assert_eq!(
LinuxSettings::default().dictation_hotkey.label(),
"Alt+Space"
);
}
#[test]
fn modifier_only_bindings_are_rejected() {
let binding = LinuxHotkey {
key: String::new(),
..LinuxHotkey::default()
};
assert!(binding.validate().is_err());
}
#[test]
fn standalone_function_keys_are_accepted() {
let binding = LinuxHotkey {
alt: false,
key: "f12".into(),
..LinuxHotkey::default()
};
assert_eq!(binding.label(), "F12");
assert!(binding.validate().is_ok());
}
#[test]
fn settings_without_transcription_keep_the_default_selection() {
let settings: LinuxSettings = serde_json::from_str(
r#"{
"schema_version": 1,
"platform": "x11",
"dictation_hotkey": {
"control": false,
"alt": true,
"shift": false,
"super_key": false,
"key": "space"
},
"double_tap_lock": true
}"#,
)
.unwrap();
assert_eq!(
settings.transcription,
crate::transcription_models::TranscriptionSelection::default()
);
}
#[test]
fn legacy_settings_are_shared_between_display_sessions() {
let legacy = r#"{"platform":"x11","double_tap_lock":false}"#;
let settings: LinuxSettings = serde_json::from_str(legacy).unwrap();
assert!(!settings.double_tap_lock);
assert!(settings.paste_with_shift);
// Display selection is runtime state, not a preference that survives logout.
let saved = serde_json::to_value(&settings).unwrap();
assert!(saved.get("platform").is_none());
assert_eq!(
serde_json::from_value::<LinuxSettings>(saved).unwrap(),
settings
);
}
#[test]
fn fresh_settings_use_standard_paste_and_preserve_an_explicit_choice() {
let settings = LinuxSettings::default();
assert!(!settings.paste_with_shift);
let saved = serde_json::to_value(&settings).unwrap();
assert_eq!(
serde_json::from_value::<LinuxSettings>(saved).unwrap(),
settings
);
let legacy: LinuxSettings = serde_json::from_str(r#"{"paste_with_shift":false}"#).unwrap();
assert!(!legacy.paste_with_shift);
}
#[test]
fn recording_volume_defaults_for_new_and_legacy_settings_and_round_trips() {
assert_eq!(LinuxSettings::default().sound_effect_volume, 0.5);
let legacy: LinuxSettings = serde_json::from_str(r#"{"platform":"x11"}"#).unwrap();
assert_eq!(legacy.sound_effect_volume, 0.5);
for volume in [0.0, 0.25, 0.5, 0.75, 1.0] {
let settings = LinuxSettings {
sound_effect_volume: volume,
..Default::default()
};
settings.validate().unwrap();
let saved = serde_json::to_vec(&settings).unwrap();
assert_eq!(
serde_json::from_slice::<LinuxSettings>(&saved).unwrap(),
settings
);
}
}
#[test]
fn invalid_sound_volume_is_rejected_before_saving() {
for volume in [-0.1, 1.1, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
let settings = LinuxSettings {
sound_effect_volume: volume,
..Default::default()
};
assert!(settings.save().is_err());
}
}
}