breed/src/main.rs

483 lines
15 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-11 22:26:02 +00:00
fs::File,
2023-04-11 22:12:56 +00:00
io::{
Read,
stdout,
Stdout,
Write,
},
2023-04-11 22:26:02 +00:00
os::fd::FromRawFd,
2023-04-11 22:12:56 +00:00
};
2023-04-11 19:56:43 +00:00
2023-04-11 20:18:16 +00:00
use crossterm::{
cursor,
event::{read, Event, KeyCode, KeyEvent},
terminal, ExecutableCommand, Result,
2023-04-11 20:18:16 +00:00
};
2023-04-11 19:56:43 +00:00
use ropey::Rope;
2023-04-11 22:12:56 +00:00
use yacexits::{ exit, EX_DATAERR, EX_UNAVAILABLE };
2023-04-11 19:56:43 +00:00
struct Buffer {
pub text: Rope,
}
impl Buffer {
pub fn from_str(text: &str) -> Self {
Self {
text: Rope::from_str(text),
}
}
pub fn draw(
&self,
cols: u16,
rows: u16,
scroll: Cursor,
out: &mut (impl ExecutableCommand + Write),
) -> Result<u32> {
2023-04-11 19:56:43 +00:00
let lr_width = self.text.len_lines().ilog10() + 1;
2023-04-11 20:32:07 +00:00
let gutter_width = lr_width + 1;
2023-04-11 21:29:52 +00:00
let text_width = cols as usize - gutter_width as usize;
2023-04-11 19:56:43 +00:00
out.execute(cursor::MoveTo(0, 0))?;
2023-04-11 21:29:52 +00:00
for (row, line) in (0..rows).zip(self.text.lines_at(scroll.line)) {
2023-04-11 21:44:10 +00:00
// only the last line is empty and should be skipped
if line.len_chars() == 0 {
break;
}
2023-04-11 21:29:52 +00:00
let row = row as usize + scroll.line;
2023-04-11 19:56:43 +00:00
write!(out, "{:width$} ", row, width = lr_width as usize)?;
2023-04-11 21:29:52 +00:00
let lhs = scroll.column;
2023-04-11 20:32:07 +00:00
let width = line.len_chars().saturating_sub(1); // lop off whitespace
2023-04-11 21:29:52 +00:00
if lhs < width {
let window = text_width.min(width - lhs);
let rhs = lhs + window;
write!(out, "{}", line.slice(lhs..rhs))?;
}
2023-04-11 19:56:43 +00:00
out.execute(cursor::MoveToNextLine(1))?;
}
2023-04-11 20:32:07 +00:00
Ok(gutter_width)
2023-04-11 19:56:43 +00:00
}
pub fn clamped_cursor(&self, cursor: Cursor) -> Cursor {
Cursor {
line: cursor.line,
column: cursor
.column
.min(self.text.line(cursor.line).len_chars() - 1),
}
}
pub fn cursor_to_char(&self, cursor: Cursor) -> usize {
let cursor = self.clamped_cursor(cursor);
self.text.line_to_char(cursor.line) + cursor.column
}
pub fn move_cursor(&self, cursor: &mut Cursor, direction: Direction, enable_linewrap: bool) {
*cursor = self.clamped_cursor(*cursor);
match direction {
Direction::Left => {
if cursor.column > 0 {
cursor.column -= 1;
} else if enable_linewrap && cursor.line > 0 {
cursor.line -= 1;
let line = self.text.line(cursor.line);
cursor.column = line.len_chars() - 1;
}
}
Direction::Down => {
2023-04-11 21:44:10 +00:00
if cursor.line + 2 < self.text.len_lines() {
2023-04-11 19:56:43 +00:00
cursor.line += 1;
}
}
Direction::Up => {
if cursor.line > 0 {
cursor.line -= 1;
}
}
Direction::Right => {
let line = self.text.line(cursor.line);
if cursor.column + 2 > line.len_chars() {
2023-04-11 21:44:10 +00:00
if enable_linewrap && cursor.line + 2 < self.text.len_lines() {
2023-04-11 19:56:43 +00:00
cursor.line += 1;
cursor.column = 0;
}
} else {
cursor.column += 1;
}
}
}
}
}
#[derive(Copy, Clone, Debug, Default)]
struct Cursor {
pub column: usize,
pub line: usize,
}
#[derive(Clone, Debug, Default)]
struct NormalState {
pub error: Option<String>,
}
#[derive(Clone, Debug, Default)]
struct CommandState {
pub buf: String,
pub cursor: usize,
}
2023-04-11 21:28:42 +00:00
#[derive(Copy, Clone, Debug)]
struct InsertState {
append: bool,
}
#[derive(Clone, Debug)]
2023-04-11 19:56:43 +00:00
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)]
enum Direction {
Left,
Down,
Up,
Right,
}
struct State {
pub buffer: Buffer,
pub cursor: Cursor,
2023-04-11 21:29:52 +00:00
pub scroll: Cursor,
pub size: (usize, usize),
2023-04-11 19:56:43 +00:00
pub mode: Mode,
pub quit: bool,
}
impl State {
2023-04-11 21:29:52 +00:00
pub fn from_str(text: &str) -> Result<Self> {
let (cols, rows) = terminal::size()?;
Ok(Self {
2023-04-11 19:56:43 +00:00
buffer: Buffer::from_str(text),
cursor: Cursor::default(),
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
mode: Mode::default(),
quit: false,
2023-04-11 21:29:52 +00:00
})
2023-04-11 19:56:43 +00:00
}
pub fn draw(&self, out: &mut impl Write) -> Result<()> {
// begin update
let (cols, rows) = terminal::size()?;
2023-04-11 19:56:43 +00:00
out.execute(terminal::BeginSynchronizedUpdate)?;
out.execute(terminal::Clear(terminal::ClearType::All))?;
// 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;
out.execute(cursor::MoveTo(0, row))?;
write!(out, ":{}", buf)?;
set_cursor_pos = Some((col, row));
show_status_bar = true;
}
Mode::Normal(NormalState { error: Some(error) }) => {
out.execute(cursor::MoveTo(0, rows - 1))?;
write!(out, "{}", error)?;
show_status_bar = true;
}
_ => {}
}
// draw buffer
let buffer_rows = if show_status_bar { rows - 1 } else { rows };
let lr_width = self.buffer.draw(cols, buffer_rows, self.scroll, 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)
});
out.execute(cursor::MoveTo(cursor_pos.0, cursor_pos.1))?;
2023-04-11 19:56:43 +00:00
out.execute(self.mode.cursor_style())?;
// finish update
2023-04-11 19:56:43 +00:00
out.execute(terminal::EndSynchronizedUpdate)?;
Ok(())
}
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-11 19:56:43 +00:00
match event {
Event::Key(KeyEvent { code, .. }) => match code {
KeyCode::Char('i') => {
let state = InsertState { append: false };
2023-04-11 21:28:42 +00:00
self.mode = Mode::Insert(state);
2023-04-11 19:56:43 +00:00
}
2023-04-11 20:53:02 +00:00
KeyCode::Char('a') => {
let state = InsertState { append: true };
2023-04-11 20:53:02 +00:00
self.move_cursor(Direction::Right);
2023-04-11 21:28:42 +00:00
self.mode = Mode::Insert(state);
2023-04-11 20:53:02 +00:00
}
2023-04-11 19:56:43 +00:00
KeyCode::Char(':') => {
self.mode = Mode::Command(Default::default());
2023-04-11 19:56:43 +00:00
}
KeyCode::Char('v') => {
self.mode = Mode::Visual;
}
2023-04-11 21:29:52 +00:00
code => self.on_any_key(code),
2023-04-11 19:56:43 +00:00
},
2023-04-11 21:29:52 +00:00
event => self.on_any_event(event),
2023-04-11 19:56:43 +00:00
}
match self.mode {
Mode::Normal(_) => self.mode = Mode::Normal(state),
_ => {}
}
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;
}
code => return self.on_any_key(code),
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 {
Event::Key(KeyEvent { code, .. }) => match code {
KeyCode::Esc => {
self.mode = Mode::default();
2023-04-11 19:56:43 +00:00
}
2023-04-11 21:29:52 +00:00
code => self.on_any_key(code),
2023-04-11 19:56:43 +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-11 21:28:42 +00:00
fn on_insert_event(&mut self, event: Event, state: InsertState) {
2023-04-11 19:56:43 +00:00
match event {
Event::Key(KeyEvent { code, .. }) => match code {
KeyCode::Char(c) => {
let index = self.buffer.cursor_to_char(self.cursor);
self.buffer.text.insert_char(index, c);
self.move_cursor(Direction::Right)
}
KeyCode::Backspace => {
self.move_cursor(Direction::Left);
let index = self.buffer.cursor_to_char(self.cursor);
self.buffer.text.remove(index..=index);
}
KeyCode::Delete => {
let index = self.buffer.cursor_to_char(self.cursor);
self.buffer.text.remove(index..=index);
}
KeyCode::Enter => {
let index = self.buffer.cursor_to_char(self.cursor);
self.buffer.text.insert_char(index, '\n');
self.cursor.line += 1;
self.cursor.column = 0;
}
KeyCode::Esc => {
2023-04-11 21:28:42 +00:00
if state.append {
self.move_cursor(Direction::Left);
}
self.mode = Mode::default();
2023-04-11 19:56:43 +00:00
}
2023-04-11 21:29:52 +00:00
code => self.on_any_key(code),
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);
}
Event::Key(KeyEvent { code, .. }) => self.on_any_key(code),
2023-04-11 19:56:43 +00:00
_ => {}
}
}
2023-04-11 21:29:52 +00:00
fn on_any_key(&mut self, code: KeyCode) {
2023-04-11 19:56:43 +00:00
match code {
KeyCode::Esc => self.mode = Mode::default(),
2023-04-11 19:56:43 +00:00
KeyCode::Char('h') | KeyCode::Left => self.move_cursor(Direction::Left),
KeyCode::Char('j') | KeyCode::Down => self.move_cursor(Direction::Down),
KeyCode::Char('k') | KeyCode::Up => self.move_cursor(Direction::Up),
KeyCode::Char('l') | KeyCode::Right => self.move_cursor(Direction::Right),
_ => {}
}
}
fn execute_command(&mut self, command: &str) -> std::result::Result<(), String> {
match command {
"q" => self.quit = true,
command => return Err(format!("unrecognized command {:?}", command)),
}
Ok(())
}
2023-04-11 19:56:43 +00:00
fn move_cursor(&mut self, direction: Direction) {
self.buffer.move_cursor(&mut self.cursor, direction, true);
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-11 19:56:43 +00:00
while !state.quit {
2023-04-11 20:04:29 +00:00
state.draw(stdout)?;
2023-04-11 20:53:02 +00:00
let event = read()?;
2023-04-11 19:56:43 +00:00
state.on_event(event);
}
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-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 => unsafe { File::from_raw_fd(0) }, // stdin as a file
2023-04-11 22:26:02 +00:00
Some(path) => {
2023-04-11 22:49:11 +00:00
std::fs::File::open(path).unwrap_or_else(|_| {
2023-04-11 22:26:02 +00:00
eprintln!(
2023-04-11 22:49:11 +00:00
"{}: {}: No such file or directory.",
argv[0],
argv[1]
2023-04-11 22:26:02 +00:00
);
2023-04-11 22:49:11 +00:00
exit(EX_UNAVAILABLE);
2023-04-11 22:26:02 +00:00
})
},
2023-04-11 22:49:11 +00:00
}.read_to_end(&mut buf).unwrap();
let text = String::from_utf8(buf).unwrap_or_else(|_| {
eprintln!(
2023-04-11 22:51: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
let state = State::from_str(&text)?;
2023-04-11 20:04:29 +00:00
let mut stdout = stdout();
terminal::enable_raw_mode()?;
stdout.execute(terminal::EnterAlternateScreen)?;
let result = screen_main(&mut stdout, state);
stdout.execute(terminal::LeaveAlternateScreen)?;
terminal::disable_raw_mode()?;
result
}