From d0fc5e2edc2e75c3fbba29cca54a3a5b1a6c57c8 Mon Sep 17 00:00:00 2001 From: hatoo Date: Sat, 22 Feb 2025 16:33:31 +0900 Subject: [PATCH] use raratui::{init, restore} --- src/lib.rs | 12 ------------ src/monitor.rs | 31 +++++++++---------------------- 2 files changed, 9 insertions(+), 34 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 2504c7f0..604d00cf 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -621,18 +621,6 @@ pub async fn run(mut opts: Opts) -> anyhow::Result<()> { } }; - // When panics, reset terminal mode and exit immediately. - std::panic::set_hook(Box::new(move |info| { - if !no_tui { - use crossterm::ExecutableCommand; - let _ = std::io::stdout().execute(crossterm::terminal::LeaveAlternateScreen); - let _ = crossterm::terminal::disable_raw_mode(); - let _ = std::io::stdout().execute(crossterm::cursor::Show); - } - eprintln!("{info}"); - std::process::exit(libc::EXIT_FAILURE); - })); - let start = std::time::Instant::now(); let data_collect_future: Pin>> = diff --git a/src/monitor.rs b/src/monitor.rs index cb268d0d..17a8b4e0 100644 --- a/src/monitor.rs +++ b/src/monitor.rs @@ -1,19 +1,14 @@ use byte_unit::Byte; -use crossterm::{ - ExecutableCommand, - event::{Event, KeyCode, KeyEvent, KeyModifiers}, -}; +use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers}; use hyper::http; -use ratatui::crossterm; +use ratatui::{DefaultTerminal, crossterm}; use ratatui::{ - Terminal, - backend::CrosstermBackend, layout::{Constraint, Direction, Layout}, style::{Color, Style}, text::{Line, Span}, widgets::{BarChart, Block, Borders, Gauge, Paragraph}, }; -use std::{collections::BTreeMap, io}; +use std::collections::BTreeMap; use crate::{ client::{ClientError, RequestResult}, @@ -67,30 +62,21 @@ pub struct Monitor { struct IntoRawMode; impl IntoRawMode { - pub fn new() -> Result { - crossterm::terminal::enable_raw_mode()?; - io::stdout().execute(crossterm::terminal::EnterAlternateScreen)?; - io::stdout().execute(crossterm::cursor::Hide)?; - Ok(IntoRawMode) + pub fn new() -> Result<(Self, DefaultTerminal), std::io::Error> { + let terminal = ratatui::try_init()?; + Ok((Self, terminal)) } } impl Drop for IntoRawMode { fn drop(&mut self) { - let _ = crossterm::terminal::disable_raw_mode(); - let _ = io::stdout().execute(crossterm::terminal::LeaveAlternateScreen); - let _ = io::stdout().execute(crossterm::cursor::Show); + ratatui::restore(); } } impl Monitor { pub async fn monitor(self) -> Result<(ResultData, PrintConfig), std::io::Error> { - let raw_mode = IntoRawMode::new()?; - - let mut terminal = { - let backend = CrosstermBackend::new(io::stdout()); - Terminal::new(backend)? - }; + let (raw_mode, mut terminal) = IntoRawMode::new()?; // Return this when ends to application print summary // We must not read all data from this due to computational cost. @@ -431,6 +417,7 @@ impl Monitor { modifiers: KeyModifiers::CONTROL, .. }) => { + drop(terminal); drop(raw_mode); let _ = crate::printer::print_result( self.print_config,