Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use ratatui instead of tui-rs for the terminal UI #505

Merged
merged 4 commits into from
Aug 25, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions metrics-observer/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name = "metrics-observer"
version = "0.4.0"
authors = ["Toby Lawrence <toby@nuclearfurnace.com>"]
edition = "2018"
rust-version = "1.70.0"
rust-version = "1.74.0"

license = "MIT"

Expand All @@ -23,8 +23,7 @@ bytes = { version = "1", default-features = false }
crossbeam-channel = { version = "0.5", default-features = false, features = ["std"] }
prost = { version = "0.12", default-features = false }
prost-types = { version = "0.12", default-features = false }
tui = { version = "0.19", default-features = false, features = ["termion"] }
termion = { version = "2", default-features = false }
ratatui = { version = "0.28.0", default-features = false, features = ["crossterm"] }
chrono = { version = "0.4", default-features = false, features = ["clock"] }

[build-dependencies]
Expand Down
35 changes: 8 additions & 27 deletions metrics-observer/src/input.rs
Original file line number Diff line number Diff line change
@@ -1,37 +1,18 @@
use std::io;
use std::thread;
use std::time::Duration;

use crossbeam_channel::{bounded, Receiver, RecvTimeoutError, TrySendError};
use termion::event::Key;
use termion::input::TermRead;
use ratatui::crossterm::event::{self, Event, KeyEvent, KeyEventKind};

pub struct InputEvents {
rx: Receiver<Key>,
}
pub struct InputEvents;

