rearchitect into buffers, allow opening multiple files

This commit is contained in:
alice pellerin
2026-03-19 03:06:38 -05:00
parent 5aa64bd7dc
commit cb2eeee932
8 changed files with 783 additions and 715 deletions
+83 -92
View File
@@ -1,11 +1,11 @@
use std::{cmp::min, fs::File, io::Write, mem::{replace, swap}}; use std::{cmp::min, fs::File, io::Write, mem::{replace, swap}};
use ratatui::{style::Stylize, text::Span}; use ratatui::{style::Stylize, text::Span};
use crate::{BYTES_PER_LINE, app::{App, Mode, PartialAction}, edit_action::EditAction}; use crate::{BYTES_PER_LINE, app::WindowSize, buffer::{Buffer, Mode, PartialAction}, edit_action::EditAction};
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub enum Action { pub enum Action {
QuitIfSaved, CloseIfSaved,
Quit, Close,
NormalMode, NormalMode,
SelectMode, SelectMode,
@@ -60,11 +60,11 @@ pub enum Action {
Save, Save,
} }
impl App { impl Buffer {
pub fn execute(&mut self, action: Action) { pub fn execute(&mut self, action: Action, window_size: WindowSize) {
match action { match action {
Action::QuitIfSaved => self.quit_if_saved(), Action::CloseIfSaved => self.close_if_saved(),
Action::Quit => self.quit(), Action::Close => self.close(),
Action::NormalMode => self.normal_mode(), Action::NormalMode => self.normal_mode(),
Action::SelectMode => self.select_mode(), Action::SelectMode => self.select_mode(),
@@ -74,37 +74,37 @@ impl App {
Action::Replace => self.replace(), Action::Replace => self.replace(),
Action::Space => self.space(), Action::Space => self.space(),
Action::MoveByteUp => self.move_byte_up(), Action::MoveByteUp => self.move_byte_up(window_size),
Action::MoveByteDown => self.move_byte_down(), Action::MoveByteDown => self.move_byte_down(window_size),
Action::MoveByteLeft => self.move_byte_left(), Action::MoveByteLeft => self.move_byte_left(window_size),
Action::MoveByteRight => self.move_byte_right(), Action::MoveByteRight => self.move_byte_right(window_size),
Action::ExtendByteUp => self.extend_byte_up(), Action::ExtendByteUp => self.extend_byte_up(window_size),
Action::ExtendByteDown => self.extend_byte_down(), Action::ExtendByteDown => self.extend_byte_down(window_size),
Action::ExtendByteLeft => self.extend_byte_left(), Action::ExtendByteLeft => self.extend_byte_left(window_size),
Action::ExtendByteRight => self.extend_byte_right(), Action::ExtendByteRight => self.extend_byte_right(window_size),
Action::GotoLineStart => self.goto_line_start(), Action::GotoLineStart => self.goto_line_start(),
Action::GotoLineEnd => self.goto_line_end(), Action::GotoLineEnd => self.goto_line_end(),
Action::GotoFileStart => self.goto_file_start(), Action::GotoFileStart => self.goto_file_start(window_size),
Action::GotoFileEnd => self.goto_file_end(), Action::GotoFileEnd => self.goto_file_end(window_size),
Action::ScrollDown => self.scroll_down(), Action::ScrollDown => self.scroll_down(window_size),
Action::ScrollUp => self.scroll_up(), Action::ScrollUp => self.scroll_up(window_size),
Action::PageCursorHalfDown => self.page_cursor_half_down(), Action::PageCursorHalfDown => self.page_cursor_half_down(window_size),
Action::PageCursorHalfUp => self.page_cursor_half_up(), Action::PageCursorHalfUp => self.page_cursor_half_up(window_size),
Action::PageDown => self.page_down(), Action::PageDown => self.page_down(window_size),
Action::PageUp => self.page_up(), Action::PageUp => self.page_up(window_size),
Action::MoveNextWordStart => self.move_next_word_start(), Action::MoveNextWordStart => self.move_next_word_start(window_size),
Action::MoveNextWordEnd => self.move_next_word_end(), Action::MoveNextWordEnd => self.move_next_word_end(window_size),
Action::MovePreviousWordStart => self.move_previous_word_start(), Action::MovePreviousWordStart => self.move_previous_word_start(window_size),
Action::ExtendNextWordStart => self.extend_next_word_start(), Action::ExtendNextWordStart => self.extend_next_word_start(window_size),
Action::ExtendNextWordEnd => self.extend_next_word_end(), Action::ExtendNextWordEnd => self.extend_next_word_end(window_size),
Action::ExtendPreviousWordStart => self.extend_previous_word_start(), Action::ExtendPreviousWordStart => self.extend_previous_word_start(window_size),
Action::CollapseSelection => self.collapse_selection(), Action::CollapseSelection => self.collapse_selection(),
@@ -120,9 +120,9 @@ impl App {
} }
} }
fn quit_if_saved(&mut self) { fn close_if_saved(&mut self) {
if self.all_changes_saved() { if self.all_changes_saved() {
self.quit(); self.close();
} else { } else {
self.alert_message = Span::from( self.alert_message = Span::from(
"there are unsaved changes, use Q to override" "there are unsaved changes, use Q to override"
@@ -130,8 +130,8 @@ impl App {
} }
} }
const fn quit(&mut self) { const fn close(&mut self) {
self.should_quit = true; self.should_close = true;
} }
const fn normal_mode(&mut self) { const fn normal_mode(&mut self) {
@@ -160,67 +160,67 @@ impl App {
self.partial_action = Some(PartialAction::Space); self.partial_action = Some(PartialAction::Space);
} }
const fn move_byte_up(&mut self) { const fn move_byte_up(&mut self, window_size: WindowSize) {
if self.cursor.head >= BYTES_PER_LINE { if self.cursor.head >= BYTES_PER_LINE {
self.cursor.head -= BYTES_PER_LINE; self.cursor.head -= BYTES_PER_LINE;
self.cursor.collapse(); self.cursor.collapse();
self.clamp_screen_to_cursor(); self.clamp_screen_to_cursor(window_size);
} }
} }
const fn move_byte_down(&mut self) { const fn move_byte_down(&mut self, window_size: WindowSize) {
if self.max_contents_index() - self.cursor.head >= BYTES_PER_LINE { if self.max_contents_index() - self.cursor.head >= BYTES_PER_LINE {
self.cursor.head += BYTES_PER_LINE; self.cursor.head += BYTES_PER_LINE;
self.cursor.collapse(); self.cursor.collapse();
self.clamp_screen_to_cursor(); self.clamp_screen_to_cursor(window_size);
} }
} }
const fn move_byte_left(&mut self) { const fn move_byte_left(&mut self, window_size: WindowSize) {
if self.cursor.head >= 1 { if self.cursor.head >= 1 {
self.cursor.head -= 1; self.cursor.head -= 1;
self.cursor.collapse(); self.cursor.collapse();
self.clamp_screen_to_cursor(); self.clamp_screen_to_cursor(window_size);
} }
} }
const fn move_byte_right(&mut self) { const fn move_byte_right(&mut self, window_size: WindowSize) {
if self.max_contents_index() - self.cursor.head >= 1 { if self.max_contents_index() - self.cursor.head >= 1 {
self.cursor.head += 1; self.cursor.head += 1;
self.cursor.collapse(); self.cursor.collapse();
self.clamp_screen_to_cursor(); self.clamp_screen_to_cursor(window_size);
} }
} }
const fn extend_byte_up(&mut self) { const fn extend_byte_up(&mut self, window_size: WindowSize) {
if self.cursor.head >= BYTES_PER_LINE { if self.cursor.head >= BYTES_PER_LINE {
self.cursor.head -= BYTES_PER_LINE; self.cursor.head -= BYTES_PER_LINE;
self.clamp_screen_to_cursor(); self.clamp_screen_to_cursor(window_size);
} }
} }
const fn extend_byte_down(&mut self) { const fn extend_byte_down(&mut self, window_size: WindowSize) {
if self.max_contents_index() - self.cursor.head >= BYTES_PER_LINE { if self.max_contents_index() - self.cursor.head >= BYTES_PER_LINE {
self.cursor.head += BYTES_PER_LINE; self.cursor.head += BYTES_PER_LINE;
self.clamp_screen_to_cursor(); self.clamp_screen_to_cursor(window_size);
} }
} }
const fn extend_byte_left(&mut self) { const fn extend_byte_left(&mut self, window_size: WindowSize) {
if self.cursor.head >= 1 { if self.cursor.head >= 1 {
self.cursor.head -= 1; self.cursor.head -= 1;
self.clamp_screen_to_cursor(); self.clamp_screen_to_cursor(window_size);
} }
} }
const fn extend_byte_right(&mut self) { const fn extend_byte_right(&mut self, window_size: WindowSize) {
if self.max_contents_index() - self.cursor.head >= 1 { if self.max_contents_index() - self.cursor.head >= 1 {
self.cursor.head += 1; self.cursor.head += 1;
self.clamp_screen_to_cursor(); self.clamp_screen_to_cursor(window_size);
} }
} }
@@ -237,43 +237,43 @@ impl App {
self.cursor.collapse(); self.cursor.collapse();
} }
const fn goto_file_start(&mut self) { const fn goto_file_start(&mut self, window_size: WindowSize) {
self.cursor.head %= BYTES_PER_LINE; self.cursor.head %= BYTES_PER_LINE;
self.cursor.collapse(); self.cursor.collapse();
self.clamp_screen_to_cursor(); self.clamp_screen_to_cursor(window_size);
} }
const fn goto_file_end(&mut self) { const fn goto_file_end(&mut self, window_size: WindowSize) {
self.cursor.head = previous_multiple_of(BYTES_PER_LINE, self.contents.len()) + self.cursor.head = previous_multiple_of(BYTES_PER_LINE, self.contents.len()) +
(self.cursor.head % BYTES_PER_LINE); (self.cursor.head % BYTES_PER_LINE);
self.cursor.collapse(); self.cursor.collapse();
self.clamp_screen_to_cursor(); self.clamp_screen_to_cursor(window_size);
} }
fn scroll_down(&mut self) { fn scroll_down(&mut self, window_size: WindowSize) {
if self.contents.len() <= 5 * BYTES_PER_LINE { return; } if self.contents.len() <= 5 * BYTES_PER_LINE { return; }
self.scroll_position = min( self.scroll_position = min(
self.scroll_position + BYTES_PER_LINE, self.scroll_position + BYTES_PER_LINE,
self.contents.len() - (5 * BYTES_PER_LINE) self.contents.len() - (5 * BYTES_PER_LINE)
); );
self.cursor.clamp(self.scroll_position, self.screen_size()); self.cursor.clamp(self.scroll_position, window_size.visible_byte_count());
} }
fn scroll_up(&mut self) { fn scroll_up(&mut self, window_size: WindowSize) {
self.scroll_position = self.scroll_position.saturating_sub(BYTES_PER_LINE); self.scroll_position = self.scroll_position.saturating_sub(BYTES_PER_LINE);
self.cursor.clamp(self.scroll_position, self.screen_size()); self.cursor.clamp(self.scroll_position, window_size.visible_byte_count());
} }
fn page_cursor_half_down(&mut self) { fn page_cursor_half_down(&mut self, window_size: WindowSize) {
if self.contents.len() <= 5 * BYTES_PER_LINE { return; } if self.contents.len() <= 5 * BYTES_PER_LINE { return; }
let head_offset = self.cursor.head - self.scroll_position; let head_offset = self.cursor.head - self.scroll_position;
let tail_offset = self.cursor.tail - self.scroll_position; let tail_offset = self.cursor.tail - self.scroll_position;
self.scroll_position = min( self.scroll_position = min(
self.scroll_position + (self.screen_size() / 2).next_multiple_of(BYTES_PER_LINE), self.scroll_position + (window_size.visible_byte_count() / 2).next_multiple_of(BYTES_PER_LINE),
self.contents.len() - (5 * BYTES_PER_LINE) self.contents.len() - (5 * BYTES_PER_LINE)
); );
@@ -281,63 +281,63 @@ impl App {
self.cursor.tail = (self.scroll_position + tail_offset).min(self.max_contents_index()); self.cursor.tail = (self.scroll_position + tail_offset).min(self.max_contents_index());
} }
fn page_cursor_half_up(&mut self) { fn page_cursor_half_up(&mut self, window_size: WindowSize) {
let head_offset = self.cursor.head - self.scroll_position; let head_offset = self.cursor.head - self.scroll_position;
let tail_offset = self.cursor.tail - self.scroll_position; let tail_offset = self.cursor.tail - self.scroll_position;
self.scroll_position = self.scroll_position.saturating_sub( self.scroll_position = self.scroll_position.saturating_sub(
(self.screen_size() / 2).next_multiple_of(BYTES_PER_LINE) (window_size.visible_byte_count() / 2).next_multiple_of(BYTES_PER_LINE)
); );
self.cursor.head = (self.scroll_position + head_offset).min(self.max_contents_index()); self.cursor.head = (self.scroll_position + head_offset).min(self.max_contents_index());
self.cursor.tail = (self.scroll_position + tail_offset).min(self.max_contents_index()); self.cursor.tail = (self.scroll_position + tail_offset).min(self.max_contents_index());
} }
fn page_down(&mut self) { fn page_down(&mut self, window_size: WindowSize) {
if self.contents.len() <= 5 * BYTES_PER_LINE { return; } if self.contents.len() <= 5 * BYTES_PER_LINE { return; }
self.scroll_position = min( self.scroll_position = min(
self.scroll_position + self.screen_size(), self.scroll_position + window_size.visible_byte_count(),
self.contents.len() - (5 * BYTES_PER_LINE) self.contents.len() - (5 * BYTES_PER_LINE)
); );
self.cursor.clamp(self.scroll_position, self.screen_size()); self.cursor.clamp(self.scroll_position, window_size.visible_byte_count());
} }
fn page_up(&mut self) { fn page_up(&mut self, window_size: WindowSize) {
self.scroll_position = self.scroll_position.saturating_sub( self.scroll_position = self.scroll_position.saturating_sub(
self.screen_size() window_size.visible_byte_count()
); );
self.cursor.clamp(self.scroll_position, self.screen_size()); self.cursor.clamp(self.scroll_position, window_size.visible_byte_count());
} }
fn move_next_word_start(&mut self) { fn move_next_word_start(&mut self, window_size: WindowSize) {
self.cursor.move_to_next_word(self.max_contents_index()); self.cursor.move_to_next_word(self.max_contents_index());
self.clamp_screen_to_cursor(); self.clamp_screen_to_cursor(window_size);
} }
fn move_next_word_end(&mut self) { fn move_next_word_end(&mut self, window_size: WindowSize) {
self.cursor.move_to_next_end(self.max_contents_index()); self.cursor.move_to_next_end(self.max_contents_index());
self.clamp_screen_to_cursor(); self.clamp_screen_to_cursor(window_size);
} }
const fn move_previous_word_start(&mut self) { const fn move_previous_word_start(&mut self, window_size: WindowSize) {
self.cursor.move_to_previous_beginning(); self.cursor.move_to_previous_beginning();
self.clamp_screen_to_cursor(); self.clamp_screen_to_cursor(window_size);
} }
fn extend_next_word_start(&mut self) { fn extend_next_word_start(&mut self, window_size: WindowSize) {
self.cursor.extend_to_next_word(self.max_contents_index()); self.cursor.extend_to_next_word(self.max_contents_index());
self.clamp_screen_to_cursor(); self.clamp_screen_to_cursor(window_size);
} }
fn extend_next_word_end(&mut self) { fn extend_next_word_end(&mut self, window_size: WindowSize) {
self.cursor.extend_to_next_end(self.max_contents_index()); self.cursor.extend_to_next_end(self.max_contents_index());
self.clamp_screen_to_cursor(); self.clamp_screen_to_cursor(window_size);
} }
const fn extend_previous_word_start(&mut self) { const fn extend_previous_word_start(&mut self, window_size: WindowSize) {
self.cursor.extend_to_previous_beginning(); self.cursor.extend_to_previous_beginning();
self.clamp_screen_to_cursor(); self.clamp_screen_to_cursor(window_size);
} }
const fn collapse_selection(&mut self) { const fn collapse_selection(&mut self) {
@@ -443,21 +443,12 @@ impl App {
} }
// helpers // helpers
impl App { impl Buffer {
// in bytes const fn clamp_screen_to_cursor(&mut self, window_size: WindowSize) {
const fn screen_size(&self) -> usize {
self.hex_rows() * BYTES_PER_LINE
}
const fn hex_rows(&self) -> usize {
self.window_rows - self.covered_window_rows
}
const fn clamp_screen_to_cursor(&mut self) {
if self.cursor.head < self.scroll_position { if self.cursor.head < self.scroll_position {
self.scroll_position -= (self.scroll_position - self.cursor.head).next_multiple_of(BYTES_PER_LINE); self.scroll_position -= (self.scroll_position - self.cursor.head).next_multiple_of(BYTES_PER_LINE);
} else if self.cursor.head > self.scroll_position + self.screen_size() - 1 { } else if self.cursor.head > self.scroll_position + window_size.visible_byte_count() - 1 {
let screen_edge_offset_to_cursor = self.cursor.head - (self.scroll_position + self.screen_size() - 1); let screen_edge_offset_to_cursor = self.cursor.head - (self.scroll_position + window_size.visible_byte_count() - 1);
self.scroll_position += screen_edge_offset_to_cursor.next_multiple_of(BYTES_PER_LINE); self.scroll_position += screen_edge_offset_to_cursor.next_multiple_of(BYTES_PER_LINE);
} }
} }
+43 -168
View File
@@ -1,122 +1,55 @@
use std::{env, fs::File, io::Read, path::PathBuf, process::exit}; use std::{cmp::min, env, process::exit};
use crossterm::{event::{self, Event, KeyEvent}, terminal::window_size}; use crossterm::{event::{self, Event, KeyEvent}, terminal::window_size};
use ratatui::{style::Color, text::Span}; use crate::{BYTES_PER_LINE, buffer::Buffer, config::Config};
use crate::{config::Config, cursor::Cursor, edit_action::EditAction};
mod widget; mod widget;
pub struct App { pub struct App {
pub config: Config, pub config: Config,
pub file_name: String,
pub file_path: PathBuf,
pub contents: Vec<u8>, pub buffers: Vec<Buffer>,
pub current_buffer_index: usize,
pub window_rows: usize, pub window_size: WindowSize,
pub covered_window_rows: usize,
pub scroll_position: usize,
pub cursor: Cursor,
pub should_quit: bool, pub should_quit: bool,
pub mode: Mode,
pub partial_action: Option<PartialAction>,
pub partial_replace: Option<u8>,
pub edit_history: Vec<EditAction>,
// the index *after* the latest edit action
pub time_traveling: Option<usize>,
// the index *after* the last saved edit action
pub last_saved_at: Option<usize>,
pub alert_message: Span<'static>,
pub logs: Vec<String>, pub logs: Vec<String>,
} }
#[derive(Clone, Copy, Hash, PartialEq, Eq)] #[derive(Clone, Copy)]
pub enum Mode { pub struct WindowSize {
Normal, Select, Insert pub rows: usize,
} pub covered_rows: usize,
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
pub enum PartialAction {
Goto, View, Replace, Space
}
impl Mode {
pub const fn label(self) -> &'static str {
match self {
Self::Normal => " NORMAL ",
Self::Select => " SELECT ",
Self::Insert => " INSERT ",
}
}
pub const fn color(self) -> Color {
match self {
Self::Normal => Color::Blue,
Self::Select => Color::Yellow,
Self::Insert => Color::Green,
}
}
}
impl PartialAction {
pub const fn label(self) -> &'static str {
match self {
Self::Goto => "g",
Self::View => "z",
Self::Replace => "r",
Self::Space => "",
}
}
} }
impl App { impl App {
pub fn init() -> Self { pub fn new() -> Self {
let input_files: Vec<_> = env::args().skip(1).collect(); let buffers: Vec<Buffer> = env::args()
.skip(1)
.map(Into::into)
.map(Buffer::new)
.collect();
if input_files.is_empty() { if buffers.is_empty() {
println!("please provide at least one file as input"); println!("please provide at least one file as input");
exit(1); exit(1);
} }
assert!(input_files.len() == 1);
let file_path: PathBuf = input_files.first().unwrap().into();
let file = File::open(&file_path);
let mut contents = Vec::new();
file.unwrap().read_to_end(&mut contents).unwrap();
Self { Self {
config: Config::default(), config: Config::default(),
file_name: file_path.file_name().unwrap().to_str().unwrap().to_owned(),
file_path,
contents, buffers,
current_buffer_index: 0,
window_rows: window_size().unwrap().rows as usize, window_size: WindowSize {
rows: window_size().unwrap().rows as usize,
// 1 because of the status line // 1 because of the status line
covered_window_rows: 1, covered_rows: 1,
},
scroll_position: 0,
cursor: Cursor::default(),
should_quit: false, should_quit: false,
mode: Mode::Normal,
partial_action: None,
partial_replace: None,
edit_history: Vec::new(),
time_traveling: None,
last_saved_at: Some(0),
alert_message: "".into(),
logs: Vec::new(), logs: Vec::new(),
} }
} }
@@ -126,7 +59,7 @@ impl App {
#[allow(clippy::collapsible_match)] #[allow(clippy::collapsible_match)]
match event::read().unwrap() { match event::read().unwrap() {
Event::Resize(_, height) => { Event::Resize(_, height) => {
self.window_rows = height as usize; self.window_size.rows = height as usize;
} }
Event::Key(key_event) => self.handle_key(key_event), Event::Key(key_event) => self.handle_key(key_event),
// Event::Mouse(mouse_event) => { // Event::Mouse(mouse_event) => {
@@ -136,93 +69,35 @@ impl App {
} }
} }
fn handle_key(&mut self, event: KeyEvent) { fn handle_key(&mut self, key_event: KeyEvent) {
self.alert_message = "".into(); self.buffers[self.current_buffer_index]
.handle_key(key_event, &self.config, self.window_size);
if self.partial_action == Some(PartialAction::Replace) { if self.current_buffer().should_close {
if let Some(hex_character) = event.code.as_char() && self.buffers.remove(self.current_buffer_index);
let Some(nybble) = nybble_from_hex(hex_character)
{ if self.buffers.is_empty() {
if let Some(partial_replace) = self.partial_replace.take() { self.should_quit = true;
self.execute_and_add( } else {
EditAction::Replace { self.current_buffer_index = min(
cursor: self.cursor, self.current_buffer_index,
old_data: self.contents[self.cursor.range()].into(), self.buffers.len() - 1
new_byte: partial_replace << 4 | nybble
}
); );
self.partial_action = None;
} else {
self.partial_replace = Some(nybble);
}
} else {
self.partial_action = None;
self.partial_replace = None;
}
} else {
let should_reset_partial = self.partial_action.is_some();
if let Some(mode_config) = self.config.0.get(&self.mode) &&
let Some(keybinds) = mode_config.0.get(&self.partial_action) &&
let Some(action) = keybinds.0.get(&event.into())
{
self.execute(*action);
}
if should_reset_partial {
self.partial_action = None;
} }
} }
} }
pub const fn has_unsaved_changes(&self) -> bool { fn current_buffer(&self) -> &Buffer {
!self.all_changes_saved() &self.buffers[self.current_buffer_index]
}
pub const fn all_changes_saved(&self) -> bool {
if let Some(last_saved_at) = self.last_saved_at {
if let Some(time_traveling) = self.time_traveling {
last_saved_at == time_traveling
} else {
last_saved_at == self.edit_history.len()
}
} else {
false
}
}
// returns 0 if empty
pub const fn max_contents_index(&self) -> usize {
self.contents.len().saturating_sub(1)
} }
} }
fn nybble_from_hex(hex: char) -> Option<u8> { impl WindowSize {
if !hex.is_ascii() { return None; } pub const fn visible_byte_count(&self) -> usize {
self.hex_rows() * BYTES_PER_LINE
}
match hex { pub const fn hex_rows(&self) -> usize {
'0'..='9' => Some(u8::try_from(hex).unwrap() - u8::try_from('0').unwrap()), self.rows - self.covered_rows
'a'..='f' => Some(u8::try_from(hex).unwrap() - u8::try_from('a').unwrap() + 10),
'A'..='F' => Some(u8::try_from(hex).unwrap() - u8::try_from('A').unwrap() + 10),
_ => None
}
}
mod tests {
#[allow(unused_imports)]
use crate::app::nybble_from_hex;
#[test]
fn nybble_from_hex_case_doesnt_matter() {
for character in 'a'..='f' {
assert_eq!(nybble_from_hex(character), nybble_from_hex(character.to_ascii_uppercase()));
}
}
#[test]
fn nybble_from_hex_digits_are_correct() {
for (index, character) in ('0'..='9').enumerate() {
assert_eq!(nybble_from_hex(character), Some(index as u8));
}
} }
} }
+4 -442
View File
@@ -1,446 +1,8 @@
use std::{cmp::min, iter}; use ratatui::{layout::Rect, widgets::Widget};
use ratatui::{buffer::Buffer, layout::Rect, text::{Line, Text}, widgets::Widget}; use crate::app::App;
use crate::{BYTES_PER_LINE, app::App};
impl Widget for &App { impl Widget for &App {
fn render(self, area: Rect, buf: &mut Buffer) { fn render(self, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let screen_end = self.scroll_position + BYTES_PER_LINE * (area.height as usize - 1); self.current_buffer().render(area, buf);
let bytes_end = min(screen_end, self.contents.len());
let bytes_to_render = &self.contents[self.scroll_position..bytes_end];
let (chunks, remainder) = bytes_to_render
.as_chunks::<BYTES_PER_LINE>();
let hex_lines = chunks
.iter()
.zip((self.scroll_position..).step_by(BYTES_PER_LINE))
.map(|(bytes, address)| self.render_line(address, bytes));
let remainder_address = bytes_end - remainder.len();
#[allow(clippy::if_not_else)]
let remainder_line = if !remainder.is_empty() {
Some(self.render_partial_line(remainder_address, remainder))
} else {
None
};
let hex_text: Text = hex_lines
.chain(remainder_line)
.collect();
let hex_area = Rect::new(area.x, area.y, area.width, area.height - 1);
hex_text.render(hex_area, buf);
if self.contents.is_empty() {
Line::from("empty file").render(area, buf);
}
let status_line_area = Rect::new(area.x, area.bottom() - 1, area.width, 1);
self.render_status_line().render(status_line_area, buf);
self.render_extra_statuses()
.right_aligned()
.render(status_line_area, buf);
// if self.partial_action == Some(PartialAction::Space) {
// let input_field_area = Rect::new(area.x, area.bottom() - 2, area.width, 1);
// Span::from("/0F673 ")
// .on_dark_gray()
// .render(input_field_area, buf);
// }
}
}
impl App {
#[allow(mismatched_lifetime_syntaxes)]
fn render_line(&self, address: usize, bytes: &[u8; BYTES_PER_LINE]) -> Line {
iter::once(address::render_address(address))
.chain(self.render_chunks(address, bytes))
.chain(iter::once(" ".into()))
.chain(self.render_character_panel(address, bytes))
.collect()
}
#[allow(mismatched_lifetime_syntaxes)]
fn render_partial_line(&self, address: usize, bytes: &[u8]) -> Line {
iter::once(address::render_address(address))
.chain(self.render_partial_chunks(address, bytes))
.chain(iter::once(" ".into()))
.chain(self.render_character_panel(address, bytes))
.collect()
}
}
mod address {
use ratatui::{style::{Color, Style}, text::Span};
pub fn render_address(address: usize) -> Span<'static> {
Span {
style: Style::new().fg(Color::Rgb(138, 187, 195)),
content: format!("{address:08x} ").into()
}
}
}
mod hex {
use std::{borrow::Cow, mem};
use itertools::{Itertools, repeat_n};
use ratatui::{style::{Color, Style, Stylize}, text::Span};
use crate::{BYTES_PER_CHUNK, BYTES_PER_LINE, CHUNKS_PER_LINE, app::{App, Mode, PartialAction}, cardinality::HasCardinality, cursor::InCursor, custom_greys::CustomGreys, empty_span::empty_span};
impl App {
pub fn render_chunks(
&self,
address: usize,
bytes: &[u8; BYTES_PER_LINE]
) -> impl Iterator<Item=Span<'static>> {
let (chunks, remainder) = bytes.as_chunks::<BYTES_PER_CHUNK>();
assert!(remainder.is_empty(), "BYTES_PER_LINE should be a multiple of BYTES_PER_CHUNK");
#[allow(unstable_name_collisions)]
chunks
.iter()
.copied()
.zip((address..).step_by(BYTES_PER_CHUNK))
.map(|(chunk, address)| self.render_chunk(address, &chunk).collect())
.interleave(
(address..)
.step_by(BYTES_PER_CHUNK)
.take(CHUNKS_PER_LINE)
.skip(1)
.map(|address| vec![self.render_large_space_before(address)])
)
.flatten()
}
pub fn render_partial_chunks(
&self,
address: usize,
bytes: &[u8]
) -> impl Iterator<Item=Span<'static>> {
let (chunks, remainder) = bytes.as_chunks::<BYTES_PER_CHUNK>();
let remainder_address = address + chunks.len() * BYTES_PER_CHUNK;
#[allow(clippy::if_not_else)]
let remainder_chunks: Option<Vec<_>> = if !remainder.is_empty() {
Some(self.render_partial_chunk(remainder_address, remainder).collect())
} else {
None
};
let chunks_rendered = chunks.len() + remainder_chunks.iter().len();
let chunks_not_rendered = CHUNKS_PER_LINE - chunks_rendered;
let spaces_per_chunk = BYTES_PER_CHUNK - 1;
let bytes_not_rendered = BYTES_PER_LINE - bytes.len();
let padding_width = 2 * bytes_not_rendered +
spaces_per_chunk * chunks_not_rendered;
#[allow(unstable_name_collisions)]
chunks
.iter()
.copied()
.zip((address..).step_by(BYTES_PER_CHUNK))
.map(|(chunk, address)| self.render_chunk(address, &chunk).collect())
.chain(remainder_chunks)
.interleave(
(address..)
.step_by(BYTES_PER_CHUNK)
.take(CHUNKS_PER_LINE)
.skip(1)
.map(|address| vec![self.render_large_space_before(address)])
)
.flatten()
.chain(repeat_n(" ".into(), padding_width))
}
fn render_chunk(
&self,
address: usize,
bytes: &[u8; BYTES_PER_CHUNK]
) -> impl Iterator<Item=Span<'static>> {
#[allow(unstable_name_collisions)]
bytes
.iter()
.copied()
.zip(address..)
.map(|(byte, address)| self.render_byte_at(address, byte))
.interleave(
(address..)
.take(BYTES_PER_CHUNK)
.skip(1)
.map(|address| self.render_space_before(address))
)
}
fn render_partial_chunk(
&self,
address: usize,
bytes: &[u8]
) -> impl Iterator<Item=Span<'static>> {
#[allow(unstable_name_collisions)]
bytes
.iter()
.copied()
.zip(address..)
.map(|(byte, address)| self.render_byte_at(address, byte))
.interleave(
(address..)
.take(BYTES_PER_CHUNK)
.skip(1)
.map(|address| self.render_space_before(address))
)
}
fn render_byte_at(
&self,
address: usize,
byte: u8
) -> Span<'static> {
if self.partial_action == Some(PartialAction::Replace) &&
self.cursor.contains(address).is_some()
{
let replaced_byte = self.partial_replace.unwrap_or(0) << 4;
self.render_byte_without_replace_preview(address, replaced_byte)
.black()
} else {
self.render_byte_without_replace_preview(address, byte)
}
}
fn render_byte_without_replace_preview(
&self,
address: usize,
byte: u8
) -> Span<'static> {
const SPAN_FOR_BYTE: [Span; u8::CARDINALITY] = create_byte_lookup_table();
let span = SPAN_FOR_BYTE[byte as usize].clone();
let head_color = match self.mode {
Mode::Select => Color::Yellow,
_ => Color::Gray
};
match self.cursor.contains(address) {
Some(InCursor::Head) => span.bg(head_color),
Some(InCursor::Rest) => span.bg(Color::select_grey()),
None => span,
}
}
fn render_large_space_before(&self, address: usize) -> Span<'static> {
if self.cursor.contains_space_before(address) {
Span {
style: Style::new().bg(Color::select_grey()),
content: " ".into()
}
} else {
" ".into()
}
}
fn render_space_before(&self, address: usize) -> Span<'static> {
if self.cursor.contains_space_before(address) {
Span {
style: Style::new().bg(Color::select_grey()),
content: " ".into()
}
} else {
" ".into()
}
}
}
const fn create_byte_lookup_table() -> [Span<'static>; u8::CARDINALITY] {
let mut result = [const { empty_span() }; u8::CARDINALITY];
let mut index = 0;
while index < u8::CARDINALITY {
result[index].style = style_for_byte(index as u8);
mem::forget(mem::replace(&mut result[index].content, content_for_byte(index as u8)));
index += 1;
}
result
}
const fn style_for_byte(byte: u8) -> Style {
Style::new().fg(fg_for_byte(byte))
}
const fn fg_for_byte(byte: u8) -> Color {
match byte {
0x00 => Color::Rgb(0xA0, 0xA0, 0xA0), // grey
0x01..0x10 => Color::Rgb(0xFF, 0x71, 0xA9), // red
0x10..0x20 => Color::Rgb(0xFF, 0x7A, 0x78), // salmon
0x20..0x30 => Color::Rgb(0xFF, 0x81, 0x23), // red-orange
0x30..0x40 => Color::Rgb(0xF7, 0x93, 0x00), // yellow-orange
0x40..0x50 => Color::Rgb(0xE6, 0x9F, 0x00), // yellow
0x50..0x60 => Color::Rgb(0xC1, 0xB2, 0x00), // green-yellow
0x60..0x70 => Color::Rgb(0x82, 0xC6, 0x00), // lime
0x70..0x80 => Color::Rgb(0x00, 0xD5, 0x00), // green
0x80..0x90 => Color::Rgb(0x00, 0xD4, 0x59), // clover
0x90..0xA0 => Color::Rgb(0x00, 0xD0, 0x91), // teal
0xA0..0xB0 => Color::Rgb(0x00, 0xCC, 0xBB), // cyan
0xB0..0xC0 => Color::Rgb(0x00, 0xC7, 0xDE), // light blue
0xC0..0xD0 => Color::Rgb(0x00, 0xBE, 0xFF), // blue
0xD0..0xE0 => Color::Rgb(0x6C, 0xAF, 0xFF), // blurple
0xE0..0xF0 => Color::Rgb(0xB2, 0x98, 0xFF), // purple
0xF0..0xFF => Color::Rgb(0xFF, 0x4D, 0xFF), // pink
0xFF => Color::White
}
}
const fn content_for_byte(byte: u8) -> Cow<'static, str> {
Cow::Borrowed(hex_for_byte(byte))
}
const fn hex_for_byte(byte: u8) -> &'static str {
const LOOK_UP_TABLE: [&str; u8::CARDINALITY] = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F", "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF", "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF", "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF", "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF"];
LOOK_UP_TABLE[byte as usize]
}
}
mod character_panel {
use std::{borrow::Cow, mem};
use ratatui::{style::{Color, Style, Stylize}, text::Span};
use crate::{app::App, cardinality::HasCardinality, cursor::InCursor, custom_greys::CustomGreys, empty_span::empty_span};
impl App {
pub fn render_character_panel(
&self,
address: usize,
bytes: &[u8]
) -> impl Iterator<Item=Span<'static>> {
bytes
.iter()
.copied()
.zip(address..)
.map(|(byte, address)| self.render_character_at(address, byte))
}
fn render_character_at(
&self,
address: usize,
byte: u8
) -> Span<'static> {
const SPAN_FOR_BYTE: [Span; u8::CARDINALITY] = create_character_lookup_table();
let span = SPAN_FOR_BYTE[byte as usize].clone();
match self.cursor.contains(address) {
Some(InCursor::Head) => span.bg(Color::select_grey()),
Some(InCursor::Rest) => span.on_dark_gray(),
None => span,
}
}
}
const fn create_character_lookup_table() -> [Span<'static>; u8::CARDINALITY] {
let mut result = [const { empty_span() }; u8::CARDINALITY];
let mut index = 0;
while index < u8::CARDINALITY {
result[index].style = style_for_character(index as u8);
mem::forget(mem::replace(
&mut result[index].content,
content_for_character(index as u8)
));
index += 1;
}
result
}
const fn style_for_character(byte: u8) -> Style {
Style::new().fg(fg_for_character(byte))
}
const fn fg_for_character(byte: u8) -> Color {
match byte {
b'\0' => Color::Rgb(0xA0, 0xA0, 0xA0), // grey
b'\t' | b'\n' | b'\r' | b' ' => Color::Red,
_ if byte.is_ascii_graphic() => Color::Red,
_ if byte.is_ascii() => Color::Green,
0xFF => Color::White,
_ => Color::Yellow,
}
}
const fn content_for_character(byte: u8) -> Cow<'static, str> {
Cow::Borrowed(character_for_byte(byte))
}
const fn character_for_byte(byte: u8) -> &'static str {
const LOOK_UP_TABLE: [&str; u8::CARDINALITY] = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", " ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", "=", ">", "?", "@", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "[", "\\", "]", "^", "_", "`", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "{", "|", "}", "~", "", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", ""];
LOOK_UP_TABLE[byte as usize]
}
}
mod status_line {
use crate::{app::App, custom_greys::CustomGreys};
use ratatui::{style::{Color, Stylize}, text::{Line, Span, Text}};
impl App {
pub fn render_status_line(&self) -> Text<'_> {
Text::from(
Line::from_iter([
self.render_mode(),
" ".into(),
self.render_file_name(),
self.modified_indicator(),
" ".into(),
self.alert_message.clone()
])
)
.bg(Color::ui_grey())
}
fn render_mode(&self) -> Span<'static> {
Span::from(self.mode.label())
.black()
.bg(self.mode.color())
}
fn render_file_name(&self) -> Span<'_> {
Span::from(&self.file_name)
}
fn modified_indicator(&self) -> Span<'static> {
if self.has_unsaved_changes() {
" [+]".into()
} else {
"".into()
}
}
}
}
mod extra_statuses {
use crate::app::App;
use ratatui::text::Line;
impl App {
pub fn render_extra_statuses(&self) -> Line<'_> {
let partial_action = self.partial_action
.as_ref()
.map_or("", |partial_action| partial_action.label());
if self.contents.is_empty() {
format!("{partial_action} ").into()
} else {
#[allow(clippy::cast_precision_loss)]
let percentage = self.cursor.head as f64 / self.max_contents_index() as f64 * 100.0;
format!("{partial_action} {percentage:.0}% ").into()
}
}
} }
} }
+194
View File
@@ -0,0 +1,194 @@
use std::{fs::File, io::Read, path::PathBuf};
use crossterm::event::KeyEvent;
use ratatui::{style::Color, text::Span};
use crate::{app::WindowSize, config::Config, cursor::Cursor, edit_action::EditAction};
mod widget;
pub struct Buffer {
pub file_name: String,
pub file_path: PathBuf,
pub contents: Vec<u8>,
pub scroll_position: usize,
pub cursor: Cursor,
pub mode: Mode,
pub partial_action: Option<PartialAction>,
pub partial_replace: Option<u8>,
pub alert_message: Span<'static>,
pub edit_history: Vec<EditAction>,
// the index *after* the latest edit action
pub time_traveling: Option<usize>,
// the index *after* the last saved edit action
pub last_saved_at: Option<usize>,
pub should_close: bool,
}
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
pub enum Mode {
Normal, Select, Insert
}
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
pub enum PartialAction {
Goto, View, Replace, Space
}
impl Mode {
pub const fn label(self) -> &'static str {
match self {
Self::Normal => " NORMAL ",
Self::Select => " SELECT ",
Self::Insert => " INSERT ",
}
}
pub const fn color(self) -> Color {
match self {
Self::Normal => Color::Blue,
Self::Select => Color::Yellow,
Self::Insert => Color::Green,
}
}
}
impl PartialAction {
pub const fn label(self) -> &'static str {
match self {
Self::Goto => "g",
Self::View => "z",
Self::Replace => "r",
Self::Space => "",
}
}
}
impl Buffer {
pub fn new(file_path: PathBuf) -> Self {
let file = File::open(&file_path);
let mut contents = Vec::new();
file.unwrap().read_to_end(&mut contents).unwrap();
Self {
file_name: file_path.file_name().unwrap().to_str().unwrap().to_owned(),
file_path,
contents,
scroll_position: 0,
cursor: Cursor::default(),
mode: Mode::Normal,
partial_action: None,
partial_replace: None,
alert_message: "".into(),
edit_history: Vec::new(),
time_traveling: None,
last_saved_at: Some(0),
should_close: false,
}
}
pub fn handle_key(
&mut self,
event: KeyEvent,
config: &Config,
window_size: WindowSize
) {
self.alert_message = "".into();
if self.partial_action == Some(PartialAction::Replace) {
if let Some(hex_character) = event.code.as_char() &&
let Some(nybble) = nybble_from_hex(hex_character)
{
if let Some(partial_replace) = self.partial_replace.take() {
self.execute_and_add(
EditAction::Replace {
cursor: self.cursor,
old_data: self.contents[self.cursor.range()].into(),
new_byte: partial_replace << 4 | nybble
}
);
self.partial_action = None;
} else {
self.partial_replace = Some(nybble);
}
} else {
self.partial_action = None;
self.partial_replace = None;
}
} else {
let should_reset_partial = self.partial_action.is_some();
if let Some(mode_config) = config.0.get(&self.mode) &&
let Some(keybinds) = mode_config.0.get(&self.partial_action) &&
let Some(action) = keybinds.0.get(&event.into())
{
self.execute(*action, window_size);
}
if should_reset_partial {
self.partial_action = None;
}
}
}
pub const fn has_unsaved_changes(&self) -> bool {
!self.all_changes_saved()
}
pub const fn all_changes_saved(&self) -> bool {
if let Some(last_saved_at) = self.last_saved_at {
if let Some(time_traveling) = self.time_traveling {
last_saved_at == time_traveling
} else {
last_saved_at == self.edit_history.len()
}
} else {
false
}
}
// returns 0 if empty
pub const fn max_contents_index(&self) -> usize {
self.contents.len().saturating_sub(1)
}
}
fn nybble_from_hex(hex: char) -> Option<u8> {
if !hex.is_ascii() { return None; }
match hex {
'0'..='9' => Some(u8::try_from(hex).unwrap() - u8::try_from('0').unwrap()),
'a'..='f' => Some(u8::try_from(hex).unwrap() - u8::try_from('a').unwrap() + 10),
'A'..='F' => Some(u8::try_from(hex).unwrap() - u8::try_from('A').unwrap() + 10),
_ => None
}
}
mod tests {
#[allow(unused_imports)]
use crate::buffer::nybble_from_hex;
#[test]
fn nybble_from_hex_case_doesnt_matter() {
for character in 'a'..='f' {
assert_eq!(nybble_from_hex(character), nybble_from_hex(character.to_ascii_uppercase()));
}
}
#[test]
fn nybble_from_hex_digits_are_correct() {
for (index, character) in ('0'..='9').enumerate() {
assert_eq!(nybble_from_hex(character), Some(index as u8));
}
}
}
+445
View File
@@ -0,0 +1,445 @@
use std::{cmp::min, iter};
use ratatui::{layout::Rect, text::{Line, Text}, widgets::Widget};
use crate::{BYTES_PER_LINE, buffer::Buffer};
impl Widget for &Buffer {
fn render(self, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let screen_end = self.scroll_position + BYTES_PER_LINE * (area.height as usize - 1);
let bytes_end = min(screen_end, self.contents.len());
let bytes_to_render = &self.contents[self.scroll_position..bytes_end];
let (chunks, remainder) = bytes_to_render
.as_chunks::<BYTES_PER_LINE>();
let hex_lines = chunks
.iter()
.zip((self.scroll_position..).step_by(BYTES_PER_LINE))
.map(|(bytes, address)| self.render_line(address, bytes));
let remainder_address = bytes_end - remainder.len();
#[allow(clippy::if_not_else)]
let remainder_line = if !remainder.is_empty() {
Some(self.render_partial_line(remainder_address, remainder))
} else {
None
};
let hex_text: Text = hex_lines
.chain(remainder_line)
.collect();
let hex_area = Rect::new(area.x, area.y, area.width, area.height - 1);
hex_text.render(hex_area, buf);
if self.contents.is_empty() {
Line::from("empty file").render(area, buf);
}
let status_line_area = Rect::new(area.x, area.bottom() - 1, area.width, 1);
self.render_status_line().render(status_line_area, buf);
self.render_extra_statuses()
.right_aligned()
.render(status_line_area, buf);
// if self.partial_action == Some(PartialAction::Space) {
// let input_field_area = Rect::new(area.x, area.bottom() - 2, area.width, 1);
// Span::from("/0F673 ")
// .on_dark_gray()
// .render(input_field_area, buf);
// }
}
}
impl Buffer {
#[allow(mismatched_lifetime_syntaxes)]
fn render_line(&self, address: usize, bytes: &[u8; BYTES_PER_LINE]) -> Line {
iter::once(address::render_address(address))
.chain(self.render_chunks(address, bytes))
.chain(iter::once(" ".into()))
.chain(self.render_character_panel(address, bytes))
.collect()
}
#[allow(mismatched_lifetime_syntaxes)]
fn render_partial_line(&self, address: usize, bytes: &[u8]) -> Line {
iter::once(address::render_address(address))
.chain(self.render_partial_chunks(address, bytes))
.chain(iter::once(" ".into()))
.chain(self.render_character_panel(address, bytes))
.collect()
}
}
mod address {
use ratatui::{style::{Color, Style}, text::Span};
pub fn render_address(address: usize) -> Span<'static> {
Span {
style: Style::new().fg(Color::Rgb(138, 187, 195)),
content: format!("{address:08x} ").into()
}
}
}
mod hex {
use std::{borrow::Cow, mem};
use itertools::{Itertools, repeat_n};
use ratatui::{style::{Color, Style, Stylize}, text::Span};
use crate::{BYTES_PER_CHUNK, BYTES_PER_LINE, CHUNKS_PER_LINE, buffer::{Buffer, Mode, PartialAction}, cardinality::HasCardinality, cursor::InCursor, custom_greys::CustomGreys, empty_span::empty_span};
impl Buffer {
pub fn render_chunks(
&self,
address: usize,
bytes: &[u8; BYTES_PER_LINE]
) -> impl Iterator<Item=Span<'static>> {
let (chunks, remainder) = bytes.as_chunks::<BYTES_PER_CHUNK>();
assert!(remainder.is_empty(), "BYTES_PER_LINE should be a multiple of BYTES_PER_CHUNK");
#[allow(unstable_name_collisions)]
chunks
.iter()
.copied()
.zip((address..).step_by(BYTES_PER_CHUNK))
.map(|(chunk, address)| self.render_chunk(address, &chunk).collect())
.interleave(
(address..)
.step_by(BYTES_PER_CHUNK)
.take(CHUNKS_PER_LINE)
.skip(1)
.map(|address| vec![self.render_large_space_before(address)])
)
.flatten()
}
pub fn render_partial_chunks(
&self,
address: usize,
bytes: &[u8]
) -> impl Iterator<Item=Span<'static>> {
let (chunks, remainder) = bytes.as_chunks::<BYTES_PER_CHUNK>();
let remainder_address = address + chunks.len() * BYTES_PER_CHUNK;
#[allow(clippy::if_not_else)]
let remainder_chunks: Option<Vec<_>> = if !remainder.is_empty() {
Some(self.render_partial_chunk(remainder_address, remainder).collect())
} else {
None
};
let chunks_rendered = chunks.len() + remainder_chunks.iter().len();
let chunks_not_rendered = CHUNKS_PER_LINE - chunks_rendered;
let spaces_per_chunk = BYTES_PER_CHUNK - 1;
let bytes_not_rendered = BYTES_PER_LINE - bytes.len();
let padding_width = 2 * bytes_not_rendered +
spaces_per_chunk * chunks_not_rendered;
#[allow(unstable_name_collisions)]
chunks
.iter()
.copied()
.zip((address..).step_by(BYTES_PER_CHUNK))
.map(|(chunk, address)| self.render_chunk(address, &chunk).collect())
.chain(remainder_chunks)
.interleave(
(address..)
.step_by(BYTES_PER_CHUNK)
.take(CHUNKS_PER_LINE)
.skip(1)
.map(|address| vec![self.render_large_space_before(address)])
)
.flatten()
.chain(repeat_n(" ".into(), padding_width))
}
fn render_chunk(
&self,
address: usize,
bytes: &[u8; BYTES_PER_CHUNK]
) -> impl Iterator<Item=Span<'static>> {
#[allow(unstable_name_collisions)]
bytes
.iter()
.copied()
.zip(address..)
.map(|(byte, address)| self.render_byte_at(address, byte))
.interleave(
(address..)
.take(BYTES_PER_CHUNK)
.skip(1)
.map(|address| self.render_space_before(address))
)
}
fn render_partial_chunk(
&self,
address: usize,
bytes: &[u8]
) -> impl Iterator<Item=Span<'static>> {
#[allow(unstable_name_collisions)]
bytes
.iter()
.copied()
.zip(address..)
.map(|(byte, address)| self.render_byte_at(address, byte))
.interleave(
(address..)
.take(BYTES_PER_CHUNK)
.skip(1)
.map(|address| self.render_space_before(address))
)
}
fn render_byte_at(
&self,
address: usize,
byte: u8
) -> Span<'static> {
if self.partial_action == Some(PartialAction::Replace) &&
self.cursor.contains(address).is_some()
{
let replaced_byte = self.partial_replace.unwrap_or(0) << 4;
self.render_byte_without_replace_preview(address, replaced_byte)
.black()
} else {
self.render_byte_without_replace_preview(address, byte)
}
}
fn render_byte_without_replace_preview(
&self,
address: usize,
byte: u8
) -> Span<'static> {
const SPAN_FOR_BYTE: [Span; u8::CARDINALITY] = create_byte_lookup_table();
let span = SPAN_FOR_BYTE[byte as usize].clone();
let head_color = match self.mode {
Mode::Select => Color::Yellow,
_ => Color::Gray
};
match self.cursor.contains(address) {
Some(InCursor::Head) => span.bg(head_color),
Some(InCursor::Rest) => span.bg(Color::select_grey()),
None => span,
}
}
fn render_large_space_before(&self, address: usize) -> Span<'static> {
if self.cursor.contains_space_before(address) {
Span {
style: Style::new().bg(Color::select_grey()),
content: " ".into()
}
} else {
" ".into()
}
}
fn render_space_before(&self, address: usize) -> Span<'static> {
if self.cursor.contains_space_before(address) {
Span {
style: Style::new().bg(Color::select_grey()),
content: " ".into()
}
} else {
" ".into()
}
}
}
const fn create_byte_lookup_table() -> [Span<'static>; u8::CARDINALITY] {
let mut result = [const { empty_span() }; u8::CARDINALITY];
let mut index = 0;
while index < u8::CARDINALITY {
result[index].style = style_for_byte(index as u8);
mem::forget(mem::replace(&mut result[index].content, content_for_byte(index as u8)));
index += 1;
}
result
}
const fn style_for_byte(byte: u8) -> Style {
Style::new().fg(fg_for_byte(byte))
}
const fn fg_for_byte(byte: u8) -> Color {
match byte {
0x00 => Color::Rgb(0xA0, 0xA0, 0xA0), // grey
0x01..0x10 => Color::Rgb(0xFF, 0x71, 0xA9), // red
0x10..0x20 => Color::Rgb(0xFF, 0x7A, 0x78), // salmon
0x20..0x30 => Color::Rgb(0xFF, 0x81, 0x23), // red-orange
0x30..0x40 => Color::Rgb(0xF7, 0x93, 0x00), // yellow-orange
0x40..0x50 => Color::Rgb(0xE6, 0x9F, 0x00), // yellow
0x50..0x60 => Color::Rgb(0xC1, 0xB2, 0x00), // green-yellow
0x60..0x70 => Color::Rgb(0x82, 0xC6, 0x00), // lime
0x70..0x80 => Color::Rgb(0x00, 0xD5, 0x00), // green
0x80..0x90 => Color::Rgb(0x00, 0xD4, 0x59), // clover
0x90..0xA0 => Color::Rgb(0x00, 0xD0, 0x91), // teal
0xA0..0xB0 => Color::Rgb(0x00, 0xCC, 0xBB), // cyan
0xB0..0xC0 => Color::Rgb(0x00, 0xC7, 0xDE), // light blue
0xC0..0xD0 => Color::Rgb(0x00, 0xBE, 0xFF), // blue
0xD0..0xE0 => Color::Rgb(0x6C, 0xAF, 0xFF), // blurple
0xE0..0xF0 => Color::Rgb(0xB2, 0x98, 0xFF), // purple
0xF0..0xFF => Color::Rgb(0xFF, 0x4D, 0xFF), // pink
0xFF => Color::White
}
}
const fn content_for_byte(byte: u8) -> Cow<'static, str> {
Cow::Borrowed(hex_for_byte(byte))
}
const fn hex_for_byte(byte: u8) -> &'static str {
const LOOK_UP_TABLE: [&str; u8::CARDINALITY] = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F", "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF", "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF", "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF", "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF"];
LOOK_UP_TABLE[byte as usize]
}
}
mod character_panel {
use std::{borrow::Cow, mem};
use ratatui::{style::{Color, Style, Stylize}, text::Span};
use crate::{buffer::Buffer, cardinality::HasCardinality, cursor::InCursor, custom_greys::CustomGreys, empty_span::empty_span};
impl Buffer {
pub fn render_character_panel(
&self,
address: usize,
bytes: &[u8]
) -> impl Iterator<Item=Span<'static>> {
bytes
.iter()
.copied()
.zip(address..)
.map(|(byte, address)| self.render_character_at(address, byte))
}
fn render_character_at(
&self,
address: usize,
byte: u8
) -> Span<'static> {
const SPAN_FOR_BYTE: [Span; u8::CARDINALITY] = create_character_lookup_table();
let span = SPAN_FOR_BYTE[byte as usize].clone();
match self.cursor.contains(address) {
Some(InCursor::Head) => span.bg(Color::select_grey()),
Some(InCursor::Rest) => span.on_dark_gray(),
None => span,
}
}
}
const fn create_character_lookup_table() -> [Span<'static>; u8::CARDINALITY] {
let mut result = [const { empty_span() }; u8::CARDINALITY];
let mut index = 0;
while index < u8::CARDINALITY {
result[index].style = style_for_character(index as u8);
mem::forget(mem::replace(
&mut result[index].content,
content_for_character(index as u8)
));
index += 1;
}
result
}
const fn style_for_character(byte: u8) -> Style {
Style::new().fg(fg_for_character(byte))
}
const fn fg_for_character(byte: u8) -> Color {
match byte {
b'\0' => Color::Rgb(0xA0, 0xA0, 0xA0), // grey
b'\t' | b'\n' | b'\r' | b' ' => Color::Red,
_ if byte.is_ascii_graphic() => Color::Red,
_ if byte.is_ascii() => Color::Green,
0xFF => Color::White,
_ => Color::Yellow,
}
}
const fn content_for_character(byte: u8) -> Cow<'static, str> {
Cow::Borrowed(character_for_byte(byte))
}
const fn character_for_byte(byte: u8) -> &'static str {
const LOOK_UP_TABLE: [&str; u8::CARDINALITY] = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", " ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", "=", ">", "?", "@", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "[", "\\", "]", "^", "_", "`", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "{", "|", "}", "~", "", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", "×", ""];
LOOK_UP_TABLE[byte as usize]
}
}
mod status_line {
use crate::{buffer::Buffer, custom_greys::CustomGreys};
use ratatui::{style::{Color, Stylize}, text::{Line, Span, Text}};
impl Buffer {
pub fn render_status_line(&self) -> Text<'_> {
Text::from(
Line::from_iter([
self.render_mode(),
" ".into(),
self.render_file_name(),
self.modified_indicator(),
" ".into(),
self.alert_message.clone()
])
)
.bg(Color::ui_grey())
}
fn render_mode(&self) -> Span<'static> {
Span::from(self.mode.label())
.black()
.bg(self.mode.color())
}
fn render_file_name(&self) -> Span<'_> {
Span::from(&self.file_name)
}
fn modified_indicator(&self) -> Span<'static> {
if self.has_unsaved_changes() {
" [+]".into()
} else {
"".into()
}
}
}
}
mod extra_statuses {
use crate::buffer::Buffer;
use ratatui::text::Line;
impl Buffer {
pub fn render_extra_statuses(&self) -> Line<'_> {
let partial_action = self.partial_action
.as_ref()
.map_or("", |partial_action| partial_action.label());
if self.contents.is_empty() {
format!("{partial_action} ").into()
} else {
#[allow(clippy::cast_precision_loss)]
let percentage = self.cursor.head as f64 / self.max_contents_index() as f64 * 100.0;
format!("{partial_action} {percentage:.0}% ").into()
}
}
}
}
+5 -5
View File
@@ -1,6 +1,6 @@
use std::collections::HashMap; use std::collections::HashMap;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use crate::{action::Action, app::{Mode, PartialAction}}; use crate::{action::Action, buffer::{Mode, PartialAction}};
pub struct Config( pub struct Config(
pub HashMap<Mode, ModeConfig> pub HashMap<Mode, ModeConfig>
@@ -99,8 +99,8 @@ impl Default for Config {
[ [
(Mode::Normal, [ (Mode::Normal, [
(None, [ (None, [
("q".try_into().unwrap(), Action::QuitIfSaved), ("q".try_into().unwrap(), Action::CloseIfSaved),
("Q".try_into().unwrap(), Action::Quit), ("Q".try_into().unwrap(), Action::Close),
("v".try_into().unwrap(), Action::SelectMode), ("v".try_into().unwrap(), Action::SelectMode),
@@ -151,8 +151,8 @@ impl Default for Config {
].into()), ].into()),
(Mode::Select, [ (Mode::Select, [
(None, [ (None, [
("q".try_into().unwrap(), Action::QuitIfSaved), ("q".try_into().unwrap(), Action::CloseIfSaved),
("Q".try_into().unwrap(), Action::Quit), ("Q".try_into().unwrap(), Action::Close),
("v".try_into().unwrap(), Action::NormalMode), ("v".try_into().unwrap(), Action::NormalMode),
+2 -2
View File
@@ -1,5 +1,5 @@
use std::cmp::min; use std::cmp::min;
use crate::{app::App, cursor::Cursor}; use crate::{buffer::Buffer, cursor::Cursor};
#[derive(Debug)] #[derive(Debug)]
pub enum EditAction { pub enum EditAction {
@@ -25,7 +25,7 @@ pub enum EditAction {
// } // }
} }
impl App { impl Buffer {
pub fn execute_and_add(&mut self, edit_action: EditAction) { pub fn execute_and_add(&mut self, edit_action: EditAction) {
assert!(!matches!(edit_action, EditAction::Placeholder)); assert!(!matches!(edit_action, EditAction::Placeholder));
+6 -5
View File
@@ -3,22 +3,23 @@
use app::App; use app::App;
mod cardinality;
mod empty_span;
mod custom_greys;
mod app; mod app;
mod buffer;
mod config; mod config;
mod cursor; mod cursor;
mod action; mod action;
mod edit_action; mod edit_action;
mod cardinality;
mod empty_span;
mod custom_greys;
const BYTES_PER_LINE: usize = 0x10; const BYTES_PER_LINE: usize = 0x10;
const BYTES_PER_CHUNK: usize = 4; const BYTES_PER_CHUNK: usize = 4;
const CHUNKS_PER_LINE: usize = BYTES_PER_LINE / BYTES_PER_CHUNK; const CHUNKS_PER_LINE: usize = BYTES_PER_LINE / BYTES_PER_CHUNK;
// TODO: // TODO:
// - multiple buffers (tabs) // - multiple buffers (tabs)
// - add a field for 'lines not couting for hex height' to offset status/tab bar/search bar
// - search // - search
// - modifications // - modifications
// - insert/append // - insert/append
@@ -54,7 +55,7 @@ const CHUNKS_PER_LINE: usize = BYTES_PER_LINE / BYTES_PER_CHUNK;
// when AsciiChar is stabilized, use it instead of char everywhere // when AsciiChar is stabilized, use it instead of char everywhere
fn main() { fn main() {
let mut app = App::init(); let mut app = App::new();
let mut terminal = ratatui::init(); let mut terminal = ratatui::init();
while !app.should_quit { while !app.should_quit {