From 48bdc408ebf09e6eb7d572abe65dbc099a12987e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 11:36:44 -0800 Subject: [PATCH 1/2] dialogs: macOS Save sheets list the file types in a Format menu A Save on macOS that offers two or more file types showed rfd's panel, which allows every type's extension but has no menu to pick one, and answered without a picked type. A document saved from such a panel kept the suggested extension unless the user typed another one. - macos.rs: such a Save is a sheet made with a Format menu (the panel's accessory view, set before the sheet begins). The menu lists each type by name with the suggested name's type chosen. Choosing a type puts its extensions first in the allowed types and changes the extension in the name field. The answer is `Saved` with the chosen type in `filter`, so the save flow's picked-type rules apply as they do for the portal. - format_menu.rs: the rules, tested on every platform: which types the menu lists, distinct item titles, the renamed name, the allowed extensions, and the type an answer reports (an extension the user typed for another listed type wins; a name the panel kept with the suggested extension keeps the chosen type). - craft-appkit: `save_panel::new_save_panel` (nil from AppKit is `None`) and `save_panel::on_choose` (a pop-up menu's action as a closure). - `FileDialog::format_label` and `FilePanels::set_format_label` set the menu's label in the app's language ("Format:" when unset). --- Cargo.lock | 2 + crates/appkit/Cargo.toml | 9 +- crates/appkit/src/lib.rs | 6 +- crates/appkit/src/save_panel.rs | 64 ++++++++++ crates/craft/tests/common/mod.rs | 2 +- crates/dialogs/Cargo.toml | 9 +- crates/dialogs/README.md | 10 +- crates/dialogs/src/format_menu.rs | 115 ++++++++++++++++++ crates/dialogs/src/format_menu/tests.rs | 110 +++++++++++++++++ crates/dialogs/src/lib.rs | 18 ++- crates/dialogs/src/macos.rs | 150 ++++++++++++++++++++++-- crates/dialogs/src/native.rs | 7 +- crates/dialogs/src/service.rs | 10 ++ 13 files changed, 487 insertions(+), 25 deletions(-) create mode 100644 crates/appkit/src/save_panel.rs create mode 100644 crates/dialogs/src/format_menu.rs create mode 100644 crates/dialogs/src/format_menu/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 59f96c7ee..04deca553 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2040,6 +2040,7 @@ name = "craft-appkit" version = "0.1.0" dependencies = [ "block2 0.6.2", + "objc2 0.6.5", "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", ] @@ -2410,6 +2411,7 @@ name = "craft-dialogs" version = "0.1.0" dependencies = [ "block2 0.6.2", + "craft-appkit", "craft-atomic", "craft-behavior", "craft-browse", diff --git a/crates/appkit/Cargo.toml b/crates/appkit/Cargo.toml index ad602e383..5d451b397 100644 --- a/crates/appkit/Cargo.toml +++ b/crates/appkit/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-appkit" -description = "The macOS menu-tracking observers that need `unsafe`, behind a safe API, so no other crate allows `unsafe`." +description = "The macOS menu-tracking observers and Save panel calls that need `unsafe`, behind a safe API, so no other crate allows `unsafe`." version.workspace = true edition.workspace = true license.workspace = true @@ -8,11 +8,12 @@ rust-version.workspace = true repository.workspace = true # `NSMenuDidBeginTrackingNotification` and `NSMenuDidEndTrackingNotification`, observed through -# `NSNotificationCenter` with a block. +# `NSNotificationCenter` with a block. A Save panel made with `-init`, and the target of a pop-up menu's action. [target.'cfg(target_os = "macos")'.dependencies] block2 = "0.6.2" -objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSMenu"] } -objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSOperation", "NSString"] } +objc2 = { version = "0.6.4", default-features = false, features = ["std"] } +objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSButton", "NSControl", "NSMenu", "NSPanel", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSView", "NSWindow"] } +objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSObject", "NSOperation", "NSString"] } # The workspace table with `unsafe_code` at `deny`: `lib.rs` allows it for this crate's FFI calls, and design-lint's # `contract/unsafe-allow` rule names this crate's source as one of the places that may. Cargo cannot override one diff --git a/crates/appkit/src/lib.rs b/crates/appkit/src/lib.rs index 78dd786b1..e023c6aaa 100644 --- a/crates/appkit/src/lib.rs +++ b/crates/appkit/src/lib.rs @@ -1,5 +1,5 @@ -//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking. macOS -//! only; the crate is empty elsewhere. +//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking, and the +//! Save panel's ([`save_panel`]). macOS only; the crate is empty elsewhere. //! //! This is one of the crates that may allow `unsafe`; the design-lint rule `contract/unsafe-allow` names it. Every //! block says why it is sound. @@ -14,6 +14,8 @@ use block2::RcBlock; use objc2_app_kit::{NSMenuDidBeginTrackingNotification, NSMenuDidEndTrackingNotification}; use objc2_foundation::{NSNotification, NSNotificationCenter}; +pub mod save_panel; + /// Calls `on_change(true)` when a menu begins tracking (`NSMenuDidBeginTrackingNotification`) and `on_change(false)` /// when it ends (`NSMenuDidEndTrackingNotification`), from the thread that posts the notification. Observes once /// for the process; a later call replaces nothing and does nothing. diff --git a/crates/appkit/src/save_panel.rs b/crates/appkit/src/save_panel.rs new file mode 100644 index 000000000..979be8f96 --- /dev/null +++ b/crates/appkit/src/save_panel.rs @@ -0,0 +1,64 @@ +//! The Save panel calls that need `unsafe`: making a panel that may be nil, and a pop-up menu's action. + +use objc2::rc::Retained; +use objc2::runtime::AnyObject; +use objc2::{ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel}; +use objc2_app_kit::{NSPopUpButton, NSSavePanel}; +use objc2_foundation::{NSObject, NSObjectProtocol}; + +/// A new Save panel, or `None` when AppKit returns nil. `+[NSSavePanel savePanel]` returns nil on some systems +/// (storytold/vectorcraft#5980), and objc2's `NSSavePanel::savePanel` panics on it. +pub fn new_save_panel(mtm: MainThreadMarker) -> Option> { + // SAFETY: `-init` is the initializer of a bare panel, called once on the allocation. The result is typed as + // `Option`, so nil is `None`. + let panel: Option> = unsafe { msg_send![NSSavePanel::alloc(mtm), init] }; + if panel.is_some() { + return panel; + } + // SAFETY: a class method that returns an autoreleased panel or nil, typed as `Option`. + unsafe { msg_send![NSSavePanel::class(), savePanel] } +} + +/// The closure a [`PopUpChoice`] calls. +pub struct Ivars { + on_choose: Box, +} + +define_class!( + // SAFETY: NSObject has no subclassing requirements, and the class implements no `Drop`. + #[unsafe(super(NSObject))] + #[thread_kind = MainThreadOnly] + #[ivars = Ivars] + #[name = "CraftPopUpChoice"] + /// The target of a pop-up menu's action; see [`on_choose`]. + pub struct PopUpChoice; + + // SAFETY: NSObjectProtocol has no additional requirements. + unsafe impl NSObjectProtocol for PopUpChoice {} + + impl PopUpChoice { + // SAFETY: NSControl's target-action sends the pop-up button as the one object argument. + #[unsafe(method(choose:))] + fn choose(&self, sender: &NSPopUpButton) { + if let Ok(index) = usize::try_from(sender.indexOfSelectedItem()) { + (self.ivars().on_choose)(index); + } + } + } +); + +/// Calls `on_choose` with the index of the item the user chooses in `popup`. A control does not retain its target, +/// so the caller keeps the returned object for as long as `popup` can send its action. +pub fn on_choose(mtm: MainThreadMarker, popup: &NSPopUpButton, on_choose: impl Fn(usize) + 'static) -> Retained { + let this = PopUpChoice::alloc(mtm).set_ivars(Ivars { on_choose: Box::new(on_choose) }); + // SAFETY: NSObject's designated initializer, called once on the allocated subclass. + let target: Retained = unsafe { msg_send![super(this), init] }; + let object: &AnyObject = ⌖ + // SAFETY: `choose:` takes the sender, the signature a control's action is sent with, and the caller keeps + // `target` alive while `popup` can send it (the documentation above). + unsafe { + popup.setTarget(Some(object)); + popup.setAction(Some(sel!(choose:))); + } + target +} diff --git a/crates/craft/tests/common/mod.rs b/crates/craft/tests/common/mod.rs index 827c55a63..9e0ba8722 100644 --- a/crates/craft/tests/common/mod.rs +++ b/crates/craft/tests/common/mod.rs @@ -6,7 +6,7 @@ use std::path::{Path, PathBuf}; /// Crates the facade leaves out, by directory, with the reason. Everything else under `crates/` is a member. pub const NOT_IN_FACADE: &[(&str, &str)] = &[ - ("appkit", "the `unsafe` AppKit observers behind a safe API, used by craft-window"), + ("appkit", "the `unsafe` AppKit calls behind a safe API, used by craft-window and craft-dialogs"), ("design-lint", "a lint template and checker for apps' clippy.toml, run from xtask"), ("feature-root", "a build tool: the dependency set tools/cl resolves every local build's features with; never built"), ("fonts-build", "a build-script helper; apps call it from build.rs"), diff --git a/crates/dialogs/Cargo.toml b/crates/dialogs/Cargo.toml index 160bec49e..48ef081d2 100644 --- a/crates/dialogs/Cargo.toml +++ b/crates/dialogs/Cargo.toml @@ -31,13 +31,14 @@ serde_json = { workspace = true, optional = true } rfd = { version = "0.17.2", default-features = false, features = ["xdg-portal"] } # The file-dialog probe asks the session bus whether the desktop portal offers a file chooser. -# The free-standing Open and Folder panel (`beginWithCompletionHandler:`). rfd and winit already -# use these. +# The free-standing Open and Folder panel (`beginWithCompletionHandler:`), and the Save sheet with a +# Format menu (`beginSheetModalForWindow:completionHandler:`). rfd and winit already use these. [target.'cfg(target_os = "macos")'.dependencies] block2 = "0.6.2" +craft-appkit = { workspace = true } objc2 = { version = "0.6.4", default-features = false, features = ["std"] } -objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSApplication", "NSOpenPanel", "NSPanel", "NSResponder", "NSSavePanel", "NSView", "NSWindow"] } -objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSArray", "NSString", "NSURL"] } +objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSAccessibilityProtocols", "NSApplication", "NSButton", "NSControl", "NSOpenPanel", "NSPanel", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSText", "NSTextField", "NSView", "NSWindow", "objc2-core-foundation"] } +objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSArray", "NSGeometry", "NSString", "NSURL", "objc2-core-foundation"] } # The Linux and BSD Save panel asks the desktop portal itself, which reports the file type picked. # The versions craft-platform already builds (zbus with async-io and blocking-api), so adopting the diff --git a/crates/dialogs/README.md b/crates/dialogs/README.md index ff9d829db..1cec23c3e 100644 --- a/crates/dialogs/README.md +++ b/crates/dialogs/README.md @@ -44,7 +44,7 @@ pub type Override = Box Answer>; pub enum Kind { Open { multiple: bool }, Folder, Save } pub struct FileDialog { pub kind: Kind, pub title: Option, pub filters: Vec, - pub directory: Option, pub file_name: Option } + pub directory: Option, pub file_name: Option, pub format_label: Option } pub struct Filter { pub name: String, pub extensions: Vec } pub struct Message { pub level: MessageLevel, pub title: String, pub description: String, pub buttons: MessageButtons } @@ -66,7 +66,7 @@ impl Dialogs { ``` `FileDialog` has builders: `FileDialog::open().title("Place").filter("Images", &["png", "jpg"])`, -and `open_many`, `folder`, `save`, `directory`, `file_name`. +and `open_many`, `folder`, `save`, `directory`, `file_name`, `format_label`. In an eframe app: @@ -127,6 +127,12 @@ they start only with a parent in a running app, and answer `Unavailable` otherwi before the event loop starts or after it ends (startup and crash messages) stay blocking `rfd` calls in the app. +A Save that offers two or more file types is a sheet the crate makes itself, with a Format menu +that lists each type by name, the suggested name's type chosen. Choosing a type changes the +extension in the name field, and the answer is `Saved` with the chosen type's index in `filter`. +The menu's label is `FileDialog::format_label`, set from `FilePanels::set_format_label` (English +"Format:" when unset). A Save with one type is rfd's sheet, which has no menu. + ## Follow-ups - Linux portal Save (`org.freedesktop.portal.FileChooser.SaveFile`), so the file type the user diff --git a/crates/dialogs/src/format_menu.rs b/crates/dialogs/src/format_menu.rs new file mode 100644 index 000000000..30d6137d1 --- /dev/null +++ b/crates/dialogs/src/format_menu.rs @@ -0,0 +1,115 @@ +//! The Format menu of a macOS Save panel with two or more file types: which types it lists, which one is chosen +//! when the panel opens, the name a choice gives the file and the extensions the panel then allows. Plain rules on +//! names and filters, so they are tested on every platform; `macos.rs` shows the menu. + +use std::path::Path; + +use crate::Filter; +use crate::service::normal; + +/// The indices into `filters` of the file types the menu lists, in order: types with an extension other than `*`. +/// Empty when fewer than two remain: the panel then has no menu. +pub(crate) fn entries(filters: &[Filter]) -> Vec { + let listed: Vec = filters + .iter() + .enumerate() + .filter(|(_, f)| f.extensions.iter().any(|e| !normal(e).is_empty()) && !f.extensions.iter().any(|e| normal(e) == "*")) + .map(|(at, _)| at) + .collect(); + if listed.len() < 2 { Vec::new() } else { listed } +} + +/// The menu's item titles for `entries`, one per entry and all different: a pop-up menu keeps one item per title, so +/// a name that repeats gets its extensions after it (`Document (docx)`), and a title that still matches an earlier +/// title or another type's name gets a number after it. +pub(crate) fn titles(filters: &[Filter], entries: &[usize]) -> Vec { + let names: Vec<&str> = entries.iter().map(|&at| filters.get(at).map_or("", |f| f.name.as_str())).collect(); + let mut out: Vec = Vec::new(); + for (&at, name) in entries.iter().zip(&names) { + let mut base = (*name).to_owned(); + if names.iter().filter(|n| *n == name).count() > 1 { + let extensions: Vec = filters.get(at).map(|f| f.extensions.iter().map(|e| normal(e)).collect()).unwrap_or_default(); + base = format!("{name} ({})", extensions.join(", ")); + } + let taken = |title: &str| out.iter().any(|t| t == title) || (title != *name && names.contains(&title)); + let mut title = base.clone(); + let mut number = 2; + while taken(&title) { + title = format!("{base} {number}"); + number += 1; + } + out.push(title); + } + out +} + +/// The file type a Save answer reports, as an index into `filters`: the one chosen in the menu (menu position +/// `chosen`), unless the name the panel returned ends in an extension that only another listed type has: the user +/// typed it, and the file is saved in that type. `kept` is the name the field still showed when the last choice could +/// not rename it. A returned name equal to it that still has the extension of the name the panel opened with +/// (`opened_with`) keeps the chosen type: the save flow gives a name with the opened extension the chosen type's +/// extension (`with_chosen_type`). Any other extension stays on the name, so the type reported is the one the name has. +pub(crate) fn answered_type( + returned: &str, + kept: Option<&str>, + opened_with: Option<&str>, + filters: &[Filter], + entries: &[usize], + chosen: usize, +) -> Option { + let chosen = entries.get(chosen).copied()?; + let Some(ext) = extension(returned) else { return Some(chosen) }; + let kept_opened = kept == Some(returned) && opened_with.and_then(extension).as_ref() == Some(&ext); + if filters.get(chosen).is_some_and(|f| lists(f, &ext)) || kept_opened { + return Some(chosen); + } + Some(entries.iter().copied().find(|&at| filters.get(at).is_some_and(|f| lists(f, &ext))).unwrap_or(chosen)) +} + +/// The menu position chosen when the panel opens: the type whose extensions include `name`'s, else the first. +pub(crate) fn initial(name: &str, filters: &[Filter], entries: &[usize]) -> usize { + let Some(ext) = extension(name) else { return 0 }; + entries.iter().position(|&at| filters.get(at).is_some_and(|f| lists(f, &ext))).unwrap_or(0) +} + +/// The name the panel shows once `chosen` is picked: an extension `chosen` lists stays; one that another of +/// `filters` lists becomes `chosen`'s first; any other is part of the name (`art.v2`), and `chosen`'s first extension +/// is added after it. An empty name stays empty. +pub(crate) fn renamed(name: &str, chosen: &Filter, filters: &[Filter]) -> String { + let Some(first) = chosen.extensions.iter().map(|e| normal(e)).find(|e| !e.is_empty()) else { return name.to_owned() }; + if name.is_empty() { + return String::new(); + } + match extension(name) { + Some(ext) if lists(chosen, &ext) => name.to_owned(), + Some(ext) if filters.iter().any(|f| lists(f, &ext)) => Path::new(name).with_extension(first).to_string_lossy().into_owned(), + _ => format!("{name}.{first}"), + } +} + +/// The extensions the panel allows with menu position `selected` chosen: that type's first, so that AppKit adds it +/// to a name typed without one, then the other listed types', so that a name typed with one of theirs is kept. +pub(crate) fn allowed(filters: &[Filter], entries: &[usize], selected: usize) -> Vec { + let chosen = entries.get(selected).copied(); + let order = chosen.into_iter().chain(entries.iter().copied().filter(|&at| Some(at) != chosen)); + let mut out: Vec = Vec::new(); + for ext in order.filter_map(|at| filters.get(at)).flat_map(|f| f.extensions.iter().map(|e| normal(e))) { + if !ext.is_empty() && !out.contains(&ext) { + out.push(ext); + } + } + out +} + +/// `name`'s extension as compared, if it has one. +fn extension(name: &str) -> Option { + Path::new(name).extension().and_then(|e| e.to_str()).map(normal) +} + +/// Whether `filter` lists `ext` (already [`normal`]). +fn lists(filter: &Filter, ext: &str) -> bool { + filter.extensions.iter().any(|e| normal(e) == ext) +} + +#[cfg(test)] +pub(crate) mod tests; diff --git a/crates/dialogs/src/format_menu/tests.rs b/crates/dialogs/src/format_menu/tests.rs new file mode 100644 index 000000000..aaf7fdea7 --- /dev/null +++ b/crates/dialogs/src/format_menu/tests.rs @@ -0,0 +1,110 @@ +use super::*; +use craft_ui::testing::trial; + +fn filters() -> Vec { + vec![Filter::new("Document", &["doc"]), Filter::new("Drawing", &["ai"]), Filter::new("Picture", &["jpg", "jpeg"])] +} + +/// The menu lists the types with an extension; "every file" types and ones without an extension stay out, and a +/// panel left with one type gets no menu. +#[trial] +fn the_menu_lists_types_with_extensions_and_needs_two() { + assert_eq!(entries(&filters()), [0, 1, 2]); + let mixed = [Filter::new("Document", &["doc"]), Filter::new("All files", &["*"]), Filter::new("Any", &[]), Filter::new("Drawing", &[".ai"])]; + assert_eq!(entries(&mixed), [0, 3], "the dot is not part of the extension"); + assert!(entries(&[Filter::new("Document", &["doc"]), Filter::new("All files", &["*"])]).is_empty()); + assert!(entries(&[]).is_empty()); +} + +/// Two types with one name both stay in the menu, under different titles; other titles are the names. +#[trial] +fn types_that_share_a_name_get_different_titles() { + let twice = [Filter::new("Document", &["doc"]), Filter::new("Document", &["docx"]), Filter::new("Drawing", &["ai"])]; + let listed = entries(&twice); + assert_eq!(listed, [0, 1, 2]); + let shown = titles(&twice, &listed); + assert_eq!(shown.len(), listed.len()); + assert!(shown.iter().enumerate().all(|(i, t)| !shown[..i].contains(t)), "{shown:?}"); + assert_eq!(shown[2], "Drawing"); + for set in [ + vec![Filter::new("Document", &["doc"]), Filter::new("Document", &["doc"])], + vec![Filter::new("X (x) 2", &["a"]), Filter::new("X", &["x"]), Filter::new("X", &["x"])], + vec![Filter::new("X", &["x"]), Filter::new("X", &["x"]), Filter::new("X (x) 2", &["a"]), Filter::new("X (x)", &["b"])], + ] { + let shown = titles(&set, &entries(&set)); + assert_eq!(shown.len(), set.len()); + assert!(shown.iter().enumerate().all(|(i, t)| !shown[..i].contains(t)), "{shown:?}"); + } +} + +/// The answer reports the chosen type, unless the user typed another listed type's extension; a name the panel kept +/// when a choice could not rename it keeps the chosen type. +#[trial] +fn a_typed_extension_of_another_type_is_the_type_saved() { + let all = filters(); + let listed = entries(&all); + let (kept, opened) = (Some("Untitled-1.doc"), Some("Untitled-1.doc")); + let answer = |returned, kept| answered_type(returned, kept, opened, &all, &listed, 1); + assert_eq!(answer("Untitled-1.ai", None), Some(1)); + assert_eq!(answer("Untitled-1.doc", kept), Some(1), "the panel kept the opened name"); + assert_eq!(answer("Other.doc", kept), Some(0), "the user typed a new name after that"); + assert_eq!(answer("Untitled-1.doc", None), Some(0), "the user typed the first type's extension back"); + assert_eq!(answer("photo.JPEG", kept), Some(2), "the user typed another type's extension"); + assert_eq!(answer("Other.doc", Some("Other.doc")), Some(1), "a kept name with the opened extension"); + assert_eq!(answer("Other.jpg", Some("Other.jpg")), Some(2), "a kept name with another type's extension keeps that type"); + assert_eq!(answer("notes.v2", None), Some(1)); + assert_eq!(answer("art", None), Some(1)); + assert_eq!(answered_type("art.ai", None, opened, &all, &listed, 9), None, "a position the menu doesn't have"); +} + +#[trial] +fn the_suggested_name_chooses_its_type_and_any_other_the_first() { + let all = filters(); + let listed = entries(&all); + for (name, at) in [("Untitled-1.doc", 0), ("art.AI", 1), ("photo.jpeg", 2), ("Untitled-1", 0), ("notes.v2", 0), ("", 0)] { + assert_eq!(initial(name, &all, &listed), at, "{name}"); + } +} + +/// Choosing a type replaces the extension of another listed type, keeps one of its own and adds its own after any +/// other dot in the name. +#[trial] +fn choosing_a_type_gives_the_name_its_extension() { + let all = filters(); + let drawing = &all[1]; + for (name, expected) in [ + ("Untitled-1.doc", "Untitled-1.ai"), + ("Plan 1.DOC", "Plan 1.ai"), + ("photo.jpeg", "photo.ai"), + ("art.ai", "art.ai"), + ("art.AI", "art.AI"), + ("art", "art.ai"), + ("art.v2", "art.v2.ai"), + ("", ""), + ] { + assert_eq!(renamed(name, drawing, &all), expected, "{name}"); + } + assert_eq!(renamed("photo.jpeg", &all[2], &all), "photo.jpeg", "a second extension of the chosen type stays"); +} + +/// A sequence of choices (A to B to C) ends with C's extension, and back to A gives A's. +#[trial] +fn each_choice_follows_the_previous_one() { + let all = filters(); + let mut name = "Untitled-1.doc".to_owned(); + for (at, ext) in [(1, "ai"), (2, "jpg"), (0, "doc")] { + name = renamed(&name, &all[at], &all); + assert_eq!(Path::new(&name).extension().and_then(|e| e.to_str()), Some(ext)); + assert_eq!(Path::new(&name).file_stem().and_then(|e| e.to_str()), Some("Untitled-1")); + } +} + +/// The chosen type's extension comes first, so AppKit adds it to a bare name; the others stay allowed. +#[trial] +fn the_chosen_type_is_allowed_first() { + let all = filters(); + let listed = entries(&all); + assert_eq!(allowed(&all, &listed, 0), ["doc", "ai", "jpg", "jpeg"]); + assert_eq!(allowed(&all, &listed, 1), ["ai", "doc", "jpg", "jpeg"]); + assert_eq!(allowed(&all, &listed, 2), ["jpg", "jpeg", "doc", "ai"]); +} diff --git a/crates/dialogs/src/lib.rs b/crates/dialogs/src/lib.rs index dbeef093d..400a80392 100644 --- a/crates/dialogs/src/lib.rs +++ b/crates/dialogs/src/lib.rs @@ -20,6 +20,8 @@ #![warn(missing_docs)] mod filter; +#[cfg(any(target_os = "macos", test))] +mod format_menu; mod native; #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))] pub(crate) mod portal; @@ -92,12 +94,18 @@ pub struct FileDialog { pub directory: Option, /// The file name a Save dialog suggests. pub file_name: Option, + /// The label of the file type menu a macOS Save panel with two or more file types shows; `None` shows + /// [`FORMAT_LABEL`]. Other platforms' dialogs label their menu themselves. + pub format_label: Option, } +/// The English label of the macOS Save panel's file type menu. +pub const FORMAT_LABEL: &str = "Format:"; + impl FileDialog { /// A dialog of `kind` with nothing else set. pub fn new(kind: Kind) -> Self { - Self { kind, title: None, filters: Vec::new(), directory: None, file_name: None } + Self { kind, title: None, filters: Vec::new(), directory: None, file_name: None, format_label: None } } /// Choose one existing file. @@ -143,6 +151,12 @@ impl FileDialog { self.file_name = Some(file_name.into()); self } + + /// Sets the label of the macOS Save panel's file type menu, in the app's language. + pub fn format_label(mut self, label: impl Into) -> Self { + self.format_label = Some(label.into()); + self + } } /// The icon a message box shows. @@ -223,7 +237,7 @@ pub enum Answer { /// The chosen files or folder. Paths(Vec), /// A Save panel's answer: the name as typed and the file type picked, when the panel reports it (the portal's - /// current filter; rfd reports `None`). + /// current filter, or the macOS panel's Format menu; rfd reports `None`). Saved { /// The name as typed. path: PathBuf, diff --git a/crates/dialogs/src/macos.rs b/crates/dialogs/src/macos.rs index f6c938d71..eb7fab3ba 100644 --- a/crates/dialogs/src/macos.rs +++ b/crates/dialogs/src/macos.rs @@ -6,22 +6,29 @@ //! rfd can't show this panel: its async dialogs always begin a sheet, on the main or first window //! when no parent is given (rfd 0.17.2 `backend/macos/modal_future.rs:71-102`). //! -//! Save and message boxes are sheets on the parent window through rfd, as native apps show them. -//! rfd falls back to the blocking `runModal` when the app isn't running or has no window -//! (`modal_future.rs:79-118`), so [`sheet_parent`] lets a sheet start only with a parent in a +//! Save and message boxes are sheets on the parent window, as native apps show them. A Save that +//! offers two or more file types is a sheet made here ([`show_save_sheet`]), with a Format menu: +//! rfd's Save panel lists the extensions of every type and has no menu to choose one +//! (rfd 0.17.2 `backend/macos/file_dialog/panel_ffi.rs:107-120`). Other Saves and message boxes +//! are rfd's sheets. rfd falls back to the blocking `runModal` when the app isn't running or has no +//! window (`modal_future.rs:79-118`), so [`sheet_parent`] lets a sheet start only with a parent in a //! running app. -use std::cell::Cell; +use std::cell::{Cell, RefCell}; use std::ffi::c_void; +use std::rc::Rc; use block2::RcBlock; use objc2::MainThreadMarker; -use objc2::rc::Retained; -use objc2_app_kit::{NSApplication, NSModalResponse, NSModalResponseOK, NSOpenPanel, NSView}; -use objc2_foundation::{NSArray, NSString, NSURL}; +use objc2::MainThreadOnly; +use objc2::rc::{Retained, Weak}; +use objc2_app_kit::{ + NSAccessibility, NSApplication, NSModalResponse, NSModalResponseOK, NSOpenPanel, NSPopUpButton, NSSavePanel, NSTextField, NSView, NSWindow, +}; +use objc2_foundation::{NSArray, NSPoint, NSRect, NSSize, NSString, NSURL}; use raw_window_handle::{HasWindowHandle, RawWindowHandle}; -use crate::{Answer, FileDialog, Kind, Reply}; +use crate::{Answer, FORMAT_LABEL, FileDialog, Filter, Kind, Reply, format_menu}; const NOT_MAIN: &str = "dialogs show from the main thread only"; const NOT_RUNNING: &str = "the app isn't running yet, so the dialog can't be shown"; @@ -62,6 +69,133 @@ fn contains(root: &NSView, view: *const c_void) -> bool { std::ptr::eq((root as *const NSView).cast(), view) || root.subviews().iter().any(|child| contains(&child, view)) } +/// The app's window that `parent`'s view is in. +fn window_of(mtm: MainThreadMarker, parent: &W) -> Option> { + let view = match parent.window_handle().map(|h| h.as_raw()) { + Ok(RawWindowHandle::AppKit(h)) => h.ns_view.as_ptr().cast_const(), + _ => return None, + }; + NSApplication::sharedApplication(mtm).windows().iter().find(|window| window.contentView().is_some_and(|content| contains(&content, view))) +} + +/// The Format menu's height and the room around and between its label and menu, in points. +const ACCESSORY_HEIGHT: f64 = 38.0; +const MARGIN: f64 = 12.0; +const GAP: f64 = 8.0; +/// The Format menu's size, in points. +const MENU: NSSize = NSSize::new(260.0, 26.0); + +/// Shows a Save sheet with a Format menu on `parent` (a [`sheet_parent`]) when `d` offers two or more file types +/// ([`format_menu::entries`]), and answers through `reply` with the type chosen in the menu. Choosing a type puts the +/// type's extensions first in the allowed types, which AppKit adds to a name typed without one, and sets the name +/// field to [`format_menu::renamed`]. The SDK's `NSSavePanel.h` says the name field can only be set while the panel is +/// configured; macOS 27.2 shows the new name. Where a system keeps the suggested name, the answer's `filter` still names the chosen +/// type, so the save flow settles the extension (`ExtensionPolicy::picked_type`, or the app's own rule) and asks +/// before replacing a file the panel did not ask about; a kept name with another extension reports that extension's +/// type ([`format_menu::answered_type`]). Gives `reply` back when `d` offers fewer types, for rfd's panel. +/// +/// The menu is the panel's accessory view, set before `beginSheetModalForWindow:completionHandler:` shows the sheet: +/// an accessory set after the sheet began made macOS dismiss the sheet at once (storytold/vectorcraft#1800). The +/// completion handler holds the panel, the menu and the menu's target until the sheet closes; the target holds the +/// panel weakly. +pub(crate) fn show_save_sheet(d: &FileDialog, parent: &W, reply: Reply) -> Result<(), Reply> { + let entries = format_menu::entries(&d.filters); + if entries.is_empty() { + return Err(reply); + } + let Some(mtm) = MainThreadMarker::new() else { return Err(reply) }; + let Some(window) = window_of(mtm, parent) else { return Err(reply) }; + let Some(panel) = craft_appkit::save_panel::new_save_panel(mtm) else { + reply.send(Answer::Unavailable("macOS returned no Save panel".into())); + return Ok(()); + }; + let name = d.file_name.clone().unwrap_or_default(); + let selected = format_menu::initial(&name, &d.filters, &entries); + set_allowed_types(&panel, &d.filters, &entries, selected); + if let Some(title) = &d.title { + panel.setMessage(Some(&NSString::from_str(title))); + } + if let Some(directory) = d.directory.as_deref().and_then(NSURL::from_directory_path) { + panel.setDirectoryURL(Some(&directory)); + } + panel.setExtensionHidden(false); + if !name.is_empty() { + panel.setNameFieldStringValue(&NSString::from_str(&name)); + } + let label = d.format_label.as_deref().unwrap_or(FORMAT_LABEL); + let (accessory, popup) = accessory(mtm, label, &d.filters, &entries, selected); + panel.setAccessoryView(Some(&accessory)); + + // The name the field kept when the last choice could not rename it. + let kept: Rc>> = Rc::default(); + let (filters, listed, weak, kept_by_choice) = (d.filters.clone(), entries.clone(), Weak::new(&*panel), kept.clone()); + let choice = craft_appkit::save_panel::on_choose(mtm, &popup, move |at| { + let (Some(panel), Some(chosen)) = (weak.load(), listed.get(at).and_then(|&i| filters.get(i))) else { return }; + set_allowed_types(&panel, &filters, &listed, at); + let name = panel.nameFieldStringValue().to_string(); + let new_name = format_menu::renamed(&name, chosen, &filters); + panel.setNameFieldStringValue(&NSString::from_str(&new_name)); + let shown = panel.nameFieldStringValue().to_string(); + *kept_by_choice.borrow_mut() = (shown != new_name).then_some(shown); + }); + let reply = Cell::new(Some(reply)); + let answered = panel.clone(); + let (filters, opened_with) = (d.filters.clone(), d.file_name.clone()); + let handler = RcBlock::new(move |response: NSModalResponse| { + // The menu sends its action to `choice` while the sheet is open; the handler keeps it until then. + let _target = &choice; + let Some(reply) = reply.take() else { return }; + if response != NSModalResponseOK { + return reply.send(Answer::Cancelled); + } + let Some(path) = answered.URL().and_then(|url| url.to_file_path()) else { return reply.send(Answer::Cancelled) }; + let returned = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let filter = usize::try_from(popup.indexOfSelectedItem()) + .ok() + .and_then(|at| format_menu::answered_type(&returned, kept.borrow().as_deref(), opened_with.as_deref(), &filters, &entries, at)); + reply.send(Answer::Saved { path, filter }); + }); + panel.beginSheetModalForWindow_completionHandler(&window, &handler); + Ok(()) +} + +/// Sets `panel`'s allowed file types to [`format_menu::allowed`]. +fn set_allowed_types(panel: &NSSavePanel, filters: &[Filter], entries: &[usize], selected: usize) { + let types: Vec> = format_menu::allowed(filters, entries, selected).iter().map(|e| NSString::from_str(e)).collect(); + // As rfd does, and as `show_panel` does for Open. + #[allow(deprecated)] + panel.setAllowedFileTypes(Some(&NSArray::from_retained_slice(&types))); +} + +/// The label and the Format menu of `filters`' `entries`, `selected` chosen, in a view for the panel's accessory. +fn accessory( + mtm: MainThreadMarker, + text: &str, + filters: &[Filter], + entries: &[usize], + selected: usize, +) -> (Retained, Retained) { + let label = NSTextField::labelWithString(&NSString::from_str(text), mtm); + label.sizeToFit(); + let size = label.frame().size; + label.setFrameOrigin(NSPoint::new(MARGIN, (ACCESSORY_HEIGHT - size.height) / 2.0)); + let x = MARGIN + size.width + GAP; + let frame = NSRect::new(NSPoint::new(x, (ACCESSORY_HEIGHT - MENU.height) / 2.0), MENU); + let popup = NSPopUpButton::initWithFrame_pullsDown(NSPopUpButton::alloc(mtm), frame, false); + // The label beside the menu is not tied to it for VoiceOver, so the menu carries the label's words as its name. + popup.setAccessibilityLabel(Some(&NSString::from_str(text.trim_end_matches([':', ':'])))); + for title in format_menu::titles(filters, entries) { + popup.addItemWithTitle(&NSString::from_str(&title)); + } + if let Ok(index) = isize::try_from(selected) { + popup.selectItemAtIndex(index); + } + let view = NSView::initWithFrame(NSView::alloc(mtm), NSRect::new(NSPoint::ZERO, NSSize::new(x + MENU.width + MARGIN, ACCESSORY_HEIGHT))); + view.addSubview(&label); + view.addSubview(&popup); + (view, popup) +} + /// Shows an Open or Folder panel that doesn't block the window and answers through `reply` when /// it closes. AppKit calls the completion handler on the main thread. pub(crate) fn show_panel(d: &FileDialog, reply: Reply) -> Option { diff --git a/crates/dialogs/src/native.rs b/crates/dialogs/src/native.rs index 3ecd0f530..8b2953369 100644 --- a/crates/dialogs/src/native.rs +++ b/crates/dialogs/src/native.rs @@ -63,10 +63,13 @@ pub(crate) fn show(request: Request, pare fn show_file(d: FileDialog, parent: Option<&W>, reply: Reply) -> Shown { #[cfg(target_os = "macos")] - let parent = match d.kind { + let (parent, reply) = match d.kind { Kind::Open { .. } | Kind::Folder => return Shown { panel: crate::macos::show_panel(&d, reply) }, Kind::Save => match crate::macos::sheet_parent(parent) { - Ok(parent) => Some(parent), + Ok(parent) => match crate::macos::show_save_sheet(&d, parent, reply) { + Ok(()) => return Shown::default(), + Err(reply) => (Some(parent), reply), + }, Err(why) => { reply.send(Answer::Unavailable(why)); return Shown::default(); diff --git a/crates/dialogs/src/service.rs b/crates/dialogs/src/service.rs index dae5fd516..273bc8961 100644 --- a/crates/dialogs/src/service.rs +++ b/crates/dialogs/src/service.rs @@ -276,6 +276,8 @@ pub struct FilePanels { extension_policy: ExtensionPolicy, replace_guard: ReplaceGuard, replace_words: ReplaceWords, + /// The label of the macOS Save panel's file type menu; `None` shows [`crate::FORMAT_LABEL`]. + format_label: Option, /// Why no file dialog can open on this system, when the probe knows. backend_problem: fn() -> Option, /// The replace questions [`pump_with`](FilePanels::pump_with) put on the app's dialog host. @@ -325,6 +327,7 @@ impl FileService { extension_policy: ExtensionPolicy::default(), replace_guard: ReplaceGuard::default(), replace_words: ReplaceWords::default(), + format_label: None, backend_problem: probe::known_problem, #[cfg(feature = "ui")] prompts: Vec::new(), @@ -393,6 +396,12 @@ impl FilePanels { self.replace_words = words; } + /// The label of the file type menu on a macOS Save panel that offers two or more types ("Format:" in English); + /// the app sets it again when the language changes. + pub fn set_format_label(&mut self, label: impl Into) { + self.format_label = Some(label.into()); + } + /// [`extension_policy`](FilePanels::extension_policy) on panels the app already keeps, for a /// preference that changes while the app runs. pub fn set_extension_policy(&mut self, policy: ExtensionPolicy) { @@ -647,6 +656,7 @@ impl FilePanels { if request.kind == PickKind::Save { let adds_extension = cfg!(windows) && !request.filters.is_empty(); dialog.file_name = request.file_name.as_deref().and_then(|name| dialog_file_name(name, adds_extension)); + dialog.format_label = self.format_label.clone(); } dialog } From 2e19dbaa9e480f53980ddd30b845de2738f0a80b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 14:48:58 -0800 Subject: [PATCH 2/2] appkit: crate docs name save_panel without an intra-doc link The module exists only on macOS, so the link did not resolve when the workspace docs build on Linux with -D warnings. --- crates/appkit/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/appkit/src/lib.rs b/crates/appkit/src/lib.rs index e023c6aaa..70ed01f92 100644 --- a/crates/appkit/src/lib.rs +++ b/crates/appkit/src/lib.rs @@ -1,5 +1,5 @@ //! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking, and the -//! Save panel's ([`save_panel`]). macOS only; the crate is empty elsewhere. +//! Save panel calls in `save_panel`. macOS only; the crate is empty elsewhere. //! //! This is one of the crates that may allow `unsafe`; the design-lint rule `contract/unsafe-allow` names it. Every //! block says why it is sound.