native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
Documentation
//! Function-style native file dialogs (found while dogfooding).
//!
//! [`crate::ui::Ui::show_file_dialog`] opens a native open/save/folder dialog
//! described by a [`FileDialog`] request and returns a token; the answer
//! arrives later as [`crate::events::UiEvent::FileDialogResponse`] with the
//! chosen paths (empty when the user cancelled). Unlike the
//! `WidgetKind::FileChooserDialog` button widget, nothing has to be created
//! or attached to the widget tree, and the request carries a title, filters,
//! a suggested file name and a starting folder.
//!
//! ```
//! use native_gui_core::file_dialog::FileDialog;
//!
//! let request = FileDialog::save()
//!     .title("Save jobs")
//!     .filter("JSON", &["*.json"])
//!     .suggested_name("jobs.json");
//! assert_eq!(request.filters[0].patterns, vec!["*.json".to_owned()]);
//! ```

use std::path::PathBuf;

use crate::error::{GuiError, GuiResult};
use crate::widgets::FileChooserMode;

/// A named file-type filter, e.g. `("JSON", ["*.json"])`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FileFilter {
    /// Label shown in the dialog's filter picker.
    pub name: String,
    /// Glob patterns such as `*.json` (matched case-insensitively where the
    /// platform supports it).
    pub patterns: Vec<String>,
}

/// A native file-dialog request for [`crate::ui::Ui::show_file_dialog`].
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FileDialog {
    /// Open an existing file, pick a folder, or choose a file to save.
    pub mode: FileChooserMode,
    /// For [`FileChooserMode::OpenFile`]: allow selecting several files.
    pub multiple: bool,
    /// Dialog title; `None` uses the platform default for the mode.
    pub title: Option<String>,
    /// File-type filters; the first one is selected initially.
    pub filters: Vec<FileFilter>,
    /// Pre-filled file name for save dialogs.
    pub suggested_name: Option<String>,
    /// Folder the dialog starts in.
    pub folder: Option<PathBuf>,
}

impl FileDialog {
    /// Choose one existing file.
    pub fn open() -> Self {
        Self {
            mode: FileChooserMode::OpenFile,
            ..Self::default()
        }
    }

    /// Choose one or more existing files.
    pub fn open_multiple() -> Self {
        Self {
            mode: FileChooserMode::OpenFile,
            multiple: true,
            ..Self::default()
        }
    }

    /// Choose a (possibly new) file to write.
    pub fn save() -> Self {
        Self {
            mode: FileChooserMode::SaveFile,
            ..Self::default()
        }
    }

    /// Choose a folder.
    pub fn pick_folder() -> Self {
        Self {
            mode: FileChooserMode::PickFolder,
            ..Self::default()
        }
    }

    /// Sets the dialog title.
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Adds a file-type filter (`name`, glob `patterns`).
    pub fn filter(mut self, name: impl Into<String>, patterns: &[&str]) -> Self {
        self.filters.push(FileFilter {
            name: name.into(),
            patterns: patterns
                .iter()
                .map(|pattern| (*pattern).to_owned())
                .collect(),
        });
        self
    }

    /// Pre-fills the file name (save dialogs).
    pub fn suggested_name(mut self, name: impl Into<String>) -> Self {
        self.suggested_name = Some(name.into());
        self
    }

    /// Sets the folder the dialog starts in.
    pub fn folder(mut self, folder: impl Into<PathBuf>) -> Self {
        self.folder = Some(folder.into());
        self
    }

    /// Validates the request: no embedded NUL bytes in any string, no empty
    /// filter, and `multiple` only for open dialogs.
    pub fn validate(&self) -> GuiResult<()> {
        let mut strings: Vec<&str> = Vec::new();
        strings.extend(self.title.as_deref());
        strings.extend(self.suggested_name.as_deref());
        for filter in &self.filters {
            strings.push(&filter.name);
            if filter.patterns.is_empty() {
                return Err(GuiError::Backend(format!(
                    "file dialog filter `{}` has no patterns",
                    filter.name
                )));
            }
            strings.extend(filter.patterns.iter().map(String::as_str));
        }
        if strings.iter().any(|value| value.contains('\0')) {
            return Err(GuiError::Backend(
                "file dialog strings must not contain NUL bytes".to_owned(),
            ));
        }
        if self.multiple && self.mode != FileChooserMode::OpenFile {
            return Err(GuiError::Backend(
                "multiple selection is only valid for open-file dialogs".to_owned(),
            ));
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn builder_collects_every_option() {
        let request = FileDialog::save()
            .title("Save jobs")
            .filter("JSON", &["*.json"])
            .filter("All files", &["*"])
            .suggested_name("jobs.json")
            .folder("/tmp");
        assert_eq!(request.mode, FileChooserMode::SaveFile);
        assert_eq!(request.title.as_deref(), Some("Save jobs"));
        assert_eq!(request.filters.len(), 2);
        assert_eq!(request.suggested_name.as_deref(), Some("jobs.json"));
        assert_eq!(request.folder, Some(PathBuf::from("/tmp")));
        assert!(request.validate().is_ok());
    }

    #[test]
    fn validation_rejects_bad_requests() {
        assert!(FileDialog::open().title("a\0b").validate().is_err());
        assert!(FileDialog::open().filter("none", &[]).validate().is_err());
        let mut multi_save = FileDialog::save();
        multi_save.multiple = true;
        assert!(multi_save.validate().is_err());
        assert!(FileDialog::open_multiple().validate().is_ok());
        assert!(FileDialog::pick_folder().validate().is_ok());
    }
}