| 1 | use std::path::PathBuf; |
| 2 | |
| 3 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 4 | pub enum Purpose { |
| 5 | Open, |
| 6 | Files, |
| 7 | Folder, |
| 8 | Destination, |
| 9 | Retry, |
| 10 | SaveZip, |
| 11 | SaveGzip, |
| 12 | RetryGzip, |
| 13 | } |
| 14 | |
| 15 | #[derive(Clone, Debug)] |
| 16 | pub struct DialogRequest { |
| 17 | pub purpose: Purpose, |
| 18 | pub directory: PathBuf, |
| 19 | pub file_name: String, |
| 20 | } |
| 21 | |
| 22 | pub trait Dialogs { |
| 23 | fn choose(&mut self, request: DialogRequest) -> Result<Option<Vec<PathBuf>>, String>; |
| 24 | } |
| 25 | |
| 26 | pub fn archive_filters() -> Vec<(&'static str, Vec<String>)> { |
| 27 | let mut extensions = Vec::new(); |
| 28 | for extension in ["zip", "7z", "tar", "gz", "tgz"] { |
| 29 | let mut variants = vec![String::new()]; |
| 30 | for character in extension.chars() { |
| 31 | let mut next = Vec::new(); |
| 32 | for prefix in variants { |
| 33 | next.push(format!("{prefix}{character}")); |
| 34 | if character.is_ascii_alphabetic() { |
| 35 | next.push(format!("{prefix}{}", character.to_ascii_uppercase())); |
| 36 | } |
| 37 | } |
| 38 | variants = next; |
| 39 | } |
| 40 | extensions.extend(variants); |
| 41 | } |
| 42 | vec![("압축파일", extensions), ("모든 파일", vec!["*".into()])] |
| 43 | } |
| 44 | |
| 45 | #[derive(Default)] |
| 46 | pub struct NativeDialogs; |
| 47 | |
| 48 | impl Dialogs for NativeDialogs { |
| 49 | fn choose(&mut self, request: DialogRequest) -> Result<Option<Vec<PathBuf>>, String> { |
| 50 | let dialog = rfd::FileDialog::new().set_directory(request.directory); |
| 51 | let answer = |
| 52 | std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match request.purpose { |
| 53 | Purpose::Open => { |
| 54 | let mut dialog = dialog.set_title("압축파일 열기"); |
| 55 | for (name, extensions) in archive_filters() { |
| 56 | dialog = dialog.add_filter(name, &extensions); |
| 57 | } |
| 58 | dialog.pick_file().map(|path| vec![path]) |
| 59 | } |
| 60 | Purpose::Files => dialog.set_title("파일 추가").pick_files(), |
| 61 | Purpose::Folder => dialog |
| 62 | .set_title("폴더 추가") |
| 63 | .pick_folder() |
| 64 | .map(|path| vec![path]), |
| 65 | Purpose::Destination | Purpose::Retry => dialog |
| 66 | .set_title("압축을 풀 폴더 선택") |
| 67 | .pick_folder() |
| 68 | .map(|path| vec![path]), |
| 69 | Purpose::SaveGzip | Purpose::RetryGzip => dialog |
| 70 | .set_title("압축 해제 파일 저장") |
| 71 | .set_file_name(request.file_name) |
| 72 | .save_file() |
| 73 | .map(|path| vec![path]), |
| 74 | Purpose::SaveZip => dialog |
| 75 | .set_title("ZIP 파일 저장") |
| 76 | .set_file_name(request.file_name) |
| 77 | .add_filter("ZIP 압축파일", &["zip"]) |
| 78 | .save_file() |
| 79 | .map(|path| vec![path]), |
| 80 | })); |
| 81 | answer.map_err(|_| "파일 선택 창을 열지 못했습니다. 다시 시도하세요".to_owned()) |
| 82 | } |
| 83 | } |