termianl rendering text, backspace needs fix
This commit is contained in:
@ -12,7 +12,7 @@ impl PathBufIsValid for PathBuf {
|
||||
}
|
||||
}
|
||||
|
||||
trait ChangeDirectory {
|
||||
trait ChangeDirectory<'a> {
|
||||
fn change_directory(&self, args: SplitWhitespace) -> Option<PathBuf>;
|
||||
fn set_current_dir(&self, new_path: &Path) -> Option<PathBuf>;
|
||||
fn specific_user_dir(&self, user: String) -> Option<PathBuf>;
|
||||
@ -20,7 +20,7 @@ trait ChangeDirectory {
|
||||
fn previous_dir(&self) -> Option<PathBuf>;
|
||||
fn home_dir(&self) -> Option<PathBuf>;
|
||||
}
|
||||
impl ChangeDirectory for Command {
|
||||
impl<'a> ChangeDirectory<'a> for Command<'a> {
|
||||
fn set_current_dir(&self, new_path: &Path) -> Option<PathBuf> {
|
||||
std::env::set_current_dir(new_path).map_or_display_none(|()| Some(new_path.to_path_buf()))
|
||||
}
|
||||
@ -87,18 +87,19 @@ impl ChangeDirectory for Command {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Command(String);
|
||||
impl Command {
|
||||
pub const fn new(input: String) -> Self {
|
||||
pub struct Command<'a>(&'a String);
|
||||
impl<'a> Command<'a> {
|
||||
pub const fn new(input: &'a String) -> Self {
|
||||
Self(input)
|
||||
}
|
||||
|
||||
pub fn spawn_sys_cmd(&mut self, history: &mut History, command_process: io::Result<process::Child>) {
|
||||
if let Ok(mut child) = command_process {
|
||||
history.add(self.0.as_str());
|
||||
child.wait().ok();
|
||||
} else {
|
||||
println!("lambdashell: Unknown command: {}", self.0)
|
||||
match command_process {
|
||||
Ok(mut child) => {
|
||||
history.add(self.0.as_str());
|
||||
child.wait().ok();
|
||||
},
|
||||
Err(_) => println!("pse: Unknown command: {}", self.0),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -3,6 +3,7 @@ pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
pub mod session;
|
||||
pub mod commands;
|
||||
pub mod history;
|
||||
pub mod terminal;
|
||||
pub mod ps;
|
||||
pub mod rc;
|
||||
pub mod vm;
|
||||
|
36
src/ps.rs
36
src/ps.rs
@ -1,4 +1,19 @@
|
||||
pub const DEFAULT_PS: &str = concat!("lambdashell-", env!("CARGO_PKG_VERSION"), " ");
|
||||
pub const DEFAULT_PS: &str = concat!("pse-", env!("CARGO_PKG_VERSION"), " ");
|
||||
|
||||
pub trait PsMut {
|
||||
fn get(&self) -> &str;
|
||||
fn modify(&mut self, prompt: String);
|
||||
}
|
||||
impl PsMut for Ps {
|
||||
#[inline]
|
||||
fn get(&self) -> &str {
|
||||
self.0.as_str()
|
||||
}
|
||||
#[inline]
|
||||
fn modify(&mut self, prompt: String) {
|
||||
self.0 = prompt
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Ps(String);
|
||||
@ -6,23 +21,4 @@ impl Ps {
|
||||
pub const fn set(prompt: String) -> Self {
|
||||
Self(prompt)
|
||||
}
|
||||
//rustc: `std::string::String::as_str` is not yet stable as a const fn
|
||||
pub fn get(&self) -> &str {
|
||||
self.0.as_str()
|
||||
}
|
||||
pub fn modify(&mut self, prompt: String) {
|
||||
self.0 = prompt
|
||||
}
|
||||
pub fn display(&self) {
|
||||
print!("{}", self.0);
|
||||
}
|
||||
|
||||
pub fn working_dir_name(&self) -> String {
|
||||
std::env::current_dir().map_or("?".to_owned(), |path| path.file_name().map_or("?".to_owned(), |name| {
|
||||
match name.to_os_string() == whoami::username_os() {
|
||||
true => "~".to_owned(),
|
||||
false => name.to_string_lossy().to_string(),
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
@ -18,7 +18,7 @@ pub fn config_dir() -> Option<PathBuf> {
|
||||
let mut config = home::home_dir()?;
|
||||
config.push(".config");
|
||||
config.is_valid_dir_or_create()?;
|
||||
config.push("lambdashell");
|
||||
config.push("pse");
|
||||
config.is_valid_dir_or_create()
|
||||
}
|
||||
|
||||
|
@ -1,16 +1,11 @@
|
||||
use std::{cell::RefCell, fs, io::{self}, rc::Rc};
|
||||
use std::{cell::RefCell, fs, rc::Rc};
|
||||
use core::fmt;
|
||||
use color_print::ceprintln;
|
||||
|
||||
use crate::{
|
||||
commands, history::History, ps::{self, Ps}, rc::{self}, vm::{self, LuauVm}
|
||||
history::History, ps::{self, Ps}, rc::{self}, terminal, vm::LuauVm
|
||||
};
|
||||
|
||||
#[inline]
|
||||
pub fn shell_error<E: fmt::Display>(err: E) {
|
||||
ceprintln!("<bold,r>[!]:</> {err}")
|
||||
}
|
||||
|
||||
pub trait MapDisplay<T, E: fmt::Display> {
|
||||
fn map_or_display<F: FnOnce(T)>(self, f: F);
|
||||
fn map_or_display_none<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R>;
|
||||
@ -28,67 +23,47 @@ impl<T, E: fmt::Display> MapDisplay<T, E> for Result<T, E> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn shell_error<E: fmt::Display>(err: E) {
|
||||
ceprintln!("<bold,r>[!]:</> {err}")
|
||||
}
|
||||
pub fn shell_error_none<T, E: fmt::Display>(err: E) -> Option<T> {
|
||||
shell_error(err);
|
||||
None
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Config {
|
||||
pub norc: bool
|
||||
pub norc: bool,
|
||||
pub nojit: bool,
|
||||
pub nosandbox: bool
|
||||
}
|
||||
pub struct LambdaShell {
|
||||
terminate: bool,
|
||||
history: History,
|
||||
config: Config,
|
||||
vm: LuauVm,
|
||||
ps: Rc<RefCell<Ps>>,
|
||||
ps: Ps,
|
||||
}
|
||||
impl LambdaShell {
|
||||
pub fn create(config: Config) -> Self {
|
||||
let ps = Rc::new(RefCell::new(Ps::set(ps::DEFAULT_PS.to_owned())));
|
||||
Self {
|
||||
ps: Rc::clone(&ps),
|
||||
vm: vm::LuauVm::new(ps),
|
||||
ps: Ps::set(ps::DEFAULT_PS.to_owned()),
|
||||
history: History::init(),
|
||||
terminate: false,
|
||||
config,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn wait(&mut self) -> Result<(), io::Error> {
|
||||
io::Write::flush(&mut io::stdout()).map(|()| {
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input).map_or_display(|_size| match input.trim() {
|
||||
"exit" => {
|
||||
self.terminate = true;
|
||||
self.history.add("exit");
|
||||
},
|
||||
trim => commands::Command::new(trim.to_owned()).exec(&mut self.history)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub fn error<E: fmt::Display>(&mut self, err: E) {
|
||||
shell_error(err);
|
||||
self.terminate = true;
|
||||
}
|
||||
|
||||
pub fn start(&mut self) {
|
||||
if !self.config.norc {
|
||||
if let Some(conf_file) = rc::config_file() {
|
||||
fs::read_to_string(conf_file).map_or_display(|luau_conf| self.vm_exec(luau_conf));
|
||||
}
|
||||
}
|
||||
self.ps.borrow().display();
|
||||
|
||||
loop {
|
||||
if self.terminate { break } else {
|
||||
match self.wait() {
|
||||
Ok(()) => self.ps.borrow().display(),
|
||||
Err(flush_err) => self.error(flush_err),
|
||||
}
|
||||
}
|
||||
}
|
||||
self.history.write_to_file_fallible();
|
||||
terminal::Processor::init()
|
||||
.input_processor(&mut self.history)
|
||||
.map_or_display(|()| self.history.write_to_file_fallible());
|
||||
}
|
||||
|
||||
pub fn vm_exec(&self, source: String) {
|
||||
self.vm.exec(source);
|
||||
let p = Rc::new(RefCell::new(&self.ps));
|
||||
LuauVm::new(Rc::clone(p)).exec(source);
|
||||
}
|
||||
}
|
||||
|
122
src/terminal.rs
Normal file
122
src/terminal.rs
Normal file
@ -0,0 +1,122 @@
|
||||
use crossterm::{event::{self, Event, KeyCode, KeyEvent, KeyModifiers}, terminal};
|
||||
use std::io::{self, Write};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{commands::Command, history::History, session};
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum InputHandleError {
|
||||
#[error("UserExit")]
|
||||
UserExit,
|
||||
#[error("Sigterm")]
|
||||
Sigterm,
|
||||
#[error("Render failure: {0}")]
|
||||
Write(io::Error),
|
||||
#[error("Flush failure: {0}")]
|
||||
Flush(io::Error),
|
||||
#[error("Disabling the terminal's raw mode failed: {0}")]
|
||||
EnableRaw(io::Error),
|
||||
#[error("Enabling the terminal's raw mode failed: {0}")]
|
||||
DisableRaw(io::Error),
|
||||
#[error("key input failure: {0}")]
|
||||
Key(KeyCode),
|
||||
}
|
||||
type InputResult<T> = Result<T, InputHandleError>;
|
||||
|
||||
trait SpecificKeybinds {
|
||||
const TERM_ID_1: &str;
|
||||
fn key_ctrl(&mut self, input_key: KeyEvent, keycode: KeyCode) -> InputResult<()>;
|
||||
fn key_enter(&mut self, history: &mut History) -> InputResult<()>;
|
||||
fn key_backspace(&mut self) -> InputResult<()>;
|
||||
}
|
||||
impl SpecificKeybinds for Processor {
|
||||
const TERM_ID_1: &str = "exit";
|
||||
|
||||
fn key_ctrl(&mut self, input_key: KeyEvent, keycode: KeyCode) -> InputResult<()> {
|
||||
if input_key.modifiers.contains(KeyModifiers::CONTROL) {
|
||||
match keycode {
|
||||
KeyCode::Char('c') => Err(InputHandleError::Sigterm),
|
||||
_ => Ok(())
|
||||
}
|
||||
} else {
|
||||
self.render(Some(keycode.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
fn key_enter(&mut self, history: &mut History) -> InputResult<()> {
|
||||
if self.0 == Self::TERM_ID_1 { return Err(InputHandleError::UserExit) };
|
||||
|
||||
terminal::disable_raw_mode().map_err(InputHandleError::DisableRaw)?;
|
||||
Command::new(&self.0).exec(history);
|
||||
self.0.clear();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn key_backspace(&mut self) -> InputResult<()> {
|
||||
match self.0.pop() {
|
||||
Some(_) => self.render(None),
|
||||
None => {
|
||||
//the string is empty, do terminal beep
|
||||
Ok(())
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Processor(String);
|
||||
impl Processor {
|
||||
pub const fn init() -> Self {
|
||||
Self(String::new())
|
||||
}
|
||||
|
||||
pub fn render(&mut self, def: Option<String>) -> InputResult<()> {
|
||||
match def {
|
||||
Some(def_string) => {
|
||||
self.0.push_str(&def_string);
|
||||
write!(io::stdout(), "{def_string}").map_err(InputHandleError::Write)?;
|
||||
},
|
||||
None => {
|
||||
write!(io::stdout(), "{}", self.0).map_err(InputHandleError::Write)?
|
||||
}
|
||||
};
|
||||
io::stdout().flush().map_err(InputHandleError::Flush)
|
||||
}
|
||||
|
||||
pub fn input_handler(&mut self, input_key: KeyEvent, history: &mut History) -> Option<()> {
|
||||
let input_handle = match input_key.code {
|
||||
KeyCode::Enter => self.key_enter(history),
|
||||
KeyCode::Backspace => self.key_backspace(),
|
||||
KeyCode::Tab => todo!(),
|
||||
KeyCode::Right => todo!(),
|
||||
KeyCode::Left => todo!(),
|
||||
KeyCode::Up => todo!(),
|
||||
KeyCode::Down => todo!(),
|
||||
keycode => self.key_ctrl(input_key, keycode)
|
||||
};
|
||||
input_handle.map_or_else(|inp_err| match inp_err {
|
||||
InputHandleError::UserExit => None,
|
||||
InputHandleError::Sigterm => self.render(Some("^C".to_owned())).ok(),
|
||||
InputHandleError::Write(e) => session::shell_error_none(e),
|
||||
InputHandleError::Flush(e) => session::shell_error_none(e),
|
||||
InputHandleError::Key(e) => session::shell_error_none(e),
|
||||
InputHandleError::DisableRaw(e) => session::shell_error_none(e),
|
||||
InputHandleError::EnableRaw(e) => session::shell_error_none(e)
|
||||
}, Some)
|
||||
}
|
||||
|
||||
fn input_mainthread(&mut self, history: &mut History) -> io::Result<()> {
|
||||
crossterm::execute!(io::stdout(), event::EnableBracketedPaste)?;
|
||||
loop {
|
||||
terminal::enable_raw_mode()?;
|
||||
if let Event::Key(event) = event::read()? {
|
||||
if self.input_handler(event, history).is_none() { break Ok(()) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn input_processor(&mut self, history: &mut History) -> io::Result<()> {
|
||||
self.input_mainthread(history)?;
|
||||
terminal::disable_raw_mode()?;
|
||||
crossterm::execute!(io::stdout(), event::DisableBracketedPaste)
|
||||
}
|
||||
}
|
@ -1,8 +1,8 @@
|
||||
use mlua::{Function, Lua as Luau, MultiValue, Result as lResult, Table, Value};
|
||||
use color_print::{cformat, ceprintln};
|
||||
use terminal::TerminalGlobal;
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
use core::fmt;
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
use shell::ShellGlobal;
|
||||
|
||||
use crate::{ps::Ps, session::MapDisplay};
|
||||
@ -27,14 +27,16 @@ impl<T, E: fmt::Display> LuauRuntimeErr<T> for Result<T, E> {
|
||||
trait Globals {
|
||||
const LIB_VERSION: &str;
|
||||
const CONV_ERROR: &str;
|
||||
fn global_warn(&self, luau_globals: &Table) -> lResult<()>;
|
||||
fn global_version(&self, luau_globals: &Table) -> lResult<()>;
|
||||
const LIB_NAME: &str;
|
||||
fn glob_warn(&self, luau_globals: &Table) -> lResult<()>;
|
||||
fn glob_version(&self, luau_globals: &Table) -> lResult<()>;
|
||||
}
|
||||
impl Globals for LuauVm {
|
||||
const LIB_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
const LIB_NAME: &str = env!("CARGO_PKG_NAME");
|
||||
const CONV_ERROR: &str = "<SHELL CONVERSION ERROR>";
|
||||
|
||||
fn global_warn(&self, luau_globals: &Table) -> lResult<()> {
|
||||
fn glob_warn(&self, luau_globals: &Table) -> lResult<()> {
|
||||
let luau_print = luau_globals.get::<Function>("print")?;
|
||||
luau_globals.raw_set("warn", self.vm.create_function(move |this, args: MultiValue| -> lResult<()> {
|
||||
let luau_multi_values = args.into_iter()
|
||||
@ -46,9 +48,9 @@ impl Globals for LuauVm {
|
||||
})?)
|
||||
}
|
||||
|
||||
fn global_version(&self, luau_globals: &Table) -> lResult<()> {
|
||||
fn glob_version(&self, luau_globals: &Table) -> lResult<()> {
|
||||
let luau_info = luau_globals.get::<String>("_VERSION")?;
|
||||
luau_globals.raw_set("_VERSION", format!("{luau_info}, liblambdashell {}", Self::LIB_VERSION))
|
||||
luau_globals.raw_set("_VERSION", format!("{luau_info}, {} {}", Self::LIB_NAME, Self::LIB_VERSION))
|
||||
}
|
||||
}
|
||||
|
||||
@ -61,12 +63,12 @@ impl LuauVm {
|
||||
Self { vm: Luau::new(), ps }
|
||||
}
|
||||
|
||||
fn set_shell_globals(&self) -> lResult<()> {
|
||||
fn setglobs(&self) -> lResult<()> {
|
||||
let luau_globals = self.vm.globals();
|
||||
self.global_shell(&luau_globals)?;
|
||||
self.global_terminal(&luau_globals)?;
|
||||
self.global_warn(&luau_globals)?;
|
||||
self.global_version(&luau_globals)?;
|
||||
self.glob_shell(&luau_globals)?;
|
||||
self.glob_terminal(&luau_globals)?;
|
||||
self.glob_warn(&luau_globals)?;
|
||||
self.glob_version(&luau_globals)?;
|
||||
luau_globals.raw_set("getfenv", mlua::Nil)?;
|
||||
luau_globals.raw_set("setfenv", mlua::Nil)?;
|
||||
self.vm.sandbox(true)?;
|
||||
@ -74,6 +76,6 @@ impl LuauVm {
|
||||
}
|
||||
|
||||
pub fn exec(&self, source: String) {
|
||||
self.set_shell_globals().map_or_display_none(|()| self.vm.load(source).exec().map_or_luau_rt_err(Some));
|
||||
self.setglobs().map_or_display_none(|()| self.vm.load(source).exec().map_or_luau_rt_err(Some));
|
||||
}
|
||||
}
|
@ -2,7 +2,7 @@ use mlua::{Lua as Luau, MetaMethod, Result as lResult, Table, UserData, UserData
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
use whoami::fallible;
|
||||
|
||||
use crate::{ps::Ps, vm::LuauVm};
|
||||
use crate::{ps::{Ps, PsMut}, vm::LuauVm};
|
||||
|
||||
const DEFAULT_HOSTNAME: &str = "hostname";
|
||||
|
||||
@ -27,20 +27,18 @@ impl UserData for Shell {
|
||||
}
|
||||
|
||||
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
|
||||
methods.add_meta_method_mut(MetaMethod::NewIndex, |_, this, (tindex, tvalue): (String, String)| -> lResult<()> {
|
||||
if tindex == "PROMPT" {
|
||||
this.0.borrow_mut().modify(tvalue);
|
||||
}
|
||||
methods.add_meta_method_mut(MetaMethod::NewIndex, |_, this, (t_index, t_value): (String, String)| -> lResult<()> {
|
||||
if t_index == "PROMPT" { this.0.borrow_mut().modify(t_value); }
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ShellGlobal {
|
||||
fn global_shell(&self, luau_globals: &Table) -> lResult<()>;
|
||||
fn glob_shell(&self, luau_globals: &Table) -> lResult<()>;
|
||||
}
|
||||
impl ShellGlobal for LuauVm {
|
||||
fn global_shell(&self, luau_globals: &Table) -> lResult<()> {
|
||||
fn glob_shell(&self, luau_globals: &Table) -> lResult<()> {
|
||||
luau_globals.raw_set("SHELL", Shell(Rc::clone(&self.ps)))?;
|
||||
Ok(())
|
||||
}
|
||||
|
@ -84,10 +84,10 @@ impl UserData for Terminal {
|
||||
}
|
||||
|
||||
pub trait TerminalGlobal {
|
||||
fn global_terminal(&self, luau_globals: &Table) -> lResult<()>;
|
||||
fn glob_terminal(&self, luau_globals: &Table) -> lResult<()>;
|
||||
}
|
||||
impl TerminalGlobal for LuauVm {
|
||||
fn global_terminal(&self, luau_globals: &Table) -> lResult<()> {
|
||||
fn glob_terminal(&self, luau_globals: &Table) -> lResult<()> {
|
||||
luau_globals.raw_set("TERMINAL", Terminal)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user