diff --git a/modules/shell/MANIFEST.yaml b/modules/shell/MANIFEST.yaml index 1807e77d..e243f72c 100644 --- a/modules/shell/MANIFEST.yaml +++ b/modules/shell/MANIFEST.yaml @@ -375,6 +375,11 @@ evidence: - pattern: '"message":"shell\.command_failed"' level: warning scenario: AB + # The window's K starts once on a settings file broken by hand: settings.rs's sentence goes to + # the log, the user is told which setting and what to do (#783). + - pattern: '"message":"shell\.settings_unread"' + level: warning + scenario: K # A failure of the page's own, thrown then rejected; any other kind of the page's is not provoked. - pattern: '^(?=.*"message":"shell\.page_failed")(?=.*"kind":"ScenarioI")' level: error diff --git a/modules/shell/scripts/e2e_window.py b/modules/shell/scripts/e2e_window.py index 89bbcdb9..8964e274 100644 --- a/modules/shell/scripts/e2e_window.py +++ b/modules/shell/scripts/e2e_window.py @@ -8467,8 +8467,11 @@ def folder_field(): held = window.file.read_text() lines = [line for line in held.splitlines() if not line.startswith("keep_audio")] + ["keep_audio = 0"] broken = "\n".join(lines) + "\n" - refused = "Le réglage n’a pas été enregistré\u00a0: le fichier des réglages ne peut pas être lu\u00a0: corrigez-le, puis réessayez.".replace("\xa0", " ") # WebDriver's `.text` reads U+00A0 as a space - locked_said = "Le fichier des réglages ne peut pas être lu\u00a0: Kitokey ne l’écrit pas tant qu’il n’est pas corrigé.".replace("\xa0", " ") # WebDriver's `.text` reads U+00A0 as a space + # Which setting, on which line, and what to do (#783) — never settings.rs's own sentence. + # WebDriver's `.text` reads U+00A0 as a space. + which = lambda line: f"Ligne {line} : « keep_audio » vaut « always » ou un nombre de jours, de 1 à 36\u202f500. Corrigez-le." # noqa: E731 + refused = f"Le réglage n’a pas été enregistré : le fichier des réglages ne peut pas être lu. {which(len(lines))}" + locked_said = f"Le fichier des réglages ne peut pas être lu : Kitokey ne l’écrit pas tant qu’il n’est pas corrigé. {which(len(lines))}" unreadable = lambda: browser.find_element(By.ID, "settings-unreadable").text # noqa: E731 window.file.write_text(broken) changed(lambda: browser.find_element(By.ID, "reminder").click()) @@ -8484,6 +8487,9 @@ def folder_field(): lines = [line for line in held.splitlines() if not line.startswith("keep_audio")] + ["keep_audio = 0"] window.file.write_text("\n".join(lines) + "\n") raw = f'settings.toml, line {len(lines)}: keep_audio is "always" or a number of days' + # The file's line has moved with developer mode written: the sentences name the new one. + refused = f"Le réglage n’a pas été enregistré : le fichier des réglages ne peut pas être lu. {which(len(lines))}" + locked_said = f"Le fichier des réglages ne peut pas être lu : Kitokey ne l’écrit pas tant qu’il n’est pas corrigé. {which(len(lines))}" changed(lambda: browser.find_element(By.ID, "reminder").click()) said = not_saved() check("developer mode on, the raw text is under the sentence of the command that failed, without its path", said == f"{refused}\n{raw}", said) @@ -8753,7 +8759,8 @@ def log_message(self, *_): wait_for(browser, lambda b: b.find_elements(By.CSS_SELECTOR, "#settings .warn")) warned = browser.find_element(By.CSS_SELECTOR, "#settings .warn").text locked = browser.execute_script("return [...document.querySelectorAll('#settings input, #settings select')].every(e => e.disabled)") - check("a settings file that cannot be read is said so, and nothing can be changed", warned == "Le fichier des réglages ne peut pas être lu : Kitokey ne l’écrit pas tant qu’il n’est pas corrigé." and locked, warned) + which = "Ligne 3 : « keep_audio » vaut « always » ou un nombre de jours, de 1 à 36\u202f500. Corrigez-le." # U+00A0 read as a space + check("a settings file that cannot be read is said so, which setting and what to do, and nothing can be changed", warned == f"Le fichier des réglages ne peut pas être lu : Kitokey ne l’écrit pas tant qu’il n’est pas corrigé. {which}" and locked, warned) check("it is left as it was", window.file.read_text() == f'sessions = "{broken}"\nwelcomed = true\nkeep_audio = 0\n') # The shell itself refuses, not only the page. refused = browser.execute_async_script( diff --git a/modules/shell/src/autostart.rs b/modules/shell/src/autostart.rs index ad67b2de..554aab24 100644 --- a/modules/shell/src/autostart.rs +++ b/modules/shell/src/autostart.rs @@ -104,7 +104,7 @@ pub fn carry_over(before: &Path, entry: &Path) -> io::Result { /// At a start: the entry written when the settings say it never was, and that it was, kept in /// them. True when it was written now. A settings file that cannot be read writes nothing. pub fn first(entry: &Path, settings_file: &Path) -> io::Result { - let mut settings = settings::read(settings_file).map_err(|why| io::Error::new(io::ErrorKind::InvalidData, why))?; + let mut settings = settings::read(settings_file).map_err(|why| io::Error::new(io::ErrorKind::InvalidData, why.detail))?; if settings.autostart.is_some() { return Ok(false); } diff --git a/modules/shell/src/main.rs b/modules/shell/src/main.rs index 634457ae..cf9871db 100644 --- a/modules/shell/src/main.rs +++ b/modules/shell/src/main.rs @@ -214,10 +214,15 @@ impl Shell { /// Reads the settings file again — the user may have changed it by hand — and holds what it /// says; a file that cannot be read is said, by its name and not its path, and what was held /// stays. - fn reread(&self) -> Result { + fn reread(&self) -> Result { let read = settings::file().map_or_else( || Ok(Settings::default()), - |file| settings::read(&file).map_err(|why| settings::unnamed(&why, &file)), + |file| { + settings::read(&file).map_err(|why| settings::Unread { + detail: settings::unnamed(&why.detail, &file), + ..why + }) + }, ); if let Ok(settings) = &read { *self.settings.lock().unwrap() = settings.clone(); @@ -266,7 +271,7 @@ impl Shell { /// The settings read again for a command. fn read_or_told(&self) -> Result { - self.reread().map_err(|why| self.told(Failure::SettingsUnread, why)) + self.reread().map_err(|why| self.told(Failure::SettingsUnread(why.refused), why)) } /// The settings written for a command. @@ -585,7 +590,11 @@ fn main() { let refused = licence::refused(&licence, &sessions, seconds_now()); tracing::info!(licence = %answer, refused, "shell.licence_read"); if let Err(why) = read { - tell(app.handle(), &words::trouble(&Trouble::Settings(why), language)); + // The sentence of `settings.rs` to the log, by the file's name; the user is told which + // setting and what to do (#783). + let detail = settings::file().map_or_else(|| why.detail.clone(), |file| settings::unnamed(&why.detail, &file)); + tracing::warn!(%detail, "shell.settings_unread"); + tell(app.handle(), &words::trouble(&Trouble::Settings(why.refused), language)); } // A recording a Kitokey ended before this one left running: shown, and stopped from here (#773). found(app.handle()); @@ -672,7 +681,7 @@ fn offer_recording(app: &AppHandle, application: String) { tracing::info!("shell.offer_off"); let shell = app.state::(); let _saving = shell.saving.lock().unwrap(); - let saved = shell.reread().and_then(|mut settings| { + let saved = shell.reread().map_err(|why| why.detail).and_then(|mut settings| { settings.offer = false; let file = settings::file().ok_or("this system names no folder for settings")?; settings::write(&file, &settings).map_err(|error| error.to_string())?; @@ -732,7 +741,7 @@ fn show_welcome(app: &AppHandle) { let shell = app.state::(); { let _saving = shell.saving.lock().unwrap(); - let written = shell.reread().and_then(|mut settings| { + let written = shell.reread().map_err(|why| why.detail).and_then(|mut settings| { settings.welcomed = true; let file = settings::file().ok_or("this system names no folder for settings")?; settings::write(&file, &settings).map_err(|error| error.to_string())?; @@ -1699,7 +1708,7 @@ fn models_offered(shell: State<'_, Shell>, name: Option) -> Result (settings, None), - Err(why) => (shell.settings(), Some(shell.told(Failure::SettingsLocked, why))), + Err(why) => (shell.settings(), Some(shell.told(Failure::SettingsLocked(why.refused), why))), }; let (mut chosen, gone, confidential) = match &name { Some(name) => { @@ -2384,7 +2393,7 @@ async fn settings_shown(app: AppHandle, shell: State<'_, Shell>) -> Result (settings, None), - Err(why) => (shell.settings(), Some(shell.told(Failure::SettingsLocked, why))), + Err(why) => (shell.settings(), Some(shell.told(Failure::SettingsLocked(why.refused), why))), }; let models = settings::whisper_models(&models_folder(), &settings) .into_iter() @@ -3290,8 +3299,8 @@ fn write_minutes_from( let settings = match shell.reread() { Ok(settings) => settings, Err(why) => { - refused(why.clone()); - return tell(app, &words::trouble(&Trouble::Settings(why), shell.language())); + refused(why.detail); + return tell(app, &words::trouble(&Trouble::Settings(why.refused), shell.language())); } }; let named = settings.minutes_provider.clone().zip(settings.minutes_model.clone()); @@ -3924,7 +3933,7 @@ fn retranscribe(app: &AppHandle, folder: PathBuf, again: Again, cancel: Cancel) return Ok(()); } shell.transcripts_tried.lock().unwrap().insert(folder.clone(), Some(again.clone())); - let read = shell.reread().map_err(|why| (Failure::SettingsUnread, why))?; + let read = shell.reread().map_err(|why| (Failure::SettingsUnread(why.refused), why.detail))?; // The models this computer lists, as Settings name theirs: a Refaire… may pick Settings' own. let listed = settings::whisper_models(&models_folder(), &read); let settings = own(&read, &folder); diff --git a/modules/shell/src/settings.rs b/modules/shell/src/settings.rs index 64c4fbdb..5ab6bac6 100644 --- a/modules/shell/src/settings.rs +++ b/modules/shell/src/settings.rs @@ -249,31 +249,108 @@ struct Written { microphone_description: Option, } +/// What in a settings file Kitokey refuses, as the user is told it (#783): which setting, on which +/// line. A key is one of the file's own (`KEYS`), never what the user typed in its place. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Refused { + /// The file is there and cannot be opened: its permissions, a folder in its place. + Unopened, + /// A line that is not a setting as TOML writes one, or a setting whose value is not of its kind. + Unparsed { line: usize, key: Option<&'static str> }, + /// `sessions`: not a folder's whole path. + SessionsNotWhole { line: usize }, + /// `model`: not a file's whole path. + ModelNotWhole { line: usize }, + /// `keep_audio`: neither "always" nor a number of days from 1 to 36,500. + KeepAudio { line: usize }, +} + +/// A settings file refused: what the user is told, and the sentence the log and developer mode +/// hold — which names the file by its whole path until `unnamed` is given it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Unread { + pub refused: Refused, + pub detail: String, +} + +impl std::fmt::Display for Unread { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.detail) + } +} + +/// The keys a settings file may hold: those a refusal names. +const KEYS: [&str; 25] = [ + "reminder", + "sessions", + "transcript", + "after", + "model", + "engine", + "transcription_provider", + "transcription_model", + "transcription_agreed", + "minutes_provider", + "minutes_model", + "meeting_language", + "minutes_agreed", + "keep_audio", + "developer", + "offer", + "autostart", + "window", + "log", + "welcomed", + "folded", + "bar_at", + "language", + "microphone", + "microphone_description", +]; + /// Reads the settings. No file is no choice made: the defaults. A file that cannot be read as /// settings is said in one sentence — which file, which line, and what in it — and nothing of /// it is used. -pub fn read(path: &Path) -> Result { +pub fn read(path: &Path) -> Result { + let unread = |refused, detail| Unread { refused, detail }; let text = match fs::read_to_string(path) { Ok(text) => text, Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Settings::default()), - Err(error) => return Err(format!("{} cannot be read ({error})", path.display())), + Err(error) => return Err(unread(Refused::Unopened, format!("{} cannot be read ({error})", path.display()))), }; // The line a place of the file is on: one more than the line ends before it. let line = |at: usize| text[..at.min(text.len())].matches('\n').count() + 1; + // The key a line sets, when it is one of the file's own. + let key = |at: usize| { + let start = text[..at.min(text.len())].rfind('\n').map_or(0, |end| end + 1); + let (named, _) = text[start..].split_once('=')?; + // A key written in quotes, as TOML allows, is the same key. + let named = named.trim().trim_matches(|c| c == '"' || c == '\''); + KEYS.into_iter().find(|key| *key == named) + }; let written: Written = toml::from_str(&text).map_err(|error| match error.span() { - Some(span) => format!("{}, line {}: {}", path.display(), line(span.start), error.message()), - None => format!("{}: {}", path.display(), error.message()), + Some(span) => unread( + Refused::Unparsed { + line: line(span.start), + key: key(span.start), + }, + format!("{}, line {}: {}", path.display(), line(span.start), error.message()), + ), + None => unread( + Refused::Unparsed { line: 1, key: None }, + format!("{}: {}", path.display(), error.message()), + ), })?; // A path written as people write it: from their home, with a tilde — or from the root. - let whole = |key: &str, what: &str, written: toml::Spanned| { + let whole = |key: &str, what: &str, refused: fn(usize) -> Refused, written: toml::Spanned| { let at = line(written.span().start); let named = from_home(written.into_inner()); if named.is_absolute() { Ok(named) } else { - Err(format!( - "{}, line {at}: {key} is {what} whole path, from the root or from ~", - path.display() + Err(unread( + refused(at), + format!("{}, line {at}: {key} is {what} whole path, from the root or from ~", path.display()), )) } }; @@ -310,18 +387,18 @@ pub fn read(path: &Path) -> Result { toml::Value::String(always) if always == "always" => KeepAudio::Always, toml::Value::Integer(days) if (1..=36_500).contains(days) => KeepAudio::Days(*days as u32), _ => { - return Err(format!( - "{}, line {at}: keep_audio is \"always\" or a number of days", - path.display() + return Err(unread( + Refused::KeepAudio { line: at }, + format!("{}, line {at}: keep_audio is \"always\" or a number of days", path.display()), )); } }; } if let Some(sessions) = written.sessions { - settings.sessions = whole("sessions", "the folder's", sessions)?; + settings.sessions = whole("sessions", "the folder's", |line| Refused::SessionsNotWhole { line }, sessions)?; } if let Some(model) = written.model { - settings.model = whole("model", "the file's", model)?; + settings.model = whole("model", "the file's", |line| Refused::ModelNotWhole { line }, model)?; } Ok(settings) } @@ -345,7 +422,7 @@ pub fn write(path: &Path, settings: &Settings) -> io::Result<()> { let refused = |why: String| io::Error::new(io::ErrorKind::InvalidData, why); // Through a link, the file it points to. let path = &fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); - let before = read(path).map_err(refused)?; + let before = read(path).map_err(|why| refused(why.detail))?; let mut document = match fs::read_to_string(path) { Ok(text) => text.parse::().map_err(|error| refused(error.to_string()))?, Err(error) if error.kind() == io::ErrorKind::NotFound => DocumentMut::new(), @@ -471,3 +548,55 @@ pub fn write(path: &Path, settings: &Settings) -> io::Result<()> { let _ = fs::remove_file(&draft); }) } + +#[cfg(test)] +mod tests { + use super::*; + + /// `KEYS` names each of `Written`'s fields, and nothing else (#813): a setting added to the file + /// is named by a refusal. The pattern lists every field — one added or taken out fails to compile + /// here — and the names compared are the pattern's own. + #[test] + fn the_keys_a_refusal_names_are_the_files_fields() { + macro_rules! fields { + ($($field:ident),* $(,)?) => {{ + #[allow(dead_code)] + fn every(written: Written) { + let Written { $($field: _),* } = written; + } + [$(stringify!($field)),*] + }}; + } + let mut fields = fields!( + reminder, + sessions, + transcript, + after, + model, + engine, + transcription_provider, + transcription_model, + transcription_agreed, + minutes_provider, + minutes_model, + meeting_language, + minutes_agreed, + keep_audio, + developer, + offer, + autostart, + window, + log, + welcomed, + folded, + bar_at, + language, + microphone, + microphone_description, + ); + let mut keys = KEYS; + fields.sort_unstable(); + keys.sort_unstable(); + assert_eq!(keys, fields); + } +} diff --git a/modules/shell/src/words.rs b/modules/shell/src/words.rs index a91f1fdd..6841df61 100644 --- a/modules/shell/src/words.rs +++ b/modules/shell/src/words.rs @@ -4,6 +4,7 @@ use crate::{ recording::{Said, Source}, registry::Good, + settings::Refused, summarising::Cause, transcription::Made, trial::Left, @@ -1670,8 +1671,8 @@ pub fn window(language: Language) -> Window { pub enum Trouble { /// The program that records could not be started: what the system said of it. NoRecorder(String), - /// The settings file was not read: the sentence that says which file, and what in it. - Settings(String), + /// The settings file was not read: which setting, on which line (#783). + Settings(Refused), /// The desktop did not bind the global shortcut: what it said of it. Shortcut(String), /// The model a transcript is heard with is not on the machine: where it was looked for. @@ -1713,8 +1714,10 @@ pub enum Failure { FolderNotWhole, FolderUnmade, Autostart, - SettingsUnread, - SettingsLocked, + /// The settings file refused, which setting and where (#783): under the command it stopped, + /// and, `SettingsLocked`, alone on Settings. + SettingsUnread(Refused), + SettingsLocked(Refused), SettingsUnwritten, FolderNotOpened, KeyboardSettings, @@ -1769,12 +1772,29 @@ pub fn failure(failure: Failure, language: Language) -> String { (Failure::Autostart, French) => { "le démarrage à l’ouverture de session n’a pas pu être changé\u{a0}: vérifiez que votre dossier personnel peut être écrit." } - (Failure::SettingsUnread, English) => "the settings file cannot be read: correct it, then try again.", - (Failure::SettingsUnread, French) => "le fichier des réglages ne peut pas être lu\u{a0}: corrigez-le, puis réessayez.", - (Failure::SettingsLocked, English) => "The settings file cannot be read: Kitokey does not write over it until it is corrected.", - (Failure::SettingsLocked, French) => { - "Le fichier des réglages ne peut pas être lu\u{a0}: Kitokey ne l’écrit pas tant qu’il n’est pas corrigé." + // Shows: under a command the window refused, after « not saved: », then the refusal. + // When: the settings file cannot be read as settings. At most: no limit. Placeholders: {} the refusal. + (Failure::SettingsUnread(why), English) => return format!("the settings file cannot be read. {}", refused(&why, language)), + (Failure::SettingsUnread(why), French) => { + return format!("le fichier des réglages ne peut pas être lu. {}", refused(&why, language)); } + // Shows: alone on Settings, then the refusal. When: the settings file cannot be read. + // At most: no limit. Placeholders: {} the refusal. + (Failure::SettingsLocked(why), English) => { + return format!( + "The settings file cannot be read: Kitokey does not write over it until it is corrected. {}", + refused(&why, language) + ); + } + (Failure::SettingsLocked(why), French) => { + return format!( + "Le fichier des réglages ne peut pas être lu\u{a0}: Kitokey ne l’écrit pas tant qu’il n’est pas corrigé. {}", + refused(&why, language) + ); + } + // Shows: under a command the window refused, after « not saved: », or alone where the page + // shows it (the folder, the keyboard settings). When: the command named by its arm fails. + // At most: no limit. Placeholders: none. (Failure::SettingsUnwritten, English) => "the settings file could not be written: check that the disk has room, then try again.", (Failure::SettingsUnwritten, French) => { "le fichier des réglages n’a pas pu être écrit\u{a0}: vérifiez qu’il reste de la place, puis réessayez." @@ -2052,6 +2072,49 @@ pub fn cause(cause: Cause, language: Language) -> &'static str { } } +/// What the user is told of a settings file refused (#783): which setting, on which line, and the +/// gesture — never `settings.rs`'s own sentence, which stays for the log and developer mode. +pub fn refused(refused: &Refused, language: Language) -> String { + use Language::{English, French}; + // Shows: after the sentence of a notification or a page that says the file was not read. + // When: `settings::read` refuses the file. At most: no limit. Placeholders: {line} the line, + // {key} the setting's name as the file writes it — one of Kitokey's own, never what the user typed. + match (*refused, language) { + (Refused::Unopened, English) => "Kitokey cannot open its settings file: check that you may read it.".into(), + (Refused::Unopened, French) => "Kitokey ne peut pas ouvrir son fichier de réglages\u{a0}: vérifiez que vous pouvez le lire.".into(), + (Refused::Unparsed { line, key: Some(key) }, English) => { + format!("Line {line}: Kitokey does not understand the value of “{key}”. Correct it, or remove the line.") + } + (Refused::Unparsed { line, key: Some(key) }, French) => { + format!("Ligne {line}\u{a0}: Kitokey ne comprend pas la valeur de «\u{a0}{key}\u{a0}». Corrigez-la, ou supprimez la ligne.") + } + (Refused::Unparsed { line, key: None }, English) => { + format!("Line {line} is not written as a setting. Correct it, or remove it.") + } + (Refused::Unparsed { line, key: None }, French) => { + format!("La ligne {line} n’est pas écrite comme un réglage. Corrigez-la, ou supprimez-la.") + } + (Refused::SessionsNotWhole { line }, English) => { + format!("Line {line}: “sessions” gives a folder’s whole path, from / or from ~. Correct it.") + } + (Refused::SessionsNotWhole { line }, French) => { + format!("Ligne {line}\u{a0}: «\u{a0}sessions\u{a0}» donne le chemin entier d’un dossier, depuis / ou depuis ~. Corrigez-le.") + } + (Refused::ModelNotWhole { line }, English) => { + format!("Line {line}: “model” gives a file’s whole path, from / or from ~. Correct it.") + } + (Refused::ModelNotWhole { line }, French) => { + format!("Ligne {line}\u{a0}: «\u{a0}model\u{a0}» donne le chemin entier d’un fichier, depuis / ou depuis ~. Corrigez-le.") + } + (Refused::KeepAudio { line }, English) => { + format!("Line {line}: “keep_audio” is “always” or a number of days, from 1 to 36,500. Correct it.") + } + (Refused::KeepAudio { line }, French) => format!( + "Ligne {line}\u{a0}: «\u{a0}keep_audio\u{a0}» vaut «\u{a0}always\u{a0}» ou un nombre de jours, de 1 à 36\u{202f}500. Corrigez-le." + ), + } +} + /// What the user is told of a trouble: what it is, and what still works. Where the user has /// something to put right — the settings file's line, the place the model goes —, it says where; /// never what a program or the system said (D29). @@ -2067,21 +2130,30 @@ pub fn trouble(trouble: &Trouble, language: Language) -> Notice { "Kitokey ne peut pas enregistrer", "Son programme d’enregistrement n’a pas pu démarrer. Réinstaller Kitokey le remet en place.", ), + // Shows: a notification at a start, its body then the refusal. When: the settings file cannot + // be read. At most: no limit. Placeholders: {} the refusal. (Trouble::Settings(why), English) => { return said( "Your settings were not read", - format!("Kitokey runs with its defaults until the file is corrected: {}.", detail(why)), + format!( + "Kitokey runs with its defaults until the file is corrected. {}", + refused(why, language) + ), ); } (Trouble::Settings(why), French) => { return said( "Vos réglages n’ont pas été lus", format!( - "Kitokey fonctionne avec ses réglages par défaut tant que le fichier n’est pas corrigé\u{a0}: {}.", - detail(why) + "Kitokey fonctionne avec ses réglages par défaut tant que le fichier n’est pas corrigé. {}", + refused(why, language) ), ); } + // Shows: a notification, its title then its body. When: the shortcut is not bound, the model or + // the program that hears is missing, the meetings' folder cannot be written, or no recording is + // there to transcribe. At most: the title, 50 characters; the body, no limit. Placeholders: + // {at} where the model is looked for, or the folder. (Trouble::Shortcut(_), English) => ( "The keyboard shortcut is not set", "The menu of Kitokey’s icon still starts and stops a recording.", diff --git a/modules/shell/tests/log.rs b/modules/shell/tests/log.rs index 304a6fda..1e6d309c 100644 --- a/modules/shell/tests/log.rs +++ b/modules/shell/tests/log.rs @@ -122,10 +122,14 @@ exit 1"#, // A command refused by a settings file broken by hand: `settings::read` names its whole path. let broken = folder.path().join("settings.toml"); fs::write(&broken, "keep_audio = 0\n").unwrap(); - let raw = settings::read(&broken).unwrap_err(); + let refused = settings::read(&broken).unwrap_err(); + let raw = refused.detail.clone(); assert!(raw.contains(&*folder.path().to_string_lossy()), "{raw}"); let unread = "settings.toml, line 1: keep_audio is \"always\" or a number of days"; - assert_eq!(log::command_failed(&Failure::SettingsUnread, &raw, Some(&broken)), unread); + assert_eq!( + log::command_failed(&Failure::SettingsUnread(refused.refused), &raw, Some(&broken)), + unread + ); let text = String::from_utf8(kept.0.lock().unwrap().clone()).unwrap(); let lines: Vec = text.lines().map(|line| serde_json::from_str(line).unwrap()).collect(); @@ -148,7 +152,7 @@ exit 1"#, let refused = lines.iter().find(|line| line["message"] == "shell.command_failed").unwrap(); assert_eq!( (&refused["failure"], &refused["detail"]), - (&"SettingsUnread".into(), &unread.into()), + (&"SettingsUnread(KeepAudio { line: 1 })".into(), &unread.into()), "{text}" ); let recorded = fs::read_to_string(folder.path().join("recording.trace")).unwrap(); diff --git a/modules/shell/tests/settings.rs b/modules/shell/tests/settings.rs index f8a9aef2..79c66dec 100644 --- a/modules/shell/tests/settings.rs +++ b/modules/shell/tests/settings.rs @@ -11,7 +11,7 @@ fn written(text: &str) -> Result { let folder = tempfile::tempdir().unwrap(); let path = folder.path().join("settings.toml"); fs::write(&path, text).unwrap(); - read(&path).map_err(|said| said.replace(&path.display().to_string(), "")) + read(&path).map_err(|unread| unread.detail.replace(&path.display().to_string(), "")) } #[test] @@ -74,7 +74,81 @@ fn a_file_that_is_not_settings_is_said_in_one_sentence_and_not_used() { } // A file that is there and cannot be read is said too, not taken for no file. let folder = tempfile::tempdir().unwrap(); - assert!(read(folder.path()).unwrap_err().contains("cannot be read")); + assert!(read(folder.path()).unwrap_err().detail.contains("cannot be read")); +} + +/// What the user is told of a file refused (#783) is which setting, on which line: the sentence +/// above stays for the log and developer mode. A key is named only when it is one of Kitokey's — +/// never what the user typed in its place. +#[test] +fn a_file_refused_names_the_setting_and_its_line() { + use kitokey_shell::settings::Refused; + let refused = |text: &str| { + let folder = tempfile::tempdir().unwrap(); + let path = folder.path().join("settings.toml"); + fs::write(&path, text).unwrap(); + read(&path).unwrap_err().refused + }; + for (text, expected) in [ + ("keep_audio = 0\n", Refused::KeepAudio { line: 1 }), + ("reminder = false\nkeep_audio = \"never\"\n", Refused::KeepAudio { line: 2 }), + ("reminder = false\nsessions = \"Kitokey\"\n", Refused::SessionsNotWhole { line: 2 }), + ("model = \"ggml.bin\"\n", Refused::ModelNotWhole { line: 1 }), + ( + "# mine\ndeveloper = \"yes\"\n", + Refused::Unparsed { + line: 2, + key: Some("developer"), + }, + ), + ( + "after = \"sometimes\"\n", + Refused::Unparsed { + line: 1, + key: Some("after"), + }, + ), + ( + " bar_at = [1]\n", + Refused::Unparsed { + line: 1, + key: Some("bar_at"), + }, + ), + ( + "reminder = false\nreminder = true\n", + Refused::Unparsed { + line: 2, + key: Some("reminder"), + }, + ), + // A key in quotes, as TOML allows, is named the same (#813). + ( + "\"after\" = \"sometimes\"\n", + Refused::Unparsed { + line: 1, + key: Some("after"), + }, + ), + ( + "'after' = \"sometimes\"\n", + Refused::Unparsed { + line: 1, + key: Some("after"), + }, + ), + ("this is not TOML\n", Refused::Unparsed { line: 1, key: None }), + ("reminder = true\n= 3\n", Refused::Unparsed { line: 2, key: None }), + ( + "# é\r\nreminder = true\r\n\r\n[sessions]\r\nx = 1\r\n", + Refused::Unparsed { line: 4, key: None }, + ), + ("my secret = 3\n", Refused::Unparsed { line: 1, key: None }), + ] { + assert_eq!(refused(text), expected, "{text:?}"); + } + let folder = tempfile::tempdir().unwrap(); + assert_eq!(read(folder.path()).unwrap_err().refused, Refused::Unopened); } #[test] @@ -617,7 +691,7 @@ fn a_failure_of_the_settings_file_names_it_without_its_path_even_through_a_link( let folder = tempfile::tempdir().unwrap(); let file = folder.path().join("settings.toml"); fs::write(&file, "keep_audio = 0\n").unwrap(); - let said = read(&file).unwrap_err(); + let said = read(&file).unwrap_err().detail; assert_eq!( unnamed(&said, &file), "settings.toml, line 1: keep_audio is \"always\" or a number of days" diff --git a/modules/shell/tests/words.rs b/modules/shell/tests/words.rs index c4cde238..f193788d 100644 --- a/modules/shell/tests/words.rs +++ b/modules/shell/tests/words.rs @@ -4,6 +4,7 @@ use std::path::PathBuf; use kitokey_shell::{ recording::{Said, Source}, + settings::Refused, words::{self, Failure, Language, Notice, Refusal}, }; @@ -308,7 +309,10 @@ fn the_menu_and_the_shells_own_troubles_are_said_in_both_languages() { for language in BOTH { for trouble in [ Trouble::NoRecorder(String::new()), - Trouble::Settings("settings.toml, line 3: invalid boolean".into()), + Trouble::Settings(Refused::Unparsed { + line: 3, + key: Some("reminder"), + }), Trouble::Shortcut(String::new()), Trouble::NoModel("/kitokey/models/ggml.bin".into()), Trouble::NoTranscriber(String::new()), @@ -319,8 +323,12 @@ fn the_menu_and_the_shells_own_troubles_are_said_in_both_languages() { "{title} — {body}" ); } - let settings = words::trouble(&Trouble::Settings("settings.toml, line 3: invalid boolean".into()), language).body; - assert!(settings.contains("settings.toml, line 3: invalid boolean"), "{settings}"); + let unparsed = Refused::Unparsed { + line: 3, + key: Some("reminder"), + }; + let settings = words::trouble(&Trouble::Settings(unparsed), language).body; + assert!(settings.ends_with(&words::refused(&unparsed, language)), "{settings}"); let model = words::trouble(&Trouble::NoModel("/kitokey/models/ggml.bin".into()), language).body; assert!(model.contains("/kitokey/models/ggml.bin"), "{model}"); } @@ -328,10 +336,8 @@ fn the_menu_and_the_shells_own_troubles_are_said_in_both_languages() { let body = |trouble, language| words::trouble(&trouble, language).body; assert!(body(Trouble::NoRecorder(String::new()), Language::English).ends_with("Installing Kitokey again puts it back.")); assert!(body(Trouble::NoRecorder(String::new()), Language::French).ends_with("Réinstaller Kitokey le remet en place.")); - assert!(body(Trouble::Settings(String::new()), Language::English).contains("runs with its defaults")); + assert!(body(Trouble::Settings(Refused::Unopened), Language::English).contains("runs with its defaults")); assert!(body(Trouble::Shortcut(String::new()), Language::French).contains("permet toujours de démarrer")); - // What the settings file holds wrong comes out on one line. - assert!(body(Trouble::Settings("line one\n\tline two".into()), Language::English).contains("line one line two")); } #[test] @@ -2011,18 +2017,25 @@ fn the_settings_files_path_stays_out_of_what_a_command_keeps_of_a_failure() { #[test] fn a_settings_file_that_cannot_be_read_is_said_whole_its_raw_text_under_it_only_in_developer_mode() { let raw = "settings.toml, line 1: keep_audio is \"always\" or a number of days"; - let page = |language, developer| serde_json::to_value(words::told(Failure::SettingsLocked, raw, language, developer)).unwrap(); + let locked = Failure::SettingsLocked(Refused::KeepAudio { line: 1 }); + let page = |language, developer| serde_json::to_value(words::told(locked, raw, language, developer)).unwrap(); assert_eq!( page(Language::French, false), - "Le fichier des réglages ne peut pas être lu\u{a0}: Kitokey ne l’écrit pas tant qu’il n’est pas corrigé." + "Le fichier des réglages ne peut pas être lu\u{a0}: Kitokey ne l’écrit pas tant qu’il n’est pas corrigé. \ + Ligne 1\u{a0}: «\u{a0}keep_audio\u{a0}» vaut «\u{a0}always\u{a0}» ou un nombre de jours, de 1 à 36\u{202f}500. Corrigez-le." ); assert_eq!( page(Language::English, false), - "The settings file cannot be read: Kitokey does not write over it until it is corrected." + "The settings file cannot be read: Kitokey does not write over it until it is corrected. \ + Line 1: “keep_audio” is “always” or a number of days, from 1 to 36,500. Correct it." ); assert_eq!( page(Language::English, true), - format!("The settings file cannot be read: Kitokey does not write over it until it is corrected.\n{raw}").as_str() + format!( + "The settings file cannot be read: Kitokey does not write over it until it is corrected. \ + Line 1: “keep_audio” is “always” or a number of days, from 1 to 36,500. Correct it.\n{raw}" + ) + .as_str() ); } @@ -2220,6 +2233,81 @@ fn a_notice_of_minutes_failed_by_the_meetings_own_model_says_what_its_page_says( } } +/// A settings file refused is said in the user's language: which setting, on which line, and what +/// to do — never `settings.rs`'s own sentence, which stays for the log and behind « Développeur » +/// (#783, D94). The window says it under each command it refuses, and the notification at a start. +#[test] +fn a_settings_file_refused_says_which_setting_and_what_to_do_in_both_languages() { + use words::Trouble; + let said = [ + ( + Refused::Unopened, + "Kitokey cannot open its settings file: check that you may read it.", + "Kitokey ne peut pas ouvrir son fichier de réglages\u{a0}: vérifiez que vous pouvez le lire.", + ), + ( + Refused::Unparsed { + line: 4, + key: Some("after"), + }, + "Line 4: Kitokey does not understand the value of “after”. Correct it, or remove the line.", + "Ligne 4\u{a0}: Kitokey ne comprend pas la valeur de «\u{a0}after\u{a0}». Corrigez-la, ou supprimez la ligne.", + ), + ( + Refused::Unparsed { line: 4, key: None }, + "Line 4 is not written as a setting. Correct it, or remove it.", + "La ligne 4 n’est pas écrite comme un réglage. Corrigez-la, ou supprimez-la.", + ), + ( + Refused::SessionsNotWhole { line: 4 }, + "Line 4: “sessions” gives a folder’s whole path, from / or from ~. Correct it.", + "Ligne 4\u{a0}: «\u{a0}sessions\u{a0}» donne le chemin entier d’un dossier, depuis / ou depuis ~. Corrigez-le.", + ), + ( + Refused::ModelNotWhole { line: 4 }, + "Line 4: “model” gives a file’s whole path, from / or from ~. Correct it.", + "Ligne 4\u{a0}: «\u{a0}model\u{a0}» donne le chemin entier d’un fichier, depuis / ou depuis ~. Corrigez-le.", + ), + ( + Refused::KeepAudio { line: 4 }, + "Line 4: “keep_audio” is “always” or a number of days, from 1 to 36,500. Correct it.", + "Ligne 4\u{a0}: «\u{a0}keep_audio\u{a0}» vaut «\u{a0}always\u{a0}» ou un nombre de jours, de 1 à 36\u{202f}500. Corrigez-le.", + ), + ]; + // Each refusal `settings.rs` makes is said: one added fails to compile here until it is named. + for (refused, ..) in &said { + match refused { + Refused::Unopened + | Refused::Unparsed { .. } + | Refused::SessionsNotWhole { .. } + | Refused::ModelNotWhole { .. } + | Refused::KeepAudio { .. } => {} + } + } + let raw = "settings.toml, line 4: keep_audio is \"always\" or a number of days"; + for (refused, english, french) in said { + for (language, sentence) in [(Language::English, english), (Language::French, french)] { + assert_eq!(words::refused(&refused, language), sentence); + // The notification at a start: what still works, then the setting and the gesture. + let Notice { title, body } = words::trouble(&Trouble::Settings(refused), language); + assert!(title.chars().count() <= 50 && body.ends_with(sentence), "{title} — {body}"); + assert!( + body.starts_with(["Kitokey runs with its defaults", "Kitokey fonctionne avec ses réglages par défaut"][language as usize]), + "{body}" + ); + // Under a command the window refused: its sentence, the refusal after it, the raw text + // only in developer mode. + for failure in [Failure::SettingsUnread(refused), Failure::SettingsLocked(refused)] { + let shown = |developer| serde_json::to_value(words::told(failure, raw, language, developer)).unwrap(); + let shown = (shown(false), shown(true)); + assert!(shown.0.as_str().unwrap().ends_with(sentence), "{shown:?}"); + assert!(!shown.0.as_str().unwrap().contains(raw), "{shown:?}"); + assert_eq!(shown.1.as_str().unwrap(), format!("{}\n{raw}", shown.0.as_str().unwrap())); + } + } + } +} + // The voice guide (`docs/voice.md`, D94): a notification's title, read whole as it is sent. /// The titles over 50 characters today, put right with the notifications' sentences (D94): a list @@ -2336,7 +2424,7 @@ fn every_notice(language: Language) -> Vec { } for trouble in [ Trouble::NoRecorder("x".into()), - Trouble::Settings("x".into()), + Trouble::Settings(Refused::Unopened), Trouble::Shortcut("x".into()), Trouble::NoModel("x".into()), Trouble::NoTranscriber("x".into()),