|
| 1 | +extern crate libc; |
| 2 | + |
| 3 | +mod ffi; |
| 4 | + |
| 5 | +use libc::c_char; |
| 6 | +use std::ffi::*; |
| 7 | +use ffi::*; |
| 8 | + |
| 9 | +/// Result of opening a file dialog |
| 10 | +pub enum NFDResult { |
| 11 | + /// User pressed okay. `String` is the file path selected |
| 12 | + Okay(String), |
| 13 | + /// User pressed cancel |
| 14 | + Cancel, |
| 15 | + /// Program error. `String` is the error description |
| 16 | + Error(String), |
| 17 | +} |
| 18 | + |
| 19 | +enum DialogType { |
| 20 | + SingleFile, |
| 21 | + SaveFile |
| 22 | +} |
| 23 | + |
| 24 | +/// Open single file dialog |
| 25 | +#[inline(always)] |
| 26 | +pub fn open_file_dialog(filter_list: &str, default_path: &str) -> NFDResult { |
| 27 | + open_dialog(filter_list, default_path, &DialogType::SingleFile) |
| 28 | +} |
| 29 | + |
| 30 | +/// Open save dialog |
| 31 | +#[inline(always)] |
| 32 | +pub fn open_save_dialog(filter_list: &str, default_path: &str) -> NFDResult { |
| 33 | + open_dialog(filter_list, default_path, &DialogType::SaveFile) |
| 34 | +} |
| 35 | + |
| 36 | +fn open_dialog(filter_list: &str, default_path: &str, dialog_type: &DialogType) -> NFDResult { |
| 37 | + |
| 38 | + let mut final_cstring = CString::new("").unwrap(); |
| 39 | + let out_path = CString::new("").unwrap().into_raw() as *mut *mut c_char; |
| 40 | + let result: nfdresult_t; |
| 41 | + |
| 42 | + unsafe { |
| 43 | + result = match dialog_type { |
| 44 | + &DialogType::SingleFile => { |
| 45 | + NFD_OpenDialog( |
| 46 | + CString::new(filter_list).unwrap().as_ptr(), |
| 47 | + CString::new(default_path).unwrap().as_ptr(), |
| 48 | + out_path) |
| 49 | + }, |
| 50 | + |
| 51 | + &DialogType::SaveFile => { |
| 52 | + NFD_SaveDialog( |
| 53 | + CString::new(filter_list).unwrap().as_ptr(), |
| 54 | + CString::new(default_path).unwrap().as_ptr(), |
| 55 | + out_path) |
| 56 | + }, |
| 57 | + }; |
| 58 | + |
| 59 | + match result { |
| 60 | + nfdresult_t::NFD_OKAY => { |
| 61 | + final_cstring = CString::from_raw(*out_path); |
| 62 | + }, |
| 63 | + nfdresult_t::NFD_ERROR => { |
| 64 | + final_cstring = CStr::from_ptr(NFD_GetError()).to_owned(); |
| 65 | + } |
| 66 | + _ => {}, |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + let final_string = final_cstring.to_str().unwrap().to_string(); |
| 71 | + |
| 72 | + match result { |
| 73 | + nfdresult_t::NFD_OKAY => NFDResult::Okay(final_string), |
| 74 | + nfdresult_t::NFD_CANCEL => NFDResult::Cancel, |
| 75 | + nfdresult_t::NFD_ERROR => NFDResult::Error(final_string) |
| 76 | + } |
| 77 | +} |
0 commit comments