FileDialog

Struct FileDialog 

Source
pub struct FileDialog { /* private fields */ }
Expand description

A struct representing a file dialog window.

This struct is used to display a file dialog window to the user, allowing them to select a file or folder. It provides an interface to the operating system’s file dialog APIs, which are used to display the dialog and retrieve the selected file or folder location.

§Examples

Creating a new FileDialog and showing it to the user, returning the path selected:

use nvdialog_rs as nvdialog;
use nvdialog::FileDialog;
use nvdialog::FileDialogType;

let mut file_dialog = FileDialog::new("Title", FileDialogType::OpenFile);
let path = PathBuf::new();
if let Some(filename) = file_dialog.retrieve_filename() {
    path = filename;
    // do something with the returned Path
} else {
    println!("No file selected.");
}

§FFI

Corresponds to NvdFileDialog.

Implementations§

Source§

impl FileDialog

Source

pub fn new<S: AsRef<str>>( title: S, type_of_dialog: FileDialogType, file_extensions: Option<impl IntoIterator<Item = S>>, ) -> Self

Creates a new FileDialog instance with the specified title and type of dialog.

This function returns a new FileDialog instance with a raw pointer to the underlying NvdFileDialog struct initialized based on the specified type of dialog. The title argument specifies the title to be displayed in the file dialog window. The type_of_dialog argument determines whether the dialog is used for opening a file (FileDialogType::OpenFile) or saving a file (FileDialogType::SaveFile).

If FileDialogType::OpenFile is specified, the raw pointer is obtained by calling the nvd_open_file_dialog_new function from the underlying C API. If FileDialogType::SaveFile is specified, the raw pointer is obtained by calling the nvd_save_file_dialog_new function from the underlying C API. In the case of FileDialogType::SaveFile, the dialog defaults to suggesting a filename of “filename”.

§Examples

Creating a new FileDialog instance for opening a file:

let file_dialog = FileDialog::new("Open File", FileDialogType::OpenFile);

Creating a new FileDialog instance for saving a file:

let file_dialog = FileDialog::new("Save File", FileDialogType::SaveFile);
Examples found in repository?
examples/folder-save-dialog.rs (lines 29-33)
27fn main() {
28    nvdialog_rs::init().expect("failed to initialize nvdialog");
29    let folder_dialog = FileDialog::new(
30        "Choose a folder",
31        FileDialogType::OpenFolder,
32        None::<Vec<&str>>,
33    );
34    let where_to_save = FileDialog::new("Save as...", FileDialogType::SaveFile, None::<Vec<&str>>);
35
36    if let Some(p) = folder_dialog.retrieve_filename() {
37        println!("You chose folder {}", p.display());
38    }
39
40    if let Some(s) = where_to_save.retrieve_filename() {
41        println!("Saved as {}", s.display());
42    }
43}
More examples
Hide additional examples
examples/file-dialog.rs (lines 34-44)
32fn main() {
33    nvdialog_rs::init().expect("Can't initialize NvDialog");
34    let file_dialog = FileDialog::new(
35        String::from("Select an image"),
36        FileDialogType::OpenFile,
37        Some(vec![
38            "png".to_owned(),
39            "jpg".to_owned(),
40            "jpeg".to_owned(),
41            "ico".to_owned(),
42            "webp".to_owned(),
43        ]),
44    );
45
46    if let Some(file) = file_dialog.retrieve_filename() {
47        DialogBox::new("File chosen", &file.to_str().unwrap(), DialogType::Simple)
48            .expect("Can't create dialog")
49            .show()
50    } else {
51        DialogBox::new("Error", "No file chosen", DialogType::Error)
52            .expect("Can't create dialog")
53            .show()
54    }
55}
examples/about-dialog.rs (lines 7-11)
4fn main() {
5    nvdialog_rs::init().expect("failed to initialize libnvdialog");
6    let extensions = ["png", "jpeg", "jpg", "ico", "webp"];
7    let filedlg = FileDialog::new(
8        "Choose the icon for the dialog",
9        FileDialogType::OpenFile,
10        Some(extensions),
11    );
12    let filename = filedlg.retrieve_filename().unwrap_or_else(|| {
13        eprintln!("No filename given!");
14        abort()
15    });
16    let img = Image::from_filename(filename).unwrap_or_else(|e| {
17        eprintln!("Failed to read image! {}", e.to_string());
18        abort();
19    });
20
21    let dialog = AboutDialog::new()
22        .name("NvDialog Example")
23        .description(
24            "An example of using nvdialog-rs and NvdAboutDialog, with a custom user-picked icon",
25        )
26        .icon(img)
27        .build();
28
29    dialog.show();
30}
Source

