2 Commits

5 changed files with 75 additions and 54 deletions

View File

@ -96,10 +96,10 @@ impl Command for Pse {
if let Some(command) = args.next() {
match command {
"cd" => if ChangeDirectory(None).change_directory(args).is_some() {
self.history.add(self.rt.input.literal.as_str())
self.rt.history.add(self.rt.input.literal.as_str())
},
command => if let Ok(mut child) = process::Command::new(command).args(args).spawn() {
self.history.add(self.rt.input.literal.as_str());
self.rt.history.add(self.rt.input.literal.as_str());
child.wait().ok();
} else {
println!("pse: Unknown command: {}", self.rt.input.literal)

View File

@ -4,38 +4,39 @@ use crate::{rc::{self}, session::{self, MapDisplay}, valid_pbuf::IsValid};
#[derive(Debug, Clone)]
pub struct History {
fs_history: Option<Vec<String>>,
history: Vec<String>,
pub history: Vec<String>,
pub index: isize,
file: Option<PathBuf>,
}
impl History {
pub fn init() -> Self {
let mut history = Vec::new();
let file = rc::config_dir().map(|mut config_dir| {
config_dir.push(".history");
config_dir.is_valid_file_or_create(b"");
config_dir
});
let fs_history = file.as_ref().and_then(|file| {
file.as_ref().and_then(|file| {
File::open(file).map_or_display_none(|file| {
Some(BufReader::new(file).lines().map_while(Result::ok).collect::<Vec<String>>())
let mut fs_history_vec = BufReader::new(file).lines().map_while(Result::ok).collect::<Vec<String>>();
fs_history_vec.dedup();
fs_history_vec.reverse();
Some(fs_history_vec)
})
});
Self {
history: Vec::new(),
fs_history,
file,
}
}).inspect(|fs_history_vec| history = fs_history_vec.clone());
Self { history, file, index: -1 }
}
pub fn write_to_file_fallible(&mut self) {
if self.history.is_empty() { return; }
if let (Some(history_file), Some(fs_history)) = (&self.file, &self.fs_history) {
if let Some(history_file) = &self.file {
OpenOptions::new()
.append(true)
.open(history_file.as_path())
.map_or_display(|mut file| {
let newline_maybe = if fs_history.is_empty() { "" } else { "\n" };
let newline_maybe = if self.history.is_empty() { "" } else { "\n" };
let formatted = format!("{newline_maybe}{}", self.history.join("\n"));
file.write_all(formatted.as_bytes()).unwrap_or_else(session::shell_error)
});

View File

@ -1,5 +1,5 @@
use mlua::Lua as Luau;
use std::{cell::RefCell, fs, rc::Rc, usize};
use std::{cell::RefCell, fs, rc::Rc};
use core::fmt;
use crate::{
@ -44,16 +44,16 @@ pub struct Config {
#[derive(Debug, Clone)]
pub struct Input {
pub literal: String,
pub cursor: usize,
pub cursor: u16,
}
pub struct Rt {
pub input: Input,
pub ps: Rc<RefCell<String>>,
pub vm: Luau,
pub history: History,
}
pub struct Pse {
pub config: Config,
pub history: History,
pub rt: Rt
}
impl Pse {
@ -63,13 +63,14 @@ impl Pse {
let rt = Rt {
ps: Rc::new(RefCell::new(Self::DEFAULT_PS.to_owned())),
vm: Luau::new(),
history: History::init(),
input: Input {
literal: String::new(),
cursor: usize::MIN,
cursor: u16::MIN,
},
};
Self { rt, config, history: History::init() }
Self { rt, config }
}
pub fn start(&mut self) {
@ -78,6 +79,6 @@ impl Pse {
fs::read_to_string(conf_file).map_or_display(|luau_conf| self.vm_exec(luau_conf));
}
};
self.term_input_processor().map_or_display(|()| self.history.write_to_file_fallible())
self.term_input_processor().map_or_display(|()| self.rt.history.write_to_file_fallible())
}
}

View File

@ -32,7 +32,7 @@ fn debug<S: fmt::Display>(s: S) {
}
trait SpecificKeybinds {
const EXIT_1: &str;
const EXIT_ID_1: &str;
const KEY_SPACE: char;
fn key_literal(&mut self, keycode: KeyCode) -> InputResult<()>;
fn key_ctrl(&mut self, input_key: KeyEvent, keycode: KeyCode) -> InputResult<()>;
@ -40,9 +40,11 @@ trait SpecificKeybinds {
fn key_backspace(&mut self) -> InputResult<()>;
fn key_arrow_right(&mut self) -> InputResult<()>;
fn key_arrow_left(&mut self) -> InputResult<()>;
fn key_arrow_up(&mut self) -> InputResult<()>;
fn key_arrow_down(&mut self) -> InputResult<()>;
}
impl SpecificKeybinds for Pse {
const EXIT_1: &str = "exit";
const EXIT_ID_1: &str = "exit";
const KEY_SPACE: char = ' ';
fn key_literal(&mut self, keycode: KeyCode) -> InputResult<()> {
@ -56,6 +58,7 @@ impl SpecificKeybinds for Pse {
match input_key.modifiers.contains(KeyModifiers::CONTROL) {
true => match keycode {
KeyCode::Char('c') => Err(InputHandleError::Sigint),
KeyCode::Char('r') => unimplemented!(),
_ => Ok(())
},
false => self.key_literal(keycode)
@ -63,13 +66,13 @@ impl SpecificKeybinds for Pse {
}
fn key_enter(&mut self) -> InputResult<()> {
if self.rt.input.literal == Self::EXIT_1 { return Err(InputHandleError::UserExit) };
if self.rt.input.literal == Self::EXIT_ID_1 { return Err(InputHandleError::UserExit) };
terminal::disable_raw_mode().map_err(InputHandleError::DisableRaw)?;
println!();
self.spawn_sys_cmd();
self.rt.input.literal.clear();
self.rt.input.cursor = usize::MIN;
self.rt.input.cursor = u16::MIN;
self.term_render_ps()
}
@ -81,10 +84,8 @@ impl SpecificKeybinds for Pse {
terminal::Clear(terminal::ClearType::UntilNewLine)
).map_err(InputHandleError::Flush)?;
self.rt.input.cursor-=1;
Ok(())
} else {
Ok(())
}
Ok(())
}
fn key_arrow_right(&mut self) -> InputResult<()> {
@ -100,6 +101,24 @@ impl SpecificKeybinds for Pse {
None => Ok(())
}
}
fn key_arrow_up(&mut self) -> InputResult<()> {
self.rt.history.index += 1;
if self.rt.history.index != self.rt.history.history.len() as isize {
self.term_render_reset()?;
self.term_render(self.rt.history.history[self.rt.history.index as usize].clone())?;
}
Ok(())
}
fn key_arrow_down(&mut self) -> InputResult<()> {
self.rt.history.index -= 1;
if self.rt.history.index != -1 {
self.term_render_reset()?;
self.term_render(self.rt.history.history[self.rt.history.index as usize].clone())?;
}
Ok(())
}
}
pub trait TermInputCursor {
@ -108,24 +127,18 @@ pub trait TermInputCursor {
}
impl TermInputCursor for Pse {
fn term_input_cursor_move_left(&mut self) -> Option<()> {
if self.rt.input.cursor == usize::MIN { None } else {
match self.rt.input.cursor>usize::MIN {
true => {
self.rt.input.cursor-=1;
Some(())
},
if self.rt.input.cursor == u16::MIN { None } else {
match self.rt.input.cursor>u16::MIN {
true => { self.rt.input.cursor-=1; Some(()) }
false => None
}
}
}
fn term_input_cursor_move_right(&mut self) -> Option<()> {
if self.rt.input.cursor == usize::MAX { None } else {
match self.rt.input.cursor<self.rt.input.literal.chars().count() {
true => {
self.rt.input.cursor+=1;
Some(())
},
if self.rt.input.cursor == u16::MAX { None } else {
match self.rt.input.cursor<self.rt.input.literal.chars().count() as u16 {
true => { self.rt.input.cursor+=1; Some(()) },
false => None
}
}
@ -135,18 +148,22 @@ impl TermInputCursor for Pse {
pub trait TermProcessor {
fn term_render(&mut self, def_string: String) -> InputResult<()>;
fn term_render_ps(&self) -> InputResult<()>;
fn term_render_reset(&mut self) -> InputResult<()>;
fn term_input_handler(&mut self, input_key: KeyEvent) -> Option<()>;
fn term_input_mainthread(&mut self) -> io::Result<()>;
fn term_input_processor(&mut self) -> io::Result<()>;
}
impl TermProcessor for Pse {
fn term_render(&mut self, def_string: String) -> InputResult<()> {
self.rt.input.literal.insert_str(self.rt.input.cursor, &def_string);
self.rt.input.cursor+=1;
if self.rt.input.cursor != self.rt.input.literal.chars().count() {
fn term_render(&mut self, text: String) -> InputResult<()> {
self.rt.input.literal.insert_str(self.rt.input.cursor.into(), &text);
let input_literal_size = self.rt.input.literal.chars().count() as u16;
self.rt.input.cursor = input_literal_size;
if self.rt.input.cursor != input_literal_size {
execute!(io::stdout(), terminal::Clear(terminal::ClearType::UntilNewLine)).map_err(InputHandleError::Flush)?;
let slice = &self.rt.input.literal[(self.rt.input.cursor as usize)..];
write!(io::stdout(), "{text}{slice}").map_err(InputHandleError::Write)?;
} else {
write!(io::stdout(), "{}", def_string).map_err(InputHandleError::Write)?;
write!(io::stdout(), "{text}").map_err(InputHandleError::Write)?;
}
io::stdout().flush().map_err(InputHandleError::Flush)
}
@ -156,6 +173,13 @@ impl TermProcessor for Pse {
io::stdout().flush().map_err(InputHandleError::Flush)
}
fn term_render_reset(&mut self) -> InputResult<()> {
execute!(io::stdout(), cursor::MoveLeft(self.rt.input.cursor)).map_err(InputHandleError::Flush)?;
self.rt.input.cursor = u16::MIN;
self.rt.input.literal.clear();
execute!(io::stdout(), terminal::Clear(terminal::ClearType::UntilNewLine)).map_err(InputHandleError::Flush)
}
fn term_input_handler(&mut self, input_key: KeyEvent) -> Option<()> {
let input_handle = match input_key.code {
KeyCode::Enter => self.key_enter(),
@ -163,8 +187,8 @@ impl TermProcessor for Pse {
KeyCode::Tab => todo!(),
KeyCode::Right => self.key_arrow_right(),
KeyCode::Left => self.key_arrow_left(),
KeyCode::Up => todo!(),
KeyCode::Down => todo!(),
KeyCode::Up => self.key_arrow_up(),
KeyCode::Down => self.key_arrow_down(),
keycode => self.key_ctrl(input_key, keycode)
};
input_handle.map_or_else(|inp_err| match inp_err {

View File

@ -29,13 +29,8 @@ impl UserData for Shell {
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
methods.add_meta_method_mut(MetaMethod::NewIndex, |_, this, (t_index, t_value): (String, String)| -> lResult<()> {
if t_index == "PROMPT" {
match t_value.len() as u16 >= u16::MAX {
true => { mlua::Error::runtime(format!("SHELL.PROMPT's length exceeded or equals the max size. ({})", u16::MAX)); },
false => {
let mut prompt = this.0.borrow_mut();
*prompt = t_value;
},
}
}
Ok(())
});