Use app.task instead of separate variables

pull/3/head
Arijit Basu 3 years ago
parent 21e4a178c7
commit d5bfe6630f
No known key found for this signature in database
GPG Key ID: 7D7BF809E7378863

2
Cargo.lock generated

@ -1133,7 +1133,7 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]] [[package]]
name = "xplr" name = "xplr"
version = "0.1.11" version = "0.1.12"
dependencies = [ dependencies = [
"criterion", "criterion",
"crossterm", "crossterm",

@ -1,6 +1,6 @@
[package] [package]
name = "xplr" name = "xplr"
version = "0.1.11" # Update app.rs version = "0.1.12" # Update app.rs
authors = ["Arijit Basu <sayanarijit@gmail.com>"] authors = ["Arijit Basu <sayanarijit@gmail.com>"]
edition = "2018" edition = "2018"
description = "An experimental, minimal, configurable TUI file explorer, stealing ideas from nnn and fzf." description = "An experimental, minimal, configurable TUI file explorer, stealing ideas from nnn and fzf."

@ -12,7 +12,7 @@ use std::io::BufReader;
use std::path::Path; use std::path::Path;
use std::path::PathBuf; use std::path::PathBuf;
pub const VERSION: &str = "v0.1.11"; // Update Cargo.toml pub const VERSION: &str = "v0.1.12"; // Update Cargo.toml
pub const UNSUPPORTED_STR: &str = "???"; pub const UNSUPPORTED_STR: &str = "???";
pub const TOTAL_ROWS: usize = 50; pub const TOTAL_ROWS: usize = 50;
@ -274,6 +274,20 @@ pub fn parse_help_menu<'a>(
m m
} }
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Task {
NoOp,
Quit,
PrintAndQuit(String),
Call(CommandConfig),
}
impl Default for Task {
fn default() -> Self {
Self::NoOp
}
}
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct App { pub struct App {
pub version: String, pub version: String,
@ -285,8 +299,7 @@ pub struct App {
pub parsed_key_bindings: HashMap<Key, (String, Vec<Action>)>, pub parsed_key_bindings: HashMap<Key, (String, Vec<Action>)>,
pub parsed_help_menu: Vec<(String, String)>, pub parsed_help_menu: Vec<(String, String)>,
pub show_hidden: bool, pub show_hidden: bool,
pub call: Option<CommandConfig>, pub task: Task,
pub result: Option<String>,
} }
impl App { impl App {
@ -322,8 +335,7 @@ impl App {
parsed_key_bindings, parsed_key_bindings,
parsed_help_menu, parsed_help_menu,
show_hidden, show_hidden,
result: None, task: Task::NoOp,
call: None,
}) })
} }
@ -411,7 +423,7 @@ impl App {
} }
pub fn call(mut self, cmd: &CommandConfig) -> Result<Self, Error> { pub fn call(mut self, cmd: &CommandConfig) -> Result<Self, Error> {
self.call = Some(cmd.clone()); self.task = Task::Call(cmd.clone());
Ok(self) Ok(self)
} }
@ -631,22 +643,28 @@ impl App {
pub fn print_focused(self) -> Result<Self, Error> { pub fn print_focused(self) -> Result<Self, Error> {
let mut app = self; let mut app = self;
app.result = app app.task = app
.directory_buffer .directory_buffer
.focused() .focused()
.and_then(|(p, _)| p.to_str().map(|s| s.to_string())); .and_then(|(p, _)| p.to_str().map(|s| Task::PrintAndQuit(s.to_string())))
.unwrap_or_default();
Ok(app) Ok(app)
} }
pub fn print_pwd(self) -> Result<Self, Error> { pub fn print_pwd(self) -> Result<Self, Error> {
let mut app = self; let mut app = self;
app.result = app.directory_buffer.pwd.to_str().map(|s| s.to_string()); app.task = app
.directory_buffer
.pwd
.to_str()
.map(|s| Task::PrintAndQuit(s.to_string()))
.unwrap_or_default();
Ok(app) Ok(app)
} }
pub fn print_selected(self) -> Result<Self, Error> { pub fn print_selected(self) -> Result<Self, Error> {
let mut app = self; let mut app = self;
app.result = Some( app.task = Task::PrintAndQuit(
app.selected_paths app.selected_paths
.clone() .clone()
.iter() .iter()
@ -661,12 +679,12 @@ impl App {
pub fn print_app_state(self) -> Result<Self, Error> { pub fn print_app_state(self) -> Result<Self, Error> {
let state = serde_yaml::to_string(&self)?; let state = serde_yaml::to_string(&self)?;
let mut app = self; let mut app = self;
app.result = Some(state); app.task = Task::PrintAndQuit(state);
Ok(app) Ok(app)
} }
pub fn quit(mut self) -> Result<Self, Error> { pub fn quit(mut self) -> Result<Self, Error> {
self.result = Some("".into()); self.task = Task::Quit;
Ok(self) Ok(self)
} }

@ -8,17 +8,21 @@ use tui::backend::CrosstermBackend;
use tui::widgets::{ListState, TableState}; use tui::widgets::{ListState, TableState};
use tui::Terminal; use tui::Terminal;
use xplr::app; use xplr::app;
use xplr::app::Task;
use xplr::error::Error; use xplr::error::Error;
use xplr::input::Key; use xplr::input::Key;
use xplr::ui; use xplr::ui;
use std::fs;
handlebars_helper!(shellescape: |v: str| format!("{}", shellwords::escape(v))); handlebars_helper!(shellescape: |v: str| format!("{}", shellwords::escape(v)));
handlebars_helper!(readfile: |v: str| fs::read_to_string(v).unwrap());
fn main() -> Result<(), Error> { fn main() -> Result<(), Error> {
let mut app = app::create()?; let mut app = app::create()?;
let mut hb = Handlebars::new(); let mut hb = Handlebars::new();
hb.register_helper("shellescape", Box::new(shellescape)); hb.register_helper("shellescape", Box::new(shellescape));
hb.register_helper("readfile", Box::new(readfile));
hb.register_template_string( hb.register_template_string(
app::TEMPLATE_TABLE_ROW, app::TEMPLATE_TABLE_ROW,
&app.config &app.config
@ -48,15 +52,7 @@ fn main() -> Result<(), Error> {
let mut list_state = ListState::default(); let mut list_state = ListState::default();
term::enable_raw_mode().unwrap(); term::enable_raw_mode().unwrap();
terminal.draw(|f| { terminal.draw(|f| ui::draw(&app, &hb, f, &mut table_state, &mut list_state))?;
ui::draw(
&app,
&hb,
f,
&mut table_state,
&mut list_state,
)
})?;
let mut result = Ok(()); let mut result = Ok(());
'outer: for key in keys { 'outer: for key in keys {
@ -64,58 +60,54 @@ fn main() -> Result<(), Error> {
for action in actions.iter() { for action in actions.iter() {
app = match app.handle(action) { app = match app.handle(action) {
Ok(mut a) => { Ok(mut a) => {
terminal.draw(|f| { terminal
ui::draw( .draw(|f| ui::draw(&a, &hb, f, &mut table_state, &mut list_state))?;
&a,
&hb,
f,
&mut table_state,
&mut list_state,
)
})?;
if let Some(result) = a.result.clone() { match a.task.clone() {
term::disable_raw_mode().unwrap(); Task::NoOp => {}
std::mem::drop(terminal);
if !result.is_empty() { Task::Quit => {
println!("{}", &result); term::disable_raw_mode().unwrap();
}; std::mem::drop(terminal);
break 'outer; break 'outer;
}; }
Task::PrintAndQuit(txt) => {
term::disable_raw_mode().unwrap();
std::mem::drop(terminal);
if !txt.is_empty() {
println!("{}", &txt);
};
break 'outer;
}
if let Some(cmd) = a.call.clone() { Task::Call(cmd) => {
term::disable_raw_mode().unwrap(); term::disable_raw_mode().unwrap();
std::mem::drop(terminal); std::mem::drop(terminal);
if let Some((_, meta)) = a.directory_buffer.focused() { if let Some((_, meta)) = a.directory_buffer.focused() {
let _ = std::process::Command::new(cmd.command.clone()) let _ = std::process::Command::new(cmd.command.clone())
.current_dir(&a.directory_buffer.pwd) .current_dir(&a.directory_buffer.pwd)
.args( .args(
cmd.args cmd.args
.iter() .iter()
.map(|arg| hb.render_template(arg, &meta).unwrap()), .map(|arg| hb.render_template(arg, &meta).unwrap()),
) )
.status(); .status();
}; };
term::enable_raw_mode().unwrap(); term::enable_raw_mode().unwrap();
let stdout = get_tty()?; let stdout = get_tty()?;
let stdout = AlternateScreen::from(stdout); let stdout = AlternateScreen::from(stdout);
let backend = CrosstermBackend::new(stdout); let backend = CrosstermBackend::new(stdout);
terminal = Terminal::new(backend)?; terminal = Terminal::new(backend)?;
a = a.refresh()?; a = a.refresh()?;
terminal.draw(|f| { terminal.draw(|f| {
ui::draw( ui::draw(&a, &hb, f, &mut table_state, &mut list_state)
&a, })?;
&hb, }
f,
&mut table_state,
&mut list_state,
)
})?;
}; };
a.call = None; a.task = Task::NoOp;
a.result = None;
a a
} }
Err(e) => { Err(e) => {

Loading…
Cancel
Save