Skip to main content

strata_platform/
dialog.rs

1//! Cross-platform native OS dialogs (file pickers, folder selectors, and message boxes).
2//!
3//! Provides native system dialogs across Linux (GTK / XDG Desktop Portal),
4//! Windows (`comdlg32` / Win32 `GetOpenFileNameW` / `MessageBoxW`), and
5//! macOS (AppKit `NSOpenPanel`, `NSSavePanel`, `NSAlert`).
6//!
7//! Includes a thread-safe mock override system (`set_dialog_mock_response`)
8//! allowing automated CI and headless tests to verify dialog logic deterministically.
9
10use std::path::PathBuf;
11#[cfg(any(test, feature = "test-internals"))]
12use std::sync::Mutex;
13
14/// File type filter used by file picker dialogs.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct DialogFilter {
17    pub name: String,
18    pub extensions: Vec<String>,
19}
20
21impl DialogFilter {
22    /// Creates a new filter with a human-readable display name and allowed file extensions.
23    pub fn new(name: impl Into<String>, extensions: &[&str]) -> Self {
24        Self {
25            name: name.into(),
26            extensions: extensions
27                .iter()
28                .map(|ext| ext.trim_start_matches('.').to_string())
29                .collect(),
30        }
31    }
32}
33
34/// Configuration options for opening files.
35#[derive(Debug, Clone, Default)]
36pub struct OpenFileOptions {
37    pub title: Option<String>,
38    pub starting_directory: Option<PathBuf>,
39    pub filters: Vec<DialogFilter>,
40    pub multiple: bool,
41}
42
43impl OpenFileOptions {
44    pub fn new() -> Self {
45        Self::default()
46    }
47
48    pub fn with_title(mut self, title: impl Into<String>) -> Self {
49        self.title = Some(title.into());
50        self
51    }
52
53    pub fn with_directory(mut self, directory: impl Into<PathBuf>) -> Self {
54        self.starting_directory = Some(directory.into());
55        self
56    }
57
58    pub fn with_filter(mut self, name: impl Into<String>, extensions: &[&str]) -> Self {
59        self.filters.push(DialogFilter::new(name, extensions));
60        self
61    }
62
63    pub fn with_multiple(mut self, multiple: bool) -> Self {
64        self.multiple = multiple;
65        self
66    }
67}
68
69/// Configuration options for saving a file.
70#[derive(Debug, Clone, Default)]
71pub struct SaveFileOptions {
72    pub title: Option<String>,
73    pub starting_directory: Option<PathBuf>,
74    pub default_name: Option<String>,
75    pub filters: Vec<DialogFilter>,
76}
77
78impl SaveFileOptions {
79    pub fn new() -> Self {
80        Self::default()
81    }
82
83    pub fn with_title(mut self, title: impl Into<String>) -> Self {
84        self.title = Some(title.into());
85        self
86    }
87
88    pub fn with_directory(mut self, directory: impl Into<PathBuf>) -> Self {
89        self.starting_directory = Some(directory.into());
90        self
91    }
92
93    pub fn with_default_name(mut self, default_name: impl Into<String>) -> Self {
94        self.default_name = Some(default_name.into());
95        self
96    }
97
98    pub fn with_filter(mut self, name: impl Into<String>, extensions: &[&str]) -> Self {
99        self.filters.push(DialogFilter::new(name, extensions));
100        self
101    }
102}
103
104/// Configuration options for selecting a folder.
105#[derive(Debug, Clone, Default)]
106pub struct PickFolderOptions {
107    pub title: Option<String>,
108    pub starting_directory: Option<PathBuf>,
109}
110
111impl PickFolderOptions {
112    pub fn new() -> Self {
113        Self::default()
114    }
115
116    pub fn with_title(mut self, title: impl Into<String>) -> Self {
117        self.title = Some(title.into());
118        self
119    }
120
121    pub fn with_directory(mut self, directory: impl Into<PathBuf>) -> Self {
122        self.starting_directory = Some(directory.into());
123        self
124    }
125}
126
127/// Semantic type of message box or alert.
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
129pub enum MessageBoxType {
130    #[default]
131    Info,
132    Warning,
133    Error,
134    Question,
135}
136
137/// Set of buttons to present in a message box.
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
139pub enum MessageBoxButtons {
140    #[default]
141    Ok,
142    OkCancel,
143    YesNo,
144    YesNoCancel,
145}
146
147/// Result returned when a user interacts with a message box.
148#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149pub enum MessageBoxResult {
150    Ok,
151    Cancel,
152    Yes,
153    No,
154}
155
156/// Mock response for automated test suites.
157#[derive(Debug, Clone)]
158pub enum DialogMockResponse {
159    OpenFile(Option<PathBuf>),
160    OpenFiles(Vec<PathBuf>),
161    SaveFile(Option<PathBuf>),
162    PickFolder(Option<PathBuf>),
163    MessageBox(MessageBoxResult),
164}
165
166#[cfg(any(test, feature = "test-internals"))]
167static DIALOG_MOCK: Mutex<Option<DialogMockResponse>> = Mutex::new(None);
168
169/// Sets an explicit mock response for testing.
170///
171/// NOTE: This hook is strictly feature-gated to `test-internals` and unit tests to prevent
172/// unauthorized backdoor overrides in production release builds.
173#[cfg(any(test, feature = "test-internals"))]
174pub fn set_dialog_mock_response(response: Option<DialogMockResponse>) {
175    let mut lock = DIALOG_MOCK.lock().unwrap();
176    *lock = response;
177}
178
179#[cfg(any(test, feature = "test-internals"))]
180fn check_mock_response() -> Option<DialogMockResponse> {
181    DIALOG_MOCK.lock().unwrap().clone()
182}
183
184#[cfg(not(any(test, feature = "test-internals")))]
185#[inline(always)]
186fn check_mock_response() -> Option<DialogMockResponse> {
187    None
188}
189
190/// Prompts user to select a single file to open.
191pub fn open_file(options: OpenFileOptions) -> Option<PathBuf> {
192    if let Some(DialogMockResponse::OpenFile(path)) = check_mock_response() {
193        return path;
194    }
195
196    #[cfg(target_os = "linux")]
197    {
198        linux_backend::open_file(&options)
199    }
200    #[cfg(windows)]
201    {
202        windows_backend::open_file(&options)
203    }
204    #[cfg(target_os = "macos")]
205    {
206        macos_backend::open_file(&options)
207    }
208    #[cfg(not(any(target_os = "linux", windows, target_os = "macos")))]
209    {
210        let _ = options;
211        None
212    }
213}
214
215/// Prompts user to select multiple files to open.
216pub fn open_multiple_files(options: OpenFileOptions) -> Vec<PathBuf> {
217    if let Some(DialogMockResponse::OpenFiles(paths)) = check_mock_response() {
218        return paths;
219    }
220
221    #[cfg(target_os = "linux")]
222    {
223        linux_backend::open_multiple_files(&options)
224    }
225    #[cfg(windows)]
226    {
227        windows_backend::open_multiple_files(&options)
228    }
229    #[cfg(target_os = "macos")]
230    {
231        macos_backend::open_multiple_files(&options)
232    }
233    #[cfg(not(any(target_os = "linux", windows, target_os = "macos")))]
234    {
235        let _ = options;
236        Vec::new()
237    }
238}
239
240/// Prompts user to choose a destination path for saving a file.
241pub fn save_file(options: SaveFileOptions) -> Option<PathBuf> {
242    if let Some(DialogMockResponse::SaveFile(path)) = check_mock_response() {
243        return path;
244    }
245
246    #[cfg(target_os = "linux")]
247    {
248        linux_backend::save_file(&options)
249    }
250    #[cfg(windows)]
251    {
252        windows_backend::save_file(&options)
253    }
254    #[cfg(target_os = "macos")]
255    {
256        macos_backend::save_file(&options)
257    }
258    #[cfg(not(any(target_os = "linux", windows, target_os = "macos")))]
259    {
260        let _ = options;
261        None
262    }
263}
264
265/// Prompts user to choose a directory / folder.
266pub fn pick_folder(options: PickFolderOptions) -> Option<PathBuf> {
267    if let Some(DialogMockResponse::PickFolder(path)) = check_mock_response() {
268        return path;
269    }
270
271    #[cfg(target_os = "linux")]
272    {
273        linux_backend::pick_folder(&options)
274    }
275    #[cfg(windows)]
276    {
277        windows_backend::pick_folder(&options)
278    }
279    #[cfg(target_os = "macos")]
280    {
281        macos_backend::pick_folder(&options)
282    }
283    #[cfg(not(any(target_os = "linux", windows, target_os = "macos")))]
284    {
285        let _ = options;
286        None
287    }
288}
289
290/// Shows a native operating system message alert / confirmation box.
291pub fn show_message_box(
292    title: &str,
293    message: &str,
294    box_type: MessageBoxType,
295    buttons: MessageBoxButtons,
296) -> MessageBoxResult {
297    if let Some(DialogMockResponse::MessageBox(result)) = check_mock_response() {
298        return result;
299    }
300
301    #[cfg(target_os = "linux")]
302    {
303        linux_backend::show_message_box(title, message, box_type, buttons)
304    }
305    #[cfg(windows)]
306    {
307        windows_backend::show_message_box(title, message, box_type, buttons)
308    }
309    #[cfg(target_os = "macos")]
310    {
311        macos_backend::show_message_box(title, message, box_type, buttons)
312    }
313    #[cfg(not(any(target_os = "linux", windows, target_os = "macos")))]
314    {
315        let _ = (title, message, box_type, buttons);
316        MessageBoxResult::Ok
317    }
318}
319
320/// Non-blocking single-file open dialog safe to call inside UI event handlers without nesting `dialog.run()`.
321pub fn open_file_async<F>(options: OpenFileOptions, callback: F)
322where
323    F: FnOnce(Option<PathBuf>) + 'static,
324{
325    if let Some(DialogMockResponse::OpenFile(path)) = check_mock_response() {
326        callback(path);
327        return;
328    }
329
330    #[cfg(all(target_os = "linux", feature = "gtk-compat"))]
331    {
332        linux_backend::open_file_async(&options, callback);
333    }
334    #[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
335    {
336        callback(open_file(options));
337    }
338}
339
340/// Non-blocking multi-file open dialog safe to call inside UI event handlers without nesting `dialog.run()`.
341pub fn open_multiple_files_async<F>(options: OpenFileOptions, callback: F)
342where
343    F: FnOnce(Vec<PathBuf>) + 'static,
344{
345    if let Some(DialogMockResponse::OpenFiles(paths)) = check_mock_response() {
346        callback(paths);
347        return;
348    }
349
350    #[cfg(all(target_os = "linux", feature = "gtk-compat"))]
351    {
352        linux_backend::open_multiple_files_async(&options, callback);
353    }
354    #[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
355    {
356        callback(open_multiple_files(options));
357    }
358}
359
360/// Non-blocking file save dialog safe to call inside UI event handlers without nesting `dialog.run()`.
361pub fn save_file_async<F>(options: SaveFileOptions, callback: F)
362where
363    F: FnOnce(Option<PathBuf>) + 'static,
364{
365    if let Some(DialogMockResponse::SaveFile(path)) = check_mock_response() {
366        callback(path);
367        return;
368    }
369
370    #[cfg(all(target_os = "linux", feature = "gtk-compat"))]
371    {
372        linux_backend::save_file_async(&options, callback);
373    }
374    #[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
375    {
376        callback(save_file(options));
377    }
378}
379
380/// Non-blocking folder selection dialog safe to call inside UI event handlers without nesting `dialog.run()`.
381pub fn pick_folder_async<F>(options: PickFolderOptions, callback: F)
382where
383    F: FnOnce(Option<PathBuf>) + 'static,
384{
385    if let Some(DialogMockResponse::PickFolder(path)) = check_mock_response() {
386        callback(path);
387        return;
388    }
389
390    #[cfg(all(target_os = "linux", feature = "gtk-compat"))]
391    {
392        linux_backend::pick_folder_async(&options, callback);
393    }
394    #[cfg(not(all(target_os = "linux", feature = "gtk-compat")))]
395    {
396        callback(pick_folder(options));
397    }
398}
399
400#[cfg(all(target_os = "linux", feature = "gtk-compat"))]
401mod linux_backend {
402    use super::*;
403    use gtk::prelude::*;
404    use std::cell::RefCell;
405    use std::path::PathBuf;
406    use std::rc::Rc;
407
408    fn active_parent_window() -> Option<gtk::Window> {
409        let windows: Vec<gtk::Window> = gtk::Window::list_toplevels()
410            .into_iter()
411            .filter_map(|w| w.downcast::<gtk::Window>().ok())
412            .collect();
413        windows
414            .iter()
415            .find(|w| w.is_visible() && w.is_active())
416            .cloned()
417            .or_else(|| windows.into_iter().find(|w| w.is_visible()))
418    }
419
420    fn create_file_chooser(
421        title: &str,
422        action: gtk::FileChooserAction,
423        accept_label: &str,
424        filters: &[DialogFilter],
425        starting_directory: Option<&PathBuf>,
426    ) -> gtk::FileChooserNative {
427        let parent = active_parent_window();
428        let dialog = gtk::FileChooserNative::new(
429            Some(title),
430            parent.as_ref(),
431            action,
432            Some(accept_label),
433            Some("Cancel"),
434        );
435        apply_filters(&dialog, filters);
436        if let Some(dir) = starting_directory {
437            dialog.set_current_folder(dir);
438        }
439        dialog
440    }
441
442    fn build_open_dialog(options: &OpenFileOptions, multiple: bool) -> gtk::FileChooserNative {
443        let default_title = if multiple { "Open Files" } else { "Open File" };
444        let dialog = create_file_chooser(
445            options.title.as_deref().unwrap_or(default_title),
446            gtk::FileChooserAction::Open,
447            "Open",
448            &options.filters,
449            options.starting_directory.as_ref(),
450        );
451        if multiple {
452            dialog.set_select_multiple(true);
453        }
454        dialog
455    }
456
457    fn build_save_dialog(options: &SaveFileOptions) -> gtk::FileChooserNative {
458        let dialog = create_file_chooser(
459            options.title.as_deref().unwrap_or("Save File"),
460            gtk::FileChooserAction::Save,
461            "Save",
462            &options.filters,
463            options.starting_directory.as_ref(),
464        );
465        dialog.set_do_overwrite_confirmation(true);
466        if let Some(name) = &options.default_name {
467            dialog.set_current_name(name);
468        }
469        dialog
470    }
471
472    fn build_folder_dialog(options: &PickFolderOptions) -> gtk::FileChooserNative {
473        create_file_chooser(
474            options.title.as_deref().unwrap_or("Select Folder"),
475            gtk::FileChooserAction::SelectFolder,
476            "Select",
477            &[],
478            options.starting_directory.as_ref(),
479        )
480    }
481
482    fn run_native_dialog_async<T: 'static>(
483        dialog: gtk::FileChooserNative,
484        on_accept: impl FnOnce(&gtk::FileChooserNative) -> T + 'static,
485        empty: impl FnOnce() -> T + 'static,
486        callback: impl FnOnce(T) + 'static,
487    ) {
488        if !gtk::is_initialized() {
489            callback(empty());
490            return;
491        }
492        // Keep a strong handle to the native dialog until the user picks or cancels,
493        // and use non-blocking show() + connect_response so we never enter a nested
494        // gtk::dialog::run() loop while AppRuntime event borrows are active.
495        let keep_dlg = Rc::new(RefCell::new(Some(dialog.clone())));
496        let accept_cell = Rc::new(RefCell::new(Some(on_accept)));
497        let empty_cell = Rc::new(RefCell::new(Some(empty)));
498        let cb_cell = Rc::new(RefCell::new(Some(callback)));
499
500        let keep_dlg_cb = keep_dlg.clone();
501        dialog.connect_response(move |dlg, response| {
502            let value = if response == gtk::ResponseType::Accept {
503                accept_cell.borrow_mut().take().map(|f| f(dlg))
504            } else {
505                empty_cell.borrow_mut().take().map(|f| f())
506            };
507            dlg.hide();
508            dlg.destroy();
509            let _ = keep_dlg_cb.borrow_mut().take();
510            if let (Some(v), Some(cb)) = (value, cb_cell.borrow_mut().take()) {
511                cb(v);
512                crate::gtk_window::post_platform_event(crate::events::PlatformEvent::AnimationTick);
513            }
514        });
515        dialog.show();
516    }
517
518    pub fn open_file(options: &OpenFileOptions) -> Option<PathBuf> {
519        if !gtk::is_initialized() {
520            return None;
521        }
522        let dialog = build_open_dialog(options, false);
523        let response = dialog.run();
524        if response == gtk::ResponseType::Accept {
525            dialog.filename()
526        } else {
527            None
528        }
529    }
530
531    pub fn open_multiple_files(options: &OpenFileOptions) -> Vec<PathBuf> {
532        if !gtk::is_initialized() {
533            return Vec::new();
534        }
535        let dialog = build_open_dialog(options, true);
536        let response = dialog.run();
537        if response == gtk::ResponseType::Accept {
538            dialog.filenames()
539        } else {
540            Vec::new()
541        }
542    }
543
544    pub fn save_file(options: &SaveFileOptions) -> Option<PathBuf> {
545        if !gtk::is_initialized() {
546            return None;
547        }
548        let dialog = build_save_dialog(options);
549        let response = dialog.run();
550        if response == gtk::ResponseType::Accept {
551            dialog.filename()
552        } else {
553            None
554        }
555    }
556
557    pub fn pick_folder(options: &PickFolderOptions) -> Option<PathBuf> {
558        if !gtk::is_initialized() {
559            return None;
560        }
561        let dialog = build_folder_dialog(options);
562        let response = dialog.run();
563        if response == gtk::ResponseType::Accept {
564            dialog.filename()
565        } else {
566            None
567        }
568    }
569
570    pub fn open_file_async<F: FnOnce(Option<PathBuf>) + 'static>(
571        options: &OpenFileOptions,
572        callback: F,
573    ) {
574        if !gtk::is_initialized() {
575            callback(None);
576            return;
577        }
578        run_native_dialog_async(
579            build_open_dialog(options, false),
580            |dlg| dlg.filename(),
581            || None,
582            callback,
583        );
584    }
585
586    pub fn open_multiple_files_async<F: FnOnce(Vec<PathBuf>) + 'static>(
587        options: &OpenFileOptions,
588        callback: F,
589    ) {
590        if !gtk::is_initialized() {
591            callback(Vec::new());
592            return;
593        }
594        run_native_dialog_async(
595            build_open_dialog(options, true),
596            |dlg| dlg.filenames(),
597            Vec::new,
598            callback,
599        );
600    }
601
602    pub fn save_file_async<F: FnOnce(Option<PathBuf>) + 'static>(
603        options: &SaveFileOptions,
604        callback: F,
605    ) {
606        if !gtk::is_initialized() {
607            callback(None);
608            return;
609        }
610        run_native_dialog_async(
611            build_save_dialog(options),
612            |dlg| dlg.filename(),
613            || None,
614            callback,
615        );
616    }
617
618    pub fn pick_folder_async<F: FnOnce(Option<PathBuf>) + 'static>(
619        options: &PickFolderOptions,
620        callback: F,
621    ) {
622        if !gtk::is_initialized() {
623            callback(None);
624            return;
625        }
626        run_native_dialog_async(
627            build_folder_dialog(options),
628            |dlg| dlg.filename(),
629            || None,
630            callback,
631        );
632    }
633
634    pub fn show_message_box(
635        title: &str,
636        message: &str,
637        box_type: MessageBoxType,
638        buttons: MessageBoxButtons,
639    ) -> MessageBoxResult {
640        if !gtk::is_initialized() {
641            return MessageBoxResult::Ok;
642        }
643        let message_type = match box_type {
644            MessageBoxType::Info => gtk::MessageType::Info,
645            MessageBoxType::Warning => gtk::MessageType::Warning,
646            MessageBoxType::Error => gtk::MessageType::Error,
647            MessageBoxType::Question => gtk::MessageType::Question,
648        };
649        let buttons_type = match buttons {
650            MessageBoxButtons::Ok => gtk::ButtonsType::Ok,
651            MessageBoxButtons::OkCancel => gtk::ButtonsType::OkCancel,
652            MessageBoxButtons::YesNo => gtk::ButtonsType::YesNo,
653            MessageBoxButtons::YesNoCancel => gtk::ButtonsType::None,
654        };
655        let dialog = gtk::MessageDialog::new(
656            active_parent_window().as_ref(),
657            gtk::DialogFlags::MODAL,
658            message_type,
659            buttons_type,
660            message,
661        );
662        dialog.set_title(title);
663        if buttons == MessageBoxButtons::YesNoCancel {
664            dialog.add_button("Yes", gtk::ResponseType::Yes);
665            dialog.add_button("No", gtk::ResponseType::No);
666            dialog.add_button("Cancel", gtk::ResponseType::Cancel);
667        }
668        let response = dialog.run();
669        dialog.close();
670        match response {
671            gtk::ResponseType::Ok | gtk::ResponseType::Accept => MessageBoxResult::Ok,
672            gtk::ResponseType::Yes => MessageBoxResult::Yes,
673            gtk::ResponseType::No => MessageBoxResult::No,
674            _ => MessageBoxResult::Cancel,
675        }
676    }
677
678    fn apply_filters(dialog: &gtk::FileChooserNative, filters: &[DialogFilter]) {
679        for f in filters {
680            let filter = gtk::FileFilter::new();
681            filter.set_name(Some(&f.name));
682            for ext in &f.extensions {
683                filter.add_pattern(&format!("*.{}", ext));
684                filter.add_pattern(&format!("*.{}", ext.to_uppercase()));
685            }
686            dialog.add_filter(filter);
687        }
688    }
689}
690
691#[cfg(all(target_os = "linux", not(feature = "gtk-compat")))]
692mod linux_backend {
693    use super::*;
694    use std::path::PathBuf;
695
696    pub fn open_file(_options: &OpenFileOptions) -> Option<PathBuf> {
697        None
698    }
699
700    pub fn open_multiple_files(_options: &OpenFileOptions) -> Vec<PathBuf> {
701        Vec::new()
702    }
703
704    pub fn save_file(_options: &SaveFileOptions) -> Option<PathBuf> {
705        None
706    }
707
708    pub fn pick_folder(_options: &PickFolderOptions) -> Option<PathBuf> {
709        None
710    }
711
712    pub fn show_message_box(
713        _title: &str,
714        _message: &str,
715        _box_type: MessageBoxType,
716        _buttons: MessageBoxButtons,
717    ) -> MessageBoxResult {
718        MessageBoxResult::Ok
719    }
720}
721
722#[cfg(windows)]
723mod windows_backend {
724    use super::*;
725    use std::path::PathBuf;
726    use windows_sys::Win32::Foundation::HWND;
727    use windows_sys::Win32::UI::Controls::Dialogs::{
728        GetOpenFileNameW, GetSaveFileNameW, OFN_ALLOWMULTISELECT, OFN_EXPLORER, OFN_FILEMUSTEXIST,
729        OFN_OVERWRITEPROMPT, OFN_PATHMUSTEXIST, OPENFILENAMEW,
730    };
731    use windows_sys::Win32::UI::WindowsAndMessaging::{
732        MessageBoxW, IDCANCEL, IDNO, IDOK, IDYES, MB_ICONERROR, MB_ICONINFORMATION,
733        MB_ICONQUESTION, MB_ICONWARNING, MB_OK, MB_OKCANCEL, MB_YESNO, MB_YESNOCANCEL,
734    };
735
736    pub fn open_file(options: &OpenFileOptions) -> Option<PathBuf> {
737        let mut paths = run_open_dialog(options, false);
738        paths.pop()
739    }
740
741    pub fn open_multiple_files(options: &OpenFileOptions) -> Vec<PathBuf> {
742        run_open_dialog(options, true)
743    }
744
745    fn run_open_dialog(options: &OpenFileOptions, multiple: bool) -> Vec<PathBuf> {
746        unsafe {
747            let mut buf = vec![0u16; 65536];
748            let filter = build_filter_string(&options.filters);
749            let title = options.title.as_ref().map(|t| {
750                t.encode_utf16()
751                    .chain(std::iter::once(0))
752                    .collect::<Vec<u16>>()
753            });
754            let dir = options
755                .starting_directory
756                .as_ref()
757                .and_then(|d| d.to_str())
758                .map(|s| {
759                    s.encode_utf16()
760                        .chain(std::iter::once(0))
761                        .collect::<Vec<u16>>()
762                });
763
764            let mut flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
765            if multiple {
766                flags |= OFN_ALLOWMULTISELECT;
767            }
768
769            let mut ofn: OPENFILENAMEW = std::mem::zeroed();
770            ofn.lStructSize = std::mem::size_of::<OPENFILENAMEW>() as u32;
771            ofn.hwndOwner = 0 as HWND;
772            ofn.lpstrFilter = filter.as_ptr();
773            ofn.lpstrFile = buf.as_mut_ptr();
774            ofn.nMaxFile = buf.len() as u32;
775            ofn.lpstrInitialDir = dir.as_ref().map(|d| d.as_ptr()).unwrap_or(std::ptr::null());
776            ofn.lpstrTitle = title
777                .as_ref()
778                .map(|t| t.as_ptr())
779                .unwrap_or(std::ptr::null());
780            ofn.Flags = flags;
781
782            if GetOpenFileNameW(&mut ofn) == 0 {
783                return Vec::new();
784            }
785
786            parse_open_file_buffer(&buf)
787        }
788    }
789
790    pub fn save_file(options: &SaveFileOptions) -> Option<PathBuf> {
791        unsafe {
792            let mut buf = vec![0u16; 4096];
793            if let Some(default_name) = &options.default_name {
794                let name_wide: Vec<u16> = default_name.encode_utf16().collect();
795                let len = name_wide.len().min(buf.len().saturating_sub(1));
796                buf[..len].copy_from_slice(&name_wide[..len]);
797            }
798
799            let filter = build_filter_string(&options.filters);
800            let title = options.title.as_ref().map(|t| {
801                t.encode_utf16()
802                    .chain(std::iter::once(0))
803                    .collect::<Vec<u16>>()
804            });
805            let dir = options
806                .starting_directory
807                .as_ref()
808                .and_then(|d| d.to_str())
809                .map(|s| {
810                    s.encode_utf16()
811                        .chain(std::iter::once(0))
812                        .collect::<Vec<u16>>()
813                });
814
815            let mut ofn: OPENFILENAMEW = std::mem::zeroed();
816            ofn.lStructSize = std::mem::size_of::<OPENFILENAMEW>() as u32;
817            ofn.hwndOwner = 0 as HWND;
818            ofn.lpstrFilter = filter.as_ptr();
819            ofn.lpstrFile = buf.as_mut_ptr();
820            ofn.nMaxFile = buf.len() as u32;
821            ofn.lpstrInitialDir = dir.as_ref().map(|d| d.as_ptr()).unwrap_or(std::ptr::null());
822            ofn.lpstrTitle = title
823                .as_ref()
824                .map(|t| t.as_ptr())
825                .unwrap_or(std::ptr::null());
826            ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT;
827
828            if GetSaveFileNameW(&mut ofn) == 0 {
829                return None;
830            }
831
832            let end = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
833            let path_str = String::from_utf16_lossy(&buf[..end]);
834            if path_str.is_empty() {
835                None
836            } else {
837                Some(PathBuf::from(path_str))
838            }
839        }
840    }
841
842    pub fn pick_folder(options: &PickFolderOptions) -> Option<PathBuf> {
843        // Fallback folder picker via Windows standard directory selection
844        let mut open_opt = OpenFileOptions::new();
845        open_opt.title = options.title.clone();
846        open_opt.starting_directory = options.starting_directory.clone();
847        open_file(&open_opt).and_then(|p| {
848            if p.is_dir() {
849                Some(p)
850            } else {
851                p.parent().map(|d| d.to_path_buf())
852            }
853        })
854    }
855
856    pub fn show_message_box(
857        title: &str,
858        message: &str,
859        box_type: MessageBoxType,
860        buttons: MessageBoxButtons,
861    ) -> MessageBoxResult {
862        unsafe {
863            let wide_msg: Vec<u16> = message.encode_utf16().chain(std::iter::once(0)).collect();
864            let wide_title: Vec<u16> = title.encode_utf16().chain(std::iter::once(0)).collect();
865
866            let mut flags = match box_type {
867                MessageBoxType::Info => MB_ICONINFORMATION,
868                MessageBoxType::Warning => MB_ICONWARNING,
869                MessageBoxType::Error => MB_ICONERROR,
870                MessageBoxType::Question => MB_ICONQUESTION,
871            };
872
873            flags |= match buttons {
874                MessageBoxButtons::Ok => MB_OK,
875                MessageBoxButtons::OkCancel => MB_OKCANCEL,
876                MessageBoxButtons::YesNo => MB_YESNO,
877                MessageBoxButtons::YesNoCancel => MB_YESNOCANCEL,
878            };
879
880            let res = MessageBoxW(0 as HWND, wide_msg.as_ptr(), wide_title.as_ptr(), flags);
881            match res {
882                IDOK => MessageBoxResult::Ok,
883                IDCANCEL => MessageBoxResult::Cancel,
884                IDYES => MessageBoxResult::Yes,
885                IDNO => MessageBoxResult::No,
886                _ => MessageBoxResult::Ok,
887            }
888        }
889    }
890
891    fn build_filter_string(filters: &[DialogFilter]) -> Vec<u16> {
892        let mut out = Vec::new();
893        for f in filters {
894            out.extend(f.name.encode_utf16());
895            out.push(0);
896            let exts: Vec<String> = f.extensions.iter().map(|e| format!("*.{}", e)).collect();
897            let ext_str = exts.join(";");
898            out.extend(ext_str.encode_utf16());
899            out.push(0);
900        }
901        if filters.is_empty() {
902            out.extend("All Files (*.*)".encode_utf16());
903            out.push(0);
904            out.extend("*.*".encode_utf16());
905            out.push(0);
906        }
907        out.push(0);
908        out
909    }
910
911    fn parse_open_file_buffer(buf: &[u16]) -> Vec<PathBuf> {
912        let mut chunks = Vec::new();
913        let mut start = 0;
914        for i in 0..buf.len() {
915            if buf[i] == 0 {
916                if start == i {
917                    break;
918                }
919                chunks.push(String::from_utf16_lossy(&buf[start..i]));
920                start = i + 1;
921            }
922        }
923        if chunks.is_empty() {
924            return Vec::new();
925        }
926        if chunks.len() == 1 {
927            return vec![PathBuf::from(&chunks[0])];
928        }
929        let base_dir = PathBuf::from(&chunks[0]);
930        chunks[1..]
931            .iter()
932            .map(|filename| base_dir.join(filename))
933            .collect()
934    }
935}
936
937#[cfg(target_os = "macos")]
938mod macos_backend {
939    use super::*;
940    use std::ffi::{c_char, c_void, CString};
941    use std::path::PathBuf;
942
943    #[link(name = "objc")]
944    extern "C" {
945        fn objc_getClass(name: *const c_char) -> *mut c_void;
946        fn sel_registerName(name: *const c_char) -> *mut c_void;
947        fn objc_msgSend();
948    }
949
950    #[link(name = "AppKit", kind = "framework")]
951    extern "C" {
952        static NSApp: *mut c_void;
953    }
954
955    unsafe fn is_appkit_main_thread_ready() -> bool {
956        if NSApp.is_null() {
957            return false;
958        }
959        let thread_cls = objc_getClass(b"NSThread\0".as_ptr() as *const c_char);
960        if thread_cls.is_null() {
961            return false;
962        }
963        let is_main_sel = sel_registerName(b"isMainThread\0".as_ptr() as *const c_char);
964        let msg_bool: unsafe extern "C" fn(*mut c_void, *mut c_void) -> i8 =
965            std::mem::transmute(objc_msgSend as *const ());
966        msg_bool(thread_cls, is_main_sel) != 0
967    }
968
969    pub fn open_file(options: &OpenFileOptions) -> Option<PathBuf> {
970        let mut files = run_open_panel(options, false);
971        files.pop()
972    }
973
974    pub fn open_multiple_files(options: &OpenFileOptions) -> Vec<PathBuf> {
975        run_open_panel(options, true)
976    }
977
978    fn run_open_panel(options: &OpenFileOptions, multiple: bool) -> Vec<PathBuf> {
979        unsafe {
980            if !is_appkit_main_thread_ready() {
981                return Vec::new();
982            }
983            let panel_cls = objc_getClass(b"NSOpenPanel\0".as_ptr() as *const c_char);
984            if panel_cls.is_null() {
985                return Vec::new();
986            }
987            let open_sel = sel_registerName(b"openPanel\0".as_ptr() as *const c_char);
988            let msg_open: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
989                std::mem::transmute(objc_msgSend as *const ());
990            let panel = msg_open(panel_cls, open_sel);
991            if panel.is_null() {
992                return Vec::new();
993            }
994
995            let set_files_sel = sel_registerName(b"setCanChooseFiles:\0".as_ptr() as *const c_char);
996            let msg_set_bool: unsafe extern "C" fn(*mut c_void, *mut c_void, bool) =
997                std::mem::transmute(objc_msgSend as *const ());
998            msg_set_bool(panel, set_files_sel, true);
999
1000            let set_dirs_sel =
1001                sel_registerName(b"setCanChooseDirectories:\0".as_ptr() as *const c_char);
1002            msg_set_bool(panel, set_dirs_sel, false);
1003
1004            let set_multi_sel =
1005                sel_registerName(b"setAllowsMultipleSelection:\0".as_ptr() as *const c_char);
1006            msg_set_bool(panel, set_multi_sel, multiple);
1007
1008            if let Some(title) = &options.title {
1009                let set_title_sel = sel_registerName(b"setTitle:\0".as_ptr() as *const c_char);
1010                let ns_title = ns_string(title);
1011                let msg_set_title: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
1012                    std::mem::transmute(objc_msgSend as *const ());
1013                msg_set_title(panel, set_title_sel, ns_title);
1014            }
1015
1016            let run_modal_sel = sel_registerName(b"runModal\0".as_ptr() as *const c_char);
1017            let msg_run: unsafe extern "C" fn(*mut c_void, *mut c_void) -> isize =
1018                std::mem::transmute(objc_msgSend as *const ());
1019            let response = msg_run(panel, run_modal_sel);
1020
1021            // NSModalResponseOK is 1
1022            if response != 1 {
1023                return Vec::new();
1024            }
1025
1026            let urls_sel = sel_registerName(b"URLs\0".as_ptr() as *const c_char);
1027            let msg_urls: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1028                std::mem::transmute(objc_msgSend as *const ());
1029            let urls_array = msg_urls(panel, urls_sel);
1030            parse_ns_array_urls(urls_array)
1031        }
1032    }
1033
1034    pub fn save_file(options: &SaveFileOptions) -> Option<PathBuf> {
1035        unsafe {
1036            if !is_appkit_main_thread_ready() {
1037                return None;
1038            }
1039            let panel_cls = objc_getClass(b"NSSavePanel\0".as_ptr() as *const c_char);
1040            if panel_cls.is_null() {
1041                return None;
1042            }
1043            let save_sel = sel_registerName(b"savePanel\0".as_ptr() as *const c_char);
1044            let msg_save: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1045                std::mem::transmute(objc_msgSend as *const ());
1046            let panel = msg_save(panel_cls, save_sel);
1047            if panel.is_null() {
1048                return None;
1049            }
1050
1051            if let Some(title) = &options.title {
1052                let set_title_sel = sel_registerName(b"setTitle:\0".as_ptr() as *const c_char);
1053                let ns_title = ns_string(title);
1054                let msg_set_str: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
1055                    std::mem::transmute(objc_msgSend as *const ());
1056                msg_set_str(panel, set_title_sel, ns_title);
1057            }
1058
1059            if let Some(name) = &options.default_name {
1060                let set_name_sel =
1061                    sel_registerName(b"setNameFieldStringValue:\0".as_ptr() as *const c_char);
1062                let ns_name = ns_string(name);
1063                let msg_set_str: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
1064                    std::mem::transmute(objc_msgSend as *const ());
1065                msg_set_str(panel, set_name_sel, ns_name);
1066            }
1067
1068            let run_modal_sel = sel_registerName(b"runModal\0".as_ptr() as *const c_char);
1069            let msg_run: unsafe extern "C" fn(*mut c_void, *mut c_void) -> isize =
1070                std::mem::transmute(objc_msgSend as *const ());
1071            let response = msg_run(panel, run_modal_sel);
1072
1073            if response != 1 {
1074                return None;
1075            }
1076
1077            let url_sel = sel_registerName(b"URL\0".as_ptr() as *const c_char);
1078            let msg_url: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1079                std::mem::transmute(objc_msgSend as *const ());
1080            let url = msg_url(panel, url_sel);
1081            path_from_ns_url(url)
1082        }
1083    }
1084
1085    pub fn pick_folder(options: &PickFolderOptions) -> Option<PathBuf> {
1086        unsafe {
1087            if !is_appkit_main_thread_ready() {
1088                return None;
1089            }
1090            let panel_cls = objc_getClass(b"NSOpenPanel\0".as_ptr() as *const c_char);
1091            if panel_cls.is_null() {
1092                return None;
1093            }
1094            let open_sel = sel_registerName(b"openPanel\0".as_ptr() as *const c_char);
1095            let msg_open: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1096                std::mem::transmute(objc_msgSend as *const ());
1097            let panel = msg_open(panel_cls, open_sel);
1098            if panel.is_null() {
1099                return None;
1100            }
1101
1102            let set_files_sel = sel_registerName(b"setCanChooseFiles:\0".as_ptr() as *const c_char);
1103            let msg_set_bool: unsafe extern "C" fn(*mut c_void, *mut c_void, bool) =
1104                std::mem::transmute(objc_msgSend as *const ());
1105            msg_set_bool(panel, set_files_sel, false);
1106
1107            let set_dirs_sel =
1108                sel_registerName(b"setCanChooseDirectories:\0".as_ptr() as *const c_char);
1109            msg_set_bool(panel, set_dirs_sel, true);
1110
1111            let set_multi_sel =
1112                sel_registerName(b"setAllowsMultipleSelection:\0".as_ptr() as *const c_char);
1113            msg_set_bool(panel, set_multi_sel, false);
1114
1115            if let Some(title) = &options.title {
1116                let set_title_sel = sel_registerName(b"setTitle:\0".as_ptr() as *const c_char);
1117                let ns_title = ns_string(title);
1118                let msg_set_title: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
1119                    std::mem::transmute(objc_msgSend as *const ());
1120                msg_set_title(panel, set_title_sel, ns_title);
1121            }
1122
1123            let run_modal_sel = sel_registerName(b"runModal\0".as_ptr() as *const c_char);
1124            let msg_run: unsafe extern "C" fn(*mut c_void, *mut c_void) -> isize =
1125                std::mem::transmute(objc_msgSend as *const ());
1126            let response = msg_run(panel, run_modal_sel);
1127
1128            if response != 1 {
1129                return None;
1130            }
1131
1132            let url_sel = sel_registerName(b"URL\0".as_ptr() as *const c_char);
1133            let msg_url: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1134                std::mem::transmute(objc_msgSend as *const ());
1135            let url = msg_url(panel, url_sel);
1136            path_from_ns_url(url)
1137        }
1138    }
1139
1140    pub fn show_message_box(
1141        title: &str,
1142        message: &str,
1143        _box_type: MessageBoxType,
1144        buttons: MessageBoxButtons,
1145    ) -> MessageBoxResult {
1146        unsafe {
1147            if !is_appkit_main_thread_ready() {
1148                return MessageBoxResult::Ok;
1149            }
1150            let alert_cls = objc_getClass(b"NSAlert\0".as_ptr() as *const c_char);
1151            if alert_cls.is_null() {
1152                return MessageBoxResult::Ok;
1153            }
1154            let alloc_sel = sel_registerName(b"alloc\0".as_ptr() as *const c_char);
1155            let init_sel = sel_registerName(b"init\0".as_ptr() as *const c_char);
1156            let msg_alloc: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1157                std::mem::transmute(objc_msgSend as *const ());
1158            let alert_inst = msg_alloc(alert_cls, alloc_sel);
1159            let alert = msg_alloc(alert_inst, init_sel);
1160
1161            let set_msg_sel = sel_registerName(b"setMessageText:\0".as_ptr() as *const c_char);
1162            let ns_title = ns_string(title);
1163            let msg_set_str: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
1164                std::mem::transmute(objc_msgSend as *const ());
1165            msg_set_str(alert, set_msg_sel, ns_title);
1166
1167            let set_info_sel = sel_registerName(b"setInformativeText:\0".as_ptr() as *const c_char);
1168            let ns_msg = ns_string(message);
1169            msg_set_str(alert, set_info_sel, ns_msg);
1170
1171            let add_btn_sel = sel_registerName(b"addButtonWithTitle:\0".as_ptr() as *const c_char);
1172            match buttons {
1173                MessageBoxButtons::Ok => {
1174                    msg_set_str(alert, add_btn_sel, ns_string("OK"));
1175                }
1176                MessageBoxButtons::OkCancel => {
1177                    msg_set_str(alert, add_btn_sel, ns_string("OK"));
1178                    msg_set_str(alert, add_btn_sel, ns_string("Cancel"));
1179                }
1180                MessageBoxButtons::YesNo => {
1181                    msg_set_str(alert, add_btn_sel, ns_string("Yes"));
1182                    msg_set_str(alert, add_btn_sel, ns_string("No"));
1183                }
1184                MessageBoxButtons::YesNoCancel => {
1185                    msg_set_str(alert, add_btn_sel, ns_string("Yes"));
1186                    msg_set_str(alert, add_btn_sel, ns_string("No"));
1187                    msg_set_str(alert, add_btn_sel, ns_string("Cancel"));
1188                }
1189            }
1190
1191            let run_modal_sel = sel_registerName(b"runModal\0".as_ptr() as *const c_char);
1192            let msg_run: unsafe extern "C" fn(*mut c_void, *mut c_void) -> isize =
1193                std::mem::transmute(objc_msgSend as *const ());
1194            let response = msg_run(alert, run_modal_sel);
1195
1196            // First button added returns 1000, second 1001, third 1002
1197            match buttons {
1198                MessageBoxButtons::Ok => MessageBoxResult::Ok,
1199                MessageBoxButtons::OkCancel => {
1200                    if response == 1000 {
1201                        MessageBoxResult::Ok
1202                    } else {
1203                        MessageBoxResult::Cancel
1204                    }
1205                }
1206                MessageBoxButtons::YesNo => {
1207                    if response == 1000 {
1208                        MessageBoxResult::Yes
1209                    } else {
1210                        MessageBoxResult::No
1211                    }
1212                }
1213                MessageBoxButtons::YesNoCancel => {
1214                    if response == 1000 {
1215                        MessageBoxResult::Yes
1216                    } else if response == 1001 {
1217                        MessageBoxResult::No
1218                    } else {
1219                        MessageBoxResult::Cancel
1220                    }
1221                }
1222            }
1223        }
1224    }
1225
1226    unsafe fn ns_string(s: &str) -> *mut c_void {
1227        let cls = objc_getClass(b"NSString\0".as_ptr() as *const c_char);
1228        let sel = sel_registerName(b"stringWithUTF8String:\0".as_ptr() as *const c_char);
1229        let cstr = CString::new(s).unwrap_or_default();
1230        let msg: unsafe extern "C" fn(*mut c_void, *mut c_void, *const c_char) -> *mut c_void =
1231            std::mem::transmute(objc_msgSend as *const ());
1232        msg(cls, sel, cstr.as_ptr())
1233    }
1234
1235    unsafe fn path_from_ns_url(url: *mut c_void) -> Option<PathBuf> {
1236        if url.is_null() {
1237            return None;
1238        }
1239        let path_sel = sel_registerName(b"path\0".as_ptr() as *const c_char);
1240        let msg_path: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1241            std::mem::transmute(objc_msgSend as *const ());
1242        let path_str = msg_path(url, path_sel);
1243        if path_str.is_null() {
1244            return None;
1245        }
1246        let utf8_sel = sel_registerName(b"UTF8String\0".as_ptr() as *const c_char);
1247        let msg_utf8: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *const c_char =
1248            std::mem::transmute(objc_msgSend as *const ());
1249        let c_str = msg_utf8(path_str, utf8_sel);
1250        if c_str.is_null() {
1251            return None;
1252        }
1253        let slice = std::ffi::CStr::from_ptr(c_str).to_str().ok()?;
1254        Some(PathBuf::from(slice))
1255    }
1256
1257    unsafe fn parse_ns_array_urls(array: *mut c_void) -> Vec<PathBuf> {
1258        if array.is_null() {
1259            return Vec::new();
1260        }
1261        let count_sel = sel_registerName(b"count\0".as_ptr() as *const c_char);
1262        let msg_count: unsafe extern "C" fn(*mut c_void, *mut c_void) -> usize =
1263            std::mem::transmute(objc_msgSend as *const ());
1264        let count = msg_count(array, count_sel);
1265        let obj_at_sel = sel_registerName(b"objectAtIndex:\0".as_ptr() as *const c_char);
1266        let msg_obj: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
1267            std::mem::transmute(objc_msgSend as *const ());
1268
1269        let mut out = Vec::with_capacity(count);
1270        for i in 0..count {
1271            let url = msg_obj(array, obj_at_sel, i);
1272            if let Some(path) = path_from_ns_url(url) {
1273                out.push(path);
1274            }
1275        }
1276        out
1277    }
1278}