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
320#[cfg(all(target_os = "linux", feature = "gtk-compat"))]
321mod linux_backend {
322 use super::*;
323 use gtk::prelude::*;
324 use std::path::PathBuf;
325
326 pub fn open_file(options: &OpenFileOptions) -> Option<PathBuf> {
327 if !gtk::is_initialized() {
328 return None;
329 }
330 let dialog = gtk::FileChooserNative::new(
331 Some(options.title.as_deref().unwrap_or("Open File")),
332 None::<>k::Window>,
333 gtk::FileChooserAction::Open,
334 Some("Open"),
335 Some("Cancel"),
336 );
337 apply_filters(&dialog, &options.filters);
338 if let Some(dir) = &options.starting_directory {
339 dialog.set_current_folder(dir);
340 }
341 let response = dialog.run();
342 if response == gtk::ResponseType::Accept {
343 dialog.filename()
344 } else {
345 None
346 }
347 }
348
349 pub fn open_multiple_files(options: &OpenFileOptions) -> Vec<PathBuf> {
350 if !gtk::is_initialized() {
351 return Vec::new();
352 }
353 let dialog = gtk::FileChooserNative::new(
354 Some(options.title.as_deref().unwrap_or("Open Files")),
355 None::<>k::Window>,
356 gtk::FileChooserAction::Open,
357 Some("Open"),
358 Some("Cancel"),
359 );
360 dialog.set_select_multiple(true);
361 apply_filters(&dialog, &options.filters);
362 if let Some(dir) = &options.starting_directory {
363 dialog.set_current_folder(dir);
364 }
365 let response = dialog.run();
366 if response == gtk::ResponseType::Accept {
367 dialog.filenames()
368 } else {
369 Vec::new()
370 }
371 }
372
373 pub fn save_file(options: &SaveFileOptions) -> Option<PathBuf> {
374 if !gtk::is_initialized() {
375 return None;
376 }
377 let dialog = gtk::FileChooserNative::new(
378 Some(options.title.as_deref().unwrap_or("Save File")),
379 None::<>k::Window>,
380 gtk::FileChooserAction::Save,
381 Some("Save"),
382 Some("Cancel"),
383 );
384 dialog.set_do_overwrite_confirmation(true);
385 apply_filters(&dialog, &options.filters);
386 if let Some(dir) = &options.starting_directory {
387 dialog.set_current_folder(dir);
388 }
389 if let Some(name) = &options.default_name {
390 dialog.set_current_name(name);
391 }
392 let response = dialog.run();
393 if response == gtk::ResponseType::Accept {
394 dialog.filename()
395 } else {
396 None
397 }
398 }
399
400 pub fn pick_folder(options: &PickFolderOptions) -> Option<PathBuf> {
401 if !gtk::is_initialized() {
402 return None;
403 }
404 let dialog = gtk::FileChooserNative::new(
405 Some(options.title.as_deref().unwrap_or("Select Folder")),
406 None::<>k::Window>,
407 gtk::FileChooserAction::SelectFolder,
408 Some("Select"),
409 Some("Cancel"),
410 );
411 if let Some(dir) = &options.starting_directory {
412 dialog.set_current_folder(dir);
413 }
414 let response = dialog.run();
415 if response == gtk::ResponseType::Accept {
416 dialog.filename()
417 } else {
418 None
419 }
420 }
421
422 pub fn show_message_box(
423 title: &str,
424 message: &str,
425 box_type: MessageBoxType,
426 buttons: MessageBoxButtons,
427 ) -> MessageBoxResult {
428 if !gtk::is_initialized() {
429 return MessageBoxResult::Ok;
430 }
431 let message_type = match box_type {
432 MessageBoxType::Info => gtk::MessageType::Info,
433 MessageBoxType::Warning => gtk::MessageType::Warning,
434 MessageBoxType::Error => gtk::MessageType::Error,
435 MessageBoxType::Question => gtk::MessageType::Question,
436 };
437 let buttons_type = match buttons {
438 MessageBoxButtons::Ok => gtk::ButtonsType::Ok,
439 MessageBoxButtons::OkCancel => gtk::ButtonsType::OkCancel,
440 MessageBoxButtons::YesNo => gtk::ButtonsType::YesNo,
441 MessageBoxButtons::YesNoCancel => gtk::ButtonsType::None,
442 };
443 let dialog = gtk::MessageDialog::new(
444 None::<>k::Window>,
445 gtk::DialogFlags::MODAL,
446 message_type,
447 buttons_type,
448 message,
449 );
450 dialog.set_title(title);
451 if buttons == MessageBoxButtons::YesNoCancel {
452 dialog.add_button("Yes", gtk::ResponseType::Yes);
453 dialog.add_button("No", gtk::ResponseType::No);
454 dialog.add_button("Cancel", gtk::ResponseType::Cancel);
455 }
456 let response = dialog.run();
457 dialog.close();
458 match response {
459 gtk::ResponseType::Ok | gtk::ResponseType::Accept => MessageBoxResult::Ok,
460 gtk::ResponseType::Yes => MessageBoxResult::Yes,
461 gtk::ResponseType::No => MessageBoxResult::No,
462 _ => MessageBoxResult::Cancel,
463 }
464 }
465
466 fn apply_filters(dialog: >k::FileChooserNative, filters: &[DialogFilter]) {
467 for f in filters {
468 let filter = gtk::FileFilter::new();
469 filter.set_name(Some(&f.name));
470 for ext in &f.extensions {
471 filter.add_pattern(&format!("*.{}", ext));
472 filter.add_pattern(&format!("*.{}", ext.to_uppercase()));
473 }
474 dialog.add_filter(filter);
475 }
476 }
477}
478
479#[cfg(all(target_os = "linux", not(feature = "gtk-compat")))]
480mod linux_backend {
481 use super::*;
482 use std::path::PathBuf;
483
484 pub fn open_file(_options: &OpenFileOptions) -> Option<PathBuf> {
485 None
486 }
487
488 pub fn open_multiple_files(_options: &OpenFileOptions) -> Vec<PathBuf> {
489 Vec::new()
490 }
491
492 pub fn save_file(_options: &SaveFileOptions) -> Option<PathBuf> {
493 None
494 }
495
496 pub fn pick_folder(_options: &PickFolderOptions) -> Option<PathBuf> {
497 None
498 }
499
500 pub fn show_message_box(
501 _title: &str,
502 _message: &str,
503 _box_type: MessageBoxType,
504 _buttons: MessageBoxButtons,
505 ) -> MessageBoxResult {
506 MessageBoxResult::Ok
507 }
508}
509
510#[cfg(windows)]
511mod windows_backend {
512 use super::*;
513 use std::path::PathBuf;
514 use windows_sys::Win32::Foundation::HWND;
515 use windows_sys::Win32::UI::Controls::Dialogs::{
516 GetOpenFileNameW, GetSaveFileNameW, OFN_ALLOWMULTISELECT, OFN_EXPLORER, OFN_FILEMUSTEXIST,
517 OFN_OVERWRITEPROMPT, OFN_PATHMUSTEXIST, OPENFILENAMEW,
518 };
519 use windows_sys::Win32::UI::WindowsAndMessaging::{
520 MessageBoxW, IDCANCEL, IDNO, IDOK, IDYES, MB_ICONERROR, MB_ICONINFORMATION,
521 MB_ICONQUESTION, MB_ICONWARNING, MB_OK, MB_OKCANCEL, MB_YESNO, MB_YESNOCANCEL,
522 };
523
524 pub fn open_file(options: &OpenFileOptions) -> Option<PathBuf> {
525 let mut paths = run_open_dialog(options, false);
526 paths.pop()
527 }
528
529 pub fn open_multiple_files(options: &OpenFileOptions) -> Vec<PathBuf> {
530 run_open_dialog(options, true)
531 }
532
533 fn run_open_dialog(options: &OpenFileOptions, multiple: bool) -> Vec<PathBuf> {
534 unsafe {
535 let mut buf = vec![0u16; 65536];
536 let filter = build_filter_string(&options.filters);
537 let title = options.title.as_ref().map(|t| {
538 t.encode_utf16()
539 .chain(std::iter::once(0))
540 .collect::<Vec<u16>>()
541 });
542 let dir = options
543 .starting_directory
544 .as_ref()
545 .and_then(|d| d.to_str())
546 .map(|s| {
547 s.encode_utf16()
548 .chain(std::iter::once(0))
549 .collect::<Vec<u16>>()
550 });
551
552 let mut flags = OFN_EXPLORER | OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
553 if multiple {
554 flags |= OFN_ALLOWMULTISELECT;
555 }
556
557 let mut ofn: OPENFILENAMEW = std::mem::zeroed();
558 ofn.lStructSize = std::mem::size_of::<OPENFILENAMEW>() as u32;
559 ofn.hwndOwner = 0 as HWND;
560 ofn.lpstrFilter = filter.as_ptr();
561 ofn.lpstrFile = buf.as_mut_ptr();
562 ofn.nMaxFile = buf.len() as u32;
563 ofn.lpstrInitialDir = dir.as_ref().map(|d| d.as_ptr()).unwrap_or(std::ptr::null());
564 ofn.lpstrTitle = title
565 .as_ref()
566 .map(|t| t.as_ptr())
567 .unwrap_or(std::ptr::null());
568 ofn.Flags = flags;
569
570 if GetOpenFileNameW(&mut ofn) == 0 {
571 return Vec::new();
572 }
573
574 parse_open_file_buffer(&buf)
575 }
576 }
577
578 pub fn save_file(options: &SaveFileOptions) -> Option<PathBuf> {
579 unsafe {
580 let mut buf = vec![0u16; 4096];
581 if let Some(default_name) = &options.default_name {
582 let name_wide: Vec<u16> = default_name.encode_utf16().collect();
583 let len = name_wide.len().min(buf.len().saturating_sub(1));
584 buf[..len].copy_from_slice(&name_wide[..len]);
585 }
586
587 let filter = build_filter_string(&options.filters);
588 let title = options.title.as_ref().map(|t| {
589 t.encode_utf16()
590 .chain(std::iter::once(0))
591 .collect::<Vec<u16>>()
592 });
593 let dir = options
594 .starting_directory
595 .as_ref()
596 .and_then(|d| d.to_str())
597 .map(|s| {
598 s.encode_utf16()
599 .chain(std::iter::once(0))
600 .collect::<Vec<u16>>()
601 });
602
603 let mut ofn: OPENFILENAMEW = std::mem::zeroed();
604 ofn.lStructSize = std::mem::size_of::<OPENFILENAMEW>() as u32;
605 ofn.hwndOwner = 0 as HWND;
606 ofn.lpstrFilter = filter.as_ptr();
607 ofn.lpstrFile = buf.as_mut_ptr();
608 ofn.nMaxFile = buf.len() as u32;
609 ofn.lpstrInitialDir = dir.as_ref().map(|d| d.as_ptr()).unwrap_or(std::ptr::null());
610 ofn.lpstrTitle = title
611 .as_ref()
612 .map(|t| t.as_ptr())
613 .unwrap_or(std::ptr::null());
614 ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT;
615
616 if GetSaveFileNameW(&mut ofn) == 0 {
617 return None;
618 }
619
620 let end = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
621 let path_str = String::from_utf16_lossy(&buf[..end]);
622 if path_str.is_empty() {
623 None
624 } else {
625 Some(PathBuf::from(path_str))
626 }
627 }
628 }
629
630 pub fn pick_folder(options: &PickFolderOptions) -> Option<PathBuf> {
631 let mut open_opt = OpenFileOptions::new();
633 open_opt.title = options.title.clone();
634 open_opt.starting_directory = options.starting_directory.clone();
635 open_file(&open_opt).and_then(|p| {
636 if p.is_dir() {
637 Some(p)
638 } else {
639 p.parent().map(|d| d.to_path_buf())
640 }
641 })
642 }
643
644 pub fn show_message_box(
645 title: &str,
646 message: &str,
647 box_type: MessageBoxType,
648 buttons: MessageBoxButtons,
649 ) -> MessageBoxResult {
650 unsafe {
651 let wide_msg: Vec<u16> = message.encode_utf16().chain(std::iter::once(0)).collect();
652 let wide_title: Vec<u16> = title.encode_utf16().chain(std::iter::once(0)).collect();
653
654 let mut flags = match box_type {
655 MessageBoxType::Info => MB_ICONINFORMATION,
656 MessageBoxType::Warning => MB_ICONWARNING,
657 MessageBoxType::Error => MB_ICONERROR,
658 MessageBoxType::Question => MB_ICONQUESTION,
659 };
660
661 flags |= match buttons {
662 MessageBoxButtons::Ok => MB_OK,
663 MessageBoxButtons::OkCancel => MB_OKCANCEL,
664 MessageBoxButtons::YesNo => MB_YESNO,
665 MessageBoxButtons::YesNoCancel => MB_YESNOCANCEL,
666 };
667
668 let res = MessageBoxW(0 as HWND, wide_msg.as_ptr(), wide_title.as_ptr(), flags);
669 match res {
670 IDOK => MessageBoxResult::Ok,
671 IDCANCEL => MessageBoxResult::Cancel,
672 IDYES => MessageBoxResult::Yes,
673 IDNO => MessageBoxResult::No,
674 _ => MessageBoxResult::Ok,
675 }
676 }
677 }
678
679 fn build_filter_string(filters: &[DialogFilter]) -> Vec<u16> {
680 let mut out = Vec::new();
681 for f in filters {
682 out.extend(f.name.encode_utf16());
683 out.push(0);
684 let exts: Vec<String> = f.extensions.iter().map(|e| format!("*.{}", e)).collect();
685 let ext_str = exts.join(";");
686 out.extend(ext_str.encode_utf16());
687 out.push(0);
688 }
689 if filters.is_empty() {
690 out.extend("All Files (*.*)".encode_utf16());
691 out.push(0);
692 out.extend("*.*".encode_utf16());
693 out.push(0);
694 }
695 out.push(0);
696 out
697 }
698
699 fn parse_open_file_buffer(buf: &[u16]) -> Vec<PathBuf> {
700 let mut chunks = Vec::new();
701 let mut start = 0;
702 for i in 0..buf.len() {
703 if buf[i] == 0 {
704 if start == i {
705 break;
706 }
707 chunks.push(String::from_utf16_lossy(&buf[start..i]));
708 start = i + 1;
709 }
710 }
711 if chunks.is_empty() {
712 return Vec::new();
713 }
714 if chunks.len() == 1 {
715 return vec![PathBuf::from(&chunks[0])];
716 }
717 let base_dir = PathBuf::from(&chunks[0]);
718 chunks[1..]
719 .iter()
720 .map(|filename| base_dir.join(filename))
721 .collect()
722 }
723}
724
725#[cfg(target_os = "macos")]
726mod macos_backend {
727 use super::*;
728 use std::ffi::{c_char, c_void, CString};
729 use std::path::PathBuf;
730
731 extern "C" {
732 fn objc_getClass(name: *const c_char) -> *mut c_void;
733 fn sel_registerName(name: *const c_char) -> *mut c_void;
734 fn objc_msgSend(receiver: *mut c_void, op: *mut c_void, ...) -> *mut c_void;
735 }
736
737 pub fn open_file(options: &OpenFileOptions) -> Option<PathBuf> {
738 let mut files = run_open_panel(options, false);
739 files.pop()
740 }
741
742 pub fn open_multiple_files(options: &OpenFileOptions) -> Vec<PathBuf> {
743 run_open_panel(options, true)
744 }
745
746 fn run_open_panel(options: &OpenFileOptions, multiple: bool) -> Vec<PathBuf> {
747 unsafe {
748 let panel_cls = objc_getClass(b"NSOpenPanel\0".as_ptr() as *const c_char);
749 if panel_cls.is_null() {
750 return Vec::new();
751 }
752 let open_sel = sel_registerName(b"openPanel\0".as_ptr() as *const c_char);
753 let msg_open: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
754 std::mem::transmute(objc_msgSend as *const ());
755 let panel = msg_open(panel_cls, open_sel);
756 if panel.is_null() {
757 return Vec::new();
758 }
759
760 let set_files_sel = sel_registerName(b"setCanChooseFiles:\0".as_ptr() as *const c_char);
761 let msg_set_bool: unsafe extern "C" fn(*mut c_void, *mut c_void, bool) =
762 std::mem::transmute(objc_msgSend as *const ());
763 msg_set_bool(panel, set_files_sel, true);
764
765 let set_dirs_sel =
766 sel_registerName(b"setCanChooseDirectories:\0".as_ptr() as *const c_char);
767 msg_set_bool(panel, set_dirs_sel, false);
768
769 let set_multi_sel =
770 sel_registerName(b"setAllowsMultipleSelection:\0".as_ptr() as *const c_char);
771 msg_set_bool(panel, set_multi_sel, multiple);
772
773 if let Some(title) = &options.title {
774 let set_title_sel = sel_registerName(b"setTitle:\0".as_ptr() as *const c_char);
775 let ns_title = ns_string(title);
776 let msg_set_title: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
777 std::mem::transmute(objc_msgSend as *const ());
778 msg_set_title(panel, set_title_sel, ns_title);
779 }
780
781 let run_modal_sel = sel_registerName(b"runModal\0".as_ptr() as *const c_char);
782 let msg_run: unsafe extern "C" fn(*mut c_void, *mut c_void) -> isize =
783 std::mem::transmute(objc_msgSend as *const ());
784 let response = msg_run(panel, run_modal_sel);
785
786 if response != 1 {
788 return Vec::new();
789 }
790
791 let urls_sel = sel_registerName(b"URLs\0".as_ptr() as *const c_char);
792 let msg_urls: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
793 std::mem::transmute(objc_msgSend as *const ());
794 let urls_array = msg_urls(panel, urls_sel);
795 parse_ns_array_urls(urls_array)
796 }
797 }
798
799 pub fn save_file(options: &SaveFileOptions) -> Option<PathBuf> {
800 unsafe {
801 let panel_cls = objc_getClass(b"NSSavePanel\0".as_ptr() as *const c_char);
802 if panel_cls.is_null() {
803 return None;
804 }
805 let save_sel = sel_registerName(b"savePanel\0".as_ptr() as *const c_char);
806 let msg_save: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
807 std::mem::transmute(objc_msgSend as *const ());
808 let panel = msg_save(panel_cls, save_sel);
809 if panel.is_null() {
810 return None;
811 }
812
813 if let Some(title) = &options.title {
814 let set_title_sel = sel_registerName(b"setTitle:\0".as_ptr() as *const c_char);
815 let ns_title = ns_string(title);
816 let msg_set_str: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
817 std::mem::transmute(objc_msgSend as *const ());
818 msg_set_str(panel, set_title_sel, ns_title);
819 }
820
821 if let Some(name) = &options.default_name {
822 let set_name_sel =
823 sel_registerName(b"setNameFieldStringValue:\0".as_ptr() as *const c_char);
824 let ns_name = ns_string(name);
825 let msg_set_str: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
826 std::mem::transmute(objc_msgSend as *const ());
827 msg_set_str(panel, set_name_sel, ns_name);
828 }
829
830 let run_modal_sel = sel_registerName(b"runModal\0".as_ptr() as *const c_char);
831 let msg_run: unsafe extern "C" fn(*mut c_void, *mut c_void) -> isize =
832 std::mem::transmute(objc_msgSend as *const ());
833 let response = msg_run(panel, run_modal_sel);
834
835 if response != 1 {
836 return None;
837 }
838
839 let url_sel = sel_registerName(b"URL\0".as_ptr() as *const c_char);
840 let msg_url: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
841 std::mem::transmute(objc_msgSend as *const ());
842 let url = msg_url(panel, url_sel);
843 path_from_ns_url(url)
844 }
845 }
846
847 pub fn pick_folder(options: &PickFolderOptions) -> Option<PathBuf> {
848 unsafe {
849 let panel_cls = objc_getClass(b"NSOpenPanel\0".as_ptr() as *const c_char);
850 if panel_cls.is_null() {
851 return None;
852 }
853 let open_sel = sel_registerName(b"openPanel\0".as_ptr() as *const c_char);
854 let msg_open: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
855 std::mem::transmute(objc_msgSend as *const ());
856 let panel = msg_open(panel_cls, open_sel);
857 if panel.is_null() {
858 return None;
859 }
860
861 let set_files_sel = sel_registerName(b"setCanChooseFiles:\0".as_ptr() as *const c_char);
862 let msg_set_bool: unsafe extern "C" fn(*mut c_void, *mut c_void, bool) =
863 std::mem::transmute(objc_msgSend as *const ());
864 msg_set_bool(panel, set_files_sel, false);
865
866 let set_dirs_sel =
867 sel_registerName(b"setCanChooseDirectories:\0".as_ptr() as *const c_char);
868 msg_set_bool(panel, set_dirs_sel, true);
869
870 let set_multi_sel =
871 sel_registerName(b"setAllowsMultipleSelection:\0".as_ptr() as *const c_char);
872 msg_set_bool(panel, set_multi_sel, false);
873
874 if let Some(title) = &options.title {
875 let set_title_sel = sel_registerName(b"setTitle:\0".as_ptr() as *const c_char);
876 let ns_title = ns_string(title);
877 let msg_set_title: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
878 std::mem::transmute(objc_msgSend as *const ());
879 msg_set_title(panel, set_title_sel, ns_title);
880 }
881
882 let run_modal_sel = sel_registerName(b"runModal\0".as_ptr() as *const c_char);
883 let msg_run: unsafe extern "C" fn(*mut c_void, *mut c_void) -> isize =
884 std::mem::transmute(objc_msgSend as *const ());
885 let response = msg_run(panel, run_modal_sel);
886
887 if response != 1 {
888 return None;
889 }
890
891 let url_sel = sel_registerName(b"URL\0".as_ptr() as *const c_char);
892 let msg_url: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
893 std::mem::transmute(objc_msgSend as *const ());
894 let url = msg_url(panel, url_sel);
895 path_from_ns_url(url)
896 }
897 }
898
899 pub fn show_message_box(
900 title: &str,
901 message: &str,
902 _box_type: MessageBoxType,
903 buttons: MessageBoxButtons,
904 ) -> MessageBoxResult {
905 unsafe {
906 let alert_cls = objc_getClass(b"NSAlert\0".as_ptr() as *const c_char);
907 if alert_cls.is_null() {
908 return MessageBoxResult::Ok;
909 }
910 let alloc_sel = sel_registerName(b"alloc\0".as_ptr() as *const c_char);
911 let init_sel = sel_registerName(b"init\0".as_ptr() as *const c_char);
912 let msg_alloc: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
913 std::mem::transmute(objc_msgSend as *const ());
914 let alert_inst = msg_alloc(alert_cls, alloc_sel);
915 let alert = msg_alloc(alert_inst, init_sel);
916
917 let set_msg_sel = sel_registerName(b"setMessageText:\0".as_ptr() as *const c_char);
918 let ns_title = ns_string(title);
919 let msg_set_str: unsafe extern "C" fn(*mut c_void, *mut c_void, *mut c_void) =
920 std::mem::transmute(objc_msgSend as *const ());
921 msg_set_str(alert, set_msg_sel, ns_title);
922
923 let set_info_sel = sel_registerName(b"setInformativeText:\0".as_ptr() as *const c_char);
924 let ns_msg = ns_string(message);
925 msg_set_str(alert, set_info_sel, ns_msg);
926
927 let add_btn_sel = sel_registerName(b"addButtonWithTitle:\0".as_ptr() as *const c_char);
928 match buttons {
929 MessageBoxButtons::Ok => {
930 msg_set_str(alert, add_btn_sel, ns_string("OK"));
931 }
932 MessageBoxButtons::OkCancel => {
933 msg_set_str(alert, add_btn_sel, ns_string("OK"));
934 msg_set_str(alert, add_btn_sel, ns_string("Cancel"));
935 }
936 MessageBoxButtons::YesNo => {
937 msg_set_str(alert, add_btn_sel, ns_string("Yes"));
938 msg_set_str(alert, add_btn_sel, ns_string("No"));
939 }
940 MessageBoxButtons::YesNoCancel => {
941 msg_set_str(alert, add_btn_sel, ns_string("Yes"));
942 msg_set_str(alert, add_btn_sel, ns_string("No"));
943 msg_set_str(alert, add_btn_sel, ns_string("Cancel"));
944 }
945 }
946
947 let run_modal_sel = sel_registerName(b"runModal\0".as_ptr() as *const c_char);
948 let msg_run: unsafe extern "C" fn(*mut c_void, *mut c_void) -> isize =
949 std::mem::transmute(objc_msgSend as *const ());
950 let response = msg_run(alert, run_modal_sel);
951
952 match buttons {
954 MessageBoxButtons::Ok => MessageBoxResult::Ok,
955 MessageBoxButtons::OkCancel => {
956 if response == 1000 {
957 MessageBoxResult::Ok
958 } else {
959 MessageBoxResult::Cancel
960 }
961 }
962 MessageBoxButtons::YesNo => {
963 if response == 1000 {
964 MessageBoxResult::Yes
965 } else {
966 MessageBoxResult::No
967 }
968 }
969 MessageBoxButtons::YesNoCancel => {
970 if response == 1000 {
971 MessageBoxResult::Yes
972 } else if response == 1001 {
973 MessageBoxResult::No
974 } else {
975 MessageBoxResult::Cancel
976 }
977 }
978 }
979 }
980 }
981
982 unsafe fn ns_string(s: &str) -> *mut c_void {
983 let cls = objc_getClass(b"NSString\0".as_ptr() as *const c_char);
984 let sel = sel_registerName(b"stringWithUTF8String:\0".as_ptr() as *const c_char);
985 let cstr = CString::new(s).unwrap_or_default();
986 let msg: unsafe extern "C" fn(*mut c_void, *mut c_void, *const c_char) -> *mut c_void =
987 std::mem::transmute(objc_msgSend as *const ());
988 msg(cls, sel, cstr.as_ptr())
989 }
990
991 unsafe fn path_from_ns_url(url: *mut c_void) -> Option<PathBuf> {
992 if url.is_null() {
993 return None;
994 }
995 let path_sel = sel_registerName(b"path\0".as_ptr() as *const c_char);
996 let msg_path: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *mut c_void =
997 std::mem::transmute(objc_msgSend as *const ());
998 let path_str = msg_path(url, path_sel);
999 if path_str.is_null() {
1000 return None;
1001 }
1002 let utf8_sel = sel_registerName(b"UTF8String\0".as_ptr() as *const c_char);
1003 let msg_utf8: unsafe extern "C" fn(*mut c_void, *mut c_void) -> *const c_char =
1004 std::mem::transmute(objc_msgSend as *const ());
1005 let c_str = msg_utf8(path_str, utf8_sel);
1006 if c_str.is_null() {
1007 return None;
1008 }
1009 let slice = std::ffi::CStr::from_ptr(c_str).to_str().ok()?;
1010 Some(PathBuf::from(slice))
1011 }
1012
1013 unsafe fn parse_ns_array_urls(array: *mut c_void) -> Vec<PathBuf> {
1014 if array.is_null() {
1015 return Vec::new();
1016 }
1017 let count_sel = sel_registerName(b"count\0".as_ptr() as *const c_char);
1018 let msg_count: unsafe extern "C" fn(*mut c_void, *mut c_void) -> usize =
1019 std::mem::transmute(objc_msgSend as *const ());
1020 let count = msg_count(array, count_sel);
1021 let obj_at_sel = sel_registerName(b"objectAtIndex:\0".as_ptr() as *const c_char);
1022 let msg_obj: unsafe extern "C" fn(*mut c_void, *mut c_void, usize) -> *mut c_void =
1023 std::mem::transmute(objc_msgSend as *const ());
1024
1025 let mut out = Vec::with_capacity(count);
1026 for i in 0..count {
1027 let url = msg_obj(array, obj_at_sel, i);
1028 if let Some(path) = path_from_ns_url(url) {
1029 out.push(path);
1030 }
1031 }
1032 out
1033 }
1034}