Skip to content

Commit

Permalink
refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
alexpasmantier committed Oct 11, 2024
1 parent 2e54917 commit c7bc99a
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 39 deletions.
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::io::{stdout, Write};
use std::io::{stdout, IsTerminal, Write};

use clap::Parser;
use cli::Cli;
Expand Down
48 changes: 10 additions & 38 deletions src/tui.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::{
io::{stderr, stdout, IsTerminal, Stderr, Stdout, Write},
io::{stderr, BufWriter, Stderr},
ops::{Deref, DerefMut},
};

Expand All @@ -10,48 +10,20 @@ use crossterm::{
};
use ratatui::backend::CrosstermBackend as Backend;
use tokio::task::JoinHandle;
use tracing::debug;

pub enum OutputHandle {
Stdout(Stdout),
Stderr(std::io::BufWriter<Stderr>),
}

impl<W: Write> Write for Tui<W> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.terminal.backend_mut().write(buf)
}

fn flush(&mut self) -> std::io::Result<()> {
self.terminal.backend_mut().flush()
}
}

// FIXME: fix this (see https://blog.orhun.dev/stdout-vs-stderr/)
pub struct Tui<W: Write> {
pub terminal: ratatui::Terminal<Backend<W>>,
pub struct Tui {
pub terminal: ratatui::Terminal<Backend<BufWriter<Stderr>>>,
pub task: JoinHandle<()>,
pub frame_rate: f64,
}

impl<W: Write> Tui<W> {
impl Tui {
pub fn new() -> Result<Self> {
if stdout().is_terminal() {
debug!("stdout is a terminal, using stdout for TUI");
Ok(Self {
terminal: ratatui::Terminal::new(Backend::new(stdout()))?,
task: tokio::spawn(async {}),
frame_rate: 60.0,
})
} else {
debug!("stdout is not a terminal, using stderr for TUI");
let buffered_stderr = std::io::BufWriter::new(stderr());
Ok(Self {
terminal: ratatui::Terminal::new(Backend::new(buffered_stderr))?,
task: tokio::spawn(async {}),
frame_rate: 60.0,
})
}
Ok(Self {
terminal: ratatui::Terminal::new(Backend::new(BufWriter::new(stderr())))?,
task: tokio::spawn(async {}),
frame_rate: 60.0,
})
}

pub fn frame_rate(mut self, frame_rate: f64) -> Self {
Expand Down Expand Up @@ -96,7 +68,7 @@ impl<W: Write> Tui<W> {
}

impl Deref for Tui {
type Target = ratatui::Terminal<Backend<OutputHandle>>;
type Target = ratatui::Terminal<Backend<BufWriter<Stderr>>>;

fn deref(&self) -> &Self::Target {
&self.terminal
Expand Down

0 comments on commit c7bc99a

Please sign in to comment.