Skip to content

Commit

Permalink
initial implementation of file information display
Browse files Browse the repository at this point in the history
  • Loading branch information
hacknus committed Nov 10, 2024
1 parent 02984b7 commit a0ab0c3
Show file tree
Hide file tree
Showing 8 changed files with 257 additions and 9 deletions.
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ license = "MIT"

[dependencies]
egui = { version = "0.29.1", default-features = false }

# Used to fetch user folders
directories = "5.0"

Expand All @@ -34,6 +33,8 @@ serde = { version = "1", features = ["derive"], optional = true }

# Used to canonicalize paths
dunce = "1.0.5"
image = { version = "0.25", default-features = false, features = ["png"] }
chrono = "0.4.38"

[features]
default = ["serde", "default_fonts"]
Expand Down
1 change: 1 addition & 0 deletions examples/multilingual/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ fn get_labels_german() -> FileDialogLabels {
show_hidden: " Versteckte Dateien anzeigen".to_string(),
show_system_files: " Systemdateien anzeigen".to_string(),

heading_meta: "Metadaten".to_string(),
heading_pinned: "Angeheftet".to_string(),
heading_places: "Orte".to_string(),
heading_devices: "Medien".to_string(),
Expand Down
4 changes: 3 additions & 1 deletion examples/select_file/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@ edition = "2021"

[dependencies]
eframe = { workspace = true }
egui-file-dialog = { path = "../../"}
egui_extras = { version = "0.29", features = ["all_loaders", "image", "file"] }
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
egui-file-dialog = { path = "../../" }
6 changes: 5 additions & 1 deletion examples/select_file/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ fn main() -> eframe::Result<()> {
eframe::run_native(
"File dialog example",
eframe::NativeOptions::default(),
Box::new(|ctx| Ok(Box::new(MyApp::new(ctx)))),
Box::new(|ctx|
{
egui_extras::install_image_loaders(&ctx.egui_ctx);
Ok(Box::new(MyApp::new(ctx)))
}),
)
}
7 changes: 7 additions & 0 deletions src/config/labels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,11 @@ pub struct FileDialogLabels {
/// Text used for the option to show or hide system files.
pub show_system_files: String,

// ------------------------------------------------------------------------
// Right panel:
/// Heading of the "Pinned" sections in the left panel
pub heading_meta: String,

// ------------------------------------------------------------------------
// Left panel:
/// Heading of the "Pinned" sections in the left panel
Expand Down Expand Up @@ -132,6 +137,8 @@ impl Default for FileDialogLabels {
show_hidden: " Show hidden".to_string(),
show_system_files: " Show system files".to_string(),

heading_meta: "Information".to_string(),

heading_pinned: "Pinned".to_string(),
heading_places: "Places".to_string(),
heading_devices: "Devices".to_string(),
Expand Down
43 changes: 43 additions & 0 deletions src/data/meta_data.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use image::RgbaImage;

#[derive(Debug, Default)]
pub struct MetaData {
pub file_name: String,
pub dimensions: Option<(usize, usize)>,
pub scaled_dimensions: Option<(usize, usize)>,
pub preview_image_bytes: Option<RgbaImage>,
pub preview_text: Option<String>,
pub file_size: Option<String>,
pub file_type: Option<String>,
pub file_modified: Option<String>,
pub file_created: Option<String>,
}

pub fn format_bytes(bytes: u64) -> String {
const KB: u64 = 1024;
const MB: u64 = KB * 1024;
const GB: u64 = MB * 1024;
const TB: u64 = GB * 1024;

if bytes >= TB {
format!("{:.2} TB", bytes as f64 / TB as f64)
} else if bytes >= GB {
format!("{:.2} GB", bytes as f64 / GB as f64)
} else if bytes >= MB {
format!("{:.2} MB", bytes as f64 / MB as f64)
} else if bytes >= KB {
format!("{:.2} KB", bytes as f64 / KB as f64)
} else {
format!("{} B", bytes)
}
}

pub fn format_pixels(pixels: usize) -> String {
const K: usize = 1_000;
const M: usize = K * 1_000;
if pixels >= K {
format!("{:.2} MPx", pixels as f64 / M as f64)
} else {
format!("{} Px", pixels)
}
}
2 changes: 2 additions & 0 deletions src/data/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,6 @@ mod disks;
pub use disks::{Disk, Disks};

mod user_directories;
pub mod meta_data;

pub use user_directories::UserDirectories;
200 changes: 194 additions & 6 deletions src/file_dialog.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
use std::fmt::Debug;
use std::io;
use std::path::{Path, PathBuf};

use egui::text::{CCursor, CCursorRange};

use crate::config::{
FileDialogConfig, FileDialogKeyBindings, FileDialogLabels, FileDialogStorage, FileFilter,
Filter, QuickAccess,
};
use crate::create_directory_dialog::CreateDirectoryDialog;
use crate::data::meta_data::{format_bytes, format_pixels, MetaData};
use crate::data::{
DirectoryContent, DirectoryContentState, DirectoryEntry, Disk, Disks, UserDirectories,
};
use crate::modals::{FileDialogModal, ModalAction, ModalState, OverwriteFileModal};
use chrono::{DateTime, Local};
use egui::text::{CCursor, CCursorRange};
use image::GenericImageView;
use std::fmt::Debug;
use std::path::{Path, PathBuf};
use std::{fs, io};

/// Represents the mode the file dialog is currently in.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
Expand Down Expand Up @@ -79,6 +80,9 @@ pub struct FileDialog {
/// The configuration of the file dialog
config: FileDialogConfig,

/// Metadata for selected file
metadata: MetaData,

/// Stack of modal windows to be displayed.
/// The top element is what is currently being rendered.
modals: Vec<Box<dyn FileDialogModal + Send + Sync>>,
Expand Down Expand Up @@ -196,6 +200,7 @@ impl FileDialog {
Self {
config: FileDialogConfig::default(),

metadata: MetaData::default(),
modals: Vec::new(),

mode: DialogMode::SelectDirectory,
Expand Down Expand Up @@ -1094,6 +1099,15 @@ impl FileDialog {
self.ui_update_left_panel(ui);
});
}
if self.config.show_left_panel {
egui::SidePanel::right(self.window_id.with("right_panel"))
.resizable(true)
.default_width(150.0)
.width_range(90.0..=250.0)
.show_inside(ui, |ui| {
self.ui_update_right_panel(ui);
});
}

// Optionally, show a custom right panel (see `update_with_custom_right_panel`)
if let Some(f) = right_panel_fn {
Expand Down Expand Up @@ -1535,6 +1549,180 @@ impl FileDialog {
});
}

/// Updates the right panel of the dialog. This contains the metadata of the selected file.
fn ui_update_right_panel(&mut self, ui: &mut egui::Ui) {
ui.with_layout(egui::Layout::top_down_justified(egui::Align::LEFT), |ui| {
// Spacing multiplier used between sections in the right sidebar
const SPACING_MULTIPLIER: f32 = 4.0;

egui::containers::ScrollArea::vertical()
.auto_shrink([false, false])
.show(ui, |ui| {
// Spacing for the first section in the right sidebar
let mut spacing = ui.ctx().style().spacing.item_spacing.y * 2.0;

// Update paths pinned to the left sidebar by the user
if self.config.show_pinned_folders && self.ui_update_pinned_paths(ui, spacing) {
spacing = ui.ctx().style().spacing.item_spacing.y * SPACING_MULTIPLIER;
}

ui.add_space(spacing);
ui.label(self.config.labels.heading_meta.as_str());
ui.add_space(spacing);

if let Some(item) = &self.selected_item {
let file_name = item.file_name();
if self.metadata.file_name != file_name {
// update metadata
let metadata = fs::metadata(item.as_path()).unwrap();
// Display creation and last modified dates
if let Ok(created) = metadata.created() {
let created: DateTime<Local> = created.into();
self.metadata.file_created =
Some(created.format("%Y-%m-%d %H:%M:%S").to_string());
}
if let Ok(modified) = metadata.modified() {
let modified: DateTime<Local> = modified.into();
self.metadata.file_modified =
Some(modified.format("%Y-%m-%d %H:%M:%S").to_string());
}
self.metadata.file_size = Some(format_bytes(metadata.len()));
self.metadata.file_name = file_name.to_string();

// Determine the file type and display relevant metadata
if let Some(ext) = item.as_path().extension().and_then(|e| e.to_str()) {
match ext.to_lowercase().as_str() {
"png" | "jpg" | "jpeg" | "bmp" | "gif" | "tiff" => {
self.metadata.file_type = Some("Image".to_string());

// For image files, show dimensions and color space
if let Ok(img) = image::open(item.as_path()) {
let (width, height) = img.dimensions();
self.metadata.dimensions =
Some((width as usize, height as usize));

let new_width = 100;
let (original_width, original_height) =
img.dimensions();
let new_height = (original_height as f32
* new_width as f32
/ original_width as f32)
as u32;

// Resize the image to the new dimensions (100px width)
let img = img.resize(
new_width,
new_height,
image::imageops::FilterType::Lanczos3,
);
self.metadata.scaled_dimensions =
Some((img.width() as usize, img.height() as usize));

self.metadata.preview_image_bytes =
Some(img.into_rgba8());
self.metadata.preview_text = None;
}
}
"txt" | "json" | "md" | "toml" | "csv" | "rtf" | "xml"
| "rs" | "py" | "c" | "h" | "cpp" | "hpp" => {
self.metadata.file_type = Some("Textfile".to_string());

// For text files, show content
if let Ok(content) = fs::read_to_string(item.as_path()) {
self.metadata.preview_text = Some(content);
}
self.metadata.preview_image_bytes = None;
self.metadata.dimensions = None;
}
_ => {
self.metadata.file_type = Some("Unknown".to_string());

self.metadata.preview_image_bytes = None;
self.metadata.dimensions = None;
self.metadata.preview_text = None;
}
}
} else {
self.metadata.file_type = Some("Unknown".to_string());

self.metadata.preview_image_bytes = None;
self.metadata.dimensions = None;
self.metadata.preview_text = None;
}
}

self.metadata.file_name = file_name.to_string();
ui.add_space(spacing);
if let Some(content) = &self.metadata.preview_text {
egui::ScrollArea::vertical()
.max_height(100.0)
.show(ui, |ui| {
ui.add(
egui::TextEdit::multiline(&mut content.clone())
.code_editor(),
);
});
}
else if let Some(img) = &self.metadata.preview_image_bytes {
if let Some((width, height)) = &self.metadata.scaled_dimensions {
// Convert image into `egui::ColorImage`
let color_image = egui::ColorImage::from_rgba_unmultiplied(
[*width, *height],
img.as_flat_samples().as_slice(),
);

// Load the image as a texture in `egui`
let texture = ui.ctx().load_texture(
"loaded_image",
color_image,
egui::TextureOptions::default(),
);

ui.vertical_centered(|ui| {
// Display the image
ui.image(&texture);
});
}
} else {
ui.vertical_centered(|ui| {
ui.label(egui::RichText::from("📁").size(120.0));
});
}
ui.add_space(spacing);
egui::Grid::new("meta_data")
.num_columns(2)
.striped(true)
.min_col_width(200.0 / 2.0)
.max_col_width(200.0 / 2.0)
.show(ui, |ui| {
ui.label("File name: ");
ui.label(format!("{}", self.metadata.file_name));
ui.end_row();
ui.label("File type: ");
ui.label(format!("{}", self.metadata.file_type.clone().unwrap_or("None".to_string())));
ui.end_row();
ui.label("File size: ");
ui.label(format!(
"{}",
self.metadata.file_size.clone().unwrap_or("NAN".to_string())
));
ui.end_row();
if let Some((width, height)) = self.metadata.dimensions {
ui.label("Dimensions: ");

ui.label(format!("{} x {}", width, height));
ui.end_row();
ui.label("Pixel count: ");

ui.label(format!("{}", format_pixels(width * height)));
ui.end_row()
}
});
}
});
});
}

/// Updates the left panel of the dialog. Including the list of the user directories (Places)
/// and system disks (Devices, Removable Devices).
fn ui_update_left_panel(&mut self, ui: &mut egui::Ui) {
Expand Down

0 comments on commit a0ab0c3

Please sign in to comment.