breed/src/main.rs

467 lines
14 KiB
Rust
Raw Normal View History

2023-04-11 21:20:12 +00:00
/*
2023-04-11 20:02:34 +00:00
* Copyright (c) 2023 Marceline Cramer
2023-04-11 22:12:56 +00:00
* Copyright (c) 2023 Emma Tebibyte <emma@tebibyte.media>
2023-04-11 20:02:34 +00:00
* SPDX-License-Identifier: AGPL-3.0-or-later
*
* This program is free software: you can redistribute it and/or modify it under
2023-04-11 21:20:12 +00:00
* the terms of the GNU Affero General Public License as published by the Free
2023-04-11 20:02:34 +00:00
* Software Foundation, either version 3 of the License, or (at your option) any
* later version.
2023-04-11 21:20:12 +00:00
*
2023-04-11 20:02:34 +00:00
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
2023-04-11 22:12:56 +00:00
use std::{
env::args,
2023-04-12 05:22:16 +00:00
ffi::OsString,
2023-04-12 21:16:07 +00:00
fs::{File, OpenOptions},
io::{stdout, Read, Stdout, Write},
2023-04-11 22:26:02 +00:00
os::fd::FromRawFd,
2023-04-12 21:16:07 +00:00
path::{Path, PathBuf},
2023-04-12 16:52:46 +00:00
sync::Arc,
2023-04-11 22:12:56 +00:00
};
2023-04-11 19:56:43 +00:00
2023-04-12 21:13:20 +00:00
use crossbeam_channel::Sender;
2023-04-11 20:18:16 +00:00
use crossterm::{
cursor,
2023-04-12 21:13:20 +00:00
event::{Event, KeyCode, KeyEvent},
2023-04-12 23:40:07 +00:00
terminal, QueueableCommand, Result,
2023-04-11 20:18:16 +00:00
};
2023-04-13 04:04:21 +00:00
use keybinds::Keybind;
2023-04-12 16:52:46 +00:00
use parking_lot::Mutex;
2023-04-12 23:40:07 +00:00
use ropey::Rope;
2023-04-12 03:55:33 +00:00
use yacexits::{exit, EX_DATAERR, EX_UNAVAILABLE};
2023-04-11 19:56:43 +00:00
2023-04-12 19:36:38 +00:00
mod actions;
2023-04-12 03:55:56 +00:00
mod buffer;
2023-04-12 21:13:20 +00:00
mod config;
2023-04-13 04:04:21 +00:00
mod keybinds;
2023-04-12 03:34:24 +00:00
mod theme;
2023-04-11 19:56:43 +00:00
2023-04-12 03:55:56 +00:00
use buffer::Buffer;
2023-04-13 04:04:21 +00:00
use config::Config;
2023-04-12 03:34:24 +00:00
use theme::StyleStore;
2023-04-11 19:56:43 +00:00
#[derive(Copy, Clone, Debug, Default)]
pub struct Cursor {
2023-04-11 19:56:43 +00:00
pub column: usize,
pub line: usize,
}
#[derive(Clone, Debug, Default)]
2023-04-12 19:46:34 +00:00
pub struct NormalState {
pub error: Option<String>,
}
#[derive(Clone, Debug, Default)]
2023-04-12 19:46:34 +00:00
pub struct CommandState {
pub buf: String,
pub cursor: usize,
}
2023-04-11 21:28:42 +00:00
#[derive(Copy, Clone, Debug)]
2023-04-12 19:46:34 +00:00
pub struct InsertState {
2023-04-11 21:28:42 +00:00
append: bool,
}
#[derive(Clone, Debug)]
2023-04-12 19:46:34 +00:00
pub enum Mode {
Normal(NormalState),
Command(CommandState),
2023-04-11 19:56:43 +00:00
Visual,
2023-04-11 21:28:42 +00:00
Insert(InsertState),
2023-04-11 19:56:43 +00:00
}
impl Default for Mode {
fn default() -> Self {
Mode::Normal(Default::default())
}
}
2023-04-11 19:56:43 +00:00
impl Mode {
pub fn cursor_style(&self) -> cursor::SetCursorStyle {
use cursor::SetCursorStyle as Style;
match self {
Mode::Normal(_) => Style::SteadyBlock,
2023-04-11 19:56:43 +00:00
Mode::Visual => Style::BlinkingBlock,
2023-04-11 21:28:42 +00:00
Mode::Insert(_) => Style::BlinkingBar,
Mode::Command(_) => Style::SteadyUnderScore,
2023-04-11 19:56:43 +00:00
}
}
}
#[derive(Copy, Clone, Debug)]
pub enum Direction {
2023-04-11 19:56:43 +00:00
Left,
Down,
Up,
Right,
}
2023-04-12 19:36:38 +00:00
pub struct State {
2023-04-12 16:52:46 +00:00
pub styles: Arc<Mutex<StyleStore>>,
2023-04-13 04:04:21 +00:00
pub config: Config,
2023-04-11 19:56:43 +00:00
pub buffer: Buffer,
pub cursor: Cursor,
2023-04-12 05:22:16 +00:00
pub file: Option<OsString>,
pub mode: Mode,
2023-04-12 23:40:07 +00:00
pub last_saved: Rope,
2023-04-11 21:29:52 +00:00
pub scroll: Cursor,
pub size: (usize, usize),
2023-04-11 19:56:43 +00:00
pub quit: bool,
2023-04-12 21:13:20 +00:00
pub theme_tx: Sender<PathBuf>,
2023-04-11 19:56:43 +00:00
}
impl State {
2023-04-12 05:22:16 +00:00
pub fn from_str(file_name: Option<OsString>, text: &str) -> Result<Self> {
2023-04-12 16:52:46 +00:00
let styles = Arc::new(Mutex::new(StyleStore::default()));
let buffer = Buffer::from_str(styles.clone(), text);
2023-04-12 23:40:07 +00:00
let last_saved = buffer.as_ref().clone();
2023-04-11 21:29:52 +00:00
let (cols, rows) = terminal::size()?;
2023-04-12 21:13:20 +00:00
let theme_tx = config::ThemeWatcher::spawn(styles.clone());
2023-04-11 21:29:52 +00:00
Ok(Self {
2023-04-12 16:52:46 +00:00
styles,
2023-04-13 04:04:21 +00:00
config: Default::default(),
2023-04-12 16:52:46 +00:00
buffer,
2023-04-11 19:56:43 +00:00
cursor: Cursor::default(),
2023-04-12 05:22:16 +00:00
file: file_name,
mode: Mode::default(),
2023-04-12 23:40:07 +00:00
last_saved,
2023-04-11 21:29:52 +00:00
scroll: Cursor::default(),
size: (cols as usize, rows as usize),
2023-04-11 19:56:43 +00:00
quit: false,
2023-04-12 21:13:20 +00:00
theme_tx,
2023-04-11 21:29:52 +00:00
})
2023-04-11 19:56:43 +00:00
}
2023-04-12 03:34:24 +00:00
pub fn draw(&mut self, out: &mut impl Write) -> Result<()> {
// begin update
let (cols, rows) = terminal::size()?;
2023-04-12 21:50:14 +00:00
out.queue(terminal::BeginSynchronizedUpdate)?;
out.queue(terminal::Clear(terminal::ClearType::All))?;
2023-04-12 16:52:46 +00:00
let mut styles = self.styles.lock();
// draw status line
let mut set_cursor_pos = None;
let mut show_status_bar = false;
match &self.mode {
Mode::Command(CommandState { buf, cursor }) => {
let col = *cursor as u16 + 1;
let row = rows - 1;
2023-04-12 21:50:14 +00:00
out.queue(cursor::MoveTo(0, row))?;
write!(out, ":{}", buf)?;
set_cursor_pos = Some((col, row));
show_status_bar = true;
}
Mode::Normal(NormalState { error: Some(error) }) => {
2023-04-12 16:52:46 +00:00
let error_style = styles.get_scope("error");
2023-04-12 21:50:14 +00:00
out.queue(cursor::MoveTo(0, rows - 1))?;
2023-04-12 03:34:24 +00:00
error_style.print_styled(out, error)?;
show_status_bar = true;
}
_ => {}
}
2023-04-12 21:13:20 +00:00
// done with styles
drop(styles);
// draw buffer
let buffer_rows = if show_status_bar { rows - 1 } else { rows };
2023-04-13 04:04:21 +00:00
let lr_width = self
.buffer
.draw(cols, buffer_rows, self.scroll, self.cursor, out)?;
// draw cursor
let cursor_pos = set_cursor_pos.unwrap_or_else(|| {
// calculate cursor position on buffer
let cursor = self.buffer.clamped_cursor(self.cursor);
let col = cursor.column.saturating_sub(self.scroll.column) as u16;
let row = cursor.line.saturating_sub(self.scroll.line) as u16;
let col = col + lr_width as u16;
(col, row)
});
2023-04-12 21:50:14 +00:00
out.queue(cursor::MoveTo(cursor_pos.0, cursor_pos.1))?;
out.queue(self.mode.cursor_style())?;
// finish update
2023-04-12 21:50:14 +00:00
out.queue(terminal::EndSynchronizedUpdate)?;
out.flush()?;
2023-04-11 19:56:43 +00:00
Ok(())
}
2023-04-13 03:39:55 +00:00
/// Sets the state to `Mode::Normal` with an error message.
pub fn set_error(&mut self, error: impl ToString) {
self.mode = Mode::Normal(NormalState {
error: Some(error.to_string()),
});
}
2023-04-11 19:56:43 +00:00
pub fn on_event(&mut self, event: Event) {
match &self.mode {
Mode::Normal(state) => self.on_normal_event(event, state.clone()),
Mode::Command(state) => self.on_command_event(event, state.clone()),
2023-04-11 19:56:43 +00:00
Mode::Visual => self.on_visual_event(event),
Mode::Insert(state) => self.on_insert_event(event, state.clone()),
2023-04-11 19:56:43 +00:00
}
}
fn on_normal_event(&mut self, event: Event, mut state: NormalState) {
// reset the error from the last event
state.error = None;
2023-04-13 04:04:21 +00:00
self.mode = Mode::Normal(state);
2023-04-11 19:56:43 +00:00
match event {
2023-04-13 04:04:21 +00:00
Event::Key(KeyEvent { code, .. }) => {
if let Some(keybind) = self.config.keybinds.visual.map.get(&code) {
self.execute_keybind(keybind.clone());
2023-04-11 19:56:43 +00:00
}
2023-04-13 04:04:21 +00:00
}
2023-04-11 21:29:52 +00:00
event => self.on_any_event(event),
2023-04-11 19:56:43 +00:00
}
}
fn on_command_event(&mut self, event: Event, mut state: CommandState) {
2023-04-11 19:56:43 +00:00
match event {
Event::Key(KeyEvent { code, .. }) => match code {
KeyCode::Char(c) => {
state.buf.insert(state.cursor, c);
state.cursor += 1;
2023-04-11 19:56:43 +00:00
}
KeyCode::Backspace => {
if state.cursor > 0 {
state.cursor -= 1;
state.buf.remove(state.cursor);
}
}
KeyCode::Delete if state.cursor < state.buf.len() => {
state.buf.remove(state.cursor);
}
KeyCode::Left if state.cursor > 0 => {
state.cursor -= 1;
}
KeyCode::Right if state.cursor < state.buf.len() => {
state.cursor += 1;
}
KeyCode::Enter => {
// TODO add to command history
let result = self.execute_command(&state.buf);
let error = result.err();
self.mode = Mode::Normal(NormalState { error });
return;
}
2023-04-13 04:04:21 +00:00
KeyCode::Esc => {
self.mode = Mode::default();
return;
}
_ => {}
2023-04-11 19:56:43 +00:00
},
event => return self.on_any_event(event),
2023-04-11 19:56:43 +00:00
}
self.mode = Mode::Command(state);
2023-04-11 19:56:43 +00:00
}
fn on_visual_event(&mut self, event: Event) {
match event {
2023-04-13 04:04:21 +00:00
Event::Key(KeyEvent { code, .. }) => {
if let Some(keybind) = self.config.keybinds.visual.map.get(&code) {
self.execute_keybind(keybind.clone());
2023-04-11 19:56:43 +00:00
}
2023-04-13 04:04:21 +00:00
}
2023-04-11 21:29:52 +00:00
event => self.on_any_event(event),
2023-04-11 19:56:43 +00:00
}
}
2023-04-13 04:04:21 +00:00
fn on_insert_event(&mut self, event: Event, _state: InsertState) {
2023-04-11 19:56:43 +00:00
match event {
2023-04-13 04:04:21 +00:00
Event::Key(KeyEvent { code, .. }) => match self.config.keybinds.insert.map.get(&code) {
Some(keybind) => self.execute_keybind(keybind.clone()),
None => {
if let KeyCode::Char(c) = code {
self.buffer.insert_char(self.cursor, c);
self.move_cursor(Direction::Right);
2023-04-11 21:28:42 +00:00
}
2023-04-11 19:56:43 +00:00
}
},
2023-04-11 21:29:52 +00:00
event => self.on_any_event(event),
}
}
fn on_any_event(&mut self, event: Event) {
match event {
Event::Resize(cols, rows) => {
self.size = (cols as usize, rows as usize);
}
2023-04-11 19:56:43 +00:00
_ => {}
}
}
2023-04-12 16:44:37 +00:00
fn write_buffer(&mut self, file: OsString) -> Result<()> {
2023-04-12 23:40:07 +00:00
self.last_saved = self.buffer.as_ref().clone();
2023-04-12 21:39:46 +00:00
let out = self.buffer.as_ref().bytes().collect::<Vec<u8>>();
2023-04-12 16:44:37 +00:00
let mut handle = OpenOptions::new().write(true).open(file)?;
handle.write_all(out.as_slice())?;
2023-04-12 05:22:16 +00:00
Ok(())
}
2023-04-12 21:27:01 +00:00
fn write_command(&mut self, command: &str, args: &[&str]) -> std::result::Result<(), String> {
let handle = match self.file.clone() {
Some(handle) => handle,
None => match args.get(0) {
Some(part) => OsString::from(part),
None => {
return Err(format!("{}: No file name.", command));
}
},
};
self.write_buffer(handle).map_err(|err| format!("{}", err))
}
2023-04-13 04:04:21 +00:00
fn execute_keybind(&mut self, keybind: Keybind) {
match keybind {
Keybind::Action(action) => action(self),
Keybind::Command(command) => {
let result = self.execute_command(&command);
let error = result.err();
self.mode = Mode::Normal(NormalState { error });
return;
}
}
}
fn execute_command(&mut self, command: &str) -> std::result::Result<(), String> {
let command_parts = command.split(' ').collect::<Vec<&str>>();
2023-04-12 21:27:01 +00:00
let command = match command_parts.get(0) {
Some(command) => command,
None => return Ok(()),
};
2023-04-12 21:27:01 +00:00
let args = &command_parts[1..];
2023-04-12 21:27:01 +00:00
match *command {
2023-04-12 23:40:07 +00:00
"q!" => self.quit = true,
"q" => {
if self.last_saved == *self.buffer.as_ref() {
self.quit = true;
} else {
return Err("Buffer is unsaved (add ! to override)".into());
2023-04-12 23:40:07 +00:00
}
}
2023-04-12 21:27:01 +00:00
"w" => return self.write_command(command, args),
"wq" => {
self.write_command(command, args)?;
self.quit = true;
}
2023-04-12 21:39:46 +00:00
command => match command.parse::<usize>() {
Err(_) => return Err(format!("{}: Unrecognized command.", command)),
Ok(line) if line >= self.buffer.as_ref().len_lines() => {
return Err(format!("Line {} is out-of-bounds", line))
}
Ok(line) => {
self.cursor.line = line;
self.scroll_to_cursor();
}
},
2023-04-12 05:22:16 +00:00
}
2023-04-12 21:27:01 +00:00
Ok(())
}
2023-04-11 19:56:43 +00:00
fn move_cursor(&mut self, direction: Direction) {
let wrap = self.config.move_linewrap;
self.buffer.move_cursor(&mut self.cursor, direction, wrap);
2023-04-12 21:39:46 +00:00
self.scroll_to_cursor();
}
2023-04-11 21:29:52 +00:00
2023-04-12 21:39:46 +00:00
fn scroll_to_cursor(&mut self) {
2023-04-11 21:29:52 +00:00
if self.cursor.column < self.scroll.column + 3 {
self.scroll.column = self.cursor.column.saturating_sub(3);
} else if self.cursor.column + 6 >= self.scroll.column + self.size.0 {
self.scroll.column = self.cursor.column.saturating_sub(self.size.0 - 6);
}
if self.cursor.line < self.scroll.line {
self.scroll.line = self.cursor.line;
} else if self.cursor.line + 3 >= self.scroll.line + self.size.1 {
self.scroll.line = self.cursor.line + 3 - self.size.1;
}
2023-04-11 19:56:43 +00:00
}
}
2023-04-11 20:04:29 +00:00
fn screen_main(stdout: &mut Stdout, mut state: State) -> Result<()> {
2023-04-12 21:13:20 +00:00
let poll_timeout = std::time::Duration::from_millis(100);
2023-04-11 19:56:43 +00:00
while !state.quit {
2023-04-11 20:04:29 +00:00
state.draw(stdout)?;
2023-04-12 21:13:20 +00:00
if let true = crossterm::event::poll(poll_timeout)? {
let event = crossterm::event::read()?;
state.on_event(event);
}
2023-04-11 19:56:43 +00:00
}
Ok(())
2023-04-11 17:40:10 +00:00
}
2023-04-11 20:04:29 +00:00
fn main() -> Result<()> {
2023-04-11 22:12:56 +00:00
let argv = args().collect::<Vec<String>>();
2023-04-11 22:26:02 +00:00
let mut buf = Vec::new();
2023-04-12 05:22:16 +00:00
let file_name: Option<OsString>;
2023-04-11 22:12:56 +00:00
2023-04-11 22:49:11 +00:00
match argv.get(1).map(|s| s.as_str()) {
Some("-") | None => {
2023-04-12 05:22:16 +00:00
file_name = None;
let stdin = 0; // get stdin as a file descriptor
if unsafe { libc::isatty(stdin) } == 0 {
unsafe { File::from_raw_fd(stdin) }
2023-04-12 21:16:07 +00:00
} else {
File::open("/dev/null").unwrap()
}
}
2023-04-11 22:26:02 +00:00
Some(path) => {
2023-04-12 05:22:16 +00:00
let input_file = Path::new(path);
2023-04-12 21:16:07 +00:00
file_name = Some(OsString::from(input_file.clone().display().to_string()));
2023-04-12 05:22:16 +00:00
File::open(input_file).unwrap_or_else(|_| {
let mut err = String::new();
if !input_file.exists() {
err = "No such file or directory.".to_string();
} else if input_file.is_dir() {
err = "Is a directory.".to_string();
}
eprintln!("{}: {}: {}", argv[0], path, err);
2023-04-11 22:49:11 +00:00
exit(EX_UNAVAILABLE);
2023-04-11 22:26:02 +00:00
})
2023-04-12 21:16:07 +00:00
}
}
.read_to_end(&mut buf)
.unwrap();
2023-04-11 22:49:11 +00:00
let text = String::from_utf8(buf).unwrap_or_else(|_| {
eprintln!(
2023-04-12 03:55:33 +00:00
"{}: {}: File contents are not valid UTF-8.",
argv[0], argv[1]
2023-04-11 22:49:11 +00:00
);
exit(EX_DATAERR);
});
2023-04-11 22:12:56 +00:00
2023-04-12 05:22:16 +00:00
let state = State::from_str(file_name, &text)?;
2023-04-11 20:04:29 +00:00
let mut stdout = stdout();
terminal::enable_raw_mode()?;
2023-04-12 21:50:14 +00:00
stdout.queue(terminal::EnterAlternateScreen)?;
2023-04-11 20:04:29 +00:00
let result = screen_main(&mut stdout, state);
2023-04-12 21:50:14 +00:00
stdout.queue(terminal::LeaveAlternateScreen)?;
2023-04-11 20:04:29 +00:00
terminal::disable_raw_mode()?;
result
}