structure
This commit is contained in:
299
client-gui/src/gui_app.rs
Normal file
299
client-gui/src/gui_app.rs
Normal file
@@ -0,0 +1,299 @@
|
||||
use client_network::{node_hash_to_hex_string, MerkleNode, NetworkCommand, NetworkEvent, NodeHash};
|
||||
use crossbeam_channel::{Receiver, Sender};
|
||||
use egui::{Align, Button, CentralPanel, CollapsingHeader, Context, Layout, ScrollArea, SidePanel, TopBottomPanel, Ui, ViewportCommand};
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub struct FileNode {
|
||||
pub name: String,
|
||||
pub is_dir: bool,
|
||||
pub hash_id: String, // The Merkle root or leaf hash (String)
|
||||
pub children: Option<Vec<FileNode>>,
|
||||
}
|
||||
|
||||
|
||||
fn build_file_node_recursively(
|
||||
hash: &NodeHash,
|
||||
storage: &HashMap<NodeHash, MerkleNode>,
|
||||
name: String,
|
||||
) -> Option<FileNode> {
|
||||
let node = storage.get(hash)?;
|
||||
let hash_id = hex::encode(hash);
|
||||
|
||||
match node {
|
||||
MerkleNode::Directory(dir_node) => {
|
||||
// Recurse through all entries to build children
|
||||
let children: Vec<FileNode> = dir_node.entries.iter().filter_map(|entry| {
|
||||
let filename_lossy = String::from_utf8_lossy(&entry.filename)
|
||||
.trim_end_matches('\0')
|
||||
.to_string();
|
||||
|
||||
build_file_node_recursively(&entry.content_hash, storage, filename_lossy)
|
||||
}).collect();
|
||||
|
||||
Some(FileNode {
|
||||
name,
|
||||
is_dir: true,
|
||||
hash_id,
|
||||
children: Some(children),
|
||||
})
|
||||
}
|
||||
MerkleNode::BigDirectory(big_dir_node) => {
|
||||
// In a real system, BigDirectory children would have names stored in an index.
|
||||
// Here, we generate dummy names to show recursion working.
|
||||
let children: Vec<FileNode> = big_dir_node.children_hashes.iter().filter_map(|child_hash| {
|
||||
let dummy_name = format!("chunk_group_{}", &hex::encode(child_hash)[..4]);
|
||||
build_file_node_recursively(child_hash, storage, dummy_name)
|
||||
}).collect();
|
||||
|
||||
Some(FileNode {
|
||||
name,
|
||||
is_dir: true,
|
||||
hash_id,
|
||||
children: Some(children),
|
||||
})
|
||||
}
|
||||
// Chunk or Big nodes are files (leaves in the file tree)
|
||||
_ => Some(FileNode {
|
||||
name,
|
||||
is_dir: false,
|
||||
hash_id,
|
||||
children: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub fn convert_merkle_to_file_nodes(root_hash: NodeHash, storage: &HashMap<NodeHash, MerkleNode>) -> Option<FileNode> {
|
||||
let root_name = "/".to_string();
|
||||
build_file_node_recursively(&root_hash, storage, root_name)
|
||||
}
|
||||
|
||||
// --- Main Application Struct ---
|
||||
pub struct P2PClientApp {
|
||||
// Communication channels
|
||||
network_cmd_tx: Sender<NetworkCommand>,
|
||||
network_event_rx: Receiver<NetworkEvent>,
|
||||
|
||||
// GUI State
|
||||
status_message: String,
|
||||
known_peers: Vec<String>,
|
||||
connect_address_input: String,
|
||||
|
||||
peer_root_hash: HashMap<String, String>, // peer_id -> root_hash
|
||||
|
||||
// Key: Parent Directory Hash (String), Value: List of children FileNode
|
||||
loaded_tree_nodes: HashMap<String, FileNode>,
|
||||
|
||||
// Which peer's tree we are currently displaying
|
||||
active_peer_id: Option<String>,
|
||||
active_root_hash: Option<String>,
|
||||
}
|
||||
|
||||
impl P2PClientApp {
|
||||
pub fn new(cmd_tx: Sender<NetworkCommand>, event_rx: Receiver<NetworkEvent>) -> Self {
|
||||
let (root_hash, tree) = MerkleNode::generate_random_tree(5).expect("Couldn't generate tree");
|
||||
let mut peer_root_hash = HashMap::new();
|
||||
peer_root_hash.insert("bob".to_string(), "yoyoyoyo".to_string());
|
||||
|
||||
let mut loaded_tree_nodes = HashMap::new();
|
||||
loaded_tree_nodes.insert(node_hash_to_hex_string(&root_hash), convert_merkle_to_file_nodes(root_hash, &tree).expect("Couldn't convert tree"));
|
||||
|
||||
Self {
|
||||
network_cmd_tx: cmd_tx,
|
||||
network_event_rx: event_rx,
|
||||
status_message: "Client Initialized. Awaiting network status...".to_string(),
|
||||
known_peers: vec![
|
||||
"bob".to_string()
|
||||
],
|
||||
connect_address_input: "127.0.0.1:8080".to_string(),
|
||||
peer_root_hash,
|
||||
loaded_tree_nodes,
|
||||
active_peer_id: None,
|
||||
active_root_hash: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- eframe::App Trait Implementation ---
|
||||
|
||||
impl eframe::App for P2PClientApp {
|
||||
fn update(&mut self, ctx: &Context, _frame: &mut eframe::Frame) {
|
||||
|
||||
// 1. Process incoming Network Events
|
||||
// We poll the channel and update the GUI state for every event received.
|
||||
while let Ok(event) = self.network_event_rx.try_recv() {
|
||||
match event {
|
||||
NetworkEvent::PeerConnected(addr) => {
|
||||
self.status_message = format!("✅ Peer connected: {}", addr);
|
||||
if !self.known_peers.contains(&addr) {
|
||||
self.known_peers.push(addr);
|
||||
}
|
||||
}
|
||||
NetworkEvent::PeerListUpdated(peers) => {
|
||||
self.known_peers = peers;
|
||||
}
|
||||
NetworkEvent::FileTreeReceived(_peer_id, _) => {
|
||||
// self.loaded_tree_nodes.insert(_peer_id, tree);
|
||||
self.status_message = "🔄 File tree updated successfully.".to_string();
|
||||
}
|
||||
NetworkEvent::FileTreeRootReceived(peer_id, root_hash) => {
|
||||
self.status_message = format!("🔄 Received Merkle Root from {}: {}", peer_id, &root_hash[..8]);
|
||||
self.peer_root_hash.insert(peer_id.clone(), root_hash.clone());
|
||||
|
||||
self.active_peer_id = Some(peer_id.clone());
|
||||
self.active_root_hash = Some(root_hash.clone());
|
||||
|
||||
// Request the content of the root directory immediately
|
||||
let _ = self.network_cmd_tx.send(NetworkCommand::RequestDirectoryContent(
|
||||
peer_id,
|
||||
root_hash,
|
||||
));
|
||||
}
|
||||
// Handle other events like Disconnect, Error, etc.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Menu Bar
|
||||
TopBottomPanel::top("top_panel").show(ctx, |ui| {
|
||||
egui::MenuBar::new().ui(ui, |ui| {
|
||||
ui.menu_button("File", |ui| {
|
||||
if ui.button("Quit").clicked() {
|
||||
// Use ViewportCommand to request a close
|
||||
ctx.send_viewport_cmd(ViewportCommand::Close);
|
||||
}
|
||||
});
|
||||
|
||||
ui.menu_button("Network", |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Connect to:");
|
||||
ui.text_edit_singleline(&mut self.connect_address_input);
|
||||
if ui.button("Connect").clicked() {
|
||||
let addr = self.connect_address_input.clone();
|
||||
let _ = self.network_cmd_tx.send(NetworkCommand::ConnectPeer(addr));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// 3. Right-sided Panel (Known Peers)
|
||||
SidePanel::right("right_panel").resizable(true).min_width(180.0).show(ctx, |ui| {
|
||||
ui.heading("🌐 Known Peers");
|
||||
ui.separator();
|
||||
ScrollArea::vertical().show(ui, |ui| {
|
||||
if self.known_peers.is_empty() {
|
||||
ui.add_space(10.0);
|
||||
ui.label("No active peers.");
|
||||
} else {
|
||||
for peer in &self.known_peers {
|
||||
let is_active = self.active_peer_id.as_ref().map_or(false, |id| id == peer);
|
||||
let root_hash_str = self.peer_root_hash.get(peer)
|
||||
.map(|h| format!("Root: {}", &h[..8]))
|
||||
.unwrap_or_else(|| "Root: N/A".to_string());
|
||||
|
||||
if ui.selectable_label(is_active, format!("{} ({})", peer, root_hash_str)).clicked() {
|
||||
// Switch to displaying this peer's tree
|
||||
self.active_peer_id = Some(peer.clone());
|
||||
if let Some(hash) = self.peer_root_hash.get(peer) {
|
||||
self.active_root_hash = Some(hash.clone());
|
||||
|
||||
// Request root content if not loaded
|
||||
if !self.loaded_tree_nodes.contains_key(hash) {
|
||||
let _ = self.network_cmd_tx.send(NetworkCommand::RequestDirectoryContent(
|
||||
peer.clone(),
|
||||
hash.clone(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// 4. Central Panel (Filesystem Tree)
|
||||
CentralPanel::default().show(ctx, |ui| {
|
||||
ui.heading("📂 Decentralized File System");
|
||||
ui.separator();
|
||||
|
||||
if let Some(root_hash) = &self.active_root_hash {
|
||||
if let Some(root_nodes) = self.loaded_tree_nodes.get(root_hash) {
|
||||
ScrollArea::vertical().show(ui, |ui| {
|
||||
// Start drawing the tree from the root hash
|
||||
self.draw_file_tree(ui, root_nodes, 0);
|
||||
});
|
||||
} else {
|
||||
ui.label(format!("Loading root content for hash: {}", &root_hash[..8]));
|
||||
}
|
||||
} else {
|
||||
ui.label("Connect to a peer to view a file tree.");
|
||||
}
|
||||
|
||||
ui.separator();
|
||||
ui.add_space(5.0);
|
||||
// This is now safe because draw_file_tree only takes an immutable borrow
|
||||
// ui.label(format!("Status: {}", self.status_message));
|
||||
});
|
||||
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Helper for Drawing the Recursive File Tree ---
|
||||
|
||||
impl P2PClientApp {
|
||||
fn draw_file_tree(&self, ui: &mut Ui, node: &FileNode, depth: usize) {
|
||||
let indent_space = 15.0 * depth as f32;
|
||||
let active_peer_id = self.active_peer_id.clone();
|
||||
|
||||
let entry_hash = &node.hash_id;
|
||||
let filename = &node.name;
|
||||
let is_dir = node.is_dir;
|
||||
|
||||
if is_dir {
|
||||
// --- Directory Node: Check if content (children) is already loaded (stored in the map) ---
|
||||
|
||||
if let Some(children) = node.children.as_ref() {
|
||||
// Content is already loaded: draw the collapsing header and recurse
|
||||
CollapsingHeader::new(format!("📁 {}", filename))
|
||||
.default_open(false)
|
||||
.enabled(true)
|
||||
.show(ui, |ui| {
|
||||
// Recursive call: iterate over children and call draw_file_tree for each
|
||||
for child_node in children {
|
||||
self.draw_file_tree(ui, child_node, depth + 1);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// Content is NOT loaded: show a clickable button to request loading
|
||||
let response = ui.with_layout(Layout::left_to_right(Align::Min), |ui| {
|
||||
ui.add_space(indent_space);
|
||||
ui.add(Button::new(format!("▶️ {} (Load)", filename)).small()).on_hover_text(format!("Hash: {}...", &entry_hash[..8]));
|
||||
}).response;
|
||||
|
||||
if response.clicked() {
|
||||
if let Some(peer_id) = active_peer_id.clone() {
|
||||
let _ = self.network_cmd_tx.send(NetworkCommand::RequestDirectoryContent(
|
||||
peer_id,
|
||||
entry_hash.clone(),
|
||||
));
|
||||
// self.status_message = format!("Requested directory content for: {}...", &entry_hash[..8]);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// --- File Node (Chunk or Big) ---
|
||||
ui.with_layout(Layout::left_to_right(Align::Center), |ui| {
|
||||
ui.add_space(indent_space);
|
||||
if ui.selectable_label(false, format!("📄 {} (Hash: {}...)", filename, &entry_hash[..8])).on_hover_text("Click to request file chunks...").clicked() {
|
||||
if let Some(peer_id) = active_peer_id.clone() {
|
||||
let _ = self.network_cmd_tx.send(NetworkCommand::RequestChunk(peer_id, entry_hash.clone()));
|
||||
// self.status_message = format!("Requested file chunks for: {}...", &entry_hash[..8]);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user