File

Struct File 

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

A file or directory in the file explorer.

Implementations§

Source§

impl File

Source

pub fn name(&self) -> &str

Returns the name of the file or directory.

§Examples

Suppose you have this tree file, with passport.png selected inside file_explorer:

/
├── .git
└── Documents
    ├── passport.png  <- selected
    └── resume.pdf

You can get the name of the selected file like this:

use fpicker::FileExplorer;

let file_explorer = FileExplorer::new().unwrap();

/* user select `password.png` */

let file = file_explorer.current();
assert_eq!(file.name(), "passport.png");
Source

pub const fn path(&self) -> &PathBuf

Returns the path of the file or directory.

§Examples

Suppose you have this tree file, with passport.png selected inside file_explorer:

/
├── .git
└── Documents
    ├── passport.png  <- selected
    └── resume.pdf

You can get the path of the selected file like this:

use fpicker::FileExplorer;

let file_explorer = FileExplorer::new().unwrap();

/* user select `password.png` */

let file = file_explorer.current();
assert_eq!(file.path().display().to_string(), "/Documents/passport.png");
Examples found in repository?
examples/basic.rs (line 37)
11fn main() -> io::Result<()> {
12    enable_raw_mode()?;
13    stdout().execute(EnterAlternateScreen)?;
14
15    let mut terminal = Terminal::new(CrosstermBackend::new(stdout()))?;
16
17    // Create a new file explorer with the default theme and title.
18    let theme = Theme::default().add_default_title();
19    let mut file_explorer = FileExplorer::with_theme(theme)?;
20
21    let mut selected_paths = vec![];
22
23    loop {
24        // Render the file explorer widget.
25        terminal.draw(|f| {
26            f.render_widget(&file_explorer.widget(), f.area());
27        })?;
28
29        // Read the next event from the terminal.
30        let event = read()?;
31        if let Event::Key(key) = event {
32            if key.code == KeyCode::Char('q') {
33                // Collect selected file paths.
34                selected_paths = file_explorer
35                    .selected_files()
36                    .iter()
37                    .map(|file| file.path().display().to_string())
38                    .collect();
39                break;
40            }
41        }
42        // Handle the event in the file explorer.
43        file_explorer.handle(&event)?;
44    }
45
46    // Restore the terminal to normal mode.
47    disable_raw_mode()?;
48    stdout().execute(LeaveAlternateScreen)?;
49
50    // Print the selected file paths to stdout.
51    for path in selected_paths {
52        println!("{}", path);
53    }
54
55    // Return exit code 0 explicitly.
56    process::exit(0);
57}
More examples
Hide additional examples
examples/file_preview.rs (line 36)
17fn main() -> io::Result<()> {
18    enable_raw_mode()?;
19    stdout().execute(EnterAlternateScreen)?;
20
21    let mut terminal = Terminal::new(CrosstermBackend::new(stdout()))?;
22    let layout = Layout::vertical([
23        Constraint::Ratio(4, 5), // Main file explorer and content area
24        Constraint::Ratio(1, 5), // Bottom window for selected file paths
25    ]);
26
27    // Inner layout for the top section
28    let top_layout = Layout::horizontal([Constraint::Ratio(1, 3), Constraint::Ratio(2, 3)]);
29
30    // Create a new file explorer with the default theme and title.
31    let theme = get_theme();
32    let mut file_explorer = FileExplorer::with_theme(theme)?;
33
34    loop {
35        // Get the content of the current selected file (if it's indeed a file).
36        let file_content = get_file_content(file_explorer.current().path())?;
37        let selected_files: String = file_explorer
38            .selected_files()
39            .iter()
40            .map(|file| file.path().display().to_string())
41            .collect::<Vec<String>>()
42            .join("\n");
43
44        // Render the file explorer widget, file content, and selected file paths.
45        terminal.draw(|f| {
46            let chunks = layout.split(f.area());
47            let top_chunks = top_layout.split(chunks[0]);
48
49            // Top section
50            f.render_widget(&file_explorer.widget(), top_chunks[0]);
51            f.render_widget(
52                Paragraph::new(file_content).block(
53                    Block::default()
54                        .borders(Borders::ALL)
55                        .border_type(BorderType::Double),
56                ),
57                top_chunks[1],
58            );
59
60            // Bottom section
61            f.render_widget(
62                Paragraph::new(selected_files.clone()).block(
63                    Block::default()
64                        .borders(Borders::ALL)
65                        .title("q:Quit, c: copy selected file contents to clipboard, p: copy paths to clipboard"),
66                ),
67                chunks[1],
68            );
69        })?;
70
71        // Read the next event from the terminal.
72        let event = read()?;
73        if let Event::Key(key) = event {
74            match key.code {
75                KeyCode::Char('q') => break, // Quit the application
76                KeyCode::Char('c') => {
77                    // Copy selected file paths to clipboard
78                    if let Ok(mut clipboard) = ClipboardContext::new() {
79                        if let Err(err) = clipboard.set_contents(get_selected_files_content(
80                            &file_explorer.selected_files(),
81                        )) {
82                            eprintln!("Failed to copy to clipboard: {}", err);
83                        }
84                    } else {
85                        eprintln!("Clipboard not available.");
86                    }
87                }
88                KeyCode::Char('p') => {
89                    // Copy selected file paths to clipboard
90                    if let Ok(mut clipboard) = ClipboardContext::new() {
91                        if let Err(err) = clipboard.set_contents(selected_files.clone()) {
92                            eprintln!("Failed to copy to clipboard: {}", err);
93                        }
94                    } else {
95                        eprintln!("Clipboard not available.");
96                    }
97                }
98                _ => {}
99            }
100        }
101        // Handle the event in the file explorer.
102        file_explorer.handle(&event)?;
103    }
104
105    disable_raw_mode()?;
106    stdout().execute(LeaveAlternateScreen)?;
107    // Print the selected file paths to stdout.
108    for file in file_explorer.selected_files() {
109        println!("{}", file.path().display());
110    }
111    Ok(())
112}
113
114fn get_file_content(path: &Path) -> io::Result<String> {
115    let mut content = String::new();
116
117    // If the path is a file, read its content.
118    if path.is_file() {
119        content = read_to_string(path)?;
120    }
121
122    Ok(content)
123}
124fn get_selected_files_content(selected_files: &Vec<File>) -> String {
125    selected_files
126        .iter()
127        .map(|file| {
128            let path = file.path().display().to_string();
129            let content = get_file_content(file.path())
130                .unwrap_or_else(|_| "Unable to read file.".to_string());
131            format!("File: {}\nContent:\n{}\n", path, content)
132        })
133        .collect::<Vec<String>>()
134        .join("\n")
135}
Source

pub const fn is_dir(&self) -> bool

Returns true is the file is a directory.

§Examples

Suppose you have this tree file, with passport.png selected inside file_explorer:

/
├── .git
└── Documents
    ├── passport.png  <- selected
    └── resume.pdf

You can know if the selected file is a directory like this:

use fpicker::FileExplorer;

let file_explorer = FileExplorer::new().unwrap();

/* user select `password.png` */

let file = file_explorer.current();
assert_eq!(file.is_dir(), false);

/* User select `Documents` */

let file = file_explorer.current();
assert_eq!(file.is_dir(), false);
Source

pub fn set_selected(&mut self, selected: bool)

Source

pub const fn is_selected(&self) -> bool

Trait Implementations§

Source§

impl Clone for File

Source§

fn clone(&self) -> File

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for File

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Hash for File

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for File

Source§

fn eq(&self, other: &File) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for File

Source§

impl StructuralPartialEq for File

Auto Trait Implementations§

§

impl Freeze for File

§

impl RefUnwindSafe for File

§

impl Send for File

§

impl Sync for File

§

impl Unpin for File

§

impl UnwindSafe for File

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.