chore: Reorganize file tree for easier onboarding. Rust project now at the root for simple git clone && cargo run
This commit is contained in:
18
harmony_tui/Cargo.toml
Normal file
18
harmony_tui/Cargo.toml
Normal file
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "harmony_tui"
|
||||
edition = "2024"
|
||||
version.workspace = true
|
||||
readme.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
harmony = { path = "../harmony" }
|
||||
log = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
ratatui = "0.29.0"
|
||||
crossterm = { version = "0.28.1", features = [ "event-stream" ] }
|
||||
color-eyre = "0.6.3"
|
||||
tokio-stream = "0.1.17"
|
||||
tui-logger = "0.14.1"
|
||||
log-panics = "2.1.0"
|
||||
205
harmony_tui/src/lib.rs
Normal file
205
harmony_tui/src/lib.rs
Normal file
@@ -0,0 +1,205 @@
|
||||
mod ratatui_utils;
|
||||
mod widget;
|
||||
|
||||
use log::{debug, error, info};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_stream::StreamExt;
|
||||
use tui_logger::{TuiWidgetEvent, TuiWidgetState};
|
||||
use widget::{help::HelpWidget, score::ScoreListWidget};
|
||||
|
||||
use std::{panic, sync::Arc, time::Duration};
|
||||
|
||||
use crossterm::event::{Event, EventStream, KeyCode, KeyEventKind};
|
||||
use harmony::{maestro::Maestro, score::Score};
|
||||
use ratatui::{
|
||||
self, Frame,
|
||||
layout::{Constraint, Layout, Position},
|
||||
style::{Color, Style},
|
||||
widgets::{Block, Borders, ListItem},
|
||||
};
|
||||
|
||||
pub mod tui {
|
||||
// Export any necessary modules or types from the internal tui module
|
||||
}
|
||||
|
||||
/// Initializes the terminal UI with the provided Maestro instance.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `maestro` - A reference to the Maestro instance containing registered scores.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use harmony;
|
||||
/// use harmony_tui::init;
|
||||
///
|
||||
/// #[harmony::main]
|
||||
/// pub async fn main(maestro: harmony::Maestro) {
|
||||
/// maestro.register(DeploymentScore::new("nginx-test", "nginx"));
|
||||
/// maestro.register(OKDLoadBalancerScore::new(&maestro.inventory, &maestro.topology));
|
||||
/// // Register other scores as needed
|
||||
///
|
||||
/// init(maestro).await.unwrap();
|
||||
/// }
|
||||
/// ```
|
||||
pub async fn init(maestro: Maestro) -> Result<(), Box<dyn std::error::Error>> {
|
||||
HarmonyTUI::new(maestro).init().await
|
||||
}
|
||||
|
||||
pub struct HarmonyTUI {
|
||||
score: ScoreListWidget,
|
||||
should_quit: bool,
|
||||
tui_state: TuiWidgetState,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum HarmonyTuiEvent {
|
||||
LaunchScore(ScoreItem),
|
||||
}
|
||||
|
||||
impl HarmonyTUI {
|
||||
pub fn new(maestro: Maestro) -> Self {
|
||||
let maestro = Arc::new(maestro);
|
||||
let (_handle, sender) = Self::start_channel(maestro.clone());
|
||||
let score = ScoreListWidget::new(Self::scores_list(&maestro), sender);
|
||||
|
||||
HarmonyTUI {
|
||||
should_quit: false,
|
||||
score,
|
||||
tui_state: TuiWidgetState::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn start_channel(
|
||||
maestro: Arc<Maestro>,
|
||||
) -> (tokio::task::JoinHandle<()>, mpsc::Sender<HarmonyTuiEvent>) {
|
||||
let (sender, mut receiver) = mpsc::channel::<HarmonyTuiEvent>(32);
|
||||
let handle = tokio::spawn(async move {
|
||||
info!("Starting message channel receiver loop");
|
||||
while let Some(event) = receiver.recv().await {
|
||||
info!("Received event {event:#?}");
|
||||
match event {
|
||||
HarmonyTuiEvent::LaunchScore(score_item) => {
|
||||
let maestro = maestro.clone();
|
||||
|
||||
let joinhandle_result =
|
||||
tokio::spawn(async move { maestro.interpret(score_item.0).await })
|
||||
.await;
|
||||
|
||||
match joinhandle_result {
|
||||
Ok(interpretation_result) => match interpretation_result {
|
||||
Ok(success) => info!("Score execution successful {success:?}"),
|
||||
Err(error) => error!("Score failed {error:?}"),
|
||||
},
|
||||
Err(joinhandle_failure) => {
|
||||
error!("Score execution TASK FAILED! {:#?}", joinhandle_failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
info!("STOPPING message channel receiver loop");
|
||||
});
|
||||
|
||||
(handle, sender)
|
||||
}
|
||||
|
||||
pub async fn init(mut self) -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Set max_log_level to Trace
|
||||
tui_logger::init_logger(log::LevelFilter::Info).unwrap();
|
||||
// Set default level for unknown targets to Trace
|
||||
tui_logger::set_default_level(log::LevelFilter::Info);
|
||||
tui_logger::set_log_file("harmony.log").unwrap();
|
||||
|
||||
color_eyre::install()?;
|
||||
let mut terminal = ratatui::init();
|
||||
log_panics::init();
|
||||
terminal.hide_cursor()?;
|
||||
|
||||
// TODO improve performance here
|
||||
// Refreshing the entire terminal 10 times a second does not seem very smart
|
||||
let period = Duration::from_secs_f32(1.0 / 10.0);
|
||||
let mut interval = tokio::time::interval(period);
|
||||
let mut events = EventStream::new();
|
||||
|
||||
while !self.should_quit {
|
||||
tokio::select! {
|
||||
_ = interval.tick() => { terminal.draw(|frame| self.render(frame))?; },
|
||||
Some(Ok(event)) = events.next() => self.handle_event(&event).await,
|
||||
}
|
||||
}
|
||||
|
||||
ratatui::restore();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn render(&self, frame: &mut Frame) {
|
||||
let size = frame.area();
|
||||
frame.set_cursor_position(Position::new(size.x / 2, size.y / 2));
|
||||
|
||||
let [app_area, help_area] =
|
||||
Layout::vertical([Constraint::Percentage(100), Constraint::Min(4)]).areas(frame.area());
|
||||
|
||||
let help_block = Block::default().borders(Borders::TOP);
|
||||
frame.render_widget(&help_block, help_area);
|
||||
frame.render_widget(HelpWidget::new(), help_block.inner(help_area));
|
||||
|
||||
let [list_area, output_area] =
|
||||
Layout::horizontal([Constraint::Min(30), Constraint::Percentage(100)]).areas(app_area);
|
||||
|
||||
let block = Block::default().borders(Borders::RIGHT);
|
||||
frame.render_widget(&block, list_area);
|
||||
self.score.render(list_area, frame);
|
||||
let tui_logger = tui_logger::TuiLoggerWidget::default()
|
||||
.style_error(Style::default().fg(Color::Red))
|
||||
.style_warn(Style::default().fg(Color::LightRed))
|
||||
.style_info(Style::default().fg(Color::LightGreen))
|
||||
.style_debug(Style::default().fg(Color::Gray))
|
||||
.style_trace(Style::default().fg(Color::Gray))
|
||||
.state(&self.tui_state);
|
||||
frame.render_widget(tui_logger, output_area)
|
||||
}
|
||||
|
||||
fn scores_list(maestro: &Maestro) -> Vec<ScoreItem> {
|
||||
let scores = maestro.scores();
|
||||
let scores_read = scores.read().expect("Should be able to read scores");
|
||||
scores_read
|
||||
.iter()
|
||||
.map(|s| ScoreItem(s.clone_box()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn handle_event(&mut self, event: &Event) {
|
||||
debug!("Got event {event:?}");
|
||||
if let Event::Key(key) = event {
|
||||
if key.kind == KeyEventKind::Press {
|
||||
match key.code {
|
||||
KeyCode::Char('q') | KeyCode::Esc => self.should_quit = true,
|
||||
KeyCode::PageUp => self.tui_state.transition(TuiWidgetEvent::PrevPageKey),
|
||||
KeyCode::PageDown => self.tui_state.transition(TuiWidgetEvent::NextPageKey),
|
||||
KeyCode::Char('G') | KeyCode::End => {
|
||||
self.tui_state.transition(TuiWidgetEvent::EscapeKey)
|
||||
}
|
||||
_ => self.score.handle_event(event).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ScoreItem(Box<dyn Score>);
|
||||
|
||||
impl ScoreItem {
|
||||
pub fn clone(&self) -> Self {
|
||||
Self(self.0.clone_box())
|
||||
}
|
||||
}
|
||||
|
||||
impl Into<ListItem<'_>> for &ScoreItem {
|
||||
fn into(self) -> ListItem<'static> {
|
||||
ListItem::new(self.0.name())
|
||||
}
|
||||
}
|
||||
22
harmony_tui/src/ratatui_utils.rs
Normal file
22
harmony_tui/src/ratatui_utils.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
use ratatui::layout::{Constraint, Flex, Layout, Rect};
|
||||
|
||||
/// Centers a [`Rect`] within another [`Rect`] using the provided [`Constraint`]s.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// use ratatui::layout::{Constraint, Rect};
|
||||
///
|
||||
/// let area = Rect::new(0, 0, 100, 100);
|
||||
/// let horizontal = Constraint::Percentage(20);
|
||||
/// let vertical = Constraint::Percentage(30);
|
||||
///
|
||||
/// let centered = center(area, horizontal, vertical);
|
||||
/// ```
|
||||
pub(crate) fn center(area: Rect, horizontal: Constraint, vertical: Constraint) -> Rect {
|
||||
let [area] = Layout::horizontal([horizontal])
|
||||
.flex(Flex::Center)
|
||||
.areas(area);
|
||||
let [area] = Layout::vertical([vertical]).flex(Flex::Center).areas(area);
|
||||
area
|
||||
}
|
||||
21
harmony_tui/src/widget/help.rs
Normal file
21
harmony_tui/src/widget/help.rs
Normal file
@@ -0,0 +1,21 @@
|
||||
use ratatui::widgets::{Paragraph, Widget, Wrap};
|
||||
|
||||
pub(crate) struct HelpWidget;
|
||||
impl HelpWidget {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
impl Widget for HelpWidget {
|
||||
fn render(self, area: ratatui::prelude::Rect, buf: &mut ratatui::prelude::Buffer)
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
let text = Paragraph::new("Usage => q/Esc: Quit | j/↑ :Select UP | k/↓: Select Down | Enter: Launch Score\nPageUp/PageDown: Scroll Logs | Shift+G/End: Logs bottom")
|
||||
.centered()
|
||||
.wrap(Wrap { trim: false });
|
||||
|
||||
Widget::render(text, area, buf)
|
||||
}
|
||||
}
|
||||
2
harmony_tui/src/widget/mod.rs
Normal file
2
harmony_tui/src/widget/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub mod help;
|
||||
pub mod score;
|
||||
138
harmony_tui/src/widget/score.rs
Normal file
138
harmony_tui/src/widget/score.rs
Normal file
@@ -0,0 +1,138 @@
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
use crossterm::event::{Event, KeyCode, KeyEventKind};
|
||||
use log::{info, warn};
|
||||
use ratatui::{
|
||||
Frame,
|
||||
layout::Rect,
|
||||
style::{Style, Stylize},
|
||||
widgets::{List, ListState, StatefulWidget, Widget},
|
||||
};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::{HarmonyTuiEvent, ScoreItem};
|
||||
|
||||
#[derive(Debug)]
|
||||
enum ExecutionState {
|
||||
INITIATED,
|
||||
RUNNING,
|
||||
CANCELED,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Execution {
|
||||
state: ExecutionState,
|
||||
score: ScoreItem,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ScoreListWidget {
|
||||
list_state: Arc<RwLock<ListState>>,
|
||||
scores: Vec<ScoreItem>,
|
||||
execution: Option<Execution>,
|
||||
execution_history: Vec<Execution>,
|
||||
sender: mpsc::Sender<HarmonyTuiEvent>,
|
||||
}
|
||||
|
||||
impl ScoreListWidget {
|
||||
pub(crate) fn new(scores: Vec<ScoreItem>, sender: mpsc::Sender<HarmonyTuiEvent>) -> Self {
|
||||
let mut list_state = ListState::default();
|
||||
list_state.select_first();
|
||||
let list_state = Arc::new(RwLock::new(list_state));
|
||||
Self {
|
||||
scores,
|
||||
list_state,
|
||||
execution: None,
|
||||
execution_history: vec![],
|
||||
sender,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn launch_execution(&mut self) {
|
||||
let list_read = self.list_state.read().unwrap();
|
||||
if let Some(index) = list_read.selected() {
|
||||
let score = self
|
||||
.scores
|
||||
.get(index)
|
||||
.expect("List state should always match with internal Vec");
|
||||
|
||||
self.execution = Some(Execution {
|
||||
state: ExecutionState::INITIATED,
|
||||
score: score.clone(),
|
||||
});
|
||||
info!("{:#?}\n\nConfirm Execution (Press y/n)", score.0);
|
||||
} else {
|
||||
warn!("No Score selected, nothing to launch");
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn scroll_down(&self) {
|
||||
self.list_state.write().unwrap().scroll_down_by(1);
|
||||
}
|
||||
|
||||
pub(crate) fn scroll_up(&self) {
|
||||
self.list_state.write().unwrap().scroll_up_by(1);
|
||||
}
|
||||
|
||||
pub(crate) fn render(&self, area: Rect, frame: &mut Frame) {
|
||||
frame.render_widget(self, area);
|
||||
}
|
||||
|
||||
fn clear_execution(&mut self) {
|
||||
match self.execution.take() {
|
||||
Some(execution) => {
|
||||
self.execution_history.push(execution);
|
||||
}
|
||||
None => warn!("Should never clear execution when no execution exists"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn confirm(&mut self, confirm: bool) {
|
||||
if let Some(execution) = &mut self.execution {
|
||||
match confirm {
|
||||
true => {
|
||||
execution.state = ExecutionState::RUNNING;
|
||||
info!("Launch execution {:?}", execution);
|
||||
self.sender
|
||||
.send(HarmonyTuiEvent::LaunchScore(execution.score.clone()))
|
||||
.await
|
||||
.expect("Should be able to send message");
|
||||
}
|
||||
false => {
|
||||
execution.state = ExecutionState::CANCELED;
|
||||
info!("Execution cancelled");
|
||||
self.clear_execution();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn handle_event(&mut self, event: &Event) {
|
||||
if let Event::Key(key) = event {
|
||||
if key.kind == KeyEventKind::Press {
|
||||
match key.code {
|
||||
KeyCode::Char('j') | KeyCode::Down => self.scroll_down(),
|
||||
KeyCode::Char('k') | KeyCode::Up => self.scroll_up(),
|
||||
KeyCode::Enter => self.launch_execution(),
|
||||
KeyCode::Char('y') => self.confirm(true).await,
|
||||
KeyCode::Char('n') => self.confirm(false).await,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Widget for &ScoreListWidget {
|
||||
fn render(self, area: ratatui::prelude::Rect, buf: &mut ratatui::prelude::Buffer)
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
let mut list_state = self.list_state.write().unwrap();
|
||||
let list = List::new(&self.scores)
|
||||
.highlight_style(Style::new().bold().italic())
|
||||
.highlight_symbol("🠊 ");
|
||||
|
||||
StatefulWidget::render(list, area, buf, &mut list_state)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user