impl InputEvents {
pub fn new() -> InputEvents {
let (tx, rx) = bounded(1);
thread::spawn(move || {
let stdin = io::stdin();
for key in stdin.keys().flatten() {
// If our queue is full, we don't care. The user can just press the key again.
if let Err(TrySendError::Disconnected(_)) = tx.try_send(key) {
eprintln!("input event channel disconnected");
return;
}
pub fn next() -> io::Result<Option<KeyEvent>> {
if event::poll(Duration::from_secs(1))? {
match event::read()? {
Event::Key(key) if key.kind == KeyEventKind::Press => return Ok(Some(key)),
_ => {}
}
});

InputEvents { rx }
}

pub fn next(&mut self) -> Result<Option<Key>, RecvTimeoutError> {
match self.rx.recv_timeout(Duration::from_secs(1)) {
Ok(key) => Ok(Some(key)),
Err(RecvTimeoutError::Timeout) => Ok(None),
Err(e) => Err(e),
}
Ok(None)
}
}
60 changes: 37 additions & 23 deletions metrics-observer/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
use std::fmt;
use std::num::FpCategory;
use std::time::Duration;
use std::{error::Error, io};
use std::{fmt, io::Stdout};

use chrono::Local;
use metrics::Unit;
use termion::{event::Key, input::MouseTerminal, raw::IntoRawMode, screen::IntoAlternateScreen};
use tui::{
backend::TermionBackend,
use ratatui::{
backend::CrosstermBackend,
crossterm::{
event::KeyCode,
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
},
layout::{Constraint, Direction, Layout},
style::{Color, Modifier, Style},
text::{Span, Spans},
text::{Line, Span},
widgets::{Block, Borders, List, ListItem, Paragraph, Wrap},
Terminal,
};
Expand All @@ -27,23 +31,23 @@ mod selector;
use self::selector::Selector;

fn main() -> Result<(), Box<dyn Error>> {
let stdout = io::stdout().into_raw_mode()?;
let stdout = MouseTerminal::from(stdout).into_alternate_screen()?;
let backend = TermionBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
let terminal = init_terminal()?;
let result = run(terminal);
restore_terminal()?;
result
}

let mut events = InputEvents::new();
fn run(mut terminal: Terminal<CrosstermBackend<Stdout>>) -> Result<(), Box<dyn Error>> {
let address = std::env::args().nth(1).unwrap_or_else(|| "127.0.0.1:5000".to_owned());
let client = metrics_inner::Client::new(address);
let mut selector = Selector::new();

loop {
terminal.draw(|f| {
let chunks = Layout::default()
.direction(Direction::Vertical)
.margin(1)
.constraints([Constraint::Length(4), Constraint::Percentage(90)].as_ref())
.split(f.size());
.split(f.area());

let current_dt = Local::now().format(" (%Y/%m/%d %I:%M:%S %p)").to_string();
let client_state = match client.state() {
Expand All @@ -58,9 +62,9 @@ fn main() -> Result<(), Box<dyn Error>> {
spans.push(Span::raw(s));
}

Spans::from(spans)
Line::from(spans)
}
ClientState::Connected => Spans::from(vec![
ClientState::Connected => Line::from(vec![
Span::raw("state: "),
Span::styled("connected", Style::default().fg(Color::Green)),
]),
Expand All @@ -75,7 +79,7 @@ fn main() -> Result<(), Box<dyn Error>> {

let text = vec![
client_state,
Spans::from(vec![
Line::from(vec![
Span::styled("controls: ", Style::default().add_modifier(Modifier::BOLD)),
Span::raw("up/down = scroll, q = quit"),
]),
Expand Down Expand Up @@ -149,21 +153,31 @@ fn main() -> Result<(), Box<dyn Error>> {

// Poll the event queue for input events. `next` will only block for 1 second,
// so our screen is never stale by more than 1 second.
if let Some(input) = events.next()? {
match input {
Key::Char('q') => break,
Key::Up => selector.previous(),
Key::Down => selector.next(),
Key::PageUp => selector.top(),
Key::PageDown => selector.bottom(),
if let Some(input) = InputEvents::next()? {
match input.code {
KeyCode::Char('q') => break,
KeyCode::Up => selector.previous(),
KeyCode::Down => selector.next(),
KeyCode::PageUp => selector.top(),
KeyCode::PageDown => selector.bottom(),
_ => {}
}
}
}

Ok(())
}

fn init_terminal() -> io::Result<Terminal<CrosstermBackend<Stdout>>> {
enable_raw_mode()?;
execute!(io::stdout(), EnterAlternateScreen)?;
Terminal::new(CrosstermBackend::new(io::stdout()))
}

fn restore_terminal() -> io::Result<()> {
disable_raw_mode()?;
execute!(io::stdout(), LeaveAlternateScreen)
}

fn u64_to_displayable(value: u64, unit: Option<Unit>) -> String {
let unit = match unit {
None => return value.to_string(),
Expand Down
2 changes: 1 addition & 1 deletion metrics-observer/src/selector.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use tui::widgets::ListState;
use ratatui::widgets::ListState;

pub struct Selector(usize, ListState);

Expand Down
2 changes: 1 addition & 1 deletion rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
[toolchain]
channel = "1.70.0"
channel = "1.74.0"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nope, we're not bumping the project-wide MSRV just for a single binary crate.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The MSRV of the other crates in the workspace doesn't change here - they can still be built with 1.70.0, but the version of the rust toolchain used to build the entire workspace does unfortunately need to change, or somehow just this this crate needs to be built with a later version. Putting a rust-toolchain.toml config in the metrics-observer works when building at that folder level, but building the workspace still uses the root rust version.

This was introduced due to the following problem:

❯ cargo build            
error: package `metrics-observer v0.4.0 (/Users/joshka/local/metrics/metrics-observer)` cannot be built because it requires rustc 1.74.0 or newer, while the currently active rustc version is 1.70.0

The same error occurs when building the workspace with cargo build --workspace

We could remove the metrics-observer from the workspace if that would help, but I think that might be sub optimal. Is there another way to get around this?

We could also use Ratatui 0.25.0, the last version which supported Rust 1.70. The delta is about 400 commits - which 30% of the total commits of the entire repo.

Incidentally Rust 1.74 is in almost the same place as Rust 1.70 was metrics last did a MSRV bump for metrics. It will be 7 versions behind current when 1.81 is released in 2 weeks time. Do you have any downstream crates that are constrained this far back?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The MSRV of the other crates in the workspace doesn't change here - they can still be built with 1.70.0, but the version of the rust toolchain used to build the entire workspace does unfortunately need to change, or somehow just this this crate needs to be built with a later version.

Fair point, and my mistake.

We could remove the metrics-observer from the workspace if that would help, but I think that might be sub optimal.

I agree it would be suboptimal, although still a reasonable approach.

We could also use Ratatui 0.25.0, the last version which supported Rust 1.70. The delta is about 400 commits - which 30% of the total commits of the entire repo.

This seems more suboptimal: switching to another replacement crate and not even getting on the latest version.

Do you have any downstream crates that are constrained this far back?

No, but maintaining a lower MSRV is just good practice (IMO) for foundational crates.

After reading through and thinking about it as I was writing all of this, I think leaving this change in place is fine, but we should update the test-matrixed CI step (here) to add the MSRV to the matrix of versions to test against. This will provide a counterbalance to rust-toolchain.toml no longer being pinned to the MSRV.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense. I added a test using rust 1.70, with a parameter to exclude testing the metrics-observer package.
I also added some docs showing why this is there (linking back to your comment here).