Skip to content

Commit

Permalink
style: make component formatting more standard
Browse files Browse the repository at this point in the history
- Reformat everything to 4 spaces and 100 characters per line
- Remove the rust-toolchain.toml file
- Remove the .rustfmt.toml file which had many unstable options
- hard code the crossterm_io to use stdout instead of making this an
  option. Users can change this easily if they want to use stderr, and
  not prompting for it simplifies the template
  • Loading branch information
joshka committed Jul 14, 2024
1 parent dbb8e5c commit 99f7d5c
Show file tree
Hide file tree
Showing 17 changed files with 1,193 additions and 1,159 deletions.
3 changes: 0 additions & 3 deletions .github/workflows/template.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
[values]
gh-username = "ratatui"
project-description = "Example of ratatui template"
msrv = "nightly"
use_gitserver = false
crossterm_io = "stderr"
use_rustfmt = false
3 changes: 0 additions & 3 deletions component/.github/workflows/template.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
[values]
gh-username = "kdheepak"
project-description = "Example of ratatui template"
msrv = "stable"
use_gitserver = false
crossterm_io = "stderr"
use_rustfmt = false
16 changes: 0 additions & 16 deletions component/template/.rustfmt.toml

This file was deleted.

7 changes: 5 additions & 2 deletions component/template/build.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
fn main() -> Result<(), Box<dyn std::error::Error>> {
vergen::EmitBuilder::builder().all_build().all_git().emit()?;
Ok(())
vergen::EmitBuilder::builder()
.all_build()
.all_git()
.emit()?;
Ok(())
}
34 changes: 0 additions & 34 deletions component/template/hooks/pre-get-repository.rhai
Original file line number Diff line number Diff line change
Expand Up @@ -55,40 +55,6 @@ if use_gitserver == "true" || use_gitserver == true {
variable::set("repository", "");
}

if !variable::is_set("crossterm_io") {
let crossterm_io = variable::prompt("Use stdout or stderr for Crossterm IO?", "stdout", ["stdout", "stderr"]);
variable::set("crossterm_io", crossterm_io);
} else {
if variable::get("crossterm_io").to_lower() == "stdout" {
variable::set("crossterm_io", "stdout");
} else if variable::get("crossterm_io").to_lower() == "stderr" {
variable::set("crossterm_io", "stderr");
} else {
print("!!! Unknown value for `crossterm_io`: " + variable::get("crossterm_io") + ". Using `stdout`.");
variable::set("crossterm_io", "stdout");
}
};

let use_rustfmt = if variable::is_set("use_rustfmt") {
variable::get("use_rustfmt")
} else {
variable::prompt("Use an opinionated rustfmt.toml file?", "false", ["true", "false"])
};

if use_rustfmt == "false" || use_rustfmt == false {
file::delete("./.rustfmt.toml");
} else {
print("!!! opinionated rustfmt.toml requires nightly.");
variable::set("msrv", "nightly");
}

let msrv = if variable::is_set("msrv") {
variable::get("msrv")
} else {
variable::prompt("What is your Minimum Supported Rust Version", "stable")
};
variable::set("msrv", msrv);

let project_name = variable::get("project-name");
let crate_name = project_name;
crate_name.replace("-", "_");
Expand Down
2 changes: 0 additions & 2 deletions component/template/rust-toolchain.toml

This file was deleted.

22 changes: 11 additions & 11 deletions component/template/src/action.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
use std::{fmt, string::ToString};

use serde::{
de::{self, Deserializer, Visitor},
Deserialize, Serialize,
de::{self, Deserializer, Visitor},
Deserialize, Serialize,
};
use strum::Display;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Display, Deserialize)]
pub enum Action {
Tick,
Render,
Resize(u16, u16),
Suspend,
Resume,
Quit,
ClearScreen,
Error(String),
Help,
Tick,
Render,
Resize(u16, u16),
Suspend,
Resume,
Quit,
ClearScreen,
Error(String),
Help,
}
256 changes: 131 additions & 125 deletions component/template/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,148 +5,154 @@ use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;

