Просмотр исходного кода

Composite windows per damage rect and add window graphics canvases

Window manager (wm.c/h):
- repaint only the damaged rectangle (wm_redraw_rect: desktop fill plus
  every intersecting window back-to-front, clipped by wm_draw_window_clip)
  instead of full-screen redraws; window moves and drags go through the
  same path.
- fbtext.c/h gain the per-pixel clipped string/cell variants that the
  clipped compositing needs.

Window graphics service (gfx.c/h, sys_gfx.c/h):
- gfx.c/h: RGB565 window canvases (page-allocated so they can be mapped
  1:1) plus bpp-aware blits into the shadow buffer.
- sys_gfx.c/h: a ring-3 command gets its window's canvas mapped RW at
  0x50000000 (SYS_GFX_BEGIN) and publishes frames with SYS_GFX_PRESENT,
  which copies the mapped back buffer into the composited front buffer
  with interrupts off (double buffering: a half-drawn frame can never
  reach the screen).  Presented frames carry monotonic seq counters so the
  WM can never lose one.  Keys of a window with a live session go to the
  session (SYS_KEY_POLL; Ctrl+C still reaches the terminal), closing a
  window kills its session, and sys_gfx_reap/sys_gfx_collect free the
  canvas after exit/crash.
- syscall.c/h: the SYS_GFX_*/SYS_KEY_POLL/SYS_RTC_HMS requests plus the
  sys_gfx_info/sys_time structures; process.c flags dead gfx sessions from
  the reaper; paging.c/h add paging_unmap_page() for the unmap path;
  rtc.c gains a robust hour/minute/second read (retries across the RTC
  update cycle, validates BCD, handles the 12-hour PM flag) for the clock.

clock and colors move from kernel commands (clock.c/colors.c, removed) to
the command pack (ucmd_clock.c, ucmd_colors.c) drawn through the canvas
service; terminal.c drops their kernel entries, ucmd_lib.h gains the
session helpers, and the Makefile builds gfx.o/sys_gfx.o and the two new
ucmds.
Johannes Zellner 1 месяц назад
Родитель
Сommit
fea42067ad
22 измененных файлов с 1209 добавлено и 540 удалено
  1. 19 5
      AGENTS.md
  2. 5 4
      Makefile
  3. 0 206
      clock.c
  4. 0 214
      colors.c
  5. 34 0
      fbtext.c
  6. 6 0
      fbtext.h
  7. 139 0
      gfx.c
  8. 25 0
      gfx.h
  9. 11 0
      paging.c
  10. 4 0
      paging.h
  11. 2 0
      process.c
  12. 66 23
      rtc.c
  13. 264 0
      sys_gfx.c
  14. 22 0
      sys_gfx.h
  15. 22 0
      syscall.c
  16. 24 0
      syscall.h
  17. 2 24
      terminal.c
  18. 207 0
      ucmd_clock.c
  19. 182 0
      ucmd_colors.c
  20. 25 0
      ucmd_lib.h
  21. 143 64
      wm.c
  22. 7 0
      wm.h

+ 19 - 5
AGENTS.md

@@ -84,7 +84,20 @@ below the run area), so adding code no longer moves any address.
 - **Window manager**: `wm.c/h` — slot 0 runs `wm_run()`; fixed-size draggable
   terminal windows (64×32) with a system bar (banner + purple "+ New" button +
   clock + rainbow). Click-to-focus, drag-by-title-bar, close (×). The "+ New"
-  button and first boot spawn terminals; there is no `term` command.
+  button and first boot spawn terminals; there is no `term` command.  Content is
+  repainted per damage rect (`wm_redraw_rect`: desktop fill + every intersecting
+  window back-to-front, clipped by `wm_draw_window_clip`), not by full redraws.
+- **Window graphics service**: `gfx.c/h` (RGB565 window canvases + bpp-aware
+  blits), `sys_gfx.c/h` — a ring-3 command gets its window's canvas mapped RW at
+  `0x50000000` (`SYS_GFX_BEGIN`; a mapped back buffer) and publishes frames with
+  `SYS_GFX_PRESENT`, which copies it into the composited front buffer (double
+  buffering; the copy runs with interrupts off, so a half-drawn frame can never
+  reach the screen).  Presented frames carry monotonic seq counters, so the WM
+  can never lose one.
+  Keys of a window with a live session go to the session (`SYS_KEY_POLL`; Ctrl+C
+  still reaches the terminal), closing a window kills its session, and
+  `sys_gfx_reap`/`sys_gfx_collect` free the canvas after exit/crash.  `clock`
+  and `colors` are its users.
 - **Graphics**: `vga.c/h`, `vga_copy.S`, `gpu.c`, `ati.c`, `nvidia.c`, `nv50.c`,
   `pci.h` — VESA LFB + shadow buffer, 30 Hz dirty-row flush. ATI Mach64 CRTC
   fixup; NVIDIA is VBE-only (never touch the legacy VGA CRTC). `nvidia.c`
@@ -199,8 +212,9 @@ below the run area), so adding code no longer moves any address.
   no readable filesystem can still run them: `run <name>` and the `prog`/
   `space` commands use the embedded copy, `run /<device>/<file>` still loads
   from FAT.  Rebuilds are wired (`space.c` -> `space.bin` -> `space_embed.o` ->
-  `kernel.elf`).  Note: full-screen programs draw over the WM, which keeps
-  repainting its desktop — running them windowed/cleanly is a follow-up.
+  `kernel.elf`).  Note: `run`/`prog`/`space` still draw over the WM (which keeps
+  repainting its desktop); the windowed path for such programs is the ring-3
+  canvas service (see the window graphics bullet, used by `clock`/`colors`).
 - **Ring-3 commands**: `ucmd_*.c`, `ucmd_lib.h`, `ucmd.ld`, `mkpack.c`,
   `ramfs.c/h` — freestanding ELFs linked at `USER_BASE` (`0x40000000`), packed
   by `mkpack` into `cmds.pack` (as `bin/<name>`), embedded in the kernel
@@ -238,7 +252,7 @@ below the run area), so adding code no longer moves any address.
 `cd [path]`, `ls [path]`, `cat <path>`, `save <path> <text>`, `rm <path>`,
 `mkdir <path>`, `rmdir <path>`, `hello`, `reboot`, `poweroff`, `run <name>|<file>`, `space`,
 `prog`,
-`clock`, `colors`, `display`, `cpuinfo`, `mouseinfo`, `lsusb`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `meminfo`, `top`, `format <device>`,
+`display`, `cpuinfo`, `mouseinfo`, `lsusb`, `lspci [id]`, `peek <addr> [len]`, `poke <addr> <val>`, `storage`, `meminfo`, `top`, `format <device>`,
 `ps`, `kill <pid>`, `help`, `clear`, `serial test|recv`, `kexec`, `dbg`.
 
 Network: `netinfo`, `netrecv`, `netsend`, `netip [a.b.c.d]`, `dhcp` (re-run the
@@ -269,7 +283,7 @@ nested). `/` is the read-only VFS root listing the mounted filesystems (the
 filesystem commands operate inside a mount, e.g. `cat /floppy1/HELLO.TXT`).
 
 `cpuinfo`, `ls`, `cat`, `save`, `rm`, `mkdir`, `rmdir`, `meminfo`, `top`,