pub fn retrieve_filename(&self) -> Option<PathBuf>

Retrieves the file name selected in the file dialog. This function returns a PathBuf instance containing the selected file name, or None if no file was selected.

This function calls the nvd_get_file_location function from the underlying C API. If the returned pointer from NvDialog is NULL, this function returns None. If the pointer is not null, this function constructs a CStr instance from the raw buffer, and constructs a PathBuf instance from the CStr.

§Safety

This function constructs the returned PathBuf using C bytes, which may cause a panic if the C data contains non-valid UTF-8 characters.

§Returns
  • Some(PathBuf) if a file was selected and the selected file name could be converted to a PathBuf instance.
  • None if no file was selected.
§Panics

This function may panic with the message “Invalid UTF-8 data” if the raw buffer returned from the underlying C API contains invalid UTF-8 data.

§Examples
let mut file_dialog = FileDialog::new("Open File", FileDialogType::OpenFile);

if let Some(path) = file_dialog.retrieve_filename() {
    // A file was selected. Do something with the file...
} else {
    eprintln!("No file was selected")
}
Examples found in repository?
examples/folder-save-dialog.rs (line 36)
27fn main() {
28    nvdialog_rs::init().expect("failed to initialize nvdialog");
29    let folder_dialog = FileDialog::new(
30        "Choose a folder",
31        FileDialogType::OpenFolder,
32        None::<Vec<&str>>,
33    );
34    let where_to_save = FileDialog::new("Save as...", FileDialogType::SaveFile, None::<Vec<&str>>);
35
36    if let Some(p) = folder_dialog.retrieve_filename() {
37        println!("You chose folder {}", p.display());
38    }
39
40    if let Some(s) = where_to_save.retrieve_filename() {
41        println!("Saved as {}", s.display());
42    }
43}
More examples
Hide additional examples
examples/file-dialog.rs (line 46)
32fn main() {
33    nvdialog_rs::init().expect("Can't initialize NvDialog");
34    let file_dialog = FileDialog::new(
35        String::from("Select an image"),
36        FileDialogType::OpenFile,
37        Some(vec![
38            "png".to_owned(),
39            "jpg".to_owned(),
40            "jpeg".to_owned(),
41            "ico".to_owned(),
42            "webp".to_owned(),
43        ]),
44    );
45
46    if let Some(file) = file_dialog.retrieve_filename() {
47        DialogBox::new("File chosen", &file.to_str().unwrap(), DialogType::Simple)
48            .expect("Can't create dialog")
49            .show()
50    } else {
51        DialogBox::new("Error", "No file chosen", DialogType::Error)
52            .expect("Can't create dialog")
53            .show()
54    }
55}
examples/about-dialog.rs (line 12)
4fn main() {
5    nvdialog_rs::init().expect("failed to initialize libnvdialog");
6    let extensions = ["png", "jpeg", "jpg", "ico", "webp"];
7    let filedlg = FileDialog::new(
8        "Choose the icon for the dialog",
9        FileDialogType::OpenFile,
10        Some(extensions),
11    );
12    let filename = filedlg.retrieve_filename().unwrap_or_else(|| {
13        eprintln!("No filename given!");
14        abort()
15    });
16    let img = Image::from_filename(filename).unwrap_or_else(|e| {
17        eprintln!("Failed to read image! {}", e.to_string());
18        abort();
19    });
20
21    let dialog = AboutDialog::new()
22        .name("NvDialog Example")
23        .description(
24            "An example of using nvdialog-rs and NvdAboutDialog, with a custom user-picked icon",
25        )
26        .icon(img)
27        .build();
28
29    dialog.show();
30}

Trait Implementations§

Source§

impl Drop for FileDialog

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl Object for FileDialog

Source§

type NativeType = _NvdFileDialog

The type of the underlying native object, created by NvDialog. It will be used as a pointer to provide compatibility with the NvDialog API.
Source§

type ReturnValue = Option<PathBuf>

The value that should be returned from Self::show. It should match the value that the dialog returns when it is presented to the user.
Source§

fn get_raw(&self) -> *mut Self::NativeType

Returns the raw object created by NvDialog internally. This should never return null.
Source§

fn show(&self) -> Option<PathBuf>

Presents the dialog to the user. If Self::ReturnValue is not () then it will also return that value. Sometimes this serves as an alias to the type’s implementation of the analogous function. If you cannot afford the overhead, you can use that instead.
Source§

fn free(&mut self)

Frees the underlying native object. This should not be usually called manually, instead the Drop implementation should handle it when the time is correct. Be wary, if you do call this, you might run into double freeing errors.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.