Skip to content

Commit

Permalink
style(fmt): fix formatting for how-to-spawn-vim using cargo fmt
Browse files Browse the repository at this point in the history
Signed-off-by: Deep Panchal <[email protected]>
  • Loading branch information
deepanchal committed Jul 1, 2024
1 parent d7315bc commit 212c8ca
Show file tree
Hide file tree
Showing 11 changed files with 1,220 additions and 1,112 deletions.
24 changes: 12 additions & 12 deletions code/how-to-spawn-vim/src/action.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
use std::{fmt, string::ToString};

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

// ANCHOR: action
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Display, Deserialize)]
pub enum Action {
Tick,
Render,
Resize(u16, u16),
Suspend,
Resume,
Quit,
Refresh,
Error(String),
Help,
EditFile,
Tick,
Render,
Resize(u16, u16),
Suspend,
Resume,
Quit,
Refresh,
Error(String),
Help,
EditFile,
}
// ANCHOR_END: action
286 changes: 149 additions & 137 deletions code/how-to-spawn-vim/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,161 +5,173 @@ 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())?;
}
}

// ANCHOR: run__action_EditFile
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::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)?;
}
}
}
})?;
},
// Add this handler
Action::EditFile => {
tui.exit()?;
let status = std::process::Command::new("vim").arg("/tmp/a.txt").status()?;
if status.success() {
log::info!("Successfully launched vim");
} else {
log::error!("Failed to launch vim");
}
tui = tui::Tui::new()?.tick_rate(self.tick_rate).frame_rate(self.frame_rate);
tui.enter()?;
},
_ => {},
}
// ANCHOR_END: run__action_EditFile
for component in self.components.iter_mut() {
if let Some(action) = component.update(action.clone())? {
action_tx.send(action)?
};

// ANCHOR: run__action_EditFile
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::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();
}
}
})?;
}
// Add this handler
Action::EditFile => {
tui.exit()?;
let status = std::process::Command::new("vim")
.arg("/tmp/a.txt")
.status()?;
if status.success() {
log::info!("Successfully launched vim");
} else {
log::error!("Failed to launch vim");
}
tui = tui::Tui::new()?
.tick_rate(self.tick_rate)
.frame_rate(self.frame_rate);
tui.enter()?;
}
_ => {}
}
// ANCHOR_END: run__action_EditFile
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)?;
tui = tui::Tui::new()?
.tick_rate(self.tick_rate)
.frame_rate(self.frame_rate);
// tui.mouse(true);
tui.enter()?;
} else if self.should_quit {
tui.stop()?;
break;
}
}
}
if self.should_suspend {
tui.suspend()?;
action_tx.send(Action::Resume)?;
tui = tui::Tui::new()?.tick_rate(self.tick_rate).frame_rate(self.frame_rate);
// tui.mouse(true);
tui.enter()?;
} else if self.should_quit {
tui.stop()?;
break;
}
tui.exit()?;
Ok(())
}
tui.exit()?;
Ok(())
}
}
26 changes: 16 additions & 10 deletions code/how-to-spawn-vim/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,21 @@ use crate::utils::version;
#[derive(Parser, Debug)]
#[command(author, version = version(), about)]
pub struct Cli {
#[arg(short, long, value_name = "FLOAT", help = "Tick rate, i.e. number of ticks per second", default_value_t = 1.0)]
pub tick_rate: f64,
#[arg(
short,
long,
value_name = "FLOAT",
help = "Tick rate, i.e. number of ticks per second",
default_value_t = 1.0
)]
pub tick_rate: f64,

#[arg(
short,
long,
value_name = "FLOAT",
help = "Frame rate, i.e. number of frames per second",
default_value_t = 4.0
)]
pub frame_rate: f64,
#[arg(
short,
long,
value_name = "FLOAT",
help = "Frame rate, i.e. number of frames per second",
default_value_t = 4.0
)]
pub frame_rate: f64,
}
Loading

0 comments on commit 212c8ca

Please sign in to comment.