@@ -35,15 +52,20 @@ I had microcontroller practicals to get through, and the course expects you to
use Keil µVision. Keil µVision doesn't run on Linux. Rather than fight with
Wine or a Windows VM every lab session, I wrote my own: bench51 does the parts
of µVision those practicals actually need (write the code, assemble it, look
-at the listing and HEX, step through it and watch the registers) right in the
-terminal.
+at the listing and HEX, step through it and watch the registers) natively on
+Linux, in a window or right in the terminal.
-----
## Features
-- **Editor** with undo/redo, breakpoint and error markers in the gutter —
- or press Ctrl-G to edit in your own `$EDITOR` (vim, nvim, nano, …).
+- **µVision layout**: menus and toolbar, a Project window, the editor, Build
+ Output, and in a debug session the Registers, Disassembly, Memory, Symbols,
+ UART #1, Ports, Timers and Interrupts windows. Every window docks and tabs
+ wherever you drag it; the edit and debug layouts are remembered separately,
+ as in µVision.
+- **Editor** with syntax highlighting, undo/redo, find, and breakpoint, error
+ and PC markers in the gutter.
- **Two-pass assembler** for the full 8051 instruction set (all 255 opcodes):
- labels, expressions (`+ - * / MOD AND OR XOR NOT SHL SHR HIGH LOW`, `$`)
- number formats `42`, `2Ah`, `0x2A`, `101010b`, `52o`, `'*'`
@@ -63,9 +85,88 @@ terminal.
breakpoints, changed-value highlighting, memory poke, adjustable speed.
- **Open `.hex` files**: they're disassembled into editable source that
re-assembles to the identical image.
+- **Dark and light themes** in a monochrome, dot-matrix design (Space
+ Grotesk, Space Mono and Doto, bundled).
## Usage
+```bash
+cargo install --path crates/bench51-gui # installs `bench51-gui`
+
+cargo run --release -p bench51-gui # welcome screen
+cargo run --release -p bench51-gui -- examples/*.asm # open several files
+cargo run --release -p bench51-gui -- firmware.hex # disassemble & debug a HEX file
+cargo run --release -p bench51-gui -- --theme light
+```
+
+`--theme system|dark|light` overrides the theme chosen in View → Theme, and
+`--clock ` the Xtal set in Project → Options for Target (default
+11.0592), which is used for the elapsed-time display.
+
+On Linux it runs on Wayland and X11 and uses the XDG desktop portal for file
+dialogs. To add it to your application launcher:
+
+```bash
+install -Dm644 crates/bench51-gui/assets/bench51-gui.desktop ~/.local/share/applications/bench51-gui.desktop
+install -Dm644 crates/bench51-gui/assets/bench51-gui.svg ~/.local/share/icons/hicolor/scalable/apps/bench51-gui.svg
+```
+
+It also builds for Windows and macOS. On Debian or Ubuntu, first install the
+packages egui needs: `libxcb-render0-dev libxcb-shape0-dev
+libxcb-xfixes0-dev libxkbcommon-dev libssl-dev`.
+
+## Keys
+
+The keys are µVision's, with the TUI's as aliases:
+
+| Key | Action |
+| --- | --- |
+| F7 | build target (also writes `.lst` and `.hex` next to a saved file) |
+| Ctrl-F5 / F4 | start / stop the debug session |
+| F5 | run / stop |
+| F11 / F10 | step into / step over |
+| Ctrl-F11 / F12 | step out |
+| Ctrl-F10 / F8 | run to the cursor line |
+| F9 / Ctrl-Shift-F9 | toggle breakpoint / remove all breakpoints |
+| F6 | reset the CPU |
+| Ctrl-N / Ctrl-O / Ctrl-S / Ctrl-W | new / open / save / close |
+| Ctrl-F | find |
+| F1 | all shortcuts |
+
+Click the gutter to toggle a breakpoint, double-click a byte in Memory to
+change it, click a pin in Ports to hold it low from outside, and click the
+bit chips in Registers, Timers and Interrupts to flip SFR bits. Files can be
+dropped onto the window.
+
+## Terminal version
+
+`bench51` is the same IDE in a terminal, the way `emacs -nw` is Emacs
+without a window. It has the editor, listing, HEX and error views, and a
+debug screen with registers, peripherals, memory, ports and the UART. The
+same binary also assembles headlessly, which is handy in scripts and
+Makefiles.
+
+
+
+
+
+
+
+
+
+
Editor + assembled listing
+
Breakpoint inside a timer ISR, SFR view
+
+
+
+
+
+
+
Assembler errors in the gutter and Errors tab
+
Intel HEX output
+
+
+
```bash
cargo install --path . # installs the `bench51` binary
@@ -81,7 +182,7 @@ cargo run --release -- --assemble prog.asm -o out.hex --lst out.lst
`--clock ` sets the oscillator frequency used for the elapsed-time display
(default 11.0592).
-## Keys
+### Terminal keys
| Key | Action |
| --- | --- |
@@ -100,7 +201,8 @@ cargo run --release -- --assemble prog.asm -o out.hex --lst out.lst
Edit mode: `Alt-1/2/3` switch between Listing, HEX and Errors; `Alt-↑/↓`,
`Alt-PgUp/PgDn` scroll them. The editor uses Emacs-style keys
-(`Ctrl-U` undo, `Ctrl-R` redo, `Ctrl-Y` paste).
+(`Ctrl-U` undo, `Ctrl-R` redo, `Ctrl-Y` paste), or press Ctrl-G to edit in
+your own `$EDITOR` (vim, nvim, nano, …).
Debug mode: `Tab` cycles focus between Source, Memory, Ports and Serial.
Letter shortcuts work too, for terminals that swallow function keys:
@@ -133,10 +235,16 @@ Letter shortcuts work too, for terminals that swallow function keys:
## Development
```bash
-cargo test # assembler, CPU, peripheral and example-program tests
-cargo clippy
+cargo test --workspace # assembler, CPU, peripheral, session and example-program tests
+cargo clippy --workspace --all-targets
```
-Code layout: `src/isa.rs` (opcode table shared by everything), `src/asm/`
-(assembler, listing, Intel HEX), `src/sim/` (CPU, peripherals, disassembler),
-`src/ui/` (ratatui front end).
+Code layout:
+
+- `crates/bench51-gui/` is the `bench51-gui` desktop app (egui).
+- `src/` is the `bench51` terminal app (ratatui), including headless
+ assembly.
+- `crates/bench51-core/`, shared by both: `isa.rs` (opcode table), `asm/`
+ (assembler, listing, Intel HEX), `sim/` (CPU, peripherals, disassembler),
+ `session.rs` (build, run, step and breakpoints), `syntax.rs`
+ (highlighting tokens), `files.rs` (HEX loading)
diff --git a/crates/bench51-core/Cargo.toml b/crates/bench51-core/Cargo.toml
new file mode 100644
index 0000000..a50fcde
--- /dev/null
+++ b/crates/bench51-core/Cargo.toml
@@ -0,0 +1,10 @@
+[package]
+name = "bench51-core"
+version.workspace = true
+edition.workspace = true
+description = "Intel 8051 assembler, simulator and debugger session shared by the bench51 front ends"
+
+[dependencies]
+
+[lints]
+workspace = true
diff --git a/src/asm/expr.rs b/crates/bench51-core/src/asm/expr.rs
similarity index 100%
rename from src/asm/expr.rs
rename to crates/bench51-core/src/asm/expr.rs
diff --git a/src/asm/hex.rs b/crates/bench51-core/src/asm/hex.rs
similarity index 100%
rename from src/asm/hex.rs
rename to crates/bench51-core/src/asm/hex.rs
diff --git a/src/asm/lexer.rs b/crates/bench51-core/src/asm/lexer.rs
similarity index 100%
rename from src/asm/lexer.rs
rename to crates/bench51-core/src/asm/lexer.rs
diff --git a/src/asm/listing.rs b/crates/bench51-core/src/asm/listing.rs
similarity index 100%
rename from src/asm/listing.rs
rename to crates/bench51-core/src/asm/listing.rs
diff --git a/src/asm/mod.rs b/crates/bench51-core/src/asm/mod.rs
similarity index 100%
rename from src/asm/mod.rs
rename to crates/bench51-core/src/asm/mod.rs
diff --git a/crates/bench51-core/src/files.rs b/crates/bench51-core/src/files.rs
new file mode 100644
index 0000000..e1fcff7
--- /dev/null
+++ b/crates/bench51-core/src/files.rs
@@ -0,0 +1,95 @@
+//! Loading programs: assembly sources as they are, Intel HEX images as
+//! disassembled source.
+
+use std::path::Path;
+
+use crate::asm::hex;
+use crate::sfr::{hex8, hex16};
+use crate::sim::disasm;
+
+pub enum Loaded {
+ Source(String),
+ /// A HEX image turned into source that reassembles to the same bytes.
+ Hex {
+ source: String,
+ bytes: usize,
+ },
+}
+
+pub fn is_hex_path(path: &Path) -> bool {
+ path.extension()
+ .is_some_and(|e| e.eq_ignore_ascii_case("hex") || e.eq_ignore_ascii_case("ihx"))
+}
+
+/// Reads `path`. Errors are ready to show to the user.
+pub fn load(path: &Path) -> Result {
+ let text = std::fs::read_to_string(path)
+ .map_err(|e| format!("cannot open {}: {e}", path.display()))?;
+ if !is_hex_path(path) {
+ return Ok(Loaded::Source(text));
+ }
+ let bytes = hex::read(&text).map_err(|e| format!("invalid HEX file: {e}"))?;
+ Ok(Loaded::Hex {
+ source: disassemble_image(&bytes, path),
+ bytes: bytes.len(),
+ })
+}
+
+/// Builds an assembler source from a HEX image by disassembling each
+/// contiguous run of bytes. Reassembling it reproduces the image exactly.
+pub fn disassemble_image(bytes: &[(u16, u8)], path: &Path) -> String {
+ let mut code = Box::new([0u8; 0x10000]);
+ let mut used = vec![false; 0x10000];
+ for &(a, b) in bytes {
+ code[a as usize] = b;
+ used[a as usize] = true;
+ }
+ let mut src = format!("; disassembled from {}\n", path.display());
+ let mut addr = 0usize;
+ while addr < 0x10000 {
+ if !used[addr] {
+ addr += 1;
+ continue;
+ }
+ src.push_str(&format!("\n ORG {}\n", hex16(addr as u16)));
+ while addr < 0x10000 && used[addr] {
+ let d = disasm::disassemble(&code, addr as u16);
+ let size = d.size as usize;
+ if (addr..addr + size).all(|a| a < 0x10000 && used[a]) {
+ src.push_str(&format!(" {:<24}; {:04X}\n", d.text, addr));
+ addr += size;
+ } else {
+ src.push_str(&format!(
+ " DB {:<21}; {:04X}\n",
+ hex8(code[addr]),
+ addr
+ ));
+ addr += 1;
+ }
+ }
+ }
+ src.push_str(" END\n");
+ src
+}
+
+#[cfg(test)]
+mod tests {
+ use std::path::Path;
+
+ use crate::asm::{assemble, hex};
+
+ #[test]
+ fn hex_disassembly_reassembles_to_the_same_image() {
+ let out = assemble(include_str!("../../../examples/serial_hello.asm"));
+ assert!(out.ok());
+ let image = hex::read(&out.intel_hex()).unwrap();
+ let src = super::disassemble_image(&image, Path::new("x.hex"));
+ let again = assemble(&src);
+ assert!(again.ok(), "{:?}", again.diagnostics);
+ let mut a: Vec<_> = out.bytes().collect();
+ let mut b: Vec<_> = again.bytes().collect();
+ a.sort();
+ b.sort();
+ assert_eq!(a, b);
+ }
+}
diff --git a/src/isa.rs b/crates/bench51-core/src/isa.rs
similarity index 99%
rename from src/isa.rs
rename to crates/bench51-core/src/isa.rs
index c2dd8da..22a5f96 100644
--- a/src/isa.rs
+++ b/crates/bench51-core/src/isa.rs
@@ -28,7 +28,7 @@ pub enum Operand {
impl Operand {
/// Bytes this operand occupies after the opcode byte.
- pub fn len(self) -> u8 {
+ pub(crate) fn len(self) -> u8 {
match self {
Operand::Imm8 | Operand::Direct | Operand::Bit | Operand::NotBit => 1,
Operand::Addr11 | Operand::Rel => 1,
diff --git a/crates/bench51-core/src/lib.rs b/crates/bench51-core/src/lib.rs
new file mode 100644
index 0000000..5af8514
--- /dev/null
+++ b/crates/bench51-core/src/lib.rs
@@ -0,0 +1,10 @@
+//! Intel 8051 assembler, simulator and debugger session shared by the
+//! bench51 front ends (the `bench51` TUI and the `bench51-gui` desktop app).
+
+pub mod asm;
+pub mod files;
+pub mod isa;
+pub mod session;
+pub mod sfr;
+pub mod sim;
+pub mod syntax;
diff --git a/crates/bench51-core/src/session.rs b/crates/bench51-core/src/session.rs
new file mode 100644
index 0000000..912204b
--- /dev/null
+++ b/crates/bench51-core/src/session.rs
@@ -0,0 +1,417 @@
+//! A debugging session: the simulator, the program loaded into it,
+//! breakpoints and run state. Front ends own the source text and decide
+//! when to build; everything else about running a program lives here.
+
+use std::collections::{HashMap, HashSet};
+use std::path::Path;
+
+use crate::asm::{self, AsmOutput, Diagnostic};
+use crate::sim::{Sim, Stop};
+
+/// Result of the last successful assembly, which the simulator runs.
+pub struct Build {
+ pub source: Vec,
+ pub out: AsmOutput,
+ pub addr_to_line: HashMap,
+}
+
+impl Build {
+ /// First address emitted by `line`, if any.
+ pub fn line_addr(&self, line: usize) -> Option {
+ self.out
+ .lines
+ .get(line)
+ .filter(|l| !l.bytes.is_empty())
+ .and_then(|l| l.addr)
+ }
+}
+
+/// Instructions executed per tick (one tick ≈ 33 ms) for each speed setting.
+pub const SPEEDS: [u32; 8] = [1, 5, 25, 100, 500, 2_000, 10_000, 40_000];
+
+/// Instruction budget for step over / step out / run to cursor.
+const STEP_BUDGET: u32 = 5_000_000;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum MemSpace {
+ Iram,
+ Sfr,
+ Xram,
+ Code,
+}
+
+impl MemSpace {
+ pub const ALL: [MemSpace; 4] = [
+ MemSpace::Iram,
+ MemSpace::Sfr,
+ MemSpace::Xram,
+ MemSpace::Code,
+ ];
+
+ pub fn name(self) -> &'static str {
+ match self {
+ MemSpace::Iram => "IRAM",
+ MemSpace::Sfr => "SFR",
+ MemSpace::Xram => "XRAM",
+ MemSpace::Code => "CODE",
+ }
+ }
+}
+
+pub struct Session {
+ pub sim: Sim,
+ /// Last assembler result, even if it had errors (for diagnostics).
+ pub last_asm: Option<(String, AsmOutput)>,
+ /// Last error-free build, loaded into the simulator.
+ pub build: Option,
+ /// Breakpoints by source line.
+ pub breakpoints: HashSet,
+ pub running: bool,
+ /// The next run chunk starts a fresh run and may leave a breakpoint.
+ resume: bool,
+ /// Index into `SPEEDS`.
+ pub speed: usize,
+ pub clock_mhz: f64,
+ /// Memory before the last step or run chunk, to highlight changes.
+ pub prev_iram: [u8; 256],
+ pub prev_sfr: [u8; 128],
+ /// Outcome of the last command, for the status line.
+ pub status: String,
+}
+
+impl Session {
+ pub fn new(clock_mhz: f64) -> Self {
+ Self {
+ sim: Sim::new(),
+ last_asm: None,
+ build: None,
+ breakpoints: HashSet::new(),
+ running: false,
+ resume: false,
+ speed: 5,
+ clock_mhz,
+ prev_iram: [0; 256],
+ prev_sfr: [0; 128],
+ status: String::new(),
+ }
+ }
+
+ /// Forgets the program and breakpoints, for a newly loaded source.
+ pub fn clear(&mut self) {
+ self.breakpoints.clear();
+ self.build = None;
+ self.last_asm = None;
+ self.running = false;
+ }
+
+ /// Whether `lines` differ from the source the simulator is running.
+ pub fn is_stale<'a>(&self, lines: impl IntoIterator) -> bool {
+ self.build
+ .as_ref()
+ .is_none_or(|b| !b.source.iter().map(String::as_str).eq(lines))
+ }
+
+ /// Diagnostics of the last assembly, if it was of exactly `source`.
+ pub fn diagnostics_for(&self, source: &str) -> &[Diagnostic] {
+ match &self.last_asm {
+ Some((src, out)) if src == source => &out.diagnostics,
+ _ => &[],
+ }
+ }
+
+ // ---- Build ----
+
+ /// Assembles `source`. On success the program is loaded into a freshly
+ /// reset simulator and, if `path` (the saved source file) is given,
+ /// `.lst` and `.hex` files are written next to it.
+ pub fn assemble(&mut self, source: &str, path: Option<&Path>) -> bool {
+ let out = asm::assemble(source);
+ let ok = out.ok();
+ if ok {
+ self.sim.load_code(out.bytes());
+ self.sim.reset();
+ self.running = false;
+ self.status = format!("assembled: {} bytes, 0 errors", out.code_size());
+ if let Some(path) = path {
+ self.write_outputs(&out, source, path);
+ }
+ self.build = Some(Build {
+ source: source.split('\n').map(String::from).collect(),
+ addr_to_line: out.addr_to_line(),
+ out: out.clone(),
+ });
+ self.snapshot();
+ } else {
+ let first = &out.diagnostics[0];
+ self.status = format!(
+ "{} error(s); line {}: {}",
+ out.diagnostics.len(),
+ first.line + 1,
+ first.msg
+ );
+ }
+ self.last_asm = Some((source.to_string(), out));
+ ok
+ }
+
+ /// Makes sure a build of `source` is loaded; returns false on errors.
+ pub fn ensure_built(&mut self, source: &str, path: Option<&Path>) -> bool {
+ !self.is_stale(source.split('\n')) || self.assemble(source, path)
+ }
+
+ fn write_outputs(&mut self, out: &AsmOutput, source: &str, path: &Path) {
+ let res = std::fs::write(path.with_extension("lst"), out.listing(source))
+ .and_then(|_| std::fs::write(path.with_extension("hex"), out.intel_hex()));
+ if let Err(e) = res {
+ self.status = format!("assembled, but writing .lst/.hex failed: {e}");
+ }
+ }
+
+ // ---- Breakpoints ----
+
+ pub fn toggle_breakpoint(&mut self, line: usize) {
+ if !self.breakpoints.remove(&line) {
+ self.breakpoints.insert(line);
+ }
+ }
+
+ pub fn bp_addrs(&self) -> HashSet {
+ let Some(b) = &self.build else {
+ return HashSet::new();
+ };
+ self.breakpoints
+ .iter()
+ .filter_map(|&l| b.line_addr(l))
+ .collect()
+ }
+
+ // ---- Execution ----
+
+ pub fn snapshot(&mut self) {
+ self.prev_iram = self.sim.iram;
+ self.prev_sfr = self.sim.sfr;
+ }
+
+ /// Source line of the instruction at the PC.
+ pub fn pc_line(&self) -> Option {
+ self.build.as_ref()?.addr_to_line.get(&self.sim.pc).copied()
+ }
+
+ /// Stops running and describes why in `status`.
+ pub fn report(&mut self, stop: Stop) {
+ self.running = false;
+ self.status = match stop {
+ Stop::Breakpoint(pc) => format!("breakpoint at {pc:04X}h"),
+ Stop::ReservedOpcode { pc, opcode } => {
+ format!("reserved opcode {opcode:02X}h at {pc:04X}h — stopped")
+ }
+ Stop::PowerDown => "CPU in power-down mode (PCON.PD) — reset to continue".into(),
+ Stop::Target | Stop::Budget => format!("stopped at {:04X}h", self.sim.pc),
+ };
+ }
+
+ fn step_with(&mut self, f: impl FnOnce(&mut Sim, &HashSet) -> Stop) {
+ self.running = false;
+ self.snapshot();
+ let bps = self.bp_addrs();
+ match f(&mut self.sim, &bps) {
+ Stop::Target => self.status = format!("PC = {:04X}h", self.sim.pc),
+ s => self.report(s),
+ }
+ }
+
+ pub fn step_into(&mut self) {
+ self.step_with(|s, _| match s.step() {
+ Ok(()) => Stop::Target,
+ Err(e) => e,
+ });
+ }
+
+ pub fn step_over(&mut self) {
+ self.step_with(|s, b| s.step_over(STEP_BUDGET, b));
+ }
+
+ pub fn step_out(&mut self) {
+ self.step_with(|s, b| s.step_out(STEP_BUDGET, b));
+ }
+
+ /// Runs until the first instruction of `line`, or a breakpoint.
+ /// Returns false if the line holds no code.
+ pub fn run_to_line(&mut self, line: usize) -> bool {
+ let Some(target) = self.build.as_ref().and_then(|b| b.line_addr(line)) else {
+ self.status = "no code on that line".into();
+ return false;
+ };
+ self.step_with(|s, bps| {
+ let mut bps = bps.clone();
+ bps.insert(target);
+ match s.run(STEP_BUDGET, &bps, true) {
+ Stop::Breakpoint(pc) if pc == target => Stop::Target,
+ other => other,
+ }
+ });
+ true
+ }
+
+ /// Starts free running; `tick` then advances the program. Needs a build.
+ pub fn start(&mut self) {
+ if self.build.is_none() {
+ return;
+ }
+ self.running = true;
+ self.resume = true;
+ self.status = "running…".into();
+ }
+
+ pub fn pause(&mut self) {
+ self.running = false;
+ self.status = format!("paused at {:04X}h", self.sim.pc);
+ }
+
+ /// Runs one chunk of `SPEEDS[speed]` instructions if running. Front ends
+ /// call this every ~33 ms.
+ pub fn tick(&mut self) {
+ if !self.running {
+ return;
+ }
+ self.snapshot();
+ let bps = self.bp_addrs();
+ let resume = std::mem::take(&mut self.resume);
+ match self.sim.run(SPEEDS[self.speed], &bps, resume) {
+ Stop::Budget => {}
+ s => self.report(s),
+ }
+ }
+
+ pub fn reset(&mut self) {
+ self.sim.reset();
+ self.running = false;
+ self.snapshot();
+ self.status = "reset".into();
+ }
+
+ /// Writes `value` at `addr` in `space`. Returns false if out of range.
+ pub fn poke(&mut self, space: MemSpace, addr: u32, value: u8) -> bool {
+ let ok = match space {
+ MemSpace::Iram if addr <= 0xFF => {
+ self.sim.iram[addr as usize] = value;
+ true
+ }
+ MemSpace::Sfr if (0x80..=0xFF).contains(&addr) => {
+ self.sim.set_sfr(addr as u8, value);
+ true
+ }
+ MemSpace::Xram if addr <= 0xFFFF => {
+ self.sim.xram[addr as usize] = value;
+ true
+ }
+ MemSpace::Code if addr <= 0xFFFF => {
+ self.sim.code[addr as usize] = value;
+ true
+ }
+ _ => false,
+ };
+ self.status = if ok {
+ format!("wrote {value:02X}h at {addr:X}h")
+ } else {
+ "address out of range".into()
+ };
+ ok
+ }
+
+ /// Simulated time since reset at `clock_mhz` (12 clocks per machine cycle).
+ pub fn elapsed(&self) -> String {
+ let micros = self.sim.cycles as f64 * 12.0 / self.clock_mhz;
+ if micros >= 1_000_000.0 {
+ format!("{:.3} s", micros / 1e6)
+ } else if micros >= 1000.0 {
+ format!("{:.3} ms", micros / 1e3)
+ } else {
+ format!("{micros:.2} µs")
+ }
+ }
+}
+
+/// Name of the interrupt source served at vector `v`.
+pub fn vector_name(v: u16) -> &'static str {
+ match v {
+ 0x03 => "INT0",
+ 0x0B => "T0",
+ 0x13 => "INT1",
+ 0x1B => "T1",
+ 0x23 => "UART",
+ _ => "?",
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{MemSpace, Session};
+
+ const PROG: &str = "\
+ ORG 0
+ LJMP main
+ ORG 30h
+main: MOV R0,#0
+loop: ACALL bump
+ SJMP loop
+bump: INC R0
+ NOP
+ RET
+ END";
+
+ fn session() -> Session {
+ let mut s = Session::new(12.0);
+ assert!(s.assemble(PROG, None), "{}", s.status);
+ s
+ }
+
+ #[test]
+ fn breakpoints_steps_and_run_to_line() {
+ let mut s = session();
+ s.toggle_breakpoint(6); // bump: INC R0
+ s.start();
+ s.tick();
+ assert!(!s.running);
+ assert_eq!(s.pc_line(), Some(6));
+ assert_eq!(s.status, format!("breakpoint at {:04X}h", s.sim.pc));
+
+ s.step_into(); // INC R0
+ assert_eq!(s.sim.reg(0), 1);
+ assert_eq!(s.pc_line(), Some(7));
+ s.step_out(); // back after ACALL
+ assert_eq!(s.pc_line(), Some(5));
+
+ s.toggle_breakpoint(6);
+ s.step_into(); // SJMP loop
+ assert_eq!(s.pc_line(), Some(4));
+ s.step_over(); // whole call
+ assert_eq!((s.pc_line(), s.sim.reg(0)), (Some(5), 2));
+
+ assert!(s.run_to_line(7));
+ assert_eq!((s.pc_line(), s.sim.reg(0)), (Some(7), 3));
+ assert!(!s.run_to_line(0)); // ORG: no code
+ }
+
+ #[test]
+ fn staleness_errors_and_poke() {
+ let mut s = session();
+ assert!(!s.is_stale(PROG.split('\n')));
+ let edited = PROG.replace("NOP", "NOP\n NOP");
+ assert!(s.is_stale(edited.split('\n')));
+ assert!(s.ensure_built(&edited, None));
+ assert!(!s.is_stale(edited.split('\n')));
+
+ let bad = " MOV A,\n FOO\n";
+ assert!(!s.assemble(bad, None));
+ assert_eq!(s.diagnostics_for(bad).len(), 2);
+ assert!(s.diagnostics_for(PROG).is_empty());
+ assert!(s.build.is_some(), "a failed build keeps the last good one");
+
+ assert!(s.poke(MemSpace::Iram, 0x30, 0xAB));
+ assert_eq!(s.sim.iram[0x30], 0xAB);
+ assert!(s.poke(MemSpace::Sfr, 0x90, 0x0F));
+ assert!(!s.poke(MemSpace::Sfr, 0x20, 1));
+ assert_eq!(s.status, "address out of range");
+ }
+}
diff --git a/src/sfr.rs b/crates/bench51-core/src/sfr.rs
similarity index 100%
rename from src/sfr.rs
rename to crates/bench51-core/src/sfr.rs
diff --git a/src/sim/cpu.rs b/crates/bench51-core/src/sim/cpu.rs
similarity index 100%
rename from src/sim/cpu.rs
rename to crates/bench51-core/src/sim/cpu.rs
diff --git a/src/sim/disasm.rs b/crates/bench51-core/src/sim/disasm.rs
similarity index 100%
rename from src/sim/disasm.rs
rename to crates/bench51-core/src/sim/disasm.rs
diff --git a/src/sim/mod.rs b/crates/bench51-core/src/sim/mod.rs
similarity index 96%
rename from src/sim/mod.rs
rename to crates/bench51-core/src/sim/mod.rs
index b8f734f..a990368 100644
--- a/src/sim/mod.rs
+++ b/crates/bench51-core/src/sim/mod.rs
@@ -385,7 +385,7 @@ mod example_tests {
#[test]
fn serial_hello_greets_and_echoes() {
- let mut s = load(include_str!("../../examples/serial_hello.asm"));
+ let mut s = load(include_str!("../../../../examples/serial_hello.asm"));
steps(&mut s, 60_000);
assert_eq!(
String::from_utf8_lossy(&s.uart.tx_log),
@@ -398,7 +398,7 @@ mod example_tests {
#[test]
fn timer_irq_ticks() {
- let mut s = load(include_str!("../../examples/timer_irq.asm"));
+ let mut s = load(include_str!("../../../../examples/timer_irq.asm"));
steps(&mut s, 5_000);
// ~10000 cycles at one interrupt per 1000 cycles.
assert!((3..=10).contains(&s.reg(7)), "R7 = {}", s.reg(7));
@@ -406,7 +406,7 @@ mod example_tests {
#[test]
fn button_counts_edges_while_idle() {
- let mut s = load(include_str!("../../examples/button_int0.asm"));
+ let mut s = load(include_str!("../../../../examples/button_int0.asm"));
steps(&mut s, 20);
assert!(s.idle);
for _ in 0..3 {
@@ -420,10 +420,10 @@ mod example_tests {
#[test]
fn bcd_and_lookup() {
- let mut s = load(include_str!("../../examples/bcd_add.asm"));
+ let mut s = load(include_str!("../../../../examples/bcd_add.asm"));
steps(&mut s, 20);
assert_eq!((s.iram[0x31], s.iram[0x30]), (0x69, 0x12));
- let mut s = load(include_str!("../../examples/lookup_movc.asm"));
+ let mut s = load(include_str!("../../../../examples/lookup_movc.asm"));
steps(&mut s, 3 + 4 * 5 + 3); // setup, digits 0-3, then up to MOV P2,A
assert_eq!(s.sfr(crate::sfr::P2), 0x66); // digit 4
}
diff --git a/src/sim/periph.rs b/crates/bench51-core/src/sim/periph.rs
similarity index 100%
rename from src/sim/periph.rs
rename to crates/bench51-core/src/sim/periph.rs
diff --git a/crates/bench51-core/src/syntax.rs b/crates/bench51-core/src/syntax.rs
new file mode 100644
index 0000000..2e7b37e
--- /dev/null
+++ b/crates/bench51-core/src/syntax.rs
@@ -0,0 +1,192 @@
+//! Minimal 8051 assembly tokenizer for syntax highlighting.
+
+use std::ops::Range;
+
+use crate::{isa, sfr};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Tok {
+ /// Whitespace, punctuation and identifiers without a special meaning.
+ Plain,
+ Comment,
+ Str,
+ /// A label definition (`name:` at the start of a line).
+ Label,
+ Mnemonic,
+ /// Directives and expression operators (`ORG`, `DB`, `HIGH`, `MOD`, …).
+ Directive,
+ Register,
+ /// Predefined SFR and bit names.
+ Sfr,
+ Number,
+}
+
+fn is_directive(w: &str) -> bool {
+ matches!(
+ w,
+ "ORG"
+ | "DB"
+ | "DW"
+ | "DS"
+ | "END"
+ | "EQU"
+ | "SET"
+ | "BIT"
+ | "DATA"
+ | "IDATA"
+ | "XDATA"
+ | "CODE"
+ | "CSEG"
+ | "XSEG"
+ | "DSEG"
+ | "AT"
+ | "USING"
+ | "NAME"
+ | "BYTE"
+ | "WORD"
+ )
+}
+
+fn word_kind(w: &str, first_word: bool) -> Tok {
+ let u = w.to_ascii_uppercase();
+ let reg = matches!(u.as_str(), "A" | "AB" | "C" | "DPTR" | "PC")
+ || (u.len() == 2
+ && u.starts_with('R')
+ && u.as_bytes()[1].is_ascii_digit()
+ && u.as_bytes()[1] < b'8');
+ if reg {
+ Tok::Register
+ } else if is_directive(&u) {
+ Tok::Directive
+ } else if first_word && isa::is_mnemonic(&u) {
+ Tok::Mnemonic
+ } else if sfr::SFRS.iter().chain(sfr::BITS).any(|(n, _)| *n == u) {
+ Tok::Sfr
+ } else if matches!(
+ u.as_str(),
+ "HIGH" | "LOW" | "MOD" | "AND" | "OR" | "XOR" | "NOT" | "SHL" | "SHR"
+ ) {
+ Tok::Directive
+ } else {
+ Tok::Plain
+ }
+}
+
+/// Splits a source line into classified byte ranges that together cover
+/// the whole line.
+pub fn tokens(line: &str) -> Vec<(Range, Tok)> {
+ let b = line.as_bytes();
+ let n = b.len();
+ let mut out = Vec::new();
+ let mut i = 0;
+ let mut seen_word = false;
+ while i < n {
+ let c = b[i];
+ let start = i;
+ let tok = if c == b';' {
+ i = n;
+ Tok::Comment
+ } else if c == b'\'' || c == b'"' {
+ i += 1;
+ while i < n && b[i] != c {
+ i += 1;
+ }
+ i = (i + 1).min(n);
+ Tok::Str
+ } else if c.is_ascii_alphabetic() || c == b'_' || c == b'?' {
+ while i < n && (b[i].is_ascii_alphanumeric() || b[i] == b'_' || b[i] == b'?') {
+ i += 1;
+ }
+ if !seen_word && b.get(i) == Some(&b':') {
+ Tok::Label
+ } else {
+ let t = word_kind(&line[start..i], !seen_word);
+ seen_word = true;
+ t
+ }
+ } else if c.is_ascii_digit() || c == b'#' || c == b'$' {
+ i += 1;
+ while i < n && b[i].is_ascii_alphanumeric() {
+ i += 1;
+ }
+ Tok::Number
+ } else {
+ // Non-ASCII bytes land here too, so ranges stay on char boundaries.
+ while i < n && !(b[i].is_ascii_alphanumeric() || b"_?;'\"#$".contains(&b[i])) {
+ i += 1;
+ }
+ Tok::Plain
+ };
+ out.push((start..i, tok));
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{Tok, tokens};
+
+ fn kinds(line: &str) -> Vec<(&str, Tok)> {
+ tokens(line)
+ .into_iter()
+ .filter(|(_, t)| *t != Tok::Plain)
+ .map(|(r, t)| (&line[r], t))
+ .collect()
+ }
+
+ #[test]
+ fn classifies_an_instruction_line() {
+ assert_eq!(
+ kinds("main: MOV TMOD,#20h ; timer 1"),
+ vec![
+ ("main", Tok::Label),
+ ("MOV", Tok::Mnemonic),
+ ("TMOD", Tok::Sfr),
+ ("#20h", Tok::Number),
+ ("; timer 1", Tok::Comment),
+ ]
+ );
+ assert_eq!(
+ kinds(" mov a,r7"),
+ vec![
+ ("mov", Tok::Mnemonic),
+ ("a", Tok::Register),
+ ("r7", Tok::Register)
+ ]
+ );
+ }
+
+ #[test]
+ fn directives_strings_and_operators() {
+ assert_eq!(
+ kinds("msg: DB \"Hi; there\", HIGH(x) ; c"),
+ vec![
+ ("msg", Tok::Label),
+ ("DB", Tok::Directive),
+ ("\"Hi; there\"", Tok::Str),
+ ("HIGH", Tok::Directive),
+ ("; c", Tok::Comment),
+ ]
+ );
+ }
+
+ #[test]
+ fn ranges_cover_the_line_even_with_unicode() {
+ for line in [
+ "",
+ " ",
+ "x DB 'é', 1 ; µs → ok",
+ "\"unterminated",
+ "€€ MOV",
+ ] {
+ let t = tokens(line);
+ let mut pos = 0;
+ for (r, _) in &t {
+ assert_eq!(r.start, pos, "{line:?}");
+ assert!(line.is_char_boundary(r.end));
+ pos = r.end;
+ }
+ assert_eq!(pos, line.len());
+ }
+ }
+}
diff --git a/crates/bench51-gui/Cargo.toml b/crates/bench51-gui/Cargo.toml
new file mode 100644
index 0000000..5c27ddb
--- /dev/null
+++ b/crates/bench51-gui/Cargo.toml
@@ -0,0 +1,24 @@
+[package]
+name = "bench51-gui"
+version.workspace = true
+edition.workspace = true
+description = "A Keil µVision-style desktop IDE for the Intel 8051, built on bench51"
+
+[dependencies]
+bench51-core.workspace = true
+clap.workspace = true
+eframe = { version = "0.37", default-features = false, features = [
+ "accesskit",
+ "clipboard",
+ "default_fonts",
+ "persistence",
+ "wayland",
+ "wgpu",
+ "x11",
+] }
+egui_tiles = { version = "0.18", features = ["serde"] }
+rfd = "0.17"
+serde = { version = "1", features = ["derive"] }
+
+[lints]
+workspace = true
diff --git a/crates/bench51-gui/assets/bench51-gui.desktop b/crates/bench51-gui/assets/bench51-gui.desktop
new file mode 100644
index 0000000..7da85ab
--- /dev/null
+++ b/crates/bench51-gui/assets/bench51-gui.desktop
@@ -0,0 +1,12 @@
+[Desktop Entry]
+Type=Application
+Name=bench51
+GenericName=8051 IDE
+Comment=Intel 8051 assembler, simulator and debugger
+Exec=bench51-gui %F
+Icon=bench51-gui
+Terminal=false
+Categories=Development;IDE;Electronics;
+Keywords=8051;8052;MCS-51;assembler;simulator;debugger;keil;microcontroller;
+MimeType=text/x-asm;
+StartupWMClass=bench51-gui
diff --git a/crates/bench51-gui/assets/bench51-gui.svg b/crates/bench51-gui/assets/bench51-gui.svg
new file mode 100644
index 0000000..570177b
--- /dev/null
+++ b/crates/bench51-gui/assets/bench51-gui.svg
@@ -0,0 +1,31 @@
+
diff --git a/crates/bench51-gui/assets/fonts/Doto[ROND,wght].ttf b/crates/bench51-gui/assets/fonts/Doto[ROND,wght].ttf
new file mode 100644
index 0000000..ed8f0db
Binary files /dev/null and b/crates/bench51-gui/assets/fonts/Doto[ROND,wght].ttf differ
diff --git a/crates/bench51-gui/assets/fonts/OFL-Doto.txt b/crates/bench51-gui/assets/fonts/OFL-Doto.txt
new file mode 100644
index 0000000..e0b8ec1
--- /dev/null
+++ b/crates/bench51-gui/assets/fonts/OFL-Doto.txt
@@ -0,0 +1,93 @@
+Copyright 2024 The Doto Project Authors (https://github.com/oliverlalan/Doto)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://openfontlicense.org
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/crates/bench51-gui/assets/fonts/OFL-SpaceGrotesk.txt b/crates/bench51-gui/assets/fonts/OFL-SpaceGrotesk.txt
new file mode 100644
index 0000000..cb512b9
--- /dev/null
+++ b/crates/bench51-gui/assets/fonts/OFL-SpaceGrotesk.txt
@@ -0,0 +1,93 @@
+Copyright 2020 The Space Grotesk Project Authors (https://github.com/floriankarsten/space-grotesk)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/crates/bench51-gui/assets/fonts/OFL-SpaceMono.txt b/crates/bench51-gui/assets/fonts/OFL-SpaceMono.txt
new file mode 100644
index 0000000..a72b0a7
--- /dev/null
+++ b/crates/bench51-gui/assets/fonts/OFL-SpaceMono.txt
@@ -0,0 +1,93 @@
+Copyright 2016 The Space Mono Project Authors (https://github.com/googlefonts/spacemono)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/crates/bench51-gui/assets/fonts/SpaceGrotesk-Medium.ttf b/crates/bench51-gui/assets/fonts/SpaceGrotesk-Medium.ttf
new file mode 100644
index 0000000..341b633
Binary files /dev/null and b/crates/bench51-gui/assets/fonts/SpaceGrotesk-Medium.ttf differ
diff --git a/crates/bench51-gui/assets/fonts/SpaceGrotesk-Regular.ttf b/crates/bench51-gui/assets/fonts/SpaceGrotesk-Regular.ttf
new file mode 100644
index 0000000..46aa5da
Binary files /dev/null and b/crates/bench51-gui/assets/fonts/SpaceGrotesk-Regular.ttf differ
diff --git a/crates/bench51-gui/assets/fonts/SpaceMono-Bold.ttf b/crates/bench51-gui/assets/fonts/SpaceMono-Bold.ttf
new file mode 100644
index 0000000..2c4f268
Binary files /dev/null and b/crates/bench51-gui/assets/fonts/SpaceMono-Bold.ttf differ
diff --git a/crates/bench51-gui/assets/fonts/SpaceMono-Regular.ttf b/crates/bench51-gui/assets/fonts/SpaceMono-Regular.ttf
new file mode 100644
index 0000000..1cfa365
Binary files /dev/null and b/crates/bench51-gui/assets/fonts/SpaceMono-Regular.ttf differ
diff --git a/crates/bench51-gui/src/app.rs b/crates/bench51-gui/src/app.rs
new file mode 100644
index 0000000..43c9f17
--- /dev/null
+++ b/crates/bench51-gui/src/app.rs
@@ -0,0 +1,661 @@
+//! The application: window chrome around a tree of docked panes, the run
+//! loop, file handling, and every action the UI can ask for.
+
+use std::path::{Path, PathBuf};
+
+use bench51_core::files::{self, Loaded};
+use eframe::egui::{
+ self, CentralPanel, Context, Key, Modifiers, Panel, Shape, ThemePreference, Ui, ViewportCommand,
+};
+use egui_tiles::Tree;
+
+use crate::layout::{self, Pane, PaneBehavior};
+use crate::state::{Action, BuildTab, LogKind, LogLine, Modal, Mode, Prefs, State, ThemePref};
+use crate::theme::{self, palette};
+use crate::{chrome, modals};
+
+/// One simulation chunk, as in the TUI's frame loop.
+const TICK: f64 = 1.0 / 30.0;
+
+const SOURCE_EXTENSIONS: [&str; 4] = ["asm", "a51", "s", "src"];
+const HEX_EXTENSIONS: [&str; 2] = ["hex", "ihx"];
+
+const TEMPLATE: &str = "\
+; New 8051 program. F7 builds, Ctrl+F5 starts debugging, F11 steps.
+ ORG 0000h
+ LJMP main
+
+ ORG 0030h
+main: MOV A,#01h ; walking LED pattern on P1
+loop: MOV P1,A
+ RL A
+ SJMP loop
+
+ END
+";
+
+pub struct GuiApp {
+ st: State,
+ edit_tree: Tree,
+ debug_tree: Tree,
+ last_time: Option,
+ tick_debt: f64,
+ /// The user confirmed quitting with unsaved changes.
+ allow_close: bool,
+ title: String,
+}
+
+fn theme_preference(t: ThemePref) -> ThemePreference {
+ match t {
+ ThemePref::System => ThemePreference::System,
+ ThemePref::Dark => ThemePreference::Dark,
+ ThemePref::Light => ThemePreference::Light,
+ }
+}
+
+fn load_tree(
+ cc: &eframe::CreationContext<'_>,
+ key: &str,
+ default: fn() -> Tree,
+) -> Tree {
+ let mut tree = cc
+ .storage
+ .and_then(|s| eframe::get_value::>(s, key))
+ .filter(|t| t.tiles.find_pane(&Pane::Editor).is_some())
+ .unwrap_or_else(default);
+ // Panes added in newer versions are simply missing; nothing to fix up.
+ if tree.root.is_none() {
+ tree = default();
+ }
+ tree
+}
+
+impl GuiApp {
+ pub fn new(
+ cc: &eframe::CreationContext<'_>,
+ files: Vec,
+ clock: Option,
+ theme: Option,
+ ) -> Self {
+ let ctx = &cc.egui_ctx;
+ theme::install(ctx);
+ let mut prefs: Prefs = cc
+ .storage
+ .and_then(|s| eframe::get_value(s, "prefs"))
+ .unwrap_or_default();
+ if let Some(c) = clock {
+ prefs.clock_mhz = c;
+ }
+ if let Some(t) = theme {
+ prefs.theme = t;
+ }
+ prefs.speed = prefs.speed.min(bench51_core::session::SPEEDS.len() - 1);
+ ctx.set_theme(theme_preference(prefs.theme));
+ ctx.set_zoom_factor(prefs.zoom.clamp(0.5, 3.0));
+ let mut app = Self {
+ st: State::new(prefs),
+ edit_tree: load_tree(cc, "edit_layout", layout::edit_tree),
+ debug_tree: load_tree(cc, "debug_layout", layout::debug_tree),
+ last_time: None,
+ tick_debt: 0.0,
+ allow_close: false,
+ title: String::new(),
+ };
+ for f in files {
+ app.open_path(&f);
+ }
+ app
+ }
+
+ fn tree(&mut self) -> &mut Tree {
+ match self.st.mode {
+ Mode::Edit => &mut self.edit_tree,
+ Mode::Debug => &mut self.debug_tree,
+ }
+ }
+
+ // ---- Input ----
+
+ fn shortcuts(&mut self, ctx: &Context) {
+ if self.st.modal.is_some() {
+ return;
+ }
+ let cmd = Modifiers::COMMAND;
+ let cmd_shift = Modifiers::COMMAND | Modifiers::SHIFT;
+ let none = Modifiers::NONE;
+ let running = self.st.running();
+ let active = self.st.active;
+ // Most specific first: `consume_key` ignores extra Shift.
+ let table: [(Modifiers, Key, Action); 25] = [
+ (cmd_shift, Key::S, Action::SaveAs),
+ (cmd, Key::S, Action::Save),
+ (none, Key::F2, Action::Save),
+ (cmd, Key::N, Action::New),
+ (cmd, Key::O, Action::Open),
+ (cmd, Key::W, Action::Close(active)),
+ (cmd, Key::Q, Action::Quit),
+ (cmd, Key::F, Action::Find),
+ (none, Key::F1, Action::Modal(Modal::Shortcuts)),
+ (none, Key::F7, Action::Build),
+ (cmd, Key::F5, Action::ToggleDebug),
+ (none, Key::F4, Action::ToggleDebug),
+ (none, Key::F5, Action::RunPause),
+ (cmd, Key::F11, Action::StepOut),
+ (none, Key::F12, Action::StepOut),
+ (none, Key::F11, Action::StepInto),
+ (cmd, Key::F10, Action::RunToCursor),
+ (none, Key::F10, Action::StepOver),
+ (none, Key::F8, Action::RunToCursor),
+ (cmd_shift, Key::F9, Action::ClearBreakpoints),
+ (none, Key::F9, Action::ToggleBreakpoint),
+ (none, Key::F6, Action::Reset),
+ (cmd, Key::Plus, Action::Zoom(0.1)),
+ (cmd, Key::Minus, Action::Zoom(-0.1)),
+ (cmd, Key::Num0, Action::ZoomReset),
+ ];
+ ctx.input_mut(|i| {
+ for (mods, key, action) in table {
+ if i.consume_key(mods, key) {
+ self.st.actions.push(action);
+ }
+ }
+ if running && i.consume_key(none, Key::Escape) {
+ self.st.actions.push(Action::RunPause);
+ }
+ });
+ }
+
+ fn handle_drops(&mut self, ctx: &Context) {
+ let dropped: Vec = ctx.input(|i| {
+ i.raw
+ .dropped_files
+ .iter()
+ .map(|f| f.path().to_path_buf())
+ .filter(|p| !p.as_os_str().is_empty())
+ .collect()
+ });
+ for path in dropped {
+ self.open_path(&path);
+ }
+ }
+
+ fn handle_close(&mut self, ctx: &Context) {
+ if ctx.input(|i| i.viewport().close_requested())
+ && !self.allow_close
+ && self.st.docs.iter().any(|d| d.dirty())
+ {
+ ctx.send_viewport_cmd(ViewportCommand::CancelClose);
+ self.st.modal = Some(Modal::ConfirmQuit);
+ }
+ }
+
+ /// Advances the running program in fixed 33 ms chunks of wall time.
+ fn pace(&mut self, ctx: &Context) {
+ let now = ctx.input(|i| i.time);
+ let dt = self.last_time.map_or(0.0, |t| now - t);
+ self.last_time = Some(now);
+ let speed = self.st.prefs.speed;
+ let Some(doc) = self.st.doc_mut() else {
+ return;
+ };
+ doc.session.speed = speed;
+ if !doc.session.running {
+ self.tick_debt = 0.0;
+ return;
+ }
+ self.tick_debt = (self.tick_debt + dt).min(TICK * 3.0);
+ while self.tick_debt >= TICK && doc.session.running {
+ doc.session.tick();
+ self.tick_debt -= TICK;
+ }
+ if !doc.session.running || speed <= 2 {
+ doc.follow_pc = true;
+ }
+ if doc.session.running {
+ ctx.request_repaint();
+ }
+ }
+
+ // ---- Files ----
+
+ fn open_path(&mut self, path: &Path) {
+ let canon = path.canonicalize().ok();
+ if let Some(i) = self.st.docs.iter().position(|d| {
+ d.path.as_ref().and_then(|p| p.canonicalize().ok()) == canon && canon.is_some()
+ }) {
+ self.activate(i);
+ return;
+ }
+ // An untouched new document is replaced, as editors usually do.
+ if self.st.docs.len() == 1 {
+ let d = &self.st.docs[0];
+ if d.path.is_none() && d.label.is_none() && !d.dirty() && d.text == TEMPLATE {
+ self.st.docs.clear();
+ }
+ }
+ match files::load(path) {
+ Err(e) => {
+ self.st.log(LogKind::Error, e.clone());
+ if let Some(d) = self.st.doc_mut() {
+ d.session.status = e;
+ }
+ }
+ Ok(Loaded::Source(text)) => {
+ self.pause_active();
+ let doc = self.st.add_doc(Some(path.to_path_buf()), &text);
+ doc.session.status = format!("opened {}", path.display());
+ self.st.prefs.add_recent(path);
+ self.st
+ .log(LogKind::Info, format!("opened {}", path.display()));
+ }
+ Ok(Loaded::Hex { source, bytes }) => {
+ self.pause_active();
+ let name = path.file_name().map(|n| n.to_string_lossy().into_owned());
+ let doc = self.st.add_doc(None, &source);
+ doc.label = name;
+ // Not saved anywhere yet: Save asks for an .asm name.
+ doc.saved.clear();
+ self.st.prefs.add_recent(path);
+ self.build();
+ if let Some(d) = self.st.doc_mut() {
+ d.session.status = format!(
+ "loaded {} ({bytes} bytes) and disassembled it",
+ path.display()
+ );
+ }
+ }
+ }
+ }
+
+ fn start_dir(&self) -> Option {
+ self.st
+ .doc()
+ .and_then(|d| d.path.as_ref())
+ .and_then(|p| p.parent().map(Path::to_path_buf))
+ .or_else(|| {
+ self.st
+ .prefs
+ .recent
+ .first()
+ .and_then(|p| p.parent().map(Path::to_path_buf))
+ })
+ .or_else(|| std::env::current_dir().ok())
+ }
+
+ fn open_dialog(&mut self) {
+ let mut all: Vec<&str> = SOURCE_EXTENSIONS.to_vec();
+ all.extend(HEX_EXTENSIONS);
+ let mut dialog = rfd::FileDialog::new()
+ .set_title("Open")
+ .add_filter("8051 source or Intel HEX", &all)
+ .add_filter("8051 assembly", &SOURCE_EXTENSIONS)
+ .add_filter("Intel HEX", &HEX_EXTENSIONS)
+ .add_filter("All files", &["*"]);
+ if let Some(dir) = self.start_dir() {
+ dialog = dialog.set_directory(dir);
+ }
+ for path in dialog.pick_files().unwrap_or_default() {
+ self.open_path(&path);
+ }
+ }
+
+ fn save(&mut self, ask: bool) {
+ let dir = self.start_dir();
+ let Some(doc) = self.st.doc_mut() else {
+ return;
+ };
+ let path = match (&doc.path, ask) {
+ (Some(p), false) => Some(p.clone()),
+ _ => {
+ let name = doc.name();
+ let stem = name.rsplit_once('.').map_or(name.as_str(), |(s, _)| s);
+ let mut dialog = rfd::FileDialog::new()
+ .set_title("Save as")
+ .add_filter("8051 assembly", &SOURCE_EXTENSIONS)
+ .set_file_name(format!("{stem}.asm"));
+ if let Some(dir) = dir {
+ dialog = dialog.set_directory(dir);
+ }
+ dialog.save_file()
+ }
+ };
+ let Some(path) = path else {
+ return;
+ };
+ let mut contents = doc.text.clone();
+ if !contents.ends_with('\n') {
+ contents.push('\n');
+ }
+ match std::fs::write(&path, contents) {
+ Ok(()) => {
+ doc.saved = doc.text.clone();
+ doc.session.status = format!("saved {}", path.display());
+ doc.path = Some(path.clone());
+ doc.label = None;
+ self.st.prefs.add_recent(&path);
+ }
+ Err(e) => {
+ let msg = format!("cannot save {}: {e}", path.display());
+ doc.session.status = msg.clone();
+ self.st.log(LogKind::Error, msg);
+ }
+ }
+ }
+
+ fn close(&mut self, i: usize) {
+ if i >= self.st.docs.len() {
+ return;
+ }
+ self.st.docs.remove(i);
+ if self.st.active >= i && self.st.active > 0 {
+ self.st.active -= 1;
+ }
+ if self.st.docs.is_empty() {
+ self.st.mode = Mode::Edit;
+ self.st.active = 0;
+ }
+ }
+
+ fn pause_active(&mut self) {
+ if let Some(d) = self.st.doc_mut()
+ && d.session.running
+ {
+ d.session.pause();
+ }
+ }
+
+ fn activate(&mut self, i: usize) {
+ if i < self.st.docs.len() && i != self.st.active {
+ self.pause_active();
+ self.st.active = i;
+ }
+ }
+
+ // ---- Build & debug ----
+
+ /// Assembles the active document and reports Keil-style in the Build
+ /// Output. Returns whether it built without errors.
+ fn build(&mut self) -> bool {
+ let Some(doc) = self.st.docs.get_mut(self.st.active) else {
+ return false;
+ };
+ let (name, target, id) = (doc.name(), doc.target(), doc.id);
+ let ok = doc.session.assemble(&doc.text, doc.path.as_deref());
+ let mut lines = vec![
+ (LogKind::Info, format!("Build target '{target}'"), None),
+ (LogKind::Info, format!("assembling {name}..."), None),
+ ];
+ let out = &doc.session.last_asm.as_ref().unwrap().1;
+ if ok {
+ lines.push((
+ LogKind::Info,
+ format!("Program Size: code={} bytes", out.code_size()),
+ None,
+ ));
+ if doc.path.is_some() {
+ lines.push((
+ LogKind::Info,
+ format!("creating hex file from \"{target}\"..."),
+ None,
+ ));
+ }
+ if doc.session.status.contains("failed") {
+ lines.push((LogKind::Error, doc.session.status.clone(), None));
+ }
+ lines.push((LogKind::Ok, format!("\"{target}\" - 0 Error(s)"), None));
+ doc.follow_pc = true;
+ } else {
+ for d in &out.diagnostics {
+ lines.push((
+ LogKind::Error,
+ format!("{name}({}:{}): error: {}", d.line + 1, d.col + 1, d.msg),
+ Some((id, d.line, d.col)),
+ ));
+ }
+ lines.push((
+ LogKind::Error,
+ format!("\"{target}\" - {} Error(s)", out.diagnostics.len()),
+ None,
+ ));
+ let first = &out.diagnostics[0];
+ doc.goto = Some((first.line, first.col));
+ }
+ for (kind, text, target) in lines {
+ self.st.log.push(LogLine { text, kind, target });
+ }
+ self.st.log(LogKind::Info, "");
+ if !ok {
+ self.st.mode = Mode::Edit;
+ self.st.build_tab = BuildTab::Messages;
+ layout::show_pane(&mut self.edit_tree, Pane::Build);
+ }
+ ok
+ }
+
+ fn ensure_built(&mut self) -> bool {
+ match self.st.doc() {
+ None => false,
+ Some(d) if d.stale() => self.build(),
+ Some(_) => true,
+ }
+ }
+
+ /// Runs a debugger command on the active document, building first and
+ /// entering the debug layout, as Keil does.
+ fn debug_cmd(&mut self, f: impl FnOnce(&mut bench51_core::session::Session, (usize, usize))) {
+ if !self.ensure_built() {
+ return;
+ }
+ self.st.mode = Mode::Debug;
+ if let Some(doc) = self.st.doc_mut() {
+ f(&mut doc.session, doc.cursor);
+ doc.follow_pc = true;
+ }
+ }
+
+ fn apply(&mut self, ctx: &Context, action: Action) {
+ match action {
+ Action::New => {
+ self.pause_active();
+ self.st.add_doc(None, TEMPLATE);
+ }
+ Action::Open => self.open_dialog(),
+ Action::OpenPath(p) => self.open_path(&p),
+ Action::Save => self.save(false),
+ Action::SaveAs => self.save(true),
+ Action::Close(i) => {
+ if self.st.docs.get(i).is_some_and(|d| d.dirty()) {
+ self.st.modal = Some(Modal::ConfirmClose(i));
+ } else {
+ self.close(i);
+ }
+ }
+ Action::ForceClose(i) => self.close(i),
+ Action::Activate(i) => self.activate(i),
+ Action::Quit => ctx.send_viewport_cmd(ViewportCommand::Close),
+ Action::ForceQuit => {
+ self.allow_close = true;
+ ctx.send_viewport_cmd(ViewportCommand::Close);
+ }
+ Action::Build => {
+ if self.build() && self.st.mode == Mode::Edit {
+ self.st.build_tab = BuildTab::Messages;
+ }
+ }
+ Action::ToggleDebug => match self.st.mode {
+ Mode::Edit => {
+ if self.ensure_built() {
+ self.st.mode = Mode::Debug;
+ if let Some(d) = self.st.doc_mut() {
+ d.follow_pc = true;
+ }
+ }
+ }
+ Mode::Debug => {
+ self.pause_active();
+ self.st.mode = Mode::Edit;
+ }
+ },
+ Action::RunPause => {
+ if self.st.running() {
+ self.pause_active();
+ if let Some(d) = self.st.doc_mut() {
+ d.follow_pc = true;
+ }
+ } else {
+ self.debug_cmd(|s, _| s.start());
+ }
+ }
+ Action::StepInto => self.debug_cmd(|s, _| s.step_into()),
+ Action::StepOver => self.debug_cmd(|s, _| s.step_over()),
+ Action::StepOut => self.debug_cmd(|s, _| s.step_out()),
+ Action::RunToCursor => self.debug_cmd(|s, (line, _)| {
+ s.run_to_line(line);
+ }),
+ Action::Reset => {
+ if let Some(d) = self.st.doc_mut() {
+ d.session.reset();
+ d.follow_pc = true;
+ }
+ }
+ Action::ToggleBreakpoint => {
+ if let Some(d) = self.st.doc_mut() {
+ d.session.toggle_breakpoint(d.cursor.0);
+ }
+ }
+ Action::ClearBreakpoints => {
+ if let Some(d) = self.st.doc_mut() {
+ d.session.breakpoints.clear();
+ d.session.status = "all breakpoints removed".into();
+ }
+ }
+ Action::SetSpeed(i) => self.st.prefs.speed = i,
+ Action::SetClock(mhz) => {
+ self.st.prefs.clock_mhz = mhz;
+ for d in &mut self.st.docs {
+ d.session.clock_mhz = mhz;
+ }
+ }
+ Action::Goto { doc, line, col } => {
+ if let Some(i) = self.st.docs.iter().position(|d| d.id == doc) {
+ self.activate(i);
+ self.st.docs[i].goto = Some((line, col));
+ layout::show_pane(self.tree(), Pane::Editor);
+ }
+ }
+ Action::ShowPane(p) => layout::show_pane(self.tree(), p),
+ Action::ResetLayout => {
+ *self.tree() = match self.st.mode {
+ Mode::Edit => layout::edit_tree(),
+ Mode::Debug => layout::debug_tree(),
+ }
+ }
+ Action::SetTheme(t) => {
+ self.st.prefs.theme = t;
+ ctx.set_theme(theme_preference(t));
+ }
+ Action::Zoom(d) => ctx.set_zoom_factor((ctx.zoom_factor() + d).clamp(0.5, 3.0)),
+ Action::ZoomReset => ctx.set_zoom_factor(1.0),
+ Action::Find => {
+ if self.st.doc().is_some() {
+ self.st.find.open = true;
+ self.st.find.focus = true;
+ }
+ }
+ Action::Modal(m) => self.st.modal = Some(m),
+ }
+ }
+
+ fn update_title(&mut self, ctx: &Context) {
+ let title = match self.st.doc() {
+ Some(d) => format!(
+ "{}{} — bench51",
+ d.name(),
+ if d.dirty() { " •" } else { "" }
+ ),
+ None => "bench51".to_string(),
+ };
+ if title != self.title {
+ ctx.send_viewport_cmd(ViewportCommand::Title(title.clone()));
+ self.title = title;
+ }
+ }
+}
+
+impl eframe::App for GuiApp {
+ fn ui(&mut self, ui: &mut Ui, _frame: &mut eframe::Frame) {
+ let ctx = ui.ctx().clone();
+ let p = palette(&ctx);
+ self.shortcuts(&ctx);
+ self.handle_drops(&ctx);
+ self.handle_close(&ctx);
+ self.pace(&ctx);
+ self.st.prefs.zoom = ctx.zoom_factor();
+
+ let bar = |top: i8, bottom: i8| {
+ egui::Frame::NONE.fill(p.black).inner_margin(egui::Margin {
+ left: 10,
+ right: 10,
+ top,
+ bottom,
+ })
+ };
+ Panel::top("menu")
+ .frame(bar(4, 0))
+ .show_separator_line(false)
+ .show(ui, |ui| chrome::menu_bar(ui, &mut self.st));
+ Panel::top("toolbar")
+ .frame(bar(4, 6))
+ .show_separator_line(false)
+ .show(ui, |ui| chrome::toolbar(ui, &mut self.st));
+ Panel::bottom("status")
+ .frame(bar(6, 6))
+ .show_separator_line(false)
+ .show(ui, |ui| chrome::status_bar(ui, &self.st));
+
+ CentralPanel::default()
+ .frame(
+ egui::Frame::NONE
+ .fill(p.black)
+ .inner_margin(egui::Margin::symmetric(6, 0)),
+ )
+ .show(ui, |ui| {
+ let tree = match self.st.mode {
+ Mode::Edit => &mut self.edit_tree,
+ Mode::Debug => &mut self.debug_tree,
+ };
+ let cards = ui.painter().add(Shape::Noop);
+ let editor_tile = tree.tiles.find_pane(&Pane::Editor);
+ let mut behavior = PaneBehavior {
+ st: &mut self.st,
+ editor_tile,
+ };
+ tree.ui(&mut behavior, ui);
+ ui.painter()
+ .set(cards, Shape::Vec(layout::card_shapes(tree, p.surface)));
+ });
+
+ modals::show(&ctx, &mut self.st);
+ for action in std::mem::take(&mut self.st.actions) {
+ self.apply(&ctx, action);
+ }
+ self.update_title(&ctx);
+ }
+
+ fn save(&mut self, storage: &mut dyn eframe::Storage) {
+ eframe::set_value(storage, "prefs", &self.st.prefs);
+ eframe::set_value(storage, "edit_layout", &self.edit_tree);
+ eframe::set_value(storage, "debug_layout", &self.debug_tree);
+ }
+
+ /// Layouts, theme and zoom are saved above. egui's own memory would
+ /// restore scroll positions keyed by document number onto whatever file
+ /// gets that number next session.
+ fn persist_egui_memory(&self) -> bool {
+ false
+ }
+
+ fn clear_color(&self, visuals: &egui::Visuals) -> [f32; 4] {
+ visuals.panel_fill.to_normalized_gamma_f32()
+ }
+}
diff --git a/crates/bench51-gui/src/chrome.rs b/crates/bench51-gui/src/chrome.rs
new file mode 100644
index 0000000..47b8325
--- /dev/null
+++ b/crates/bench51-gui/src/chrome.rs
@@ -0,0 +1,421 @@
+//! Window chrome: menu bar, toolbar and status bar. They sit directly on
+//! the page, without boxes.
+
+use bench51_core::session::SPEEDS;
+use eframe::egui::{self, Align, Button, FontId, Layout, RichText, Stroke, Ui};
+
+use crate::icons::Icon;
+use crate::layout::Pane;
+use crate::state::{Action, Modal, Mode, State, ThemePref};
+use crate::theme::{ACCENT, LABEL, LABEL_TRACKING, palette};
+use crate::widgets;
+
+fn item(ui: &mut Ui, text: &str, shortcut: &str) -> bool {
+ let p = palette(ui.ctx());
+ let label = RichText::new(text.to_uppercase())
+ .font(FontId::monospace(12.0))
+ .extra_letter_spacing(0.5)
+ .color(p.text_primary);
+ let mut b = Button::new(label).min_size(egui::vec2(240.0, 24.0));
+ if !shortcut.is_empty() {
+ b = b.shortcut_text(
+ RichText::new(shortcut)
+ .font(FontId::monospace(11.0))
+ .color(p.text_disabled),
+ );
+ }
+ ui.add(b).clicked()
+}
+
+fn check(ui: &mut Ui, text: &str, on: bool) -> bool {
+ let mark = if on { "● " } else { " " };
+ item(ui, &format!("{mark}{text}"), "")
+}
+
+fn title(ui: &Ui, text: &str) -> RichText {
+ let p = palette(ui.ctx());
+ RichText::new(text.to_uppercase())
+ .font(FontId::monospace(LABEL))
+ .extra_letter_spacing(LABEL_TRACKING)
+ .color(p.text_secondary)
+}
+
+pub fn menu_bar(ui: &mut Ui, st: &mut State) {
+ let mut acts = Vec::new();
+ let has_doc = st.doc().is_some();
+ egui::MenuBar::new().ui(ui, |ui| {
+ ui.menu_button(title(ui, "File"), |ui| {
+ if item(ui, "New", "Ctrl+N") {
+ acts.push(Action::New);
+ }
+ if item(ui, "Open…", "Ctrl+O") {
+ acts.push(Action::Open);
+ }
+ ui.menu_button(title(ui, "Open recent"), |ui| {
+ if st.prefs.recent.is_empty() {
+ ui.label(palette(ui.ctx()).label("none"));
+ }
+ for path in &st.prefs.recent {
+ let name = path.display().to_string();
+ if ui
+ .button(RichText::new(name).font(FontId::monospace(12.0)))
+ .clicked()
+ {
+ acts.push(Action::OpenPath(path.clone()));
+ }
+ }
+ });
+ ui.separator();
+ if item(ui, "Save", "Ctrl+S") {
+ acts.push(Action::Save);
+ }
+ if item(ui, "Save as…", "Ctrl+Shift+S") {
+ acts.push(Action::SaveAs);
+ }
+ if has_doc && item(ui, "Close file", "Ctrl+W") {
+ acts.push(Action::Close(st.active));
+ }
+ ui.separator();
+ if item(ui, "Quit", "Ctrl+Q") {
+ acts.push(Action::Quit);
+ }
+ });
+ ui.menu_button(title(ui, "Edit"), |ui| {
+ if item(ui, "Find…", "Ctrl+F") {
+ acts.push(Action::Find);
+ }
+ ui.separator();
+ if item(ui, "Toggle breakpoint", "F9") {
+ acts.push(Action::ToggleBreakpoint);
+ }
+ if item(ui, "Kill all breakpoints", "Ctrl+Shift+F9") {
+ acts.push(Action::ClearBreakpoints);
+ }
+ });
+ ui.menu_button(title(ui, "View"), |ui| {
+ for pane in Pane::ALL {
+ if item(ui, pane.title(), "") {
+ acts.push(Action::ShowPane(pane));
+ }
+ }
+ ui.separator();
+ ui.menu_button(title(ui, "Theme"), |ui| {
+ for (t, name) in [
+ (ThemePref::System, "System"),
+ (ThemePref::Dark, "Dark"),
+ (ThemePref::Light, "Light"),
+ ] {
+ if check(ui, name, st.prefs.theme == t) {
+ acts.push(Action::SetTheme(t));
+ }
+ }
+ });
+ if item(ui, "Zoom in", "Ctrl++") {
+ acts.push(Action::Zoom(0.1));
+ }
+ if item(ui, "Zoom out", "Ctrl+-") {
+ acts.push(Action::Zoom(-0.1));
+ }
+ if item(ui, "Actual size", "Ctrl+0") {
+ acts.push(Action::ZoomReset);
+ }
+ ui.separator();
+ if item(ui, "Reset layout", "") {
+ acts.push(Action::ResetLayout);
+ }
+ });
+ ui.menu_button(title(ui, "Project"), |ui| {
+ if item(ui, "Build target", "F7") {
+ acts.push(Action::Build);
+ }
+ ui.separator();
+ if item(ui, "Options for target…", "") {
+ acts.push(Action::Modal(Modal::Options(
+ st.prefs.clock_mhz.to_string(),
+ )));
+ }
+ });
+ ui.menu_button(title(ui, "Debug"), |ui| {
+ let session = if st.mode == Mode::Debug {
+ "Stop debug session"
+ } else {
+ "Start debug session"
+ };
+ if item(ui, session, "Ctrl+F5") {
+ acts.push(Action::ToggleDebug);
+ }
+ ui.separator();
+ let run = if st.running() { "Stop" } else { "Run" };
+ if item(ui, run, "F5") {
+ acts.push(Action::RunPause);
+ }
+ if item(ui, "Step into", "F11") {
+ acts.push(Action::StepInto);
+ }
+ if item(ui, "Step over", "F10") {
+ acts.push(Action::StepOver);
+ }
+ if item(ui, "Step out", "Ctrl+F11") {
+ acts.push(Action::StepOut);
+ }
+ if item(ui, "Run to cursor line", "Ctrl+F10") {
+ acts.push(Action::RunToCursor);
+ }
+ if item(ui, "Reset CPU", "F6") {
+ acts.push(Action::Reset);
+ }
+ ui.separator();
+ ui.menu_button(title(ui, "Speed"), |ui| {
+ for (i, n) in SPEEDS.iter().enumerate() {
+ if check(ui, &format!("{n} / tick"), st.prefs.speed == i) {
+ acts.push(Action::SetSpeed(i));
+ }
+ }
+ });
+ });
+ ui.menu_button(title(ui, "Peripherals"), |ui| {
+ for (pane, name) in [
+ (Pane::Ports, "I/O ports"),
+ (Pane::Timers, "Timers"),
+ (Pane::Interrupts, "Interrupts"),
+ (Pane::Serial, "Serial (UART #1)"),
+ ] {
+ if item(ui, name, "") {
+ acts.push(Action::ShowPane(pane));
+ }
+ }
+ });
+ ui.menu_button(title(ui, "Help"), |ui| {
+ if item(ui, "Keyboard shortcuts", "F1") {
+ acts.push(Action::Modal(Modal::Shortcuts));
+ }
+ if item(ui, "About bench51", "") {
+ acts.push(Action::Modal(Modal::About));
+ }
+ });
+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
+ let p = palette(ui.ctx());
+ ui.label(title(ui, "bench51").color(p.text_disabled));
+ });
+ });
+ st.actions.extend(acts);
+}
+
+pub fn toolbar(ui: &mut Ui, st: &mut State) {
+ let p = palette(ui.ctx());
+ let has_doc = st.doc().is_some();
+ let running = st.running();
+ let debug = st.mode == Mode::Debug;
+ let mut acts = Vec::new();
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 2.0;
+ let mut b = |ui: &mut Ui, icon, tip, enabled, on, act| {
+ if widgets::icon_button(ui, icon, tip, enabled, on).clicked() {
+ acts.push(act);
+ }
+ };
+ b(ui, Icon::New, "New file (Ctrl+N)", true, false, Action::New);
+ b(ui, Icon::Open, "Open (Ctrl+O)", true, false, Action::Open);
+ b(
+ ui,
+ Icon::Save,
+ "Save (Ctrl+S)",
+ has_doc,
+ false,
+ Action::Save,
+ );
+ ui.add_space(18.0);
+ b(
+ ui,
+ Icon::Build,
+ "Build target (F7)",
+ has_doc,
+ false,
+ Action::Build,
+ );
+ ui.add_space(18.0);
+ b(
+ ui,
+ Icon::Debug,
+ if debug {
+ "Stop debug session (Ctrl+F5)"
+ } else {
+ "Start debug session (Ctrl+F5)"
+ },
+ has_doc,
+ debug,
+ Action::ToggleDebug,
+ );
+ ui.add_space(18.0);
+ b(
+ ui,
+ Icon::Reset,
+ "Reset CPU (F6)",
+ has_doc,
+ false,
+ Action::Reset,
+ );
+ if running {
+ b(
+ ui,
+ Icon::Pause,
+ "Stop (F5)",
+ has_doc,
+ false,
+ Action::RunPause,
+ );
+ } else {
+ b(ui, Icon::Run, "Run (F5)", has_doc, false, Action::RunPause);
+ }
+ b(
+ ui,
+ Icon::StepInto,
+ "Step into (F11)",
+ has_doc,
+ false,
+ Action::StepInto,
+ );
+ b(
+ ui,
+ Icon::StepOver,
+ "Step over (F10)",
+ has_doc,
+ false,
+ Action::StepOver,
+ );
+ b(
+ ui,
+ Icon::StepOut,
+ "Step out (Ctrl+F11)",
+ has_doc,
+ false,
+ Action::StepOut,
+ );
+ b(
+ ui,
+ Icon::RunToCursor,
+ "Run to cursor line (Ctrl+F10)",
+ has_doc,
+ false,
+ Action::RunToCursor,
+ );
+ ui.add_space(18.0);
+ b(
+ ui,
+ Icon::Breakpoint,
+ "Toggle breakpoint (F9)",
+ has_doc,
+ false,
+ Action::ToggleBreakpoint,
+ );
+
+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
+ ui.spacing_mut().item_spacing.x = 10.0;
+ ui.add_space(6.0);
+ let speed = st.prefs.speed;
+ ui.label(
+ RichText::new(format!("{:>6} / TICK", SPEEDS[speed]))
+ .font(FontId::monospace(LABEL))
+ .color(p.text_secondary),
+ );
+ if let Some(i) = widgets::segment_bar(
+ ui,
+ 136.0,
+ 10.0,
+ SPEEDS.len(),
+ speed + 1,
+ p.text_display,
+ true,
+ ) {
+ acts.push(Action::SetSpeed(i));
+ }
+ ui.label(p.label("Speed"));
+ });
+ });
+ st.actions.extend(acts);
+}
+
+/// True for status messages that report a failure.
+fn is_error(msg: &str) -> bool {
+ let m = msg.to_ascii_lowercase();
+ [
+ "error(s)",
+ "cannot ",
+ "invalid ",
+ "failed",
+ "reserved opcode",
+ "out of range",
+ ]
+ .iter()
+ .any(|w| m.contains(w))
+}
+
+pub fn status_bar(ui: &mut Ui, st: &State) {
+ let p = palette(ui.ctx());
+ let text = |s: String| {
+ RichText::new(s.to_uppercase())
+ .font(FontId::monospace(LABEL))
+ .extra_letter_spacing(0.6)
+ };
+ ui.horizontal(|ui| {
+ ui.spacing_mut().item_spacing.x = 14.0;
+ let doc = st.doc();
+ let (state, live) = match doc {
+ None => ("no file", false),
+ Some(d) if d.session.running => ("running", true),
+ Some(d) if d.session.build.is_none() => ("not built", false),
+ Some(d) if d.stale() => ("source changed", false),
+ Some(_) if st.mode == Mode::Debug => ("stopped", false),
+ Some(_) => ("ready", false),
+ };
+ let mode = if st.mode == Mode::Debug {
+ "simulation"
+ } else {
+ "edit"
+ };
+ ui.label(text(mode.into()).color(p.text_disabled));
+ // Running: a dot that blinks in hard 2 Hz steps.
+ let (r, _) = ui.allocate_exact_size(egui::vec2(8.0, 8.0), egui::Sense::hover());
+ let on = !live || (ui.input(|i| i.time) * 4.0) as i64 % 2 == 0;
+ if live && on {
+ ui.painter().circle_filled(r.center(), 3.5, p.text_display);
+ } else {
+ ui.painter()
+ .circle_stroke(r.center(), 3.0, Stroke::new(1.0, p.text_disabled));
+ }
+ ui.label(text(format!("[{state}]")).color(if live {
+ p.text_display
+ } else {
+ p.text_secondary
+ }));
+ if let Some(d) = doc {
+ let msg = &d.session.status;
+ if !msg.is_empty() {
+ let color = if is_error(msg) {
+ ACCENT
+ } else {
+ p.text_primary
+ };
+ let shown = if is_error(msg) {
+ format!("[error: {msg}]")
+ } else {
+ msg.clone()
+ };
+ ui.label(text(shown).color(color));
+ }
+ }
+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
+ ui.label(text(format!("{} MHz", st.prefs.clock_mhz)).color(p.text_disabled));
+ if let Some(d) = doc {
+ if d.session.build.is_some() {
+ ui.label(text(format!("cyc {}", d.session.sim.cycles)).color(p.text_secondary));
+ ui.label(text(format!("t {}", d.session.elapsed())).color(p.text_secondary));
+ }
+ ui.label(
+ text(format!("l {} c {}", d.cursor.0 + 1, d.cursor.1 + 1))
+ .color(p.text_secondary),
+ );
+ }
+ });
+ });
+}
diff --git a/crates/bench51-gui/src/editor.rs b/crates/bench51-gui/src/editor.rs
new file mode 100644
index 0000000..8efc1b2
--- /dev/null
+++ b/crates/bench51-gui/src/editor.rs
@@ -0,0 +1,657 @@
+//! The code editor: document tabs, a find bar, syntax-highlighted text and
+//! a gutter with breakpoints, line numbers, addresses, errors and the PC.
+
+use std::collections::{HashMap, HashSet};
+
+use bench51_core::syntax::tokens;
+use eframe::egui::{
+ self, Align, Align2, Color32, CursorIcon, FontId, Id, Key, Layout, Modifiers, Rect, RichText,
+ Sense, Shape, Stroke, TextBuffer, TextFormat, Ui, Vec2,
+ cache::{ComputerMut, FrameCache},
+ pos2,
+ text::{CCursor, CCursorRange, LayoutJob},
+ text_edit::TextEditState,
+ vec2,
+};
+
+use crate::state::{Action, Document, Mode, State};
+use crate::theme::{self, ACCENT, BODY, DARK, LIGHT, WARNING, palette};
+use crate::widgets::{self, PillKind};
+
+const MARGIN: Vec2 = vec2(10.0, 8.0);
+
+pub fn show(ui: &mut Ui, st: &mut State) {
+ doc_tabs(ui, st);
+ if st.docs.is_empty() {
+ welcome(ui, st);
+ return;
+ }
+ if st.find.open {
+ find_bar(ui, st);
+ }
+ code(ui, st);
+}
+
+// ------------------------------------------------------------- tabs, find
+
+fn doc_tabs(ui: &mut Ui, st: &mut State) {
+ let p = palette(ui.ctx());
+ let height = 30.0;
+ let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover());
+ ui.painter().hline(
+ strip.x_range(),
+ strip.bottom() - 0.5,
+ Stroke::new(1.0, p.border),
+ );
+ let mut child = ui.new_child(
+ egui::UiBuilder::new()
+ .max_rect(strip.shrink2(vec2(6.0, 0.0)))
+ .layout(Layout::left_to_right(Align::Center)),
+ );
+ let ui = &mut child;
+ ui.spacing_mut().item_spacing.x = 0.0;
+ for (i, doc) in st.docs.iter().enumerate() {
+ let active = i == st.active;
+ let name = doc.name();
+ let galley =
+ ui.painter()
+ .layout_no_wrap(name, FontId::monospace(12.0), Color32::PLACEHOLDER);
+ let pad = 12.0;
+ let dirty_w = if doc.dirty() { 10.0 } else { 0.0 };
+ let w = galley.size().x + 2.0 * pad + dirty_w + 14.0;
+ let (rect, resp) = ui.allocate_exact_size(vec2(w, height), Sense::click());
+ let resp = resp.on_hover_cursor(CursorIcon::PointingHand);
+ let fg = if active {
+ p.text_display
+ } else if resp.hovered() {
+ p.text_secondary
+ } else {
+ p.text_disabled
+ };
+ let text_pos = Align2::LEFT_CENTER
+ .align_size_within_rect(galley.size(), rect.shrink2(vec2(pad, 0.0)))
+ .min;
+ let text_w = galley.size().x;
+ ui.painter().galley(text_pos, galley, fg);
+ if active {
+ ui.painter().hline(
+ text_pos.x..=text_pos.x + text_w,
+ rect.bottom() - 1.5,
+ Stroke::new(2.0, p.text_display),
+ );
+ }
+ if doc.dirty() {
+ ui.painter().circle_filled(
+ pos2(text_pos.x + text_w + 7.0, rect.center().y),
+ 2.5,
+ p.text_secondary,
+ );
+ }
+ let close =
+ Rect::from_center_size(pos2(rect.right() - pad, rect.center().y), Vec2::splat(12.0));
+ let close_resp = ui
+ .interact(close, Id::unique(("doc_close", doc.id)), Sense::click())
+ .on_hover_cursor(CursorIcon::PointingHand);
+ if resp.hovered() || close_resp.hovered() || active {
+ let c = if close_resp.hovered() {
+ p.text_display
+ } else {
+ p.text_disabled
+ };
+ let r = close.shrink(3.0);
+ let s = Stroke::new(1.2, c);
+ ui.painter()
+ .line_segment([r.left_top(), r.right_bottom()], s);
+ ui.painter()
+ .line_segment([r.right_top(), r.left_bottom()], s);
+ }
+ if close_resp.clicked() || resp.clicked_by(egui::PointerButton::Middle) {
+ st.actions.push(Action::Close(i));
+ } else if resp.clicked() {
+ st.actions.push(Action::Activate(i));
+ }
+ }
+ let plus = ui
+ .add(
+ egui::Button::new(
+ RichText::new("+")
+ .font(FontId::monospace(14.0))
+ .color(p.text_disabled),
+ )
+ .frame(false),
+ )
+ .on_hover_text("New file (Ctrl+N)");
+ if plus.clicked() {
+ st.actions.push(Action::New);
+ }
+ if st.mode == Mode::Debug {
+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
+ ui.add_space(8.0);
+ ui.label(p.label("Read-only while debugging").color(p.text_disabled));
+ });
+ }
+}
+
+fn find_bar(ui: &mut Ui, st: &mut State) {
+ let p = palette(ui.ctx());
+ let mut step = None;
+ let mut close = false;
+ ui.horizontal(|ui| {
+ ui.add_space(MARGIN.x);
+ ui.label(p.label("Find"));
+ let resp = widgets::underline_input(ui, &mut st.find.query, "text", 220.0);
+ if std::mem::take(&mut st.find.focus) {
+ resp.request_focus();
+ }
+ if resp.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) {
+ step = Some(!ui.input(|i| i.modifiers.shift));
+ resp.request_focus();
+ }
+ if resp.has_focus() && ui.input(|i| i.key_pressed(Key::Escape)) {
+ close = true;
+ }
+ let count = st
+ .doc()
+ .map_or(0, |d| find_all(&d.text, &st.find.query).len());
+ ui.label(p.label(format!("{count} found")).color(p.text_disabled));
+ if widgets::pill(ui, "Prev", PillKind::Ghost).clicked() {
+ step = Some(false);
+ }
+ if widgets::pill(ui, "Next", PillKind::Ghost).clicked() {
+ step = Some(true);
+ }
+ if widgets::pill(ui, "Close", PillKind::Ghost).clicked() {
+ close = true;
+ }
+ });
+ if let (Some(forward), Some(doc)) = (step, st.docs.get_mut(st.active)) {
+ find_step(doc, &st.find.query, forward);
+ }
+ if close {
+ st.find.open = false;
+ }
+}
+
+/// Byte ranges of case-insensitive matches of `query` in `text`.
+fn find_all(text: &str, query: &str) -> Vec<(usize, usize)> {
+ if query.is_empty() {
+ return Vec::new();
+ }
+ let hay = text.to_ascii_lowercase();
+ let needle = query.to_ascii_lowercase();
+ hay.match_indices(&needle)
+ .take(2000)
+ .map(|(i, m)| (i, i + m.len()))
+ .collect()
+}
+
+fn find_step(doc: &mut Document, query: &str, forward: bool) {
+ let matches = find_all(&doc.text, query);
+ if matches.is_empty() {
+ doc.find_hit = None;
+ return;
+ }
+ let here = char_to_byte(&doc.text, doc.cursor_char);
+ let hit = doc.find_hit.filter(|h| matches.contains(h));
+ let pick = if forward {
+ let from = hit.map_or(here, |h| h.0 + 1);
+ matches.iter().find(|m| m.0 >= from).or(matches.first())
+ } else {
+ let before = hit.map_or(here, |h| h.0);
+ matches
+ .iter()
+ .rev()
+ .find(|m| m.0 < before)
+ .or(matches.last())
+ };
+ if let Some(&(a, b)) = pick {
+ let ca = doc.text[..a].chars().count();
+ let cb = ca + doc.text[a..b].chars().count();
+ doc.select = Some((ca, cb));
+ doc.find_hit = Some((a, b));
+ }
+}
+
+// -------------------------------------------------------------- welcome
+
+fn welcome(ui: &mut Ui, st: &mut State) {
+ let p = palette(ui.ctx());
+ let rect = ui.available_rect_before_wrap();
+ let grid = if ui.visuals().dark_mode {
+ p.border
+ } else {
+ p.border_visible.gamma_multiply(0.5)
+ };
+ widgets::dot_grid(ui.painter(), rect, grid, 16.0);
+ let inner = rect.shrink2(vec2(56.0, 48.0));
+ ui.scope_builder(egui::UiBuilder::new().max_rect(inner), |ui| {
+ ui.add_space(24.0);
+ ui.label(p.hero("BENCH51", theme::HERO_XL));
+ ui.add_space(4.0);
+ ui.label(p.label("8051 assembler · simulator · debugger"));
+ ui.add_space(40.0);
+ ui.horizontal(|ui| {
+ if widgets::pill(ui, "New file", PillKind::Primary).clicked() {
+ st.actions.push(Action::New);
+ }
+ ui.add_space(8.0);
+ if widgets::pill(ui, "Open…", PillKind::Secondary).clicked() {
+ st.actions.push(Action::Open);
+ }
+ });
+ if !st.prefs.recent.is_empty() {
+ ui.add_space(48.0);
+ ui.label(p.label("Recent"));
+ ui.add_space(8.0);
+ for path in st.prefs.recent.clone() {
+ let name = path.file_name().map_or_else(
+ || path.display().to_string(),
+ |n| n.to_string_lossy().into(),
+ );
+ let dir = path
+ .parent()
+ .map(|d| d.display().to_string())
+ .unwrap_or_default();
+ ui.horizontal(|ui| {
+ let r = ui
+ .add(
+ egui::Label::new(
+ RichText::new(name)
+ .font(FontId::monospace(BODY))
+ .color(p.text_primary),
+ )
+ .sense(Sense::click()),
+ )
+ .on_hover_cursor(CursorIcon::PointingHand);
+ ui.label(
+ RichText::new(dir)
+ .font(FontId::monospace(12.0))
+ .color(p.text_disabled),
+ );
+ if r.clicked() {
+ st.actions.push(Action::OpenPath(path.clone()));
+ }
+ });
+ }
+ }
+ });
+}
+
+// ----------------------------------------------------------------- code
+
+#[derive(Default)]
+struct Highlighter;
+
+impl ComputerMut<(bool, &str), LayoutJob> for Highlighter {
+ fn compute(&mut self, (dark, text): (bool, &str)) -> LayoutJob {
+ highlight(text, dark)
+ }
+}
+
+type HighlightCache = FrameCache;
+
+/// Lays out `text` with the greyscale syntax palette. The job's text is
+/// exactly `text`, as `TextEdit` requires.
+pub fn highlight(text: &str, dark: bool) -> LayoutJob {
+ let p = if dark { &DARK } else { &LIGHT };
+ let font = FontId::monospace(BODY);
+ let bold = FontId::new(BODY, theme::mono_bold());
+ let mut job = LayoutJob::default();
+ job.wrap.max_width = f32::INFINITY;
+ for (i, line) in text.split('\n').enumerate() {
+ if i > 0 {
+ job.append("\n", 0.0, TextFormat::simple(font.clone(), p.text_primary));
+ }
+ for (r, tok) in tokens(line) {
+ let (color, strong) = p.syntax(tok);
+ let font_id = if strong { bold.clone() } else { font.clone() };
+ job.append(&line[r], 0.0, TextFormat::simple(font_id, color));
+ }
+ }
+ job
+}
+
+pub fn char_to_byte(text: &str, ci: usize) -> usize {
+ text.char_indices().nth(ci).map_or(text.len(), |(b, _)| b)
+}
+
+/// (line, column) of char index `ci`.
+fn line_col(text: &str, ci: usize) -> (usize, usize) {
+ let b = char_to_byte(text, ci);
+ let before = &text[..b];
+ let line = before.matches('\n').count();
+ let start = before.rfind('\n').map_or(0, |i| i + 1);
+ (line, before[start..].chars().count())
+}
+
+/// Char index of (line, column), clamped to the text.
+fn char_index(text: &str, line: usize, col: usize) -> usize {
+ let mut ci = 0;
+ for (i, l) in text.split('\n').enumerate() {
+ let n = l.chars().count();
+ if i == line {
+ return ci + col.min(n);
+ }
+ ci += n + 1;
+ }
+ text.chars().count()
+}
+
+/// Replaces the selection with spaces up to the next 8-column tab stop,
+/// matching the assembler listing.
+fn insert_tab(ctx: &egui::Context, id: Id, text: &mut String) {
+ let Some(mut state) = TextEditState::load(ctx, id) else {
+ return;
+ };
+ let Some(range) = state.cursor.char_range() else {
+ return;
+ };
+ let (a, b) = {
+ let (x, y) = (range.primary.index.0, range.secondary.index.0);
+ (x.min(y), x.max(y))
+ };
+ let (ba, bb) = (char_to_byte(text, a), char_to_byte(text, b));
+ let start = text[..ba].rfind('\n').map_or(0, |i| i + 1);
+ let col = text[start..ba].chars().count();
+ let n = 8 - col % 8;
+ text.replace_range(ba..bb, &" ".repeat(n));
+ state
+ .cursor
+ .set_char_range(Some(CCursorRange::one(CCursor::new(a + n))));
+ state.store(ctx, id);
+}
+
+/// What the gutter and backgrounds need, gathered before the text is
+/// borrowed by the `TextEdit`.
+struct Marks {
+ errors: HashMap,
+ breakpoints: HashSet,
+ pc_line: Option,
+ /// Code address of each line, shown while debugging.
+ addrs: Option>,
+}
+
+fn code(ui: &mut Ui, st: &mut State) {
+ let debug = st.mode == Mode::Debug;
+ let query = if st.find.open {
+ st.find.query.clone()
+ } else {
+ String::new()
+ };
+ let Some(doc) = st.docs.get_mut(st.active) else {
+ return;
+ };
+ let p = palette(ui.ctx());
+ let dark = ui.visuals().dark_mode;
+ let font = FontId::monospace(BODY);
+ let row_h = ui.fonts_mut(|f| f.row_height(&font));
+ let char_w = ui.fonts_mut(|f| f.glyph_width(&font, '0'));
+ let n_lines = doc.text.split('\n').count();
+ let digits = n_lines.to_string().len().max(3);
+
+ let s = &doc.session;
+ let built = s.build.is_some() && !doc.stale();
+ let marks = Marks {
+ errors: s
+ .diagnostics_for(&doc.text)
+ .iter()
+ .rev()
+ .map(|d| (d.line, d.msg.clone()))
+ .collect(),
+ breakpoints: s.breakpoints.clone(),
+ pc_line: (debug && built && (!s.running || s.speed <= 2))
+ .then(|| s.pc_line())
+ .flatten(),
+ addrs: (debug && built).then(|| {
+ let b = s.build.as_ref().unwrap();
+ (0..b.out.lines.len())
+ .filter_map(|l| Some((l, b.line_addr(l)?)))
+ .collect()
+ }),
+ };
+ let follow = std::mem::take(&mut doc.follow_pc)
+ .then_some(marks.pc_line)
+ .flatten();
+
+ let bp_w = 20.0;
+ let num_w = digits as f32 * char_w;
+ let addr_w = if marks.addrs.is_some() {
+ 4.0 * char_w + 16.0
+ } else {
+ 0.0
+ };
+ let gutter_w = bp_w + num_w + addr_w + 16.0;
+ let edit_id = Id::unique(("editor", doc.id));
+ let ctx = ui.ctx().clone();
+
+ if !debug
+ && ctx.memory(|m| m.has_focus(edit_id))
+ && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Tab))
+ {
+ insert_tab(&ctx, edit_id, &mut doc.text);
+ }
+
+ // Programmatic cursor moves: jump to a line (taking keyboard focus), or
+ // select a find match (leaving focus in the find bar, so Enter there
+ // can't overwrite the match).
+ let mut scroll_to_char = None;
+ let jump = doc
+ .goto
+ .take()
+ .map(|(line, col)| {
+ let c = char_index(&doc.text, line, col);
+ ((c, c), true)
+ })
+ .or(doc.select.take().map(|r| (r, false)));
+ if let Some(((a, b), focus)) = jump {
+ let mut state = TextEditState::load(&ctx, edit_id).unwrap_or_default();
+ state
+ .cursor
+ .set_char_range(Some(CCursorRange::two(CCursor::new(a), CCursor::new(b))));
+ state.store(&ctx, edit_id);
+ if focus {
+ ctx.memory_mut(|m| m.request_focus(edit_id));
+ }
+ // The TextEdit only reports its cursor while focused.
+ doc.cursor_char = a;
+ doc.cursor = line_col(&doc.text, a);
+ scroll_to_char = Some(a);
+ }
+ let hit = doc.find_hit;
+
+ let matches = find_all(&doc.text, &query);
+ let mut clicked_line = None;
+ let mut cursor = None;
+
+ egui::ScrollArea::both()
+ .id_salt(("code", doc.id))
+ .auto_shrink([false; 2])
+ .show(ui, |ui| {
+ let bg = ui.painter().add(Shape::Noop);
+ ui.horizontal_top(|ui| {
+ ui.spacing_mut().item_spacing = Vec2::ZERO;
+ let min_h = n_lines as f32 * row_h + 2.0 * MARGIN.y;
+ let (gutter, gutter_resp) = ui.allocate_exact_size(
+ vec2(gutter_w, min_h.max(ui.available_height())),
+ Sense::click(),
+ );
+
+ let mut layouter = |ui: &Ui, buf: &dyn TextBuffer, _wrap: f32| {
+ let job = ui.memory_mut(|m| {
+ m.caches
+ .cache::()
+ .get((dark, buf.as_str()))
+ .clone()
+ });
+ ui.fonts_mut(|f| f.layout_job(job))
+ };
+ let mut ro: &str;
+ let buf: &mut dyn TextBuffer = if debug {
+ ro = doc.text.as_str();
+ &mut ro
+ } else {
+ &mut doc.text
+ };
+ let out = egui::TextEdit::multiline(buf)
+ .id(edit_id)
+ .font(font.clone())
+ .frame(egui::Frame::NONE)
+ .margin(egui::Margin::symmetric(MARGIN.x as i8, MARGIN.y as i8))
+ .desired_width(f32::INFINITY)
+ .desired_rows(1)
+ .lock_focus(true)
+ .layouter(&mut layouter)
+ .show(ui);
+ cursor = out.cursor_range.map(|r| r.primary.index.0);
+
+ let galley = &out.galley;
+ let origin = out.galley_pos;
+ let content_right = ui
+ .max_rect()
+ .right()
+ .max(origin.x + galley.size().x + MARGIN.x);
+ let row_rect = |line: usize| -> Rect {
+ let y = galley
+ .rows
+ .get(line)
+ .map_or(origin.y + line as f32 * row_h, |r| origin.y + r.pos.y);
+ Rect::from_min_max(pos2(gutter.left(), y), pos2(content_right, y + row_h))
+ };
+
+ // Backgrounds: find matches and the PC row.
+ let mut shapes = Vec::new();
+ for &(a, b) in matches.iter().take(500) {
+ let ca = doc_text_chars(galley.text(), a);
+ let cb = doc_text_chars(galley.text(), b);
+ let ra = galley.pos_from_cursor(CCursor::new(ca));
+ let rb = galley.pos_from_cursor(CCursor::new(cb));
+ if (ra.top() - rb.top()).abs() < 1.0 {
+ let r = Rect::from_min_max(ra.min, pos2(rb.left(), ra.bottom()))
+ .translate(origin.to_vec2());
+ let current = hit == Some((a, b));
+ shapes.push(Shape::rect_filled(
+ r.expand(1.0),
+ 2.0,
+ WARNING.gamma_multiply(if current { 0.85 } else { 0.3 }),
+ ));
+ }
+ }
+ if let Some(pc) = marks.pc_line {
+ let r = row_rect(pc);
+ shapes.push(Shape::rect_filled(r, 0.0, p.surface_raised));
+ shapes.push(Shape::rect_filled(
+ Rect::from_min_size(r.min, vec2(2.0, r.height())),
+ 0.0,
+ ACCENT,
+ ));
+ }
+ ui.painter().set(bg, Shape::Vec(shapes));
+
+ // Gutter.
+ let clip = ui.clip_rect();
+ let painter = ui.painter();
+ let first = ((clip.top() - origin.y) / row_h).floor().max(0.0) as usize;
+ let last = (((clip.bottom() - origin.y) / row_h).ceil() as usize + 1).min(n_lines);
+ let cursor_line = doc.cursor.0;
+ for line in first..last {
+ let r = row_rect(line);
+ let cy = r.center().y;
+ let err = marks.errors.contains_key(&line);
+ let bp = marks.breakpoints.contains(&line);
+ let bx = gutter.left() + 4.0 + bp_w / 2.0;
+ if bp {
+ painter.circle_filled(pos2(bx, cy), 4.5, ACCENT);
+ } else if err {
+ let s = Stroke::new(1.5, ACCENT);
+ let d = 3.5;
+ painter.line_segment([pos2(bx - d, cy - d), pos2(bx + d, cy + d)], s);
+ painter.line_segment([pos2(bx + d, cy - d), pos2(bx - d, cy + d)], s);
+ }
+ let num_color = if err {
+ ACCENT
+ } else if Some(line) == marks.pc_line {
+ p.text_display
+ } else if line == cursor_line && !debug {
+ p.text_secondary
+ } else {
+ p.text_disabled
+ };
+ painter.text(
+ pos2(gutter.left() + 4.0 + bp_w + num_w, cy),
+ Align2::RIGHT_CENTER,
+ (line + 1).to_string(),
+ font.clone(),
+ num_color,
+ );
+ if let Some(addr) = marks.addrs.as_ref().and_then(|a| a.get(&line)) {
+ painter.text(
+ pos2(gutter.left() + 4.0 + bp_w + num_w + 12.0, cy),
+ Align2::LEFT_CENTER,
+ format!("{addr:04X}"),
+ font.clone(),
+ p.text_disabled,
+ );
+ }
+ }
+ let gutter_resp = gutter_resp.on_hover_cursor(CursorIcon::PointingHand);
+ if gutter_resp.clicked()
+ && let Some(pos) = gutter_resp.interact_pointer_pos()
+ {
+ let line = ((pos.y - origin.y) / row_h).floor();
+ if line >= 0.0 && (line as usize) < n_lines {
+ clicked_line = Some(line as usize);
+ }
+ }
+ let hovered_line = gutter_resp
+ .hover_pos()
+ .map(|pos| ((pos.y - origin.y) / row_h).floor() as usize);
+ if let Some(msg) = hovered_line.and_then(|l| marks.errors.get(&l)) {
+ gutter_resp.on_hover_text(msg);
+ }
+
+ if let Some(line) = follow {
+ ui.scroll_to_rect(row_rect(line), Some(Align::Center));
+ }
+ if let Some(ci) = scroll_to_char {
+ let r = galley
+ .pos_from_cursor(CCursor::new(ci))
+ .translate(origin.to_vec2());
+ ui.scroll_to_rect(r.expand2(vec2(40.0, 0.0)), Some(Align::Center));
+ }
+ });
+ });
+
+ if let Some(ci) = cursor {
+ doc.cursor_char = ci;
+ doc.cursor = line_col(&doc.text, ci);
+ }
+ if let Some(line) = clicked_line {
+ doc.session.toggle_breakpoint(line);
+ }
+}
+
+/// Char index of byte offset `b` in `text`.
+fn doc_text_chars(text: &str, b: usize) -> usize {
+ text[..b.min(text.len())].chars().count()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{char_index, highlight, line_col};
+
+ #[test]
+ fn layout_job_reproduces_the_text() {
+ let text = "main: MOV A,#1 ; µs\n\n\tDB \"x\"\n";
+ assert_eq!(highlight(text, true).text, text);
+ }
+
+ #[test]
+ fn cursor_conversions_round_trip() {
+ let text = "ab\nµcd\n\nx";
+ for ci in 0..=text.chars().count() {
+ let (l, c) = line_col(text, ci);
+ assert_eq!(char_index(text, l, c), ci);
+ }
+ assert_eq!(line_col(text, 4), (1, 1));
+ }
+}
diff --git a/crates/bench51-gui/src/icons.rs b/crates/bench51-gui/src/icons.rs
new file mode 100644
index 0000000..c3bb77a
--- /dev/null
+++ b/crates/bench51-gui/src/icons.rs
@@ -0,0 +1,200 @@
+//! Monoline toolbar icons drawn with the painter: 1.5 px strokes on a
+//! 16-unit grid, at most six strokes each, no fills.
+
+use std::f32::consts::TAU;
+
+use eframe::egui::{Color32, IconData, Painter, Pos2, Rect, Shape, Stroke, vec2};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Icon {
+ New,
+ Open,
+ Save,
+ Build,
+ Debug,
+ Reset,
+ Run,
+ Pause,
+ StepInto,
+ StepOver,
+ StepOut,
+ RunToCursor,
+ Breakpoint,
+}
+
+pub fn paint(painter: &Painter, rect: Rect, icon: Icon, color: Color32) {
+ let s = rect.width().min(rect.height()) / 16.0;
+ let o = rect.center() - vec2(8.0, 8.0) * s;
+ let p = |x: f32, y: f32| o + vec2(x, y) * s;
+ let stroke = Stroke::new(1.5, color);
+ let line = |pts: &[(f32, f32)]| {
+ painter.add(Shape::line(
+ pts.iter().map(|&(x, y)| p(x, y)).collect(),
+ stroke,
+ ));
+ };
+ let closed = |pts: &[(f32, f32)]| {
+ painter.add(Shape::closed_line(
+ pts.iter().map(|&(x, y)| p(x, y)).collect(),
+ stroke,
+ ));
+ };
+ // Arc around (cx, cy) from angle a0 to a1 (radians, clockwise on screen).
+ let arc = |cx: f32, cy: f32, r: f32, a0: f32, a1: f32| -> Vec {
+ let n = 24;
+ (0..=n)
+ .map(|i| {
+ let a = a0 + (a1 - a0) * i as f32 / n as f32;
+ p(cx + r * a.cos(), cy + r * a.sin())
+ })
+ .collect()
+ };
+ let dot = |x: f32, y: f32| painter.circle_stroke(p(x, y), 1.5 * s, stroke);
+
+ match icon {
+ Icon::New => {
+ closed(&[
+ (3.0, 1.5),
+ (9.5, 1.5),
+ (13.0, 5.0),
+ (13.0, 14.5),
+ (3.0, 14.5),
+ ]);
+ line(&[(9.5, 1.5), (9.5, 5.0), (13.0, 5.0)]);
+ }
+ Icon::Open => {
+ closed(&[
+ (1.5, 3.0),
+ (6.0, 3.0),
+ (7.5, 4.5),
+ (14.5, 4.5),
+ (14.5, 13.0),
+ (1.5, 13.0),
+ ]);
+ line(&[(1.5, 7.0), (14.5, 7.0)]);
+ }
+ Icon::Save => {
+ line(&[(8.0, 1.5), (8.0, 10.0)]);
+ line(&[(4.5, 6.5), (8.0, 10.0), (11.5, 6.5)]);
+ line(&[(2.0, 10.0), (2.0, 14.0), (14.0, 14.0), (14.0, 10.0)]);
+ }
+ Icon::Build => {
+ // A DIP chip: body and four pins.
+ closed(&[(4.0, 3.5), (12.0, 3.5), (12.0, 12.5), (4.0, 12.5)]);
+ for y in [6.0, 10.0] {
+ line(&[(1.5, y), (4.0, y)]);
+ line(&[(12.0, y), (14.5, y)]);
+ }
+ }
+ Icon::Debug => {
+ // Power switch: starts and stops the debug session.
+ painter.add(Shape::line(
+ arc(8.0, 9.0, 5.5, -TAU * 0.17, TAU * 0.67),
+ stroke,
+ ));
+ line(&[(8.0, 1.5), (8.0, 8.0)]);
+ }
+ Icon::Reset => {
+ painter.add(Shape::line(
+ arc(8.0, 8.5, 5.5, -TAU * 0.2, TAU * 0.6),
+ stroke,
+ ));
+ let tip = (
+ 8.0 + 5.5 * (TAU * 0.6f32).cos(),
+ 8.5 + 5.5 * (TAU * 0.6f32).sin(),
+ );
+ line(&[(tip.0 - 3.5, tip.1 - 0.5), tip, (tip.0 + 0.5, tip.1 - 3.5)]);
+ }
+ Icon::Run => closed(&[(4.5, 2.5), (13.0, 8.0), (4.5, 13.5)]),
+ Icon::Pause => {
+ line(&[(5.5, 3.0), (5.5, 13.0)]);
+ line(&[(10.5, 3.0), (10.5, 13.0)]);
+ }
+ Icon::StepInto => {
+ line(&[(8.0, 1.5), (8.0, 9.5)]);
+ line(&[(4.5, 6.0), (8.0, 9.5), (11.5, 6.0)]);
+ dot(8.0, 13.5);
+ }
+ Icon::StepOver => {
+ painter.add(Shape::line(arc(8.0, 9.0, 5.5, TAU * 0.5, TAU), stroke));
+ line(&[(10.5, 8.0), (13.5, 9.0), (14.5, 6.0)]);
+ dot(8.0, 13.5);
+ }
+ Icon::StepOut => {
+ line(&[(8.0, 10.5), (8.0, 2.0)]);
+ line(&[(4.5, 5.5), (8.0, 2.0), (11.5, 5.5)]);
+ dot(8.0, 13.5);
+ }
+ Icon::RunToCursor => {
+ line(&[(1.5, 8.0), (11.0, 8.0)]);
+ line(&[(7.5, 4.5), (11.0, 8.0), (7.5, 11.5)]);
+ line(&[(14.5, 3.0), (14.5, 13.0)]);
+ }
+ Icon::Breakpoint => {
+ painter.circle_stroke(p(8.0, 8.0), 5.0 * s, stroke);
+ }
+ }
+}
+
+/// Window icon: a dot-matrix "51" in white on black with one red dot.
+pub fn app_icon() -> IconData {
+ const N: usize = 64;
+ // 5×7 glyphs.
+ const FIVE: [&str; 7] = [
+ "#####", "#....", "####.", "....#", "....#", "#...#", ".###.",
+ ];
+ const ONE: [&str; 7] = [
+ "..#..", ".##..", "..#..", "..#..", "..#..", "..#..", ".###.",
+ ];
+ let mut rgba = vec![0u8; N * N * 4];
+ // Rounded black tile.
+ let r = 12.0;
+ for y in 0..N {
+ for x in 0..N {
+ let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5);
+ let dx = (r - fx).max(fx - (N as f32 - r)).max(0.0);
+ let dy = (r - fy).max(fy - (N as f32 - r)).max(0.0);
+ let a = (r + 0.5 - (dx * dx + dy * dy).sqrt()).clamp(0.0, 1.0);
+ rgba[(y * N + x) * 4 + 3] = (a * 255.0) as u8;
+ }
+ }
+ let mut put_disc = |cx: f32, cy: f32, r: f32, c: [u8; 3]| {
+ for y in 0..N {
+ for x in 0..N {
+ let d = ((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt();
+ let a = (r + 0.5 - d).clamp(0.0, 1.0);
+ if a > 0.0 {
+ let i = (y * N + x) * 4;
+ for k in 0..3 {
+ rgba[i + k] = (rgba[i + k] as f32 * (1.0 - a) + c[k] as f32 * a) as u8;
+ }
+ rgba[i + 3] = 255;
+ }
+ }
+ }
+ };
+ let pitch = 4.0;
+ let (x0, y0) = (11.0, 19.0);
+ for (gi, glyph) in [FIVE, ONE].iter().enumerate() {
+ for (row, bits) in glyph.iter().enumerate() {
+ for (col, b) in bits.bytes().enumerate() {
+ if b == b'#' {
+ let cx = x0 + (gi * 6 + col) as f32 * pitch + pitch / 2.0;
+ let cy = y0 + row as f32 * pitch + pitch / 2.0;
+ put_disc(cx, cy, 1.5, [255, 255, 255]);
+ }
+ }
+ }
+ }
+ put_disc(52.0, 12.0, 3.0, [0xD7, 0x19, 0x21]);
+ IconData {
+ rgba,
+ width: N as u32,
+ height: N as u32,
+ }
+}
+
+/// Square box for an icon of size `size` centred in `rect`.
+pub fn icon_rect(rect: Rect, size: f32) -> Rect {
+ Rect::from_center_size(rect.center(), vec2(size, size))
+}
diff --git a/crates/bench51-gui/src/layout.rs b/crates/bench51-gui/src/layout.rs
new file mode 100644
index 0000000..b4b2407
--- /dev/null
+++ b/crates/bench51-gui/src/layout.rs
@@ -0,0 +1,362 @@
+//! Dockable panes: Keil's edit and debug window layouts on `egui_tiles`,
+//! with Nothing-style tab bars and flat surface cards.
+
+use eframe::egui::{
+ self, Align2, Color32, CornerRadius, Id, Rect, Response, Sense, Shape, Stroke, Ui, Vec2,
+ WidgetText, vec2,
+};
+use egui_tiles::{
+ Behavior, Container, LinearDir, ResizeState, SimplificationOptions, TabState, Tabs, Tile,
+ TileId, Tiles, Tree, UiResponse,
+};
+use serde::{Deserialize, Serialize};
+
+use crate::panes;
+use crate::state::State;
+use crate::theme::{self, palette};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub enum Pane {
+ Project,
+ Editor,
+ Build,
+ Registers,
+ Memory,
+ Disassembly,
+ Symbols,
+ Serial,
+ Ports,
+ Timers,
+ Interrupts,
+}
+
+impl Pane {
+ pub const ALL: [Pane; 11] = [
+ Pane::Project,
+ Pane::Editor,
+ Pane::Build,
+ Pane::Registers,
+ Pane::Disassembly,
+ Pane::Memory,
+ Pane::Symbols,
+ Pane::Serial,
+ Pane::Ports,
+ Pane::Timers,
+ Pane::Interrupts,
+ ];
+
+ pub fn title(self) -> &'static str {
+ match self {
+ Pane::Project => "Project",
+ Pane::Editor => "Editor",
+ Pane::Build => "Build Output",
+ Pane::Registers => "Registers",
+ Pane::Memory => "Memory",
+ Pane::Disassembly => "Disassembly",
+ Pane::Symbols => "Symbols",
+ Pane::Serial => "UART #1",
+ Pane::Ports => "Ports",
+ Pane::Timers => "Timers",
+ Pane::Interrupts => "Interrupts",
+ }
+ }
+
+ /// Panes this one is grouped with by default, to dock it next to them
+ /// when it is reopened.
+ fn neighbours(self) -> &'static [Pane] {
+ match self {
+ Pane::Project | Pane::Registers => &[Pane::Registers, Pane::Project],
+ Pane::Editor | Pane::Disassembly => &[Pane::Disassembly, Pane::Editor],
+ Pane::Build | Pane::Memory | Pane::Symbols => {
+ &[Pane::Memory, Pane::Build, Pane::Symbols]
+ }
+ Pane::Serial | Pane::Ports | Pane::Timers | Pane::Interrupts => &[
+ Pane::Serial,
+ Pane::Ports,
+ Pane::Timers,
+ Pane::Interrupts,
+ Pane::Memory,
+ ],
+ }
+ }
+}
+
+const GAP: f32 = 6.0;
+const TAB_BAR: f32 = 30.0;
+
+fn tabs(tiles: &mut Tiles, panes: &[Pane]) -> TileId {
+ let ids = panes.iter().map(|&p| tiles.insert_pane(p)).collect();
+ tiles.insert_tab_tile(ids)
+}
+
+fn linear(tiles: &mut Tiles, dir: LinearDir, children: &[(TileId, f32)]) -> TileId {
+ let ids: Vec = children.iter().map(|c| c.0).collect();
+ let id = match dir {
+ LinearDir::Horizontal => tiles.insert_horizontal_tile(ids),
+ LinearDir::Vertical => tiles.insert_vertical_tile(ids),
+ };
+ if let Some(Tile::Container(Container::Linear(l))) = tiles.get_mut(id) {
+ for &(child, share) in children {
+ l.shares.set_share(child, share);
+ }
+ }
+ id
+}
+
+/// Keil's build-mode layout: project on the left, editor over build output.
+pub fn edit_tree() -> Tree {
+ let mut t = Tiles::default();
+ let project = tabs(&mut t, &[Pane::Project]);
+ let editor = tabs(&mut t, &[Pane::Editor]);
+ let build = tabs(&mut t, &[Pane::Build]);
+ let right = linear(&mut t, LinearDir::Vertical, &[(editor, 0.7), (build, 0.3)]);
+ let root = linear(
+ &mut t,
+ LinearDir::Horizontal,
+ &[(project, 0.18), (right, 0.82)],
+ );
+ Tree::new(Id::unique("edit_layout"), root, t)
+}
+
+/// Keil's debug-mode layout: registers on the left, source and disassembly
+/// in the middle, memory and peripherals along the bottom.
+pub fn debug_tree() -> Tree {
+ let mut t = Tiles::default();
+ let regs = tabs(&mut t, &[Pane::Registers, Pane::Project]);
+ let editor = tabs(&mut t, &[Pane::Editor]);
+ let disasm = tabs(&mut t, &[Pane::Disassembly]);
+ let mem = tabs(&mut t, &[Pane::Memory, Pane::Symbols, Pane::Build]);
+ let periph = tabs(
+ &mut t,
+ &[Pane::Serial, Pane::Ports, Pane::Timers, Pane::Interrupts],
+ );
+ let top = linear(
+ &mut t,
+ LinearDir::Horizontal,
+ &[(editor, 0.62), (disasm, 0.38)],
+ );
+ let bottom = linear(
+ &mut t,
+ LinearDir::Horizontal,
+ &[(mem, 0.56), (periph, 0.44)],
+ );
+ let right = linear(&mut t, LinearDir::Vertical, &[(top, 0.6), (bottom, 0.4)]);
+ let root = linear(
+ &mut t,
+ LinearDir::Horizontal,
+ &[(regs, 0.19), (right, 0.81)],
+ );
+ Tree::new(Id::unique("debug_layout"), root, t)
+}
+
+/// Brings `pane` to the front, docking it next to its usual neighbours if
+/// it was closed.
+pub fn show_pane(tree: &mut Tree, pane: Pane) {
+ if let Some(id) = tree.tiles.find_pane(&pane) {
+ tree.make_active(|tid, _| tid == id);
+ return;
+ }
+ let new = tree.tiles.insert_pane(pane);
+ let target = pane
+ .neighbours()
+ .iter()
+ .filter_map(|n| tree.tiles.find_pane(n))
+ .filter_map(|id| tree.tiles.parent_of(id))
+ .find(|&parent| {
+ matches!(
+ tree.tiles.get(parent),
+ Some(Tile::Container(Container::Tabs(_)))
+ )
+ });
+ if let Some(parent) = target
+ && let Some(Tile::Container(Container::Tabs(t))) = tree.tiles.get_mut(parent)
+ {
+ t.add_child(new);
+ t.set_active(new);
+ return;
+ }
+ let tabs_id = tree.tiles.insert_container(Tabs::new(vec![new]));
+ match tree.root {
+ Some(root) => {
+ if let Some(Tile::Container(c)) = tree.tiles.get_mut(root) {
+ c.add_child(tabs_id);
+ } else {
+ tree.root = Some(tree.tiles.insert_horizontal_tile(vec![root, tabs_id]));
+ }
+ }
+ None => tree.root = Some(tabs_id),
+ }
+}
+
+/// Flat surface cards behind every visible tab group: the page shows
+/// through the gaps between them.
+pub fn card_shapes(tree: &Tree, fill: Color32) -> Vec {
+ tree.tiles
+ .iter()
+ .filter(|(_, t)| matches!(t, Tile::Container(Container::Tabs(_))))
+ .filter_map(|(&id, _)| tree.tiles.rect(id))
+ .map(|r| Shape::rect_filled(r, CornerRadius::same(8), fill))
+ .collect()
+}
+
+pub struct PaneBehavior<'a> {
+ pub st: &'a mut State,
+ /// Tile of the editor pane, whose group hides its tab bar.
+ pub editor_tile: Option,
+}
+
+impl Behavior for PaneBehavior<'_> {
+ fn pane_ui(&mut self, ui: &mut Ui, _tile_id: TileId, pane: &mut Pane) -> UiResponse {
+ panes::show(*pane, ui, self.st);
+ UiResponse::None
+ }
+
+ fn tab_title_for_pane(&mut self, pane: &Pane) -> WidgetText {
+ pane.title().into()
+ }
+
+ fn is_tab_closable(&self, tiles: &Tiles, tile_id: TileId) -> bool {
+ matches!(tiles.get(tile_id), Some(Tile::Pane(p)) if *p != Pane::Editor)
+ }
+
+ fn tab_ui(
+ &mut self,
+ tiles: &mut Tiles,
+ ui: &mut Ui,
+ id: Id,
+ tile_id: TileId,
+ state: &TabState,
+ ) -> Response {
+ let p = palette(ui.ctx());
+ let title = match tiles.get(tile_id) {
+ Some(Tile::Pane(pane)) => pane.title(),
+ _ => "Group",
+ };
+ let galley = WidgetText::from(p.label(title)).into_galley(
+ ui,
+ Some(egui::TextWrapMode::Extend),
+ f32::INFINITY,
+ egui::TextStyle::Small,
+ );
+ let pad = 12.0;
+ let close_w = if state.closable { 16.0 } else { 0.0 };
+ let width = galley.size().x + 2.0 * pad + close_w;
+ let (_, rect) = ui.allocate_space(vec2(width, ui.available_height()));
+ let resp = ui
+ .interact(rect, id, Sense::click_and_drag())
+ .on_hover_cursor(egui::CursorIcon::PointingHand);
+
+ if ui.is_rect_visible(rect) && !state.is_being_dragged {
+ let fg = if state.active {
+ p.text_display
+ } else if resp.hovered() {
+ p.text_secondary
+ } else {
+ p.text_disabled
+ };
+ let text_rect = Rect::from_min_max(
+ rect.min + vec2(pad, 0.0),
+ rect.max - vec2(pad + close_w, 0.0),
+ );
+ let pos = Align2::LEFT_CENTER
+ .align_size_within_rect(galley.size(), text_rect)
+ .min;
+ let text_w = galley.size().x;
+ ui.painter().galley(pos, galley, fg);
+ if state.active {
+ ui.painter().hline(
+ pos.x..=pos.x + text_w,
+ rect.bottom() - 1.0,
+ Stroke::new(2.0, p.text_display),
+ );
+ }
+ if state.closable {
+ let c = Rect::from_center_size(
+ egui::pos2(rect.right() - pad - 4.0, rect.center().y),
+ Vec2::splat(12.0),
+ );
+ let close = ui
+ .interact(c, id.with("close"), Sense::click())
+ .on_hover_cursor(egui::CursorIcon::PointingHand);
+ if resp.hovered() || close.hovered() || state.active {
+ let col = if close.hovered() {
+ p.text_display
+ } else {
+ p.text_disabled
+ };
+ let r = c.shrink(3.0);
+ let s = Stroke::new(1.2, col);
+ ui.painter()
+ .line_segment([r.left_top(), r.right_bottom()], s);
+ ui.painter()
+ .line_segment([r.right_top(), r.left_bottom()], s);
+ }
+ if (close.clicked() || resp.clicked_by(egui::PointerButton::Middle))
+ && self.on_tab_close(tiles, tile_id)
+ {
+ tiles.remove(tile_id);
+ }
+ }
+ }
+ resp
+ }
+
+ fn is_tab_bar_visible(&self, _tile_id: TileId, tabs: &Tabs) -> bool {
+ // The editor brings its own document tabs; a second bar above them
+ // would only repeat "EDITOR".
+ !(tabs.children.len() == 1 && self.editor_tile == Some(tabs.children[0]))
+ }
+
+ fn tab_bar_height(&self, _style: &egui::Style) -> f32 {
+ TAB_BAR
+ }
+
+ fn gap_width(&self, _style: &egui::Style) -> f32 {
+ GAP
+ }
+
+ fn min_size(&self) -> f32 {
+ 64.0
+ }
+
+ fn tab_bar_color(&self, _visuals: &egui::Visuals) -> Color32 {
+ Color32::TRANSPARENT
+ }
+
+ fn tab_bar_hline_stroke(&self, visuals: &egui::Visuals) -> Stroke {
+ let p = if visuals.dark_mode {
+ &theme::DARK
+ } else {
+ &theme::LIGHT
+ };
+ Stroke::new(1.0, p.border)
+ }
+
+ fn resize_stroke(&self, style: &egui::Style, state: ResizeState) -> Stroke {
+ let p = if style.visuals.dark_mode {
+ &theme::DARK
+ } else {
+ &theme::LIGHT
+ };
+ match state {
+ ResizeState::Idle => Stroke::NONE,
+ ResizeState::Hovering => Stroke::new(1.0, p.text_disabled),
+ ResizeState::Dragging => Stroke::new(1.0, p.text_display),
+ }
+ }
+
+ fn simplification_options(&self) -> SimplificationOptions {
+ SimplificationOptions {
+ all_panes_must_have_tabs: true,
+ ..Default::default()
+ }
+ }
+
+ fn drag_preview_color(&self, visuals: &egui::Visuals) -> Color32 {
+ visuals.selection.bg_fill
+ }
+
+ fn drag_preview_stroke(&self, visuals: &egui::Visuals) -> Stroke {
+ visuals.selection.stroke
+ }
+}
diff --git a/crates/bench51-gui/src/main.rs b/crates/bench51-gui/src/main.rs
new file mode 100644
index 0000000..8b45fbe
--- /dev/null
+++ b/crates/bench51-gui/src/main.rs
@@ -0,0 +1,57 @@
+// No console window behind the app on Windows release builds.
+#![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")]
+
+mod app;
+mod chrome;
+mod editor;
+mod icons;
+mod layout;
+mod modals;
+mod panes;
+mod state;
+mod theme;
+mod widgets;
+
+use std::path::PathBuf;
+use std::sync::Arc;
+
+use clap::Parser;
+use eframe::egui;
+
+/// Keil µVision-style desktop IDE for the Intel 8051, built on bench51.
+#[derive(Parser, Debug)]
+#[command(version, about)]
+struct Args {
+ /// Assembly sources (.asm, .a51) or Intel HEX files (.hex, .ihx) to open.
+ files: Vec,
+
+ /// Oscillator frequency in MHz, used to show elapsed time.
+ #[arg(long)]
+ clock: Option,
+
+ /// Colour theme, overriding the saved choice.
+ #[arg(long, value_enum)]
+ theme: Option,
+}
+
+fn main() -> eframe::Result {
+ let args = Args::parse();
+ let options = eframe::NativeOptions {
+ viewport: egui::ViewportBuilder::default()
+ .with_title("bench51")
+ .with_app_id("bench51-gui")
+ .with_inner_size([1440.0, 900.0])
+ .with_min_inner_size([960.0, 600.0])
+ .with_icon(Arc::new(icons::app_icon())),
+ ..Default::default()
+ };
+ eframe::run_native(
+ "bench51-gui",
+ options,
+ Box::new(move |cc| {
+ Ok(Box::new(app::GuiApp::new(
+ cc, args.files, args.clock, args.theme,
+ )))
+ }),
+ )
+}
diff --git a/crates/bench51-gui/src/modals.rs b/crates/bench51-gui/src/modals.rs
new file mode 100644
index 0000000..c1c791c
--- /dev/null
+++ b/crates/bench51-gui/src/modals.rs
@@ -0,0 +1,208 @@
+//! Dialogs: unsaved-changes confirmation, target options, shortcuts, about.
+
+use eframe::egui::{
+ self, Align, Color32, Context, CornerRadius, FontId, Key, Layout, RichText, Stroke, Ui,
+};
+
+use crate::state::{Action, Modal, State};
+use crate::theme::{BODY, HERO, palette};
+use crate::widgets::{self, PillKind};
+
+const SHORTCUTS: &[(&str, &[(&str, &str)])] = &[
+ (
+ "File",
+ &[
+ ("Ctrl+N", "new file"),
+ ("Ctrl+O", "open .asm / .a51, or .hex (disassembled)"),
+ ("Ctrl+S F2", "save"),
+ ("Ctrl+Shift+S", "save as"),
+ ("Ctrl+W", "close file"),
+ ("Ctrl+F", "find"),
+ ],
+ ),
+ (
+ "Build & debug",
+ &[
+ ("F7", "build target (writes .lst and .hex)"),
+ ("Ctrl+F5 F4", "start / stop debug session"),
+ ("F5", "run / stop"),
+ ("F11", "step into"),
+ ("F10", "step over"),
+ ("Ctrl+F11 F12", "step out"),
+ ("Ctrl+F10 F8", "run to cursor line"),
+ ("F9", "toggle breakpoint"),
+ ("Ctrl+Shift+F9", "kill all breakpoints"),
+ ("F6", "reset CPU"),
+ ("Esc", "stop running"),
+ ],
+ ),
+ (
+ "Windows",
+ &[
+ ("Ctrl+Tab", "next tab in the hovered group"),
+ ("Ctrl+ +/-/0", "zoom"),
+ ("double-click", "edit a memory byte"),
+ ],
+ ),
+];
+
+fn frame(ctx: &Context) -> egui::Frame {
+ let p = crate::theme::palette(ctx);
+ egui::Frame::new()
+ .fill(p.surface)
+ .stroke(Stroke::new(1.0, p.border_visible))
+ .corner_radius(CornerRadius::same(16))
+ .inner_margin(egui::Margin::same(24))
+}
+
+/// Title on the left, `[ X ]` close on the right.
+fn header(ui: &mut Ui, title: &str) -> bool {
+ let p = palette(ui.ctx());
+ let mut close = false;
+ ui.horizontal(|ui| {
+ ui.label(p.label(title));
+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
+ close = widgets::pill(ui, "[ X ]", PillKind::Ghost).clicked();
+ });
+ });
+ ui.add_space(12.0);
+ close
+}
+
+pub fn show(ctx: &Context, st: &mut State) {
+ let Some(modal) = st.modal.clone() else {
+ return;
+ };
+ let mut close = false;
+ let mut acts = Vec::new();
+ let resp = egui::Modal::new(egui::Id::unique("modal"))
+ .frame(frame(ctx))
+ .backdrop_color(Color32::from_black_alpha(204))
+ .show(ctx, |ui| {
+ let p = palette(ui.ctx());
+ ui.set_max_width(480.0);
+ match &modal {
+ Modal::ConfirmClose(i) => {
+ let name = st.docs.get(*i).map(|d| d.name()).unwrap_or_default();
+ close |= header(ui, "Unsaved changes");
+ ui.label(
+ RichText::new(format!("Save changes to {name} before closing?"))
+ .size(BODY)
+ .color(p.text_primary),
+ );
+ ui.add_space(24.0);
+ ui.horizontal(|ui| {
+ if widgets::pill(ui, "Save", PillKind::Primary).clicked() {
+ acts.push(Action::Activate(*i));
+ acts.push(Action::Save);
+ acts.push(Action::Close(*i));
+ close = true;
+ }
+ if widgets::pill(ui, "Discard", PillKind::Secondary).clicked() {
+ acts.push(Action::ForceClose(*i));
+ close = true;
+ }
+ close |= widgets::pill(ui, "Cancel", PillKind::Ghost).clicked();
+ });
+ }
+ Modal::ConfirmQuit => {
+ let n = st.docs.iter().filter(|d| d.dirty()).count();
+ close |= header(ui, "Unsaved changes");
+ ui.label(
+ RichText::new(format!(
+ "{n} file{} unsaved changes.",
+ if n == 1 { " has" } else { "s have" }
+ ))
+ .size(BODY)
+ .color(p.text_primary),
+ );
+ ui.add_space(24.0);
+ ui.horizontal(|ui| {
+ if widgets::pill(ui, "Quit without saving", PillKind::Secondary).clicked() {
+ acts.push(Action::ForceQuit);
+ close = true;
+ }
+ close |= widgets::pill(ui, "Cancel", PillKind::Ghost).clicked();
+ });
+ }
+ Modal::Options(text) => {
+ close |= header(ui, "Options for target");
+ let mut text = text.clone();
+ ui.label(p.label("Xtal (MHz)"));
+ ui.add_space(4.0);
+ let r = widgets::underline_input(ui, &mut text, "11.0592", 160.0);
+ if !r.has_focus() && !r.lost_focus() && text.is_empty() {
+ r.request_focus();
+ }
+ ui.add_space(4.0);
+ ui.label(
+ p.label("Used to turn machine cycles into elapsed time")
+ .color(p.text_disabled),
+ );
+ let valid = text.trim().parse::().ok().filter(|v| *v > 0.0);
+ ui.add_space(24.0);
+ let enter = r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter));
+ ui.horizontal(|ui| {
+ if (widgets::pill(ui, "OK", PillKind::Primary).clicked() || enter)
+ && let Some(v) = valid
+ {
+ acts.push(Action::SetClock(v));
+ close = true;
+ }
+ close |= widgets::pill(ui, "Cancel", PillKind::Ghost).clicked();
+ });
+ if !close {
+ st.modal = Some(Modal::Options(text));
+ }
+ }
+ Modal::Shortcuts => {
+ close |= header(ui, "Keyboard shortcuts");
+ egui::ScrollArea::vertical()
+ .max_height(420.0)
+ .show(ui, |ui| {
+ for (section, keys) in SHORTCUTS {
+ ui.label(p.label(section).color(p.text_disabled));
+ ui.add_space(4.0);
+ egui::Grid::new(section)
+ .num_columns(2)
+ .spacing([24.0, 4.0])
+ .show(ui, |ui| {
+ for (k, what) in *keys {
+ ui.label(
+ RichText::new(*k)
+ .font(FontId::monospace(12.0))
+ .color(p.text_display),
+ );
+ ui.label(RichText::new(*what).color(p.text_secondary));
+ ui.end_row();
+ }
+ });
+ ui.add_space(16.0);
+ }
+ });
+ }
+ Modal::About => {
+ close |= header(ui, "About");
+ ui.label(p.hero("BENCH51", HERO));
+ ui.add_space(4.0);
+ ui.label(p.label(format!("version {}", env!("CARGO_PKG_VERSION"))));
+ ui.add_space(16.0);
+ ui.label(
+ RichText::new(
+ "An Intel 8051 assembler, simulator and debugger laid out like \
+ Keil µVision. A learning tool, not a cycle-exact replacement \
+ for a vendor simulator.",
+ )
+ .color(p.text_primary),
+ );
+ }
+ }
+ });
+ if resp.should_close() {
+ close = true;
+ }
+ if close {
+ st.modal = None;
+ }
+ st.actions.extend(acts);
+}
diff --git a/crates/bench51-gui/src/panes/build.rs b/crates/bench51-gui/src/panes/build.rs
new file mode 100644
index 0000000..296d324
--- /dev/null
+++ b/crates/bench51-gui/src/panes/build.rs
@@ -0,0 +1,188 @@
+//! Build Output: Keil-style messages, the listing and the Intel HEX file.
+
+use bench51_core::syntax::tokens;
+use eframe::egui::text::LayoutJob;
+use eframe::egui::{self, Align, CursorIcon, FontId, Layout, RichText, Sense, TextFormat, Ui};
+
+use crate::state::{Action, BuildTab, LogKind, Mode, State};
+use crate::theme::{ACCENT, HERO, palette};
+use crate::widgets;
+
+pub fn show(ui: &mut Ui, st: &mut State) {
+ let p = palette(ui.ctx());
+ let summary = st.doc().map(|d| match &d.session.last_asm {
+ Some((src, out)) if out.ok() => {
+ (out.code_size().to_string(), "bytes", false, src != &d.text)
+ }
+ Some((src, out)) => (
+ out.diagnostics.len().to_string(),
+ "errors",
+ true,
+ src != &d.text,
+ ),
+ None => (String::new(), "not built", false, false),
+ });
+ ui.horizontal(|ui| {
+ if let Some((n, unit, err, changed)) = &summary {
+ let color = if *err { ACCENT } else { p.text_display };
+ // The PC is the hero while debugging; one per screen.
+ if n.is_empty() {
+ } else if st.mode == Mode::Edit {
+ ui.label(p.hero(n, HERO).color(color));
+ } else {
+ ui.label(p.data(n).size(18.0).color(color));
+ }
+ ui.vertical(|ui| {
+ ui.add_space(if st.mode == Mode::Edit { 14.0 } else { 2.0 });
+ ui.label(p.label(*unit));
+ if *changed {
+ ui.label(p.label("[source changed]").color(p.text_disabled));
+ }
+ });
+ }
+ ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
+ widgets::segmented(
+ ui,
+ &mut st.build_tab,
+ &[
+ (BuildTab::Messages, "Messages"),
+ (BuildTab::Listing, "Listing"),
+ (BuildTab::Hex, "HEX"),
+ ],
+ );
+ });
+ });
+ ui.add_space(8.0);
+ match st.build_tab {
+ BuildTab::Messages => messages(ui, st),
+ BuildTab::Listing => listing(ui, st),
+ BuildTab::Hex => hex(ui, st),
+ }
+}
+
+fn messages(ui: &mut Ui, st: &mut State) {
+ let p = palette(ui.ctx());
+ if st.log.is_empty() {
+ widgets::empty_state(
+ ui,
+ "No messages",
+ "Build output appears here. F7 assembles.",
+ );
+ return;
+ }
+ let mut goto = None;
+ egui::ScrollArea::vertical()
+ .stick_to_bottom(true)
+ .auto_shrink([false; 2])
+ .show(ui, |ui| {
+ ui.spacing_mut().item_spacing.y = 3.0;
+ for line in &st.log {
+ let color = match line.kind {
+ LogKind::Info => p.text_secondary,
+ LogKind::Ok => p.text_primary,
+ LogKind::Error => ACCENT,
+ };
+ let text = RichText::new(&line.text)
+ .font(FontId::monospace(12.5))
+ .color(color);
+ if let Some(target) = line.target {
+ let r = ui
+ .add(egui::Label::new(text).sense(Sense::click()))
+ .on_hover_cursor(CursorIcon::PointingHand);
+ if r.clicked() {
+ goto = Some(target);
+ }
+ } else {
+ ui.label(text);
+ }
+ }
+ });
+ if let Some((doc, line, col)) = goto {
+ st.actions.push(Action::Goto { doc, line, col });
+ }
+}
+
+fn rows(ui: &mut Ui, id: &str, lines: &[&str], mut row: impl FnMut(&str) -> LayoutJob) {
+ let row_h = ui.fonts_mut(|f| f.row_height(&FontId::monospace(12.5))) + 2.0;
+ egui::ScrollArea::both()
+ .id_salt(id)
+ .auto_shrink([false; 2])
+ .show_rows(ui, row_h, lines.len(), |ui, range| {
+ ui.spacing_mut().item_spacing.y = 0.0;
+ for i in range {
+ ui.add(egui::Label::new(row(lines[i])).extend());
+ }
+ });
+}
+
+fn listing(ui: &mut Ui, st: &State) {
+ let p = palette(ui.ctx());
+ let Some((src, out)) = st.doc().and_then(|d| d.session.last_asm.as_ref()) else {
+ widgets::empty_state(ui, "No listing", "Press F7 to assemble.");
+ return;
+ };
+ let text = out.listing(src);
+ let lines: Vec<&str> = text.lines().collect();
+ let size = 12.5;
+ rows(ui, "listing", &lines, |l| {
+ let font = FontId::monospace(size);
+ if l.starts_with("***") {
+ return LayoutJob::simple_singleline(l.to_string(), font, ACCENT);
+ }
+ let is_code = l.len() > 25 && l.is_char_boundary(25);
+ if is_code && (l.as_bytes()[0].is_ascii_hexdigit() || l.starts_with(' ')) {
+ let (head, rest) = l.split_at(25);
+ let mut job = LayoutJob::default();
+ let head_color = if l.starts_with(' ') {
+ p.text_disabled
+ } else {
+ p.text_secondary
+ };
+ job.append(head, 0.0, TextFormat::simple(font, head_color));
+ for (r, tok) in tokens(rest) {
+ let (color, _) = p.syntax(tok);
+ job.append(
+ &rest[r],
+ 0.0,
+ TextFormat::simple(FontId::monospace(size), color),
+ );
+ }
+ return job;
+ }
+ LayoutJob::simple_singleline(l.to_string(), font, p.text_secondary)
+ });
+}
+
+fn hex(ui: &mut Ui, st: &State) {
+ let p = palette(ui.ctx());
+ let Some((_, out)) = st.doc().and_then(|d| d.session.last_asm.as_ref()) else {
+ widgets::empty_state(ui, "No HEX file", "Press F7 to assemble.");
+ return;
+ };
+ if !out.ok() {
+ widgets::empty_state(ui, "No HEX file", "Fix the errors to generate Intel HEX.");
+ return;
+ }
+ let text = out.intel_hex();
+ let lines: Vec<&str> = text.lines().collect();
+ rows(ui, "hex", &lines, |l| {
+ let font = FontId::monospace(12.5);
+ let mut job = LayoutJob::default();
+ if l.len() < 11 {
+ job.append(l, 0.0, TextFormat::simple(font, p.text_primary));
+ return job;
+ }
+ let n = l.len();
+ for (part, color) in [
+ (&l[..1], p.text_disabled),
+ (&l[1..3], p.text_secondary),
+ (&l[3..7], p.text_display),
+ (&l[7..9], p.text_secondary),
+ (&l[9..n - 2], p.text_primary),
+ (&l[n - 2..], p.text_disabled),
+ ] {
+ job.append(part, 0.0, TextFormat::simple(font.clone(), color));
+ }
+ job
+ });
+}
diff --git a/crates/bench51-gui/src/panes/disasm.rs b/crates/bench51-gui/src/panes/disasm.rs
new file mode 100644
index 0000000..3021687
--- /dev/null
+++ b/crates/bench51-gui/src/panes/disasm.rs
@@ -0,0 +1,193 @@
+//! Disassembly window: every instruction of the build with its address,
+//! bytes and label, decoded from code memory as it is now.
+
+use bench51_core::sim::disasm;
+use bench51_core::syntax::{Tok, tokens};
+use eframe::egui::{self, Align2, CursorIcon, FontId, Id, Rect, Sense, Ui, pos2, vec2};
+
+use crate::state::{Action, State};
+use crate::theme::{ACCENT, palette};
+use crate::widgets;
+
+struct Row {
+ line: usize,
+ addr: u16,
+ len: usize,
+ label: String,
+ /// Source text for DB/DW lines, which aren't instructions.
+ data: Option,
+}
+
+fn rows(source: &[String], build: &bench51_core::session::Build) -> Vec {
+ let mut out = Vec::new();
+ for (line, lo) in build.out.lines.iter().enumerate() {
+ let (Some(addr), false) = (lo.addr, lo.bytes.is_empty()) else {
+ continue;
+ };
+ let text = source.get(line).map_or("", String::as_str);
+ let toks = tokens(text);
+ let mut label = String::new();
+ let mut data = None;
+ for (r, t) in &toks {
+ match t {
+ Tok::Label if label.is_empty() => label = text[r.clone()].to_string(),
+ Tok::Directive => {
+ let rest = &text[r.start..];
+ let rest = rest.split(';').next().unwrap_or(rest).trim_end();
+ data = Some(rest.to_string());
+ break;
+ }
+ Tok::Mnemonic => break,
+ _ => {}
+ }
+ }
+ out.push(Row {
+ line,
+ addr,
+ len: lo.bytes.len(),
+ label,
+ data,
+ });
+ }
+ out
+}
+
+pub fn show(ui: &mut Ui, st: &mut State) {
+ let p = palette(ui.ctx());
+ let Some(doc) = st.docs.get_mut(st.active) else {
+ widgets::empty_state(ui, "No program", "Open or create a source file.");
+ return;
+ };
+ let doc_id = doc.id;
+ let s = &mut doc.session;
+ let Some(build) = &s.build else {
+ widgets::empty_state(ui, "Not built", "Press F7 to assemble.");
+ return;
+ };
+ let rows = rows(&build.source, build);
+ let font = FontId::monospace(13.0);
+ let cw = ui.fonts_mut(|f| f.glyph_width(&font, '0'));
+ let row_h = ui.fonts_mut(|f| f.row_height(&font)) + 6.0;
+ let col_addr = 20.0;
+ let col_bytes = col_addr + 6.0 * cw;
+ let col_label = col_bytes + 10.0 * cw;
+ let col_insn = col_label + 10.0 * cw;
+
+ // Header.
+ let (hdr, _) = ui.allocate_exact_size(vec2(ui.available_width(), 18.0), Sense::hover());
+ for (x, name) in [
+ (col_addr, "Addr"),
+ (col_bytes, "Bytes"),
+ (col_label, "Label"),
+ (col_insn, "Instruction"),
+ ] {
+ ui.painter().text(
+ pos2(hdr.left() + x, hdr.center().y),
+ Align2::LEFT_CENTER,
+ name.to_uppercase(),
+ FontId::monospace(crate::theme::LABEL),
+ p.text_disabled,
+ );
+ }
+ ui.add_space(4.0);
+
+ let pc = s.sim.pc;
+ let show_pc = !s.running || s.speed <= 2;
+ let pc_row = rows.iter().position(|r| r.addr == pc);
+ let bps = s.breakpoints.clone();
+
+ // Follow the PC whenever it moves while stopped.
+ let last_id = Id::unique(("disasm_last_pc", doc_id));
+ let last = ui.data(|d| d.get_temp::(last_id));
+ let mut area = egui::ScrollArea::vertical()
+ .id_salt(("disasm", doc_id))
+ .auto_shrink([false; 2]);
+ if show_pc && last != Some(pc) {
+ ui.data_mut(|d| d.insert_temp(last_id, pc));
+ if let Some(i) = pc_row {
+ let view = ui.available_height();
+ area = area.vertical_scroll_offset((i as f32 * row_h - view / 2.0).max(0.0));
+ }
+ }
+
+ let mut toggle = None;
+ let mut goto = None;
+ area.show_rows(ui, row_h, rows.len(), |ui, range| {
+ ui.spacing_mut().item_spacing.y = 0.0;
+ for i in range {
+ let r = &rows[i];
+ let (rect, resp) =
+ ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::click());
+ let painter = ui.painter();
+ let cy = rect.center().y;
+ let is_pc = show_pc && pc_row == Some(i);
+ if is_pc {
+ painter.rect_filled(rect, 0.0, p.surface_raised);
+ painter.rect_filled(
+ Rect::from_min_size(rect.min, vec2(2.0, rect.height())),
+ 0.0,
+ ACCENT,
+ );
+ }
+ if bps.contains(&r.line) {
+ painter.circle_filled(pos2(rect.left() + 10.0, cy), 4.0, ACCENT);
+ }
+ let text = |x: f32, s: String, c| {
+ painter.text(
+ pos2(rect.left() + x, cy),
+ Align2::LEFT_CENTER,
+ s,
+ font.clone(),
+ c,
+ );
+ };
+ text(
+ col_addr,
+ format!("{:04X}", r.addr),
+ if is_pc {
+ p.text_display
+ } else {
+ p.text_secondary
+ },
+ );
+ let bytes: Vec = (0..r.len.min(3))
+ .map(|k| format!("{:02X}", s.sim.code[r.addr.wrapping_add(k as u16) as usize]))
+ .collect();
+ let more = if r.len > 3 { "…" } else { "" };
+ text(col_bytes, bytes.join(" ") + more, p.text_disabled);
+ text(col_label, r.label.clone(), p.text_display);
+ match &r.data {
+ Some(d) => text(col_insn, d.clone(), p.text_secondary),
+ None => text(
+ col_insn,
+ disasm::disassemble(&s.sim.code, r.addr).text,
+ if is_pc {
+ p.text_display
+ } else {
+ p.text_primary
+ },
+ ),
+ }
+ let resp = resp.on_hover_cursor(CursorIcon::Default);
+ if resp.clicked()
+ && resp
+ .interact_pointer_pos()
+ .is_some_and(|pos| pos.x < rect.left() + col_addr)
+ {
+ toggle = Some(r.line);
+ } else if resp.double_clicked() {
+ goto = Some(r.line);
+ }
+ }
+ });
+ if let Some(line) = toggle {
+ s.toggle_breakpoint(line);
+ }
+ if let Some(line) = goto {
+ st.actions.push(Action::Goto {
+ doc: doc_id,
+ line,
+ col: 0,
+ });
+ }
+}
diff --git a/crates/bench51-gui/src/panes/interrupts.rs b/crates/bench51-gui/src/panes/interrupts.rs
new file mode 100644
index 0000000..7f088fa
--- /dev/null
+++ b/crates/bench51-gui/src/panes/interrupts.rs
@@ -0,0 +1,83 @@
+//! Interrupt system: enable, priority and request flag of each source.
+
+use bench51_core::session::{Session, vector_name};
+use bench51_core::sfr::{IE, IP, SCON, TCON};
+use eframe::egui::{self, Ui};
+
+use super::sfr_chip;
+use crate::theme::{WARNING, palette};
+use crate::widgets;
+
+/// (name, vector, IE/IP mask, request flag as (SFR, mask)).
+const SOURCES: [(&str, u16, u8, (u8, u8)); 5] = [
+ ("INT0", 0x03, 0x01, (TCON, 0x02)),
+ ("T0", 0x0B, 0x02, (TCON, 0x20)),
+ ("INT1", 0x13, 0x04, (TCON, 0x08)),
+ ("T1", 0x1B, 0x08, (TCON, 0x80)),
+ ("UART", 0x23, 0x10, (SCON, 0x03)),
+];
+
+pub fn show(ui: &mut Ui, s: &mut Session) {
+ let p = palette(ui.ctx());
+ egui::ScrollArea::vertical()
+ .auto_shrink([false; 2])
+ .show(ui, |ui| {
+ ui.horizontal(|ui| {
+ sfr_chip(ui, s, "EA", IE, 0x80);
+ ui.add_space(12.0);
+ let state = if s.sim.power_down {
+ ("power-down", WARNING)
+ } else if s.sim.idle {
+ ("idle", WARNING)
+ } else {
+ ("running", p.text_secondary)
+ };
+ ui.label(p.label("CPU"));
+ ui.label(p.label(state.0).color(state.1));
+ });
+ ui.add_space(10.0);
+ egui::Grid::new("irqs")
+ .num_columns(5)
+ .spacing([14.0, 6.0])
+ .show(ui, |ui| {
+ for h in ["Source", "Vector", "Enable", "Priority", "Request"] {
+ ui.label(p.label(h).color(p.text_disabled));
+ }
+ ui.end_row();
+ for (name, vector, mask, (flag_sfr, flag_mask)) in SOURCES {
+ let active = s.sim.last_irq == Some(vector) && !s.sim.in_service.is_empty();
+ ui.label(p.label(name).color(if active {
+ p.text_display
+ } else {
+ p.text_primary
+ }));
+ ui.label(p.data(format!("{vector:04X}")).color(p.text_secondary));
+ sfr_chip(ui, s, "EN", IE, mask);
+ sfr_chip(ui, s, "HI", IP, mask);
+ let req = s.sim.sfr(flag_sfr) & flag_mask != 0;
+ if flag_sfr == SCON {
+ widgets::bit_chip(ui, "RI|TI", req);
+ } else {
+ sfr_chip(ui, s, "REQ", flag_sfr, flag_mask);
+ }
+ ui.end_row();
+ }
+ });
+ widgets::section(ui, "In service");
+ let levels = if s.sim.in_service.is_empty() {
+ "none".to_string()
+ } else {
+ s.sim
+ .in_service
+ .iter()
+ .map(|l| format!("L{l}"))
+ .collect::>()
+ .join(" > ")
+ };
+ widgets::stat_row(ui, "Levels", p.data(levels));
+ let last = s.sim.last_irq.map_or("—".to_string(), |v| {
+ format!("{v:04X}h {}", vector_name(v))
+ });
+ widgets::stat_row(ui, "Last taken", p.data(last));
+ });
+}
diff --git a/crates/bench51-gui/src/panes/memory.rs b/crates/bench51-gui/src/panes/memory.rs
new file mode 100644
index 0000000..acd1d18
--- /dev/null
+++ b/crates/bench51-gui/src/panes/memory.rs
@@ -0,0 +1,305 @@
+//! Memory window: IRAM, SFRs, XRAM and code as a hex grid. Double-click a
+//! byte to change it.
+
+use bench51_core::session::{MemSpace, Session};
+use bench51_core::sfr;
+use eframe::egui::{
+ self, Align, Align2, FontId, Key, Layout, Rect, Sense, TextEdit, Ui, pos2, vec2,
+};
+
+use crate::state::{MemView, State};
+use crate::theme::{ACCENT, WARNING, palette};
+use crate::widgets;
+
+const PER_ROW: usize = 16;
+
+pub fn show(ui: &mut Ui, st: &mut State) {
+ let p = palette(ui.ctx());
+ let mut space = st.mem.space;
+ ui.horizontal(|ui| {
+ if widgets::segmented(
+ ui,
+ &mut space,
+ &[
+ (MemSpace::Iram, "IRAM"),
+ (MemSpace::Sfr, "SFR"),
+ (MemSpace::Xram, "XRAM"),
+ (MemSpace::Code, "CODE"),
+ ],
+ ) {
+ st.mem.edit = None;
+ }
+ if space != MemSpace::Sfr {
+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
+ let r = widgets::underline_input(ui, &mut st.mem.goto, "addr", 64.0);
+ ui.label(p.label("Go to"));
+ if r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) {
+ let t = st.mem.goto.trim().trim_start_matches("0x");
+ if let Ok(a) = u32::from_str_radix(t.trim_end_matches(['h', 'H']), 16) {
+ st.mem.scroll_to = Some(a);
+ }
+ }
+ });
+ }
+ });
+ st.mem.space = space;
+ ui.add_space(8.0);
+ let Some(doc) = st.docs.get_mut(st.active) else {
+ widgets::empty_state(ui, "No program", "Open or create a source file.");
+ return;
+ };
+ if doc.session.build.is_none() {
+ widgets::empty_state(ui, "Not built", "Press F7 to assemble.");
+ return;
+ }
+ match space {
+ MemSpace::Sfr => sfr_table(ui, &mut doc.session, &mut st.mem),
+ _ => hex_grid(ui, &mut doc.session, &mut st.mem),
+ }
+}
+
+fn parse_byte(s: &str) -> Option {
+ u8::from_str_radix(s.trim().trim_end_matches(['h', 'H']), 16).ok()
+}
+
+/// Inline editor for one byte. Returns true when editing ended.
+fn edit_cell(ui: &mut Ui, rect: Rect, text: &mut String) -> (bool, Option) {
+ let p = palette(ui.ctx());
+ ui.painter()
+ .rect_filled(rect.expand(2.0), 2.0, p.surface_raised);
+ let r = ui.put(
+ rect.expand(2.0),
+ TextEdit::singleline(text)
+ .font(FontId::monospace(13.0))
+ .char_limit(2)
+ .frame(egui::Frame::NONE)
+ .margin(egui::Margin::ZERO)
+ .text_color(p.text_display),
+ );
+ if !r.has_focus() && !r.lost_focus() {
+ r.request_focus();
+ }
+ if r.lost_focus() {
+ let commit = ui.input(|i| i.key_pressed(Key::Enter));
+ return (true, commit.then(|| parse_byte(text)).flatten());
+ }
+ (false, None)
+}
+
+fn hex_grid(ui: &mut Ui, s: &mut Session, mem: &mut MemView) {
+ let p = palette(ui.ctx());
+ let space = mem.space;
+ let font = FontId::monospace(13.0);
+ let cw = ui.fonts_mut(|f| f.glyph_width(&font, '0'));
+ let row_h = ui.fonts_mut(|f| f.row_height(&font)) + 4.0;
+ let total = if space == MemSpace::Iram {
+ 256
+ } else {
+ 0x10000
+ };
+ let addr_digits = if total > 256 { 4 } else { 2 };
+ let x_bytes = (addr_digits + 2) as f32 * cw;
+ let byte_x = |i: usize| x_bytes + (i * 3) as f32 * cw + if i >= 8 { cw } else { 0.0 };
+ let x_ascii = byte_x(PER_ROW) + cw;
+
+ let pc = s.sim.pc as usize;
+ let pc_len = bench51_core::isa::info(s.sim.code[pc]).map_or(1, |i| i.size as usize);
+ let bps = s.bp_addrs();
+ let bank = s.sim.reg_addr(0) as usize;
+ let sp = s.sim.sp() as usize;
+
+ let mut area = egui::ScrollArea::vertical()
+ .id_salt(("mem", space.name()))
+ .auto_shrink([false; 2]);
+ if let Some(a) = mem.scroll_to.take() {
+ area = area.vertical_scroll_offset((a as usize % total / PER_ROW) as f32 * row_h);
+ }
+ let mut poke = None;
+ area.show_rows(ui, row_h, total / PER_ROW, |ui, range| {
+ ui.spacing_mut().item_spacing.y = 0.0;
+ for row in range {
+ let base = row * PER_ROW;
+ let (rect, resp) =
+ ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::click());
+ if !ui.is_rect_visible(rect) {
+ continue;
+ }
+ let painter = ui.painter();
+ let cy = rect.center().y;
+ let addr = if addr_digits == 4 {
+ format!("{base:04X}")
+ } else {
+ format!("{base:02X}")
+ };
+ painter.text(
+ pos2(rect.left(), cy),
+ Align2::LEFT_CENTER,
+ addr,
+ font.clone(),
+ p.text_secondary,
+ );
+ let mut ascii = String::with_capacity(PER_ROW);
+ for i in 0..PER_ROW {
+ let a = base + i;
+ let (v, fg, inverted) = match space {
+ MemSpace::Iram => {
+ let v = s.sim.iram[a];
+ let fg = if v != s.prev_iram[a] {
+ WARNING
+ } else if (bank..bank + 8).contains(&a) {
+ p.text_display
+ } else if v == 0 {
+ p.text_disabled
+ } else {
+ p.text_primary
+ };
+ (v, fg, a == sp)
+ }
+ MemSpace::Xram => {
+ let v = s.sim.xram[a];
+ (
+ v,
+ if v == 0 {
+ p.text_disabled
+ } else {
+ p.text_primary
+ },
+ false,
+ )
+ }
+ _ => {
+ let v = s.sim.code[a];
+ let fg = if bps.contains(&(a as u16)) {
+ ACCENT
+ } else if v == 0 {
+ p.text_disabled
+ } else {
+ p.text_primary
+ };
+ (v, fg, (pc..pc + pc_len).contains(&a))
+ }
+ };
+ let cell = Rect::from_min_size(
+ pos2(rect.left() + byte_x(i) - 2.0, rect.top() + 1.0),
+ vec2(2.0 * cw + 4.0, row_h - 2.0),
+ );
+ let editing = mem.edit.as_ref().is_some_and(|(ea, _)| *ea as usize == a);
+ if editing {
+ let (_, text) = mem.edit.as_mut().unwrap();
+ let (done, value) = edit_cell(ui, cell.shrink2(vec2(2.0, 1.0)), text);
+ if done {
+ if let Some(v) = value {
+ poke = Some((a as u32, v));
+ }
+ mem.edit = None;
+ }
+ } else {
+ let painter = ui.painter();
+ let fg = if inverted {
+ painter.rect_filled(cell, 2.0, p.text_display);
+ p.black
+ } else {
+ fg
+ };
+ painter.text(
+ pos2(rect.left() + byte_x(i), cy),
+ Align2::LEFT_CENTER,
+ format!("{v:02X}"),
+ font.clone(),
+ fg,
+ );
+ }
+ ascii.push(if v.is_ascii_graphic() || v == b' ' {
+ v as char
+ } else {
+ '·'
+ });
+ }
+ ui.painter().text(
+ pos2(rect.left() + x_ascii, cy),
+ Align2::LEFT_CENTER,
+ ascii,
+ font.clone(),
+ p.text_disabled,
+ );
+ if resp.double_clicked()
+ && let Some(pos) = resp.interact_pointer_pos()
+ {
+ let x = pos.x - rect.left();
+ if let Some(i) =
+ (0..PER_ROW).find(|&i| x >= byte_x(i) - 4.0 && x < byte_x(i) + 2.5 * cw)
+ {
+ let a = base + i;
+ let v = match space {
+ MemSpace::Iram => s.sim.iram[a],
+ MemSpace::Xram => s.sim.xram[a],
+ _ => s.sim.code[a],
+ };
+ mem.edit = Some((a as u32, format!("{v:02X}")));
+ }
+ }
+ }
+ });
+ if let Some((a, v)) = poke {
+ s.poke(space, a, v);
+ }
+}
+
+fn sfr_table(ui: &mut Ui, s: &mut Session, mem: &mut MemView) {
+ let p = palette(ui.ctx());
+ let cols = if ui.available_width() > 620.0 { 3 } else { 2 };
+ let per_col = sfr::SFRS.len().div_ceil(cols);
+ let mut poke = None;
+ egui::ScrollArea::vertical()
+ .auto_shrink([false; 2])
+ .show(ui, |ui| {
+ egui::Grid::new("sfr_table")
+ .num_columns(cols * 4)
+ .spacing([14.0, 5.0])
+ .show(ui, |ui| {
+ for r in 0..per_col {
+ for c in 0..cols {
+ let Some(&(name, addr)) = sfr::SFRS.get(c * per_col + r) else {
+ continue;
+ };
+ let v = s.sim.read_direct(addr, true);
+ let changed = super::sfr_changed(s, addr);
+ ui.label(p.label(name).color(p.text_secondary));
+ ui.label(p.data(format!("{addr:02X}")).color(p.text_disabled));
+ let editing = mem.edit.as_ref().is_some_and(|(a, _)| *a == addr as u32);
+ if editing {
+ let (rect, _) =
+ ui.allocate_exact_size(vec2(24.0, 18.0), Sense::hover());
+ let (_, text) = mem.edit.as_mut().unwrap();
+ let (done, value) = edit_cell(ui, rect, text);
+ if done {
+ if let Some(v) = value {
+ poke = Some((addr as u32, v));
+ }
+ mem.edit = None;
+ }
+ } else {
+ let color = if changed { WARNING } else { p.text_primary };
+ let resp = ui.add(
+ egui::Label::new(p.data(format!("{v:02X}")).color(color))
+ .sense(Sense::click()),
+ );
+ if resp.double_clicked() {
+ mem.edit = Some((addr as u32, format!("{v:02X}")));
+ }
+ }
+ let bits = p.data(format!("{v:08b}")).size(12.0).color(if changed {
+ WARNING
+ } else {
+ p.text_disabled
+ });
+ ui.label(bits);
+ }
+ ui.end_row();
+ }
+ });
+ });
+ if let Some((a, v)) = poke {
+ s.poke(MemSpace::Sfr, a, v);
+ }
+}
diff --git a/crates/bench51-gui/src/panes/mod.rs b/crates/bench51-gui/src/panes/mod.rs
new file mode 100644
index 0000000..2aac7bf
--- /dev/null
+++ b/crates/bench51-gui/src/panes/mod.rs
@@ -0,0 +1,68 @@
+//! Tool windows docked around the editor.
+
+mod build;
+mod disasm;
+mod interrupts;
+mod memory;
+mod ports;
+mod project;
+mod registers;
+mod serial;
+mod symbols;
+mod timers;
+
+use bench51_core::session::Session;
+use eframe::egui::{self, Ui};
+
+use crate::editor;
+use crate::layout::Pane;
+use crate::state::State;
+use crate::widgets;
+
+pub fn show(pane: Pane, ui: &mut Ui, st: &mut State) {
+ if pane == Pane::Editor {
+ editor::show(ui, st);
+ return;
+ }
+ egui::Frame::NONE
+ .inner_margin(egui::Margin::symmetric(14, 10))
+ .show(ui, |ui| {
+ ui.set_min_size(ui.available_size());
+ match pane {
+ Pane::Project => project::show(ui, st),
+ Pane::Build => build::show(ui, st),
+ Pane::Registers => with_session(ui, st, registers::show),
+ Pane::Memory => memory::show(ui, st),
+ Pane::Disassembly => disasm::show(ui, st),
+ Pane::Symbols => symbols::show(ui, st),
+ Pane::Serial => serial::show(ui, st),
+ Pane::Ports => with_session(ui, st, ports::show),
+ Pane::Timers => with_session(ui, st, timers::show),
+ Pane::Interrupts => with_session(ui, st, interrupts::show),
+ Pane::Editor => unreachable!(),
+ }
+ });
+}
+
+/// Runs `f` with the active document's session, or shows why there is
+/// nothing to inspect yet.
+fn with_session(ui: &mut Ui, st: &mut State, f: fn(&mut Ui, &mut Session)) {
+ match st.docs.get_mut(st.active) {
+ Some(doc) if doc.session.build.is_some() => f(ui, &mut doc.session),
+ Some(_) => widgets::empty_state(ui, "Not built", "Press F7 to assemble."),
+ None => widgets::empty_state(ui, "No program", "Open or create a source file."),
+ }
+}
+
+/// Whether bit `mask` of SFR `addr` is set, and a click toggles it.
+pub fn sfr_chip(ui: &mut Ui, s: &mut Session, name: &str, addr: u8, mask: u8) {
+ let v = s.sim.sfr(addr);
+ if widgets::bit_chip(ui, name, v & mask != 0).clicked() {
+ s.sim.set_sfr(addr, v ^ mask);
+ }
+}
+
+/// An SFR value differs from the snapshot taken before the last step.
+pub fn sfr_changed(s: &Session, addr: u8) -> bool {
+ s.sim.sfr(addr) != s.prev_sfr[(addr & 0x7F) as usize]
+}
diff --git a/crates/bench51-gui/src/panes/ports.rs b/crates/bench51-gui/src/panes/ports.rs
new file mode 100644
index 0000000..b55b151
--- /dev/null
+++ b/crates/bench51-gui/src/panes/ports.rs
@@ -0,0 +1,77 @@
+//! I/O ports: the latch each instruction writes, and the pins the program
+//! reads. Click a pin to hold it low from outside, like a button.
+
+use bench51_core::session::Session;
+use bench51_core::sfr::P0;
+use eframe::egui::{self, Ui};
+
+use crate::theme::palette;
+use crate::widgets::{self, Dot};
+
+pub fn show(ui: &mut Ui, s: &mut Session) {
+ let p = palette(ui.ctx());
+ egui::ScrollArea::vertical()
+ .auto_shrink([false; 2])
+ .show(ui, |ui| {
+ egui::Grid::new("ports")
+ .num_columns(11)
+ .spacing([2.0, 4.0])
+ .show(ui, |ui| {
+ ui.label("");
+ ui.label("");
+ for bit in (0..8).rev() {
+ ui.vertical_centered(|ui| {
+ ui.label(p.label(bit.to_string()).color(p.text_disabled));
+ });
+ }
+ ui.label("");
+ ui.end_row();
+ for port in 0..4usize {
+ let addr = P0 + 0x10 * port as u8;
+ let latch = s.sim.sfr(addr);
+ let pins = s.sim.port_pins(port);
+ ui.label(p.label(format!("P{port}")).color(p.text_primary));
+ ui.label(p.label("latch").color(p.text_disabled));
+ for bit in (0..8u8).rev() {
+ let m = 1 << bit;
+ let dot = if latch & m != 0 { Dot::High } else { Dot::Low };
+ let r = widgets::pin_dot(ui, dot)
+ .on_hover_text(format!("P{port}.{bit} latch — click to toggle"));
+ if r.clicked() {
+ s.sim.set_sfr(addr, latch ^ m);
+ }
+ }
+ ui.label(p.data(format!("{latch:02X}")).color(p.text_secondary));
+ ui.end_row();
+
+ ui.label("");
+ ui.label(p.label("pins").color(p.text_disabled));
+ for bit in (0..8u8).rev() {
+ let m = 1 << bit;
+ let dot = if s.sim.pins[port] & m == 0 {
+ Dot::PulledLow
+ } else if pins & m != 0 {
+ Dot::High
+ } else {
+ Dot::Low
+ };
+ let r = widgets::pin_dot(ui, dot).on_hover_text(format!(
+ "P{port}.{bit} pin — click to pull low from outside"
+ ));
+ if r.clicked() {
+ s.sim.pins[port] ^= m;
+ }
+ }
+ ui.label(p.data(format!("{pins:02X}")));
+ ui.end_row();
+ ui.add_space(6.0);
+ ui.end_row();
+ }
+ });
+ ui.add_space(4.0);
+ ui.label(
+ p.label("● 1 ○ 0 red: held low outside")
+ .color(p.text_disabled),
+ );
+ });
+}
diff --git a/crates/bench51-gui/src/panes/project.rs b/crates/bench51-gui/src/panes/project.rs
new file mode 100644
index 0000000..12f764c
--- /dev/null
+++ b/crates/bench51-gui/src/panes/project.rs
@@ -0,0 +1,137 @@
+//! Project window: the target being built, open files, and the sources in
+//! its folder.
+
+use std::path::{Path, PathBuf};
+
+use eframe::egui::{self, CursorIcon, FontId, Id, RichText, Sense, Ui};
+
+use crate::state::{Action, State};
+use crate::theme::{BODY, palette};
+use crate::widgets;
+
+const EXTENSIONS: [&str; 6] = ["asm", "a51", "s", "src", "hex", "ihx"];
+
+/// Source files in `dir`, re-read at most every two seconds.
+fn folder_files(ui: &Ui, dir: &Path) -> Vec {
+ let id = Id::unique(("project_dir", dir));
+ let now = ui.input(|i| i.time);
+ if let Some((t, files)) = ui.data(|d| d.get_temp::<(f64, Vec)>(id))
+ && now - t < 2.0
+ {
+ return files;
+ }
+ let mut files: Vec = std::fs::read_dir(dir)
+ .into_iter()
+ .flatten()
+ .flatten()
+ .map(|e| e.path())
+ .filter(|p| {
+ p.extension()
+ .and_then(|e| e.to_str())
+ .is_some_and(|e| EXTENSIONS.contains(&e.to_ascii_lowercase().as_str()))
+ })
+ .collect();
+ files.sort();
+ ui.data_mut(|d| d.insert_temp(id, (now, files.clone())));
+ files
+}
+
+fn row(ui: &mut Ui, text: &str, color: egui::Color32, indent: f32) -> egui::Response {
+ ui.horizontal(|ui| {
+ ui.add_space(indent);
+ ui.add(
+ egui::Label::new(
+ RichText::new(text)
+ .font(FontId::monospace(BODY - 1.0))
+ .color(color),
+ )
+ .sense(Sense::click())
+ .truncate(),
+ )
+ .on_hover_cursor(CursorIcon::PointingHand)
+ })
+ .inner
+}
+
+pub fn show(ui: &mut Ui, st: &mut State) {
+ let p = palette(ui.ctx());
+ egui::ScrollArea::vertical()
+ .auto_shrink([false; 2])
+ .show(ui, |ui| {
+ ui.label(p.label("Target"));
+ ui.add_space(4.0);
+ match st.doc() {
+ Some(doc) => {
+ ui.label(
+ RichText::new(doc.target())
+ .font(FontId::new(18.0, crate::theme::grotesk_medium()))
+ .color(p.text_display),
+ );
+ let built = if doc.session.build.is_none() {
+ "not built"
+ } else if doc.stale() {
+ "source changed"
+ } else {
+ "built"
+ };
+ ui.label(p.label(built).color(p.text_disabled));
+ }
+ None => {
+ ui.label(p.label("none").color(p.text_disabled));
+ }
+ }
+
+ widgets::section(ui, "Open files");
+ let mut act = None;
+ for (i, doc) in st.docs.iter().enumerate() {
+ let color = if i == st.active {
+ p.text_display
+ } else {
+ p.text_secondary
+ };
+ let name = if doc.dirty() {
+ format!("{} •", doc.name())
+ } else {
+ doc.name()
+ };
+ if row(ui, &name, color, 12.0).clicked() {
+ act = Some(Action::Activate(i));
+ }
+ }
+
+ let dir = st
+ .doc()
+ .and_then(|d| d.path.as_ref())
+ .and_then(|p| p.parent().map(Path::to_path_buf))
+ .or_else(|| std::env::current_dir().ok());
+ if let Some(dir) = dir {
+ let shown = dir
+ .file_name()
+ .map_or_else(|| dir.display().to_string(), |n| n.to_string_lossy().into());
+ widgets::section(ui, &format!("Folder · {shown}"));
+ let files = folder_files(ui, &dir);
+ if files.is_empty() {
+ ui.label(p.label("no sources").color(p.text_disabled));
+ }
+ for f in files {
+ let open = st.docs.iter().any(|d| d.path.as_deref() == Some(&f));
+ let name = f
+ .file_name()
+ .unwrap_or_default()
+ .to_string_lossy()
+ .into_owned();
+ let color = if open {
+ p.text_primary
+ } else {
+ p.text_secondary
+ };
+ if row(ui, &name, color, 12.0).double_clicked() {
+ act = Some(Action::OpenPath(f.clone()));
+ }
+ }
+ }
+ if let Some(a) = act {
+ st.actions.push(a);
+ }
+ });
+}
diff --git a/crates/bench51-gui/src/panes/registers.rs b/crates/bench51-gui/src/panes/registers.rs
new file mode 100644
index 0000000..5257cb7
--- /dev/null
+++ b/crates/bench51-gui/src/panes/registers.rs
@@ -0,0 +1,105 @@
+//! Keil's register window. The program counter is the screen's hero.
+
+use bench51_core::session::Session;
+use bench51_core::sfr::{ACC, B, DPH, DPL, PSW, SP};
+use bench51_core::sim::disasm;
+use eframe::egui::{self, RichText, Ui};
+
+use super::{sfr_changed, sfr_chip};
+use crate::theme::{HERO, WARNING, palette};
+use crate::widgets;
+
+pub fn show(ui: &mut Ui, s: &mut Session) {
+ let p = palette(ui.ctx());
+ egui::ScrollArea::vertical()
+ .auto_shrink([false; 2])
+ .show(ui, |ui| {
+ ui.label(p.label("Program counter"));
+ ui.label(p.hero(format!("{:04X}", s.sim.pc), HERO));
+ let here = disasm::disassemble(&s.sim.code, s.sim.pc);
+ let state = if s.sim.power_down {
+ "power-down"
+ } else if s.sim.idle {
+ "idle"
+ } else {
+ ""
+ };
+ ui.horizontal(|ui| {
+ ui.label(p.data(here.text).color(p.text_secondary));
+ if !state.is_empty() {
+ ui.label(p.label(state).color(WARNING));
+ }
+ });
+
+ widgets::section(ui, "Registers");
+ let value = |v: String, changed: bool| {
+ p.data(v)
+ .color(if changed { WARNING } else { p.text_primary })
+ };
+ let iram_changed = |a: u8| s.sim.iram[a as usize] != s.prev_iram[a as usize];
+ egui::Grid::new("regs")
+ .num_columns(4)
+ .spacing([16.0, 6.0])
+ .show(ui, |ui| {
+ let pairs: [(&str, String, bool); 4] = [
+ ("A", format!("{:02X}", s.sim.acc()), sfr_changed(s, ACC)),
+ ("B", format!("{:02X}", s.sim.b()), sfr_changed(s, B)),
+ ("SP", format!("{:02X}", s.sim.sp()), sfr_changed(s, SP)),
+ (
+ "DPTR",
+ format!("{:04X}", s.sim.dptr()),
+ sfr_changed(s, DPL) || sfr_changed(s, DPH),
+ ),
+ ];
+ for row in pairs.chunks(2) {
+ for (name, v, ch) in row {
+ ui.label(p.label(*name));
+ ui.label(value(v.clone(), *ch));
+ }
+ ui.end_row();
+ }
+ for r in 0..4u8 {
+ for n in [r, r + 4] {
+ let a = s.sim.reg_addr(n);
+ ui.label(p.label(format!("R{n}")));
+ ui.label(value(
+ format!("{:02X}", s.sim.iram[a as usize]),
+ iram_changed(a),
+ ));
+ }
+ ui.end_row();
+ }
+ });
+
+ widgets::section(ui, "PSW");
+ ui.horizontal_wrapped(|ui| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ ui.label(value(format!("{:02X}", s.sim.psw()), sfr_changed(s, PSW)));
+ ui.add_space(6.0);
+ for (name, mask) in [
+ ("CY", 0x80),
+ ("AC", 0x40),
+ ("F0", 0x20),
+ ("RS1", 0x10),
+ ("RS0", 0x08),
+ ("OV", 0x04),
+ ("P", 0x01),
+ ] {
+ sfr_chip(ui, s, name, PSW, mask);
+ }
+ });
+ ui.add_space(4.0);
+ widgets::stat_row(ui, "Bank", p.data(s.sim.bank().to_string()));
+
+ widgets::section(ui, "Time");
+ widgets::stat_row(ui, "Cycles", p.data(s.sim.cycles.to_string()));
+ widgets::stat_row(ui, "Elapsed", p.data(s.elapsed()));
+ widgets::stat_row(
+ ui,
+ "Clock",
+ RichText::new(format!("{} MHz", s.clock_mhz))
+ .font(crate::theme::mono(crate::theme::LABEL + 1.0))
+ .color(p.text_secondary),
+ );
+ });
+}
diff --git a/crates/bench51-gui/src/panes/serial.rs b/crates/bench51-gui/src/panes/serial.rs
new file mode 100644
index 0000000..9bfe8a2
--- /dev/null
+++ b/crates/bench51-gui/src/panes/serial.rs
@@ -0,0 +1,86 @@
+//! UART #1: what the 8051 transmits, and a line to type into its receiver.
+
+use bench51_core::sfr::SCON;
+use eframe::egui::{self, Align, FontId, Key, Layout, RichText, Ui};
+
+use crate::state::State;
+use crate::theme::palette;
+use crate::widgets::{self, PillKind};
+
+pub fn show(ui: &mut Ui, st: &mut State) {
+ let p = palette(ui.ctx());
+ let Some(doc) = st.docs.get_mut(st.active) else {
+ widgets::empty_state(ui, "No program", "Open or create a source file.");
+ return;
+ };
+ let s = &mut doc.session;
+ let scon = s.sim.sfr(SCON);
+ ui.horizontal(|ui| {
+ ui.label(p.label(format!("Mode {}", scon >> 6)));
+ ui.add_space(8.0);
+ ui.spacing_mut().item_spacing.x = 4.0;
+ for (name, mask) in [("REN", 0x10), ("TI", 0x02), ("RI", 0x01)] {
+ super::sfr_chip(ui, s, name, SCON, mask);
+ }
+ ui.add_space(8.0);
+ ui.label(
+ p.label(format!("{} queued", s.sim.uart_rx_pending().len()))
+ .color(p.text_disabled),
+ );
+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
+ if widgets::pill(ui, "Clear", PillKind::Ghost).clicked() {
+ s.sim.uart.tx_log.clear();
+ }
+ });
+ });
+ ui.add_space(6.0);
+
+ let mut text = String::new();
+ for &b in &s.sim.uart.tx_log {
+ match b {
+ b'\n' => text.push('\n'),
+ b'\r' => {}
+ 0x20..=0x7E => text.push(b as char),
+ _ => text.push('·'),
+ }
+ }
+ let input_h = 34.0;
+ egui::ScrollArea::vertical()
+ .stick_to_bottom(true)
+ .auto_shrink([false; 2])
+ .max_height((ui.available_height() - input_h).max(40.0))
+ .show(ui, |ui| {
+ if text.is_empty() {
+ ui.label(p.label("[no output yet]").color(p.text_disabled));
+ } else {
+ ui.label(
+ RichText::new(text)
+ .font(FontId::monospace(13.0))
+ .color(p.text_primary),
+ );
+ }
+ });
+ ui.add_space(6.0);
+ ui.horizontal(|ui| {
+ ui.label(
+ RichText::new(">")
+ .font(FontId::monospace(13.0))
+ .color(p.text_secondary),
+ );
+ let w = ui.available_width();
+ let r = widgets::underline_input(
+ ui,
+ &mut st.serial_input,
+ "type, then Enter sends it with CR",
+ w,
+ );
+ if r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)) {
+ let mut bytes = std::mem::take(&mut st.serial_input).into_bytes();
+ bytes.push(b'\r');
+ if let Some(doc) = st.docs.get_mut(st.active) {
+ doc.session.sim.uart_send(&bytes);
+ }
+ r.request_focus();
+ }
+ });
+}
diff --git a/crates/bench51-gui/src/panes/symbols.rs b/crates/bench51-gui/src/panes/symbols.rs
new file mode 100644
index 0000000..fcfbaed
--- /dev/null
+++ b/crates/bench51-gui/src/panes/symbols.rs
@@ -0,0 +1,90 @@
+//! Symbol table of the build, with live values for memory symbols.
+
+use bench51_core::asm::SymKind;
+use eframe::egui::{self, CursorIcon, Sense, Ui};
+
+use crate::state::{Action, State};
+use crate::theme::{WARNING, palette};
+use crate::widgets;
+
+pub fn show(ui: &mut Ui, st: &mut State) {
+ let p = palette(ui.ctx());
+ let Some(doc) = st.docs.get(st.active) else {
+ widgets::empty_state(ui, "No program", "Open or create a source file.");
+ return;
+ };
+ let doc_id = doc.id;
+ let s = &doc.session;
+ let Some(build) = &s.build else {
+ widgets::empty_state(ui, "Not built", "Press F7 to assemble.");
+ return;
+ };
+ let mut goto = None;
+ if build.out.symbols.is_empty() {
+ widgets::empty_state(ui, "No symbols", "Labels and EQU names appear here.");
+ return;
+ }
+ egui::ScrollArea::vertical()
+ .auto_shrink([false; 2])
+ .show(ui, |ui| {
+ egui::Grid::new("symbols")
+ .num_columns(4)
+ .spacing([20.0, 6.0])
+ .show(ui, |ui| {
+ for h in ["Name", "Kind", "Value", "Now"] {
+ ui.label(p.label(h).color(p.text_disabled));
+ }
+ ui.end_row();
+ for (name, sym) in &build.out.symbols {
+ let v = sym.value;
+ let name_label = egui::Label::new(p.data(name).color(p.text_display))
+ .sense(Sense::click());
+ let resp = ui
+ .add(name_label)
+ .on_hover_cursor(CursorIcon::PointingHand)
+ .on_hover_text("Go to definition");
+ if resp.clicked() {
+ goto = Some(sym.line);
+ }
+ ui.label(p.label(sym.kind.name()));
+ let width = if (0..=0xFF).contains(&v) { 2 } else { 4 };
+ ui.label(
+ p.data(format!("{:0width$X}", v & 0xFFFF))
+ .color(p.text_secondary),
+ );
+ let now = match sym.kind {
+ SymKind::Data | SymKind::Idata if (0..=0xFF).contains(&v) => {
+ let a = v as usize;
+ Some((
+ format!("{:02X}", s.sim.iram[a]),
+ s.sim.iram[a] != s.prev_iram[a],
+ ))
+ }
+ SymKind::Xdata if (0..=0xFFFF).contains(&v) => {
+ Some((format!("{:02X}", s.sim.xram[v as usize]), false))
+ }
+ SymKind::Bit if (0..=0xFF).contains(&v) => {
+ Some((u8::from(s.sim.read_bit(v as u8, true)).to_string(), false))
+ }
+ _ => None,
+ };
+ match now {
+ Some((t, changed)) => ui.label(p.data(t).color(if changed {
+ WARNING
+ } else {
+ p.text_primary
+ })),
+ None => ui.label(p.data("—").color(p.text_disabled)),
+ };
+ ui.end_row();
+ }
+ });
+ });
+ if let Some(line) = goto {
+ st.actions.push(Action::Goto {
+ doc: doc_id,
+ line,
+ col: 0,
+ });
+ }
+}
diff --git a/crates/bench51-gui/src/panes/timers.rs b/crates/bench51-gui/src/panes/timers.rs
new file mode 100644
index 0000000..b4f0fab
--- /dev/null
+++ b/crates/bench51-gui/src/panes/timers.rs
@@ -0,0 +1,102 @@
+//! Timer/counter 0 and 1: mode, control bits and progress to overflow.
+
+use bench51_core::session::Session;
+use bench51_core::sfr::{TCON, TH0, TH1, TL0, TL1, TMOD};
+use eframe::egui::{self, Align, Layout, Ui};
+
+use super::{sfr_changed, sfr_chip};
+use crate::theme::{WARNING, palette};
+use crate::widgets;
+
+/// Count so far and the count at which the timer overflows.
+pub fn progress(mode: u8, th: u8, tl: u8) -> (u32, u32) {
+ match mode {
+ 0 => (((th as u32) << 5) | (tl as u32 & 0x1F), 1 << 13),
+ 1 => (((th as u32) << 8) | tl as u32, 1 << 16),
+ 2 => {
+ let span = 256 - th as u32;
+ ((tl as u32).saturating_sub(th as u32).min(span), span.max(1))
+ }
+ _ => (tl as u32, 256),
+ }
+}
+
+fn timer(ui: &mut Ui, s: &mut Session, n: u8) {
+ let p = palette(ui.ctx());
+ let (th, tl) = if n == 0 { (TH0, TL0) } else { (TH1, TL1) };
+ let shift = 4 * n;
+ let ctl = (s.sim.sfr(TMOD) >> shift) & 0x0F;
+ let mut mode = ctl & 3;
+ let (tr, tf) = if n == 0 { (0x10, 0x20) } else { (0x40, 0x80) };
+ let running = s.sim.sfr(TCON) & tr != 0;
+
+ ui.horizontal(|ui| {
+ ui.label(p.label(format!("Timer {n}")).color(p.text_primary));
+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
+ let desc = match mode {
+ 0 => "13-bit",
+ 1 => "16-bit",
+ 2 => "8-bit auto-reload",
+ _ => "split 8-bit",
+ };
+ ui.label(p.label(desc).color(p.text_disabled));
+ });
+ });
+ ui.add_space(4.0);
+ ui.horizontal(|ui| {
+ let changed = sfr_changed(s, th) || sfr_changed(s, tl);
+ ui.label(
+ p.data(format!("{:02X} {:02X}", s.sim.sfr(th), s.sim.sfr(tl)))
+ .size(18.0)
+ .color(if changed { WARNING } else { p.text_primary }),
+ );
+ ui.label(p.label(format!("TH{n} TL{n}")).color(p.text_disabled));
+ });
+ let (count, max) = progress(mode, s.sim.sfr(th), s.sim.sfr(tl));
+ let segments = 24;
+ let filled = (count as u64 * segments as u64 / max as u64) as usize;
+ let color = if running {
+ p.text_display
+ } else {
+ p.text_disabled
+ };
+ let w = ui.available_width().min(360.0);
+ widgets::segment_bar(ui, w, 8.0, segments, filled, color, false);
+ ui.add_space(6.0);
+ ui.horizontal_wrapped(|ui| {
+ ui.spacing_mut().item_spacing.x = 4.0;
+ if widgets::segmented(ui, &mut mode, &[(0, "M0"), (1, "M1"), (2, "M2"), (3, "M3")]) {
+ let tmod = s.sim.sfr(TMOD) & !(3 << shift) | (mode << shift);
+ s.sim.set_sfr(TMOD, tmod);
+ }
+ ui.add_space(6.0);
+ sfr_chip(ui, s, "GATE", TMOD, 0x08 << shift);
+ sfr_chip(ui, s, "C/T", TMOD, 0x04 << shift);
+ sfr_chip(ui, s, &format!("TR{n}"), TCON, tr);
+ sfr_chip(ui, s, &format!("TF{n}"), TCON, tf);
+ });
+}
+
+pub fn show(ui: &mut Ui, s: &mut Session) {
+ egui::ScrollArea::vertical()
+ .auto_shrink([false; 2])
+ .show(ui, |ui| {
+ timer(ui, s, 0);
+ ui.add_space(24.0);
+ timer(ui, s, 1);
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::progress;
+
+ #[test]
+ fn overflow_progress_per_mode() {
+ assert_eq!(progress(1, 0x80, 0x00), (0x8000, 0x10000));
+ assert_eq!(progress(0, 0x01, 0xFF), (0x3F, 0x2000));
+ assert_eq!(progress(2, 0xFD, 0xFE), (1, 3));
+ assert_eq!(progress(2, 0xFF, 0xFF), (0, 1));
+ assert_eq!(progress(3, 0x12, 0x40), (0x40, 256));
+ }
+}
diff --git a/crates/bench51-gui/src/state.rs b/crates/bench51-gui/src/state.rs
new file mode 100644
index 0000000..c008b92
--- /dev/null
+++ b/crates/bench51-gui/src/state.rs
@@ -0,0 +1,293 @@
+//! Application state shared by every pane, and the actions panes ask for.
+
+use std::path::{Path, PathBuf};
+
+use bench51_core::session::{MemSpace, Session};
+use serde::{Deserialize, Serialize};
+
+use crate::layout::Pane;
+
+/// Keil's two window layouts: building and debugging.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Mode {
+ Edit,
+ Debug,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
+pub enum ThemePref {
+ System,
+ Dark,
+ Light,
+}
+
+/// Settings that survive restarts.
+#[derive(Serialize, Deserialize)]
+#[serde(default)]
+pub struct Prefs {
+ pub theme: ThemePref,
+ pub recent: Vec,
+ pub speed: usize,
+ pub clock_mhz: f64,
+ pub zoom: f32,
+}
+
+impl Default for Prefs {
+ fn default() -> Self {
+ Self {
+ theme: ThemePref::System,
+ recent: Vec::new(),
+ speed: 5,
+ clock_mhz: 11.0592,
+ zoom: 1.0,
+ }
+ }
+}
+
+impl Prefs {
+ pub fn add_recent(&mut self, path: &Path) {
+ let path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
+ self.recent.retain(|p| *p != path);
+ self.recent.insert(0, path);
+ self.recent.truncate(10);
+ }
+}
+
+/// An open source file and the simulator running it.
+pub struct Document {
+ /// Stable id for egui widget state.
+ pub id: u64,
+ pub path: Option,
+ /// Name shown for documents without a path (e.g. a disassembled HEX file).
+ pub label: Option,
+ pub text: String,
+ pub saved: String,
+ pub session: Session,
+ /// Cursor position as (line, column), updated by the editor.
+ pub cursor: (usize, usize),
+ /// Cursor position as a char index into `text`.
+ pub cursor_char: usize,
+ /// Move the cursor here and scroll to it on the next frame.
+ pub goto: Option<(usize, usize)>,
+ /// Select this char range and scroll to it on the next frame, keeping
+ /// keyboard focus where it is (the find bar).
+ pub select: Option<(usize, usize)>,
+ /// Byte range of the current find match.
+ pub find_hit: Option<(usize, usize)>,
+ /// Scroll the editor and disassembly to the PC on the next frame.
+ pub follow_pc: bool,
+}
+
+impl Document {
+ pub fn new(id: u64, path: Option, text: &str, clock_mhz: f64) -> Self {
+ let text = text.replace("\r\n", "\n");
+ Self {
+ id,
+ path,
+ label: None,
+ saved: text.clone(),
+ text,
+ session: Session::new(clock_mhz),
+ cursor: (0, 0),
+ cursor_char: 0,
+ goto: None,
+ select: None,
+ find_hit: None,
+ follow_pc: false,
+ }
+ }
+
+ pub fn name(&self) -> String {
+ if let Some(name) = self.path.as_ref().and_then(|p| p.file_name()) {
+ return name.to_string_lossy().into_owned();
+ }
+ self.label.clone().unwrap_or_else(|| "untitled.asm".into())
+ }
+
+ /// File name without extension, Keil's "target" name.
+ pub fn target(&self) -> String {
+ let name = self.name();
+ match name.rsplit_once('.') {
+ Some((stem, _)) if !stem.is_empty() => stem.to_string(),
+ _ => name,
+ }
+ }
+
+ pub fn dirty(&self) -> bool {
+ self.text != self.saved
+ }
+
+ /// The editor text differs from the program in the simulator.
+ pub fn stale(&self) -> bool {
+ self.session.is_stale(self.text.split('\n'))
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum LogKind {
+ Info,
+ Ok,
+ Error,
+}
+
+/// A line in the Build Output messages.
+pub struct LogLine {
+ pub text: String,
+ pub kind: LogKind,
+ /// Clicking the line jumps here: (document id, line, column).
+ pub target: Option<(u64, usize, usize)>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum BuildTab {
+ Messages,
+ Listing,
+ Hex,
+}
+
+/// Everything the menus, toolbar, shortcuts and panes can ask for. They
+/// queue actions; `GuiApp::apply` runs them once the frame's UI is done.
+#[derive(Debug, Clone, PartialEq)]
+pub enum Action {
+ New,
+ Open,
+ OpenPath(PathBuf),
+ Save,
+ SaveAs,
+ /// Close a document, asking first if it has unsaved changes.
+ Close(usize),
+ /// Close without asking.
+ ForceClose(usize),
+ Activate(usize),
+ Quit,
+ /// Quit even with unsaved changes.
+ ForceQuit,
+ Build,
+ ToggleDebug,
+ RunPause,
+ StepInto,
+ StepOver,
+ StepOut,
+ RunToCursor,
+ Reset,
+ ToggleBreakpoint,
+ ClearBreakpoints,
+ SetSpeed(usize),
+ SetClock(f64),
+ Goto {
+ doc: u64,
+ line: usize,
+ col: usize,
+ },
+ ShowPane(Pane),
+ ResetLayout,
+ SetTheme(ThemePref),
+ Zoom(f32),
+ ZoomReset,
+ Find,
+ Modal(Modal),
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub enum Modal {
+ /// Unsaved changes in this document.
+ ConfirmClose(usize),
+ ConfirmQuit,
+ Shortcuts,
+ /// Options for Target: the oscillator frequency, being edited.
+ Options(String),
+ About,
+}
+
+pub struct MemView {
+ pub space: MemSpace,
+ pub goto: String,
+ /// Scroll so this address is visible on the next frame.
+ pub scroll_to: Option,
+ /// Byte being edited inline: (address, text).
+ pub edit: Option<(u32, String)>,
+}
+
+pub struct FindBar {
+ pub open: bool,
+ pub query: String,
+ /// Give the query field keyboard focus on the next frame.
+ pub focus: bool,
+}
+
+pub struct State {
+ pub docs: Vec,
+ pub active: usize,
+ next_doc_id: u64,
+ pub mode: Mode,
+ pub prefs: Prefs,
+ pub log: Vec,
+ pub actions: Vec,
+ pub modal: Option,
+ pub mem: MemView,
+ pub build_tab: BuildTab,
+ pub serial_input: String,
+ pub find: FindBar,
+}
+
+impl State {
+ pub fn new(prefs: Prefs) -> Self {
+ Self {
+ docs: Vec::new(),
+ active: 0,
+ next_doc_id: 1,
+ mode: Mode::Edit,
+ prefs,
+ log: Vec::new(),
+ actions: Vec::new(),
+ modal: None,
+ mem: MemView {
+ space: MemSpace::Iram,
+ goto: String::new(),
+ scroll_to: None,
+ edit: None,
+ },
+ build_tab: BuildTab::Messages,
+ serial_input: String::new(),
+ find: FindBar {
+ open: false,
+ query: String::new(),
+ focus: false,
+ },
+ }
+ }
+
+ pub fn doc(&self) -> Option<&Document> {
+ self.docs.get(self.active)
+ }
+
+ pub fn doc_mut(&mut self) -> Option<&mut Document> {
+ self.docs.get_mut(self.active)
+ }
+
+ pub fn add_doc(&mut self, path: Option, text: &str) -> &mut Document {
+ let id = self.next_doc_id;
+ self.next_doc_id += 1;
+ let mut doc = Document::new(id, path, text, self.prefs.clock_mhz);
+ doc.session.speed = self.prefs.speed;
+ self.docs.push(doc);
+ self.active = self.docs.len() - 1;
+ self.docs.last_mut().unwrap()
+ }
+
+ pub fn log(&mut self, kind: LogKind, text: impl Into) {
+ self.log.push(LogLine {
+ text: text.into(),
+ kind,
+ target: None,
+ });
+ if self.log.len() > 2000 {
+ self.log.drain(..500);
+ }
+ }
+
+ /// The active document's simulator is free running.
+ pub fn running(&self) -> bool {
+ self.doc().is_some_and(|d| d.session.running)
+ }
+}
diff --git a/crates/bench51-gui/src/theme.rs b/crates/bench51-gui/src/theme.rs
new file mode 100644
index 0000000..4ce80e7
--- /dev/null
+++ b/crates/bench51-gui/src/theme.rs
@@ -0,0 +1,293 @@
+//! Nothing design tokens mapped onto egui: palettes for both themes, the
+//! bundled fonts, and text helpers that keep the type budget in one place.
+
+use std::sync::Arc;
+
+use bench51_core::syntax::Tok;
+use eframe::egui::{
+ self, Color32, Context, CornerRadius, FontData, FontDefinitions, FontFamily, FontId, RichText,
+ Shadow, Stroke, Style, TextStyle, Theme, Visuals,
+ epaint::text::{FontTweak, VariationCoords},
+};
+
+/// The colour tokens of one theme (`references/tokens.md` §2).
+pub struct Palette {
+ /// Page background: OLED black / warm off-white paper.
+ pub black: Color32,
+ pub surface: Color32,
+ pub surface_raised: Color32,
+ pub border: Color32,
+ pub border_visible: Color32,
+ pub text_disabled: Color32,
+ pub text_secondary: Color32,
+ pub text_primary: Color32,
+ pub text_display: Color32,
+ pub interactive: Color32,
+}
+
+pub const DARK: Palette = Palette {
+ black: Color32::from_rgb(0x00, 0x00, 0x00),
+ surface: Color32::from_rgb(0x11, 0x11, 0x11),
+ surface_raised: Color32::from_rgb(0x1A, 0x1A, 0x1A),
+ border: Color32::from_rgb(0x22, 0x22, 0x22),
+ border_visible: Color32::from_rgb(0x33, 0x33, 0x33),
+ text_disabled: Color32::from_rgb(0x66, 0x66, 0x66),
+ text_secondary: Color32::from_rgb(0x99, 0x99, 0x99),
+ text_primary: Color32::from_rgb(0xE8, 0xE8, 0xE8),
+ text_display: Color32::from_rgb(0xFF, 0xFF, 0xFF),
+ interactive: Color32::from_rgb(0x5B, 0x9B, 0xF6),
+};
+
+pub const LIGHT: Palette = Palette {
+ black: Color32::from_rgb(0xF5, 0xF5, 0xF5),
+ surface: Color32::from_rgb(0xFF, 0xFF, 0xFF),
+ surface_raised: Color32::from_rgb(0xF0, 0xF0, 0xF0),
+ border: Color32::from_rgb(0xE8, 0xE8, 0xE8),
+ border_visible: Color32::from_rgb(0xCC, 0xCC, 0xCC),
+ text_disabled: Color32::from_rgb(0x99, 0x99, 0x99),
+ text_secondary: Color32::from_rgb(0x66, 0x66, 0x66),
+ text_primary: Color32::from_rgb(0x1A, 0x1A, 0x1A),
+ text_display: Color32::from_rgb(0x00, 0x00, 0x00),
+ interactive: Color32::from_rgb(0x00, 0x7A, 0xFF),
+};
+
+/// Signal red: breakpoints, errors, the PC bar. Never decorative.
+pub const ACCENT: Color32 = Color32::from_rgb(0xD7, 0x19, 0x21);
+/// Values that changed since the last step.
+pub const WARNING: Color32 = Color32::from_rgb(0xD4, 0xA8, 0x43);
+
+/// The three type sizes: labels, body/data, and the one hero per screen.
+pub const LABEL: f32 = 11.0;
+pub const BODY: f32 = 14.0;
+pub const HERO: f32 = 44.0;
+/// Doto at welcome-screen scale.
+pub const HERO_XL: f32 = 72.0;
+/// Tracking for ALL CAPS labels (0.08em at 11px).
+pub const LABEL_TRACKING: f32 = 0.9;
+
+pub fn palette(ctx: &Context) -> &'static Palette {
+ match ctx.theme() {
+ Theme::Dark => &DARK,
+ Theme::Light => &LIGHT,
+ }
+}
+
+pub fn mono_bold() -> FontFamily {
+ FontFamily::Name("mono-bold".into())
+}
+
+pub fn grotesk_medium() -> FontFamily {
+ FontFamily::Name("grotesk-medium".into())
+}
+
+pub fn doto() -> FontFamily {
+ FontFamily::Name("doto".into())
+}
+
+pub fn mono(size: f32) -> FontId {
+ FontId::monospace(size)
+}
+
+impl Palette {
+ /// Instrument-panel label: Space Mono, ALL CAPS, tracked, secondary grey.
+ pub fn label(&self, text: impl AsRef) -> RichText {
+ RichText::new(text.as_ref().to_uppercase())
+ .font(mono(LABEL))
+ .extra_letter_spacing(LABEL_TRACKING)
+ .color(self.text_secondary)
+ }
+
+ /// Data value in Space Mono at body size.
+ pub fn data(&self, text: impl Into) -> RichText {
+ RichText::new(text)
+ .font(mono(BODY))
+ .color(self.text_primary)
+ }
+
+ /// Dot-matrix hero number. One per screen.
+ pub fn hero(&self, text: impl Into, size: f32) -> RichText {
+ RichText::new(text)
+ .font(FontId::new(size, doto()))
+ .color(self.text_display)
+ }
+
+ /// Syntax colours: greyscale first, hierarchy by brightness and weight.
+ pub fn syntax(&self, tok: Tok) -> (Color32, bool) {
+ match tok {
+ Tok::Label => (self.text_display, true),
+ Tok::Mnemonic => (self.text_display, false),
+ Tok::Register | Tok::Sfr | Tok::Plain => (self.text_primary, false),
+ Tok::Number | Tok::Str | Tok::Directive => (self.text_secondary, false),
+ Tok::Comment => (self.text_disabled, false),
+ }
+ }
+}
+
+fn fonts() -> FontDefinitions {
+ let mut defs = FontDefinitions::default();
+ let mut add = |name: &str, bytes: &'static [u8], tweak: FontTweak| {
+ defs.font_data.insert(
+ name.to_owned(),
+ Arc::new(FontData::from_static(bytes).tweak(tweak)),
+ );
+ };
+ add(
+ "space-grotesk",
+ include_bytes!("../assets/fonts/SpaceGrotesk-Regular.ttf"),
+ FontTweak::default(),
+ );
+ add(
+ "space-grotesk-medium",
+ include_bytes!("../assets/fonts/SpaceGrotesk-Medium.ttf"),
+ FontTweak::default(),
+ );
+ add(
+ "space-mono",
+ include_bytes!("../assets/fonts/SpaceMono-Regular.ttf"),
+ FontTweak::default(),
+ );
+ add(
+ "space-mono-bold",
+ include_bytes!("../assets/fonts/SpaceMono-Bold.ttf"),
+ FontTweak::default(),
+ );
+ // Round dots, bold enough to read as a display face.
+ add(
+ "doto",
+ include_bytes!("../assets/fonts/Doto[ROND,wght].ttf"),
+ FontTweak {
+ coords: VariationCoords::new([(b"ROND", 100.0), (b"wght", 800.0)]),
+ ..FontTweak::default()
+ },
+ );
+
+ // egui's own fonts stay behind ours as fallbacks for symbols.
+ let prop_fallback = defs.families[&FontFamily::Proportional].clone();
+ let mono_fallback = defs.families[&FontFamily::Monospace].clone();
+ let with = |first: &[&str], rest: &[String]| -> Vec {
+ first
+ .iter()
+ .map(|s| s.to_string())
+ .chain(rest.iter().cloned())
+ .collect()
+ };
+ defs.families.insert(
+ FontFamily::Proportional,
+ with(&["space-grotesk"], &prop_fallback),
+ );
+ defs.families
+ .insert(FontFamily::Monospace, with(&["space-mono"], &mono_fallback));
+ defs.families
+ .insert(mono_bold(), with(&["space-mono-bold"], &mono_fallback));
+ defs.families.insert(
+ grotesk_medium(),
+ with(&["space-grotesk-medium"], &prop_fallback),
+ );
+ defs.families
+ .insert(doto(), with(&["doto", "space-mono"], &mono_fallback));
+ defs
+}
+
+fn visuals(p: &Palette, dark: bool) -> Visuals {
+ let mut v = if dark {
+ Visuals::dark()
+ } else {
+ Visuals::light()
+ };
+ let technical = CornerRadius::same(4);
+ v.panel_fill = p.black;
+ v.window_fill = p.surface;
+ v.window_stroke = Stroke::new(1.0, p.border_visible);
+ v.window_shadow = Shadow::NONE;
+ v.popup_shadow = Shadow::NONE;
+ v.window_corner_radius = CornerRadius::same(16);
+ v.menu_corner_radius = CornerRadius::same(8);
+ v.window_highlight_topmost = false;
+ v.extreme_bg_color = p.surface;
+ v.text_edit_bg_color = Some(p.surface);
+ v.faint_bg_color = p.surface_raised;
+ v.code_bg_color = p.surface_raised;
+ v.hyperlink_color = p.interactive;
+ v.warn_fg_color = WARNING;
+ v.error_fg_color = ACCENT;
+ v.selection.bg_fill = if dark {
+ Color32::from_white_alpha(46)
+ } else {
+ Color32::from_black_alpha(36)
+ };
+ v.selection.stroke = Stroke::new(1.0, p.text_display);
+ v.text_cursor.stroke = Stroke::new(2.0, p.text_display);
+ v.striped = false;
+ v.indent_has_left_vline = false;
+ v.collapsing_header_frame = false;
+ v.slider_trailing_fill = true;
+ v.resize_corner_size = 8.0;
+
+ let w = &mut v.widgets;
+ w.noninteractive.bg_fill = p.surface;
+ w.noninteractive.weak_bg_fill = p.surface;
+ w.noninteractive.bg_stroke = Stroke::new(1.0, p.border);
+ w.noninteractive.fg_stroke = Stroke::new(1.0, p.text_primary);
+ w.noninteractive.corner_radius = technical;
+
+ w.inactive.bg_fill = p.surface_raised;
+ w.inactive.weak_bg_fill = Color32::TRANSPARENT;
+ w.inactive.bg_stroke = Stroke::new(1.0, p.border_visible);
+ w.inactive.fg_stroke = Stroke::new(1.0, p.text_primary);
+ w.inactive.corner_radius = technical;
+ w.inactive.expansion = 0.0;
+
+ // Hover: the border and text brighten. No scale, no glow.
+ w.hovered.bg_fill = p.surface_raised;
+ w.hovered.weak_bg_fill = p.surface_raised;
+ w.hovered.bg_stroke = Stroke::new(1.0, p.text_secondary);
+ w.hovered.fg_stroke = Stroke::new(1.5, p.text_display);
+ w.hovered.corner_radius = technical;
+ w.hovered.expansion = 0.0;
+
+ w.active.bg_fill = p.surface_raised;
+ w.active.weak_bg_fill = p.surface_raised;
+ w.active.bg_stroke = Stroke::new(1.0, p.text_primary);
+ w.active.fg_stroke = Stroke::new(2.0, p.text_display);
+ w.active.corner_radius = technical;
+ w.active.expansion = 0.0;
+
+ w.open = w.hovered;
+ v
+}
+
+fn style(theme: Theme) -> Style {
+ let (p, dark) = match theme {
+ Theme::Dark => (&DARK, true),
+ Theme::Light => (&LIGHT, false),
+ };
+ let mut s = Style {
+ visuals: visuals(p, dark),
+ ..Style::default()
+ };
+ s.text_styles = [
+ (TextStyle::Small, FontId::monospace(LABEL)),
+ (TextStyle::Body, FontId::proportional(BODY)),
+ (TextStyle::Button, FontId::monospace(12.0)),
+ (TextStyle::Heading, FontId::new(18.0, grotesk_medium())),
+ (TextStyle::Monospace, FontId::monospace(13.0)),
+ ]
+ .into();
+ s.spacing.item_spacing = egui::vec2(8.0, 4.0);
+ s.spacing.button_padding = egui::vec2(10.0, 4.0);
+ s.spacing.interact_size.y = 22.0;
+ s.spacing.menu_margin = egui::Margin::same(8);
+ s.spacing.window_margin = egui::Margin::same(16);
+ s.spacing.menu_spacing = 2.0;
+ s.animation_time = 0.15;
+ s.interaction.selectable_labels = false;
+ s.interaction.tooltip_delay = 0.4;
+ s
+}
+
+/// Installs the fonts and both themes on `ctx`.
+pub fn install(ctx: &Context) {
+ ctx.set_fonts(fonts());
+ ctx.set_style_of(Theme::Dark, style(Theme::Dark));
+ ctx.set_style_of(Theme::Light, style(Theme::Light));
+}
diff --git a/crates/bench51-gui/src/widgets.rs b/crates/bench51-gui/src/widgets.rs
new file mode 100644
index 0000000..6fdadd3
--- /dev/null
+++ b/crates/bench51-gui/src/widgets.rs
@@ -0,0 +1,378 @@
+//! Nothing-style controls: buttons, segmented controls and bars, bit chips,
+//! pin dots, stat rows and empty states.
+
+use eframe::egui::{
+ self, Align, Align2, Color32, CornerRadius, CursorIcon, FontId, Layout, Painter, Rect,
+ Response, RichText, Sense, Stroke, StrokeKind, TextWrapMode, Ui, WidgetText, pos2, vec2,
+};
+
+use crate::icons::{self, Icon};
+use crate::theme::{self, ACCENT, LABEL, LABEL_TRACKING, palette};
+
+fn galley(ui: &Ui, text: RichText) -> std::sync::Arc {
+ WidgetText::from(text).into_galley(
+ ui,
+ Some(TextWrapMode::Extend),
+ f32::INFINITY,
+ egui::TextStyle::Small,
+ )
+}
+
+/// Square toolbar button with a monoline icon. `on` shows it latched
+/// (inverted), e.g. while the debug session is active.
+pub fn icon_button(ui: &mut Ui, icon: Icon, tip: &str, enabled: bool, on: bool) -> Response {
+ let p = palette(ui.ctx());
+ let size = vec2(30.0, 28.0);
+ let sense = if enabled {
+ Sense::click()
+ } else {
+ Sense::hover()
+ };
+ let (rect, resp) = ui.allocate_exact_size(size, sense);
+ let resp = resp.on_hover_text(tip);
+ if ui.is_rect_visible(rect) {
+ let painter = ui.painter();
+ let radius = CornerRadius::same(4);
+ let fg = if !enabled {
+ p.text_disabled
+ } else if on {
+ p.black
+ } else if resp.hovered() {
+ p.text_display
+ } else {
+ p.text_primary
+ };
+ if on && enabled {
+ painter.rect_filled(rect, radius, p.text_display);
+ } else if resp.hovered() {
+ painter.rect_stroke(
+ rect,
+ radius,
+ Stroke::new(1.0, p.border_visible),
+ StrokeKind::Inside,
+ );
+ }
+ icons::paint(painter, icons::icon_rect(rect, 16.0), icon, fg);
+ }
+ if enabled {
+ resp.on_hover_cursor(CursorIcon::PointingHand)
+ } else {
+ resp
+ }
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum PillKind {
+ /// White pill with black text: the one action to take.
+ Primary,
+ /// Outlined pill.
+ Secondary,
+ /// Text only.
+ Ghost,
+}
+
+/// Pill button: Space Mono, ALL CAPS, tracked.
+pub fn pill(ui: &mut Ui, text: &str, kind: PillKind) -> Response {
+ let p = palette(ui.ctx());
+ let label = RichText::new(text.to_uppercase())
+ .font(FontId::monospace(12.0))
+ .extra_letter_spacing(0.7);
+ let g = galley(ui, label);
+ let size = vec2(g.size().x + 36.0, 32.0);
+ let (rect, resp) = ui.allocate_exact_size(size, Sense::click());
+ if ui.is_rect_visible(rect) {
+ let painter = ui.painter();
+ let hovered = resp.hovered();
+ let (fill, stroke, fg) = match kind {
+ PillKind::Primary => (p.text_display, Stroke::NONE, p.black),
+ PillKind::Secondary => (
+ Color32::TRANSPARENT,
+ Stroke::new(
+ 1.0,
+ if hovered {
+ p.text_primary
+ } else {
+ p.border_visible
+ },
+ ),
+ p.text_primary,
+ ),
+ PillKind::Ghost => (
+ Color32::TRANSPARENT,
+ Stroke::NONE,
+ if hovered {
+ p.text_display
+ } else {
+ p.text_secondary
+ },
+ ),
+ };
+ painter.rect(
+ rect,
+ CornerRadius::same(255),
+ fill,
+ stroke,
+ StrokeKind::Inside,
+ );
+ let pos = Align2::CENTER_CENTER
+ .align_size_within_rect(g.size(), rect)
+ .min;
+ painter.galley(pos, g, fg);
+ }
+ resp.on_hover_cursor(CursorIcon::PointingHand)
+}
+
+/// Segmented control: the active segment is inverted. Returns true if the
+/// value changed.
+pub fn segmented(ui: &mut Ui, value: &mut T, options: &[(T, &str)]) -> bool {
+ let p = palette(ui.ctx());
+ let galleys: Vec<_> = options
+ .iter()
+ .map(|(_, l)| galley(ui, p.label(l)))
+ .collect();
+ let pad = 10.0;
+ let widths: Vec = galleys.iter().map(|g| g.size().x + 2.0 * pad).collect();
+ let size = vec2(widths.iter().sum(), 24.0);
+ let (rect, _) = ui.allocate_exact_size(size, Sense::hover());
+ let radius = CornerRadius::same(4);
+ let mut changed = false;
+ let mut x = rect.left();
+ for (i, ((v, label), g)) in options.iter().zip(galleys).enumerate() {
+ let seg = Rect::from_min_size(pos2(x, rect.top()), vec2(widths[i], rect.height()));
+ x += widths[i];
+ let resp = ui
+ .interact(seg, ui.auto_id_with(("seg", label, i)), Sense::click())
+ .on_hover_cursor(CursorIcon::PointingHand);
+ let active = *value == *v;
+ if resp.clicked() && !active {
+ *value = *v;
+ changed = true;
+ }
+ let fg = if active {
+ ui.painter().rect_filled(seg, radius, p.text_display);
+ p.black
+ } else if resp.hovered() {
+ p.text_display
+ } else {
+ p.text_secondary
+ };
+ let pos = Align2::CENTER_CENTER
+ .align_size_within_rect(g.size(), seg)
+ .min;
+ ui.painter().galley(pos, g, fg);
+ }
+ ui.painter().rect_stroke(
+ rect,
+ radius,
+ Stroke::new(1.0, p.border_visible),
+ StrokeKind::Inside,
+ );
+ changed
+}
+
+/// Segmented bar: `filled` of `segments` square blocks with 2 px gaps.
+/// Returns the index of a clicked segment.
+pub fn segment_bar(
+ ui: &mut Ui,
+ width: f32,
+ height: f32,
+ segments: usize,
+ filled: usize,
+ color: Color32,
+ clickable: bool,
+) -> Option {
+ let p = palette(ui.ctx());
+ let sense = if clickable {
+ Sense::click()
+ } else {
+ Sense::hover()
+ };
+ let (rect, resp) = ui.allocate_exact_size(vec2(width, height), sense);
+ let gap = 2.0;
+ let seg_w = (width - gap * (segments as f32 - 1.0)) / segments as f32;
+ let hover_idx = resp
+ .hover_pos()
+ .filter(|_| clickable)
+ .map(|pos| (((pos.x - rect.left()) / (seg_w + gap)) as usize).min(segments - 1));
+ let empty = if ui.visuals().dark_mode {
+ p.border
+ } else {
+ Color32::from_gray(0xE0)
+ };
+ for i in 0..segments {
+ let x = rect.left() + i as f32 * (seg_w + gap);
+ let r = Rect::from_min_size(pos2(x, rect.top()), vec2(seg_w, height));
+ let c = if i < filled {
+ color
+ } else if hover_idx.is_some_and(|h| i <= h) {
+ p.text_disabled
+ } else {
+ empty
+ };
+ ui.painter().rect_filled(r, 0.0, c);
+ }
+ if clickable && resp.clicked() {
+ resp.on_hover_cursor(CursorIcon::PointingHand);
+ return hover_idx;
+ }
+ if clickable {
+ resp.on_hover_cursor(CursorIcon::PointingHand);
+ }
+ None
+}
+
+/// Bit flag as a technical tag: lit when set. Clicking toggles it.
+pub fn bit_chip(ui: &mut Ui, name: &str, on: bool) -> Response {
+ let p = palette(ui.ctx());
+ let g = galley(
+ ui,
+ RichText::new(name)
+ .font(FontId::monospace(LABEL))
+ .extra_letter_spacing(LABEL_TRACKING * 0.5),
+ );
+ let size = vec2(g.size().x + 12.0, 20.0);
+ let (rect, resp) = ui.allocate_exact_size(size, Sense::click());
+ if ui.is_rect_visible(rect) {
+ let hovered = resp.hovered();
+ let (stroke, fg) = if on {
+ (p.text_display, p.text_display)
+ } else if hovered {
+ (p.text_secondary, p.text_secondary)
+ } else {
+ (p.border_visible, p.text_disabled)
+ };
+ ui.painter().rect_stroke(
+ rect,
+ CornerRadius::same(4),
+ Stroke::new(1.0, stroke),
+ StrokeKind::Inside,
+ );
+ let pos = Align2::CENTER_CENTER
+ .align_size_within_rect(g.size(), rect)
+ .min;
+ ui.painter().galley(pos, g, fg);
+ }
+ resp.on_hover_cursor(CursorIcon::PointingHand)
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub enum Dot {
+ High,
+ Low,
+ /// Held low from outside the chip, like a pressed button.
+ PulledLow,
+}
+
+/// A port pin as an LED-like dot.
+pub fn pin_dot(ui: &mut Ui, state: Dot) -> Response {
+ let p = palette(ui.ctx());
+ let (rect, resp) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::click());
+ if ui.is_rect_visible(rect) {
+ let c = rect.center();
+ let r = 5.0;
+ match state {
+ Dot::High => {
+ ui.painter().circle_filled(c, r, p.text_display);
+ }
+ Dot::PulledLow => {
+ ui.painter().circle_filled(c, r, ACCENT);
+ }
+ Dot::Low => {
+ ui.painter()
+ .circle_stroke(c, r - 0.5, Stroke::new(1.5, p.text_disabled));
+ }
+ }
+ if resp.hovered() {
+ ui.painter()
+ .circle_stroke(c, r + 3.0, Stroke::new(1.0, p.border_visible));
+ }
+ }
+ resp.on_hover_cursor(CursorIcon::PointingHand)
+}
+
+/// Label on the left, value on the right of the available width.
+pub fn stat_row(ui: &mut Ui, label: &str, value: RichText) {
+ let p = palette(ui.ctx());
+ ui.horizontal(|ui| {
+ ui.label(p.label(label));
+ ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
+ ui.label(value);
+ });
+ });
+}
+
+/// Uniform dot grid, the dot-matrix motif for empty backgrounds.
+pub fn dot_grid(painter: &Painter, rect: Rect, color: Color32, pitch: f32) {
+ let x0 = (rect.left() / pitch).ceil() * pitch;
+ let y0 = (rect.top() / pitch).ceil() * pitch;
+ let mut y = y0;
+ while y < rect.bottom() {
+ let mut x = x0;
+ while x < rect.right() {
+ painter.circle_filled(pos2(x, y), 0.9, color);
+ x += pitch;
+ }
+ y += pitch;
+ }
+}
+
+/// Centred two-line empty state on a faint dot grid.
+pub fn empty_state(ui: &mut Ui, headline: &str, hint: &str) {
+ let p = palette(ui.ctx());
+ let rect = ui.available_rect_before_wrap();
+ let grid = if ui.visuals().dark_mode {
+ p.border
+ } else {
+ p.border_visible.gamma_multiply(0.6)
+ };
+ dot_grid(ui.painter(), rect, grid, 16.0);
+ ui.scope_builder(
+ egui::UiBuilder::new()
+ .max_rect(rect)
+ .layout(Layout::top_down(Align::Center)),
+ |ui| {
+ ui.add_space((rect.height() / 2.0 - 24.0).max(8.0));
+ ui.label(p.label(headline).color(p.text_secondary));
+ ui.add_space(6.0);
+ ui.label(
+ RichText::new(hint)
+ .size(theme::BODY - 1.0)
+ .color(p.text_disabled),
+ );
+ },
+ );
+}
+
+/// ALL CAPS section heading with breathing room above.
+pub fn section(ui: &mut Ui, title: &str) {
+ let p = palette(ui.ctx());
+ ui.add_space(12.0);
+ ui.label(p.label(title).color(p.text_disabled));
+ ui.add_space(2.0);
+}
+
+/// Underlined single-line input in Space Mono.
+pub fn underline_input(ui: &mut Ui, text: &mut String, hint: &str, width: f32) -> Response {
+ let p = palette(ui.ctx());
+ let out = egui::TextEdit::singleline(text)
+ .font(FontId::monospace(13.0))
+ .hint_text(
+ RichText::new(hint)
+ .font(FontId::monospace(13.0))
+ .color(p.text_disabled),
+ )
+ .frame(egui::Frame::NONE)
+ .margin(egui::Margin::symmetric(0, 3))
+ .desired_width(width)
+ .show(ui);
+ let resp = out.response.response;
+ let color = if resp.has_focus() {
+ p.text_primary
+ } else {
+ p.border_visible
+ };
+ let r = resp.rect;
+ ui.painter()
+ .hline(r.x_range(), r.bottom(), Stroke::new(1.0, color));
+ resp
+}
diff --git a/docs/screenshots/gui_breakpoint_light.png b/docs/screenshots/gui_breakpoint_light.png
new file mode 100644
index 0000000..eb6ccf8
Binary files /dev/null and b/docs/screenshots/gui_breakpoint_light.png differ
diff --git a/docs/screenshots/gui_debug.png b/docs/screenshots/gui_debug.png
new file mode 100644
index 0000000..68cb749
Binary files /dev/null and b/docs/screenshots/gui_debug.png differ
diff --git a/docs/screenshots/gui_edit.png b/docs/screenshots/gui_edit.png
new file mode 100644
index 0000000..7002b84
Binary files /dev/null and b/docs/screenshots/gui_edit.png differ
diff --git a/docs/screenshots/gui_errors.png b/docs/screenshots/gui_errors.png
new file mode 100644
index 0000000..ee27084
Binary files /dev/null and b/docs/screenshots/gui_errors.png differ
diff --git a/docs/screenshots/gui_peripherals.png b/docs/screenshots/gui_peripherals.png
new file mode 100644
index 0000000..2657238
Binary files /dev/null and b/docs/screenshots/gui_peripherals.png differ
diff --git a/src/main.rs b/src/main.rs
index 0189edd..79a037f 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,12 +1,9 @@
-mod asm;
-mod isa;
-mod sfr;
-mod sim;
mod ui;
use std::path::PathBuf;
use std::process::ExitCode;
+use bench51_core::asm;
use clap::Parser;
/// Intel 8051 assembler, simulator and TUI debugger.
diff --git a/src/ui/app.rs b/src/ui/app.rs
index 1feba97..da8a9be 100644
--- a/src/ui/app.rs
+++ b/src/ui/app.rs
@@ -1,13 +1,11 @@
-use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::process::Command;
+use bench51_core::files::{self, Loaded};
+use bench51_core::session::{MemSpace, SPEEDS, Session};
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseEvent, MouseEventKind};
use ratatui_textarea::{CursorMove, TextArea};
-use crate::asm::{self, AsmOutput};
-use crate::sim::{Sim, Stop, disasm};
-
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
Edit,
@@ -31,13 +29,7 @@ pub enum Focus {
Serial,
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum MemTab {
- Iram,
- Sfr,
- Xram,
- Code,
-}
+pub type MemTab = MemSpace;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PromptKind {
@@ -52,27 +44,6 @@ pub struct Prompt {
pub input: String,
}
-/// Result of the last successful assembly, which the debugger runs.
-pub struct Build {
- pub source: Vec,
- pub out: AsmOutput,
- pub addr_to_line: HashMap,
-}
-
-impl Build {
- /// First address emitted by `line`, if any.
- pub fn line_addr(&self, line: usize) -> Option {
- self.out
- .lines
- .get(line)
- .filter(|l| !l.bytes.is_empty())
- .and_then(|l| l.addr)
- }
-}
-
-/// Instructions executed per frame (~30 fps) for each speed setting.
-pub const SPEEDS: [u32; 8] = [1, 5, 25, 100, 500, 2_000, 10_000, 40_000];
-
pub struct App {
pub path: Option,
pub editor: TextArea<'static>,
@@ -82,27 +53,14 @@ pub struct App {
pub focus: Focus,
pub mem_tab: MemTab,
pub mem_scroll: usize,
- /// Last assembler result, even if it had errors (for diagnostics).
- pub last_asm: Option<(String, AsmOutput)>,
- /// Last error-free build, loaded into the simulator.
- pub build: Option,
- pub sim: Sim,
- /// Breakpoints by source line.
- pub breakpoints: HashSet,
- pub running: bool,
- /// The next run chunk starts a fresh run and may leave a breakpoint.
- resume: bool,
- pub speed: usize,
- pub clock_mhz: f64,
- pub status: String,
+ /// Simulator, build, breakpoints and run state.
+ pub session: Session,
/// Selected line in the debug source view.
pub src_cursor: usize,
pub src_scroll: usize,
pub out_scroll: usize,
pub port_sel: (usize, u8),
pub serial_input: String,
- pub prev_iram: [u8; 256],
- pub prev_sfr: [u8; 128],
pub show_help: bool,
pub prompt: Option,
pub quit: bool,
@@ -123,28 +81,19 @@ impl App {
focus: Focus::Source,
mem_tab: MemTab::Iram,
mem_scroll: 0,
- last_asm: None,
- build: None,
- sim: Sim::new(),
- breakpoints: HashSet::new(),
- running: false,
- resume: false,
- speed: 5,
- clock_mhz,
- status: "F1 help · F7 assemble · F5 run · F11 step".into(),
+ session: Session::new(clock_mhz),
src_cursor: 0,
src_scroll: 0,
out_scroll: 0,
port_sel: (1, 0),
serial_input: String::new(),
- prev_iram: [0; 256],
- prev_sfr: [0; 128],
show_help: false,
prompt: None,
quit: false,
quit_armed: false,
external_edit: false,
};
+ app.session.status = "F1 help · F7 assemble · F5 run · F11 step".into();
match path {
Some(p) => app.open(&p),
None => app.set_text(TEMPLATE),
@@ -161,9 +110,7 @@ impl App {
});
crate::ui::draw::style_editor(&mut self.editor);
self.saved_text = self.text();
- self.breakpoints.clear();
- self.build = None;
- self.last_asm = None;
+ self.session.clear();
self.focus = Focus::Source;
self.serial_input.clear();
}
@@ -178,9 +125,8 @@ impl App {
/// Source differs from what the simulator is running.
pub fn stale(&self) -> bool {
- self.build
- .as_ref()
- .is_none_or(|b| b.source != self.editor.lines())
+ self.session
+ .is_stale(self.editor.lines().iter().map(String::as_str))
}
pub fn title(&self) -> String {
@@ -194,37 +140,24 @@ impl App {
// ---- Files ----
fn open(&mut self, path: &Path) {
- let text = match std::fs::read_to_string(path) {
- Ok(t) => t,
- Err(e) => {
- self.status = format!("cannot open {}: {e}", path.display());
- return;
+ match files::load(path) {
+ Err(e) => self.session.status = e,
+ Ok(Loaded::Hex { source, bytes }) => {
+ self.set_text(&source);
+ self.saved_text.clear();
+ self.path = None;
+ self.assemble();
+ self.session.status = format!(
+ "loaded {} ({bytes} bytes) and disassembled it",
+ path.display()
+ );
}
- };
- if path
- .extension()
- .is_some_and(|e| e.eq_ignore_ascii_case("hex") || e.eq_ignore_ascii_case("ihx"))
- {
- match asm::hex::read(&text) {
- Ok(bytes) => {
- let src = disassemble_image(&bytes, path);
- self.set_text(&src);
- self.saved_text.clear();
- self.path = None;
- self.assemble();
- self.status = format!(
- "loaded {} ({} bytes) and disassembled it",
- path.display(),
- bytes.len()
- );
- }
- Err(e) => self.status = format!("invalid HEX file: {e}"),
+ Ok(Loaded::Source(text)) => {
+ self.set_text(&text);
+ self.path = Some(path.to_path_buf());
+ self.mode = Mode::Edit;
+ self.session.status = format!("opened {}", path.display());
}
- } else {
- self.set_text(&text);
- self.path = Some(path.to_path_buf());
- self.mode = Mode::Edit;
- self.status = format!("opened {}", path.display());
}
}
@@ -241,10 +174,10 @@ impl App {
match std::fs::write(&path, text) {
Ok(()) => {
self.saved_text = self.text();
- self.status = format!("saved {}", path.display());
+ self.session.status = format!("saved {}", path.display());
self.path = Some(path);
}
- Err(e) => self.status = format!("cannot save {}: {e}", path.display()),
+ Err(e) => self.session.status = format!("cannot save {}: {e}", path.display()),
}
}
@@ -266,7 +199,7 @@ impl App {
None => {
let p = std::env::temp_dir().join(format!("bench51-{}.asm", std::process::id()));
if let Err(e) = std::fs::write(&p, self.text() + "\n") {
- self.status = format!("cannot write {}: {e}", p.display());
+ self.session.status = format!("cannot write {}: {e}", p.display());
return;
}
(p, true)
@@ -280,11 +213,11 @@ impl App {
let _ = std::fs::remove_file(&path);
}
match (result, text) {
- (Err(e), _) => self.status = format!("cannot start editor: {e}"),
+ (Err(e), _) => self.session.status = format!("cannot start editor: {e}"),
(Ok(s), _) if !s.success() => {
- self.status = format!("editor exited with {s}; changes not loaded")
+ self.session.status = format!("editor exited with {s}; changes not loaded")
}
- (Ok(_), Err(e)) => self.status = format!("cannot read {}: {e}", path.display()),
+ (Ok(_), Err(e)) => self.session.status = format!("cannot read {}: {e}", path.display()),
(Ok(_), Ok(text)) => self.reload(&text, !temp),
}
}
@@ -299,7 +232,7 @@ impl App {
lines
};
if lines == self.editor.lines() {
- self.status = "no changes from external editor".into();
+ self.session.status = "no changes from external editor".into();
return;
}
let cursor = self.editor.cursor();
@@ -312,61 +245,33 @@ impl App {
self.saved_text = self.text();
}
let n = self.editor.lines().len();
- self.breakpoints.retain(|&l| l < n);
+ self.session.breakpoints.retain(|&l| l < n);
if self.assemble() {
- self.status = format!("reloaded from external editor; {}", self.status);
+ self.session.status = format!("reloaded from external editor; {}", self.session.status);
}
}
// ---- Build & run ----
/// Assembles the editor contents. On success the program is loaded
- /// into a freshly reset simulator.
+ /// into a freshly reset simulator; on errors the cursor jumps to the
+ /// first one.
pub fn assemble(&mut self) -> bool {
let source = self.text();
- let out = asm::assemble(&source);
- let ok = out.ok();
+ let ok = self.session.assemble(&source, self.path.as_deref());
if ok {
- self.sim.load_code(out.bytes());
- self.sim.reset();
- self.running = false;
- self.status = format!("assembled: {} bytes, 0 errors", out.code_size());
- self.write_outputs(&out, &source);
- self.build = Some(Build {
- source: self.editor.lines().to_vec(),
- addr_to_line: out.addr_to_line(),
- out: out.clone(),
- });
- self.snapshot();
self.follow_pc();
- } else {
+ } else if let Some((_, out)) = &self.session.last_asm {
let first = &out.diagnostics[0];
- self.status = format!(
- "{} error(s); line {}: {}",
- out.diagnostics.len(),
- first.line + 1,
- first.msg
- );
self.editor
.move_cursor(CursorMove::Jump(first.line as u16, first.col as u16));
self.mode = Mode::Edit;
self.out_tab = OutTab::Errors;
}
self.out_scroll = 0;
- self.last_asm = Some((source, out));
ok
}
- /// Writes `.lst` and `.hex` next to a saved source file.
- fn write_outputs(&mut self, out: &AsmOutput, source: &str) {
- let Some(path) = &self.path else { return };
- let res = std::fs::write(path.with_extension("lst"), out.listing(source))
- .and_then(|_| std::fs::write(path.with_extension("hex"), out.intel_hex()));
- if let Err(e) = res {
- self.status = format!("assembled, but writing .lst/.hex failed: {e}");
- }
- }
-
/// Makes sure an up-to-date build is loaded; returns false on errors.
fn ensure_built(&mut self) -> bool {
if self.stale() && !self.assemble() {
@@ -379,132 +284,65 @@ impl App {
true
}
- pub fn bp_addrs(&self) -> HashSet {
- let Some(b) = &self.build else {
- return HashSet::new();
- };
- self.breakpoints
- .iter()
- .filter_map(|&l| b.line_addr(l))
- .collect()
- }
-
- pub fn snapshot(&mut self) {
- self.prev_iram = self.sim.iram;
- self.prev_sfr = self.sim.sfr;
- }
-
- pub fn pc_line(&self) -> Option {
- self.build.as_ref()?.addr_to_line.get(&self.sim.pc).copied()
- }
-
- /// Scrolls the source view so the PC line is visible.
+ /// Moves the source cursor to the PC line.
pub fn follow_pc(&mut self) {
- if let Some(l) = self.pc_line() {
+ if let Some(l) = self.session.pc_line() {
self.src_cursor = l;
}
}
- fn report(&mut self, stop: Stop) {
- self.running = false;
- self.status = match stop {
- Stop::Breakpoint(pc) => format!("breakpoint at {pc:04X}h"),
- Stop::ReservedOpcode { pc, opcode } => {
- format!("reserved opcode {opcode:02X}h at {pc:04X}h — stopped")
- }
- Stop::PowerDown => "CPU in power-down mode (PCON.PD) — reset to continue".into(),
- Stop::Target | Stop::Budget => format!("stopped at {:04X}h", self.sim.pc),
- };
- self.follow_pc();
- }
-
- fn step_cmd(&mut self, f: impl FnOnce(&mut Sim, &HashSet) -> Stop) {
+ /// Runs a session command once a build is loaded, then follows the PC.
+ fn debug_cmd(&mut self, f: impl FnOnce(&mut Session)) {
if !self.ensure_built() {
return;
}
- self.running = false;
- self.snapshot();
- let bps = self.bp_addrs();
- let stop = f(&mut self.sim, &bps);
- match stop {
- Stop::Target => {
- self.status = format!("PC = {:04X}h", self.sim.pc);
- self.follow_pc();
- }
- Stop::Budget => self.report(Stop::Budget),
- s => self.report(s),
- }
+ f(&mut self.session);
+ self.follow_pc();
}
fn toggle_run(&mut self) {
- if self.running {
- self.running = false;
- self.status = format!("paused at {:04X}h", self.sim.pc);
+ if self.session.running {
+ self.session.pause();
self.follow_pc();
} else if self.ensure_built() {
- self.running = true;
- self.resume = true;
- self.status = "running…".into();
+ self.session.start();
}
}
- fn run_to_cursor(&mut self) {
- if !self.ensure_built() {
- return;
- }
- let line = if self.mode == Mode::Debug {
+ /// Source line the cursor is on in the current mode.
+ fn cursor_line(&self) -> usize {
+ if self.mode == Mode::Debug {
self.src_cursor
} else {
self.editor.cursor().0
- };
- let Some(target) = self.build.as_ref().and_then(|b| b.line_addr(line)) else {
- self.status = "no code on that line".into();
+ }
+ }
+
+ fn run_to_cursor(&mut self) {
+ if !self.ensure_built() {
return;
- };
- self.step_cmd(|s, bps| {
- let mut bps = bps.clone();
- bps.insert(target);
- match s.run(5_000_000, &bps, true) {
- Stop::Breakpoint(pc) if pc == target => Stop::Target,
- other => other,
- }
+ }
+ let line = self.cursor_line();
+ self.debug_cmd(|s| {
+ s.run_to_line(line);
});
}
fn reset(&mut self) {
- self.sim.reset();
- self.running = false;
- self.snapshot();
+ self.session.reset();
self.follow_pc();
- self.status = "reset".into();
}
fn toggle_breakpoint(&mut self) {
- let line = if self.mode == Mode::Debug {
- self.src_cursor
- } else {
- self.editor.cursor().0
- };
- if !self.breakpoints.remove(&line) {
- self.breakpoints.insert(line);
- }
+ let line = self.cursor_line();
+ self.session.toggle_breakpoint(line);
}
/// Called once per frame.
pub fn tick(&mut self) {
- if !self.running {
- return;
- }
- self.snapshot();
- let bps = self.bp_addrs();
- let resume = std::mem::take(&mut self.resume);
- match self.sim.run(SPEEDS[self.speed], &bps, resume) {
- Stop::Budget => {
- if let Some(l) = self.pc_line() {
- self.src_cursor = l;
- }
- }
- s => self.report(s),
+ if self.session.running {
+ self.session.tick();
+ self.follow_pc();
}
}
@@ -541,7 +379,7 @@ impl App {
(KeyCode::Char('q'), true) => {
if self.dirty() && !self.quit_armed {
self.quit_armed = true;
- self.status = "unsaved changes — press Ctrl-Q again to quit".into();
+ self.session.status = "unsaved changes — press Ctrl-Q again to quit".into();
} else {
self.quit = true;
}
@@ -571,12 +409,9 @@ impl App {
}
(KeyCode::F(8), _) => self.run_to_cursor(),
(KeyCode::F(9), _) => self.toggle_breakpoint(),
- (KeyCode::F(10), _) => self.step_cmd(|s, b| s.step_over(5_000_000, b)),
- (KeyCode::F(11), _) => self.step_cmd(|s, _| match s.step() {
- Ok(()) => Stop::Target,
- Err(e) => e,
- }),
- (KeyCode::F(12), _) => self.step_cmd(|s, b| s.step_out(5_000_000, b)),
+ (KeyCode::F(10), _) => self.debug_cmd(Session::step_over),
+ (KeyCode::F(11), _) => self.debug_cmd(Session::step_into),
+ (KeyCode::F(12), _) => self.debug_cmd(Session::step_out),
_ => match self.mode {
Mode::Edit => self.on_edit_key(key),
Mode::Debug => self.on_debug_key(key),
@@ -595,7 +430,7 @@ impl App {
KeyCode::Down if alt => self.out_scroll += 1,
KeyCode::PageUp if alt => self.out_scroll = self.out_scroll.saturating_sub(20),
KeyCode::PageDown if alt => self.out_scroll += 20,
- KeyCode::Esc if self.running => self.toggle_run(),
+ KeyCode::Esc if self.session.running => self.toggle_run(),
_ => {
self.editor.input(key);
}
@@ -608,7 +443,7 @@ impl App {
KeyCode::Enter => {
let mut bytes = std::mem::take(&mut self.serial_input).into_bytes();
bytes.push(b'\r');
- self.sim.uart_send(&bytes);
+ self.session.sim.uart_send(&bytes);
return;
}
KeyCode::Backspace => {
@@ -628,7 +463,7 @@ impl App {
KeyCode::Tab => self.cycle_focus(true),
KeyCode::BackTab => self.cycle_focus(false),
KeyCode::Esc => {
- if self.running {
+ if self.session.running {
self.toggle_run();
} else if self.focus == Focus::Serial {
self.focus = Focus::Source;
@@ -637,9 +472,9 @@ impl App {
}
}
KeyCode::Char('+') | KeyCode::Char('=') => {
- self.speed = (self.speed + 1).min(SPEEDS.len() - 1)
+ self.session.speed = (self.session.speed + 1).min(SPEEDS.len() - 1)
}
- KeyCode::Char('-') => self.speed = self.speed.saturating_sub(1),
+ KeyCode::Char('-') => self.session.speed = self.session.speed.saturating_sub(1),
KeyCode::Char('?') => self.show_help = true,
// Letter aliases for terminals that swallow function keys.
KeyCode::Char('r') => self.toggle_run(),
@@ -684,6 +519,7 @@ impl App {
fn move_src(&mut self, code: KeyCode, page: usize) {
let max = self
+ .session
.build
.as_ref()
.map_or(0, |b| b.source.len().saturating_sub(1));
@@ -694,7 +530,7 @@ impl App {
KeyCode::PageDown => self.src_cursor + page,
KeyCode::Home => 0,
KeyCode::End => max,
- KeyCode::Char('.') => self.pc_line().unwrap_or(self.src_cursor),
+ KeyCode::Char('.') => self.session.pc_line().unwrap_or(self.src_cursor),
_ => self.src_cursor,
}
.min(max);
@@ -745,7 +581,7 @@ impl App {
KeyCode::Left => *bit = (*bit + 1).min(7),
KeyCode::Right => *bit = bit.saturating_sub(1),
KeyCode::Char(' ') | KeyCode::Enter => {
- self.sim.pins[*port] ^= 1 << *bit;
+ self.session.sim.pins[*port] ^= 1 << *bit;
}
_ => {}
}
@@ -786,38 +622,14 @@ impl App {
parts.first().and_then(|s| parse(s)),
parts.get(1).and_then(|s| parse(s)),
) else {
- self.status = "usage: (hex), e.g. 30 FF".into();
+ self.session.status = "usage: (hex), e.g. 30 FF".into();
return;
};
if val > 0xFF {
- self.status = "value must be a byte".into();
+ self.session.status = "value must be a byte".into();
return;
}
- let v = val as u8;
- let ok = match self.mem_tab {
- MemTab::Iram if addr <= 0xFF => {
- self.sim.iram[addr as usize] = v;
- true
- }
- MemTab::Sfr if (0x80..=0xFF).contains(&addr) => {
- self.sim.set_sfr(addr as u8, v);
- true
- }
- MemTab::Xram if addr <= 0xFFFF => {
- self.sim.xram[addr as usize] = v;
- true
- }
- MemTab::Code if addr <= 0xFFFF => {
- self.sim.code[addr as usize] = v;
- true
- }
- _ => false,
- };
- self.status = if ok {
- format!("wrote {v:02X}h at {addr:X}h")
- } else {
- "address out of range".into()
- };
+ self.session.poke(self.mem_tab, addr, val as u8);
}
}
@@ -848,46 +660,6 @@ fn editor_command(path: &Path, line: usize) -> Command {
cmd
}
-/// Builds an assembler source from a HEX image by disassembling each
-/// contiguous run of bytes. Reassembling it reproduces the image exactly.
-fn disassemble_image(bytes: &[(u16, u8)], path: &Path) -> String {
- let mut code = Box::new([0u8; 0x10000]);
- let mut used = vec![false; 0x10000];
- for &(a, b) in bytes {
- code[a as usize] = b;
- used[a as usize] = true;
- }
- let mut src = format!("; disassembled from {}\n", path.display());
- let mut addr = 0usize;
- while addr < 0x10000 {
- if !used[addr] {
- addr += 1;
- continue;
- }
- src.push_str(&format!(
- "\n ORG {}\n",
- crate::sfr::hex16(addr as u16)
- ));
- while addr < 0x10000 && used[addr] {
- let d = disasm::disassemble(&code, addr as u16);
- let size = d.size as usize;
- if (addr..addr + size).all(|a| a < 0x10000 && used[a]) {
- src.push_str(&format!(" {:<24}; {:04X}\n", d.text, addr));
- addr += size;
- } else {
- src.push_str(&format!(
- " DB {:<21}; {:04X}\n",
- crate::sfr::hex8(code[addr]),
- addr
- ));
- addr += 1;
- }
- }
- }
- src.push_str(" END\n");
- src
-}
-
const TEMPLATE: &str = "\
; New 8051 program. F7 assembles, F5 runs, F11 steps, F1 shows all keys.
ORG 0000h
diff --git a/src/ui/draw.rs b/src/ui/draw.rs
index 36f7db9..050158d 100644
--- a/src/ui/draw.rs
+++ b/src/ui/draw.rs
@@ -5,9 +5,10 @@ use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Borders, Clear, Paragraph, Tabs, Wrap};
use ratatui_textarea::TextArea;
-use super::app::{App, Focus, MemTab, Mode, OutTab, PromptKind, SPEEDS};
+use super::app::{App, Focus, MemTab, Mode, OutTab, PromptKind};
use super::syntax::highlight;
-use crate::sfr::{self, IE, IP, PCON, PSW, SCON, TCON, TH0, TH1, TL0, TL1, TMOD};
+use bench51_core::session::{SPEEDS, vector_name};
+use bench51_core::sfr::{self, IE, IP, PCON, PSW, SCON, TCON, TH0, TH1, TL0, TL1, TMOD};
const ACCENT: Color = Color::Cyan;
const CHANGED: Style = Style::new().fg(Color::Yellow).add_modifier(Modifier::BOLD);
@@ -73,12 +74,12 @@ fn draw_header(f: &mut Frame, app: &App, area: Rect) {
Style::new().bg(Color::Magenta).fg(Color::White).bold(),
),
};
- let (state, state_style) = if app.running {
+ let (state, state_style) = if app.session.running {
(
" RUNNING ",
Style::new().bg(Color::Green).fg(Color::Black).bold(),
)
- } else if app.build.is_none() {
+ } else if app.session.build.is_none() {
(
" NOT BUILT ",
Style::new().bg(Color::DarkGray).fg(Color::White),
@@ -96,14 +97,14 @@ fn draw_header(f: &mut Frame, app: &App, area: Rect) {
Span::styled(state, state_style),
Span::raw(format!(" {}", app.title())),
];
- if app.build.is_some() && app.stale() {
+ if app.session.build.is_some() && app.stale() {
spans.push(Span::styled(
" (source changed — F7 to rebuild)",
Style::new().fg(Color::Yellow),
));
}
spans.push(Span::styled(
- format!(" speed {}/frame (+/-)", SPEEDS[app.speed]),
+ format!(" speed {}/frame (+/-)", SPEEDS[app.session.speed]),
DIM,
));
f.render_widget(Line::from(spans), area);
@@ -137,7 +138,7 @@ fn draw_footer(f: &mut Frame, app: &App, area: Rect) {
}
};
let width = area.width as usize;
- let status = format!(" {}", app.status);
+ let status = format!(" {}", app.session.status);
let pad = width.saturating_sub(status.chars().count() + keys.len() + 1);
let line = Line::from(vec![
Span::styled(status, Style::new().fg(Color::White)),
@@ -163,16 +164,16 @@ fn draw_edit(f: &mut Frame, app: &mut App, area: Rect) {
// Breakpoint / error markers aligned with the editor's scroll position.
let top = app.editor.scroll_offset().0 as usize;
let errors: Vec = app
- .last_asm
- .as_ref()
- .filter(|(src, _)| *src == app.text())
- .map(|(_, o)| o.diagnostics.iter().map(|d| d.line).collect())
- .unwrap_or_default();
+ .session
+ .diagnostics_for(&app.text())
+ .iter()
+ .map(|d| d.line)
+ .collect();
let marks: Vec = (top..top + gutter.height as usize)
.map(|l| {
if errors.contains(&l) {
Line::styled("✗", Style::new().fg(Color::Red).bold())
- } else if app.breakpoints.contains(&l) {
+ } else if app.session.breakpoints.contains(&l) {
Line::styled("●", Style::new().fg(Color::Red))
} else {
Line::raw("")
@@ -186,6 +187,7 @@ fn draw_edit(f: &mut Frame, app: &mut App, area: Rect) {
fn draw_output(f: &mut Frame, app: &mut App, area: Rect) {
let n_err = app
+ .session
.last_asm
.as_ref()
.map_or(0, |(_, o)| o.diagnostics.len());
@@ -214,7 +216,7 @@ fn draw_output(f: &mut Frame, app: &mut App, area: Rect) {
.highlight_style(Style::new().fg(ACCENT).bold().underlined());
f.render_widget(tabs, tabs_area);
- let lines: Vec = match (app.out_tab, &app.last_asm) {
+ let lines: Vec = match (app.out_tab, &app.session.last_asm) {
(_, None) => vec![Line::styled("Press F7 to assemble.", DIM)],
(OutTab::Listing, Some((src, out))) => out
.listing(src)
@@ -312,7 +314,7 @@ fn draw_source(f: &mut Frame, app: &mut App, area: Rect) {
let block = panel("Source", focused);
let inner = block.inner(area);
f.render_widget(block, area);
- let Some(build) = &app.build else {
+ let Some(build) = &app.session.build else {
f.render_widget(
Paragraph::new("Nothing assembled yet — press F7.").style(DIM),
inner,
@@ -326,7 +328,7 @@ fn draw_source(f: &mut Frame, app: &mut App, area: Rect) {
} else if app.src_cursor >= app.src_scroll + h {
app.src_scroll = app.src_cursor + 1 - h;
}
- let pc_line = build.addr_to_line.get(&app.sim.pc).copied();
+ let pc_line = build.addr_to_line.get(&app.session.sim.pc).copied();
let lines: Vec = build
.source
.iter()
@@ -343,7 +345,7 @@ fn draw_source(f: &mut Frame, app: &mut App, area: Rect) {
} else {
Style::new()
};
- let bp = if app.breakpoints.contains(&i) {
+ let bp = if app.session.breakpoints.contains(&i) {
Span::styled("●", bg.fg(Color::Red))
} else {
Span::styled(" ", bg)
@@ -394,27 +396,20 @@ fn flags(byte: u8, names: [&'static str; 8]) -> Vec> {
}
fn draw_registers(f: &mut Frame, app: &App, area: Rect) {
- let s = &app.sim;
+ let s = &app.session.sim;
let block = panel("Registers", false);
let inner = block.inner(area);
f.render_widget(block, area);
- let ch = |addr: u8| s.sfr(addr) != app.prev_sfr[(addr & 0x7F) as usize];
+ let ch = |addr: u8| s.sfr(addr) != app.session.prev_sfr[(addr & 0x7F) as usize];
let reg = |n: u8| {
let a = s.reg_addr(n) as usize;
vec![
Span::styled(format!("R{n} "), LABEL),
- hex2(s.iram[a], s.iram[a] != app.prev_iram[a]),
+ hex2(s.iram[a], s.iram[a] != app.session.prev_iram[a]),
Span::raw(" "),
]
};
- let micros = s.cycles as f64 * 12.0 / app.clock_mhz;
- let time = if micros >= 1_000_000.0 {
- format!("{:.3} s", micros / 1e6)
- } else if micros >= 1000.0 {
- format!("{:.3} ms", micros / 1e3)
- } else {
- format!("{micros:.2} µs")
- };
+ let time = app.session.elapsed();
let lines = vec![
Line::from(vec![
Span::styled("PC ", LABEL),
@@ -461,18 +456,18 @@ fn draw_registers(f: &mut Frame, app: &App, area: Rect) {
Line::from(vec![
Span::styled("Time ", LABEL),
Span::raw(time),
- Span::styled(format!(" @{}MHz", app.clock_mhz), DIM),
+ Span::styled(format!(" @{}MHz", app.session.clock_mhz), DIM),
]),
];
f.render_widget(Paragraph::new(lines), inner);
}
fn draw_peripherals(f: &mut Frame, app: &App, area: Rect) {
- let s = &app.sim;
+ let s = &app.session.sim;
let block = panel("Peripherals", false);
let inner = block.inner(area);
f.render_widget(block, area);
- let ch = |addr: u8| s.sfr(addr) != app.prev_sfr[(addr & 0x7F) as usize];
+ let ch = |addr: u8| s.sfr(addr) != app.session.prev_sfr[(addr & 0x7F) as usize];
let sfr_val = |name: &'static str, addr: u8| {
vec![
Span::styled(name, LABEL),
@@ -609,17 +604,6 @@ fn draw_peripherals(f: &mut Frame, app: &App, area: Rect) {
f.render_widget(Paragraph::new(lines), inner);
}
-fn vector_name(v: u16) -> &'static str {
- match v {
- 0x03 => "INT0",
- 0x0B => "T0",
- 0x13 => "INT1",
- 0x1B => "T1",
- 0x23 => "UART",
- _ => "?",
- }
-}
-
fn draw_memory(f: &mut Frame, app: &mut App, area: Rect) {
let focused = app.focus == Focus::Memory;
let block = panel("Memory", focused);
@@ -646,7 +630,7 @@ fn draw_memory(f: &mut Frame, app: &mut App, area: Rect) {
return;
}
- let s = &app.sim;
+ let s = &app.session.sim;
let per_row: usize = if content.width >= 74 { 16 } else { 8 };
let total = match app.mem_tab {
MemTab::Iram => 256,
@@ -655,9 +639,9 @@ fn draw_memory(f: &mut Frame, app: &mut App, area: Rect) {
let rows = total / per_row;
let h = content.height as usize;
app.mem_scroll = app.mem_scroll.min(rows.saturating_sub(h));
- let bps = app.bp_addrs();
+ let bps = app.session.bp_addrs();
let pc = s.pc as usize;
- let pc_len = crate::isa::info(s.code[pc]).map_or(1, |i| i.size as usize);
+ let pc_len = bench51_core::isa::info(s.code[pc]).map_or(1, |i| i.size as usize);
let bank = s.reg_addr(0) as usize;
let lines: Vec = (app.mem_scroll..rows.min(app.mem_scroll + h))
@@ -679,7 +663,7 @@ fn draw_memory(f: &mut Frame, app: &mut App, area: Rect) {
let v = s.iram[a];
let st = if a == s.sp() as usize {
Style::new().fg(Color::Black).bg(Color::LightMagenta)
- } else if v != app.prev_iram[a] {
+ } else if v != app.session.prev_iram[a] {
CHANGED
} else if (bank..bank + 8).contains(&a) {
Style::new().fg(Color::LightBlue)
@@ -724,7 +708,7 @@ fn draw_memory(f: &mut Frame, app: &mut App, area: Rect) {
}
fn draw_sfr_table(f: &mut Frame, app: &App, area: Rect) {
- let s = &app.sim;
+ let s = &app.session.sim;
let cols = if area.width >= 64 { 3 } else { 2 };
let per_col = sfr::SFRS.len().div_ceil(cols);
let lines: Vec = (0..per_col)
@@ -733,7 +717,7 @@ fn draw_sfr_table(f: &mut Frame, app: &App, area: Rect) {
for c in 0..cols {
if let Some(&(name, addr)) = sfr::SFRS.get(c * per_col + r) {
let v = s.read_direct(addr, true);
- let changed = s.sfr(addr) != app.prev_sfr[(addr & 0x7F) as usize];
+ let changed = s.sfr(addr) != app.session.prev_sfr[(addr & 0x7F) as usize];
spans.push(Span::styled(format!("{name:<5}"), LABEL));
spans.push(Span::styled(format!("{addr:02X} "), DIM));
spans.push(hex2(v, changed));
@@ -754,7 +738,7 @@ fn draw_ports(f: &mut Frame, app: &App, area: Rect) {
let block = panel("Ports", focused);
let inner = block.inner(area);
f.render_widget(block, area);
- let s = &app.sim;
+ let s = &app.session.sim;
let mut lines: Vec = (0..4)
.map(|p| {
let latch = s.sfr(sfr::P0 + 0x10 * p as u8);
@@ -797,7 +781,7 @@ fn draw_serial(f: &mut Frame, app: &App, area: Rect) {
Layout::vertical([Constraint::Min(1), Constraint::Length(1)]).areas(inner);
let mut text = String::new();
- for &b in &app.sim.uart.tx_log {
+ for &b in &app.session.sim.uart.tx_log {
match b {
b'\n' => text.push('\n'),
b'\r' => {}
diff --git a/src/ui/syntax.rs b/src/ui/syntax.rs
index 513450a..665525a 100644
--- a/src/ui/syntax.rs
+++ b/src/ui/syntax.rs
@@ -1,122 +1,27 @@
-//! Minimal 8051 assembly syntax highlighting.
+//! 8051 assembly syntax highlighting for the TUI.
+use bench51_core::syntax::{Tok, tokens};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::Span;
-use crate::{isa, sfr};
-
-const COMMENT: Style = Style::new().fg(Color::DarkGray);
-const LABEL: Style = Style::new().fg(Color::Yellow);
-const MNEMONIC: Style = Style::new().fg(Color::Cyan).add_modifier(Modifier::BOLD);
-const DIRECTIVE: Style = Style::new().fg(Color::Magenta);
-const REGISTER: Style = Style::new().fg(Color::LightBlue);
-const NUMBER: Style = Style::new().fg(Color::LightGreen);
-const STRING: Style = Style::new().fg(Color::Green);
-const SFR: Style = Style::new().fg(Color::LightMagenta);
-
-fn is_directive(w: &str) -> bool {
- matches!(
- w,
- "ORG"
- | "DB"
- | "DW"
- | "DS"
- | "END"
- | "EQU"
- | "SET"
- | "BIT"
- | "DATA"
- | "IDATA"
- | "XDATA"
- | "CODE"
- | "CSEG"
- | "XSEG"
- | "DSEG"
- | "AT"
- | "USING"
- | "NAME"
- | "BYTE"
- | "WORD"
- )
-}
-
-fn word_style(w: &str, first_word: bool) -> Style {
- let u = w.to_ascii_uppercase();
- let reg = matches!(u.as_str(), "A" | "AB" | "C" | "DPTR" | "PC")
- || (u.len() == 2
- && u.starts_with('R')
- && u.as_bytes()[1].is_ascii_digit()
- && u.as_bytes()[1] < b'8');
- if reg {
- REGISTER
- } else if is_directive(&u) {
- DIRECTIVE
- } else if first_word && isa::is_mnemonic(&u) {
- MNEMONIC
- } else if sfr::SFRS.iter().chain(sfr::BITS).any(|(n, _)| *n == u) {
- SFR
- } else if matches!(
- u.as_str(),
- "HIGH" | "LOW" | "MOD" | "AND" | "OR" | "XOR" | "NOT" | "SHL" | "SHR"
- ) {
- DIRECTIVE
- } else {
- Style::new()
+fn style(t: Tok) -> Style {
+ match t {
+ Tok::Plain => Style::new(),
+ Tok::Comment => Style::new().fg(Color::DarkGray),
+ Tok::Label => Style::new().fg(Color::Yellow),
+ Tok::Mnemonic => Style::new().fg(Color::Cyan).add_modifier(Modifier::BOLD),
+ Tok::Directive => Style::new().fg(Color::Magenta),
+ Tok::Register => Style::new().fg(Color::LightBlue),
+ Tok::Number => Style::new().fg(Color::LightGreen),
+ Tok::Str => Style::new().fg(Color::Green),
+ Tok::Sfr => Style::new().fg(Color::LightMagenta),
}
}
/// Splits a source line into styled spans, applying `base` underneath.
pub fn highlight(line: &str, base: Style) -> Vec> {
- let chars: Vec = line.chars().collect();
- let mut spans = Vec::new();
- let mut i = 0;
- let mut seen_word = false;
- let push = |spans: &mut Vec>, s: String, st: Style| {
- spans.push(Span::styled(s, base.patch(st)))
- };
- while i < chars.len() {
- let c = chars[i];
- let start = i;
- if c == ';' {
- push(&mut spans, chars[i..].iter().collect(), COMMENT);
- break;
- } else if c == '\'' || c == '"' {
- i += 1;
- while i < chars.len() && chars[i] != c {
- i += 1;
- }
- i = (i + 1).min(chars.len());
- push(&mut spans, chars[start..i].iter().collect(), STRING);
- } else if c.is_ascii_alphabetic() || c == '_' || c == '?' {
- while i < chars.len()
- && (chars[i].is_ascii_alphanumeric() || chars[i] == '_' || chars[i] == '?')
- {
- i += 1;
- }
- let w: String = chars[start..i].iter().collect();
- let is_label = !seen_word && chars.get(i) == Some(&':');
- let style = if is_label {
- LABEL
- } else {
- let st = word_style(&w, !seen_word);
- seen_word = true;
- st
- };
- push(&mut spans, w, style);
- } else if c.is_ascii_digit() || c == '#' || c == '$' {
- i += 1;
- while i < chars.len() && chars[i].is_ascii_alphanumeric() {
- i += 1;
- }
- push(&mut spans, chars[start..i].iter().collect(), NUMBER);
- } else {
- while i < chars.len()
- && !(chars[i].is_ascii_alphanumeric() || "_?;'\"#$".contains(chars[i]))
- {
- i += 1;
- }
- push(&mut spans, chars[start..i].iter().collect(), Style::new());
- }
- }
- spans
+ tokens(line)
+ .into_iter()
+ .map(|(r, t)| Span::styled(line[r].to_string(), base.patch(style(t))))
+ .collect()
}