1use std::path::PathBuf;
11#[cfg(any(test, feature = "test-internals"))]
12use std::sync::Mutex;
13
14#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct DialogFilter {
17 pub name: String,
18 pub extensions: Vec<String>,
19}
20
21impl DialogFilter {
22 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#[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#[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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
129pub enum MessageBoxType {
130 #[default]
131 Info,
132 Warning,
133 Error,
134 Question,
135}
136
137#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
139pub enum MessageBoxButtons {
140 #[default]
141 Ok,
142 OkCancel,
143 YesNo,
144 YesNoCancel,
145}
146
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149pub enum MessageBoxResult {
150 Ok,
151 Cancel,
152 Yes,
153 No,
154}
155
156#[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#[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
190pub 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
215pub 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
240pub 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
265pub 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
290pub 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
320pub 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
340pub 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
360pub 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
380pub 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(>k::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 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: >k::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 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 extern "C" {
944 fn objc_getClass(name: *const c_char) -> *mut c_void;
945 fn sel_registerName(name: *const c_char) -> *mut c_void;
946 fn objc_msgSend(receiver: *mut c_void, op: *mut c_void, ...) -> *mut c_void;
947 }
948
949 pub fn open_file(options: &OpenFileOptions) -> Option<PathBuf> {
950 let mut files = run_open_panel(options, false);
951 files.pop()
952 }
953
954 pub fn open_multiple_files(options: &OpenFileOptions) -> Vec<PathBuf> {
955 run_open_panel(options, true)
956 }
957
958 fn run_open_panel(options: &OpenFileOptions, multiple: bool) -> Vec<PathBuf> {
959 unsafe {
960 let panel_cls = objc_getClass(b"NSOpenPanel\0".as_ptr() as *const c_char);
961 if panel_cls.is_null() {
962 return Vec::new();
963 }
964 let open_sel = sel_registerName(b"openPanel\0".as_ptr() as *const c_char);
965 let msg_open: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
966 std::mem::transmute(objc_msgSend as *const ());
967 let panel = msg_open(panel_cls, open_sel);
968 if panel.is_null() {
969 return Vec::new();
970 }
971
972 let set_files_sel = sel_registerName(b"setCanChooseFiles:\0".as_ptr() as *const c_char);
973 let msg_set_bool: unsafe extern "C" fn(*mut c_void, *mut c_void, bool) =
974 std::mem::transmute(objc_msgSend as *const ());
975 msg_set_bool(panel, set_files_sel, true);
976
977 let set_dirs_sel =
978 sel_registerName(b"setCanChooseDirectories:\0".as_ptr() as *const c_char);
979 msg_set_bool(panel, set_dirs_sel, false);
980
981 let set_multi_sel =
982 sel_registerName(b"setAllowsMultipleSelection:\0".as_ptr() as *const c_char);
983 msg_set_bool(panel, set_multi_sel, multiple);
984
985 if let Some(title) = &options.title {
986 let set_title_sel = sel_registerName(b"setTitle:\0".as_ptr() as *const c_char);
987 let ns_title = ns_string(title);
988 let msg_set_title: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
989 std::mem::transmute(objc_msgSend as *const ());
990 msg_set_title(panel, set_title_sel, ns_title);
991 }
992
993 let run_modal_sel = sel_registerName(b"runModal\0".as_ptr() as *const c_char);
994 let msg_run: unsafe extern "C" fn(*mut c_void, *mut c_void) -> isize =
995 std::mem::transmute(objc_msgSend as *const ());
996 let response = msg_run(panel, run_modal_sel);
997
998 if response != 1 {
1000 return Vec::new();
1001 }
1002
1003 let urls_sel = sel_registerName(b"URLs\0".as_ptr() as *const c_char);
1004 let msg_urls: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1005 std::mem::transmute(objc_msgSend as *const ());
1006 let urls_array = msg_urls(panel, urls_sel);
1007 parse_ns_array_urls(urls_array)
1008 }
1009 }
1010
1011 pub fn save_file(options: &SaveFileOptions) -> Option<PathBuf> {
1012 unsafe {
1013 let panel_cls = objc_getClass(b"NSSavePanel\0".as_ptr() as *const c_char);
1014 if panel_cls.is_null() {
1015 return None;
1016 }
1017 let save_sel = sel_registerName(b"savePanel\0".as_ptr() as *const c_char);
1018 let msg_save: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1019 std::mem::transmute(objc_msgSend as *const ());
1020 let panel = msg_save(panel_cls, save_sel);
1021 if panel.is_null() {
1022 return None;
1023 }
1024
1025 if let Some(title) = &options.title {
1026 let set_title_sel = sel_registerName(b"setTitle:\0".as_ptr() as *const c_char);
1027 let ns_title = ns_string(title);
1028 let msg_set_str: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
1029 std::mem::transmute(objc_msgSend as *const ());
1030 msg_set_str(panel, set_title_sel, ns_title);
1031 }
1032
1033 if let Some(name) = &options.default_name {
1034 let set_name_sel =
1035 sel_registerName(b"setNameFieldStringValue:\0".as_ptr() as *const c_char);
1036 let ns_name = ns_string(name);
1037 let msg_set_str: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
1038 std::mem::transmute(objc_msgSend as *const ());
1039 msg_set_str(panel, set_name_sel, ns_name);
1040 }
1041
1042 let run_modal_sel = sel_registerName(b"runModal\0".as_ptr() as *const c_char);
1043 let msg_run: unsafe extern "C" fn(*mut c_void, *mut c_void) -> isize =
1044 std::mem::transmute(objc_msgSend as *const ());
1045 let response = msg_run(panel, run_modal_sel);
1046
1047 if response != 1 {
1048 return None;
1049 }
1050
1051 let url_sel = sel_registerName(b"URL\0".as_ptr() as *const c_char);
1052 let msg_url: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1053 std::mem::transmute(objc_msgSend as *const ());
1054 let url = msg_url(panel, url_sel);
1055 path_from_ns_url(url)
1056 }
1057 }
1058
1059 pub fn pick_folder(options: &PickFolderOptions) -> Option<PathBuf> {
1060 unsafe {
1061 let panel_cls = objc_getClass(b"NSOpenPanel\0".as_ptr() as *const c_char);
1062 if panel_cls.is_null() {
1063 return None;
1064 }
1065 let open_sel = sel_registerName(b"openPanel\0".as_ptr() as *const c_char);
1066 let msg_open: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1067 std::mem::transmute(objc_msgSend as *const ());
1068 let panel = msg_open(panel_cls, open_sel);
1069 if panel.is_null() {
1070 return None;
1071 }
1072
1073 let set_files_sel = sel_registerName(b"setCanChooseFiles:\0".as_ptr() as *const c_char);
1074 let msg_set_bool: unsafe extern "C" fn(*mut c_void, *mut c_void, bool) =
1075 std::mem::transmute(objc_msgSend as *const ());
1076 msg_set_bool(panel, set_files_sel, false);
1077
1078 let set_dirs_sel =
1079 sel_registerName(b"setCanChooseDirectories:\0".as_ptr() as *const c_char);
1080 msg_set_bool(panel, set_dirs_sel, true);
1081
1082 let set_multi_sel =
1083 sel_registerName(b"setAllowsMultipleSelection:\0".as_ptr() as *const c_char);
1084 msg_set_bool(panel, set_multi_sel, false);
1085
1086 if let Some(title) = &options.title {
1087 let set_title_sel = sel_registerName(b"setTitle:\0".as_ptr() as *const c_char);
1088 let ns_title = ns_string(title);
1089 let msg_set_title: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
1090 std::mem::transmute(objc_msgSend as *const ());
1091 msg_set_title(panel, set_title_sel, ns_title);
1092 }
1093
1094 let run_modal_sel = sel_registerName(b"runModal\0".as_ptr() as *const c_char);
1095 let msg_run: unsafe extern "C" fn(*mut c_void, *mut c_void) -> isize =
1096 std::mem::transmute(objc_msgSend as *const ());
1097 let response = msg_run(panel, run_modal_sel);
1098
1099 if response != 1 {
1100 return None;
1101 }
1102
1103 let url_sel = sel_registerName(b"URL\0".as_ptr() as *const c_char);
1104 let msg_url: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1105 std::mem::transmute(objc_msgSend as *const ());
1106 let url = msg_url(panel, url_sel);
1107 path_from_ns_url(url)
1108 }
1109 }
1110
1111 pub fn show_message_box(
1112 title: &str,
1113 message: &str,
1114 _box_type: MessageBoxType,
1115 buttons: MessageBoxButtons,
1116 ) -> MessageBoxResult {
1117 unsafe {
1118 let alert_cls = objc_getClass(b"NSAlert\0".as_ptr() as *const c_char);
1119 if alert_cls.is_null() {
1120 return MessageBoxResult::Ok;
1121 }
1122 let alloc_sel = sel_registerName(b"alloc\0".as_ptr() as *const c_char);
1123 let init_sel = sel_registerName(b"init\0".as_ptr() as *const c_char);
1124 let msg_alloc: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1125 std::mem::transmute(objc_msgSend as *const ());
1126 let alert_inst = msg_alloc(alert_cls, alloc_sel);
1127 let alert = msg_alloc(alert_inst, init_sel);
1128
1129 let set_msg_sel = sel_registerName(b"setMessageText:\0".as_ptr() as *const c_char);
1130 let ns_title = ns_string(title);
1131 let msg_set_str: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
1132 std::mem::transmute(objc_msgSend as *const ());
1133 msg_set_str(alert, set_msg_sel, ns_title);
1134
1135 let set_info_sel = sel_registerName(b"setInformativeText:\0".as_ptr() as *const c_char);
1136 let ns_msg = ns_string(message);
1137 msg_set_str(alert, set_info_sel, ns_msg);
1138
1139 let add_btn_sel = sel_registerName(b"addButtonWithTitle:\0".as_ptr() as *const c_char);
1140 match buttons {
1141 MessageBoxButtons::Ok => {
1142 msg_set_str(alert, add_btn_sel, ns_string("OK"));
1143 }
1144 MessageBoxButtons::OkCancel => {
1145 msg_set_str(alert, add_btn_sel, ns_string("OK"));
1146 msg_set_str(alert, add_btn_sel, ns_string("Cancel"));
1147 }
1148 MessageBoxButtons::YesNo => {
1149 msg_set_str(alert, add_btn_sel, ns_string("Yes"));
1150 msg_set_str(alert, add_btn_sel, ns_string("No"));
1151 }
1152 MessageBoxButtons::YesNoCancel => {
1153 msg_set_str(alert, add_btn_sel, ns_string("Yes"));
1154 msg_set_str(alert, add_btn_sel, ns_string("No"));
1155 msg_set_str(alert, add_btn_sel, ns_string("Cancel"));
1156 }
1157 }
1158
1159 let run_modal_sel = sel_registerName(b"runModal\0".as_ptr() as *const c_char);
1160 let msg_run: unsafe extern "C" fn(*mut c_void, *mut c_void) -> isize =
1161 std::mem::transmute(objc_msgSend as *const ());
1162 let response = msg_run(alert, run_modal_sel);
1163
1164 match buttons {
1166 MessageBoxButtons::Ok => MessageBoxResult::Ok,
1167 MessageBoxButtons::OkCancel => {
1168 if response == 1000 {
1169 MessageBoxResult::Ok
1170 } else {
1171 MessageBoxResult::Cancel
1172 }
1173 }
1174 MessageBoxButtons::YesNo => {
1175 if response == 1000 {
1176 MessageBoxResult::Yes
1177 } else {
1178 MessageBoxResult::No
1179 }
1180 }
1181 MessageBoxButtons::YesNoCancel => {
1182 if response == 1000 {
1183 MessageBoxResult::Yes
1184 } else if response == 1001 {
1185 MessageBoxResult::No
1186 } else {
1187 MessageBoxResult::Cancel
1188 }
1189 }
1190 }
1191 }
1192 }
1193
1194 unsafe fn ns_string(s: &str) -> *mut c_void {
1195 let cls = objc_getClass(b"NSString\0".as_ptr() as *const c_char);
1196 let sel = sel_registerName(b"stringWithUTF8String:\0".as_ptr() as *const c_char);
1197 let cstr = CString::new(s).unwrap_or_default();
1198 let msg: unsafe extern "C" fn(*mut c_void, *mut c_void, *const c_char) -> *mut c_void =
1199 std::mem::transmute(objc_msgSend as *const ());
1200 msg(cls, sel, cstr.as_ptr())
1201 }
1202
1203 unsafe fn path_from_ns_url(url: *mut c_void) -> Option<PathBuf> {
1204 if url.is_null() {
1205 return None;
1206 }
1207 let path_sel = sel_registerName(b"path\0".as_ptr() as *const c_char);
1208 let msg_path: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
1209 std::mem::transmute(objc_msgSend as *const ());
1210 let path_str = msg_path(url, path_sel);
1211 if path_str.is_null() {
1212 return None;
1213 }
1214 let utf8_sel = sel_registerName(b"UTF8String\0".as_ptr() as *const c_char);
1215 let msg_utf8: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *const c_char =
1216 std::mem::transmute(objc_msgSend as *const ());
1217 let c_str = msg_utf8(path_str, utf8_sel);
1218 if c_str.is_null() {
1219 return None;
1220 }
1221 let slice = std::ffi::CStr::from_ptr(c_str).to_str().ok()?;
1222 Some(PathBuf::from(slice))
1223 }
1224
1225 unsafe fn parse_ns_array_urls(array: *mut c_void) -> Vec<PathBuf> {
1226 if array.is_null() {
1227 return Vec::new();
1228 }
1229 let count_sel = sel_registerName(b"count\0".as_ptr() as *const c_char);
1230 let msg_count: unsafe extern "C" fn(*mut c_void, *mut c_void) -> usize =
1231 std::mem::transmute(objc_msgSend as *const ());
1232 let count = msg_count(array, count_sel);
1233 let obj_at_sel = sel_registerName(b"objectAtIndex:\0".as_ptr() as *const c_char);
1234 let msg_obj: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
1235 std::mem::transmute(objc_msgSend as *const ());
1236
1237 let mut out = Vec::with_capacity(count);
1238 for i in 0..count {
1239 let url = msg_obj(array, obj_at_sel, i);
1240 if let Some(path) = path_from_ns_url(url) {
1241 out.push(path);
1242 }
1243 }
1244 out
1245 }
1246}