From 819778f292ee4e1294603b98662e083e49e23463 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sat, 1 Aug 2026 19:52:05 +0200 Subject: rsnix v0.5.0: graphics layer + cursor compositor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The first visible GUI surface: real rect primitives, a single shadow→display push path, and an on-screen mouse cursor that can never race the text surface. gop: - fill_rect + push_rect(x,y,w,h): every raster op rasterises into the RAM shadow, then push_rect copies the rect to the display (write-only, still never read) and composites the cursor on top. blit_glyph and scroll shifts now route through it. - cursor overlay: 12x16 pointer (const-fn built from column lists) drawn white with a black offset outline; position in one AtomicU64 (x:high 32, y:low 32) — unpack masks the low word (a bare 'as usize' cast is a no-op on 64-bit). The cursor never enters the shadow, so erasing is just a shadow push of the old rect. - cursor_redraw after scroll shifts and once at spawn (the vt diff never re-blits idle cells). cursor task (task 2, spawned at boot when a mouse is present): - owns the PS/2 ring; polls every 10 ms, moves the cursor (clamped), tracks buttons, and forwards every event to a task's queue when 'mouse ' armed it (the window-manager input path). - /dev/mouse is now a position device (x/y/buttons snapshot); 'mouse' watches the cursor live (prints on change); 'cursor' prints one-shot state; 'gfx' draws a status-bar demo; 'gfx check' is an in-kernel pixel self-test (shadow readback, display readback, cursor overlay purity) — PASS/FAIL per stage. Tests (headless QEMU + monitor injection): - make test-gfx (new): all four compositor checks PASS. - make test-mouse (rewritten): cursor tracks mouse_move deltas, buttons ride along, /dev/mouse snapshot, live watch, real-event queue routing. - make test-msg: task numbering shifted (cursor is task 2; msgrecv is task 3) — updated, still PASS. - make test-disk regression re-passes. 0 build warnings. --- CONTEXT.md | 74 +++++++++++--- Cargo.lock | 6 +- Cargo.toml | 2 +- Makefile | 5 +- rsdos/src/main.rs | 5 + rsnix/src/cursor.rs | 71 +++++++++++++ rsnix/src/fs.rs | 37 +++---- rsnix/src/gop.rs | 268 ++++++++++++++++++++++++++++++++++++++++++++++++-- rsnix/src/lib.rs | 1 + scripts/test-gfx.sh | 114 +++++++++++++++++++++ scripts/test-mouse.sh | 125 ++++++++++++++--------- scripts/test-msg.sh | 37 +++---- shell/src/lib.rs | 194 +++++++++++++++++++++++++++++------- 13 files changed, 791 insertions(+), 148 deletions(-) create mode 100644 rsnix/src/cursor.rs create mode 100755 scripts/test-gfx.sh diff --git a/CONTEXT.md b/CONTEXT.md index 9ceb81d..bfe0170 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -113,9 +113,10 @@ Workspace version is `a.b.c` (single version for all crates): Bump the workspace version in the root `Cargo.toml` when a change of that class lands — do not leave the version to drift. Current: -`0.4.0` — the GUI input foundation (PS/2 mouse + scheduler message -queues) landed as a `b` bump; the GUI era itself is reserved for the -`a` bump (1.0.0). +`0.5.0` — the GUI era landed (graphics layer + cursor compositor) as a +`b` bump from the 0.4.0 input foundation; a future major GUI overhaul +(graphics windows beyond the text surface) would be the `a` bump +(1.0.0). ## Project layout @@ -426,19 +427,24 @@ Workspace of four crates, all built for the `x86_64-unknown-uefi` target: relative** (`dx` + = right, `dy` + = down — the PS/2 Y-up wire convention is negated), buttons decoded; 9-bit sign extension via the packet sign bits. -- `fs`: `/dev/mouse` char device — `cat /dev/mouse` drains up to 32 - pending events (`dx=+N dy=+N buttons=L-R`), reports - `mouse: no PS/2 mouse` / `mouse: no events` otherwise. -- shell: `mouse` command streams live events (10 ms poll via - `sleep_ms`) until ^C. +- `fs`: `/dev/mouse` is now a **position device** — `cat /dev/mouse` + prints the cursor's current state (`x=N y=N buttons=---`), since + the cursor task owns the PS/2 ring; `mouse: no PS/2 mouse` + otherwise. +- shell: `mouse` **watches the on-screen cursor** (x/y/buttons, + printed only on change, 10 ms poll) until ^C; `mouse ` also + routes every decoded event to that task's queue (`cursor still + tracks`, route cleared on exit). `cursor` prints a one-shot state + line (the parseable test surface). Verified in QEMU (`make test-mouse`, headless, via the monitor's - `mouse_move`/`mouse_button` HMP commands): boot line `ps2: mouse - ready`, `/dev/mouse` drains a pre-consumer move (`8,4`), the live - stream decodes `mouse_move 20 7` → `dx=+20 dy=+7 buttons=---`, - `mouse_button 1` → `buttons=L--`, a held-button move - (`-5,-3` while L down) → `dx=-5 dy=-3 buttons=L--`, release, - and ^C stops the stream. `make test-disk` regression re-passes. + `mouse_move`/`mouse_button` HMP commands): the cursor starts centred, + `mouse_move 20 7` moves it +20/+7 (asserted against `cursor` output), + `mouse_button 1` → `buttons=L--`, a held-button move (`-5,-3`) + tracks position *and* keeps the button, release clears, `/dev/mouse` + reports the same position snapshot, the live `mouse` watch prints the + changed line and ^C stops it, and `mouse 3` routes a real move into + the msgrecv task's queue. `make test-disk` regression re-passes. ✅ **Scheduler message queues (the GUI-era primitive from ADR 0003)** — every task gets a static 16-slot ring of `TaskMsg` (4 KB in .bss, @@ -475,6 +481,46 @@ Workspace of four crates, all built for the `x86_64-unknown-uefi` target: the shell's never-consumed queue), and `jobs` shows q=0 + task back to `blocked` after draining. `make test-disk` regression re-passes. +✅ **Graphics layer + cursor compositor** — the first visible GUI + surface: real rect primitives, a shadow→display push path, and an + on-screen mouse cursor that never races the text surface: + +- `gop`: `fill_rect` + `push_rect(x,y,w,h)` — the **single display + write path**. Every raster op rasterises into the RAM shadow + first, then `push_rect` copies that rect to the display (write- + only; the display is still never *read*) and composites the + cursor on top. `blit_glyph` and scroll shifts now route through + it, so text redraws can never erase or corrupt the cursor. The + cursor lives *only* in the overlay — never in the shadow — which + makes save/restore impossible to get wrong: erasing = push the + old rect (the shadow simply doesn't contain the cursor there). +- cursor bitmap: 12×16 pointer built by a const fn from explicit + column lists (hand-mangled bit literals were the one real bug + this round — twice), drawn white with a black offset outline + (+1,+1). Position lives in one `AtomicU64` (x:high 32, y:low 32) + so a relaxed load never sees a torn pair — *and* the unpack must + mask the low word (a bare `as usize` cast is a no-op on 64-bit + and returned the whole packed value). +- `cursor` task (spawned at boot when the mouse is present, task 2): + polls the PS/2 ring every 10 ms, moves the cursor via + `cursor_move` (clamped to the screen; erase-old + draw-new are + both shadow pushes), tracks buttons, and forwards every event to + a task's queue when `mouse ` armed it. The cursor is drawn + once at spawn (the vt diff never re-blits idle cells) and stays + visible because every display write composites it; scrolls + re-overlay it after the bulk shift. +- shell: `gfx` draws a status-bar demo scene (navy strip + RGB + boxes); `gfx check` is an in-kernel pixel self-test — draws a red + rect, reads it back from the shadow *and* the display, asserts + the cursor tip is white on the display but absent from the shadow + (overlay purity), and prints PASS/FAIL per stage. + + Verified in QEMU (`make test-gfx`): `fill_rect/shadow: OK`, + `display push: OK`, `cursor overlay: OK`, `cursor not in shadow: + OK`, `gfx check: PASS`; the demo draws; the cursor tracks injected + mouse input (test-mouse) with the overlay intact. `make test-disk` + regression re-passes. + ## Known issues / perf notes - **Scroll cost** — scrolling still shifts the whole framebuffer (a diff --git a/Cargo.lock b/Cargo.lock index 444738e..19806d4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,7 +4,7 @@ version = 4 [[package]] name = "rsdos" -version = "0.4.0" +version = "0.5.0" dependencies = [ "rsnix", "shell", @@ -19,11 +19,11 @@ dependencies = [ [[package]] name = "rsnix" -version = "0.4.0" +version = "0.5.0" [[package]] name = "shell" -version = "0.4.0" +version = "0.5.0" dependencies = [ "rsdosedit", "rsnix", diff --git a/Cargo.toml b/Cargo.toml index 2864712..273966b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "2" members = ["rsnix", "shell", "rsdos", "rsdosedit"] [workspace.package] -version = "0.4.0" +version = "0.5.0" edition = "2024" # no_std UEFI kernel: no unwinder available, so panic must abort. diff --git a/Makefile b/Makefile index f244251..9604893 100644 --- a/Makefile +++ b/Makefile @@ -14,7 +14,7 @@ export BOOT_EFI=$(ESP_DIR)/EFI/BOOT/BOOTX64.EFI # Create one with: make disk (or: ./scripts/mkdisk.sh) export DISK_IMG ?= /tmp/disk.img -.PHONY: all run run-gui clean image debug release fmt bootloader boot-image disk disk-fresh inspect test-disk test-mouse test-msg +.PHONY: all run run-gui clean image debug release fmt bootloader boot-image disk disk-fresh inspect test-disk test-mouse test-gfx test-msg # ---- Build --------------------------------------------------------------- @@ -118,6 +118,9 @@ test-disk: test-mouse: ./scripts/test-mouse.sh +test-gfx: + ./scripts/test-gfx.sh + # Automated scheduler message-queue round trip: msgrecv/send, real-input # routing into a task's queue, queue-full boundary. test-msg: diff --git a/rsdos/src/main.rs b/rsdos/src/main.rs index fc47c82..13923ea 100644 --- a/rsdos/src/main.rs +++ b/rsdos/src/main.rs @@ -219,6 +219,11 @@ pub unsafe extern "efiapi" fn efi_main(image_handle: Handle, system_table: *mut } rsnix::serial_println!("boot: entering shell"); + if rsnix::ps2::mouse_present() { + rsnix::cursor::spawn(); + } else { + rsnix::serial_println!("cursor: no mouse — overlay disabled"); + } shell::run(); } diff --git a/rsnix/src/cursor.rs b/rsnix/src/cursor.rs new file mode 100644 index 0000000..18c9a1d --- /dev/null +++ b/rsnix/src/cursor.rs @@ -0,0 +1,71 @@ +// --------------------------------------------------------------------------- +// cursor — the mouse cursor task. +// +// One background task owns the PS/2 mouse: it polls the packet ring every +// 10 ms, moves the on-screen cursor (gop's display overlay), tracks the +// button state, and optionally *forwards* every event to another task's +// message queue (`mouse ` sets the target) — the input-routing half +// of the future window manager. +// +// The cursor itself never touches the text surface: `gop::push_rect` +// composites it on top of every display write, so text scrolling and +// cursor movement cannot corrupt each other (see gop.rs). +// --------------------------------------------------------------------------- +use core::sync::atomic::{AtomicUsize, Ordering}; + +use crate::ps2::MouseEvent; +use crate::sched::TaskMsg; + +/// Forward target task id, or `usize::MAX` = none. +static FORWARD_TARGET: AtomicUsize = AtomicUsize::new(usize::MAX); + +/// Spawn the cursor task. Call after `sched::init`; only makes sense +/// when the PS/2 mouse came up at boot. The cursor starts centred. +pub fn spawn() -> Option { + let (w, h) = crate::gop::pixel_dims(); + crate::gop::cursor_set(w / 2 - 6, h / 2 - 8); + // Draw it immediately: the vt diff only re-blits changed cells, so an + // idle centre cell would never push (and thus never composite) it. + crate::gop::cursor_redraw(); + let id = crate::sched::spawn(task_main, "cursor")?; + crate::serial_println!( + "cursor: task {} — mouse poll + display overlay (forward target: none)", + id + ); + Some(id) +} + +/// Route decoded mouse events to a task's queue (the shell's `mouse +/// `). `None` stops forwarding. +pub fn set_forward(target: Option) { + FORWARD_TARGET.store(target.unwrap_or(usize::MAX), Ordering::Relaxed); +} + +fn forward_target() -> Option { + match FORWARD_TARGET.load(Ordering::Relaxed) { + usize::MAX => None, + id => Some(id), + } +} + +fn task_main() { + loop { + while let Some(ev) = crate::ps2::try_poll_mouse() { + crate::gop::cursor_move(ev.dx, ev.dy); + crate::gop::cursor_set_buttons(btn_bits(&ev)); + if let Some(id) = forward_target() + && crate::sched::send(id, TaskMsg::Mouse(ev)).is_err() + { + // The listener died mid-stream: stop routing (the + // cursor keeps tracking) rather than spam errors. + set_forward(None); + crate::serial_println!("cursor: forward target task {} gone — stopped routing", id); + } + } + crate::sched::sleep_ms(10); + } +} + +fn btn_bits(ev: &MouseEvent) -> u8 { + (ev.left as u8) | ((ev.right as u8) << 1) | ((ev.middle as u8) << 2) +} diff --git a/rsnix/src/fs.rs b/rsnix/src/fs.rs index 0b7a772..5fc6d7a 100644 --- a/rsnix/src/fs.rs +++ b/rsnix/src/fs.rs @@ -713,34 +713,23 @@ fn dev_text(dev: CharDevice, _pos: u64) -> String { } } -/// Render `/dev/mouse`: drain every pending PS/2 event (up to 32) into one -/// line each, so `cat /dev/mouse` shows the movement that happened since -/// the last read. Falls back to a clear message when there is no device or -/// nothing pending. +/// Render `/dev/mouse`: the current cursor state (position + buttons). +/// The cursor task owns the PS/2 ring, so this is a position device — +/// the GUI-correct semantic — rather than an event drain. fn mouse_text() -> String { if !crate::ps2::mouse_present() { return String::from("mouse: no PS/2 mouse\n"); } - let mut s = String::new(); - for _ in 0..32 { - let Some(ev) = crate::ps2::try_poll_mouse() else { - break; - }; - let mut b = String::new(); - b.push(if ev.left { 'L' } else { '-' }); - b.push(if ev.right { 'R' } else { '-' }); - b.push(if ev.middle { 'M' } else { '-' }); - s.push_str(&alloc::format!( - "dx={:+} dy={:+} buttons={}\n", - ev.dx, - ev.dy, - b - )); - } - if s.is_empty() { - s.push_str("mouse: no events\n"); - } - s + let (x, y) = crate::gop::cursor_pos(); + let b = crate::gop::cursor_buttons(); + alloc::format!( + "x={} y={} buttons={}{}{}\n", + x, + y, + if b & 1 != 0 { 'L' } else { '-' }, + if b & 2 != 0 { 'R' } else { '-' }, + if b & 4 != 0 { 'M' } else { '-' } + ) } // --- self-test ------------------------------------------------------------ diff --git a/rsnix/src/gop.rs b/rsnix/src/gop.rs index 0d24d7d..9dedcb8 100644 --- a/rsnix/src/gop.rs +++ b/rsnix/src/gop.rs @@ -10,11 +10,11 @@ use alloc::vec; use alloc::vec::Vec; use core::fmt; use core::ptr; +use core::sync::atomic::{AtomicU8, AtomicU64, Ordering}; /// Framebuffer state captured before ExitBootServices. pub struct Framebuffer { base: *mut u8, - #[allow(dead_code)] width: usize, height: usize, pitch: usize, // bytes per scan line @@ -119,6 +119,242 @@ pub fn dims() -> (usize, usize) { } } +/// (width, height) of the framebuffer in pixels. +pub fn pixel_dims() -> (usize, usize) { + match fb().as_ref() { + Some(f) => (f.width, f.height), + None => (0, 0), + } +} + +// --------------------------------------------------------------------------- +// Rect primitives + the push path +// --------------------------------------------------------------------------- + +/// Copy a shadow rect to the display and composite the mouse cursor on +/// top. Every display write goes through here (glyph blits, fills, +/// scroll shifts), so the cursor — which lives *only* in this overlay, +/// never in the shadow — stays on top of whatever the content is without +/// any save/restore bookkeeping. The display is never read. +pub(crate) fn push_rect(x: usize, y: usize, w: usize, h: usize) { + let Some(fb) = fb().as_ref() else { + return; + }; + if unsafe { SHADOW.is_null() } || x >= fb.width || y >= fb.height { + return; + } + let w = w.min(fb.width - x); + let h = h.min(fb.height - y); + let row_words = fb.pitch / 4; + unsafe { + for dy in 0..h { + let off = (y + dy) * row_words + x; + ptr::copy_nonoverlapping(SHADOW.add(off), fb.base.add(off * 4) as *mut u32, w); + } + } + overlay_cursor(x, y, w, h); +} + +/// Fill a rectangle in the shadow and push it (with cursor composited). +pub fn fill_rect(x: usize, y: usize, w: usize, h: usize, color: u32) { + let Some(fb) = fb().as_ref() else { + return; + }; + if x >= fb.width || y >= fb.height { + return; + } + let w = w.min(fb.width - x); + let h = h.min(fb.height - y); + if unsafe { SHADOW.is_null() } { + // Degraded: no backbuffer — write the display directly. + let row_words = fb.pitch / 4; + unsafe { + for dy in 0..h { + let off = (y + dy) * row_words + x; + for dx in 0..w { + ptr::write_volatile(fb.base.add((off + dx) * 4) as *mut u32, color); + } + } + } + return; + } + let row_words = fb.pitch / 4; + unsafe { + for dy in 0..h { + let off = (y + dy) * row_words + x; + for dx in 0..w { + *SHADOW.add(off + dx) = color; + } + } + } + push_rect(x, y, w, h); +} + +/// Read one pixel back from the shadow (RAM; cheap). Test/demo use only. +pub fn shadow_pixel(x: usize, y: usize) -> Option { + let fb = fb().as_ref()?; + if x >= fb.width || y >= fb.height || unsafe { SHADOW.is_null() } { + return None; + } + Some(unsafe { *SHADOW.add(y * (fb.pitch / 4) + x) }) +} + +/// Read one pixel back from the display (volatile; uncached on real +/// hardware — test/demo use only, never on a hot path). +pub fn display_pixel(x: usize, y: usize) -> Option { + let fb = fb().as_ref()?; + if x >= fb.width || y >= fb.height { + return None; + } + Some(unsafe { ptr::read_volatile(fb.base.add((y * (fb.pitch / 4) + x) * 4) as *mut u32) }) +} + +// --------------------------------------------------------------------------- +// Mouse cursor — a display overlay, composited by `push_rect`. +// --------------------------------------------------------------------------- + +/// Cursor bitmap: 12×16 classic pointer, 1 = opaque. The hotspot is the +/// top-left corner of the bitmap; the arrow tip sits at (2, 0). Built by +/// a const fn from explicit column lists (pixel column `dx` = bit `11-dx`) +/// so the shape is auditable instead of hand-mangled bit literals. +const CURSOR_W: usize = 12; +const CURSOR_H: usize = 16; + +const fn bmp_row(cols: &[u8]) -> u16 { + let mut v: u16 = 0; + let mut i = 0; + while i < cols.len() { + v |= 1u16 << (11 - cols[i] as u16); + i += 1; + } + v +} + +/// Head: triangle from a 1-px tip at (2,0) widening right to col 11. +/// Tail: 2-px diagonal dropping down-right from the head's base. +const CURSOR_BMP: [u16; CURSOR_H] = [ + bmp_row(&[2]), + bmp_row(&[2, 3]), + bmp_row(&[2, 3, 4]), + bmp_row(&[2, 3, 4, 5]), + bmp_row(&[2, 3, 4, 5, 6]), + bmp_row(&[2, 3, 4, 5, 6, 7]), + bmp_row(&[2, 3, 4, 5, 6, 7, 8]), + bmp_row(&[2, 3, 4, 5, 6, 7, 8, 9]), + bmp_row(&[2, 3, 4, 5, 6, 7, 8, 9, 10]), + bmp_row(&[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]), + bmp_row(&[8, 9]), + bmp_row(&[9, 10]), + bmp_row(&[9, 10]), + bmp_row(&[10, 11]), + bmp_row(&[10, 11]), + bmp_row(&[10, 11]), +]; + +/// Packed cursor position: x in the high 32 bits, y in the low 32, so a +/// single relaxed load never sees a torn pair. Written by the cursor +/// task, read by every push (any task). +static CURSOR_POS: AtomicU64 = AtomicU64::new(0); +static CURSOR_BUTTONS: AtomicU8 = AtomicU8::new(0); + +fn pack(x: usize, y: usize) -> u64 { + ((x as u64) << 32) | (y as u64) +} + +/// Current cursor position (top-left of the bitmap). +pub fn cursor_pos() -> (usize, usize) { + let v = CURSOR_POS.load(Ordering::Relaxed); + ((v >> 32) as usize, (v & 0xFFFF_FFFF) as usize) +} + +/// Current button state: bit 0 = left, bit 1 = right, bit 2 = middle. +pub fn cursor_buttons() -> u8 { + CURSOR_BUTTONS.load(Ordering::Relaxed) +} + +pub fn cursor_set_buttons(b: u8) { + CURSOR_BUTTONS.store(b, Ordering::Relaxed); +} + +/// Place the cursor (used at init; centre of the screen). +pub fn cursor_set(x: usize, y: usize) { + CURSOR_POS.store(pack(x, y), Ordering::Relaxed); +} + +/// Move the cursor by a relative delta, clamped to the screen, erasing +/// the old position (a shadow push — the shadow never held the cursor) +/// and drawing the new one. Returns the new position. +pub fn cursor_move(dx: i16, dy: i16) -> (usize, usize) { + let Some(fb) = fb().as_ref() else { + return cursor_pos(); + }; + let (cx, cy) = cursor_pos(); + let max_x = fb.width.saturating_sub(CURSOR_W); + let max_y = fb.height.saturating_sub(CURSOR_H); + let nx = (cx as i64 + dx as i64).clamp(0, max_x as i64) as usize; + let ny = (cy as i64 + dy as i64).clamp(0, max_y as i64) as usize; + if (nx, ny) == (cx, cy) { + return (cx, cy); + } + CURSOR_POS.store(pack(nx, ny), Ordering::Relaxed); + // Restore the old rect (overlay now composites at the new position). + push_rect(cx, cy, CURSOR_W, CURSOR_H); + // Draw at the new position. + push_rect(nx, ny, CURSOR_W, CURSOR_H); + (nx, ny) +} + +/// If the cursor overlaps the given rect, composite it (black outline +/// offset +1,+1, white body on top). Called by `push_rect`. +fn overlay_cursor(x: usize, y: usize, w: usize, h: usize) { + let (cx, cy) = cursor_pos(); + if x >= cx + CURSOR_W || y >= cy + CURSOR_H { + return; + } + if cx >= x + w || cy >= y + h { + return; + } + draw_bmp(cx + 1, cy + 1, rgb(0, 0, 0)); + draw_bmp(cx, cy, rgb(255, 255, 255)); +} + +/// Re-composite the cursor where it is (after a scroll shift, which +/// bypasses `push_rect`, and once at init so it is visible over idle +/// cells the diff never re-blits). +pub(crate) fn cursor_redraw() { + let (cx, cy) = cursor_pos(); + draw_bmp(cx + 1, cy + 1, rgb(0, 0, 0)); + draw_bmp(cx, cy, rgb(255, 255, 255)); +} + +/// Write the cursor bitmap at (x, y) in one colour — display only, the +/// shadow is never touched (that is what makes the overlay race-free). +fn draw_bmp(x: usize, y: usize, color: u32) { + let Some(fb) = fb().as_ref() else { + return; + }; + let row_words = fb.pitch / 4; + unsafe { + for dy in 0..CURSOR_H { + let yy = y + dy; + if yy >= fb.height { + break; + } + let row = CURSOR_BMP[dy]; + for dx in 0..CURSOR_W { + let xx = x + dx; + if xx >= fb.width { + break; + } + if row & (1u16 << (11 - dx)) != 0 { + let off = yy * row_words + xx; + ptr::write_volatile(fb.base.add(off * 4) as *mut u32, color); + } + } + } + } +} + /// Pack an (r, g, b) colour for the framebuffer's pixel format. pub fn rgb(r: u8, g: u8, b: u8) -> u32 { match fb().as_ref() { @@ -191,6 +427,9 @@ impl Framebuffer { // coalesce well on WC framebuffers — far fewer bus // transactions than per-pixel stores. ptr::copy_nonoverlapping(SHADOW, self.base as *mut u32, words); + // The scroll copied the shadow (which never contains the + // cursor); re-composite it on top of the pushed frame. + crate::gop::cursor_redraw(); } } } @@ -363,20 +602,35 @@ pub(crate) fn blit_glyph(col: usize, row: usize, ch: u16, fg: (u8, u8, u8), bg: let x = col * 8; let y = row * 16; + if unsafe { SHADOW.is_null() } { + // Degraded: no backbuffer — write the display directly, no + // cursor overlay. + for cy in 0..16 { + let row_bits = data[cy]; + for cx in 0..8 { + let offset = (y + cy) * fb.pitch + (x + cx) * fb.bytes_per_pixel; + let px = if row_bits & (0x80 >> cx) != 0 { fg } else { bg }; + unsafe { + ptr::write_volatile(fb.base.add(offset) as *mut u32, px); + } + } + } + return; + } + + // Normal path: rasterise into the RAM shadow, then one push + // copies the cell to the display and composites the cursor. for cy in 0..16 { let row_bits = data[cy]; for cx in 0..8 { let offset = (y + cy) * fb.pitch + (x + cx) * fb.bytes_per_pixel; + let px = if row_bits & (0x80 >> cx) != 0 { fg } else { bg }; unsafe { - let px = if row_bits & (0x80 >> cx) != 0 { fg } else { bg }; - // Display (volatile; the fb is MMIO-ish) + RAM shadow. - ptr::write_volatile(fb.base.add(offset) as *mut u32, px); - if !SHADOW.is_null() { - *SHADOW.add(offset / 4) = px; - } + *SHADOW.add(offset / 4) = px; } } } + push_rect(x, y, 8, 16); } } diff --git a/rsnix/src/lib.rs b/rsnix/src/lib.rs index 08ac6c2..f4645a5 100644 --- a/rsnix/src/lib.rs +++ b/rsnix/src/lib.rs @@ -3,6 +3,7 @@ extern crate alloc; pub mod ahci; +pub mod cursor; pub mod fat; pub mod font; pub mod fs; diff --git a/scripts/test-gfx.sh b/scripts/test-gfx.sh new file mode 100755 index 0000000..a6e4016 --- /dev/null +++ b/scripts/test-gfx.sh @@ -0,0 +1,114 @@ +#!/usr/bin/env bash +# +# scripts/test-gfx.sh — automated graphics-layer verification. +# +# The cursor overlay compositor is the core of the GUI path: the shadow +# holds true content, the display gets shadow pushes with the cursor +# painted on top at every push, and the cursor never enters the shadow. +# This test boots QEMU headless and runs `gfx check` — an in-kernel +# pixel self-test that reads back shadow *and* display pixels — plus the +# `gfx` demo scene. Cursor *movement* against injected mouse input is +# covered by test-mouse.sh; here we prove the compositor math. +# +# Usage: ./scripts/test-gfx.sh +# Env: OVMF, QEMU (same defaults as other test scripts) +# +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +PROJECT_DIR="$(dirname "$SCRIPT_DIR")" +cd "$PROJECT_DIR" + +OVMF="${OVMF:-/usr/share/edk2/x64/OVMF.4m.fd}" +QEMU="${QEMU:-qemu-system-x86_64}" +ESP_DIR="$PROJECT_DIR/esp" +QPID=/tmp/rsdos-gfx-qpid +SOCK=/tmp/rsdos-gfx-qmon.sock +LOG=/tmp/rsdos-gfx-serial.log +QLOG=/tmp/rsdos-gfx-qemu.log + +trap 'kill "$(cat "$QPID" 2>/dev/null)" 2>/dev/null || true' EXIT + +fail() { + echo "FAIL: $1" + [ -f "$LOG" ] && tail -40 "$LOG" + exit 1 +} + +wait_log() { + local i=0 + while [ "$i" -lt $((${3:-60} * 10)) ]; do + grep -q "$2" "$1" 2>/dev/null && return 0 + sleep 0.1 + i=$((i + 1)) + done + return 1 +} + +wait_qemu_exit() { + local i=0 + while [ "$i" -lt $((${1:-30} * 10)) ]; do + kill -0 "$(cat "$QPID" 2>/dev/null)" 2>/dev/null || return 0 + sleep 0.1 + i=$((i + 1)) + done + return 1 +} + +qemu_hmp() { + python3 - "$SOCK" "$1" <<'EOF' +import socket, sys, time +s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) +s.connect(sys.argv[1]) +s.sendall((sys.argv[2] + "\n").encode()) +time.sleep(0.4) +EOF +} + +echo "==> 1/5 build kernel (debug)" +cargo build --package rsdos --target x86_64-unknown-uefi + +echo "==> 2/5 deploy to ESP" +mkdir -p "$ESP_DIR/EFI/BOOT" +cp target/x86_64-unknown-uefi/debug/rsdos.efi "$ESP_DIR/EFI/BOOT/BOOTX64.EFI" + +echo "==> 3/5 boot QEMU (headless)" +kill "$(cat "$QPID" 2>/dev/null)" 2>/dev/null || true +sleep 1 +rm -f "$SOCK" "$LOG" +"$QEMU" -bios "$OVMF" \ + -drive file=fat:rw:"$ESP_DIR",format=raw \ + -serial file:"$LOG" \ + -monitor unix:"$SOCK",server,nowait \ + -m 256M -machine q35 -cpu qemu64 -no-reboot -display none \ + >"$QLOG" 2>&1 & +echo $! >"$QPID" + +wait_log "$LOG" "boot: entering shell" 90 || fail "kernel never reached the shell" +grep -aq "cursor: task " "$LOG" || fail "cursor task did not spawn" + +echo "==> 4/5 in-kernel pixel self-test (gfx check)" +python3 "$SCRIPT_DIR/sendkeys.py" --sock "$SOCK" \ + "clear" \ + "gfx check" +sleep 1.5 + +# Every sub-check must have printed OK. +grep -aq "fill_rect/shadow: OK" "$LOG" || fail "shadow writeback failed" +grep -aq "display push: OK" "$LOG" || fail "shadow→display push failed" +grep -aq "cursor overlay: OK" "$LOG" || fail "cursor not composited on display" +grep -aq "cursor not in shadow: OK" "$LOG" || fail "cursor leaked into the shadow" +grep -aq "gfx check: PASS" "$LOG" || fail "gfx check did not PASS" +grep -aq "gfx check: FAIL" "$LOG" && fail "gfx check reported FAIL" + +echo "==> 5/5 demo scene + poweroff" +python3 "$SCRIPT_DIR/sendkeys.py" --sock "$SOCK" \ + "gfx" \ + "poweroff" +wait_qemu_exit 30 || fail "QEMU did not exit after poweroff" + +grep -aq "gfx: drew status bar" "$LOG" || fail "gfx demo did not draw" + +echo "" +echo "PASS — graphics layer OK (shadow, display push, cursor overlay)" +echo " compositor: shadow=content, display=push+cursor, cursor never in shadow" diff --git a/scripts/test-mouse.sh b/scripts/test-mouse.sh index ed4df44..e58d474 100755 --- a/scripts/test-mouse.sh +++ b/scripts/test-mouse.sh @@ -1,20 +1,19 @@ #!/usr/bin/env bash # -# scripts/test-mouse.sh — automated PS/2 mouse round trip. +# scripts/test-mouse.sh — automated mouse round trip (cursor model). # -# Builds the kernel, boots QEMU headless, injects mouse movement and -# button presses through the monitor's `mouse_move` / `mouse_button` -# commands, and verifies the guest decoded them via IRQ12 → ring → -# packet decoder. Covers both surfaces: -# - `cat /dev/mouse` (VFS snapshot of pending events) -# - `mouse` (live streaming command, stopped by ^C) +# Since v0.5.0 the cursor task owns the PS/2 ring: mouse input shows up +# as *cursor position + buttons* on the screen, not as an event drain. +# This script boots QEMU headless, injects movement/buttons via the +# monitor, and verifies: +# - the `cursor` command reports a position that moves with `mouse_move` +# - button presses ride along (L while held) +# - `/dev/mouse` is a position device (one snapshot line) +# - the `mouse` watch command prints live changes and stops on ^C +# - a `mouse ` forward routes real events to a task's queue # -# Usage: -# ./scripts/test-mouse.sh -# -# Environment: -# OVMF firmware (default: /usr/share/edk2/x64/OVMF.4m.fd) -# QEMU qemu binary (default: qemu-system-x86_64) +# Usage: ./scripts/test-mouse.sh +# Env: OVMF, QEMU (same defaults as other test scripts) # set -euo pipefail @@ -30,16 +29,14 @@ SOCK=/tmp/rsdos-mouse-qmon.sock LOG=/tmp/rsdos-mouse-serial.log QLOG=/tmp/rsdos-mouse-qemu.log -# Never leave a QEMU behind. trap 'kill "$(cat "$QPID" 2>/dev/null)" 2>/dev/null || true' EXIT fail() { echo "FAIL: $1" - [ -f "$LOG" ] && tail -20 "$LOG" + [ -f "$LOG" ] && tail -30 "$LOG" exit 1 } -# wait_log FILE PATTERN TIMEOUT-SECONDS wait_log() { local i=0 while [ "$i" -lt $((${3:-60} * 10)) ]; do @@ -50,7 +47,6 @@ wait_log() { return 1 } -# wait_qemu_exit TIMEOUT-SECONDS wait_qemu_exit() { local i=0 while [ "$i" -lt $((${1:-30} * 10)) ]; do @@ -61,7 +57,6 @@ wait_qemu_exit() { return 1 } -# qemu_hmp — send one raw HMP command to the monitor socket. qemu_hmp() { python3 - "$SOCK" "$1" <<'EOF' import socket, sys, time @@ -72,14 +67,21 @@ time.sleep(0.4) EOF } -echo "==> 1/5 build kernel (debug)" +# cursor_state — run `cursor`, return "x y buttons" of the LAST occurrence. +cursor_state() { + python3 "$SCRIPT_DIR/sendkeys.py" --sock "$SOCK" "cursor" + sleep 0.5 + sed -n 's/.*cursor: x=\([0-9]*\) y=\([0-9]*\) buttons=\([A-Za-z-]*\).*/\1 \2 \3/p' "$LOG" | tail -1 +} + +echo "==> 1/6 build kernel (debug)" cargo build --package rsdos --target x86_64-unknown-uefi -echo "==> 2/5 deploy to ESP" +echo "==> 2/6 deploy to ESP" mkdir -p "$ESP_DIR/EFI/BOOT" cp target/x86_64-unknown-uefi/debug/rsdos.efi "$ESP_DIR/EFI/BOOT/BOOTX64.EFI" -echo "==> 3/5 boot QEMU (headless)" +echo "==> 3/6 boot QEMU (headless)" kill "$(cat "$QPID" 2>/dev/null)" 2>/dev/null || true sleep 1 rm -f "$SOCK" "$LOG" @@ -93,38 +95,73 @@ echo $! >"$QPID" wait_log "$LOG" "boot: entering shell" 90 || fail "kernel never reached the shell" grep -aq "ps2: mouse ready" "$LOG" || fail "mouse driver did not come up at boot" +grep -aq "cursor: task " "$LOG" || fail "cursor task did not spawn" -# Seed a move *before* any consumer runs, so `cat /dev/mouse` has a -# queued event to drain (exercises the VFS snapshot path). -qemu_hmp "mouse_move 8 4" - -echo "==> 4/5 drive the shell (cat /dev/mouse, mouse stream, poweroff)" -python3 "$SCRIPT_DIR/sendkeys.py" --sock "$SOCK" \ - "cat /dev/mouse" \ - "mouse" +echo "==> 4/6 cursor position tracks injected movement" +INIT=$(cursor_state) +[ -n "$INIT" ] || fail "no initial cursor position" +IX=$(echo "$INIT" | awk '{print $1}') +IY=$(echo "$INIT" | awk '{print $2}') +IB=$(echo "$INIT" | awk '{print $3}') +echo " initial: x=$IX y=$IY buttons=$IB" +[ "$IB" = "---" ] || fail "expected no buttons at boot, got $IB" -# While the `mouse` stream is live: a move, a left-press, a move with the -# button held, then release — the button state must ride along on the -# movement packet. qemu_hmp "mouse_move 20 7" +S1=$(cursor_state) +X1=$(echo "$S1" | awk '{print $1}') +Y1=$(echo "$S1" | awk '{print $2}') +[ "$X1" -eq $((IX + 20)) ] || fail "x did not move +20 (was $IX, now $X1)" +[ "$Y1" -eq $((IY + 7)) ] || fail "y did not move +7 (was $IY, now $Y1)" + +echo "==> 5/6 buttons ride along; /dev/mouse is a position device" qemu_hmp "mouse_button 1" +S2=$(cursor_state) +B2=$(echo "$S2" | awk '{print $3}') +[ "$B2" = "L--" ] || fail "left press not seen (got $B2)" + qemu_hmp "mouse_move -5 -3" +S3=$(cursor_state) +X3=$(echo "$S3" | awk '{print $1}') +Y3=$(echo "$S3" | awk '{print $2}') +B3=$(echo "$S3" | awk '{print $3}') +[ "$X3" -eq $((X1 - 5)) ] || fail "held move x wrong ($X1 -5 = $((X1 - 5)), got $X3)" +[ "$Y3" -eq $((Y1 - 3)) ] || fail "held move y wrong ($Y1 -3 = $((Y1 - 3)), got $Y3)" +[ "$B3" = "L--" ] || fail "button state dropped during held move (got $B3)" + qemu_hmp "mouse_button 0" -qemu_hmp "sendkey ctrl-c" +S4=$(cursor_state) +B4=$(echo "$S4" | awk '{print $3}') +[ "$B4" = "---" ] || fail "release not seen (got $B4)" + +python3 "$SCRIPT_DIR/sendkeys.py" --sock "$SOCK" "cat /dev/mouse" +sleep 0.5 +grep -aq "x=$X3 y=$Y3 buttons=---" "$LOG" || fail "/dev/mouse does not report position snapshot (x=$X3 y=$Y3)" +grep -aq "mouse: no events" "$LOG" && fail "/dev/mouse is still an event drain" +echo "==> 6/6 live watch + forwarding + poweroff" python3 "$SCRIPT_DIR/sendkeys.py" --sock "$SOCK" \ - "poweroff" + "msgrecv" \ + "mouse 3" -echo "==> 5/5 wait for shutdown + verify" -wait_qemu_exit 30 || fail "QEMU did not exit after poweroff" +# Live watch running: a move must appear as a changed line. +qemu_hmp "mouse_move 3 2" +# Forwarding live: the same move must reach the msgrecv task (spawned as +# task 3; task 2 is the cursor task itself). +sleep 1 +qemu_hmp "sendkey ctrl-c" + +grep -aq "mouse: routing events to task 3" "$LOG" || fail "mouse 3 did not arm routing" +grep -aq "msgrecv\[3\]: Mouse(+" "$LOG" || fail "task 3 queue did not receive the routed Mouse event" +# Watch line: x/y/buttons format (any occurrence after watching started). +grep -aq "mouse: x=$((X3 + 3)) y=$((Y3 + 2)) buttons=---" "$LOG" || fail "watch did not print the moved cursor (x=$((X3+3)) y=$((Y3+2)))" +grep -aq "mouse: stopped" "$LOG" || fail "^C did not stop the mouse watch" -grep -aq "ps2: mouse ready (IRQ12, stream mode)" "$LOG" || fail "no mouse-ready boot line" -grep -aq "dx=+8 dy=+4 buttons=---" "$LOG" || fail "/dev/mouse did not drain the queued move (dx=+8 dy=+4)" -grep -aq "dx=+20 dy=+7 buttons=---" "$LOG" || fail "mouse stream missed mouse_move 20 7" -grep -aq "dx=+0 dy=+0 buttons=L--" "$LOG" || fail "left-button press did not decode" -grep -aq "dx=-5 dy=-3 buttons=L--" "$LOG" || fail "held-button movement wrong (dx=-5 dy=-3 L)" -grep -aq "mouse: stopped" "$LOG" || fail "^C did not stop the mouse stream" +python3 "$SCRIPT_DIR/sendkeys.py" --sock "$SOCK" "poweroff" + +echo "==> done: wait for shutdown + verify" +wait_qemu_exit 30 || fail "QEMU did not exit after poweroff" echo "" -echo "PASS — PS/2 mouse round trip OK (IRQ12, /dev/mouse, live stream, buttons)" -echo " events: 8,4 · 20,7 · L-press · -5,-3 held · release" +echo "PASS — mouse round trip OK (cursor task, /dev/mouse, watch, forward)" +echo " moves: +20,+7 · -5,-3 held · +3,+2 watch" +echo " path: IRQ12 → ring → cursor task → overlay + queue" diff --git a/scripts/test-msg.sh b/scripts/test-msg.sh index 0bd1c81..d81d8d7 100755 --- a/scripts/test-msg.sh +++ b/scripts/test-msg.sh @@ -93,20 +93,21 @@ echo $! >"$QPID" wait_log "$LOG" "boot: entering shell" 90 || fail "kernel never reached the shell" echo "==> 4/5 drive the shell (msgrecv / send / mouse routing / queue-full)" +# msgrecv spawns as task 3 (task 2 is the cursor task). python3 "$SCRIPT_DIR/sendkeys.py" --sock "$SOCK" \ "msgrecv" \ - "send 2 user 42" \ - "send 2 timer" \ - "send 2 key enter" \ - "send 2 key ctrl-c" \ - "send 2 key f3" \ - "send 2 mouse 5 -3 3" \ + "send 3 user 42" \ + "send 3 timer" \ + "send 3 key enter" \ + "send 3 key ctrl-c" \ + "send 3 key f3" \ + "send 3 mouse 5 -3 3" \ "sleep 800" \ "jobs" -# Real IRQ12 events through the queue: start routing to task 2, inject +# Real IRQ12 events through the queue: start routing to task 3, inject # moves + a left press, stop. -python3 "$SCRIPT_DIR/sendkeys.py" --sock "$SOCK" "mouse 2" +python3 "$SCRIPT_DIR/sendkeys.py" --sock "$SOCK" "mouse 3" qemu_hmp "mouse_move 20 7" qemu_hmp "mouse_button 1" qemu_hmp "mouse_move -5 -3" @@ -140,20 +141,20 @@ python3 "$SCRIPT_DIR/sendkeys.py" --sock "$SOCK" \ echo "==> 5/5 wait for shutdown + verify" wait_qemu_exit 30 || fail "QEMU did not exit after poweroff" -grep -aq "msgrecv: task 2 listening" "$LOG" || fail "msgrecv did not spawn" -grep -aq "msgrecv\[2\]: User(42)" "$LOG" || fail "user message missing" -grep -aq "msgrecv\[2\]: Timer" "$LOG" || fail "timer message missing" -grep -aq "msgrecv\[2\]: Key(Enter)" "$LOG" || fail "key enter missing" -grep -aq "msgrecv\[2\]: Key(Ctrl-c)" "$LOG" || fail "key ctrl-c missing" -grep -aq "msgrecv\[2\]: Key(F3)" "$LOG" || fail "key f3 missing" -grep -aq "msgrecv\[2\]: Mouse(+5,-3 L R)" "$LOG" || fail "synthesized mouse message missing" +grep -aq "msgrecv: task 3 listening" "$LOG" || fail "msgrecv did not spawn" +grep -aq "msgrecv\[3\]: User(42)" "$LOG" || fail "user message missing" +grep -aq "msgrecv\[3\]: Timer" "$LOG" || fail "timer message missing" +grep -aq "msgrecv\[3\]: Key(Enter)" "$LOG" || fail "key enter missing" +grep -aq "msgrecv\[3\]: Key(Ctrl-c)" "$LOG" || fail "key ctrl-c missing" +grep -aq "msgrecv\[3\]: Key(F3)" "$LOG" || fail "key f3 missing" +grep -aq "msgrecv\[3\]: Mouse(+5,-3 L R)" "$LOG" || fail "synthesized mouse message missing" # Real IRQ12 events routed through the queue (button held across the move). -grep -aq "msgrecv\[2\]: Mouse(+20,+7" "$LOG" || fail "real mouse move 20,7 not routed to queue" -grep -aq "msgrecv\[2\]: Mouse(-5,-3 L" "$LOG" || fail "held-button routed move missing" +grep -aq "msgrecv\[3\]: Mouse(+20,+7" "$LOG" || fail "real mouse move 20,7 not routed to queue" +grep -aq "msgrecv\[3\]: Mouse(-5,-3 L" "$LOG" || fail "held-button routed move missing" grep -aq "queue full" "$LOG" || fail "17th send did not report queue full" grep -aq "send: unknown type" "$LOG" && fail "a bad send slipped through (expected none)" echo "" echo "PASS — message queues OK (all types, ordering, real-input routing, queue-full)" echo " sent: user · timer · key(enter,ctrl-c,f3) · mouse · 16+1 queue-full" -echo " routed: mouse_move 20,7 → queue → msgrecv[2]" +echo " routed: mouse_move 20,7 → queue → msgrecv[3]" diff --git a/shell/src/lib.rs b/shell/src/lib.rs index c18d319..e1d54c8 100644 --- a/shell/src/lib.rs +++ b/shell/src/lib.rs @@ -704,6 +704,8 @@ write `{} TIL `", "pci" => cmd_pci(&parsed), "rescan" => cmd_rescan(&parsed), "mouse" => cmd_mouse(&parsed), + "cursor" => cmd_cursor(&parsed), + "gfx" => cmd_gfx(&parsed), "ls" => cmd_ls(&parsed), "cat" => cmd_cat(&parsed), "klog" => cmd_klog(&parsed), @@ -741,8 +743,11 @@ fn cmd_help(_p: &Parsed) { date — show current date/time (RTC) pci — list PCI devices rescan — re-scan for hotplugged/removed disks (also runs automatically) - mouse — live mouse events (dx/dy/buttons); ^C stops - mouse — post decoded mouse events to task 's queue (input routing) + cursor — report the on-screen mouse cursor (x, y, buttons) + mouse — watch the cursor live (x/y/buttons); ^C stops + mouse — route mouse events to task 's queue (cursor still tracks) + gfx — demo: draw a status bar + RGB boxes (bottom strip) + gfx check — pixel self-test: shadow, display push, cursor overlay bg — spawn a background task (spinner, ticker, counter, boom, overflow) msgrecv — spawn a task that blocks on its message queue and logs every message to serial (ids from `jobs`) @@ -1546,13 +1551,11 @@ fn cmd_rescan(_p: &Parsed) { } } -/// Live mouse event stream: print each decoded packet (dx/dy/buttons) as -/// it arrives until ^C. With an optional task id, events are **posted to -/// that task's message queue** instead of printed — the input-routing -/// path the window manager will use (`mouse ` + `msgrecv` proves the -/// whole chain: IRQ12 → ring → decoder → queue → blocked task). Polls -/// the PS/2 ring every 10 ms (via `sleep_ms`, which only blocks the -/// shell task) so background tasks keep running. +/// Mouse front-end. The cursor task owns the PS/2 ring, so this +/// command *watches the on-screen cursor* (position + buttons, printed +/// only on change) until ^C. With a task id it also routes every event +/// to that task's queue — the window-manager input path — clearing the +/// route on exit. fn cmd_mouse(p: &Parsed) { let target: Option = p.args.first().and_then(|s| s.parse::().ok()); if let Some(id) = target { @@ -1560,48 +1563,167 @@ fn cmd_mouse(p: &Parsed) { term_err(&alloc::format!("mouse: no such task {}", id)); return; } + rsnix::cursor::set_forward(Some(id)); term_println(&alloc::format!( - "mouse: posting events to task {} — ^C to stop", + "mouse: routing events to task {} (cursor still tracks) — ^C to stop", id )); + } else if !rsnix::ps2::mouse_present() { + term_err("mouse: no PS/2 mouse at boot — cat /dev/mouse still works"); + return; } else { - if !rsnix::ps2::mouse_present() { - term_err("mouse: no PS/2 mouse at boot — cat /dev/mouse still works"); - return; - } - term_println("mouse: streaming events — ^C to stop"); + term_println("mouse: watching cursor — move the mouse, ^C to stop"); } + let mut last = (usize::MAX, usize::MAX, u8::MAX); loop { if tty::interrupt_pressed() { + rsnix::cursor::set_forward(None); term_println("mouse: stopped"); return; } - while let Some(ev) = rsnix::ps2::try_poll_mouse() { - match target { - Some(id) => { - if let Err(e) = rsnix::sched::send(id, rsnix::sched::TaskMsg::Mouse(ev)) { - term_err(&alloc::format!("mouse: {}", e)); - return; - } - } - None => { - let mut b = String::new(); - b.push(if ev.left { 'L' } else { '-' }); - b.push(if ev.right { 'R' } else { '-' }); - b.push(if ev.middle { 'M' } else { '-' }); - term_println(&alloc::format!( - "dx={:+} dy={:+} buttons={}", - ev.dx, - ev.dy, - b - )); - } - } + let (x, y, b) = ( + rsnix::gop::cursor_pos().0, + rsnix::gop::cursor_pos().1, + rsnix::gop::cursor_buttons(), + ); + if (x, y, b) != last { + last = (x, y, b); + term_println(&alloc::format!( + "mouse: x={} y={} buttons={}{}{}", + x, + y, + if b & 1 != 0 { 'L' } else { '-' }, + if b & 2 != 0 { 'R' } else { '-' }, + if b & 4 != 0 { 'M' } else { '-' } + )); } rsnix::sched::sleep_ms(10); } } +/// One-shot cursor state (parseable; used by the test harness). +fn cmd_cursor(_p: &Parsed) { + let (x, y) = rsnix::gop::cursor_pos(); + let b = rsnix::gop::cursor_buttons(); + term_println(&alloc::format!( + "cursor: x={} y={} buttons={}{}{}", + x, + y, + if b & 1 != 0 { 'L' } else { '-' }, + if b & 2 != 0 { 'R' } else { '-' }, + if b & 4 != 0 { 'M' } else { '-' } + )); +} + +/// Graphics primitives demo + pixel self-test (shadow + display + cursor +/// overlay readbacks). `gfx` / `gfx demo` draws a status-bar scene; +/// `gfx check` runs the readback assertions (run after `clear` for a +/// predictable background). +fn cmd_gfx(p: &Parsed) { + match p.args.first().map(|s| s.as_str()) { + Some("check") => gfx_check(), + _ => gfx_demo(), + } +} + +fn gfx_demo() { + let (w, h) = rsnix::gop::pixel_dims(); + if w == 0 { + term_err("gfx: no framebuffer"); + return; + } + // Status-bar strip across the bottom, with three RGB boxes. + rsnix::gop::fill_rect(0, h - 40, w, 40, rsnix::gop::rgb(0, 0, 128)); + rsnix::gop::fill_rect(20, h - 32, 60, 24, rsnix::gop::rgb(255, 0, 0)); + rsnix::gop::fill_rect(90, h - 32, 60, 24, rsnix::gop::rgb(0, 255, 0)); + rsnix::gop::fill_rect(160, h - 32, 60, 24, rsnix::gop::rgb(255, 255, 0)); + term_println(&alloc::format!( + "gfx: drew status bar + RGB boxes ({}x{} px bottom strip)", + w, + h + )); +} + +fn gfx_check() { + let (w, _h) = rsnix::gop::pixel_dims(); + if w == 0 { + term_err("gfx: no framebuffer"); + return; + } + let mut ok = true; + let mut report = String::new(); + + // 1. fill_rect lands in the shadow. + let (rx, ry, rw, rh) = (8usize, 8usize, 40usize, 16usize); + let red = rsnix::gop::rgb(255, 0, 0); + rsnix::gop::fill_rect(rx, ry, rw, rh, red); + match rsnix::gop::shadow_pixel(rx + rw / 2, ry + rh / 2) { + Some(p) if p == red => report.push_str("fill_rect/shadow: OK\n"), + Some(p) => { + ok = false; + report.push_str(&alloc::format!("fill_rect/shadow: FAIL ({:#x})\n", p)); + } + None => { + ok = false; + report.push_str("fill_rect/shadow: FAIL (no shadow)\n"); + } + } + // 2. the push reached the display. + match rsnix::gop::display_pixel(rx + rw / 2, ry + rh / 2) { + Some(p) if p == red => report.push_str("display push: OK\n"), + Some(p) => { + ok = false; + report.push_str(&alloc::format!("display push: FAIL ({:#x})\n", p)); + } + None => { + ok = false; + report.push_str("display push: FAIL (readback)\n"); + } + } + // 3. cursor overlay: the arrow tip is white on the display… + let (cx, cy) = rsnix::gop::cursor_pos(); + let (dw, dh) = rsnix::gop::pixel_dims(); + let white = rsnix::gop::rgb(255, 255, 255); + let tip = rsnix::gop::display_pixel(cx + 2, cy); + let out = rsnix::gop::display_pixel(cx, cy); + match (tip, out) { + (Some(t), Some(o)) if t == white && o != white => report.push_str("cursor overlay: OK\n"), + (Some(t), Some(o)) => { + ok = false; + report.push_str(&alloc::format!( + "cursor overlay: FAIL (tip={:#x} outside={:#x})\n", + t, + o + )); + } + _ => { + ok = false; + report.push_str(&alloc::format!( + "cursor overlay: FAIL (readback cx={} cy={} dims={}x{})\n", + cx, + cy, + dw, + dh + )); + } + } + // …and it must NOT be in the shadow (pure overlay). + match rsnix::gop::shadow_pixel(cx + 2, cy) { + Some(p) if p != white => report.push_str("cursor not in shadow: OK\n"), + p => { + ok = false; + report.push_str(&alloc::format!("cursor in shadow: FAIL ({:?})\n", p)); + } + } + + term_println(&report); + term_println(if ok { + "gfx check: PASS" + } else { + "gfx check: FAIL" + }); +} + // --------------------------------------------------------------------------- // Multitasking: bg / jobs / sleep / kill / demo // -- cgit v1.2.3