use crate::{
action::Action,
components::{home::Home, fps::FpsCounter, Component},
config::Config,
mode::Mode,
tui,
action::Action,
components::{fps::FpsCounter, home::Home, Component},
config::Config,
mode::Mode,
tui,
};

pub struct App {
pub config: Config,
pub tick_rate: f64,
pub frame_rate: f64,
pub components: Vec<Box<dyn Component>>,
pub should_quit: bool,
pub should_suspend: bool,
pub mode: Mode,
pub last_tick_key_events: Vec<KeyEvent>,
pub config: Config,
pub tick_rate: f64,
pub frame_rate: f64,
pub components: Vec<Box<dyn Component>>,
pub should_quit: bool,
pub should_suspend: bool,
pub mode: Mode,
pub last_tick_key_events: Vec<KeyEvent>,
}

impl App {
pub fn new(tick_rate: f64, frame_rate: f64) -> Result<Self> {
let home = Home::new();
let fps = FpsCounter::default();
let config = Config::new()?;
let mode = Mode::Home;
Ok(Self {
tick_rate,
frame_rate,
components: vec![Box::new(home), Box::new(fps)],
should_quit: false,
should_suspend: false,
config,
mode,
last_tick_key_events: Vec::new(),
})
}

pub async fn run(&mut self) -> Result<()> {
let (action_tx, mut action_rx) = mpsc::unbounded_channel();

let mut tui = tui::Tui::new()?.tick_rate(self.tick_rate).frame_rate(self.frame_rate);
// tui.mouse(true);
tui.enter()?;

for component in self.components.iter_mut() {
component.register_action_handler(action_tx.clone())?;
pub fn new(tick_rate: f64, frame_rate: f64) -> Result<Self> {
let home = Home::new();
let fps = FpsCounter::default();
let config = Config::new()?;
let mode = Mode::Home;
Ok(Self {
tick_rate,
frame_rate,
components: vec![Box::new(home), Box::new(fps)],
should_quit: false,
should_suspend: false,
config,
mode,
last_tick_key_events: Vec::new(),
})
}

for component in self.components.iter_mut() {
component.register_config_handler(self.config.clone())?;
}

for component in self.components.iter_mut() {
component.init(tui.size()?)?;
}
pub async fn run(&mut self) -> Result<()> {
let (action_tx, mut action_rx) = mpsc::unbounded_channel();

loop {
if let Some(e) = tui.next().await {
match e {
tui::Event::Quit => action_tx.send(Action::Quit)?,
tui::Event::Tick => action_tx.send(Action::Tick)?,
tui::Event::Render => action_tx.send(Action::Render)?,
tui::Event::Resize(x, y) => action_tx.send(Action::Resize(x, y))?,
tui::Event::Key(key) => {
if let Some(keymap) = self.config.keybindings.get(&self.mode) {
if let Some(action) = keymap.get(&vec![key]) {
log::info!("Got action: {action:?}");
action_tx.send(action.clone())?;
} else {
// If the key was not handled as a single key action,
// then consider it for multi-key combinations.
self.last_tick_key_events.push(key);
let mut tui = tui::Tui::new()?
.tick_rate(self.tick_rate)
.frame_rate(self.frame_rate);
// tui.mouse(true);
tui.enter()?;

// Check for multi-key combinations
if let Some(action) = keymap.get(&self.last_tick_key_events) {
log::info!("Got action: {action:?}");
action_tx.send(action.clone())?;
}
}
};
},
_ => {},
for component in self.components.iter_mut() {
component.register_action_handler(action_tx.clone())?;
}

for component in self.components.iter_mut() {
if let Some(action) = component.handle_events(Some(e.clone()))? {
action_tx.send(action)?;
}
component.register_config_handler(self.config.clone())?;
}
}

while let Ok(action) = action_rx.try_recv() {
if action != Action::Tick && action != Action::Render {
log::debug!("{action:?}");
for component in self.components.iter_mut() {
component.init(tui.size()?)?;
}
match action {
Action::Tick => {
self.last_tick_key_events.drain(..);
},
Action::Quit => self.should_quit = true,
Action::Suspend => self.should_suspend = true,
Action::Resume => self.should_suspend = false,
Action::ClearScreen => tui.terminal.clear()?,
Action::Resize(w, h) => {
tui.resize(Rect::new(0, 0, w, h))?;
tui.draw(|f| {
for component in self.components.iter_mut() {
let r = component.draw(f, f.size());
if let Err(e) = r {
action_tx.send(Action::Error(format!("Failed to draw: {:?}", e))).unwrap();

loop {
if let Some(e) = tui.next().await {
match e {
tui::Event::Quit => action_tx.send(Action::Quit)?,
tui::Event::Tick => action_tx.send(Action::Tick)?,
tui::Event::Render => action_tx.send(Action::Render)?,
tui::Event::Resize(x, y) => action_tx.send(Action::Resize(x, y))?,
tui::Event::Key(key) => {
if let Some(keymap) = self.config.keybindings.get(&self.mode) {
if let Some(action) = keymap.get(&vec![key]) {
log::info!("Got action: {action:?}");
action_tx.send(action.clone())?;
} else {
// If the key was not handled as a single key action,
// then consider it for multi-key combinations.
self.last_tick_key_events.push(key);

// Check for multi-key combinations
if let Some(action) = keymap.get(&self.last_tick_key_events) {
log::info!("Got action: {action:?}");
action_tx.send(action.clone())?;
}
}
};
}
_ => {}
}
}
})?;
},
Action::Render => {
tui.draw(|f| {
for component in self.components.iter_mut() {
let r = component.draw(f, f.size());
if let Err(e) = r {
action_tx.send(Action::Error(format!("Failed to draw: {:?}", e))).unwrap();
for component in self.components.iter_mut() {
if let Some(action) = component.handle_events(Some(e.clone()))? {
action_tx.send(action)?;
}
}
}
})?;
},
_ => {},
}
for component in self.components.iter_mut() {
if let Some(action) = component.update(action.clone())? {
action_tx.send(action)?
};
}

while let Ok(action) = action_rx.try_recv() {
if action != Action::Tick && action != Action::Render {
log::debug!("{action:?}");
}
match action {
Action::Tick => {
self.last_tick_key_events.drain(..);
}
Action::Quit => self.should_quit = true,
Action::Suspend => self.should_suspend = true,
Action::Resume => self.should_suspend = false,
Action::ClearScreen => tui.terminal.clear()?,
Action::Resize(w, h) => {
tui.resize(Rect::new(0, 0, w, h))?;
tui.draw(|f| {
for component in self.components.iter_mut() {
let r = component.draw(f, f.size());
if let Err(e) = r {
action_tx
.send(Action::Error(format!("Failed to draw: {:?}", e)))
.unwrap();
}
}
})?;
}
Action::Render => {
tui.draw(|f| {
for component in self.components.iter_mut() {
let r = component.draw(f, f.size());
if let Err(e) = r {
action_tx
.send(Action::Error(format!("Failed to draw: {:?}", e)))
.unwrap();
}
}
})?;
}
_ => {}
}
for component in self.components.iter_mut() {
if let Some(action) = component.update(action.clone())? {
action_tx.send(action)?
};
}
}
if self.should_suspend {
tui.suspend()?;
action_tx.send(Action::Resume)?;
action_tx.send(Action::ClearScreen)?;
// tui.mouse(true);
tui.enter()?;
} else if self.should_quit {
tui.stop()?;
break;
}
}
}
if self.should_suspend {
tui.suspend()?;
action_tx.send(Action::Resume)?;
action_tx.send(Action::ClearScreen)?;
// tui.mouse(true);
tui.enter()?;
} else if self.should_quit {
tui.stop()?;
break;
}
tui.exit()?;
Ok(())
}
tui.exit()?;
Ok(())
}
}
Loading

0 comments on commit 99f7d5c

Please sign in to comment.