Skip to content

Commit

Permalink
chore: Remove all build warninings, update deprecated ratatui methods…
Browse files Browse the repository at this point in the history
… for UI components, cleanup and formatting
  • Loading branch information
hackinghieser committed Jan 6, 2025
1 parent 2916f57 commit b3ec6f9
Show file tree
Hide file tree
Showing 5 changed files with 74 additions and 66 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ crossterm = "0.28.0"
ratatui = "0.29.0"
unicode-width = "0.2.0"
chrono = "0.4.38"
cleverlib = "0.1.4"
cleverlib = { path = "../cleverlib/" }
18 changes: 14 additions & 4 deletions src/app.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::error::Error;

use crate::event_log_level::EventLogLevel;
use cleverlib::event_collection::EventCollection;
use cleverlib::{clever_parser_options::CleverParserOptions, event_collection::EventCollection};
use ratatui::widgets::{ListState, Row, TableState};

#[derive(Debug, Default)]
Expand Down Expand Up @@ -29,8 +31,16 @@ impl<'a> App<'a> {

pub fn tick(&self) {}

pub fn load_lines(&mut self, lines: &Vec<String>) {
self.event_collection = EventCollection::create(lines).unwrap();
pub fn load_lines(&mut self, lines: &Vec<String>) -> Result<(), Box<dyn Error>> {
let parsing_options = CleverParserOptions {
ignore_errors: Some(false),
debug: Some(false),
};
self.event_collection = match EventCollection::create(lines, Some(&parsing_options)) {
Ok(collection) => collection,
Err(e) => return Err(e.into()),
};
Ok(())
}

pub fn get_event_types(&mut self) {
Expand All @@ -51,7 +61,7 @@ impl<'a> App<'a> {

pub fn move_row_up(&mut self, range: usize) {
if let Some(selected) = self.event_table_state.selected() {
if selected >= range + 1 {
if selected > range {
self.event_table_state.select(Some(selected - range));
} else {
self.event_table_state
Expand Down
54 changes: 29 additions & 25 deletions src/event.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
use std::{sync::mpsc::{self, RecvError}, thread, time::{Duration, Instant}};
use std::{
sync::mpsc::{self, RecvError},
thread,
time::{Duration, Instant},
};

use crossterm::event::{self, KeyEvent, MouseEvent, Event as CrosstermEvent};
use crossterm::event::{self, Event as CrosstermEvent, KeyEvent, MouseEvent};

#[derive(Clone,Copy,Debug)]
#[derive(Clone, Copy, Debug)]
pub enum Event {
Tick,
Key(KeyEvent),
Mouse(MouseEvent),
Resize(u16,u16)
Resize(u16, u16),
}

#[derive(Debug)]
Expand All @@ -16,51 +20,51 @@ pub struct EventHandler {
sender: mpsc::Sender<Event>,
receiver: mpsc::Receiver<Event>,
#[allow(dead_code)]
handler: thread::JoinHandle<()>
handler: thread::JoinHandle<()>,
}

impl EventHandler {
impl EventHandler {
pub fn new(tick_rate: u64) -> Self {
let tick_rate = Duration::from_millis(tick_rate);
let (sender,receiver) = mpsc::channel();
let (sender, receiver) = mpsc::channel();
let handler = {
let sender = sender.clone();
thread::spawn(move || {
let mut last_tick = Instant::now();
let mut last_tick = Instant::now();
loop {
let timeout = tick_rate.checked_sub(last_tick.elapsed()).unwrap_or(tick_rate);
if event::poll(timeout).expect("Unable to poll for event") {
let timeout = tick_rate
.checked_sub(last_tick.elapsed())
.unwrap_or(tick_rate);
if event::poll(timeout).expect("Unable to poll for event") {
match event::read().expect("Unable to read event") {
CrosstermEvent::Key(e) => {
if e.kind == event::KeyEventKind::Press {
sender.send(Event::Key(e))
}else {
} else {
Ok(())
}
},
CrosstermEvent::Mouse(e) => {
sender.send(Event::Mouse(e))
},
CrosstermEvent::Resize(w,h ) => {
sender.send(Event::Resize(w, h))
},
_ => unimplemented!()
}
CrosstermEvent::Mouse(e) => sender.send(Event::Mouse(e)),
CrosstermEvent::Resize(w, h) => sender.send(Event::Resize(w, h)),
_ => unimplemented!(),
}
.expect("Failed to send terminal event")
}
if last_tick.elapsed() >= tick_rate {
}
if last_tick.elapsed() >= tick_rate {
sender.send(Event::Tick).expect("failed to send tick event");
last_tick = Instant::now();
}
}
}
})
};
Self {
sender, receiver, handler
sender,
receiver,
handler,
}
}

pub fn next(&self) -> Result<Event,RecvError> {
pub fn next(&self) -> Result<Event, RecvError> {
Ok(self.receiver.recv()?)
}
}
}
22 changes: 14 additions & 8 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ pub mod ui;
/// Terminal user interface.
pub mod tui;

pub mod event_log_level;
/// Application updater.
pub mod update;

pub mod event_log_level;

use std::{
error::Error,
fs,
io::{self},
};
Expand All @@ -23,6 +23,7 @@ use update::update;
#[command(author, version, about)]
struct Args {
file: Option<String>,
ignore_parsing_erros: Option<bool>,
}

use app::App;
Expand All @@ -37,16 +38,21 @@ use tui::Tui;

fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = Args::parse();
let path: String;
match args.file {
Some(p) => path = p,
let path = match args.file {
Some(p) => p,
None => {
println!("No file path provided");
return Ok(());
}
};
// Create an application.
let mut app = create_app(path)?;
let mut app = match create_app(path) {
Ok(app) => app,
Err(e) => {
println!("Could not create Application {}", e);
return Err(e);
}
};
// Initialize the terminal user interface.
let backend = CrosstermBackend::new(std::io::stderr());
let terminal = Terminal::new(backend)?;
Expand All @@ -71,15 +77,15 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}

fn create_app(path: String) -> Result<App<'static>, io::Error> {
fn create_app(path: String) -> Result<App<'static>, Box<dyn Error>> {
let lines = read_file(path.as_str())?;
let mut app = App::new();
app.file_path = path;
app.event_table_state = TableState::new();
app.filter_list_state = ListState::default();
app.filter_list_state.select(Some(0));
app.event_table_state.select(Some(0));
app.load_lines(&lines);
app.load_lines(&lines)?;
app.get_event_types();
Ok(app)
}
Expand Down
44 changes: 16 additions & 28 deletions src/ui.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
use std::{str::FromStr, vec};

use chrono::DateTime;
use cleverlib::event::Event;
use ratatui::{
layout::{Constraint, Direction, Layout, Rect},
style::{Color, Modifier, Style, Styled, Stylize},
style::{Color, Modifier, Style, Stylize},
text::Line,
widgets::{
block::{self, Title},
block::{self},
Block, Borders, Clear, List, ListDirection, Paragraph, Row, Table, Wrap,
},
Frame,
};
use std::vec;

struct Detail {
timestap: String,
Expand All @@ -30,7 +30,7 @@ pub fn render(app: &mut App, f: &mut Frame) {
let main = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Percentage(70), Constraint::Percentage(30)])
.split(f.size());
.split(f.area());

let detail_area = Layout::default()
.direction(Direction::Vertical)
Expand All @@ -47,7 +47,7 @@ pub fn render(app: &mut App, f: &mut Frame) {
.constraints([Constraint::Percentage(100)])
.split(detail_area[1]);
for line in app.event_collection.events.iter() {
if app.event_types.len() >= 1 {
if !app.event_types.is_empty() {
let event_level = line.level.clone().unwrap_or_default().to_string();
if app
.event_types
Expand All @@ -66,18 +66,18 @@ pub fn render(app: &mut App, f: &mut Frame) {
),
line.message.clone().unwrap_or_default().to_string(),
]);
clef_rows.push((&line, row));
clef_rows.push((line, row));
}
}
}

if clef_rows.len() >= 1 {
if !clef_rows.is_empty() {
let mut selected_row_index = app.event_table_state.selected().unwrap();
let selected_row: &Event = match clef_rows.get(selected_row_index) {
None => {
app.event_table_state.select(Some(0));
selected_row_index = 0;
clef_rows.get(0).unwrap().0
clef_rows.first().unwrap().0
}
Some(val) => val.0,
};
Expand All @@ -100,24 +100,16 @@ pub fn render(app: &mut App, f: &mut Frame) {
.block(
Block::default()
.title("Clever")
.title(
block::Title::from(app.file_path.as_str())
.position(block::Position::Top)
.alignment(ratatui::layout::Alignment::Left),
)
.title(
block::Title::from(selection_text)
.position(block::Position::Bottom)
.alignment(ratatui::layout::Alignment::Center),
)
.title_top(Line::from(app.file_path.as_str()).left_aligned())
.title_bottom(Line::from(selection_text.as_str()).centered())
.title_position(ratatui::widgets::block::Position::Top)
.title_alignment(ratatui::layout::Alignment::Center)
.borders(Borders::ALL)
.border_type(ratatui::widgets::BorderType::Rounded)
.title_style(Style::default().fg(ratatui::style::Color::White)),
)
.style(Style::default().fg(ratatui::style::Color::White))
.highlight_style(Style::default().reversed());
.row_highlight_style(Style::default().reversed());
f.render_stateful_widget(table, main[0], &mut app.event_table_state);

let log_level_detail = if detail.level.is_empty() {
Expand Down Expand Up @@ -159,7 +151,7 @@ pub fn render(app: &mut App, f: &mut Frame) {
}
let stats = Block::default()
.borders(Borders::ALL)
.title(block::Title::from("Detail").position(block::Position::Top))
.title_top(Line::from("Detail"))
.border_type(ratatui::widgets::BorderType::Rounded)
.title("Quit:'Q' Filter:'F")
.title_position(ratatui::widgets::block::Position::Bottom)
Expand All @@ -172,8 +164,8 @@ pub fn render(app: &mut App, f: &mut Frame) {
f.render_widget(stats, main[1]);
}
AppState::FILTERING => {
f.render_widget(Clear, f.size());
let area = centered_rect(40, 30, f.size());
f.render_widget(Clear, f.area());
let area = centered_rect(40, 30, f.area());
let type_list: Vec<String> = app
.event_types
.iter()
Expand All @@ -197,11 +189,7 @@ pub fn render(app: &mut App, f: &mut Frame) {
.borders(Borders::ALL)
.style(Style::default().fg(Color::White))
.border_type(block::BorderType::Rounded)
.title(
Title::from("Select: Spc | Close: F")
.alignment(ratatui::layout::Alignment::Center)
.position(block::Position::Bottom),
),
.title_bottom(Line::from("Select: Spc | Close: F").centered()),
)
.style(Style::default().fg(Color::White))
.highlight_style(Style::default().add_modifier(Modifier::BOLD))
Expand Down

0 comments on commit b3ec6f9

Please sign in to comment.