-`mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
+`clock`, `colors`, `mouseinfo`, `storage`, `netinfo`, `netip`, `netdns`, `host`, `dhcp`, `ping`,
 `pong`, `netsend`, `netrecv`, `netlog`, `netconsole`, `netregs`, `netloop`,
 `netreset`, `curl` and `hello` are files in `/ramfs/bin` (packed by the
 Makefile), found through the shell's PATH; the rest are kernel commands

+ 5 - 4
Makefile

@@ -104,10 +104,10 @@ radeon.o: radeon.c radeon.h pci.h paging.h serial.h vga.h
 mtrr.o: mtrr.c mtrr.h kdbg.h serial.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-clock.o: clock.c io.h rtc.h timer.h vga.h
+gfx.o: gfx.c gfx.h mm.h vga.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-colors.o: colors.c fbtext.h io.h timer.h vga.h
+sys_gfx.o: sys_gfx.c sys_gfx.h gfx.h paging.h process.h wm.h syscall.h
 	$(CC) $(CFLAGS) -o $@ $<
 
 display.o: display.c io.h vga.h gpu.h ati.h nvidia.h radeon.h mouse.h fbtext.h
@@ -248,7 +248,7 @@ sys_net.o: sys_net.c sys_net.h syscall.h dhcp.h dns.h net.h netdev.h netlog.h
 syscall_stub.o: syscall_stub.S irqret.inc
 	$(AS) $(ASFLAGS) -o $@ $<
 
-kernel.elf: vesa_stage.o entry.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o screen.o io.o rtc.o terminal.o wm.o reboot.o poweroff.o disk.o fat.o run.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o vga_copy.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o clock.o colors.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o kdbg.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_net.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o prog_embed.o space_embed.o cmds_pack.o ramfs.o payload.o
+kernel.elf: vesa_stage.o entry.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o screen.o io.o rtc.o terminal.o wm.o reboot.o poweroff.o disk.o fat.o run.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o vga_copy.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o kdbg.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_net.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o prog_embed.o space_embed.o cmds_pack.o ramfs.o payload.o
 	$(LD) $(KERNEL_LDFLAGS) -o $@ $^
 
 MBR_LDFLAGS = -T mbr.ld -nostdlib -m elf_i386
@@ -334,6 +334,7 @@ prog: prog.bin
 # ucmd_<name>.c to UCMDS; the pack is rebuilt automatically.
 UCMDS = ucmd_cpuinfo ucmd_ls ucmd_cat ucmd_save ucmd_rm ucmd_mkdir ucmd_rmdir \
         ucmd_meminfo ucmd_mouseinfo ucmd_storage ucmd_top \
+        ucmd_clock ucmd_colors \
         ucmd_netinfo ucmd_netip ucmd_netdns ucmd_host ucmd_dhcp \
         ucmd_netsend ucmd_netrecv ucmd_ping ucmd_pong ucmd_netlog \
         ucmd_netconsole ucmd_netregs ucmd_netloop ucmd_netreset ucmd_curl
@@ -582,4 +583,4 @@ net-dev: kernel.bin netkexec_send
 	./netkexec_send $(BOARD_IP) $(NETKEXEC_PORT) 0x$$entry kernel.bin
 
 clean:
-	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o screen.o io.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o vga_copy.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o clock.o colors.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o kdbg.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin hello.elf hello_embed.o prog_embed.o space_embed.o cmds.pack cmds_pack.o ramfs.o payload.o mkpack $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) $(TLSLIB_OBJS) tls_test bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor
+	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o screen.o io.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o vga_copy.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o gfx.o sys_gfx.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o kdbg.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin hello.elf hello_embed.o prog_embed.o space_embed.o cmds.pack cmds_pack.o ramfs.o payload.o mkpack $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) $(TLSLIB_OBJS) tls_test bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor

+ 0 - 206
clock.c

@@ -1,206 +0,0 @@
-/* clock command: analog clock in VESA LFB. Press ESC to return. */
-
-#include "io.h"
-#include "rtc.h"
-#include "timer.h"
-#include "vga.h"
-
-/* Palette index to RGB. 0=black, 7=gray, 12=light red, 15=white */
-static const unsigned int pal_r[16] = { 0, 0, 0, 0, 170, 170, 170, 170, 85, 85, 85, 85, 255, 255, 255, 255 };
-static const unsigned int pal_g[16] = { 0, 0, 170, 170, 0, 0, 85, 170, 85, 85, 255, 255, 85, 85, 255, 255 };
-static const unsigned int pal_b[16] = { 0, 170, 0, 170, 0, 170, 0, 170, 85, 255, 85, 255, 85, 255, 85, 255 };
-
-#define COL_BG      0
-#define COL_FACE    15
-#define COL_TICK    7
-#define COL_HOUR    15
-#define COL_MIN     15
-#define COL_SEC     12
-#define COL_CENTER  15
-
-/*
- * Precomputed unit-vector table at radius 64 for 60 clock positions.
- */
-static const signed char tab_x[60] = {
-	  0,  7, 13, 20, 26, 32, 37, 42, 47, 51,
-	 55, 59, 62, 63, 64, 63, 62, 59, 55, 51,
-	 47, 42, 37, 32, 26, 20, 13,  7,  0, -7,
-	-13,-20,-26,-32,-37,-42,-47,-51,-55,-59,
-	-62,-63,-64,-63,-62,-59,-55,-51,-47,-42,
-	-37,-32,-26,-20,-13, -7
-};
-static const signed char tab_y[60] = {
-	-64,-63,-62,-59,-55,-51,-47,-42,-37,-32,
-	-26,-20,-13, -7,  0,  7, 13, 20, 26, 32,
-	 37, 42, 47, 51, 55, 59, 62, 63, 64, 63,
-	 62, 59, 55, 51, 47, 42, 37, 32, 26, 20,
-	 13,  7,  0, -7,-13,-20,-26,-32,-37,-42,
-	-47,-51,-55,-59,-62,-63
-};
-
-/*
- * Hour tick positions at radius 256 for exact alignment on the circle.
- * For hour h (0=12 o'clock): x = 256*sin(h*30°), y = -256*cos(h*30°).
- * 256*√3/2 ≈ 222.
- */
-static const short hour_tab_x[12] = {
-	   0,  128,  222,  256,  222,  128,    0, -128, -222, -256, -222, -128
-};
-static const short hour_tab_y[12] = {
-	-256, -222, -128,    0,  128,  222,  256,  222,  128,    0, -128, -222
-};
-
-static unsigned int clock_cx, clock_cy, clock_radius, clock_rad_hour, clock_rad_min, clock_rad_sec, clock_tick_len;
-
-static void put_pixel(int x, int y, unsigned char color)
-{
-	vga_put_pixel_rgb((unsigned int)x, (unsigned int)y,
-		pal_r[color], pal_g[color], pal_b[color]);
-}
-
-static void clear_screen(unsigned char color)
-{
-	vga_clear_rgb(pal_r[color], pal_g[color], pal_b[color]);
-}
-
-static void draw_line(int x0, int y0, int x1, int y1, unsigned char color)
-{
-	int dx = x1 - x0;
-	int dy = y1 - y0;
-	int ax = (dx < 0) ? -dx : dx;
-	int ay = (dy < 0) ? -dy : dy;
-	int steps = (ax > ay) ? ax : ay;
-	int i;
-
-	if (steps == 0) {
-		put_pixel(x0, y0, color);
-		return;
-	}
-	for (i = 0; i <= steps; i++) {
-		int x = x0 + dx * i / steps;
-		int y = y0 + dy * i / steps;
-		put_pixel(x, y, color);
-	}
-}
-
-static void draw_circle(int cx, int cy, int r, unsigned char color)
-{
-	int x = r, y = 0;
-	int d = 1 - r;
-
-	while (y <= x) {
-		put_pixel(cx + x, cy + y, color);
-		put_pixel(cx - x, cy + y, color);
-		put_pixel(cx + x, cy - y, color);
-		put_pixel(cx - x, cy - y, color);
-		put_pixel(cx + y, cy + x, color);
-		put_pixel(cx - y, cy + x, color);
-		put_pixel(cx + y, cy - x, color);
-		put_pixel(cx - y, cy - x, color);
-		if (d <= 0) {
-			d += 2 * y + 3;
-		} else {
-			d += 2 * (y - x) + 5;
-			x--;
-		}
-		y++;
-	}
-}
-
-static void draw_thick_line(int x0, int y0, int x1, int y1, unsigned char color)
-{
-	draw_line(x0, y0, x1, y1, color);
-	draw_line(x0 + 1, y0, x1 + 1, y1, color);
-	draw_line(x0, y0 + 1, x1, y1 + 1, color);
-}
-
-static void draw_face(void)
-{
-	int i;
-	int inner = clock_radius - clock_tick_len;
-
-	draw_circle(clock_cx, clock_cy, clock_radius, COL_FACE);
-	draw_circle(clock_cx, clock_cy, clock_radius - 1, COL_FACE);
-
-	for (i = 0; i < 12; i++) {
-		/* Use high-precision hour table and rounded scaling so ticks sit on the circle */
-		int ox = clock_cx + (hour_tab_x[i] * (int)clock_radius + 128) / 256;
-		int oy = clock_cy + (hour_tab_y[i] * (int)clock_radius + 128) / 256;
-		int ix = clock_cx + (hour_tab_x[i] * (int)inner + 128) / 256;
-		int iy = clock_cy + (hour_tab_y[i] * (int)inner + 128) / 256;
-		draw_line(ix, iy, ox, oy, COL_TICK);
-	}
-}
-
-static void draw_hand(int idx60, int length, unsigned char color, int thick)
-{
-	int ex = clock_cx + tab_x[idx60] * (int)length / 64;
-	int ey = clock_cy + tab_y[idx60] * (int)length / 64;
-
-	if (thick)
-		draw_thick_line(clock_cx, clock_cy, ex, ey, color);
-	else
-		draw_line(clock_cx, clock_cy, ex, ey, color);
-}
-
-static void draw_hands(unsigned int h, unsigned int m, unsigned int s)
-{
-	int hour_idx;
-
-	hour_idx = (int)((h % 12) * 5 + m / 12);
-	if (hour_idx >= 60)
-		hour_idx = 59;
-
-	draw_hand(hour_idx, (int)clock_rad_hour, COL_HOUR, 1);
-	draw_hand((int)m, (int)clock_rad_min, COL_MIN, 1);
-	draw_hand((int)s, (int)clock_rad_sec, COL_SEC, 0);
-
-	put_pixel(clock_cx, clock_cy, COL_CENTER);
-	put_pixel(clock_cx + 1, clock_cy, COL_CENTER);
-	put_pixel(clock_cx, clock_cy + 1, COL_CENTER);
-	put_pixel(clock_cx + 1, clock_cy + 1, COL_CENTER);
-}
-
-void program_clock_main(void)
-{
-	unsigned int last_sec = 99;
-	unsigned int h, m, s;
-	unsigned int tick;
-	unsigned int w, h_;
-
-	w = vga_fb_width();
-	h_ = vga_fb_height();
-	clock_cx = w / 2;
-	clock_cy = h_ / 2;
-	clock_radius = (w < h_) ? (w / 2) : (h_ / 2);
-	if (clock_radius > 200)
-		clock_radius = 200;
-	clock_rad_hour = clock_radius / 2;
-	clock_rad_min = clock_radius * 7 / 10;
-	clock_rad_sec = clock_radius * 9 / 10;
-	clock_tick_len = clock_radius / 13;
-	if (clock_tick_len < 2)
-		clock_tick_len = 2;
-
-	clear_screen(COL_BG);
-	io_drain_keyboard();
-
-	for (;;) {
-		int k = io_poll_key();
-		if (k == 0x1B)
-			break;
-
-		rtc_read_hms(&h, &m, &s);
-		if (s != last_sec) {
-			clear_screen(COL_BG);
-			draw_face();
-			draw_hands(h, m, s);
-			last_sec = s;
-		}
-
-		tick = get_ticks_ms();
-		while (get_ticks_ms() - tick < 50)
-			__asm__ volatile ("hlt");
-	}
-
-}

+ 0 - 214
colors.c

@@ -1,214 +0,0 @@
-/* colors command: full-screen animated rainbow in VESA LFB. Target 30fps (matches flush rate). Press ESC to return. */
-
-#include "fbtext.h"
-#include "io.h"
-#include "timer.h"
-#include "vga.h"
-
-#define RAINBOW_SEG   256
-#define RAINBOW_FULL  (6 * RAINBOW_SEG)
-#define FRAME_MS      33 /* matches 30Hz flush rate */
-#define PHASE_STEP    32
-/* FPS overlay: 7 chars × 8 px wide, 8 px tall. Rainbow must not draw here. */
-#define FPS_RECT_W    (7 * 8)
-#define FPS_RECT_H    8
-
-/* Precomputed hue-to-RGB lookup table. Packed as 0x00BBGGRR for fast 32-bit load.
- * The hue cycle is RAINBOW_FULL entries, but the table is decimated by
- * LUT_STEP: a 4-hue step is ~1.5% of a color segment and invisible, and the
- * smaller table keeps the kernel image under its link-time budget (see the
- * ASSERT in kernel.ld). */
-#define LUT_STEP      4
-#define LUT_SIZE      (RAINBOW_FULL / LUT_STEP)
-
-static unsigned int hue_lut[LUT_SIZE];
-
-static void build_hue_lut(void)
-{
-	unsigned int i;
-	for (i = 0; i < LUT_SIZE; i++) {
-		unsigned int hue = i * LUT_STEP;
-		unsigned int seg = hue / RAINBOW_SEG;
-		unsigned int f   = hue % RAINBOW_SEG;
-		unsigned int r1, g1, b1, r2, g2, b2;
-		if (seg >= 6)
-			seg = 0;
-		switch (seg) {
-			case 0: r1=255; g1=0;   b1=0;   r2=255; g2=255; b2=0;   break;
-			case 1: r1=255; g1=255; b1=0;   r2=0;   g2=255; b2=0;   break;
-			case 2: r1=0;   g1=255; b1=0;   r2=0;   g2=255; b2=255; break;
-			case 3: r1=0;   g1=255; b1=255; r2=0;   g2=0;   b2=255; break;
-			case 4: r1=0;   g1=0;   b1=255; r2=255; g2=0;   b2=255; break;
-			default: r1=255; g1=0; b1=255; r2=255; g2=0;   b2=0;   break;
-		}
-		unsigned int r = (r1 * (RAINBOW_SEG - f) + r2 * f) / RAINBOW_SEG;
-		unsigned int g = (g1 * (RAINBOW_SEG - f) + g2 * f) / RAINBOW_SEG;
-		unsigned int b = (b1 * (RAINBOW_SEG - f) + b2 * f) / RAINBOW_SEG;
-		hue_lut[i] = b | (g << 8) | (r << 16);
-	}
-}
-
-static void draw_frame(unsigned char *fb, unsigned int w, unsigned int h,
-		unsigned int pitch, unsigned int bpp, unsigned int phase)
-{
-	unsigned int scale_x = RAINBOW_FULL / (w ? w : 1);
-	unsigned int scale_y = RAINBOW_FULL / (h ? h : 1);
-	unsigned int y;
-
-	for (y = 0; y < h; y++) {
-		unsigned int row_hue = (phase + y * scale_y) % RAINBOW_FULL;
-		unsigned char *row = fb + (unsigned long)y * pitch;
-
-		if (y < FPS_RECT_H) {
-			/* Skip FPS rect columns */
-			unsigned int x;
-			if (bpp == 32) {
-				unsigned int *p = (unsigned int *)row;
-				for (x = 0; x < w; x++) {
-					if (x >= FPS_RECT_W) {
-						unsigned int packed = hue_lut[row_hue / LUT_STEP];
-						*p = packed;
-					}
-					p++;
-					row_hue += scale_x;
-					if (row_hue >= RAINBOW_FULL)
-						row_hue -= RAINBOW_FULL;
-				}
-			} else if (bpp == 24) {
-				for (x = 0; x < w; x++) {
-					if (x >= FPS_RECT_W) {
-						unsigned int packed = hue_lut[row_hue / LUT_STEP];
-						row[x * 3]     = (unsigned char)(packed & 0xFF);
-						row[x * 3 + 1] = (unsigned char)((packed >> 8) & 0xFF);
-						row[x * 3 + 2] = (unsigned char)((packed >> 16) & 0xFF);
-					}
-					row_hue += scale_x;
-					if (row_hue >= RAINBOW_FULL)
-						row_hue -= RAINBOW_FULL;
-				}
-			} else if (bpp == 16) {
-				for (x = 0; x < w; x++) {
-					if (x >= FPS_RECT_W) {
-						unsigned int packed = hue_lut[row_hue / LUT_STEP];
-						unsigned int r = (packed >> 16) & 0xFF;
-						unsigned int g = (packed >> 8) & 0xFF;
-						unsigned int b = packed & 0xFF;
-						unsigned int rgb16 = ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3);
-						unsigned short *p = (unsigned short *)(row + x * 2);
-						*p = (unsigned short)rgb16;
-					}
-					row_hue += scale_x;
-					if (row_hue >= RAINBOW_FULL)
-						row_hue -= RAINBOW_FULL;
-				}
-			}
-		} else {
-			/* Full row, no FPS rect check — tight inner loop */
-			unsigned int x;
-			if (bpp == 32) {
-				unsigned int *p = (unsigned int *)row;
-				for (x = 0; x < w; x++) {
-					*p++ = hue_lut[row_hue / LUT_STEP];
-					row_hue += scale_x;
-					if (row_hue >= RAINBOW_FULL)
-						row_hue -= RAINBOW_FULL;
-				}
-			} else if (bpp == 24) {
-				for (x = 0; x < w; x++) {
-					unsigned int packed = hue_lut[row_hue / LUT_STEP];
-					row[x * 3]     = (unsigned char)(packed & 0xFF);
-					row[x * 3 + 1] = (unsigned char)((packed >> 8) & 0xFF);
-					row[x * 3 + 2] = (unsigned char)((packed >> 16) & 0xFF);
-					row_hue += scale_x;
-					if (row_hue >= RAINBOW_FULL)
-						row_hue -= RAINBOW_FULL;
-				}
-			} else if (bpp == 16) {
-				for (x = 0; x < w; x++) {
-					unsigned int packed = hue_lut[row_hue / LUT_STEP];
-					unsigned int r = (packed >> 16) & 0xFF;
-					unsigned int g = (packed >> 8) & 0xFF;
-					unsigned int b = packed & 0xFF;
-					unsigned int rgb16 = ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3);
-					unsigned short *p = (unsigned short *)(row + x * 2);
-					*p = (unsigned short)rgb16;
-					row_hue += scale_x;
-					if (row_hue >= RAINBOW_FULL)
-						row_hue -= RAINBOW_FULL;
-				}
-			}
-		}
-	}
-}
-
-#define FPS_BUF_SIZE  8
-
-static void format_fps(unsigned int fps, char *buf)
-{
-	unsigned int f = fps;
-	if (f > 999)
-		f = 999;
-	buf[0] = (char)('0' + (f / 100));
-	buf[1] = (char)('0' + ((f / 10) % 10));
-	buf[2] = (char)('0' + (f % 10));
-	buf[3] = ' ';
-	buf[4] = 'f';
-	buf[5] = 'p';
-	buf[6] = 's';
-	buf[7] = '\0';
-}
-
-void program_colors_main(void)
-{
-	unsigned char *fb;
-	unsigned int w, h, pitch, bpp;
-	unsigned int phase = 0;
-	unsigned int frame_start;
-	unsigned int frame_count = 0;
-	unsigned int last_fps_ticks;
-	unsigned int displayed_fps = 0;
-	char fps_buf[FPS_BUF_SIZE];
-
-	if (!vga_has_vesa())
-		return;
-	build_hue_lut();
-	fb = (unsigned char *)vga_fb_ptr();
-	if (!fb)
-		return;
-	w = vga_fb_width();
-	h = vga_fb_height();
-	pitch = vga_fb_pitch();
-	bpp = vga_fb_bpp();
-	if (bpp != 16 && bpp != 24 && bpp != 32)
-		return;
-
-	io_drain_keyboard();
-	last_fps_ticks = get_ticks_ms();
-
-	for (;;) {
-		frame_start = get_ticks_ms();
-		if (io_poll_key() == 0x1B)
-			break;
-		draw_frame(fb, w, h, pitch, bpp, phase);
-		phase = (phase + PHASE_STEP) % RAINBOW_FULL;
-
-		/* Mark all rows dirty since we drew the full screen */
-		vga_fb_mark_dirty_rect(0, h);
-
-		/* Trigger flush so the 30Hz timer sees dirty rows */
-		vga_fb_flush_pending_check();
-
-		frame_count++;
-		if (get_ticks_ms() - last_fps_ticks >= 1000) {
-			displayed_fps = frame_count;
-			frame_count = 0;
-			last_fps_ticks = get_ticks_ms();
-		}
-		format_fps(displayed_fps, fps_buf);
-		fbtext_draw_string_xy(0, 0, fps_buf, 255, 255, 255, 0);
-
-		/* Sleep with hlt to give the system breathing room */
-		while (get_ticks_ms() - frame_start < FRAME_MS)
-			__asm__ volatile ("hlt");
-	}
-}

+ 34 - 0
fbtext.c

@@ -328,6 +328,40 @@ void fbtext_draw_string_xy(unsigned int x0, unsigned int y0, const char *str,
 	vga_fb_mark_dirty_rect(y0, FONT_8X8_ROWS);
 }
 
+/* Like fbtext_draw_string_xy, but per-pixel clipped to (cx, cy, cw, ch): only
+ * foreground pixels inside the clip rect are written. */
+void fbtext_draw_string_xy_clip(unsigned int x0, unsigned int y0, const char *str,
+		unsigned int r_fg, unsigned int g_fg, unsigned int b_fg,
+		unsigned int cx, unsigned int cy, unsigned int cw, unsigned int ch)
+{
+	unsigned int i;
+
+	for (i = 0; str[i]; i++) {
+		unsigned int gx = x0 + i * 8;
+		const unsigned char *glyph;
+		unsigned int x, y;
+
+		if (gx + 8 <= cx || gx >= cx + cw ||
+		    y0 + FONT_8X8_ROWS <= cy || y0 >= cy + ch)
+			continue;
+		glyph = &font_8x8[(unsigned int)str[i] * FONT_8X8_ROWS];
+		for (y = 0; y < FONT_8X8_ROWS; y++) {
+			unsigned char bits = glyph[y];
+			unsigned int py = y0 + y;
+			unsigned int xa, xb;
+
+			if (!bits || py < cy || py >= cy + ch)
+				continue;
+			xa = (gx > cx) ? gx : cx;
+			xb = (gx + 8 < cx + cw) ? gx + 8 : cx + cw;
+			for (x = xa; x < xb; x++)
+				if (bits & (0x80u >> (x - gx)))
+					vga_put_pixel_rgb(x, py, r_fg, g_fg, b_fg);
+		}
+	}
+	vga_fb_mark_dirty_rect_xy(cy, ch, cx, cx + cw);
+}
+
 #define RAINBOW_LINE_HEIGHT  2   /* 2-pixel tall line for visibility */
 
 void fbtext_draw_rainbow_separator(void)

+ 6 - 0
fbtext.h

@@ -31,6 +31,12 @@ void fbtext_hide_cursor(unsigned char c, unsigned char attr);
 void fbtext_draw_string_xy(unsigned int x0, unsigned int y0, const char *str,
 		unsigned int r_fg, unsigned int g_fg, unsigned int b_fg, int transparent_bg);
 
+/* Same, but per-pixel clipped to (cx, cy, cw, ch): pixels outside the clip
+ * are never written (used by the window manager's damage-rect repaints). */
+void fbtext_draw_string_xy_clip(unsigned int x0, unsigned int y0, const char *str,
+		unsigned int r_fg, unsigned int g_fg, unsigned int b_fg,
+		unsigned int cx, unsigned int cy, unsigned int cw, unsigned int ch);
+
 /* Draw a rainbow gradient line just below the header row (between header and content). No-op if not LFB. */
 void fbtext_draw_rainbow_separator(void);
 

+ 139 - 0
gfx.c

@@ -0,0 +1,139 @@
+/* RGB565 window canvas: page-allocated, page-aligned (so it can be mapped
+ * into a ring-3 process 1:1), plus bpp-aware blits into the shadow buffer. */
+
+#include "gfx.h"
+#include "mm.h"
+#include "vga.h"
+
+int gfx_alloc(struct gfx_canvas *c, unsigned int w, unsigned int h)
+{
+	unsigned int bytes, pages, i;
+
+	c->px = 0;
+	c->w = c->h = 0;
+	c->seq = c->drawn = 0;
+	if (w == 0 || h == 0 || w > 4096 || h > 4096)
+		return -1;
+
+	bytes = w * h * 2;
+	pages = (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
+	{
+		unsigned int phys = mm_alloc_pages(pages);
+		if (!phys)
+			return -1;
+		c->px = (unsigned short *)phys;
+	}
+	c->w = w;
+	c->h = h;
+	for (i = 0; i < w * h; i++)     /* fresh memory is not zeroed */
+		c->px[i] = 0;
+	c->seq = 1;                     /* first frame: draw it once */
+	c->drawn = 0;
+	return 0;
+}
+
+void gfx_free(struct gfx_canvas *c)
+{
+	unsigned int bytes, pages, i;
+
+	if (!c->px)
+		return;
+	bytes = c->w * c->h * 2;
+	pages = (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
+	for (i = 0; i < pages; i++)
+		mm_free_page((unsigned int)c->px + i * PAGE_SIZE);
+	c->px = 0;
+	c->w = c->h = 0;
+	c->seq = c->drawn = 0;
+}
+
+/* One row of RGB565 -> the shadow buffer's pixel format.  Byte order mirrors
+ * fbtext.c's draw_glyph_at(); the 8-bit values replicate the high bits of the
+ * 5/6-bit fields so black/white and the EGA palette stay exact. */
+static void blit_row(unsigned char *dst, const unsigned short *src,
+		     unsigned int n, unsigned int bpp)
+{
+	unsigned int x;
+
+	if (bpp == 16) {
+		unsigned short *d = (unsigned short *)dst;
+		for (x = 0; x < n; x++)
+			d[x] = src[x];
+	} else if (bpp == 24) {
+		for (x = 0; x < n; x++) {
+			unsigned int p = src[x];
+			unsigned int r5 = (p >> 11) & 0x1F;
+			unsigned int g6 = (p >> 5) & 0x3F;
+			unsigned int b5 = p & 0x1F;
+
+			dst[0] = (unsigned char)((b5 << 3) | (b5 >> 2));
+			dst[1] = (unsigned char)((g6 << 2) | (g6 >> 4));
+			dst[2] = (unsigned char)((r5 << 3) | (r5 >> 2));
+			dst += 3;
+		}
+	} else {
+		unsigned int *d = (unsigned int *)dst;
+		for (x = 0; x < n; x++) {
+			unsigned int p = src[x];
+			unsigned int r5 = (p >> 11) & 0x1F;
+			unsigned int g6 = (p >> 5) & 0x3F;
+			unsigned int b5 = p & 0x1F;
+
+			d[x] = ((((r5 << 3) | (r5 >> 2))) << 16) |
+			       ((((g6 << 2) | (g6 >> 4))) << 8) |
+			       ((b5 << 3) | (b5 >> 2));
+		}
+	}
+}
+
+void gfx_blit(const struct gfx_canvas *c, unsigned int x0, unsigned int y0)
+{
+	unsigned char *fb = (unsigned char *)vga_fb_ptr();
+	unsigned int pitch = vga_fb_pitch();
+	unsigned int bpp = vga_fb_bpp();
+	unsigned int pb = (bpp == 16) ? 2 : (bpp == 24) ? 3 : 4;
+	unsigned int y;
+
+	if (!c->px || !fb)
+		return;
+	for (y = 0; y < c->h; y++)
+		blit_row(fb + (unsigned long)(y0 + y) * pitch + (unsigned long)x0 * pb,
+			 c->px + (unsigned long)y * c->w, c->w, bpp);
+	vga_fb_mark_dirty_rect_xy(y0, c->h, x0, x0 + c->w);
+}
+
+void gfx_blit_clip(const struct gfx_canvas *c, unsigned int x0, unsigned int y0,
+		   unsigned int cx, unsigned int cy, unsigned int cw, unsigned int ch)
+{
+	unsigned char *fb = (unsigned char *)vga_fb_ptr();
+	unsigned int pitch = vga_fb_pitch();
+	unsigned int bpp = vga_fb_bpp();
+	unsigned int pb = (bpp == 16) ? 2 : (bpp == 24) ? 3 : 4;
+	int dx0 = (int)x0, dy0 = (int)y0;
+	int sx0 = 0, sy0 = 0, sx1 = (int)c->w, sy1 = (int)c->h;
+	int y;
+
+	if (!c->px || !fb)
+		return;
+
+	/* Canvas coords of the clip rect (signed: the rect may miss entirely). */
+	if ((int)cx > dx0)
+		sx0 = (int)cx - dx0;
+	if ((int)cy > dy0)
+		sy0 = (int)cy - dy0;
+	if ((int)(cx + cw) < dx0 + (int)c->w)
+		sx1 = (int)(cx + cw) - dx0;
+	if ((int)(cy + ch) < dy0 + (int)c->h)
+		sy1 = (int)(cy + ch) - dy0;
+	if (sx1 <= sx0 || sy1 <= sy0)
+		return;
+
+	for (y = sy0; y < sy1; y++)
+		blit_row(fb + (unsigned long)(y0 + (unsigned int)y) * pitch +
+				(unsigned long)(x0 + (unsigned int)sx0) * pb,
+			 c->px + (unsigned long)y * c->w + sx0,
+			 (unsigned int)(sx1 - sx0), bpp);
+	vga_fb_mark_dirty_rect_xy(y0 + (unsigned int)sy0,
+				  (unsigned int)(sy1 - sy0),
+				  x0 + (unsigned int)sx0, x0 + (unsigned int)sx1);
+}

+ 25 - 0
gfx.h

@@ -0,0 +1,25 @@
+/* Window-local RGB565 canvas + blit into the VGA shadow buffer. */
+#ifndef GFX_H
+#define GFX_H
+
+struct gfx_canvas {
+	unsigned short *px;   /* w*h RGB565, page-aligned; NULL = none */
+	unsigned int w, h;
+	unsigned int seq;     /* frames the owner has presented */
+	unsigned int drawn;   /* last seq the WM composited (catch-up safe) */
+};
+
+/* Allocate a canvas of w*h pixels (zeroed; fresh memory is not).  Returns 0/-1. */
+int gfx_alloc(struct gfx_canvas *c, unsigned int w, unsigned int h);
+void gfx_free(struct gfx_canvas *c);
+
+/* Copy the canvas into the shadow buffer at pixel origin (x0, y0), converting
+ * RGB565 to the mode's 16/24/32 bpp, and mark the affected rows dirty. */
+void gfx_blit(const struct gfx_canvas *c, unsigned int x0, unsigned int y0);
+
+/* Same, but only the part whose destination bounds intersect the clip rect
+ * (cx, cy, cw, ch) - used to restore window slivers. */
+void gfx_blit_clip(const struct gfx_canvas *c, unsigned int x0, unsigned int y0,
+		   unsigned int cx, unsigned int cy, unsigned int cw, unsigned int ch);
+
+#endif

+ 11 - 0
paging.c

@@ -134,6 +134,17 @@ int paging_map_page(unsigned int cr3, unsigned int va, unsigned int phys,
 	return 1;
 }
 
+void paging_unmap_page(unsigned int cr3, unsigned int va)
+{
+	unsigned int *pd = (unsigned int *)cr3;
+	unsigned int pde = va >> 22;
+	unsigned int pte = (va >> 12) & 0x3FF;
+
+	if (!(pd[pde] & PDE_PRESENT))
+		return;
+	((unsigned int *)(pd[pde] & 0xFFFFF000))[pte] = 0;
+}
+
 /* Identity-map an MMIO range uncacheable into one page directory (4 MB pages;
  * the range is rounded up to a whole number of them). */
 void paging_map_mmio_cr3(unsigned int cr3, unsigned int phys_base, unsigned int size)

+ 4 - 0
paging.h

@@ -21,6 +21,10 @@ unsigned int paging_new_directory(void);
 int paging_map_page(unsigned int cr3, unsigned int va, unsigned int phys,
 		    unsigned int flags);
 
+/* Clear one 4 KB page (va) in page directory `cr3` (no-op when the page
+ * table is absent). */
+void paging_unmap_page(unsigned int cr3, unsigned int va);
+
 /* Identity-map an MMIO range (e.g. a GPU register aperture) uncacheable into
  * the current page directory.  Uses 4 MB pages; the range is rounded up to a
  * whole number of 4 MB pages. */

+ 2 - 0
process.c

@@ -9,6 +9,7 @@
 #include "paging.h"
 #include "serial.h"
 #include "sys_fs.h"
+#include "sys_gfx.h"
 #include "sys_net.h"
 #include "syscall.h"
 #include "timer.h"
@@ -473,6 +474,7 @@ void schedule(void)
 	for (i = 0; i < proc_cap; i++) {
 		if (procs[i].state == PROC_DEAD && i != current_pid) {
 			sys_net_reap(procs[i].pid);   /* release a held NIC */
+			sys_gfx_reap(procs[i].pid);   /* flag a gfx session dead */
 			if (procs[i].stack_base)
 				mm_free_page(procs[i].stack_base);
 			if (procs[i].cr3 && procs[i].cr3 != paging_current_cr3())

+ 66 - 23
rtc.c

@@ -19,32 +19,81 @@ static unsigned int bcd_to_bin(unsigned char bcd)
 	return (unsigned int)((bcd >> 4) * 10 + (bcd & 0x0F));
 }
 
+static int bcd_digits(unsigned char bcd)
+{
+	return (bcd & 0x0F) <= 9 && ((bcd >> 4) & 0x0F) <= 9;
+}
+
+/* Read hour/minute/second out of the CMOS.  A read that straddles the RTC's
+ * update cycle can tear (invalid BCD, or a value out of range), which used to
+ * feed nonsense into callers - retry a few times and fall back to the last
+ * values that validated.  Handles the 12-hour PM flag (hour bit 7). */
+static void rtc_read_time(unsigned int *hour, unsigned int *minute,
+			  unsigned int *second)
+{
+	static unsigned int last_h, last_m, last_s;
+	unsigned int tries;
+
+	for (tries = 0; tries < 4; tries++) {
+		unsigned int n = 0;
+		unsigned char s, m, h;
+		unsigned int sv, mv, hv;
+
+		while ((cmos_read(0x0A) & 0x80) && ++n < 10000)
+			;
+
+		s = cmos_read(0x00);
+		m = cmos_read(0x02);
+		h = (unsigned char)(cmos_read(0x04) & 0x7F);   /* drop the PM flag */
+
+		if (!bcd_digits(s) || !bcd_digits(m) || !bcd_digits(h))
+			continue;
+
+		sv = bcd_to_bin(s);
+		mv = bcd_to_bin(m);
+		hv = bcd_to_bin(h);
+		if (sv > 59 || mv > 59 || hv > 23)
+			continue;
+
+		last_h = hv;
+		last_m = mv;
+		last_s = sv;
+		break;
+	}
+
+	*hour = last_h;
+	*minute = last_m;
+	*second = last_s;
+}
+
 void rtc_read_datetime(char *buf)
 {
-	unsigned char sec, min, hour, day, month, year;
+	static unsigned int last_d = 1, last_mo = 1, last_y = 2000;
 	unsigned int s, m, h, d, mo, y;
+	unsigned char dd, mm, yy;
+
+	rtc_read_time(&h, &m, &s);
 
-	/* Wait for RTC update to finish. Timeout to avoid hang. */
+	/* Date registers (a torn read keeps the last good values). */
 	{
 		unsigned int n = 0;
+
 		while ((cmos_read(0x0A) & 0x80) && ++n < 10000)
 			;
 	}
+	dd = cmos_read(0x07);
+	mm = cmos_read(0x08);
+	yy = cmos_read(0x09);
+	if (bcd_digits(dd) && bcd_to_bin(dd) >= 1 && bcd_to_bin(dd) <= 31)
+		last_d = bcd_to_bin(dd);
+	if (bcd_digits(mm) && bcd_to_bin(mm) >= 1 && bcd_to_bin(mm) <= 12)
+		last_mo = bcd_to_bin(mm);
+	if (bcd_digits(yy))
+		last_y = 2000 + bcd_to_bin(yy);
 
-	sec   = cmos_read(0x00);
-	min   = cmos_read(0x02);
-	hour  = cmos_read(0x04);
-	day   = cmos_read(0x07);
-	month = cmos_read(0x08);
-	year  = cmos_read(0x09);
-
-	s  = bcd_to_bin(sec);
-	m  = bcd_to_bin(min);
-	h  = bcd_to_bin(hour);
-	d  = bcd_to_bin(day);
-	mo = bcd_to_bin(month);
-	y  = bcd_to_bin(year);
-	y += 2000;
+	d = last_d;
+	mo = last_mo;
+	y = last_y;
 	if (y < 2000)
 		y += 100;
 
@@ -72,11 +121,5 @@ void rtc_read_datetime(char *buf)
 
 void rtc_read_hms(unsigned int *hour, unsigned int *minute, unsigned int *second)
 {
-	unsigned int n = 0;
-
-	while ((cmos_read(0x0A) & 0x80) && ++n < 10000)
-		;
-	*second = bcd_to_bin(cmos_read(0x00));
-	*minute = bcd_to_bin(cmos_read(0x02));
-	*hour   = bcd_to_bin(cmos_read(0x04));
+	rtc_read_time(hour, minute, second);
 }

+ 264 - 0
sys_gfx.c

@@ -0,0 +1,264 @@
+/* Window graphics sessions: one double-buffered canvas per window, mapped
+ * into the owning ring-3 process.  The process draws into the mapped back
+ * buffer; SYS_GFX_PRESENT copies it into the front buffer, which is the only
+ * thing the WM ever composites - so a half-drawn frame can never reach the
+ * screen (the copy runs with interrupts off).  Sessions are keyed by the
+ * owner's pid and by the terminal screen (the screen pointer is what a
+ * spawned command inherits, so it identifies the window without any new
+ * plumbing in process.c). */
+
+#include "sys_gfx.h"
+#include "mm.h"
+#include "paging.h"
+#include "process.h"
+#include "wm.h"
+
+#define GFX_MAX_SESSIONS MAX_WINDOWS
+#define GFX_USER_BASE    0x50000000   /* canvas mapping for the owner */
+#define GFX_KEY_RING     16
+
+struct gfx_session {
+	int used;
+	int dead;             /* owner gone: free on the next WM collect */
+	unsigned int pid;
+	unsigned int cr3;     /* owner's page directory (to unmap on END) */
+	struct term *term;
+	struct gfx_canvas c;  /* front buffer: what the WM composites */
+	unsigned short *back; /* back buffer: mapped to the owner */
+	unsigned int back_pages;
+	int keys[GFX_KEY_RING];
+	unsigned int key_head, key_tail;
+};
+
+static struct gfx_session sessions[GFX_MAX_SESSIONS];
+
+static inline void invlpg_va(unsigned int va)
+{
+	__asm__ volatile ("invlpg (%0)" : : "r"(va) : "memory");
+}
+
+static struct gfx_session *by_pid(unsigned int pid)
+{
+	unsigned int i;
+
+	for (i = 0; i < GFX_MAX_SESSIONS; i++)
+		if (sessions[i].used && !sessions[i].dead && sessions[i].pid == pid)
+			return &sessions[i];
+	return 0;
+}
+
+static struct gfx_session *by_screen(struct text_screen *s)
+{
+	unsigned int i;
+
+	for (i = 0; i < GFX_MAX_SESSIONS; i++)
+		if (sessions[i].used && !sessions[i].dead &&
+		    &sessions[i].term->screen == s)
+			return &sessions[i];
+	return 0;
+}
+
+static void free_back(struct gfx_session *s)
+{
+	unsigned int i;
+
+	if (!s->back)
+		return;
+	for (i = 0; i < s->back_pages; i++)
+		mm_free_page((unsigned int)s->back + i * PAGE_SIZE);
+	s->back = 0;
+	s->back_pages = 0;
+}
+
+static void unmap_all(struct gfx_session *s)
+{
+	unsigned int i;
+
+	if (!s->cr3 || !s->back)
+		return;
+	for (i = 0; i < s->back_pages; i++)
+		paging_unmap_page(s->cr3, GFX_USER_BASE + i * PAGE_SIZE);
+	s->cr3 = 0;
+}
+
+int sys_gfx_begin(struct sys_gfx_info *info)
+{
+	struct gfx_session *s = 0;
+	struct term *t;
+	unsigned int w, h, i, pages;
+
+	if (!info)
+		return -1;
+	if (by_pid(procs[current_pid].pid))
+		return -1;                       /* one session per process */
+	t = wm_term_for_screen(procs[current_pid].screen);
+	if (!t)
+		return -1;                       /* no window (not spawned by a terminal) */
+	if (by_screen(&t->screen))
+		return -1;                       /* one gfx command per window */
+
+	for (i = 0; i < GFX_MAX_SESSIONS; i++)
+		if (!sessions[i].used) {
+			s = &sessions[i];
+			break;
+		}
+	if (!s)
+		return -1;
+	if (wm_content_size(t, &w, &h) != 0)
+		return -1;
+	if (gfx_alloc(&s->c, w, h) != 0)
+		return -1;
+
+	pages = (w * h * 2 + PAGE_SIZE - 1) / PAGE_SIZE;
+	s->back = (unsigned short *)mm_alloc_pages(pages);
+	if (!s->back) {
+		gfx_free(&s->c);
+		return -1;
+	}
+	s->back_pages = pages;
+	for (i = 0; i < w * h; i++)     /* fresh memory is not zeroed */
+		s->back[i] = 0;
+
+	for (i = 0; i < pages; i++) {
+		if (!paging_map_page(procs[current_pid].cr3,
+				     GFX_USER_BASE + i * PAGE_SIZE,
+				     (unsigned int)s->back + i * PAGE_SIZE,
+				     PTE_USER | PTE_WRITABLE | PTE_PRESENT)) {
+			while (i--)
+				paging_unmap_page(procs[current_pid].cr3,
+						  GFX_USER_BASE + i * PAGE_SIZE);
+			free_back(s);
+			gfx_free(&s->c);
+			return -1;
+		}
+		invlpg_va(GFX_USER_BASE + i * PAGE_SIZE);
+	}
+
+	s->used = 1;
+	s->dead = 0;
+	s->pid = procs[current_pid].pid;
+	s->cr3 = procs[current_pid].cr3;
+	s->term = t;
+	s->key_head = s->key_tail = 0;
+
+	info->width = w;
+	info->height = h;
+	info->fb = (void *)GFX_USER_BASE;
+	return 0;
+}
+
+int sys_gfx_present(void)
+{
+	struct gfx_session *s = by_pid(procs[current_pid].pid);
+	const unsigned short *src;   /* the caller's own view of its canvas */
+	unsigned int n, i;
+
+	if (!s)
+		return -1;
+	n = s->c.w * s->c.h;
+
+	/* The syscall runs on the caller's page directory, so read the canvas
+	 * through the caller's mapping: that is exactly the memory the command
+	 * drew into and presented. */
+	src = (const unsigned short *)GFX_USER_BASE;
+
+	/* Publish: copy the finished frame into the composited front buffer.
+	 * The syscall runs with interrupts off, so the WM can never observe (or
+	 * blit) a half-copied frame. */
+	for (i = 0; i + 1 < n; i += 2)
+		((unsigned int *)s->c.px)[i / 2] = ((const unsigned int *)src)[i / 2];
+	if (n & 1)
+		s->c.px[n - 1] = src[n - 1];
+	s->c.seq++;
+	return 0;
+}
+
+int sys_gfx_end(void)
+{
+	struct gfx_session *s = by_pid(procs[current_pid].pid);
+
+	if (!s)
+		return -1;
+	unmap_all(s);
+	gfx_free(&s->c);
+	free_back(s);
+	s->used = 0;
+	wm_request_redraw();       /* the window falls back to its text cells */
+	return 0;
+}
+
+int sys_gfx_key_poll(void)
+{
+	struct gfx_session *s = by_pid(procs[current_pid].pid);
+	int k;
+
+	if (!s || s->key_tail == s->key_head)
+		return 0;
+	k = s->keys[s->key_tail];
+	s->key_tail = (s->key_tail + 1) % GFX_KEY_RING;
+	return k;
+}
+
+/* WM: the canvas to composite for a window's screen, or NULL. */
+struct gfx_canvas *sys_gfx_canvas_for(struct text_screen *screen)
+{
+	struct gfx_session *s = by_screen(screen);
+
+	return s ? &s->c : 0;
+}
+
+/* WM: hand a key to the focused window's gfx command.  1 = consumed. */
+int sys_gfx_push_key(struct text_screen *screen, int k)
+{
+	struct gfx_session *s = by_screen(screen);
+	unsigned int next;
+
+	if (!s)
+		return 0;
+	next = (s->key_head + 1) % GFX_KEY_RING;
+	if (next != s->key_tail) {
+		s->keys[s->key_head] = k;
+		s->key_head = next;
+	}
+	return 1;      /* consumed even when the ring is full (drop, don't leak) */
+}
+
+/* WM: the window is closing; stop its gfx command and free its canvas. */
+void sys_gfx_kill_for_screen(struct text_screen *screen)
+{
+	struct gfx_session *s = by_screen(screen);
+
+	if (!s)
+		return;
+	process_kill(s->pid);
+	s->dead = 1;   /* freed by the next sys_gfx_collect() */
+}
+
+/* Reaper hook (schedule(), IRQ context): only flag the session. */
+void sys_gfx_reap(unsigned int pid)
+{
+	unsigned int i;
+
+	for (i = 0; i < GFX_MAX_SESSIONS; i++)
+		if (sessions[i].used && !sessions[i].dead && sessions[i].pid == pid)
+			sessions[i].dead = 1;
+}
+
+/* WM loop: free dead sessions away from the renderer (the reaper can run
+ * while the WM is mid-blit, so freeing there would be unsafe). */
+void sys_gfx_collect(void)
+{
+	unsigned int i;
+	int freed = 0;
+
+	for (i = 0; i < GFX_MAX_SESSIONS; i++) {
+		if (sessions[i].used && sessions[i].dead) {
+			gfx_free(&sessions[i].c);
+			free_back(&sessions[i]);
+			sessions[i].used = 0;
+			freed = 1;
+		}
+	}
+	if (freed)
+		wm_request_redraw();
+}

+ 22 - 0
sys_gfx.h

@@ -0,0 +1,22 @@
+/* Window graphics service for ring-3 commands (see sys_gfx.c). */
+#ifndef SYS_GFX_H
+#define SYS_GFX_H
+
+#include "gfx.h"
+#include "syscall.h"
+
+struct text_screen;
+
+int  sys_gfx_begin(struct sys_gfx_info *info);
+int  sys_gfx_present(void);
+int  sys_gfx_end(void);
+int  sys_gfx_key_poll(void);
+
+/* WM-facing helpers. */
+struct gfx_canvas *sys_gfx_canvas_for(struct text_screen *screen);
+int  sys_gfx_push_key(struct text_screen *screen, int k);   /* 1 = consumed */
+void sys_gfx_kill_for_screen(struct text_screen *screen);   /* window close */
+void sys_gfx_reap(unsigned int pid);                        /* IRQ context */
+void sys_gfx_collect(void);                                 /* WM loop */
+
+#endif

+ 22 - 0
syscall.c

@@ -3,8 +3,10 @@
 #include "syscall.h"
 #include "io.h"
 #include "process.h"
+#include "rtc.h"
 #include "serial.h"
 #include "sys_fs.h"
+#include "sys_gfx.h"
 #include "sys_info.h"
 #include "sys_net.h"
 #include "timer.h"
@@ -143,6 +145,26 @@ int syscall_dispatch(int num, int a1, int a2, int a3)
 	case SYS_SET_CURSOR:
 		io_set_cursor((unsigned int)a1);
 		return 0;
+	case SYS_GFX_BEGIN:
+		return sys_gfx_begin((struct sys_gfx_info *)a1);
+	case SYS_GFX_PRESENT:
+		return sys_gfx_present();
+	case SYS_GFX_END:
+		return sys_gfx_end();
+	case SYS_KEY_POLL:
+		return sys_gfx_key_poll();
+	case SYS_RTC_HMS: {
+		struct sys_time *out = (struct sys_time *)a1;
+		unsigned int h, m, s;
+
+		if (!out)
+			return -1;
+		rtc_read_hms(&h, &m, &s);
+		out->hour = h;
+		out->minute = m;
+		out->second = s;
+		return 0;
+	}
 	default:
 		return -1;
 	}

+ 24 - 0
syscall.h

@@ -75,6 +75,16 @@
 #define SYS_GET_CURSOR   50  /* () -> cursor position of the caller's screen */
 #define SYS_SET_CURSOR   51  /* (unsigned int pos) -> 0 */
 
+/* Window graphics service (see sys_gfx.c): a ring-3 command maps its terminal
+ * window's RGB565 back buffer and draws directly into it; SYS_GFX_PRESENT
+ * copies it into the composited front buffer (double buffering, so the WM
+ * never shows a half-drawn frame).  One session per process and per window. */
+#define SYS_GFX_BEGIN    52  /* (struct sys_gfx_info *out) -> 0/-1 */
+#define SYS_GFX_PRESENT  53  /* () -> 0/-1; publish a finished frame */
+#define SYS_GFX_END      54  /* () -> 0/-1; unmap + free the canvas */
+#define SYS_KEY_POLL     55  /* () -> 0 none, ASCII, or IO_KEY_*; gfx session only */
+#define SYS_RTC_HMS      56  /* (struct sys_time *out) -> 0/-1 */
+
 struct sys_netinfo {
 	unsigned int present;
 	unsigned char mac[6];
@@ -130,6 +140,20 @@ struct sys_procinfo {
 	char name[12];
 };
 
+/* Window canvas handed to a ring-3 graphics command (see sys_gfx.c). */
+struct sys_gfx_info {
+	unsigned int width;    /* canvas (= window content) size in pixels */
+	unsigned int height;
+	void *fb;              /* user VA of the mapped RGB565 canvas */
+};
+
+/* Wall clock for the ring-3 clock (see rtc.c). */
+struct sys_time {
+	unsigned int hour;     /* 0-23 */
+	unsigned int minute;   /* 0-59 */
+	unsigned int second;   /* 0-59 */
+};
+
 struct sys_e820 {
 	unsigned int base;      /* low 32 bits, as meminfo always printed */
 	unsigned int length;

+ 2 - 24
terminal.c

@@ -12,8 +12,6 @@
 extern void program_reboot_main(void);
 extern void program_poweroff_main(void);
 extern void program_run_main(const char *filename);
-extern void program_clock_main(void);
-extern void program_colors_main(void);
 extern void program_display_main(void);
 extern void program_serial_loop_main(const char *arg);
 extern void program_serial_recv_main(const char *arg);
@@ -40,8 +38,8 @@ static void term_print_prompt(struct term *t, int first)
  *
  * One table drives command dispatch, `help` and Tab completion.  Most commands
  * are spawned as separate kernel processes; the CK_CUSTOM handlers are the
- * shell builtins, the commands that must run inline (ps/kill/kexec/...) and the
- * ones deliberately unavailable in a windowed terminal. */
+ * shell builtins, the commands that must run inline (ps/kill/kexec/...) and
+ * `run`, the one command still unavailable in a windowed terminal. */
 
 enum cmd_kind {
 	CK_SPAWN = 0,        /* spawn, no arguments */
@@ -72,8 +70,6 @@ static int term_path_spawn(struct term *t, const char *word, const char *args);
 
 static int cmd_cd(struct term *t, const char *args);
 static int cmd_clear(struct term *t, const char *args);
-static int cmd_clock(struct term *t, const char *args);
-static int cmd_colors(struct term *t, const char *args);
 static int cmd_dbg(struct term *t, const char *args);
 static int cmd_format(struct term *t, const char *args);
 static int cmd_help(struct term *t, const char *args);
@@ -98,8 +94,6 @@ static const struct kcmd cmds[] = {
 	{ "prog",       "prog",                          CK_SPAWN, 0, 0, program_run_embedded_main, "prog", 0 },
 	{ "reboot",     "reboot",                        CK_CUSTOM, 0, 0, 0, 0, cmd_reboot },
 	{ "poweroff",   "poweroff",                      CK_CUSTOM, 0, 0, 0, 0, cmd_poweroff },
-	{ "clock",      "clock",                         CK_CUSTOM, 0, 0, 0, 0, cmd_clock },
-	{ "colors",     "colors",                        CK_CUSTOM, 0, 0, 0, 0, cmd_colors },
 	{ "display",    "display",                       CK_SPAWN, 0, program_display_main, 0, 0, 0 },
 	{ "lsusb",      "lsusb",                         CK_SPAWN, 0, program_lsusb_main, 0, 0, 0 },
 	{ "format",     "format <device>",               CK_CUSTOM, 0, 0, 0, 0, cmd_format },
@@ -243,22 +237,6 @@ static int cmd_clear(struct term *t, const char *args)
 	return 1;   /* prompt already printed */
 }
 
-static int cmd_clock(struct term *t, const char *args)
-{
-	(void)t;
-	(void)args;
-	io_putstr("clock: not available in windowed mode yet\n");
-	return 0;
-}
-
-static int cmd_colors(struct term *t, const char *args)
-{
-	(void)t;
-	(void)args;
-	io_putstr("colors: not available in windowed mode yet\n");
-	return 0;
-}
-
 static int cmd_dbg(struct term *t, const char *args)
 {
 	(void)t;

+ 207 - 0
ucmd_clock.c

@@ -0,0 +1,207 @@
+/* clock: analog clock drawn into the terminal window's canvas.  ESC (or
+ * Ctrl+C, which the terminal turns into a kill) returns to the shell. */
+
+#include "ucmd_lib.h"
+
+/* Palette index to RGB. 0=black, 7=gray, 12=light red, 15=white */
+static const unsigned char pal_r[16] = { 0, 0, 0, 0, 170, 170, 170, 170, 85, 85, 85, 85, 255, 255, 255, 255 };
+static const unsigned char pal_g[16] = { 0, 0, 170, 170, 0, 0, 85, 170, 85, 85, 255, 255, 85, 85, 255, 255 };
+static const unsigned char pal_b[16] = { 0, 170, 0, 170, 0, 170, 0, 170, 85, 255, 85, 255, 85, 255, 85, 255 };
+
+#define COL_BG      0
+#define COL_FACE    15
+#define COL_TICK    7
+#define COL_HOUR    15
+#define COL_MIN     15
+#define COL_SEC     12
+#define COL_CENTER  15
+
+/* Unit-vector table at radius 64 for 60 clock positions (from the old kernel
+ * clock.c). */
+static const signed char tab_x[60] = {
+	  0,  7, 13, 20, 26, 32, 37, 42, 47, 51,
+	 55, 59, 62, 63, 64, 63, 62, 59, 55, 51,
+	 47, 42, 37, 32, 26, 20, 13,  7,  0, -7,
+	-13,-20,-26,-32,-37,-42,-47,-51,-55,-59,
+	-62,-63,-64,-63,-62,-59,-55,-51,-47,-42,
+	-37,-32,-26,-20,-13, -7
+};
+static const signed char tab_y[60] = {
+	-64,-63,-62,-59,-55,-51,-47,-42,-37,-32,
+	-26,-20,-13, -7,  0,  7, 13, 20, 26, 32,
+	 37, 42, 47, 51, 55, 59, 62, 63, 64, 63,
+	 62, 59, 55, 51, 47, 42, 37, 32, 26, 20,
+	 13,  7,  0, -7,-13,-20,-26,-32,-37,-42,
+	-47,-51,-55,-59,-62,-63
+};
+
+/* Hour tick positions at radius 256; 256*sin(h*30), -256*cos(h*30). */
+static const short hour_tab_x[12] = {
+	   0,  128,  222,  256,  222,  128,    0, -128, -222, -256, -222, -128
+};
+static const short hour_tab_y[12] = {
+	-256, -222, -128,    0,  128,  222,  256,  222,  128,    0, -128, -222
+};
+
+static unsigned short *fb;
+static unsigned int cw, ch;
+static unsigned int cx, cy, radius, rad_hour, rad_min, rad_sec, tick_len;
+
+static unsigned short rgb565(unsigned int r, unsigned int g, unsigned int b)
+{
+	return (unsigned short)(((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3));
+}
+
+static void put_pixel(int x, int y, unsigned char color)
+{
+	if (x < 0 || y < 0 || (unsigned int)x >= cw || (unsigned int)y >= ch)
+		return;
+	fb[(unsigned int)y * cw + (unsigned int)x] =
+		rgb565(pal_r[color], pal_g[color], pal_b[color]);
+}
+
+static void clear_screen(unsigned char color)
+{
+	unsigned int i, n = cw * ch;
+	unsigned short v = rgb565(pal_r[color], pal_g[color], pal_b[color]);
+
+	for (i = 0; i < n; i++)
+		fb[i] = v;
+}
+
+static void draw_line(int x0, int y0, int x1, int y1, unsigned char color)
+{
+	int dx = x1 - x0, dy = y1 - y0;
+	int ax = (dx < 0) ? -dx : dx, ay = (dy < 0) ? -dy : dy;
+	int steps = (ax > ay) ? ax : ay;
+	int i;
+
+	if (steps == 0) {
+		put_pixel(x0, y0, color);
+		return;
+	}
+	for (i = 0; i <= steps; i++)
+		put_pixel(x0 + dx * i / steps, y0 + dy * i / steps, color);
+}
+
+static void draw_circle(int ccx, int ccy, int r, unsigned char color)
+{
+	int x = r, y = 0, d = 1 - r;
+
+	while (y <= x) {
+		put_pixel(ccx + x, ccy + y, color);
+		put_pixel(ccx - x, ccy + y, color);
+		put_pixel(ccx + x, ccy - y, color);
+		put_pixel(ccx - x, ccy - y, color);
+		put_pixel(ccx + y, ccy + x, color);
+		put_pixel(ccx - y, ccy + x, color);
+		put_pixel(ccx + y, ccy - x, color);
+		put_pixel(ccx - y, ccy - x, color);
+		if (d <= 0)
+			d += 2 * y + 3;
+		else {
+			d += 2 * (y - x) + 5;
+			x--;
+		}
+		y++;
+	}
+}
+
+static void draw_thick_line(int x0, int y0, int x1, int y1, unsigned char color)
+{
+	draw_line(x0, y0, x1, y1, color);
+	draw_line(x0 + 1, y0, x1 + 1, y1, color);
+	draw_line(x0, y0 + 1, x1, y1 + 1, color);
+}
+
+static void draw_face(void)
+{
+	int i, inner = (int)radius - (int)tick_len;
+
+	draw_circle((int)cx, (int)cy, (int)radius, COL_FACE);
+	draw_circle((int)cx, (int)cy, (int)radius - 1, COL_FACE);
+	for (i = 0; i < 12; i++) {
+		int ox = (int)cx + (hour_tab_x[i] * (int)radius + 128) / 256;
+		int oy = (int)cy + (hour_tab_y[i] * (int)radius + 128) / 256;
+		int ix = (int)cx + (hour_tab_x[i] * inner + 128) / 256;
+		int iy = (int)cy + (hour_tab_y[i] * inner + 128) / 256;
+		draw_line(ix, iy, ox, oy, COL_TICK);
+	}
+}
+
+static void draw_hand(int idx60, int length, unsigned char color, int thick)
+{
+	int ex = (int)cx + tab_x[idx60] * length / 64;
+	int ey = (int)cy + tab_y[idx60] * length / 64;
+
+	if (thick)
+		draw_thick_line((int)cx, (int)cy, ex, ey, color);
+	else
+		draw_line((int)cx, (int)cy, ex, ey, color);
+}
+
+static void draw_hands(unsigned int h, unsigned int m, unsigned int s)
+{
+	int hour_idx = (int)((h % 12) * 5 + m / 12);
+
+	if (hour_idx >= 60)
+		hour_idx = 59;
+	draw_hand(hour_idx, (int)rad_hour, COL_HOUR, 1);
+	draw_hand((int)m, (int)rad_min, COL_MIN, 1);
+	draw_hand((int)s, (int)rad_sec, COL_SEC, 0);
+	put_pixel((int)cx, (int)cy, COL_CENTER);
+	put_pixel((int)cx + 1, (int)cy, COL_CENTER);
+	put_pixel((int)cx, (int)cy + 1, COL_CENTER);
+	put_pixel((int)cx + 1, (int)cy + 1, COL_CENTER);
+}
+
+void _start(const char *arg)
+{
+	struct sys_gfx_info info;
+	struct sys_time tm;
+	unsigned int last_sec = 99;
+
+	(void)arg;
+	if (u_gfx_begin(&info) != 0) {
+		u_puts("clock: no graphics window\n");
+		u_exit(1);
+	}
+	fb = (unsigned short *)info.fb;
+	cw = info.width;
+	ch = info.height;
+
+	cx = cw / 2;
+	cy = ch / 2;
+	radius = (cw < ch) ? cw / 2 : ch / 2;
+	if (radius > 200)
+		radius = 200;
+	rad_hour = radius / 2;
+	rad_min = radius * 7 / 10;
+	rad_sec = radius * 9 / 10;
+	tick_len = radius / 13;
+	if (tick_len < 2)
+		tick_len = 2;
+
+	for (;;) {
+		int k = u_key_poll();
+
+		if (k == 0x1B)
+			break;
+		u_rtc_hms(&tm);
+		if (tm.hour > 23 || tm.minute > 59 || tm.second > 59) {
+			/* bogus read (should not happen): never index with it */
+			u_sleep_ms(50);
+			continue;
+		}
+		if (tm.second != last_sec) {
+			clear_screen(COL_BG);
+			draw_face();
+			draw_hands(tm.hour, tm.minute, tm.second);
+			last_sec = tm.second;
+			u_gfx_present();
+		}
+		u_sleep_ms(50);
+	}
+	u_gfx_end();
+	u_exit(0);
+}

+ 182 - 0
ucmd_colors.c

@@ -0,0 +1,182 @@
+/* colors: animated rainbow in the terminal window's canvas.  ESC returns.
+ * Target 30 fps, matching the WM flush rate. */
+
+#include "ucmd_lib.h"
+
+#define RAINBOW_SEG   256
+#define RAINBOW_FULL  (6 * RAINBOW_SEG)
+#define FRAME_MS      33
+#define PHASE_STEP    32
+
+/* Hue LUT decimated by 4 (see the old kernel colors.c): stores RGB565. */
+#define LUT_STEP      4
+#define LUT_SIZE      (RAINBOW_FULL / LUT_STEP)
+
+/* FPS overlay: 7 chars x 8 px, top-left; the rainbow skips this rect. */
+#define FPS_RECT_W    (7 * 8)
+#define FPS_RECT_H    8
+
+static unsigned short hue_lut[LUT_SIZE];
+
+static unsigned short rgb565(unsigned int r, unsigned int g, unsigned int b)
+{
+	return (unsigned short)(((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3));
+}
+
+static void build_hue_lut(void)
+{
+	unsigned int i;
+
+	for (i = 0; i < LUT_SIZE; i++) {
+		unsigned int hue = i * LUT_STEP;
+		unsigned int seg = hue / RAINBOW_SEG;
+		unsigned int f = hue % RAINBOW_SEG;
+		unsigned int r1, g1, b1, r2, g2, b2, r, g, b;
+
+		if (seg >= 6)
+			seg = 0;
+		switch (seg) {
+		case 0: r1 = 255; g1 = 0;   b1 = 0;   r2 = 255; g2 = 255; b2 = 0;   break;
+		case 1: r1 = 255; g1 = 255; b1 = 0;   r2 = 0;   g2 = 255; b2 = 0;   break;
+		case 2: r1 = 0;   g1 = 255; b1 = 0;   r2 = 0;   g2 = 255; b2 = 255; break;
+		case 3: r1 = 0;   g1 = 255; b1 = 255; r2 = 0;   g2 = 0;   b2 = 255; break;
+		case 4: r1 = 0;   g1 = 0;   b1 = 255; r2 = 255; g2 = 0;   b2 = 255; break;
+		default: r1 = 255; g1 = 0; b1 = 255;  r2 = 255; g2 = 0;   b2 = 0;   break;
+		}
+		r = (r1 * (RAINBOW_SEG - f) + r2 * f) / RAINBOW_SEG;
+		g = (g1 * (RAINBOW_SEG - f) + g2 * f) / RAINBOW_SEG;
+		b = (b1 * (RAINBOW_SEG - f) + b2 * f) / RAINBOW_SEG;
+		hue_lut[i] = rgb565(r, g, b);
+	}
+}
+
+static void draw_frame(unsigned short *px, unsigned int w, unsigned int h,
+		       unsigned int phase)
+{
+	unsigned int scale_x = RAINBOW_FULL / (w ? w : 1);
+	unsigned int scale_y = RAINBOW_FULL / (h ? h : 1);
+	unsigned int y, x;
+
+	for (y = 0; y < h; y++) {
+		unsigned int row_hue = (phase + y * scale_y) % RAINBOW_FULL;
+		unsigned short *row = px + y * w;
+
+		for (x = 0; x < w; x++) {
+			if (!(y < FPS_RECT_H && x < FPS_RECT_W))
+				row[x] = hue_lut[row_hue / LUT_STEP];
+			row_hue += scale_x;
+			if (row_hue >= RAINBOW_FULL)
+				row_hue -= RAINBOW_FULL;
+		}
+	}
+}
+
+/* Minimal 8x8 glyphs for the FPS overlay: "0123456789 fps" (subset of
+ * font_8x8.c, to keep the ELF small). */
+static const unsigned char glyphs[13][8] = {
+	{ 0x3C,0x66,0x6E,0x76,0x66,0x66,0x3C,0x00 }, /* 0 */
+	{ 0x18,0x38,0x18,0x18,0x18,0x18,0x7E,0x00 }, /* 1 */
+	{ 0x3C,0x66,0x06,0x0C,0x18,0x30,0x7E,0x00 }, /* 2 */
+	{ 0x3C,0x66,0x06,0x1C,0x06,0x66,0x3C,0x00 }, /* 3 */
+	{ 0x06,0x0E,0x1E,0x36,0x66,0x7F,0x06,0x00 }, /* 4 */
+	{ 0x7E,0x60,0x7C,0x06,0x06,0x66,0x3C,0x00 }, /* 5 */
+	{ 0x3C,0x66,0x60,0x7C,0x66,0x66,0x3C,0x00 }, /* 6 */
+	{ 0x7E,0x06,0x0C,0x18,0x30,0x30,0x30,0x00 }, /* 7 */
+	{ 0x3C,0x66,0x66,0x3C,0x66,0x66,0x3C,0x00 }, /* 8 */
+	{ 0x3C,0x66,0x66,0x3E,0x06,0x66,0x3C,0x00 }, /* 9 */
+	{ 0x1C,0x30,0x30,0x7C,0x30,0x30,0x30,0x00 }, /* f */
+	{ 0x00,0x00,0x7C,0x66,0x66,0x7C,0x60,0x60 }, /* p */
+	{ 0x00,0x00,0x3E,0x60,0x3C,0x06,0x7C,0x00 }, /* s */
+};
+
+static int glyph_index(char c)
+{
+	if (c >= '0' && c <= '9')
+		return c - '0';
+	if (c == 'f')
+		return 10;
+	if (c == 'p')
+		return 11;
+	if (c == 's')
+		return 12;
+	return -1;
+}
+
+static void draw_string(unsigned short *px, unsigned int w, unsigned int h,
+			unsigned int x0, unsigned int y0, const char *s)
+{
+	for (; *s; s++, x0 += 8) {
+		int gi = glyph_index(*s);
+		unsigned int x, y;
+
+		if (gi < 0)
+			continue;      /* spaces etc. */
+		for (y = 0; y < 8; y++) {
+			if (y0 + y >= h)
+				break;
+			for (x = 0; x < 8; x++)
+				if ((glyphs[gi][y] & (0x80u >> x)) && x0 + x < w)
+					px[(y0 + y) * w + x0 + x] = rgb565(255, 255, 255);
+		}
+	}
+}
+
+static void format_fps(unsigned int fps, char *buf)
+{
+	if (fps > 999)
+		fps = 999;
+	buf[0] = (char)('0' + fps / 100);
+	buf[1] = (char)('0' + (fps / 10) % 10);
+	buf[2] = (char)('0' + fps % 10);
+	buf[3] = ' ';
+	buf[4] = 'f';
+	buf[5] = 'p';
+	buf[6] = 's';
+	buf[7] = '\0';
+}
+
+void _start(const char *arg)
+{
+	struct sys_gfx_info info;
+	unsigned short *px;
+	unsigned int w, h, phase = 0, frames = 0, last_fps, displayed = 0;
+	char fps_buf[8];
+
+	(void)arg;
+	if (u_gfx_begin(&info) != 0) {
+		u_puts("colors: no graphics window\n");
+		u_exit(1);
+	}
+	px = (unsigned short *)info.fb;
+	w = info.width;
+	h = info.height;
+	build_hue_lut();
+	last_fps = u_ticks_ms();
+
+	for (;;) {
+		unsigned int frame_start, elapsed;
+
+		if (u_key_poll() == 0x1B)
+			break;
+		frame_start = u_ticks_ms();
+
+		draw_frame(px, w, h, phase);
+		phase = (phase + PHASE_STEP) % RAINBOW_FULL;
+
+		frames++;
+		if (frame_start - last_fps >= 1000) {
+			displayed = frames;
+			frames = 0;
+			last_fps = frame_start;
+		}
+		format_fps(displayed, fps_buf);
+		draw_string(px, w, h, 0, 0, fps_buf);
+		u_gfx_present();
+
+		elapsed = u_ticks_ms() - frame_start;
+		if (elapsed < FRAME_MS)
+			u_sleep_ms(FRAME_MS - elapsed);
+	}
+	u_gfx_end();
+	u_exit(0);
+}

+ 25 - 0
ucmd_lib.h

@@ -181,4 +181,29 @@ static inline void u_exit(int code)
 		;
 }
 
+static inline int u_rtc_hms(struct sys_time *t)
+{
+	return u_syscall1(SYS_RTC_HMS, (int)t);
+}
+
+static inline int u_gfx_begin(struct sys_gfx_info *info)
+{
+	return u_syscall1(SYS_GFX_BEGIN, (int)info);
+}
+
+static inline int u_gfx_present(void)
+{
+	return u_syscall0(SYS_GFX_PRESENT);
+}
+
+static inline int u_gfx_end(void)
+{
+	return u_syscall0(SYS_GFX_END);
+}
+
+static inline int u_key_poll(void)
+{
+	return u_syscall0(SYS_KEY_POLL);
+}
+
 #endif

+ 143 - 64
wm.c

@@ -14,6 +14,7 @@
 #include "payload.h"
 #include "process.h"
 #include "rtc.h"
+#include "sys_gfx.h"
 #include "timer.h"
 #include "version.h"
 #include "vga.h"
@@ -48,6 +49,34 @@ int wm_is_focused(const struct window *w)
 	return w->focused;
 }
 
+/* The terminal whose screen is `screen`, or NULL: a spawned ring-3 command
+ * inherits its terminal's screen pointer, so this maps it back to the window
+ * (used by the sys_gfx window-canvas service). */
+struct term *wm_term_for_screen(struct text_screen *screen)
+{
+	unsigned int i;
+
+	for (i = 0; i < MAX_WINDOWS; i++)
+		if (windows[i].used && windows[i].term &&
+		    &windows[i].term->screen == screen)
+			return windows[i].term;
+	return 0;
+}
+
+/* Pixel size of a window's content area (the size of its gfx canvas). */
+int wm_content_size(struct term *t, unsigned int *w, unsigned int *h)
+{
+	unsigned int i;
+
+	for (i = 0; i < MAX_WINDOWS; i++)
+		if (windows[i].used && windows[i].term == t) {
+			*w = windows[i].pw - 2;
+			*h = SCREEN_ROWS * 10;
+			return 0;
+		}
+	return -1;
+}
+
 static int wm_point_in_rect(unsigned int px, unsigned int py,
 	unsigned int rx, unsigned int ry, unsigned int rw, unsigned int rh)
 {
@@ -152,6 +181,7 @@ static void wm_focus_top(void)
 static void wm_close_window(unsigned int idx)
 {
 	struct window *w = &windows[idx];
+	sys_gfx_kill_for_screen(&w->term->screen);   /* stop a running demo */
 	if (w->pid)
 		process_kill(w->pid);
 	w->used = 0;
@@ -251,37 +281,39 @@ static void wm_fill_rect_clip(unsigned int rx, unsigned int ry, unsigned int rw,
 		vga_fill_rect(x0, y0, x1 - x0, y1 - y0, r, g, b);
 }
 
-/* Redraw a rectangular region of the desktop (background + underlying windows,
-   excluding the window being dragged). Restores the exposed sliver. */
-static void wm_redraw_sliver(unsigned int x, unsigned int y, unsigned int w, unsigned int h)
+static void wm_draw_window_clip(struct window *w, unsigned int cx, unsigned int cy,
+				unsigned int cw, unsigned int ch);
+
+/* Repaint the desktop rectangle (x, y, w, h): background, then every
+   intersecting window back-to-front (focused last), then mark it dirty.  The
+   caller handles the mouse cursor.  The rect must lie below the system bar
+   (windows are clamped to y >= WM_BAR_H, so the bar is never overlapped and
+   needs no clip variant). */
+static void wm_redraw_rect(unsigned int x, unsigned int y,
+			   unsigned int w, unsigned int h)
 {
 	unsigned int i;
+
+	if (w == 0 || h == 0)
+		return;
 	vga_fill_rect(x, y, w, h, 32, 32, 48);
 	for (i = 0; i < MAX_WINDOWS; i++) {
 		struct window *w2 = &windows[i];
-		if (!w2->used || (int)i == drag_window)
-			continue;
-		if (!(x < w2->x + w2->pw && x + w > w2->x &&
-		      y < w2->y + w2->ph && y + h > w2->y))
-			continue;
 
-		/* Border. */
-		wm_fill_rect_clip(w2->x, w2->y, w2->pw, w2->ph,
-			x, y, w, h, 200, 200, 200);
-		/* Title bar. */
-		if (w2->focused)
-			wm_fill_rect_clip(w2->x + 1, w2->y + 1, w2->pw - 2, WM_TITLE_H,
-				x, y, w, h, 70, 90, 150);
-		else
-			wm_fill_rect_clip(w2->x + 1, w2->y + 1, w2->pw - 2, WM_TITLE_H,
-				x, y, w, h, 100, 100, 100);
-		/* Content background + cells. */
-		wm_fill_rect_clip(w2->x + 1, w2->y + 1 + WM_TITLE_H,
-			w2->pw - 2, SCREEN_ROWS * 10, x, y, w, h, 0, 0, 0);
-		fbtext_draw_cells_clip(w2->term->screen.cells,
-			w2->term->screen.cols, w2->term->screen.rows,
-			w2->x + 1, w2->y + 1 + WM_TITLE_H, x, y, w, h);
+		if (w2->used && !w2->focused &&
+		    x < w2->x + w2->pw && x + w > w2->x &&
+		    y < w2->y + w2->ph && y + h > w2->y)
+			wm_draw_window_clip(w2, x, y, w, h);
 	}
+	for (i = 0; i < MAX_WINDOWS; i++) {
+		struct window *w2 = &windows[i];
+
+		if (w2->used && w2->focused &&
+		    x < w2->x + w2->pw && x + w > w2->x &&
+		    y < w2->y + w2->ph && y + h > w2->y)
+			wm_draw_window_clip(w2, x, y, w, h);
+	}
+	vga_fb_mark_dirty_rect_xy(y, h, x, x + w);
 }
 
 /* Move a window in the shadow buffer: copy its rect, redraw the exposed
@@ -299,13 +331,13 @@ static void wm_drag_shadow(struct window *w, unsigned int ox, unsigned int oy,
 	wm_shadow_copy(ox, oy, nx, ny, w->pw, w->ph);
 
 	if (dy > 0)
-		wm_redraw_sliver(ox, oy, w->pw, (unsigned int)dy);
+		wm_redraw_rect(ox, oy, w->pw, (unsigned int)dy);
 	else if (dy < 0)
-		wm_redraw_sliver(ox, ny + w->ph, w->pw, (unsigned int)(-dy));
+		wm_redraw_rect(ox, ny + w->ph, w->pw, (unsigned int)(-dy));
 	if (dx > 0)
-		wm_redraw_sliver(ox, oy, (unsigned int)dx, w->ph);
+		wm_redraw_rect(ox, oy, (unsigned int)dx, w->ph);
 	else if (dx < 0)
-		wm_redraw_sliver(nx + w->pw, oy, (unsigned int)(-dx), w->ph);
+		wm_redraw_rect(nx + w->pw, oy, (unsigned int)(-dx), w->ph);
 
 	/* Mark the swept band so the flush copies the moved window + sliver.
 	   Limit the horizontal span to the window's swept x-range so the flush
@@ -408,7 +440,12 @@ static void wm_handle_keyboard(void)
 		kdbg_wm_count++;
 		kdbg_wm_last = (unsigned int)k;
 		handled = 1;
-		term_key_push(fw->term, k);
+		/* A graphics command owns its window's keys (ESC etc.);
+		 * Ctrl+C always reaches the terminal so its foreground kill
+		 * keeps working. */
+		if (k == IO_KEY_CTRL_C ||
+		    !sys_gfx_push_key(&fw->term->screen, k))
+			term_key_push(fw->term, k);
 	}
 	if (handled)
 		kdbg_status();
@@ -449,43 +486,62 @@ static void wm_draw_bar(void)
 	fbtext_draw_rainbow_separator();
 }
 
-static void wm_draw_window(struct window *w)
+/* Draw window w clipped to (cx, cy, cw, ch).  Chrome uses wm_fill_rect_clip,
+ * content the cells/canvas clip variants, so pixels outside the clip are
+ * untouched. */
+static void wm_draw_window_clip(struct window *w, unsigned int cx, unsigned int cy,
+				unsigned int cw, unsigned int ch)
 {
 	struct text_screen *s = &w->term->screen;
-	unsigned int cx = w->x + 1;
-	unsigned int cy = w->y + 1 + WM_TITLE_H;
+	struct gfx_canvas *g = sys_gfx_canvas_for(&w->term->screen);
+	unsigned int bx = w->x + w->pw - 1 - WM_CLOSE_W;
+	unsigned int cony = w->y + 1 + WM_TITLE_H;
 
 	/* Border. */
-	vga_fill_rect(w->x, w->y, w->pw, w->ph, 200, 200, 200);
+	wm_fill_rect_clip(w->x, w->y, w->pw, w->ph, cx, cy, cw, ch, 200, 200, 200);
 
 	/* Title bar. */
 	if (w->focused)
-		vga_fill_rect(cx, w->y + 1, w->pw - 2, WM_TITLE_H, 70, 90, 150);
+		wm_fill_rect_clip(w->x + 1, w->y + 1, w->pw - 2, WM_TITLE_H,
+			cx, cy, cw, ch, 70, 90, 150);
 	else
-		vga_fill_rect(cx, w->y + 1, w->pw - 2, WM_TITLE_H, 100, 100, 100);
+		wm_fill_rect_clip(w->x + 1, w->y + 1, w->pw - 2, WM_TITLE_H,
+			cx, cy, cw, ch, 100, 100, 100);
 
 	/* Title text. */
-	fbtext_draw_string_xy(w->x + 4, w->y + 3, w->title, 255, 255, 255, 1);
+	fbtext_draw_string_xy_clip(w->x + 4, w->y + 3, w->title, 255, 255, 255,
+		cx, cy, cw, ch);
 
 	/* Close button. */
-	{
-		unsigned int bx = w->x + w->pw - 1 - WM_CLOSE_W;
-		vga_fill_rect(bx, w->y + 1, WM_CLOSE_W, WM_TITLE_H, 190, 60, 60);
-		fbtext_draw_string_xy(bx + 3, w->y + 3, "x", 255, 255, 255, 1);
-	}
-
-	/* Content (black background) + cell buffer. */
-	vga_fill_rect(cx, cy, w->pw - 2, SCREEN_ROWS * 10, 0, 0, 0);
-	fbtext_draw_cells(s->cells, s->cols, s->rows, cx, cy);
+	wm_fill_rect_clip(bx, w->y + 1, WM_CLOSE_W, WM_TITLE_H,
+		cx, cy, cw, ch, 190, 60, 60);
+	fbtext_draw_string_xy_clip(bx + 3, w->y + 3, "x", 255, 255, 255,
+		cx, cy, cw, ch);
+
+	/* Content: text cells or the gfx canvas. */
+	wm_fill_rect_clip(w->x + 1, cony, w->pw - 2, SCREEN_ROWS * 10,
+		cx, cy, cw, ch, 0, 0, 0);
+	if (g)
+		gfx_blit_clip(g, w->x + 1, cony, cx, cy, cw, ch);
+	else
+		fbtext_draw_cells_clip(s->cells, s->cols, s->rows,
+			w->x + 1, cony, cx, cy, cw, ch);
 
-	/* Blinking block cursor for the focused window. */
-	if (w->focused && s->cursor_visible) {
+	/* Blinking block cursor (text windows only). */
+	if (!g && w->focused && s->cursor_visible) {
 		unsigned int col = s->cursor % s->cols;
 		unsigned int row = s->cursor / s->cols;
-		vga_fill_rect(cx + col * 8, cy + row * 10, 2, 10, 255, 255, 255);
+
+		wm_fill_rect_clip(w->x + 1 + col * 8, cony + row * 10, 2, 10,
+			cx, cy, cw, ch, 255, 255, 255);
 	}
 }
 
+static void wm_draw_window(struct window *w)
+{
+	wm_draw_window_clip(w, w->x, w->y, w->pw, w->ph);
+}
+
 static void wm_render_full(void)
 {
 	unsigned int fbw = vga_fb_width();
@@ -529,41 +585,61 @@ static void wm_redraw_if_needed(void)
 	static unsigned int last_kexec_tick;
 	unsigned int now_ms = get_ticks_ms();
 	unsigned int now_sec = now_ms / 1000;
-	int clock_changed = (now_sec != last_sec);
 	int kexec_changed = kexec_busy && (now_ms - last_kexec_tick >= 100);
-	int need_full = wm_full_redraw;
+	int bar_changed;
 
 	if (kexec_changed)
 		last_kexec_tick = now_ms;
+	bar_changed = (now_sec != last_sec) || kexec_changed;
 
-	/* A background window's content changed -> full redraw (rare). */
-	for (i = 0; i < MAX_WINDOWS; i++)
-		if (windows[i].used && !windows[i].focused && windows[i].term->screen.dirty)
-			need_full = 1;
+	if (wm_full_redraw) {
+		unsigned int seq_before[MAX_WINDOWS];
+
+		for (i = 0; i < MAX_WINDOWS; i++) {
+			struct gfx_canvas *g = windows[i].used ?
+				sys_gfx_canvas_for(&windows[i].term->screen) : 0;
 
-	if (need_full) {
+			seq_before[i] = g ? g->seq : 0;
+		}
 		wm_render_full();
 		for (i = 0; i < MAX_WINDOWS; i++)
-			if (windows[i].used)
+			if (windows[i].used) {
+				struct gfx_canvas *g = sys_gfx_canvas_for(&windows[i].term->screen);
+
 				windows[i].term->screen.dirty = 0;
+				if (g)
+					g->drawn = seq_before[i];   /* keep a frame
+						presented during the render */
+			}
 		wm_full_redraw = 0;
 		last_sec = now_sec;
 		return;
 	}
 
-	if (clock_changed || kexec_changed) {
+	if (bar_changed) {
 		wm_render_bar();
 		last_sec = now_sec;
 	}
 
-	/* Focused window's content changed -> redraw only that window. */
+	/* Any window whose content changed (focused or not): repaint just its
+	   content rect through the damage-rect compositor. */
 	for (i = 0; i < MAX_WINDOWS; i++) {
-		if (windows[i].used && windows[i].focused && windows[i].term->screen.dirty) {
-			mouse_cursor_erase();
-			wm_draw_window(&windows[i]);
-			mouse_redraw_cursor();
-			windows[i].term->screen.dirty = 0;
-		}
+		struct gfx_canvas *g;
+		unsigned int seq;
+
+		if (!windows[i].used)
+			continue;
+		g = sys_gfx_canvas_for(&windows[i].term->screen);
+		if (!windows[i].term->screen.dirty && !(g && g->seq != g->drawn))
+			continue;
+		seq = g ? g->seq : 0;   /* capture before compositing */
+		mouse_cursor_erase();
+		wm_redraw_rect(windows[i].x + 1, windows[i].y + 1 + WM_TITLE_H,
+			windows[i].pw - 2, SCREEN_ROWS * 10);
+		mouse_redraw_cursor();
+		windows[i].term->screen.dirty = 0;
+		if (g)
+			g->drawn = seq;
 	}
 }
 
@@ -589,6 +665,8 @@ static void wm_blink_cursor(void)
 
 	if (!fw || !fw->term)
 		return;
+	if (sys_gfx_canvas_for(&fw->term->screen))
+		return;   /* no text cursor over a graphics command */
 	if (now - last_cursor_tick >= CURSOR_MS) {
 		last_cursor_tick = now;
 		fw->term->screen.cursor_visible = !fw->term->screen.cursor_visible;
@@ -632,6 +710,7 @@ void wm_run(void)
 		wm_blink_cursor();
 		netlog_flush();
 		wm_handle_kexec();
+		sys_gfx_collect();
 		wm_redraw_if_needed();
 		vga_fb_flush_pending_check();
 		cpu_idle();

+ 7 - 0
wm.h

@@ -33,4 +33,11 @@ struct window *wm_focused_window(void);
 int  wm_is_focused(const struct window *w);
 void wm_request_redraw(void);
 
+/* The terminal whose screen is `screen`, or NULL (the sys_gfx service uses the
+ * inherited screen pointer to find a command's window). */
+struct term *wm_term_for_screen(struct text_screen *screen);
+
+/* Pixel size of a window's content area (its canvas size).  Returns 0/-1. */
+int wm_content_size(struct term *t, unsigned int *w, unsigned int *h);
+
 #endif