diff --git a/Cargo.lock b/Cargo.lock index 2472642..9917b9b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -477,6 +477,7 @@ dependencies = [ "sha1", "sha2", "windows-sys 0.59.0", + "winresource", "yaxpeax-6502", "yaxpeax-arch 0.2.8", "yaxpeax-arch 0.3.2", @@ -3125,6 +3126,15 @@ dependencies = [ "syn 2.0.118", ] +[[package]] +name = "serde_spanned" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782" +dependencies = [ + "serde_core", +] + [[package]] name = "sha1" version = "0.10.6" @@ -3505,11 +3515,26 @@ dependencies = [ "zerovec", ] +[[package]] +name = "toml" +version = "1.2.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + [[package]] name = "toml_datetime" -version = "1.1.1+spec-1.1.0" +version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" dependencies = [ "serde_core", ] @@ -3528,13 +3553,19 @@ dependencies = [ [[package]] name = "toml_parser" -version = "1.1.2+spec-1.1.0" +version = "1.1.5+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" dependencies = [ "winnow", ] +[[package]] +name = "toml_writer" +version = "1.2.0+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a" + [[package]] name = "tracing" version = "0.1.44" @@ -4447,6 +4478,16 @@ dependencies = [ "memchr", ] +[[package]] +name = "winresource" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b" +dependencies = [ + "toml", + "version_check", +] + [[package]] name = "wit-bindgen" version = "0.57.1" diff --git a/Cargo.toml b/Cargo.toml index 1cd3b66..9726e2e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -48,6 +48,9 @@ objc2 = "0.5" objc2-app-kit = "0.2" objc2-foundation = "0.2" +[target.'cfg(windows)'.build-dependencies] +winresource = "0.1" + [target.'cfg(target_os = "windows")'.dependencies] windows-sys = { version = "0.59", features = [ "Win32_Foundation", @@ -86,7 +89,7 @@ byte patterns, data-folds and file tools. """ category = "DeveloperTool" copyright = "Copyright (c) Digital Gangster Enterprises, LLC" -icon = ["assets/icon.png"] +icon = ["assets/icon.png", "assets/icon.ico"] # Debian package metadata for `cargo install cargo-deb` + `cargo deb`. [package.metadata.deb] diff --git a/README.md b/README.md index d489d53..5278df6 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # bewitched +bewitched icon + A fast, cross-platform, hacker-esque **hex editor** for files, raw disks and RAM, written in Rust with an immediate-mode (`egui`) GUI. It edits files of any size (up to 8 EB) with instant opening, unlimited undo, and a streamlined, @@ -39,6 +41,13 @@ blocks. - **Navigation**: arrows, page up/down, home/end, go-to-address (`Ctrl+G`), nibble stepping (`Ctrl+←/→`), 10 bookmarks (`Ctrl+Shift+0-9` to set, `Ctrl+0-9` to jump). +- **Vim mode** (Edit ▸ vim keybindings, remembered between launches): modal + NORMAL / VISUAL / INSERT / REPLACE editing with counts. Motions `h j k l`, + `w b e` (byte group, or 8 bytes ungrouped), `0 ^ $`, `gg G` (`nG` = row n), + `Ctrl+F/B/D/U`; edits `i a I A R`, `r` (or `r` in the text + pane), `x X dd D ~`, `u` / `Ctrl+R`; `yy p P`; `v` visual with `o d y`; + `/ ? n N` search, `:` go to address, `m0-9` / `'0-9` bookmarks; Esc returns + to NORMAL. The current mode shows in the status bar. - **Search / replace** (`Ctrl+F`) for text, Unicode (UTF-16), hex, integers (8/16/32/64) and floats (32/64), little/big-endian, forward / backward / from-start, case-insensitive, streaming (never loads the whole file). Hex diff --git a/assets/icon.ico b/assets/icon.ico new file mode 100644 index 0000000..a6acb3d Binary files /dev/null and b/assets/icon.ico differ diff --git a/assets/icon.png b/assets/icon.png index a966444..269fc22 100644 Binary files a/assets/icon.png and b/assets/icon.png differ diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..1dc7646 --- /dev/null +++ b/build.rs @@ -0,0 +1,14 @@ +// Embed the application icon into the Windows executable so Explorer, the +// taskbar pin and shortcuts show it (the runtime window icon is set separately +// in `ui::run`). +fn main() { + println!("cargo:rerun-if-changed=assets/icon.ico"); + #[cfg(windows)] + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { + let mut res = winresource::WindowsResource::new(); + res.set_icon("assets/icon.ico"); + if let Err(e) = res.compile() { + println!("cargo:warning=could not embed Windows icon: {e}"); + } + } +} diff --git a/src/ops/mod.rs b/src/ops/mod.rs index fc58aa7..b1af1db 100644 --- a/src/ops/mod.rs +++ b/src/ops/mod.rs @@ -27,6 +27,20 @@ pub mod strings; pub mod template; pub mod transform; +/// The per-user config directory (`%APPDATA%\bewitched` on Windows, +/// `$XDG_CONFIG_HOME/bewitched` or `~/.config/bewitched` elsewhere). +pub fn config_dir() -> std::path::PathBuf { + #[cfg(windows)] + let base = std::env::var("APPDATA").ok(); + #[cfg(not(windows))] + let base = std::env::var("XDG_CONFIG_HOME") + .ok() + .or_else(|| std::env::var("HOME").ok().map(|h| format!("{h}/.config"))); + let mut p = std::path::PathBuf::from(base.unwrap_or_else(|| ".".into())); + p.push("bewitched"); + p +} + /// Parse a `0x`-prefixed hex or plain decimal unsigned integer — an offset, /// length or address as typed by the user. Whitespace is trimmed. pub fn parse_u64(s: &str) -> Option { diff --git a/src/ops/script_store.rs b/src/ops/script_store.rs index 2dbe68d..a2b3a58 100644 --- a/src/ops/script_store.rs +++ b/src/ops/script_store.rs @@ -12,14 +12,7 @@ pub fn scripts_dir() -> PathBuf { if let Ok(d) = std::env::var("BEWITCHED_SCRIPT_DIR") { return PathBuf::from(d); } - #[cfg(windows)] - let base = std::env::var("APPDATA").ok(); - #[cfg(not(windows))] - let base = std::env::var("XDG_CONFIG_HOME") - .ok() - .or_else(|| std::env::var("HOME").ok().map(|h| format!("{h}/.config"))); - let mut p = PathBuf::from(base.unwrap_or_else(|| ".".into())); - p.push("bewitched"); + let mut p = super::config_dir(); p.push("scripts"); p } diff --git a/src/ui/app.rs b/src/ui/app.rs index b8cb8da..d1e284f 100644 --- a/src/ui/app.rs +++ b/src/ui/app.rs @@ -17,6 +17,7 @@ use super::charset::Charset; use super::donate; use super::hexview::{self, Layout, Pane, ViewMode}; use super::theme; +use super::vim; #[derive(Clone, Copy, PartialEq, Eq)] enum EditMode { @@ -414,6 +415,10 @@ pub struct App { regions_open: bool, about_open: bool, donate: donate::DonateUi, + /// Vim-style modal keybindings (Edit ▸ vim keybindings), persisted. + vim_enabled: bool, + vim_mode: vim::Mode, + vim: vim::Vim, } impl App { @@ -498,6 +503,9 @@ impl App { regions_open: false, about_open: false, donate: donate::DonateUi::default(), + vim_enabled: vim::load_enabled(), + vim_mode: vim::Mode::Normal, + vim: vim::Vim::default(), } } diff --git a/src/ui/app_ui.rs b/src/ui/app_ui.rs index a907828..6860f7d 100644 --- a/src/ui/app_ui.rs +++ b/src/ui/app_ui.rs @@ -14,6 +14,13 @@ const REDO_HINT: &str = "⇧⌘Z"; #[cfg(not(target_os = "macos"))] const REDO_HINT: &str = "^Y"; +/// Hover help listing the vim keybindings. +const VIM_HELP: &str = "vim-style modal editing. NORMAL mode keys are commands; counts work (e.g. 4j, 3x, 2dd).\n\ +move: h j k l · w b e (next/prev/end of byte group, 8 bytes if ungrouped) · 0 ^ $ (row start/end) · gg G (file start/end; nG = row n) · ^F ^B ^D ^U (page / half page)\n\ +edit: i a I A (insert) · R (overwrite) · r replace byte (r in text pane) · x X (delete) · dd D · ~ (flip case) · u ^R (undo/redo)\n\ +yank/paste: yy · p P · v (visual: o d y)\n\ +search: / ? n N · : go to address · m0-9 / '0-9 bookmarks · Tab switches hex/text · Esc back to NORMAL"; + impl eframe::App for App { fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { self.poll_bg(ctx); @@ -208,6 +215,11 @@ impl App { self.toggle_mode(); ui.close_menu(); } + let mut vim_on = self.vim_enabled; + if ui.checkbox(&mut vim_on, "vim keybindings").on_hover_text(VIM_HELP).changed() { + self.set_vim_enabled(vim_on); + ui.close_menu(); + } }); ui.menu_button("view", |ui| { @@ -421,8 +433,23 @@ impl App { "insert mode: typing adds bytes at the cursor, growing the file. press insert to switch to OVR", ), }; - ui.label(egui::RichText::new(mode).color(theme::GREEN).strong()) - .on_hover_text(mode_tip); + if self.vim_enabled { + let label = match (self.vim_mode, self.mode) { + (vim::Mode::Normal, _) => "NORMAL", + (vim::Mode::Visual, _) => "VISUAL", + (vim::Mode::Insert, EditMode::Insert) => "INSERT", + (vim::Mode::Insert, EditMode::Overwrite) => "REPLACE", + }; + ui.label(egui::RichText::new(label).color(theme::GREEN).strong()) + .on_hover_text(VIM_HELP); + let pending = self.vim.pending_text(); + if !pending.is_empty() { + ui.label(egui::RichText::new(pending).color(theme::AMBER)); + } + } else { + ui.label(egui::RichText::new(mode).color(theme::GREEN).strong()) + .on_hover_text(mode_tip); + } ui.separator(); if self.process_target.is_some() { ui.label( @@ -696,6 +723,9 @@ impl App { fn handle_keys(&mut self, ctx: &egui::Context) { let events = ctx.input(|i| i.events.clone()); for ev in events { + if self.vim_enabled && self.vim_event(&ev, ctx) { + continue; + } match ev { egui::Event::Key { key, @@ -841,6 +871,350 @@ impl App { self.scroll_to_cursor = true; } + // ---- vim mode ---- + + fn set_vim_enabled(&mut self, on: bool) { + self.vim_enabled = on; + self.vim.reset(); + self.vim_mode = vim::Mode::Normal; + if on { + self.mode = EditMode::Overwrite; + self.clamp_cursor_normal(); + } + vim::save_enabled(on); + self.status = if on { + "vim keybindings on — NORMAL mode (i to insert, Esc to return)".into() + } else { + "vim keybindings off".into() + }; + } + + /// NORMAL/VISUAL keep the cursor on an existing byte (no one-past-end). + fn clamp_cursor_normal(&mut self) { + let last = self.doc.len().saturating_sub(1); + if self.cursor > last { + self.cursor = last; + } + self.nibble = 0; + } + + /// Route one input event through vim mode. Returns `true` when consumed. + fn vim_event(&mut self, ev: &egui::Event, ctx: &egui::Context) -> bool { + use vim::Input; + let hex = self.pane == Pane::Hex; + + if self.vim_mode == vim::Mode::Insert { + // Typing goes to the normal editor; only Esc is ours. + if let egui::Event::Key { key: Key::Escape, pressed: true, .. } = ev { + self.vim_mode = vim::Mode::Normal; + self.mode = EditMode::Overwrite; + self.clamp_cursor_normal(); + return true; + } + return false; + } + + match ev { + egui::Event::Text(t) => { + for ch in t.chars() { + if let Some(cmd) = self.vim.feed(Input::Char(ch), self.vim_mode, hex) { + self.vim_exec(cmd, ctx); + } + // `i`, `a`, … switch to insert mode: the rest of the text is typed. + if self.vim_mode == vim::Mode::Insert { + break; + } + } + true + } + egui::Event::Key { key, pressed: true, modifiers: m, .. } => { + let input = if *key == Key::Escape { + Input::Esc + } else if m.ctrl && !m.shift && !m.alt { + match key { + Key::F => Input::Ctrl('f'), + Key::B => Input::Ctrl('b'), + Key::D => Input::Ctrl('d'), + Key::U => Input::Ctrl('u'), + Key::R => Input::Ctrl('r'), + _ => return false, + } + } else if m.any() && !m.shift_only() { + return false; // ⌘/Ctrl shortcuts keep working + } else { + // Map navigation keys onto vim motions so VISUAL extends. + let c = match key { + Key::ArrowLeft | Key::Backspace => 'h', + Key::ArrowRight => 'l', + Key::ArrowUp => 'k', + Key::ArrowDown => 'j', + Key::Home => '0', + Key::End => '$', + Key::Delete => 'x', + Key::Insert => 'i', + Key::PageDown => return self.vim_key(Input::Ctrl('f'), ctx), + Key::PageUp => return self.vim_key(Input::Ctrl('b'), ctx), + _ => return false, + }; + Input::Char(c) + }; + self.vim_key(input, ctx) + } + _ => false, + } + } + + fn vim_key(&mut self, input: vim::Input, ctx: &egui::Context) -> bool { + let hex = self.pane == Pane::Hex; + if let Some(cmd) = self.vim.feed(input, self.vim_mode, hex) { + self.vim_exec(cmd, ctx); + } + true + } + + /// Step size for `w`/`b`/`e`: the byte grouping, or 8 bytes when ungrouped. + fn vim_word(&self) -> u64 { + if self.group > 1 { + self.group as u64 + } else { + 8 + } + } + + /// Copy `[start, start+len)` into the internal clipboard (vim's register). + fn vim_yank(&mut self, start: u64, len: u64) { + self.clipboard = self.doc.read_range(start, len as usize); + self.status = format!("yanked {} bytes", self.clipboard.len()); + } + + /// Delete `[start, start+len)`, yanking it first. + fn vim_delete(&mut self, start: u64, len: u64) { + if len == 0 { + return; + } + self.vim_yank(start, len); + self.doc.delete(start, len); + self.status = format!("deleted {len} bytes"); + self.cursor = start; + self.clamp_cursor_normal(); + self.scroll_to_cursor = true; + } + + fn vim_enter_insert(&mut self, at: u64, mode: EditMode) { + self.sel_anchor = None; + self.cursor = at.min(self.doc.len()); + self.nibble = 0; + self.mode = mode; + self.vim_mode = vim::Mode::Insert; + self.scroll_to_cursor = true; + } + + fn vim_exec(&mut self, cmd: vim::Cmd, ctx: &egui::Context) { + use vim::{Cmd, Motion}; + let len = self.doc.len(); + let last = len.saturating_sub(1); + let bpr = self.bytes_per_row as u64; + let cur = self.cursor.min(last); + let row_start = cur - cur % bpr; + let visual = self.vim_mode == vim::Mode::Visual; + + match cmd { + Cmd::Move { motion, count, explicit } => { + let n = count as u64; + let page = (self.page_rows as u64).max(1); + let w = self.vim_word(); + let target = match motion { + Motion::Left => cur.saturating_sub(n), + Motion::Right => cur.saturating_add(n), + Motion::Up => cur.saturating_sub(n.saturating_mul(bpr)), + Motion::Down => cur.saturating_add(n.saturating_mul(bpr)), + Motion::WordFwd => (cur / w).saturating_add(n).saturating_mul(w), + Motion::WordBack => { + let mut p = cur; + for _ in 0..count.min(1 << 20) { + p = if !p.is_multiple_of(w) { p - p % w } else { p.saturating_sub(w) }; + } + p + } + Motion::WordEnd => { + let mut p = cur; + for _ in 0..count.min(1 << 20) { + p = ((p + 1) / w + 1) * w - 1; + } + p + } + Motion::RowStart => row_start, + Motion::RowEnd => row_start + bpr - 1, + Motion::FileStart if !explicit => 0, + Motion::FileEnd if !explicit => last, + Motion::FileStart | Motion::FileEnd => (n - 1).saturating_mul(bpr), + Motion::PageDown => cur.saturating_add(n.saturating_mul(page * bpr)), + Motion::PageUp => cur.saturating_sub(n.saturating_mul(page * bpr)), + Motion::HalfPageDown => { + cur.saturating_add(n.saturating_mul((page / 2).max(1) * bpr)) + } + Motion::HalfPageUp => { + cur.saturating_sub(n.saturating_mul((page / 2).max(1) * bpr)) + } + }; + self.set_cursor(target.min(last), visual); + } + Cmd::Insert => self.vim_enter_insert(cur, EditMode::Insert), + Cmd::Append => self.vim_enter_insert(if len == 0 { 0 } else { cur + 1 }, EditMode::Insert), + Cmd::InsertRowStart => self.vim_enter_insert(row_start, EditMode::Insert), + Cmd::AppendRowEnd => self.vim_enter_insert(row_start + bpr, EditMode::Insert), + Cmd::ReplaceMode => self.vim_enter_insert(cur, EditMode::Overwrite), + Cmd::ReplaceByte { byte, count } => { + if cur < len { + let k = (count as u64).min(len - cur); + let data = vec![byte; k as usize]; + self.doc.overwrite(cur, &data); + for i in 0..k { + self.live_poke(cur + i, byte); + } + self.set_cursor(cur + k - 1, false); + } + } + Cmd::DeleteFwd(n) => { + if cur < len { + self.vim_delete(cur, (n as u64).min(len - cur)); + } + } + Cmd::DeleteBack(n) => { + let k = (n as u64).min(cur); + self.vim_delete(cur - k, k); + } + Cmd::DeleteRows(n) => { + if row_start < len { + let k = (n as u64).saturating_mul(bpr).min(len - row_start); + self.vim_delete(row_start, k); + } + } + Cmd::DeleteToRowEnd => { + if cur < len { + let end = (row_start + bpr).min(len); + self.vim_delete(cur, end - cur); + } + } + Cmd::YankRows(n) => { + if row_start < len { + let k = (n as u64).saturating_mul(bpr).min(len - row_start); + self.vim_yank(row_start, k); + } + } + Cmd::PasteAfter(n) | Cmd::PasteBefore(n) => { + if self.clipboard.is_empty() { + self.status = "nothing yanked".into(); + return; + } + let pos = match cmd { + Cmd::PasteAfter(_) if len > 0 => cur + 1, + _ => cur, + }; + let reps = n.min((64 << 20) / self.clipboard.len()).max(1); + let data = self.clipboard.repeat(reps); + self.doc.insert(pos, &data); + self.status = format!("pasted {} bytes", data.len()); + self.set_cursor(pos + data.len() as u64 - 1, false); + } + Cmd::ToggleCase(n) => { + if cur < len { + let k = (n as u64).min(len - cur); + let mut data = self.doc.read_range(cur, k as usize); + for b in &mut data { + if b.is_ascii_alphabetic() { + *b ^= 0x20; + } + } + self.doc.overwrite(cur, &data); + for (i, b) in data.iter().enumerate() { + self.live_poke(cur + i as u64, *b); + } + self.set_cursor((cur + k).min(last), false); + } + } + Cmd::Undo(n) | Cmd::Redo(n) => { + for _ in 0..n.min(10_000) { + if matches!(cmd, Cmd::Undo(_)) { + self.doc.undo(); + } else { + self.doc.redo(); + } + } + self.clamp_cursor_normal(); + self.scroll_to_cursor = true; + } + Cmd::ToggleVisual => { + if visual { + self.vim_mode = vim::Mode::Normal; + self.clear_selection(); + } else { + self.vim_mode = vim::Mode::Visual; + self.cursor = cur; + self.sel_anchor = Some(cur); + } + } + Cmd::VisualSwap => { + if let Some(a) = self.sel_anchor { + self.sel_anchor = Some(self.cursor); + self.cursor = a; + self.scroll_to_cursor = true; + } + } + Cmd::VisualDelete => { + if let Some((s, e)) = self.selection_range() { + self.sel_anchor = None; + self.vim_delete(s, e - s); + } + self.vim_mode = vim::Mode::Normal; + } + Cmd::VisualYank => { + if let Some((s, _)) = self.selection_range() { + self.copy(ctx); // also puts the hex on the system clipboard + self.set_cursor(s, false); + } + self.vim_mode = vim::Mode::Normal; + } + Cmd::Search => self.search.open = true, + Cmd::SearchNext | Cmd::SearchPrev => { + if self.search.needle.is_empty() { + self.status = "no previous search — press / to search".into(); + } else { + let dir = if cmd == Cmd::SearchNext { + search::Direction::Forward + } else { + search::Direction::Backward + }; + self.do_find(dir); + self.status = self.search.status.clone(); + // n/N land on the match start (not a selection) in NORMAL. + if !visual { + if let Some((s, _)) = self.selection_range() { + self.set_cursor(s, false); + } + } + } + } + Cmd::Goto => self.goto.open = true, + Cmd::SetMark(i) => { + self.bookmarks[i] = Some(cur); + self.status = format!("bookmark {i} set at {cur:#X}"); + } + Cmd::JumpMark(i) => match self.bookmarks[i] { + Some(addr) => { + self.jump_to(addr.min(last)); + self.status = format!("jumped to bookmark {i}"); + } + None => self.status = format!("bookmark {i} not set"), + }, + Cmd::Escape => { + self.vim_mode = vim::Mode::Normal; + self.clear_selection(); + self.extra_cursors.clear(); + } + } + } + // ---- dialogs ---- fn search_window(&mut self, ctx: &egui::Context) { diff --git a/src/ui/icon.rs b/src/ui/icon.rs index 843d709..1c5d989 100644 --- a/src/ui/icon.rs +++ b/src/ui/icon.rs @@ -1,115 +1,21 @@ -//! The application icon: a pixel-art witch flying on a broom, built from a -//! character grid so it stays in-tree and dependency-free. The base grid is -//! scaled up with nearest-neighbour so it keeps crisp pixel edges at any size. - -/// Base art, 32×32. Legend: -/// `.` transparent `K` outline `P` purple cloak/hat `M` light purple -/// `G` witch-green skin `B` broom handle `Y` straw bristles -/// `W` moon `A` amber star -const ART: &[&str] = &[ - "................................", // 0 - "....WW.................A.........", // 1 - "...WWWW.........KK...............", // 2 - "...WWW........KKPPKK.............", // 3 - "...WWWW......KKPPPPKK............", // 4 - "....WW......KPPPPPPPK............", // 5 - "...........KPPPPPPPPK....A.......", // 6 - "..........KPPPPPPPPPK............", // 7 - ".........KPPPPPPPPPPPK...........", // 8 - "........KPPPPPPPPPPPPPK..........", // 9 - ".......KKKKKKKKKKKKKKKKK.........", // 10 - "..........KGGGGGGK...............", // 11 - ".........KGGGGGGGGK..............", // 12 - ".........KGKKGGKKGK......Y.......", // 13 - ".........KGGGGGGGGK....YYYYY.....", // 14 - "..........KGGGGGGK...YYYYYYYY....", // 15 - "..........KGWWGGK..YYYYYYYYYY....", // 16 - ".........KPPPPPPPK.YYYYYYYYY.....", // 17 - "........KPPPMMPPPPK.YYYYYYY......", // 18 - ".......KPPPPMPPPPPPK..YYYY.......", // 19 - "BBBBBBKKPPPPPPPPPPPPKYYY.........", // 20 - ".....BBBKPPPPPPPPPPPK............", // 21 - "........KPPPPPPPPPPK.............", // 22 - ".......KPPPK.KPPPPK..............", // 23 - "......KPPPK...KPPPK..............", // 24 - "......KKKK....KKKK...............", // 25 - "................................", // 26 - "..........A.....................", // 27 - "...............................A", // 28 - "................................", // 29 - "...............A................", // 30 - "................................", // 31 -]; - -fn palette(c: char) -> [u8; 4] { - match c { - 'K' => [20, 16, 28, 255], // near-black outline - 'P' => [104, 56, 148, 255], // purple - 'M' => [170, 110, 210, 255], // light purple highlight - 'G' => [120, 205, 130, 255], // witch green - 'B' => [150, 100, 52, 255], // broom handle (brown) - 'Y' => [226, 182, 92, 255], // straw bristles - 'W' => [236, 236, 250, 255], // moon / eye whites - 'A' => [255, 200, 80, 255], // amber star - _ => [0, 0, 0, 0], // transparent - } -} - -/// Build the icon as `(rgba, width, height)`, scaled by `scale` (nearest-neighbour). -pub fn rgba(scale: usize) -> (Vec, u32, u32) { - let scale = scale.max(1); - let bw = ART[0].len(); - let bh = ART.len(); - let w = bw * scale; - let h = bh * scale; - let mut out = vec![0u8; w * h * 4]; - for (y, row) in ART.iter().enumerate() { - for (x, c) in row.chars().enumerate() { - let col = palette(c); - for dy in 0..scale { - for dx in 0..scale { - let px = x * scale + dx; - let py = y * scale + dy; - let i = (py * w + px) * 4; - out[i..i + 4].copy_from_slice(&col); - } - } +//! The application icon: a green-phosphor CRT "b" over a hex dump, embedded +//! from `assets/icon.png` so the window/taskbar icon matches the bundle icon. + +/// The icon artwork (512×512 RGBA PNG). +pub const PNG: &[u8] = include_bytes!("../../assets/icon.png"); + +/// Decode the icon as `(rgba, width, height)`. +pub fn rgba() -> (Vec, u32, u32) { + match image::load_from_memory_with_format(PNG, image::ImageFormat::Png) { + Ok(img) => { + let img = img.into_rgba8(); + let (w, h) = img.dimensions(); + (img.into_raw(), w, h) } + // Unreachable with the bundled asset; fall back to a 1×1 transparent pixel + // rather than refusing to start. + Err(_) => (vec![0, 0, 0, 0], 1, 1), } - (out, w as u32, h as u32) -} - -/// Encode an RGBA buffer as a PNG (used to render the icon for inspection and to -/// produce a bundle icon file). Pure Rust: zlib via the shared compress backend. -pub fn to_png(rgba: &[u8], w: u32, h: u32) -> Vec { - fn chunk(out: &mut Vec, kind: &[u8; 4], data: &[u8]) { - out.extend_from_slice(&(data.len() as u32).to_be_bytes()); - out.extend_from_slice(kind); - out.extend_from_slice(data); - let mut crc_in = Vec::with_capacity(4 + data.len()); - crc_in.extend_from_slice(kind); - crc_in.extend_from_slice(data); - out.extend_from_slice(&crc32fast::hash(&crc_in).to_be_bytes()); - } - - let mut png = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]; - let mut ihdr = Vec::new(); - ihdr.extend_from_slice(&w.to_be_bytes()); - ihdr.extend_from_slice(&h.to_be_bytes()); - ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); // 8-bit, RGBA, no interlace - chunk(&mut png, b"IHDR", &ihdr); - - // filtered scanlines: each row prefixed with filter type 0 (None) - let mut raw = Vec::with_capacity((w as usize * 4 + 1) * h as usize); - for y in 0..h as usize { - raw.push(0); - let start = y * w as usize * 4; - raw.extend_from_slice(&rgba[start..start + w as usize * 4]); - } - let idat = crate::ops::compress::compress(&raw, crate::ops::compress::Codec::Zlib, 6); - chunk(&mut png, b"IDAT", &idat); - chunk(&mut png, b"IEND", &[]); - png } #[cfg(test)] @@ -117,32 +23,12 @@ mod tests { use super::*; #[test] - fn icon_dimensions_and_opaque_pixels() { - let (buf, w, h) = rgba(8); - assert_eq!((w, h), (256, 256)); - assert_eq!(buf.len(), 256 * 256 * 4); - // there is some non-transparent content + fn icon_decodes() { + let (buf, w, h) = rgba(); + assert_eq!((w, h), (512, 512)); + assert_eq!(buf.len(), (w * h * 4) as usize); + // opaque artwork in the middle, transparent rounded corners assert!(buf.chunks(4).any(|p| p[3] == 255)); - } - - #[test] - fn png_has_signature_and_chunks() { - let (buf, w, h) = rgba(1); - let png = to_png(&buf, w, h); - assert_eq!(&png[..8], &[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]); - // IHDR right after the signature, IEND at the end - assert_eq!(&png[12..16], b"IHDR"); - assert_eq!(&png[png.len() - 8..png.len() - 4], b"IEND"); - } - - /// Writes the icon to a PNG for visual inspection: `cargo test render_icon -- --nocapture`. - #[test] - #[ignore] - fn render_icon() { - let (buf, w, h) = rgba(8); - let png = to_png(&buf, w, h); - let path = std::env::temp_dir().join("bewitched_icon.png"); - std::fs::write(&path, &png).unwrap(); - println!("wrote {}", path.display()); + assert_eq!(buf[3], 0); } } diff --git a/src/ui/mod.rs b/src/ui/mod.rs index cd51023..ed8454d 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -8,6 +8,7 @@ pub mod icon; #[cfg(target_os = "macos")] mod macos; mod theme; +mod vim; use app::App; use std::path::PathBuf; @@ -41,7 +42,7 @@ pub fn run() -> eframe::Result<()> { } } - let (rgba, iw, ih) = icon::rgba(8); + let (rgba, iw, ih) = icon::rgba(); let title = format!("bewitched v{}", env!("CARGO_PKG_VERSION")); let options = eframe::NativeOptions { viewport: egui::ViewportBuilder::default() diff --git a/src/ui/vim.rs b/src/ui/vim.rs new file mode 100644 index 0000000..5833bd1 --- /dev/null +++ b/src/ui/vim.rs @@ -0,0 +1,465 @@ +//! Optional vim-style modal keybindings for the hex view. +//! +//! This module is a pure key-sequence parser: it turns keystrokes (with counts +//! and multi-key prefixes such as `dd`, `gg`, `r41`, `m3`) into [`Cmd`]s that +//! the app then executes. Keeping it free of GUI/document state makes the +//! grammar unit-testable. + +/// File remembering whether vim mode is on between launches. +fn setting_path() -> std::path::PathBuf { + crate::ops::config_dir().join("vim_mode") +} + +/// Whether vim mode was left enabled last session. +pub fn load_enabled() -> bool { + std::fs::read_to_string(setting_path()) + .map(|s| s.trim() == "on") + .unwrap_or(false) +} + +/// Remember the vim-mode toggle for the next launch (best effort). +pub fn save_enabled(on: bool) { + let path = setting_path(); + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + let _ = std::fs::write(path, if on { "on\n" } else { "off\n" }); +} + +/// The vim mode the editor is in. Insert/replace typing is handled by the +/// regular editing code; `Normal` and `Visual` interpret keys as commands. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Mode { + Normal, + Visual, + /// Typing edits the document (`i`/`a`/`I`/`A` insert, `R` overwrite). + Insert, +} + +/// A keystroke fed to the parser. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Input { + /// A typed character (from a text event; shift already applied). + Char(char), + /// A Ctrl-chord, lower-cased letter (`Ctrl+D` → `Ctrl('d')`). + Ctrl(char), + Esc, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Motion { + Left, + Right, + Up, + Down, + /// `w`: start of the next word (byte group). + WordFwd, + /// `b`: start of the previous word (byte group). + WordBack, + /// `e`: end of the current/next word (byte group). + WordEnd, + /// `0` / `^`: first byte of the row. + RowStart, + /// `$`: last byte of the row. + RowEnd, + /// `gg`: start of the file, or row `n` (1-based) with a count. + FileStart, + /// `G`: last byte of the file, or row `n` (1-based) with a count. + FileEnd, + PageDown, + PageUp, + HalfPageDown, + HalfPageUp, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Cmd { + /// Move the cursor. `count` is the repeat (or the row number for + /// `gg`/`G`, where `explicit` says a count was actually typed). + Move { + motion: Motion, + count: usize, + explicit: bool, + }, + /// `i`: insert before the cursor. + Insert, + /// `a`: insert after the cursor. + Append, + /// `I`: insert at row start. + InsertRowStart, + /// `A`: insert after row end. + AppendRowEnd, + /// `R`: overwrite ("replace") typing mode. + ReplaceMode, + /// `r`: overwrite `count` bytes with `byte`. + ReplaceByte { + byte: u8, + count: usize, + }, + /// `x` / `Del`: delete `count` bytes at the cursor (yanked). + DeleteFwd(usize), + /// `X`: delete `count` bytes before the cursor (yanked). + DeleteBack(usize), + /// `dd`: delete `count` whole rows (yanked). + DeleteRows(usize), + /// `D`: delete to the end of the row (yanked). + DeleteToRowEnd, + /// `yy`: yank `count` whole rows. + YankRows(usize), + /// `p`: paste after the cursor, `count` times. + PasteAfter(usize), + /// `P`: paste before the cursor, `count` times. + PasteBefore(usize), + /// `~`: flip ASCII case of `count` bytes. + ToggleCase(usize), + Undo(usize), + Redo(usize), + /// `v`: enter (or leave) visual mode. + ToggleVisual, + /// `o` in visual: jump to the other end of the selection. + VisualSwap, + /// `d`/`x` in visual: delete the selection (yanked). + VisualDelete, + /// `y` in visual: yank the selection. + VisualYank, + /// `/` or `?`: open the search window. + Search, + /// `n`: next match. + SearchNext, + /// `N`: previous match. + SearchPrev, + /// `:`: open go-to-address. + Goto, + /// `m0`-`m9`: set bookmark. + SetMark(usize), + /// `'0`-`'9` (or `` `0 ``): jump to bookmark. + JumpMark(usize), + /// Esc: leave insert/visual, cancel a pending sequence. + Escape, +} + +/// Parser state for one editor. +#[derive(Default)] +pub struct Vim { + count: Option, + /// Multi-key prefix waiting for its next key: `g`, `d`, `y`, `r`, `m`, `'`. + pending: Option, + /// The high nibble typed after `r` in the hex pane. + r_high: Option, +} + +impl Vim { + /// What has been typed so far of an incomplete command (for the status bar). + pub fn pending_text(&self) -> String { + let mut s = String::new(); + if let Some(c) = self.count { + s.push_str(&c.to_string()); + } + if let Some(p) = self.pending { + s.push(p); + } + if let Some(h) = self.r_high { + s.push(char::from_digit(h as u32, 16).unwrap_or('?')); + } + s + } + + pub fn reset(&mut self) { + *self = Self::default(); + } + + /// Feed one keystroke in `Normal`/`Visual` mode. `hex_pane` selects how + /// `r` reads its replacement (two hex digits vs. one character). + /// Returns a command once a full sequence has been typed. + pub fn feed(&mut self, input: Input, mode: Mode, hex_pane: bool) -> Option { + let c = match input { + Input::Esc => { + self.reset(); + return Some(Cmd::Escape); + } + Input::Ctrl(k) => { + let n = self.take_count(); + self.pending = None; + self.r_high = None; + let mv = |motion| Cmd::Move { + motion, + count: n, + explicit: false, + }; + return match k { + 'f' => Some(mv(Motion::PageDown)), + 'b' => Some(mv(Motion::PageUp)), + 'd' => Some(mv(Motion::HalfPageDown)), + 'u' => Some(mv(Motion::HalfPageUp)), + 'r' => Some(Cmd::Redo(n)), + _ => None, + }; + } + Input::Char(c) => c, + }; + + // Second key of a multi-key sequence. + if let Some(p) = self.pending { + return self.finish_pending(p, c, hex_pane); + } + + // Count prefix (a leading `0` is the row-start motion, not a digit). + if let Some(d) = c.to_digit(10) { + if d != 0 || self.count.is_some() { + let cur = self.count.unwrap_or(0); + self.count = Some( + cur.saturating_mul(10) + .saturating_add(d as usize) + .min(1 << 40), + ); + return None; + } + } + + let explicit = self.count.is_some(); + let n = self.take_count(); + let mv = |motion| { + Some(Cmd::Move { + motion, + count: n, + explicit, + }) + }; + let visual = mode == Mode::Visual; + match c { + 'h' | ' ' => mv(Motion::Left), + 'l' => mv(Motion::Right), + 'k' => mv(Motion::Up), + 'j' => mv(Motion::Down), + 'w' => mv(Motion::WordFwd), + 'b' => mv(Motion::WordBack), + 'e' => mv(Motion::WordEnd), + '0' | '^' => mv(Motion::RowStart), + '$' => mv(Motion::RowEnd), + 'G' => mv(Motion::FileEnd), + 'v' => Some(Cmd::ToggleVisual), + 'o' if visual => Some(Cmd::VisualSwap), + 'd' | 'x' if visual => Some(Cmd::VisualDelete), + 'y' if visual => Some(Cmd::VisualYank), + 'i' => Some(Cmd::Insert), + 'a' => Some(Cmd::Append), + 'I' => Some(Cmd::InsertRowStart), + 'A' => Some(Cmd::AppendRowEnd), + 'R' => Some(Cmd::ReplaceMode), + 'x' => Some(Cmd::DeleteFwd(n)), + 'X' => Some(Cmd::DeleteBack(n)), + 'D' => Some(Cmd::DeleteToRowEnd), + 'p' => Some(Cmd::PasteAfter(n)), + 'P' => Some(Cmd::PasteBefore(n)), + '~' => Some(Cmd::ToggleCase(n)), + 'u' => Some(Cmd::Undo(n)), + '/' | '?' => Some(Cmd::Search), + 'n' => Some(Cmd::SearchNext), + 'N' => Some(Cmd::SearchPrev), + ':' => Some(Cmd::Goto), + 'g' | 'd' | 'y' | 'r' | 'm' | '\'' | '`' => { + // keep the count for the completed sequence + if explicit { + self.count = Some(n); + } + self.pending = Some(c); + None + } + _ => None, + } + } + + fn take_count(&mut self) -> usize { + self.count.take().unwrap_or(1).max(1) + } + + fn finish_pending(&mut self, p: char, c: char, hex_pane: bool) -> Option { + if p == 'r' && hex_pane { + // `r` in the hex pane takes two hex digits: the new byte value. + let Some(d) = c.to_digit(16) else { + self.reset(); + return None; + }; + match self.r_high.take() { + None => { + self.r_high = Some(d as u8); + return None; + } + Some(hi) => { + self.pending = None; + let count = self.take_count(); + return Some(Cmd::ReplaceByte { + byte: (hi << 4) | d as u8, + count, + }); + } + } + } + self.pending = None; + let explicit = self.count.is_some(); + let n = self.take_count(); + match (p, c) { + ('g', 'g') => Some(Cmd::Move { + motion: Motion::FileStart, + count: n, + explicit, + }), + ('d', 'd') => Some(Cmd::DeleteRows(n)), + ('y', 'y') => Some(Cmd::YankRows(n)), + ('r', c) if (c as u32) < 0x100 && !c.is_control() => Some(Cmd::ReplaceByte { + byte: c as u8, + count: n, + }), + ('m', c) => c.to_digit(10).map(|d| Cmd::SetMark(d as usize)), + ('\'' | '`', c) => c.to_digit(10).map(|d| Cmd::JumpMark(d as usize)), + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn run(v: &mut Vim, keys: &str, mode: Mode, hex: bool) -> Vec { + keys.chars() + .filter_map(|c| v.feed(Input::Char(c), mode, hex)) + .collect() + } + + fn normal(keys: &str) -> Vec { + run(&mut Vim::default(), keys, Mode::Normal, true) + } + + #[test] + fn motions_with_counts() { + assert_eq!( + normal("3j"), + vec![Cmd::Move { + motion: Motion::Down, + count: 3, + explicit: true + }] + ); + assert_eq!( + normal("12l"), + vec![Cmd::Move { + motion: Motion::Right, + count: 12, + explicit: true + }] + ); + assert_eq!( + normal("0"), + vec![Cmd::Move { + motion: Motion::RowStart, + count: 1, + explicit: false + }] + ); + assert_eq!( + normal("10G"), + vec![Cmd::Move { + motion: Motion::FileEnd, + count: 10, + explicit: true + }] + ); + assert_eq!( + normal("gg"), + vec![Cmd::Move { + motion: Motion::FileStart, + count: 1, + explicit: false + }] + ); + assert_eq!( + normal("5gg"), + vec![Cmd::Move { + motion: Motion::FileStart, + count: 5, + explicit: true + }] + ); + } + + #[test] + fn operators() { + assert_eq!(normal("dd"), vec![Cmd::DeleteRows(1)]); + assert_eq!(normal("2dd"), vec![Cmd::DeleteRows(2)]); + assert_eq!(normal("3yy"), vec![Cmd::YankRows(3)]); + assert_eq!(normal("4x"), vec![Cmd::DeleteFwd(4)]); + assert_eq!(normal("u"), vec![Cmd::Undo(1)]); + assert_eq!(normal("2p"), vec![Cmd::PasteAfter(2)]); + // an unknown second key cancels the sequence + assert_eq!(normal("dzx"), vec![Cmd::DeleteFwd(1)]); + } + + #[test] + fn replace_byte_hex_and_text() { + assert_eq!( + normal("r4f"), + vec![Cmd::ReplaceByte { + byte: 0x4f, + count: 1 + }] + ); + assert_eq!( + normal("3rff"), + vec![Cmd::ReplaceByte { + byte: 0xff, + count: 3 + }] + ); + let mut v = Vim::default(); + assert_eq!( + run(&mut v, "rA", Mode::Normal, false), + vec![Cmd::ReplaceByte { + byte: b'A', + count: 1 + }] + ); + // non-hex digit in the hex pane cancels + assert_eq!(normal("rzj").len(), 1); + } + + #[test] + fn marks() { + assert_eq!(normal("m3"), vec![Cmd::SetMark(3)]); + assert_eq!(normal("'3"), vec![Cmd::JumpMark(3)]); + assert_eq!(normal("`7"), vec![Cmd::JumpMark(7)]); + } + + #[test] + fn visual_mode_keys() { + let mut v = Vim::default(); + assert_eq!( + run(&mut v, "d", Mode::Visual, true), + vec![Cmd::VisualDelete] + ); + assert_eq!(run(&mut v, "y", Mode::Visual, true), vec![Cmd::VisualYank]); + assert_eq!(run(&mut v, "o", Mode::Visual, true), vec![Cmd::VisualSwap]); + } + + #[test] + fn ctrl_and_escape() { + let mut v = Vim::default(); + assert_eq!(v.feed(Input::Char('4'), Mode::Normal, true), None); + assert_eq!(v.pending_text(), "4"); + assert_eq!( + v.feed(Input::Ctrl('d'), Mode::Normal, true), + Some(Cmd::Move { + motion: Motion::HalfPageDown, + count: 4, + explicit: false + }) + ); + assert_eq!(v.feed(Input::Char('d'), Mode::Normal, true), None); + assert_eq!(v.feed(Input::Esc, Mode::Normal, true), Some(Cmd::Escape)); + assert_eq!(v.pending_text(), ""); + assert_eq!( + v.feed(Input::Ctrl('r'), Mode::Normal, true), + Some(Cmd::Redo(1)) + ); + } +}