[WIP] Daemon & CLI

This commit is contained in:
Alex-Emmet 2026-07-23 23:13:02 +02:00
commit 8b158108bb
100 changed files with 6519 additions and 1596 deletions

View file

@ -2,7 +2,6 @@ use crossterm::event::{KeyCode, KeyEvent};
use ratatui::{
Frame,
layout::Rect,
style::{Color, Style},
text::{Line, Span},
widgets::{Block, Borders, Paragraph},
};
@ -18,6 +17,7 @@ use crate::{
elements::elements::{Element, InteractableElement, JoinableElement},
interaction_result::InteractionResult,
ipc_client::IpcClient,
render_context::RenderContext,
util::borders::draw_block_joins,
};
@ -34,6 +34,7 @@ pub struct ConsoleCard {
cursor: Arc<Mutex<bool>>,
last_swap: Arc<Mutex<Instant>>,
pending_restore: Arc<Mutex<Option<String>>>,
pending_confirmation: Option<String>,
}
impl ConsoleCard {
@ -49,6 +50,7 @@ impl ConsoleCard {
cursor: Arc::new(Mutex::new(true)),
last_swap: Arc::new(Mutex::new(Instant::now())),
pending_restore: Arc::new(Mutex::new(None)),
pending_confirmation: None,
}
}
@ -85,26 +87,25 @@ impl ConsoleCard {
}
}
fn cursor_spans(&self) -> Vec<Span<'static>> {
fn cursor_spans(&self, theme: &crate::theme::ResolvedTheme) -> Vec<Span<'static>> {
let cursor_visible = self.cursor_visible();
let cursor_style = Style::default().fg(Color::White).bg(Color::DarkGray);
let mut spans = Vec::new();
if self.content.is_empty() {
if self.focused {
if cursor_visible {
spans.push(Span::styled(" ", cursor_style));
Self::push_cursor(&mut spans, theme);
} else {
spans.push(Span::styled(" ", Style::default().fg(Color::White)));
spans.push(Span::styled(" ", theme.console.text));
}
spans.push(Span::styled(
"send command (/help for info)",
Style::default().fg(Color::DarkGray),
theme.console.hint,
));
} else {
spans.push(Span::styled(
" send command (/help for info)",
Style::default().fg(Color::DarkGray),
theme.console.hint,
));
}
return spans;
@ -119,52 +120,64 @@ impl ConsoleCard {
if prefix_len > 0 && before.len() >= prefix_len {
let prefix = &before[..prefix_len];
let rest = &before[prefix_len..];
spans.push(Span::styled(
prefix.to_string(),
Self::style_for_part(true, false, false),
));
spans.push(Span::styled(prefix.to_string(), theme.console.prefix));
if !rest.is_empty() {
spans.push(Span::styled(
rest.to_string(),
Style::default().fg(Color::White),
));
spans.push(Span::styled(rest.to_string(), theme.console.text));
}
} else if !before.is_empty() {
spans.push(Span::styled(
before.clone(),
Style::default().fg(Color::White),
));
spans.push(Span::styled(before.clone(), theme.console.text));
}
if cursor_visible {
spans.push(Span::styled(" ", cursor_style));
Self::push_cursor(&mut spans, theme);
}
if !after.is_empty() {
spans.push(Span::styled(after, Style::default().fg(Color::White)));
spans.push(Span::styled(after, theme.console.text));
}
spans
}
fn style_for_part(is_prefix: bool, is_hint: bool, is_error: bool) -> Style {
if is_error {
return Style::default().fg(Color::Red);
fn push_cursor(spans: &mut Vec<Span<'static>>, theme: &crate::theme::ResolvedTheme) {
match &theme.console.cursor {
crate::theme::CursorPresentation::StyledCell(style) => {
spans.push(Span::styled(" ", *style))
}
crate::theme::CursorPresentation::Character { glyph, style } => {
spans.push(Span::styled(*glyph, *style))
}
}
if is_hint {
return Style::default().fg(Color::DarkGray);
}
if is_prefix {
return Style::default().fg(Color::DarkGray);
}
Style::default().fg(Color::White)
}
fn render_cursor_spans(&self) -> Vec<Span<'static>> {
self.cursor_spans()
fn render_cursor_spans(&self, theme: &crate::theme::ResolvedTheme) -> Vec<Span<'static>> {
if let Some(command) = &self.pending_confirmation {
return vec![Span::styled(
format!("Confirm `{command}`? [y/N]"),
theme.console.confirmation,
)];
}
self.cursor_spans(theme)
}
fn is_destructive(command: &str) -> bool {
matches!(
command.trim_start_matches('/').trim(),
"restart" | "reload" | "stop" | "shutdown" | "regenerate keys"
) || command
.trim_start_matches('/')
.trim_start()
.starts_with("user remove ")
}
fn dispatch_command(&self, command: String) {
let ipc = self.ipc.clone();
let restore = self.pending_restore.clone();
tokio::spawn(async move {
if ipc.send_command(0, command.clone()).await.is_err() {
*restore.lock().unwrap() = Some(command);
}
});
}
fn move_cursor_left(&mut self) {
@ -212,28 +225,34 @@ impl Element for ConsoleCard {
self
}
fn render(&self, f: &mut Frame, r: Rect) {
fn render(&self, f: &mut Frame, r: Rect, context: &RenderContext<'_>) {
let block = Block::default()
.borders(self.borders)
.title(self.title.clone())
.title_style(Style::default().fg(Color::White))
.title_style(context.theme.console.title)
.border_style(if self.focused {
Style::default().fg(Color::Yellow)
context.theme.console.focused_border
} else {
Style::default()
context.theme.console.border
})
.style(if self.focused {
Style::default().fg(Color::White)
} else {
Style::default()
});
.style(context.theme.console.text);
let spans = self.render_cursor_spans();
let spans = self.render_cursor_spans(context.theme);
let par = Paragraph::new(Line::from(spans))
.block(block)
.scroll((0, 0));
f.render_widget(par, r);
draw_block_joins(f, r, self.borders, self.joins);
draw_block_joins(
f,
r,
self.borders,
self.joins,
if self.focused {
context.theme.borders.focused
} else {
context.theme.borders.normal
},
);
}
}
@ -287,6 +306,13 @@ impl InteractableElement for ConsoleCard {
self.cursor_position = self.content.chars().count();
}
if let Some(command) = self.pending_confirmation.take() {
if matches!(key.code, KeyCode::Char('y') | KeyCode::Char('Y')) {
self.dispatch_command(command);
}
return InteractionResult::Handled;
}
match key.code {
KeyCode::Enter => {
if self.content.is_empty() {
@ -294,16 +320,13 @@ impl InteractableElement for ConsoleCard {
}
let command = self.content.clone();
let ipc = self.ipc.clone();
let restore = self.pending_restore.clone();
tokio::spawn(async move {
if ipc.send_command(0, command.clone()).await.is_err() {
*restore.lock().unwrap() = Some(command);
}
});
self.content.clear();
self.cursor_position = 0;
if Self::is_destructive(&command) {
self.pending_confirmation = Some(command);
} else {
self.dispatch_command(command);
}
InteractionResult::Handled
}
KeyCode::Backspace => {

View file

@ -3,14 +3,16 @@ use std::any::Any;
use crossterm::event::KeyEvent;
use ratatui::{Frame, layout::Rect, widgets::Borders};
use crate::{interaction_result::InteractionResult, screens::screens::Screen};
use crate::{
interaction_result::InteractionResult, render_context::RenderContext, screens::screens::Screen,
};
#[allow(unused)]
pub trait Element: Send + Sync + Any {
fn as_any(&self) -> &dyn Any;
fn as_any_mut(&mut self) -> &mut dyn Any;
fn render(&self, f: &mut Frame, r: Rect);
fn render(&self, f: &mut Frame, r: Rect, context: &RenderContext<'_>);
}
#[allow(unused)]

View file

@ -5,7 +5,6 @@ use iota_state::ClientState;
use ratatui::{
Frame,
layout::Rect,
style::{Color, Style},
widgets::{
Block, Borders,
canvas::{Canvas, Line},
@ -15,6 +14,7 @@ use ratatui::{
use crate::{
elements::elements::{Element, InteractableElement, JoinableElement},
interaction_result::InteractionResult,
render_context::RenderContext,
ui::UI,
util::borders::draw_block_joins,
};
@ -26,43 +26,30 @@ pub enum GRAPHS {
}
impl GRAPHS {
pub fn get_color(&self) -> Color {
pub fn get_color(&self, theme: &crate::theme::ResolvedTheme) -> ratatui::style::Color {
match self {
GRAPHS::Ram => Color::Blue,
GRAPHS::Cpu => Color::Red,
GRAPHS::Ping => Color::Green,
GRAPHS::Ram => theme.graphs.ram,
GRAPHS::Cpu => theme.graphs.cpu,
GRAPHS::Ping => theme.graphs.ping,
}
}
pub fn get_graph(&self, state: &ClientState) -> Vec<(f64, f64)> {
let state = match state.app.try_lock() {
Ok(state) => state,
Err(_) => return Vec::new(),
};
match self {
GRAPHS::Ram => state
.app
.lock()
.unwrap_or_else(|error| error.into_inner())
.with_width(28)
.ram
.clone(),
GRAPHS::Cpu => state
.app
.lock()
.unwrap_or_else(|error| error.into_inner())
.with_width(28)
.cpu
.clone(),
GRAPHS::Ping => state
.app
.lock()
.unwrap_or_else(|error| error.into_inner())
.with_width(28)
.ping
.clone(),
GRAPHS::Ram => state.with_width(28).ram.clone(),
GRAPHS::Cpu => state.with_width(28).cpu.clone(),
GRAPHS::Ping => state.with_width(28).ping.clone(),
}
}
pub fn get_unit(&self) -> String {
match self {
GRAPHS::Ram => "MB".to_string(),
// Memory is collected as a percentage of total RAM, not MiB.
GRAPHS::Ram => "%".to_string(),
GRAPHS::Cpu => "%".to_string(),
GRAPHS::Ping => "ms".to_string(),
}
@ -111,19 +98,24 @@ impl Element for GraphCard {
self
}
fn render(&self, f: &mut Frame, r: Rect) {
fn render(&self, f: &mut Frame, r: Rect, context: &RenderContext<'_>) {
if self.open {
let graph = self.graph_type.get_graph(&self.state);
let unit = self.graph_type.get_unit();
let min_x = graph.first().map(|(x, _)| *x).unwrap_or(0.0);
let max_x = graph.last().map(|(x, _)| *x).unwrap_or(100.0);
let max_x = if max_x <= min_x { min_x + 1.0 } else { max_x };
let min_y = graph
.iter()
.map(|(_, y)| *y)
.filter(|y| *y > 0.0)
.min_by(|a, b| a.total_cmp(b))
.unwrap_or(0.0);
let max_y = graph.iter().map(|(_, y)| *y).fold(-1.0, f64::max);
let max_y = graph.iter().map(|(_, y)| *y).fold(0.0, f64::max);
let y_upper = match self.graph_type {
GRAPHS::Cpu | GRAPHS::Ram => 100.0,
GRAPHS::Ping => (max_y * 1.2).max(10.0),
};
let block = Block::default()
.title(format!(
@ -136,15 +128,15 @@ impl Element for GraphCard {
))
.borders(self.borders)
.border_style(if self.focused {
Style::default().fg(Color::Yellow)
context.theme.graphs.focused_border
} else {
Style::default()
context.theme.graphs.border
});
let canvas = Canvas::default()
.block(block)
.x_bounds([min_x, max_x])
.y_bounds([0.0, 100.0])
.y_bounds([0.0, y_upper])
.paint(|ctx| {
for (x, y) in &graph {
ctx.draw(&Line {
@ -152,7 +144,7 @@ impl Element for GraphCard {
y1: 0.0,
x2: *x,
y2: *y,
color: self.graph_type.get_color(),
color: self.graph_type.get_color(context.theme),
});
}
});
@ -162,13 +154,23 @@ impl Element for GraphCard {
.title("")
.borders(self.borders)
.border_style(if self.focused {
Style::default().fg(Color::Yellow)
context.theme.graphs.focused_border
} else {
Style::default()
context.theme.graphs.border
});
f.render_widget(block, r);
}
draw_block_joins(f, r, self.borders, self.joins);
draw_block_joins(
f,
r,
self.borders,
self.joins,
if self.focused {
context.theme.borders.focused
} else {
context.theme.borders.normal
},
);
}
}

View file

@ -1,16 +1,54 @@
use crate::elements::elements::{Element, InteractableElement, JoinableElement};
use crate::interaction_result::InteractionResult;
use crate::util::borders::draw_block_joins;
use crate::{interaction_result::InteractionResult, render_context::RenderContext};
use crossterm::event::{KeyCode, KeyEvent};
use iota_state::{ClientState, UiLogEntry};
use ratatui::{
Frame,
layout::Rect,
style::{Color, Style},
style::Style,
text::{Line, Span},
widgets::{Block, Borders, Paragraph},
};
use std::any::Any;
use unicode_width::UnicodeWidthChar;
#[derive(Clone, Copy)]
enum LogSource {
Call,
Client,
Iota,
Omikron,
Omega,
Command,
Other,
}
impl LogSource {
fn from_sender(sender: &str) -> Self {
match sender {
"Call" => Self::Call,
"Client" => Self::Client,
"Iota" => Self::Iota,
"Omikron" => Self::Omikron,
"Omega" => Self::Omega,
"Command" => Self::Command,
_ => Self::Other,
}
}
fn style(self, theme: &crate::theme::ResolvedTheme) -> Style {
match self {
Self::Call => theme.logs.call,
Self::Client => theme.logs.client,
Self::Iota => theme.logs.iota,
Self::Omikron => theme.logs.omikron,
Self::Omega => theme.logs.omega,
Self::Command => theme.logs.command,
Self::Other => theme.logs.other,
}
}
}
pub struct LogCard {
state: ClientState,
@ -38,11 +76,10 @@ impl LogCard {
}
fn get_logs(&self) -> Vec<UiLogEntry> {
let state = self
.state
.app
.lock()
.unwrap_or_else(|error| error.into_inner());
let state = match self.state.app.try_lock() {
Ok(state) => state,
Err(_) => return Vec::new(),
};
state
.get_logs()
.iter()
@ -64,7 +101,7 @@ impl LogCard {
let mut last_boundary = 0usize;
for (idx, ch) in s.char_indices() {
let char_width = if ch.is_ascii() { 1 } else { 2 };
let char_width = UnicodeWidthChar::width(ch).unwrap_or(0);
if current_width + char_width > max_width {
if last_boundary == 0 {
return idx + ch.len_utf8();
@ -78,7 +115,7 @@ impl LogCard {
s.len()
}
fn wrap_entry(entry: &UiLogEntry, available_width: usize) -> Vec<(String, Color, bool)> {
fn wrap_entry(entry: &UiLogEntry, available_width: usize) -> Vec<(String, LogSource, bool)> {
let mut result = Vec::new();
let timestamp = entry.format_timestamp();
@ -141,29 +178,17 @@ impl LogCard {
line.push_str(&timestamp);
}
result.push((line, Self::sender_color(&entry.sender), entry.is_error));
result.push((line, LogSource::from_sender(&entry.sender), entry.is_error));
}
result
}
fn sender_color(sender: &str) -> Color {
match sender {
"Call" => Color::Magenta,
"Client" => Color::Green,
"Iota" => Color::Yellow,
"Omikron" => Color::Blue,
"Omega" => Color::Cyan,
"Command" => Color::LightGreen,
_ => Color::LightCyan,
}
}
fn build_all_lines(
&self,
entries: Vec<UiLogEntry>,
width: usize,
) -> Vec<(String, Color, bool)> {
) -> Vec<(String, LogSource, bool)> {
let mut lines = Vec::new();
for entry in entries {
@ -269,23 +294,33 @@ impl Element for LogCard {
self
}
fn render(&self, f: &mut Frame, area: Rect) {
fn render(&self, f: &mut Frame, area: Rect, context: &RenderContext<'_>) {
let entries = self.get_logs();
let block = Block::default()
.title(self.build_title())
.borders(self.borders)
.border_style(if self.focused {
Style::default().fg(Color::Yellow)
context.theme.logs.focused_border
} else {
Style::default()
context.theme.logs.border
});
let inner_area = block.inner(area);
f.render_widget(block, area);
if inner_area.width == 0 || inner_area.height == 0 {
draw_block_joins(f, area, self.borders, self.joins);
draw_block_joins(
f,
area,
self.borders,
self.joins,
if self.focused {
context.theme.borders.focused
} else {
context.theme.borders.normal
},
);
return;
}
@ -298,7 +333,7 @@ impl Element for LogCard {
let rendered_lines: Vec<Line> = visible_lines
.iter()
.map(|(line, prefix_color, is_error)| {
.map(|(line, source, is_error)| {
let mut spans = Vec::new();
let (prefix, rest) = Self::split_line_prefix(line);
@ -306,24 +341,25 @@ impl Element for LogCard {
if !prefix.is_empty() {
spans.push(Span::styled(
prefix.to_string(),
Style::default().fg(*prefix_color),
source.style(context.theme),
));
}
let (content, timestamp) = Self::split_timestamp_suffix(rest);
let text_color = if *is_error { Color::Red } else { Color::White };
let text_style = if *is_error {
context.theme.logs.error
} else {
context.theme.logs.text
};
if !content.is_empty() {
spans.push(Span::styled(
content.to_string(),
Style::default().fg(text_color),
));
spans.push(Span::styled(content.to_string(), text_style));
}
if !timestamp.is_empty() {
spans.push(Span::styled(
timestamp.to_string(),
Style::default().fg(Color::DarkGray),
context.theme.logs.timestamp,
));
}
@ -341,7 +377,17 @@ impl Element for LogCard {
f.render_widget(Paragraph::new(line.clone()), line_area);
}
draw_block_joins(f, area, self.borders, self.joins);
draw_block_joins(
f,
area,
self.borders,
self.joins,
if self.focused {
context.theme.borders.focused
} else {
context.theme.borders.normal
},
);
}
}