/ src / bin / dir_list.rs
dir_list.rs
 1  use cursive::traits::*;
 2  use cursive::views::{Dialog, SelectView};
 3  use cursive::{Cursive, CursiveExt};
 4  use std::path::PathBuf;
 5  use walkdir::WalkDir;
 6  
 7  fn main() {
 8      let mut siv = Cursive::default();
 9      siv.add_global_callback('q', Cursive::quit);
10  
11      // Add an initial button to start browsing directories
12      siv.add_layer(
13          Dialog::text("Welcome to the Directory Browser!")
14              .button("Browse", |siv| {
15                  // Call show_directory on button click
16                  show_directory(siv, PathBuf::from("."));
17              })
18              .button("Quit", |siv| siv.quit()),
19      );
20  
21      siv.run();
22  }
23  
24  fn show_directory(siv: &mut Cursive, path: PathBuf) {
25      let mut select_view = SelectView::new();
26  
27      // Read the contents of the directory
28      for entry in WalkDir::new(&path)
29          .min_depth(1)
30          .max_depth(1)
31          .into_iter()
32          .filter_map(Result::ok)
33      {
34          let file_name = entry.file_name().to_string_lossy().to_string();
35          let entry_path = entry.path().to_path_buf();
36          if entry.file_type().is_dir() {
37              select_view.add_item(format!("📁 {}", file_name), entry_path);
38          } else {
39              select_view.add_item(file_name, entry_path);
40          }
41      }
42  
43      select_view.set_on_submit(move |siv, selected_path: &PathBuf| {
44          if selected_path.is_dir() {
45              // If it's a directory, show its contents
46              show_directory(siv, selected_path.clone());
47          } else {
48              // If it's a file, show a message
49              siv.add_layer(Dialog::info(format!(
50                  "You selected the file: {}",
51                  selected_path.display()
52              )));
53          }
54      });
55  
56      // Replace the current layer with the new SelectView
57      siv.add_layer(
58          Dialog::around(select_view.scrollable())
59              .title(format!("Contents of: {}", path.display()))
60              .button("Back", back),
61      );
62  }
63  
64  fn back(s: &mut Cursive) {
65      s.pop_layer();
66  }