mist-core 2.0.1

core functionality of mist
//! Dialog boxes to prompt the user for things.
//!
//! Uses [tinyfiledialogs] to provide dialog boxes, which is cross-platform and can even work
//! in a terminal if none of the dialog APIs it's expecting are available.
use crate::error::MistError;
use tinyfiledialogs::{
    message_box_ok, message_box_yes_no, open_file_dialog, save_file_dialog_with_filter,
    MessageBoxIcon, YesNo,
};

fn boolean_check(title: &str, msg: &str) -> bool {
    match message_box_yes_no(title, msg, MessageBoxIcon::Question, YesNo::Yes) {
        YesNo::Yes => true,
        YesNo::No => false,
    }
}

/// Check if the user wants to save their modified split file.
///
/// If they click yes, return `true`. No returns `false`.
pub fn save_check() -> bool {
    boolean_check(
        "Save run?",
        "Your split file has been updated, do you want to save it?",
    )
}

/// Open a file select dialog box.
///
/// Box title will be `title`. `filter` should be formatted like `*.msf` to filter for msf file extensions etc.
/// Returns `None` if the user closes the dialog box or presses Cancel.
pub fn get_file(title: &str, filter: &str) -> Option<String> {
    open_file_dialog(title, "", Some((&[filter], "")))
}

/// Open a save as dialog box.
///
/// Returns `None` if the user cancels the dialog box.
pub fn get_save_as() -> Option<String> {
    save_file_dialog_with_filter("Save as:", "", &["*.msf"], "mist split files")
}

/// Ask the user if they want to try another file.
pub fn try_again(err: MistError) -> bool {
    boolean_check("Error", &format!("{err}. Would you like to try again?"))
}

/// Notify user that parsing a file has failed.
pub fn fail(err: MistError) {
    message_box_ok(
        "File parse failed",
        &format!("File could not be parsed: {}", err),
        MessageBoxIcon::Error,
    );
}

/// Get the path of an msf file to use.
///
/// Returns [`None`] if the user cancels the dialog box
pub fn get_run_path() -> Option<String> {
    get_file("Open split file", "*.msf")
}

/// Get the path of a state dump file to use.
///
/// Returns [`None`] if the user cancels the dialog box
pub fn get_dump_path() -> Option<String> {
    get_file("Open dump file", "*.ron")
}

/// Open a save as dialog box for state dumps.
///
/// Returns [`None`] if the user cancels the dialog box
pub fn get_dump_save() -> Option<String> {
    save_file_dialog_with_filter("Save as:", "", &["*.ron"], "ron files")
}

/// Ask the user whether they want to exit the program or not.
pub fn confirm_exit() -> bool {
    boolean_check("Confirm exit", "Are you sure you want to exit?")
}

/// Inform the user of an error.
pub fn error(err: &str) {
    let err = err.replace(['\'', '"'], "");
    message_box_ok("Error", &err, MessageBoxIcon::Error);
}