use crate::dialog::{DialogImpl, OpenMultipleFile, OpenSingleDir, OpenSingleFile, SaveSingleFile};
use crate::Result;
use raw_window_handle::{HasRawWindowHandle, RawWindowHandle};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone)]
pub struct Filter<'a> {
pub(crate) description: &'a str,
pub(crate) extensions: &'a [&'a str],
}
#[derive(Debug, Clone)]
pub struct FileDialog<'a> {
pub(crate) filename: Option<&'a str>,
pub(crate) location: Option<&'a Path>,
pub(crate) filters: Vec<Filter<'a>>,
pub(crate) owner: Option<RawWindowHandle>,
pub(crate) title: Option<&'a str>,
}
impl<'a> FileDialog<'a> {
pub fn new() -> Self {
FileDialog {
filename: None,
location: None,
filters: vec![],
owner: None,
title: None,
}
}
pub fn set_title(mut self, title: &'a str) -> Self {
self.title = Some(title);
self
}
pub fn set_filename(mut self, filename: &'a str) -> Self {
self.filename = Some(filename);
self
}
pub fn reset_filename(mut self) -> Self {
self.filename = None;
self
}
pub fn set_location<P: AsRef<Path> + ?Sized>(mut self, path: &'a P) -> Self {
self.location = Some(path.as_ref());
self
}
pub fn reset_location(mut self) -> Self {
self.location = None;
self
}
pub fn add_filter(mut self, description: &'a str, extensions: &'a [&'a str]) -> Self {
if extensions.is_empty() {
panic!("The file extensions of a filter must be specified.")
}
self.filters.push(Filter {
description,
extensions,
});
self
}
pub fn remove_all_filters(mut self) -> Self {
self.filters = vec![];
self
}
pub fn set_owner<W: HasRawWindowHandle>(mut self, window: &W) -> Self {
self.owner = Some(window.raw_window_handle());
self
}
pub unsafe fn set_owner_handle(mut self, handle: RawWindowHandle) -> Self {
self.owner = Some(handle);
self
}
pub fn reset_owner(mut self) -> Self {
self.owner = None;
self
}
pub fn show_open_single_file(self) -> Result<Option<PathBuf>> {
let mut dialog = OpenSingleFile {
filename: self.filename,
location: self.location,
filters: self.filters,
owner: self.owner,
title: self.title.unwrap_or("Open File"),
};
dialog.show()
}
pub fn show_open_multiple_file(self) -> Result<Vec<PathBuf>> {
let mut dialog = OpenMultipleFile {
filename: self.filename,
location: self.location,
filters: self.filters,
owner: self.owner,
title: self.title.unwrap_or("Open File"),
};
dialog.show()
}
pub fn show_open_single_dir(self) -> Result<Option<PathBuf>> {
let mut dialog = OpenSingleDir {
filename: self.filename,
location: self.location,
owner: self.owner,
title: self.title.unwrap_or("Open Folder"),
};
dialog.show()
}
pub fn show_save_single_file(self) -> Result<Option<PathBuf>> {
let mut dialog = SaveSingleFile {
filename: self.filename,
location: self.location,
filters: self.filters,
owner: self.owner,
title: self.title.unwrap_or("Save As"),
};
dialog.show()
}
}
impl Default for FileDialog<'_> {
fn default() -> Self {
Self::new()
}
}