From 9023fc351ac9c21bc3daa1aa8eb19b2f879849a5 Mon Sep 17 00:00:00 2001 From: FluxxCode Date: Sun, 14 Jan 2024 23:30:00 +0100 Subject: [PATCH] Dynamically load directory content --- examples/sandbox/src/main.rs | 6 ++-- src/file_explorer.rs | 55 +++++++++++++++++++++++++++++------- 2 files changed, 49 insertions(+), 12 deletions(-) diff --git a/examples/sandbox/src/main.rs b/examples/sandbox/src/main.rs index c6c64385..2b68619a 100644 --- a/examples/sandbox/src/main.rs +++ b/examples/sandbox/src/main.rs @@ -7,9 +7,11 @@ struct MyApp { impl MyApp { pub fn new(_cc: &eframe::CreationContext) -> Self { - Self { + let mut obj = Self { file_explorer: FileExplorer::new() - } + }; + obj.file_explorer.open(); + obj } } diff --git a/src/file_explorer.rs b/src/file_explorer.rs index 7d907fb9..fbffadc7 100644 --- a/src/file_explorer.rs +++ b/src/file_explorer.rs @@ -1,5 +1,7 @@ +use std::{fs, io}; pub struct FileExplorer { + directory_content: Vec, search_value: String } @@ -11,7 +13,15 @@ impl Default for FileExplorer { impl FileExplorer { pub fn new() -> Self { - FileExplorer { search_value: String::new() } + FileExplorer { + directory_content: vec![], + search_value: String::new() } + } + + // TODO: Enable option to set initial directory + pub fn open(&mut self) { + // TODO: Error handling + let _ = self.load_directory("./"); } pub fn update(&mut self, ctx: &egui::Context) { @@ -146,15 +156,40 @@ impl FileExplorer { } fn update_central_panel(&mut self, ui: &mut egui::Ui) { - // NOTE: These are currently only hardcoded test values! - let _ = ui.selectable_label(false, "🗀 projects"); - let _ = ui.selectable_label(false, "🗀 documents"); - let _ = ui.selectable_label(false, "🗀 images"); - let _ = ui.selectable_label(false, "🗀 music"); - - let _ = ui.selectable_label(false, "🖹 some_config.txt"); - let _ = ui.selectable_label(false, "🖹 README.md"); - let _ = ui.selectable_label(false, "🖹 LICENSE.md"); + for item in self.directory_content.iter() { + let path = item.path(); + + let icon = match path.is_dir() { + true => "🗀", + _ => "🖹" + }; + + // Is there a way to write this better? + let file_name = match path.file_name() { + Some(x) => { + match x.to_str() { + Some(v) => v, + _ => continue + } + }, + _ => continue + }; + + let _ = ui.selectable_label(false, format!("{} {}", icon, file_name)); + } } + fn load_directory(&mut self, path: &str) -> io::Result<()> { + let paths = fs::read_dir(path)?; + + self.directory_content.clear(); + for path in paths { + match path { + Ok(entry) => self.directory_content.push(entry), + _ => continue + }; + } + + Ok(()) + } }