joecalsend/src/main.rs
2025-07-06 16:02:11 -07:00

142 lines
4 KiB
Rust

use std::io;
use joecalsend::{Config, JoecalState, RunningState, error, models::Device};
use local_ip_address::local_ip;
use network_interface::{Addr, NetworkInterface, NetworkInterfaceConfig, V4IfAddr};
use ratatui::{
DefaultTerminal, Frame,
buffer::Buffer,
crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind},
layout::Rect,
style::Stylize,
symbols::border,
text::{Line, Text},
widgets::{Block, Paragraph, Widget},
};
#[tokio::main]
async fn main() -> error::Result<()> {
let device = Device::default();
dbg!(&device);
let std::net::IpAddr::V4(ip) = local_ip()? else {
unreachable!()
};
// for enumerating subnet peers when multicast fails (https://github.com/localsend/protocol?tab=readme-ov-file#32-http-legacy-mode)
let mut network_ip = ip;
let nifs = NetworkInterface::show().unwrap();
for addr in nifs.into_iter().flat_map(|i| i.addr) {
if let Addr::V4(V4IfAddr {
ip: ifip,
netmask: Some(netmask),
..
}) = addr
&& ip == ifip
{
network_ip = ip & netmask;
break;
}
}
dbg!(network_ip);
let state = JoecalState::new(device)
.await
.expect("Could not create application session");
let config = Config::default();
let (h1, h2, h3) = state.start(&config).await.unwrap();
let mut app = App::new(state.clone());
let mut terminal = ratatui::init();
let result = app.run(&mut terminal).await;
ratatui::restore();
let _ = tokio::join!(h1, h2, h3);
Ok(result?)
}
struct App {
state: JoecalState,
}
impl App {
pub fn new(state: JoecalState) -> Self {
App { state }
}
pub async fn run(&mut self, terminal: &mut DefaultTerminal) -> io::Result<()> {
loop {
terminal.draw(|frame| self.draw(frame))?;
self.handle_events().await?;
if let Ok(lock) = self.state.running_state.try_lock()
&& *lock == RunningState::Stopping
{
break;
}
}
Ok(())
}
fn draw(&self, frame: &mut Frame) {
frame.render_widget(self, frame.area());
}
async fn handle_events(&mut self) -> io::Result<()> {
match event::read()? {
// it's important to check that the event is a key press event as
// crossterm also emits key release and repeat events on Windows.
Event::Key(key_event) if key_event.kind == KeyEventKind::Press => {
self.handle_key_event(key_event).await
}
_ => {}
};
Ok(())
}
async fn handle_key_event(&mut self, key_event: KeyEvent) {
match key_event.code {
KeyCode::Char('q') => self.exit().await,
KeyCode::Char('s') => {}
KeyCode::Char('r') => {}
KeyCode::Char('d') => {}
_ => {}
}
}
async fn exit(&self) {
self.state.stop().await;
}
}
impl Widget for &App {
fn render(self, area: Rect, buf: &mut Buffer) {
let title = Line::from(" Counter App Tutorial ".bold());
let instructions = Line::from(vec![
" Send ".into(),
"<S>".blue().bold(),
" Receive ".into(),
"<R>".blue().bold(),
" Discover ".into(),
"<D>".blue().bold(),
" Quit ".into(),
"<Q> ".blue().bold(),
]);
let block = Block::bordered()
.title(title.centered())
.title_bottom(instructions.centered())
.border_set(border::THICK);
let rs = self
.state
.running_state
.try_lock()
.map(|s| format!("{s:?}"))
.unwrap_or("Just a moment...".into());
let state_text = Text::from(vec![Line::from(vec!["runstate: ".into(), rs.yellow()])]);
Paragraph::new(state_text)
.centered()
.block(block)
.render(area, buf);
}
}