From 124b4d7f7ec907d745e52d56cf50f3ed0f05bf64 Mon Sep 17 00:00:00 2001 From: Carlos Gama <22821064+one-bit@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:42:01 +0000 Subject: [PATCH 1/4] macos: Keep the save dialog's file name extension in step with the selected format The format picker only changed the panel's allowed content types. The name field kept the extension it was given, so the panel refused a name such as `Untitled.psd` once a format that does not allow `psd` was selected. When a format is selected, the name field now changes as follows: - A name without an extension gets the first extension of the format. - A name that still has the extension of the previous format, or of the name given to `set_file_name`, gets the first extension of the format instead, unless that extension is one the format lists. - An extension the user typed is kept, and so is one the format lists. - Nothing changes for a format whose first extension is `*` or empty. The rule is a function of strings, with unit tests. --- CHANGELOG.md | 2 + src/backend/macos/file_dialog.rs | 1 + src/backend/macos/file_dialog/panel_ffi.rs | 49 ++++- src/backend/macos/file_dialog/save_name.rs | 222 +++++++++++++++++++++ 4 files changed, 270 insertions(+), 4 deletions(-) create mode 100644 src/backend/macos/file_dialog/save_name.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 42462f57..63fe5865 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- macOS: a save dialog with a format picker now keeps the extension of the name field in step with the selected format. The format's first extension is added to a name that has none, and replaces the extension of the previous format or of the name given to `set_file_name`. An extension the user typed is kept, and so is one the selected format lists. A format whose first extension is `*` or empty changes nothing. Before, the panel refused a name whose extension the selected format did not allow. + ## 0.18.0 - Fix some GTK3 memory leaks diff --git a/src/backend/macos/file_dialog.rs b/src/backend/macos/file_dialog.rs index c8cd92dc..eeef5afe 100755 --- a/src/backend/macos/file_dialog.rs +++ b/src/backend/macos/file_dialog.rs @@ -3,6 +3,7 @@ use objc2_app_kit::NSModalResponseOK; use std::path::PathBuf; mod panel_ffi; +mod save_name; use self::panel_ffi::Panel; use super::modal_future::ModalFuture; diff --git a/src/backend/macos/file_dialog/panel_ffi.rs b/src/backend/macos/file_dialog/panel_ffi.rs index 4cc249d0..07b5ca96 100755 --- a/src/backend/macos/file_dialog/panel_ffi.rs +++ b/src/backend/macos/file_dialog/panel_ffi.rs @@ -1,4 +1,5 @@ use core::str; +use std::cell::Cell; use std::path::Path; use std::path::PathBuf; @@ -18,6 +19,7 @@ use super::super::{ modal_future::{AsModal, InnerModal}, utils::{FocusManager, PolicyManager}, }; +use super::save_name; use crate::backend::macos::utils::window_from_raw_window_handle; use crate::file_dialog::Filter; use crate::FileDialog; @@ -185,11 +187,16 @@ impl PanelExt for Retained { struct FormatOption { types: Retained>, + extensions: Vec, } struct SavePanelHandlerIvars { panel: Retained, options: Vec, + // The name the panel was opened with, see `FileDialog::set_file_name` + file_name: Option, + // Index in `options` of the selected format + selected: Cell, } define_class!( @@ -208,8 +215,34 @@ define_class!( return; } - if let Some(option) = self.ivars().options.get(idx as usize) { - unsafe { self.ivars().panel.setAllowedContentTypes(&option.types) }; + let ivars = self.ivars(); + let Some(option) = ivars.options.get(idx as usize) else { + return; + }; + let previous = ivars.selected.replace(idx as usize); + + // The name is read before the allowed types change, and set after them, so the panel + // never sees a name whose extension is not allowed. + let name = unsafe { ivars.panel.nameFieldStringValue() }.to_string(); + let previous_extensions = ivars + .options + .get(previous) + .map_or(&[][..], |previous| &previous.extensions); + let renamed = save_name::name_for_format( + &name, + previous_extensions, + ivars.file_name.as_deref(), + &option.extensions, + ); + + unsafe { ivars.panel.setAllowedContentTypes(&option.types) }; + + if let Some(renamed) = renamed { + unsafe { + ivars + .panel + .setNameFieldStringValue(&NSString::from_str(&renamed)) + }; } } } @@ -220,8 +253,14 @@ impl SavePanelHandler { mtm: MainThreadMarker, panel: Retained, options: Vec, + file_name: Option, ) -> Retained { - let this = Self::alloc(mtm).set_ivars(SavePanelHandlerIvars { panel, options }); + let this = Self::alloc(mtm).set_ivars(SavePanelHandlerIvars { + panel, + options, + file_name, + selected: Cell::new(0), + }); unsafe { msg_send![super(this), init] } } } @@ -340,10 +379,12 @@ impl Panel { .iter() .map(|filter| FormatOption { types: utypes_for_filter(filter), + extensions: filter.extensions.clone(), }) .collect(); - let handler = SavePanelHandler::new(mtm, panel.clone(), options); + let handler = + SavePanelHandler::new(mtm, panel.clone(), options, opt.file_name.clone()); unsafe { popup.setTarget(Some(&handler)); diff --git a/src/backend/macos/file_dialog/save_name.rs b/src/backend/macos/file_dialog/save_name.rs new file mode 100644 index 00000000..d0012428 --- /dev/null +++ b/src/backend/macos/file_dialog/save_name.rs @@ -0,0 +1,222 @@ +//! Keeps the extension of a save panel's name in step with the selected format. + +/// The name to show in a save panel once the user has selected another format, or `None` when the +/// name should stay as it is. +/// +/// - `name` is what the name field holds now. +/// - `previous` holds the extensions of the format that was selected until now. +/// - `suggested` is the name the panel was opened with (`FileDialog::set_file_name`). +/// - `selected` holds the extensions of the format that has just been selected. +/// +/// The name gets the first extension of the selected format when it has none, or when it still has +/// the extension of the previous format or of the suggested name, and that extension is not one of +/// the selected format's own. An extension the user typed is kept, and so is any extension the +/// selected format lists, whatever its case. A format whose first extension is `*` or empty accepts +/// any name, so it never changes one. +pub(super) fn name_for_format( + name: &str, + previous: &[String], + suggested: Option<&str>, + selected: &[String], +) -> Option { + let new_ext = selected + .first() + .map(String::as_str) + .filter(|ext| !ext.is_empty() && *ext != "*")?; + if name.trim().is_empty() { + return None; + } + + let Some((stem, ext)) = split_extension(name) else { + // No extension, or only dots at the end + let stem = name.trim_end_matches('.'); + return (!stem.is_empty()).then(|| format!("{stem}.{new_ext}")); + }; + if has_extension(selected, ext) { + return None; + } + let suggested_ext = suggested + .and_then(split_extension) + .map(|(_, suggested_ext)| suggested_ext); + let was_ours = has_extension(previous, ext) + || suggested_ext.is_some_and(|suggested_ext| suggested_ext.eq_ignore_ascii_case(ext)); + was_ours.then(|| format!("{stem}.{new_ext}")) +} + +/// The part of `name` before its extension, and the extension. A leading dot does not start an +/// extension (`.plan` has none), and neither does a dot at the end. +fn split_extension(name: &str) -> Option<(&str, &str)> { + name.rsplit_once('.') + .filter(|(stem, ext)| !stem.is_empty() && !ext.is_empty()) +} + +fn has_extension(extensions: &[String], ext: &str) -> bool { + extensions + .iter() + .any(|candidate| candidate.eq_ignore_ascii_case(ext)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn exts(list: &[&str]) -> Vec { + list.iter().map(|ext| ext.to_string()).collect() + } + + fn renamed( + name: &str, + previous: &[&str], + suggested: Option<&str>, + selected: &[&str], + ) -> Option { + name_for_format(name, &exts(previous), suggested, &exts(selected)) + } + + #[test] + fn the_previous_formats_extension_is_replaced() { + assert_eq!( + renamed("Untitled.psd", &["psd"], None, &["png"]), + Some("Untitled.png".to_string()) + ); + // A name the user changed keeps its stem + assert_eq!( + renamed("Holiday.psd", &["psd"], None, &["tiff"]), + Some("Holiday.tiff".to_string()) + ); + // The case of the old extension does not matter + assert_eq!( + renamed("Holiday.PixMap", &["pixmap"], None, &["tiff"]), + Some("Holiday.tiff".to_string()) + ); + } + + #[test] + fn any_extension_of_the_previous_format_is_replaced() { + assert_eq!( + renamed("Holiday.jpeg", &["jpg", "jpeg"], None, &["png"]), + Some("Holiday.png".to_string()) + ); + } + + #[test] + fn only_the_last_extension_is_replaced() { + assert_eq!( + renamed("archive.tar.psd", &["psd"], None, &["png"]), + Some("archive.tar.png".to_string()) + ); + } + + #[test] + fn the_extension_of_the_suggested_name_is_replaced() { + // The suggested extension is not one the first format lists + assert_eq!( + renamed("cat.psd", &["png"], Some("Untitled.psd"), &["jpg"]), + Some("cat.jpg".to_string()) + ); + assert_eq!( + renamed("cat.PSD", &["png"], Some("Untitled.psd"), &["jpg"]), + Some("cat.jpg".to_string()) + ); + } + + #[test] + fn a_typed_extension_is_kept() { + assert_eq!( + renamed("notes.txt", &["psd"], Some("Untitled.psd"), &["png"]), + None + ); + // Without a suggested name there is nothing to tell a typed extension from + assert_eq!(renamed("notes.txt", &["psd"], None, &["png"]), None); + } + + #[test] + fn an_extension_the_selected_format_lists_is_kept() { + assert_eq!( + renamed( + "Holiday.tiff", + &["psd"], + Some("Holiday.tiff"), + &["tiff", "tif"] + ), + None + ); + assert_eq!( + renamed("Holiday.tif", &["psd"], None, &["tiff", "tif"]), + None + ); + assert_eq!( + renamed("Holiday.TIF", &["psd"], None, &["tiff", "tif"]), + None + ); + } + + #[test] + fn a_missing_extension_is_added() { + assert_eq!( + renamed("Untitled", &["psd"], Some("Untitled.psd"), &["tiff", "tif"]), + Some("Untitled.tiff".to_string()) + ); + assert_eq!( + renamed("Untitled", &["psd"], None, &["png"]), + Some("Untitled.png".to_string()) + ); + // A hidden file's leading dot does not start an extension + assert_eq!( + renamed(".notes", &["psd"], None, &["png"]), + Some(".notes.png".to_string()) + ); + // A dot with nothing after it is not an extension either + assert_eq!( + renamed("Untitled.", &["psd"], None, &["png"]), + Some("Untitled.png".to_string()) + ); + } + + #[test] + fn a_format_without_an_extension_changes_nothing() { + for any in [&["*"][..], &[""][..], &[][..]] { + assert_eq!( + renamed("Untitled.psd", &["psd"], Some("Untitled.psd"), any), + None + ); + assert_eq!(renamed("Untitled", &["psd"], None, any), None); + } + // Only the first extension decides + assert_eq!(renamed("Untitled", &["psd"], None, &["*", "png"]), None); + } + + #[test] + fn an_empty_name_stays_empty() { + assert_eq!(renamed("", &["psd"], None, &["png"]), None); + assert_eq!(renamed(" ", &["psd"], None, &["png"]), None); + assert_eq!(renamed("..", &["psd"], None, &["png"]), None); + } + + #[test] + fn a_name_follows_a_series_of_formats() { + let formats = [ + exts(&["psd", "psb"]), + exts(&["png"]), + exts(&["tiff", "tif"]), + exts(&["psd", "psb"]), + ]; + let mut name = "Untitled.psd".to_string(); + for pair in formats.windows(2) { + if let Some(next) = name_for_format(&name, &pair[0], Some("Untitled.psd"), &pair[1]) { + name = next; + } + } + assert_eq!(name, "Untitled.psd"); + + // A format that accepts any name leaves the extension, and the next format replaces it + let mut name = "Untitled.png".to_string(); + assert_eq!( + name_for_format(&name, &exts(&["png"]), None, &exts(&["*"])), + None + ); + name = name_for_format(&name, &exts(&["*"]), Some("Untitled.png"), &exts(&["tiff"])) + .unwrap_or(name); + assert_eq!(name, "Untitled.tiff"); + } +} From 2703d475b119f092187e16efb979eb17d44fb9f7 Mon Sep 17 00:00:00 2001 From: Carlos Gama <22821064+one-bit@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:11:40 +0000 Subject: [PATCH 2/4] macos: Leave the panel to accept any name for a format whose types prefer another extension The save panel changes the extension of the name it returns to the preferred extension of the allowed type. Which type an extension resolves to depends on the applications that are installed: one may declare a type that lists an extension among its tags and prefers another. The panel then returned `name.other` for the name `name.ext` that the format picker had just set. A format is now exact when, for each of its extensions, the system has a type whose preferred extension is that extension (any case). The panel is given the types of an exact format, as before. For any other format, including one that lists `*` or an empty extension, the panel is given no types and `allowsOtherFileTypes` is set, so it returns the name as it is. The original value is restored when an exact format is selected again. The panel no longer adds an extension for such a format, so a returned name without one gets the first extension of the selected format, unless that name is another file's: the panel only asked about overwriting the one it returned. The decision and the added extension are functions of strings, with unit tests. A format picker with a single format goes through the same code. --- CHANGELOG.md | 2 +- src/backend/macos/file_dialog.rs | 4 +- src/backend/macos/file_dialog/panel_ffi.rs | 147 +++++++++++++++++---- src/backend/macos/file_dialog/save_name.rs | 128 ++++++++++++++++++ 4 files changed, 253 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 63fe5865..5dc4a814 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- macOS: a save dialog with a format picker now keeps the extension of the name field in step with the selected format. The format's first extension is added to a name that has none, and replaces the extension of the previous format or of the name given to `set_file_name`. An extension the user typed is kept, and so is one the selected format lists. A format whose first extension is `*` or empty changes nothing. Before, the panel refused a name whose extension the selected format did not allow. +- macOS: a save dialog with a format picker now keeps the extension of the name field in step with the selected format. The format's first extension is added to a name that has none, and replaces the extension of the previous format or of the name given to `set_file_name`. An extension the user typed is kept, and so is one the selected format lists. A format whose first extension is `*` or empty changes nothing. Before, the panel refused a name whose extension the selected format did not allow. A format with an extension for which the system has no type, or a type that prefers another extension (an installed application can declare one), is no longer given to the panel as its allowed types, which would change the extension of the name to the preferred one when saving: the panel accepts any name then, and the format's first extension is added to a returned name that has none. ## 0.18.0 diff --git a/src/backend/macos/file_dialog.rs b/src/backend/macos/file_dialog.rs index eeef5afe..435d43ef 100755 --- a/src/backend/macos/file_dialog.rs +++ b/src/backend/macos/file_dialog.rs @@ -258,7 +258,7 @@ impl FileSaveDialogImpl for FileDialog { run_on_main(move |mtm| { let panel = Panel::build_save_file(&self, mtm); if panel.run_modal() == NSModalResponseOK { - Some(panel.get_result()) + Some(panel.get_save_result()) } else { None } @@ -277,7 +277,7 @@ impl AsyncFileSaveDialogImpl for FileDialog { move |mtm| Panel::build_save_file(&self, mtm), |panel, res_id| { if res_id == NSModalResponseOK { - Some(panel.get_result().into()) + Some(panel.get_save_result().into()) } else { None } diff --git a/src/backend/macos/file_dialog/panel_ffi.rs b/src/backend/macos/file_dialog/panel_ffi.rs index 07b5ca96..a507e25c 100755 --- a/src/backend/macos/file_dialog/panel_ffi.rs +++ b/src/backend/macos/file_dialog/panel_ffi.rs @@ -95,6 +95,15 @@ impl Panel { } } + /// The file a save panel chose, with the extension of the selected format. + pub fn get_save_result(&self) -> PathBuf { + let path = self.get_result(); + match &self._save_panel_handler { + Some(handler) => handler.path_with_format_extension(path), + None => path, + } + } + pub fn get_results(&self) -> Vec { unsafe { let urls = self.as_open_panel().unwrap().URLs(); @@ -188,6 +197,41 @@ impl PanelExt for Retained { struct FormatOption { types: Retained>, extensions: Vec, + // Whether the panel can be given `types`, see `save_name::format_is_exact`. When it can't, the + // panel would change the extension of the name to the one its type prefers, so it is left to + // accept any name. + exact: bool, +} + +impl FormatOption { + fn new(filter: &Filter) -> Self { + let exact = save_name::format_is_exact(&filter.extensions, |ext| { + let preferred = unsafe { utype_for_extension(ext)?.preferredFilenameExtension() }; + preferred.map(|preferred| preferred.to_string()) + }); + Self { + types: utypes_for_filter(filter), + extensions: filter.extensions.clone(), + exact, + } + } +} + +/// Gives the panel what the format needs: its types when it is exact, and when it is not, every +/// type, with other file types allowed. `allows_other_file_types` is the panel's own setting. +fn apply_format(panel: &NSSavePanel, option: &FormatOption, allows_other_file_types: bool) { + if option.exact { + unsafe { + panel.setAllowedContentTypes(&option.types); + panel.setAllowsOtherFileTypes(allows_other_file_types); + } + } else { + let any: Vec> = Vec::new(); + unsafe { + panel.setAllowedContentTypes(&NSArray::from_retained_slice(&any)); + panel.setAllowsOtherFileTypes(true); + } + } } struct SavePanelHandlerIvars { @@ -197,6 +241,8 @@ struct SavePanelHandlerIvars { file_name: Option, // Index in `options` of the selected format selected: Cell, + // What `allowsOtherFileTypes` was before a format changed it + allows_other_file_types: bool, } define_class!( @@ -235,7 +281,7 @@ define_class!( &option.extensions, ); - unsafe { ivars.panel.setAllowedContentTypes(&option.types) }; + apply_format(&ivars.panel, option, ivars.allows_other_file_types); if let Some(renamed) = renamed { unsafe { @@ -255,14 +301,47 @@ impl SavePanelHandler { options: Vec, file_name: Option, ) -> Retained { + let allows_other_file_types = unsafe { panel.allowsOtherFileTypes() }; let this = Self::alloc(mtm).set_ivars(SavePanelHandlerIvars { panel, options, file_name, selected: Cell::new(0), + allows_other_file_types, }); unsafe { msg_send![super(this), init] } } + + /// Gives the panel what the first format needs, the one that is selected when it opens. + fn apply_first_format(&self) { + let ivars = self.ivars(); + if let Some(first) = ivars.options.first() { + apply_format(&ivars.panel, first, ivars.allows_other_file_types); + } + } + + /// `path`, a name the panel returned, with the first extension of the selected format when the + /// format is not exact and the name has none. The panel returns the name as it was typed then. + /// A name that would be another file's is left as the panel returned it, since the panel only + /// asked about overwriting that one. + fn path_with_format_extension(&self, path: PathBuf) -> PathBuf { + let ivars = self.ivars(); + let Some(option) = ivars.options.get(ivars.selected.get()) else { + return path; + }; + if option.exact { + return path; + } + let renamed = path + .file_name() + .and_then(|name| name.to_str()) + .and_then(|name| save_name::name_with_format_extension(name, &option.extensions)) + .map(|name| path.with_file_name(name)); + match renamed { + Some(renamed) if !renamed.exists() => renamed, + _ => path, + } + } } fn build_format_accessory_view( @@ -367,34 +446,25 @@ impl Panel { let save_panel_handler = match opt.filters.as_slice() { [] => None, - [single] => { - unsafe { panel.setAllowedContentTypes(&utypes_for_filter(single)) }; - None - } - multiple => { - let label_text = opt.format_label.as_deref().unwrap_or("Format:"); - let (view, popup) = build_format_accessory_view(mtm, multiple, label_text); - - let options = multiple - .iter() - .map(|filter| FormatOption { - types: utypes_for_filter(filter), - extensions: filter.extensions.clone(), - }) - .collect(); - + filters => { + let options = filters.iter().map(FormatOption::new).collect(); let handler = SavePanelHandler::new(mtm, panel.clone(), options, opt.file_name.clone()); + handler.apply_first_format(); - unsafe { - popup.setTarget(Some(&handler)); - popup.setAction(Some(sel!(formatChanged:))); - } + if filters.len() > 1 { + let label_text = opt.format_label.as_deref().unwrap_or("Format:"); + let (view, popup) = build_format_accessory_view(mtm, filters, label_text); - unsafe { - panel.setAllowedContentTypes(&utypes_for_filter(&multiple[0])); - popup.selectItemAtIndex(0); - panel.setAccessoryView(Some(&view)); + unsafe { + popup.setTarget(Some(&handler)); + popup.setAction(Some(sel!(formatChanged:))); + } + + unsafe { + popup.selectItemAtIndex(0); + panel.setAccessoryView(Some(&view)); + } } Some(handler) @@ -563,3 +633,30 @@ impl Panel { Self::new(Retained::into_super(panel), opt.parent.as_ref()) } } + +#[cfg(test)] +mod tests { + use super::*; + + fn exact(extensions: &[&str]) -> bool { + FormatOption::new(&Filter { + name: "Format".to_string(), + extensions: extensions.iter().map(|ext| ext.to_string()).collect(), + }) + .exact + } + + /// The types the system itself declares for these extensions prefer them. + #[test] + fn formats_of_the_systems_own_types_are_exact() { + assert!(exact(&["png"])); + assert!(exact(&["pdf"])); + } + + #[test] + fn a_format_that_accepts_any_name_is_not_exact() { + assert!(!exact(&["*"])); + assert!(!exact(&[""])); + assert!(!exact(&[])); + } +} diff --git a/src/backend/macos/file_dialog/save_name.rs b/src/backend/macos/file_dialog/save_name.rs index d0012428..6d08a893 100644 --- a/src/backend/macos/file_dialog/save_name.rs +++ b/src/backend/macos/file_dialog/save_name.rs @@ -43,6 +43,38 @@ pub(super) fn name_for_format( was_ours.then(|| format!("{stem}.{new_ext}")) } +/// Whether the panel can be given the types of a format, for it to name the file by them. +/// +/// The panel changes the extension of the name it returns to the preferred extension of the +/// allowed type, and which type an extension resolves to depends on the applications that are +/// installed: an application may declare a type that lists the extension among its tags and +/// prefers another. A format is exact when, for each of its extensions, `preferred` (the preferred +/// extension of the type the system gives for it, if there is one) is that extension, whatever its +/// case. For any other format the panel must be left to accept every name, and the extension is +/// kept by [`name_for_format`] and [`name_with_format_extension`] alone. +/// +/// A format with no extension, and one that lists `*` or an empty extension, accepts any name and +/// is never exact. +pub(super) fn format_is_exact( + extensions: &[String], + preferred: impl Fn(&str) -> Option, +) -> bool { + let names_extensions = + !extensions.is_empty() && extensions.iter().all(|ext| !ext.is_empty() && ext != "*"); + names_extensions + && extensions + .iter() + .all(|ext| preferred(ext).is_some_and(|preferred| preferred.eq_ignore_ascii_case(ext))) +} + +/// The name a save panel returned, with the first extension of the selected format when it has no +/// extension, or `None` when it should stay as it is. +/// +/// This is for a format that is not exact, whose panel returns the name as it was typed. +pub(super) fn name_with_format_extension(name: &str, selected: &[String]) -> Option { + name_for_format(name, &[], None, selected) +} + /// The part of `name` before its extension, and the extension. A leading dot does not start an /// extension (`.plan` has none), and neither does a dot at the end. fn split_extension(name: &str) -> Option<(&str, &str)> { @@ -219,4 +251,100 @@ mod tests { .unwrap_or(name); assert_eq!(name, "Untitled.tiff"); } + + /// What the system gives for made-up extensions: `plain` and `simple` have types that prefer + /// themselves, `fancy` has one that prefers `fz`, `shouty` one that prefers `SHOUTY`, and + /// `ghost` has none. + fn preferred(ext: &str) -> Option { + match ext.to_ascii_lowercase().as_str() { + "plain" | "simple" => Some(ext.to_ascii_lowercase()), + "fancy" => Some("fz".to_string()), + "shouty" => Some("SHOUTY".to_string()), + _ => None, + } + } + + fn exact(list: &[&str]) -> bool { + format_is_exact(&exts(list), preferred) + } + + #[test] + fn a_format_whose_types_prefer_its_extensions_is_exact() { + assert!(exact(&["plain"])); + assert!(exact(&["plain", "simple"])); + // The case of either side does not matter + assert!(exact(&["PLAIN"])); + assert!(exact(&["shouty"])); + } + + #[test] + fn a_format_with_an_extension_whose_type_prefers_another_is_not_exact() { + assert!(!exact(&["fancy"])); + // Any of the extensions can be the one + assert!(!exact(&["plain", "fancy"])); + assert!(!exact(&["fancy", "plain"])); + } + + #[test] + fn a_format_with_an_extension_that_has_no_type_is_not_exact() { + assert!(!exact(&["ghost"])); + assert!(!exact(&["plain", "ghost"])); + } + + #[test] + fn a_format_that_accepts_any_name_is_not_exact_and_asks_nothing() { + let asked = std::cell::Cell::new(0); + let lookup = |_: &str| { + asked.set(asked.get() + 1); + Some("plain".to_string()) + }; + for any in [ + &[][..], + &["*"][..], + &[""][..], + &["*", "plain"][..], + &["plain", ""][..], + ] { + assert!(!format_is_exact(&exts(any), lookup), "{any:?}"); + } + assert_eq!(asked.get(), 0); + } + + #[test] + fn a_returned_name_with_no_extension_gets_the_first_extension() { + let named = + |name: &str, selected: &[&str]| name_with_format_extension(name, &exts(selected)); + assert_eq!( + named("Untitled", &["fancy", "fz"]), + Some("Untitled.fancy".to_string()) + ); + assert_eq!( + named("Untitled.", &["fancy"]), + Some("Untitled.fancy".to_string()) + ); + assert_eq!( + named(".notes", &["fancy"]), + Some(".notes.fancy".to_string()) + ); + } + + #[test] + fn a_returned_name_with_an_extension_stays() { + let named = + |name: &str, selected: &[&str]| name_with_format_extension(name, &exts(selected)); + assert_eq!(named("Untitled.fancy", &["fancy"]), None); + assert_eq!(named("Untitled.FZ", &["fancy", "fz"]), None); + // An extension the person typed is theirs, even when the format does not list it + assert_eq!(named("Untitled.txt", &["fancy"]), None); + } + + #[test] + fn a_returned_name_is_left_alone_by_a_format_that_accepts_any_name() { + let named = + |name: &str, selected: &[&str]| name_with_format_extension(name, &exts(selected)); + assert_eq!(named("Untitled", &["*"]), None); + assert_eq!(named("Untitled", &[""]), None); + assert_eq!(named("Untitled", &[]), None); + assert_eq!(named("", &["fancy"]), None); + } } From 8f90a19d8d9441057904bdacbaea4e946fdbfede Mon Sep 17 00:00:00 2001 From: Carlos Gama <22821064+one-bit@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:35:20 +0000 Subject: [PATCH 3/4] macos: Show the extension for a format the panel is not given types for When the panel hides the extension of the name, it takes the type of the name from the extension in the name field and returns the preferred extension of that type. The extension that the format picker had just set could still come back changed, such as `name.ext` as `name.other`, when an installed application declares a type for `ext` that prefers `other`, whatever types the panel was allowed. For a format that is not exact, the panel now also shows the extension. The hide-extension setting is recorded with the other settings when the handler is built, and restored when an exact format is selected again. As a safety net, when the selected format is not exact and the name the panel returned does not end in an extension the format lists, while the name field does and both are names of the same file, the name field's name is returned (unless that file exists, as for the other additions). That decision is a function of strings, with unit tests. --- CHANGELOG.md | 2 +- src/backend/macos/file_dialog/panel_ffi.rs | 61 +++++++---- src/backend/macos/file_dialog/save_name.rs | 113 +++++++++++++++++++++ 3 files changed, 158 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5dc4a814..2baaa3fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- macOS: a save dialog with a format picker now keeps the extension of the name field in step with the selected format. The format's first extension is added to a name that has none, and replaces the extension of the previous format or of the name given to `set_file_name`. An extension the user typed is kept, and so is one the selected format lists. A format whose first extension is `*` or empty changes nothing. Before, the panel refused a name whose extension the selected format did not allow. A format with an extension for which the system has no type, or a type that prefers another extension (an installed application can declare one), is no longer given to the panel as its allowed types, which would change the extension of the name to the preferred one when saving: the panel accepts any name then, and the format's first extension is added to a returned name that has none. +- macOS: a save dialog with a format picker now keeps the extension of the name field in step with the selected format. The format's first extension is added to a name that has none, and replaces the extension of the previous format or of the name given to `set_file_name`. An extension the user typed is kept, and so is one the selected format lists. A format whose first extension is `*` or empty changes nothing. Before, the panel refused a name whose extension the selected format did not allow. A format with an extension for which the system has no type, or a type that prefers another extension (an installed application can declare one), is no longer given to the panel as its allowed types, which would change the extension of the name to the preferred one when saving: the panel accepts any name then, and the format's first extension is added to a returned name that has none. The panel shows the extension for such a format: a panel that hides it takes the type of the name from the extension in the name field, and returns that type's preferred extension, whatever types it is allowed (the hide-extension setting is restored when an exact format is selected again). If the panel returns another extension anyway, the name field's is used when the format lists it. ## 0.18.0 diff --git a/src/backend/macos/file_dialog/panel_ffi.rs b/src/backend/macos/file_dialog/panel_ffi.rs index a507e25c..d289e8b8 100755 --- a/src/backend/macos/file_dialog/panel_ffi.rs +++ b/src/backend/macos/file_dialog/panel_ffi.rs @@ -99,7 +99,10 @@ impl Panel { pub fn get_save_result(&self) -> PathBuf { let path = self.get_result(); match &self._save_panel_handler { - Some(handler) => handler.path_with_format_extension(path), + Some(handler) => { + let name_field = unsafe { self.panel.nameFieldStringValue() }.to_string(); + handler.path_with_format_extension(path, &name_field) + } None => path, } } @@ -217,19 +220,42 @@ impl FormatOption { } } -/// Gives the panel what the format needs: its types when it is exact, and when it is not, every -/// type, with other file types allowed. `allows_other_file_types` is the panel's own setting. -fn apply_format(panel: &NSSavePanel, option: &FormatOption, allows_other_file_types: bool) { +/// What the panel's own settings were before a format changed them. +#[derive(Clone, Copy)] +struct PanelSettings { + allows_other_file_types: bool, + extension_hidden: bool, +} + +impl PanelSettings { + fn of(panel: &NSSavePanel) -> Self { + unsafe { + Self { + allows_other_file_types: panel.allowsOtherFileTypes(), + extension_hidden: panel.isExtensionHidden(), + } + } + } +} + +/// Gives the panel what the format needs: its types when it is exact, and its own settings +/// (`original`). When it is not exact, every type, with other file types allowed, and the +/// extension shown: a panel that hides the extension takes the type of the name from the +/// extension in the name field, and returns the preferred extension of that type, whatever types +/// it is allowed. +fn apply_format(panel: &NSSavePanel, option: &FormatOption, original: PanelSettings) { if option.exact { unsafe { panel.setAllowedContentTypes(&option.types); - panel.setAllowsOtherFileTypes(allows_other_file_types); + panel.setAllowsOtherFileTypes(original.allows_other_file_types); + panel.setExtensionHidden(original.extension_hidden); } } else { let any: Vec> = Vec::new(); unsafe { panel.setAllowedContentTypes(&NSArray::from_retained_slice(&any)); panel.setAllowsOtherFileTypes(true); + panel.setExtensionHidden(false); } } } @@ -241,8 +267,8 @@ struct SavePanelHandlerIvars { file_name: Option, // Index in `options` of the selected format selected: Cell, - // What `allowsOtherFileTypes` was before a format changed it - allows_other_file_types: bool, + // What the panel's settings were before a format changed them + original: PanelSettings, } define_class!( @@ -281,7 +307,7 @@ define_class!( &option.extensions, ); - apply_format(&ivars.panel, option, ivars.allows_other_file_types); + apply_format(&ivars.panel, option, ivars.original); if let Some(renamed) = renamed { unsafe { @@ -301,13 +327,13 @@ impl SavePanelHandler { options: Vec, file_name: Option, ) -> Retained { - let allows_other_file_types = unsafe { panel.allowsOtherFileTypes() }; + let original = PanelSettings::of(&panel); let this = Self::alloc(mtm).set_ivars(SavePanelHandlerIvars { panel, options, file_name, selected: Cell::new(0), - allows_other_file_types, + original, }); unsafe { msg_send![super(this), init] } } @@ -316,15 +342,16 @@ impl SavePanelHandler { fn apply_first_format(&self) { let ivars = self.ivars(); if let Some(first) = ivars.options.first() { - apply_format(&ivars.panel, first, ivars.allows_other_file_types); + apply_format(&ivars.panel, first, ivars.original); } } - /// `path`, a name the panel returned, with the first extension of the selected format when the - /// format is not exact and the name has none. The panel returns the name as it was typed then. - /// A name that would be another file's is left as the panel returned it, since the panel only - /// asked about overwriting that one. - fn path_with_format_extension(&self, path: PathBuf) -> PathBuf { + /// `path`, the file the panel returned, with the name `save_name::returned_name` gives for it + /// when the selected format is not exact: the panel may not have kept the extension of the + /// name field, or the name has none. `name_field` is what the name field holds. A name that + /// would be another file's is left as the panel returned it, since the panel only asked about + /// overwriting that one. + fn path_with_format_extension(&self, path: PathBuf, name_field: &str) -> PathBuf { let ivars = self.ivars(); let Some(option) = ivars.options.get(ivars.selected.get()) else { return path; @@ -335,7 +362,7 @@ impl SavePanelHandler { let renamed = path .file_name() .and_then(|name| name.to_str()) - .and_then(|name| save_name::name_with_format_extension(name, &option.extensions)) + .and_then(|name| save_name::returned_name(name, name_field, &option.extensions)) .map(|name| path.with_file_name(name)); match renamed { Some(renamed) if !renamed.exists() => renamed, diff --git a/src/backend/macos/file_dialog/save_name.rs b/src/backend/macos/file_dialog/save_name.rs index 6d08a893..20779f5a 100644 --- a/src/backend/macos/file_dialog/save_name.rs +++ b/src/backend/macos/file_dialog/save_name.rs @@ -75,6 +75,39 @@ pub(super) fn name_with_format_extension(name: &str, selected: &[String]) -> Opt name_for_format(name, &[], None, selected) } +/// The name to return for a save panel that returned `raw`, or `None` when `raw` should stay. +/// +/// - `raw` is the name of the file the panel returned. +/// - `field` is what the panel's name field holds. +/// - `selected` holds the extensions of the selected format. +/// +/// This is for a format that is not exact. The panel may still return an extension of its own for +/// the one in the name field (it does when it hides the extension: it takes the name's type +/// from the extension, and the type may prefer another), so `field` is returned when `raw` does not +/// end in an extension the format lists, `field` does, and both are names of the same file. Else a +/// `raw` with no extension gets the first extension of the format, see +/// [`name_with_format_extension`]. An extension the person typed is kept. +pub(super) fn returned_name(raw: &str, field: &str, selected: &[String]) -> Option { + let lists = |name: &str| { + split_extension(name).is_some_and(|(_, extension)| has_extension(selected, extension)) + }; + let usable = selected + .first() + .is_some_and(|ext| !ext.is_empty() && ext != "*"); + if !usable || lists(raw) { + return None; + } + if lists(field) && stem(raw) == stem(field) { + return Some(field.to_string()); + } + name_with_format_extension(raw, selected) +} + +/// The part of `name` before its extension, or the whole name when it has none. +fn stem(name: &str) -> &str { + split_extension(name).map_or_else(|| name.trim_end_matches('.'), |(stem, _)| stem) +} + /// The part of `name` before its extension, and the extension. A leading dot does not start an /// extension (`.plan` has none), and neither does a dot at the end. fn split_extension(name: &str) -> Option<(&str, &str)> { @@ -347,4 +380,84 @@ mod tests { assert_eq!(named("Untitled", &[]), None); assert_eq!(named("", &["fancy"]), None); } + + #[test] + fn the_name_field_is_returned_when_the_panel_changed_its_extension() { + let returned = |raw: &str, field: &str| returned_name(raw, field, &exts(&["fancy", "fz"])); + assert_eq!( + returned("Untitled.other", "Untitled.fancy"), + Some("Untitled.fancy".to_string()) + ); + // Any extension the format lists, whatever its case + assert_eq!( + returned("Untitled.OTHER", "Untitled.FZ"), + Some("Untitled.FZ".to_string()) + ); + assert_eq!( + returned("a.b.other", "a.b.fancy"), + Some("a.b.fancy".to_string()) + ); + // A panel that took the extension away + assert_eq!( + returned("Untitled", "Untitled.fz"), + Some("Untitled.fz".to_string()) + ); + assert_eq!( + returned(".notes", ".notes.fancy"), + Some(".notes.fancy".to_string()) + ); + } + + #[test] + fn a_returned_name_that_has_an_extension_the_format_lists_stays() { + let returned = |raw: &str, field: &str| returned_name(raw, field, &exts(&["fancy", "fz"])); + assert_eq!(returned("Untitled.fancy", "Untitled.fancy"), None); + assert_eq!(returned("Untitled.FZ", "Untitled.fancy"), None); + assert_eq!(returned("Untitled.fz", ""), None); + } + + #[test] + fn a_name_field_that_is_not_the_returned_file_is_not_used() { + let returned = |raw: &str, field: &str| returned_name(raw, field, &exts(&["fancy"])); + // Another stem + assert_eq!(returned("Holiday.other", "Untitled.fancy"), None); + // An extension the format does not list + assert_eq!(returned("Untitled.other", "Untitled.txt"), None); + assert_eq!(returned("Untitled.other", "Untitled"), None); + assert_eq!(returned("Untitled.other", ""), None); + } + + #[test] + fn a_typed_extension_stays_when_the_name_field_has_it_too() { + let returned = |raw: &str, field: &str| returned_name(raw, field, &exts(&["fancy"])); + assert_eq!(returned("Untitled.txt", "Untitled.txt"), None); + } + + #[test] + fn a_returned_name_with_no_extension_gets_the_first_extension_when_the_name_field_has_none() { + let returned = |raw: &str, field: &str| returned_name(raw, field, &exts(&["fancy", "fz"])); + assert_eq!( + returned("Untitled", "Untitled"), + Some("Untitled.fancy".to_string()) + ); + assert_eq!(returned("Untitled", ""), Some("Untitled.fancy".to_string())); + assert_eq!( + returned("Untitled", "Holiday.txt"), + Some("Untitled.fancy".to_string()) + ); + } + + #[test] + fn a_format_that_accepts_any_name_never_changes_a_returned_name() { + for any in [&[][..], &["*"][..], &[""][..]] { + assert_eq!( + returned_name("Untitled", "Untitled.fancy", &exts(any)), + None + ); + assert_eq!( + returned_name("Untitled.other", "Untitled.fancy", &exts(any)), + None + ); + } + } } From 4137f254f8ea858c58c543fef6ee0c7da9b054ea Mon Sep 17 00:00:00 2001 From: Carlos Gama <22821064+one-bit@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:46:33 +0000 Subject: [PATCH 4/4] macos: Ask before replacing the file a corrected save name gives The panel asks about replacing the file it returned. When the name it returned is corrected (the format's extension added to a name that has none, or the name field's extension used for one the panel changed), the file that gets the corrected name was never asked about, and a save would write over it. When the corrected path exists, show the same question as the panel, with Cancel as the default button, after the panel has closed. Replace returns the corrected path, and Cancel makes the save return `None`, as if the person had cancelled. The sync and the async save paths both get this from `get_save_result`. What to do is a function of the panel's path, the corrected path and whether a file has it, with three outcomes: the panel's path, the corrected path, or ask. The words of the question are a function of the path. Both have unit tests. --- CHANGELOG.md | 2 +- src/backend/macos/file_dialog.rs | 4 +- src/backend/macos/file_dialog/panel_ffi.rs | 65 ++++++--- src/backend/macos/file_dialog/save_name.rs | 149 +++++++++++++++++++++ 4 files changed, 195 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2baaa3fc..acf3406c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- macOS: a save dialog with a format picker now keeps the extension of the name field in step with the selected format. The format's first extension is added to a name that has none, and replaces the extension of the previous format or of the name given to `set_file_name`. An extension the user typed is kept, and so is one the selected format lists. A format whose first extension is `*` or empty changes nothing. Before, the panel refused a name whose extension the selected format did not allow. A format with an extension for which the system has no type, or a type that prefers another extension (an installed application can declare one), is no longer given to the panel as its allowed types, which would change the extension of the name to the preferred one when saving: the panel accepts any name then, and the format's first extension is added to a returned name that has none. The panel shows the extension for such a format: a panel that hides it takes the type of the name from the extension in the name field, and returns that type's preferred extension, whatever types it is allowed (the hide-extension setting is restored when an exact format is selected again). If the panel returns another extension anyway, the name field's is used when the format lists it. +- macOS: a save dialog with a format picker now keeps the extension of the name field in step with the selected format. The format's first extension is added to a name that has none, and replaces the extension of the previous format or of the name given to `set_file_name`. An extension the user typed is kept, and so is one the selected format lists. A format whose first extension is `*` or empty changes nothing. Before, the panel refused a name whose extension the selected format did not allow. A format with an extension for which the system has no type, or a type that prefers another extension (an installed application can declare one), is no longer given to the panel as its allowed types, which would change the extension of the name to the preferred one when saving: the panel accepts any name then and shows the extension (the original settings are restored when an exact format is selected again), and the format's first extension is added to a returned name that has none. The panel can still return the preferred extension of such a type with the extension shown (measured on macOS 26.5 with an application that declares one), so when the name it returned does not end in an extension the format lists and its name field does, the name field's name is used. When a file has the name that is used instead of the one the panel asked about, the person is asked whether to replace it, with Cancel the default, and Cancel makes the save return `None`, as if the person had cancelled. ## 0.18.0 diff --git a/src/backend/macos/file_dialog.rs b/src/backend/macos/file_dialog.rs index 435d43ef..e8474a96 100755 --- a/src/backend/macos/file_dialog.rs +++ b/src/backend/macos/file_dialog.rs @@ -258,7 +258,7 @@ impl FileSaveDialogImpl for FileDialog { run_on_main(move |mtm| { let panel = Panel::build_save_file(&self, mtm); if panel.run_modal() == NSModalResponseOK { - Some(panel.get_save_result()) + panel.get_save_result() } else { None } @@ -277,7 +277,7 @@ impl AsyncFileSaveDialogImpl for FileDialog { move |mtm| Panel::build_save_file(&self, mtm), |panel, res_id| { if res_id == NSModalResponseOK { - Some(panel.get_save_result().into()) + panel.get_save_result().map(FileHandle::wrap) } else { None } diff --git a/src/backend/macos/file_dialog/panel_ffi.rs b/src/backend/macos/file_dialog/panel_ffi.rs index d289e8b8..3ed2328e 100755 --- a/src/backend/macos/file_dialog/panel_ffi.rs +++ b/src/backend/macos/file_dialog/panel_ffi.rs @@ -16,12 +16,14 @@ use objc2_uniform_type_identifiers::UTType; use raw_window_handle::RawWindowHandle; use super::super::{ + message_dialog::Alert, modal_future::{AsModal, InnerModal}, utils::{FocusManager, PolicyManager}, }; -use super::save_name; +use super::save_name::{self, Correction}; use crate::backend::macos::utils::window_from_raw_window_handle; use crate::file_dialog::Filter; +use crate::message_dialog::{MessageButtons, MessageDialog, MessageDialogResult, MessageLevel}; use crate::FileDialog; extern "C" { @@ -95,16 +97,39 @@ impl Panel { } } - /// The file a save panel chose, with the extension of the selected format. - pub fn get_save_result(&self) -> PathBuf { + /// The file a save panel chose, with the extension of the selected format, or `None` when the + /// file that name gives it exists and the person does not want to replace it. + pub fn get_save_result(&self) -> Option { let path = self.get_result(); - match &self._save_panel_handler { - Some(handler) => { - let name_field = unsafe { self.panel.nameFieldStringValue() }.to_string(); - handler.path_with_format_extension(path, &name_field) - } - None => path, - } + let Some(handler) = &self._save_panel_handler else { + return Some(path); + }; + let name_field = unsafe { self.panel.nameFieldStringValue() }.to_string(); + match handler.corrected_path(&path, &name_field) { + Correction::Panels => Some(path), + Correction::Use(corrected) => Some(corrected), + // The panel asked about replacing the file it returned, which is not this one + Correction::Ask(corrected) => self.confirm_replace(&corrected).then_some(corrected), + } + } + + /// Asks whether to replace the file at `path`, as the panel does for the file it returned. + /// Cancel is the default button. + fn confirm_replace(&self, path: &Path) -> bool { + let (title, description) = save_name::replace_question(path); + let dialog = MessageDialog::new() + .set_level(MessageLevel::Info) + .set_title(title) + .set_description(description) + .set_buttons(MessageButtons::OkCancelCustom( + "Cancel".to_string(), + "Replace".to_string(), + )); + let mtm = MainThreadMarker::from(&*self.panel); + matches!( + Alert::new(dialog, mtm).run(), + MessageDialogResult::Custom(answer) if answer == "Replace" + ) } pub fn get_results(&self) -> Vec { @@ -346,28 +371,24 @@ impl SavePanelHandler { } } - /// `path`, the file the panel returned, with the name `save_name::returned_name` gives for it - /// when the selected format is not exact: the panel may not have kept the extension of the - /// name field, or the name has none. `name_field` is what the name field holds. A name that - /// would be another file's is left as the panel returned it, since the panel only asked about - /// overwriting that one. - fn path_with_format_extension(&self, path: PathBuf, name_field: &str) -> PathBuf { + /// What to do with `path`, the file the panel returned, when the selected format is not + /// exact: the name `save_name::returned_name` gives for it, if it is not the panel's, and + /// whether a file has that name. The panel may not have kept the extension of the name field, + /// or the name has none. `name_field` is what the name field holds. + fn corrected_path(&self, path: &Path, name_field: &str) -> Correction { let ivars = self.ivars(); let Some(option) = ivars.options.get(ivars.selected.get()) else { - return path; + return Correction::Panels; }; if option.exact { - return path; + return Correction::Panels; } let renamed = path .file_name() .and_then(|name| name.to_str()) .and_then(|name| save_name::returned_name(name, name_field, &option.extensions)) .map(|name| path.with_file_name(name)); - match renamed { - Some(renamed) if !renamed.exists() => renamed, - _ => path, - } + save_name::correction(path, renamed, Path::exists) } } diff --git a/src/backend/macos/file_dialog/save_name.rs b/src/backend/macos/file_dialog/save_name.rs index 20779f5a..d92dae41 100644 --- a/src/backend/macos/file_dialog/save_name.rs +++ b/src/backend/macos/file_dialog/save_name.rs @@ -1,5 +1,7 @@ //! Keeps the extension of a save panel's name in step with the selected format. +use std::path::{Path, PathBuf}; + /// The name to show in a save panel once the user has selected another format, or `None` when the /// name should stay as it is. /// @@ -103,6 +105,59 @@ pub(super) fn returned_name(raw: &str, field: &str, selected: &[String]) -> Opti name_with_format_extension(raw, selected) } +/// What to do with the path a save panel returned, once the name has been corrected. +#[derive(Debug, PartialEq, Eq)] +pub(super) enum Correction { + /// Return the path the panel returned: nothing was corrected, or the corrected path is it. + Panels, + /// Return this path, the panel's with its name corrected. + Use(PathBuf), + /// Another file has the corrected name, and the panel asked about replacing the one it + /// returned: ask whether to replace this one, and return it if the answer is yes. + Ask(PathBuf), +} + +/// What to do with `path`, which the panel returned, when `renamed` is the path with the name +/// corrected (`None` when it needs no correction) and `exists` says whether a file has a path. +pub(super) fn correction( + path: &Path, + renamed: Option, + exists: impl Fn(&Path) -> bool, +) -> Correction { + match renamed { + Some(renamed) if renamed != path => { + if exists(&renamed) { + Correction::Ask(renamed) + } else { + Correction::Use(renamed) + } + } + _ => Correction::Panels, + } +} + +/// What to ask the person who is to replace the file at `path`: the question and its explanation. +pub(super) fn replace_question(path: &Path) -> (String, String) { + let name = path + .file_name() + .map_or_else(String::new, |name| name.to_string_lossy().into_owned()); + let title = format!("\u{201c}{name}\u{201d} already exists. Do you want to replace it?"); + let folder = path + .parent() + .and_then(Path::file_name) + .map(|folder| { + format!( + " in the folder \u{201c}{}\u{201d}", + folder.to_string_lossy() + ) + }) + .unwrap_or_default(); + let text = format!( + "A file or folder with the same name already exists{folder}. Replacing it will overwrite its current contents." + ); + (title, text) +} + /// The part of `name` before its extension, or the whole name when it has none. fn stem(name: &str) -> &str { split_extension(name).map_or_else(|| name.trim_end_matches('.'), |(stem, _)| stem) @@ -460,4 +515,98 @@ mod tests { ); } } + + fn corrected(path: &str, renamed: Option<&str>, existing: &[&str]) -> Correction { + correction(Path::new(path), renamed.map(PathBuf::from), |checked| { + existing.iter().any(|file| Path::new(file) == checked) + }) + } + + #[test] + fn a_path_that_needs_no_correction_is_the_panels() { + assert_eq!( + corrected("/d/Untitled.other", None, &[]), + Correction::Panels + ); + // Whatever exists, the panel already asked about its own path + assert_eq!( + corrected( + "/d/Untitled.other", + None, + &["/d/Untitled.other", "/d/Untitled.fancy"] + ), + Correction::Panels + ); + } + + #[test] + fn a_corrected_path_nothing_has_is_used() { + assert_eq!( + corrected( + "/d/Untitled.other", + Some("/d/Untitled.fancy"), + &["/d/Untitled.other"] + ), + Correction::Use(PathBuf::from("/d/Untitled.fancy")) + ); + } + + #[test] + fn a_corrected_path_a_file_has_is_asked_about() { + assert_eq!( + corrected( + "/d/Untitled.other", + Some("/d/Untitled.fancy"), + &["/d/Untitled.fancy"] + ), + Correction::Ask(PathBuf::from("/d/Untitled.fancy")) + ); + // A name that had no extension, and now has one + assert_eq!( + corrected( + "/d/Untitled", + Some("/d/Untitled.fancy"), + &["/d/Untitled.fancy"] + ), + Correction::Ask(PathBuf::from("/d/Untitled.fancy")) + ); + } + + #[test] + fn a_correction_that_is_the_panels_own_path_is_the_panels() { + assert_eq!( + corrected( + "/d/Untitled.fancy", + Some("/d/Untitled.fancy"), + &["/d/Untitled.fancy"] + ), + Correction::Panels + ); + } + + #[test] + fn the_question_names_the_file_and_its_folder() { + let (title, text) = replace_question(Path::new("/home/me/Documents/Untitled.fancy")); + assert_eq!( + title, + "\u{201c}Untitled.fancy\u{201d} already exists. Do you want to replace it?" + ); + assert_eq!( + text, + "A file or folder with the same name already exists in the folder \u{201c}Documents\u{201d}. Replacing it will overwrite its current contents." + ); + } + + #[test] + fn the_question_has_no_folder_to_name_for_a_file_at_the_root() { + let (title, text) = replace_question(Path::new("/Untitled.fancy")); + assert_eq!( + title, + "\u{201c}Untitled.fancy\u{201d} already exists. Do you want to replace it?" + ); + assert_eq!( + text, + "A file or folder with the same name already exists. Replacing it will overwrite its current contents." + ); + } }