diff options
Diffstat (limited to 'src')
38 files changed, 177 insertions, 3840 deletions
@@ -1,7 +1,7 @@ //! The editor's 9P surface. The wire protocol, the client, the transports //! and the file-server engine (`cloud9.fs.Server`) live in cloud9; this -//! module names the two engine configurations Pardes builds, the editor's -//! and the board's, and re-exports what the transports and firmware use. +//! module names the engine configuration Pardes builds, the editor's, and +//! re-exports what the transports use. const cloud9 = @import("cloud9"); pub const fs = cloud9.fs; pub const Server = cloud9.fs.Server; @@ -44,12 +44,7 @@ pub const msize: u32 = 65536; pub const editor: cloud9.fs.Options = .{ .fid_capacity = max_fids, .name_capacity = 255, .park_data_max = msize - 23, .slot_capacity = max_held }; pub const max_held: usize = 128; -/// The board's engine: the GPIO firmware's budget (src/esp32p4_9p.zig). -pub const board: cloud9.fs.Options = .{ .fid_capacity = board_fids, .name_capacity = board_name_capacity }; - pub const max_fids: usize = 256; -pub const board_fids: usize = 32; -pub const board_name_capacity: usize = 28; const std = @import("std"); const testing = std.testing; @@ -67,19 +62,11 @@ test "9p server: the editor's engine can park the largest write a client sends" try testing.expect(editor.park_data_max >= client.maxWrite()); } -test "9p server: board and native capacities size the actual fid storage" { - const Board = Server(Stub, board); +test "9p server: the editor's capacities size the actual fid storage" { const Native = Server(Stub, editor); - const BoardFids = @FieldType(Board, "fids"); const NativeFids = @FieldType(Native, "fids"); - try testing.expectEqual(32, @typeInfo(BoardFids).array.len); try testing.expectEqual(256, @typeInfo(NativeFids).array.len); - try testing.expectEqual(28, @sizeOf(@FieldType(Board.Fid, "name"))); try testing.expectEqual(255, @sizeOf(@FieldType(Native.Fid, "name"))); - try testing.expectEqual(32 * @sizeOf(Board.Fid), @sizeOf(BoardFids)); try testing.expectEqual(256 * @sizeOf(Native.Fid), @sizeOf(NativeFids)); - try testing.expect(@sizeOf(BoardFids) <= 3 * 1024); - try testing.expect(@sizeOf(@FieldType(Board, "slots")) <= 8 * 1024); - try testing.expect(3 * 4096 + @sizeOf(Board) <= 24 * 1024); try testing.expect(min_msize >= msize_min); } diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index d90143c4..90b93efb 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +- The ESP32-P4 board port is gone: `-Dplatform=esp32p4` with its + `-Desp32p4-cols` and `-rows`, the `Peek`, `Poke`, `Hexdump` and `Gpio` + words, and every limit and guard only the board needed; the desktop + builds keep their capacities. - 9P over QUIC is gone: the `-Dquic` build with its OpenSSL, `quic!` dials for `--9p-quic` and Mount, the poll loop that served them on the editor's thread, and their tests. Unix and TCP serve and mount sessions diff --git a/src/File.zig b/src/File.zig index d1636852..94e211a1 100644 --- a/src/File.zig +++ b/src/File.zig @@ -1824,10 +1824,10 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. const tints: ?DiffTints = if ((algo == .diff or algo == .locations) and highlights.len > 0) DiffTints.of(p) else null; const row_tint = algo == .diff; var filtered_storage: terminal.FilteredColors = undefined; - const filtered: ?*terminal.FilteredColors = if (comptime terminal.enabled) (if (pane.tty_filter and spans.len > 0) blk: { + const filtered: ?*terminal.FilteredColors = if (pane.tty_filter and spans.len > 0) blk: { filtered_storage = .init(p, null); break :blk &filtered_storage; - } else null) else null; + } else null; // indexed start, same as bodyText — an empty tail simply paints nothing var flines = std.mem.splitScalar(u8, f.content[lineStart(p.gpa, f, f.scroll)..], '\n'); const total = nlines(p.gpa, f); diff --git a/src/Output.zig b/src/Output.zig index 3f869154..990032be 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -974,7 +974,7 @@ pub fn openConfig(p: *Pardes, id: usize) !void { var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); var dir_buf: [1024]u8 = undefined; - const host_fs = comptime (pardes.platform != .web and pardes.platform != .esp32p4); + const host_fs = comptime (pardes.platform != .web); var located: std.Io.Writer.Allocating = .init(p.gpa); defer located.deinit(); try p.locations_config.write(&located.writer); diff --git a/src/Pipe.zig b/src/Pipe.zig index c6e53162..276f9967 100644 --- a/src/Pipe.zig +++ b/src/Pipe.zig @@ -194,7 +194,7 @@ fn pipeFailed(p: *Pardes, wait: *const PendingPipe, failure: ?selection_pipe.Fai pub fn writeFailure(w: *std.Io.Writer, failure: ?selection_pipe.Failure) !void { const fail = failure orelse { // No diagnosis at all: nobody ran it. The detached daemon, the - // browser and the board all leave `pipe` null on purpose. + // browser leave `pipe` null on purpose. return w.writeAll("this session cannot run filters\n"); }; switch (fail.kind) { diff --git a/src/Places.zig b/src/Places.zig index 82595e2a..037b50be 100644 --- a/src/Places.zig +++ b/src/Places.zig @@ -49,7 +49,7 @@ pub const max_hits = 1 << 20; /// What one frame spends finding places: about 4 ms on the clock, checked /// between pieces of the text; mvzr's steps (Regex.budget is about 300 ms /// of them, so this is about 5 ms), which bound one slow piece; and bytes -/// read, the bound where there is no clock (the board, the web). +/// read, the bound where there is no clock (the web). pub const frame_ns: u64 = 4 * std.time.ns_per_ms; pub const frame_steps: u64 = regexp.Regex.budget / 64; pub const frame_bytes: usize = 8 << 20; diff --git a/src/Stream.zig b/src/Stream.zig index 8953e660..7f5e9162 100644 --- a/src/Stream.zig +++ b/src/Stream.zig @@ -13,7 +13,7 @@ //! //! Hosts with workers perform the `search` effect (host_io.Host.search): //! `start` runs `work` on io.concurrent, posting through the shell's -//! inbox. A host without (a test, a board) runs it on the loop (`runHere`), +//! inbox. A host without (a test) runs it on the loop (`runHere`), //! its cap a hard stop. const Stream = @This(); diff --git a/src/builtins.zig b/src/builtins.zig index d203cd9e..5dae567a 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -12,8 +12,6 @@ const Pane = pardes.Pane; const panes = @import("panes.zig"); const layout = @import("layout.zig"); const config = @import("config.zig"); -const builtin = @import("builtin"); -const Header = @import("esp32p4_gpio.zig").Header; const limits = @import("memory.zig").limits; /// What this build's own frontend draws and its host does: the render's. @@ -21,9 +19,8 @@ pub const frontend: config.Runtime.Capabilities = .{ .font_picker = pardes.font_picker, .panel_transitions = pardes.hosted, .scene_shaders = pardes.platform == .gui or pardes.platform == .macos, - // The tty's font belongs to its emulator, and the P4 firmware's belongs to - // whatever terminal is on the other end of the serial line. - .tagline_font_size = pardes.platform != .tui and pardes.platform != .esp32p4, + // The tty's font belongs to its emulator. + .tagline_font_size = pardes.platform != .tui, .window_opacity = pardes.platform == .gui or pardes.platform == .macos, .window_blur = pardes.platform == .macos, // Only the SDL shell shapes with HarfBuzz and honours the setting. macOS @@ -520,13 +517,6 @@ test "Ligatures is a setting only in the shell that shapes text" { try std.testing.expectEqual(!exists, std.mem.indexOf(u8, storage[0..out.end], "Ligatures unsupported\n") != null); } -comptime { - for ([_][]const u8{ "Peek", "Poke", "Hexdump" }) |name| - if (@hasField(registry.Builtin(), name) != Board.enabled) @compileError( - "bare-metal memory word gating leaked: " ++ name, - ); -} - // ---- the two acme verbs ---- /// Look at its argument: open the file or address it names, else find the word, as a right click does. @@ -2048,327 +2038,6 @@ pub const Lspwhy = struct { } }; -/// Read the board memory at an address, into a pane. -pub const Peek = struct { - pub const scope: Scope = .session; - pub const takes_arg = true; - pub const requires_arg = true; - pub const enabled = Board.enabled; - pub const output: OutputTraits = .{ .name = config.peek_buffer }; - pub fn run(c: Ctx) void { - Board.peek(c.p, c.id, c.arg orelse "") catch |err| - c.p.reportError(c.id, "peek", err); - } -}; - -/// Write a value to the board memory at an address. -pub const Poke = struct { - pub const scope: Scope = .session; - pub const takes_arg = true; - pub const requires_arg = true; - pub const enabled = Board.enabled; - pub fn run(c: Ctx) void { - Board.poke(c.p, c.id, c.arg orelse "") catch |err| - c.p.reportError(c.id, "poke", err); - } -}; - -/// Dump a range of the board memory in hex, into a pane. -pub const Hexdump = struct { - pub const scope: Scope = .session; - pub const takes_arg = true; - pub const requires_arg = true; - pub const enabled = Board.enabled; - pub const output: OutputTraits = .{ .name = config.hexdump_buffer }; - pub fn run(c: Ctx) void { - Board.hexdump(c.p, c.id, c.arg orelse "") catch |err| - c.p.reportError(c.id, "hexdump", err); - } -}; - -/// Read or set the board GPIO pins, into a pane. -pub const Gpio = struct { - pub const scope: Scope = .session; - pub const takes_arg = true; - pub const enabled = Board.enabled; - pub const output: OutputTraits = .{ .name = config.gpio_buffer }; - pub fn run(c: Ctx) void { - Board.gpio(c.p, c.id, c.arg orelse "") catch |err| - c.p.reportError(c.id, "gpio", err); - } -}; - -const Board = struct { - const enabled = pardes.platform == .esp32p4; - - comptime { - if (enabled and pardes.hosted) @compileError("an OS is not bare metal"); - if (enabled and builtin.os.tag != .freestanding) @compileError("the P4 firmware is freestanding"); - if (enabled and builtin.target.cpu.arch.isWasm()) @compileError("wasm addresses are not a bus"); - } - - // Bound output sent over the board's 115200-baud console. - const max_bytes: u32 = 4096; - const max_words: u32 = max_bytes / 4; - - const address_space_end: u64 = 1 << 32; - - const Error = error{ - MissingAddress, - BadAddress, - BadCount, - MissingValue, - BadValue, - MisalignedAddress, - ExtraArgument, - BadPin, - NoPads, - }; - - fn parseHex(comptime T: type, tok: []const u8, bad: Error) Error!T { - const body = if (tok.len > 2 and tok[0] == '0' and (tok[1] | 0x20) == 'x') tok[2..] else tok; - return std.fmt.parseInt(T, body, 16) catch bad; - } - - fn parseAddr(tok: []const u8) Error!u32 { - return parseHex(u32, tok, Error.BadAddress); - } - - fn parseCount(tok: []const u8) Error!u64 { - return parseHex(u64, tok, Error.BadCount); - } - - fn parseValue(tok: []const u8) Error!u32 { - return parseHex(u32, tok, Error.BadValue); - } - - // Callers reject unaligned words; volatile accesses must reach the device. - fn readWord(addr: u32) u32 { - const cell: *allowzero const volatile u32 = @ptrFromInt(@as(usize, addr)); - return cell.*; - } - - fn writeWord(addr: u32, value: u32) void { - const cell: *allowzero volatile u32 = @ptrFromInt(@as(usize, addr)); - cell.* = value; - } - - fn readByte(addr: u32) u8 { - const cell: *allowzero const volatile u8 = @ptrFromInt(@as(usize, addr)); - return cell.*; - } - - const Limit = enum { - console, - space, - }; - - const Extent = struct { - count: u32, - limit: ?Limit, - }; - - fn extent(addr: u32, requested: u64, unit: u32, cap: u32) Extent { - var count = requested; - var limit: ?Limit = null; - if (count > cap) { - count = cap; - limit = .console; - } - const fits = (address_space_end - addr) / unit; - if (count > fits) { - count = fits; - limit = .space; - } - return .{ .count = @intCast(count), .limit = limit }; - } - - fn writeNote(w: *std.Io.Writer, e: Extent, requested: u64, unit_name: []const u8) !void { - switch (e.limit orelse return) { - .console => try w.print( - "clamped: 0x{x} {s} requested, 0x{x} shown (0x{x}-byte cap, one 115200-baud console)\n", - .{ requested, unit_name, e.count, max_bytes }, - ), - .space => try w.print( - "clamped: 0x{x} {s} requested, 0x{x} shown (the 32-bit address space ends at 0x100000000)\n", - .{ requested, unit_name, e.count }, - ), - } - } - - fn peek(p: *Pardes, id: usize, argument: []const u8) !void { - var it = std.mem.tokenizeAny(u8, argument, " \t\r\n"); - const addr = try parseAddr(it.next() orelse return Error.MissingAddress); - const requested = if (it.next()) |tok| try parseCount(tok) else 0x1; - if (it.next() != null) return Error.ExtraArgument; - if (addr % 4 != 0) return Error.MisalignedAddress; - - const e = extent(addr, requested, 4, max_words); - var out: std.Io.Writer.Allocating = .init(p.gpa); - errdefer out.deinit(); - try writeNote(&out.writer, e, requested, "words"); - for (0..e.count) |i| { - const at = addr + @as(u32, @intCast(i * 4)); - try out.writer.print("{x:0>8}: {x:0>8}\n", .{ at, readWord(at) }); - } - const content = try out.toOwnedSlice(); - try fill(p, id, .{ .cmd = .Peek }, content); - } - - fn poke(p: *Pardes, id: usize, argument: []const u8) !void { - var it = std.mem.tokenizeAny(u8, argument, " \t\r\n"); - const addr = try parseAddr(it.next() orelse return Error.MissingAddress); - const value = try parseValue(it.next() orelse return Error.MissingValue); - if (it.next() != null) return Error.ExtraArgument; - if (addr % 4 != 0) return Error.MisalignedAddress; - - writeWord(addr, value); - const back = readWord(addr); - var buf: [96]u8 = undefined; - // unreachable below: three 8-digit hex words and 18 bytes fit 96 - p.setMessage(id, std.fmt.bufPrint( - &buf, - "{x:0>8}: wrote {x:0>8}, reads {x:0>8}", - .{ addr, value, back }, - ) catch unreachable); - } - - fn gpio(p: *Pardes, id: usize, argument: []const u8) !void { - var it = std.mem.tokenizeAny(u8, argument, " \t\r\n"); - const tok = it.next() orelse { - const content = try p.gpa.dupe(u8, Header.text); - return fill(p, id, .{ .cmd = .Gpio }, content); - }; - if (it.next() != null) return Error.ExtraArgument; - const pin = std.fmt.parseInt(u16, tok, 10) catch return Error.BadPin; - - const toggle = p.host.vtable.gpio_toggle orelse return Error.NoPads; - var was: u8 = 0; - var now: u8 = 0; - if (!toggle(p.host.ctx, pin, &was, &now)) return Error.BadPin; - - var buf: [48]u8 = undefined; - // unreachable: three small numbers and 10 bytes fit 48 - p.setMessage(id, std.fmt.bufPrint(&buf, "GPIO {d}: {d}->{d}", .{ pin, was, now }) catch unreachable); - } - - const row_bytes: u32 = limits.hexdump_row_bytes; - - fn hexdump(p: *Pardes, id: usize, argument: []const u8) !void { - var it = std.mem.tokenizeAny(u8, argument, " \t\r\n"); - const addr = try parseAddr(it.next() orelse return Error.MissingAddress); - const requested = if (it.next()) |tok| try parseCount(tok) else 0x100; - if (it.next() != null) return Error.ExtraArgument; - - const e = extent(addr, requested, 1, max_bytes); - var out: std.Io.Writer.Allocating = .init(p.gpa); - errdefer out.deinit(); - try writeNote(&out.writer, e, requested, "bytes"); - var row: u32 = 0; - while (row < e.count) : (row += row_bytes) { - const n = @min(row_bytes, e.count - row); - var bytes: [row_bytes]u8 = undefined; - for (0..n) |i| bytes[i] = readByte(addr + row + @as(u32, @intCast(i))); - try out.writer.print("{x:0>8} ", .{addr + row}); - for (0..row_bytes) |i| { - if (i == row_bytes / 2) try out.writer.writeByte(' '); - if (i < n) - try out.writer.print(" {x:0>2}", .{bytes[i]}) - else - try out.writer.writeAll(" "); - } - try out.writer.writeAll(" |"); - for (0..n) |i| try out.writer.writeByte( - if (bytes[i] >= 0x20 and bytes[i] < 0x7f) bytes[i] else '.', - ); - try out.writer.writeAll("|\n"); - } - const content = try out.toOwnedSlice(); - try fill(p, id, .{ .cmd = .Hexdump }, content); - } - - fn fill(p: *Pardes, id: usize, from: panes.Output.Origin, content: []u8) !void { - const pane = p.panes[id] orelse { - p.gpa.free(content); - return error.MissingPane; - }; - const dir = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice(); - try panes.Output.fillResults(p, id, dir, from, "", content, null); - } - - test "the clamp reports the tighter bound and never wraps the address space" { - const eq = std.testing.expectEqual; - try eq(Extent{ .count = 3, .limit = null }, extent(0x4ff40000, 3, 4, max_words)); - try eq(Extent{ .count = max_words, .limit = .console }, extent(0x4ff40000, 99_999, 4, max_words)); - try eq(Extent{ .count = max_bytes, .limit = .console }, extent(0, 100_000, 1, max_bytes)); - try eq(Extent{ .count = 16, .limit = .space }, extent(0xfffffff0, 64, 1, max_bytes)); - try eq(Extent{ .count = 4, .limit = .space }, extent(0xfffffff0, 64, 4, max_words)); - try eq(Extent{ .count = 0, .limit = .space }, extent(0xffffffff, 1, 4, max_words)); - try eq(Extent{ .count = max_bytes, .limit = .console }, extent(0xffff0000, 1 << 20, 1, max_bytes)); - } - - test "a clamp note is written exactly when something was clamped" { - var buf: [256]u8 = undefined; - var w: std.Io.Writer = .fixed(&buf); - - try writeNote(&w, extent(0x4ff40000, 3, 4, max_words), 3, "words"); - try std.testing.expectEqualStrings("", w.buffered()); - - try writeNote(&w, extent(0x4ff40000, 99_999, 4, max_words), 99_999, "words"); - try std.testing.expectEqualStrings( - "clamped: 0x1869f words requested, 0x400 shown (0x1000-byte cap, one 115200-baud console)\n", - w.buffered(), - ); - - w = .fixed(&buf); - try writeNote(&w, extent(0xfffffff0, 64, 1, max_bytes), 64, "bytes"); - try std.testing.expectEqualStrings( - "clamped: 0x40 bytes requested, 0x10 shown (the 32-bit address space ends at 0x100000000)\n", - w.buffered(), - ); - } - - test "every literal is hex, with or without the prefix" { - const eq = std.testing.expectEqual; - try eq(0x4ff40000, parseAddr("0x4ff40000")); - try eq(0x4ff40000, parseAddr("4ff40000")); - try eq(0x4ff40000, parseAddr("0X4FF40000")); - try eq(0x4ff40000, parseAddr("4FF40000")); - try eq(0x100, parseCount("100")); - try eq(0x256, parseCount("256")); - try eq(0xdeadbeef, parseValue("deadbeef")); - try std.testing.expectError(Error.BadAddress, parseAddr("0x100000000")); - try std.testing.expectError(Error.BadAddress, parseAddr("0x")); - try std.testing.expectError(Error.BadAddress, parseAddr("nope")); - try std.testing.expectError(Error.BadAddress, parseAddr("12g4")); - try std.testing.expectError(Error.BadCount, parseCount("-1")); - try std.testing.expectError(Error.BadValue, parseValue("0x1_0000_0000")); - } - - test "the pinout fits the board's own grid, in two aligned columns" { - const cols: usize = @import("pardes_config").esp32p4_cols; - const usable = cols - 7; - - var rows: usize = 0; - var pins: usize = 0; - var first_bar: ?usize = null; - var it = std.mem.splitScalar(u8, Header.text, '\n'); - while (it.next()) |line| { - try std.testing.expect(line.len <= usable); - rows += 1; - const bar = std.mem.indexOfScalar(u8, line, '|') orelse continue; - if (line[line.len - 1] == '+') continue; - pins += 1; - if (first_bar) |b| try std.testing.expectEqual(b, bar) else first_bar = bar; - } - try std.testing.expectEqual(@as(usize, 13), pins); - try std.testing.expect(rows > 15); - - try std.testing.expect(std.mem.indexOf(u8, Header.text, "GPIO 20 | 17 |") != null); - try std.testing.expect(std.mem.indexOf(u8, Header.text, "| 8 | --") != null); - } -}; - test "Exit and Restore name a modified +New scratch as well as files" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); diff --git a/src/colors.zig b/src/colors.zig index fc288194..47af08b4 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -670,7 +670,7 @@ pub const ChromeTheme = struct { /// fade keeps its lightness even, never going muddy or dark between two /// hues as a mix of sRGB bytes does). A change eases in and out (§8.1); one /// set off partway through another eases out, moving at once, so it never -/// stalls (§7.2). A build without theme_animation (the board) snaps instead +/// stalls (§7.2). A build without theme_animation snaps instead /// (finishThemeInitialization). pub const ChromeAnimation = struct { from: ChromeTheme, diff --git a/src/config.zig b/src/config.zig index 0227f898..f84f438c 100644 --- a/src/config.zig +++ b/src/config.zig @@ -214,12 +214,6 @@ pub const leader_path = paths: { table.set(.Adopt, null); table.set(.Upgrade, "sU"); } - if (builtins.Peek.enabled) { - table.set(.Peek, null); - table.set(.Poke, null); - table.set(.Hexdump, null); - table.set(.Gpio, null); - } if (pardes.pdf_enabled) { table.set(.PdfTint, "ti"); table.set(.PdfSections, "ts"); @@ -565,9 +559,6 @@ pub const hover_buffer = "+Hover"; pub const lsp_buffer = "+Lsp"; pub const changelog_buffer = "+Changelog"; pub const messages_buffer = "+Messages"; -pub const peek_buffer = "+Peek"; -pub const hexdump_buffer = "+Hexdump"; -pub const gpio_buffer = "+Gpio"; pub const scratch_buffer = "+New"; pub const errors_buffer = "+Errors"; diff --git a/src/draw.zig b/src/draw.zig index 96a12145..e28c9f9d 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -486,10 +486,10 @@ fn resolved(color: Color, default: ?[3]u8, palette: ?[16][3]u8) ?[3]u8 { .rgb => |rgb| rgb, .default => default, // A theme's own sixteen, as the painters give them (Terminal.palColor). - .index => |index| if (palette != null and index < 16) palette.?[index] else if (comptime pardes.terminal_panes) blk: { + .index => |index| if (palette != null and index < 16) palette.?[index] else blk: { const rgb = @import("ghostty-vt").color.default[index]; break :blk .{ rgb.r, rgb.g, rgb.b }; - } else null, + }, }; } @@ -2042,7 +2042,7 @@ test "the focused cursor glides a jump, eases a step, the thin caret too, and is } test "a terminal's cursor lands with scrolling output, never gliding against it" { - if (!builtins.frontend.lift or !pardes.terminal_panes) return error.SkipZigTest; + if (!builtins.frontend.lift) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 12 }); defer p.deinit(); while (p.nextEffect()) |_| {} diff --git a/src/dump.zig b/src/dump.zig index 153e4a82..6bdfb7d4 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -13,7 +13,6 @@ const config = @import("config.zig"); const pdf_enabled = pardes.pdf_enabled; const platform = pardes.platform; const isolated = pardes.isolated; -const terminal_panes = pardes.terminal_panes; const MAX_PANES = pardes.MAX_PANES; const MAX_COLS = pardes.MAX_COLS; const effect_path_cap = pardes.effect_path_cap; @@ -73,7 +72,7 @@ test "two dumps in one second get names of their own" { try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "pardes-x.dump", .data = "" }); try std.testing.expect(std.mem.endsWith(u8, uniqueIn(&buf, dir, "pardes-x").?, "/pardes-x-2.dump")); } -/// The host's environment; a freestanding core (web, the board) has none +/// The host's environment; a freestanding core (the web's) has none /// and no libc to ask, so only a DumpDir with no `~/` names a directory there. fn hostEnv(name: [*:0]const u8) ?[*:0]u8 { if (builtin.os.tag == .freestanding) return null; @@ -91,7 +90,7 @@ pub fn directory(buf: []u8, dir_setting: []const u8) ?[]const u8 { var fba_buf: [4096]u8 = undefined; var fba = std.heap.FixedBufferAllocator.init(&fba_buf); var cwd_buf: [1024]u8 = undefined; - // No libc on the web or the board: there a relative one is from `/`. + // No libc on the web: there a relative one is from `/`. const cwd: []const u8 = if (comptime !pardes.hosted) "/" else if (std.fs.path.isAbsolute(raw)) "/" else if (std.c.getcwd(&cwd_buf, cwd_buf.len)) |c| std.mem.span(@as([*:0]const u8, @ptrCast(c))) else "/"; const resolved = std.fs.path.resolvePosix(fba.allocator(), &.{ cwd, raw }) catch return null; return std.fmt.bufPrint(buf, "{s}", .{resolved}) catch null; @@ -471,7 +470,7 @@ fn revivePane(p: *Pardes, id: usize, pane: *pardes.panes.Pane, was_on_disk: bool pane.command_done = true; return; } - if (comptime !(terminal_panes and platform != .web and !isolated)) return; + if (comptime platform == .web or isolated) return; if (pane.cwdSlice().len > effect_path_cap) return; pardes.panes.terminal.reviveShell(pane); p.emitSpawn(id, pane.serial, pane.cwdSlice()); @@ -663,7 +662,7 @@ test "a pane restored with unsaved text is asked about by Exit, Restore, Del and } test "a loaded terminal's history stays above its banner, the cursor where it was" { - if (comptime !pardes.panes.terminal.enabled or isolated) return error.SkipZigTest; + if (comptime isolated) return error.SkipZigTest; const gpa = std.testing.allocator; const term = pardes.panes.terminal; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); @@ -684,7 +683,7 @@ test "a loaded terminal's history stays above its banner, the cursor where it wa } test "an upgraded session's dump keeps its views and its running terminal as they were, and settings the startup config would change" { - if (comptime !pardes.panes.terminal.enabled or isolated) return error.SkipZigTest; + if (comptime isolated) return error.SkipZigTest; const gpa = std.testing.allocator; const term = pardes.panes.terminal; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12, .startup_config = "Verbose off\n" }); diff --git a/src/echo.zig b/src/echo.zig index e25953e0..e98aff49 100644 --- a/src/echo.zig +++ b/src/echo.zig @@ -149,7 +149,7 @@ pub const Echo = struct { /// it was applied here at once (so it was no key into a terminal). pub fn typed(e: *Echo, c: *Pardes, view: u8, ev: pardes.Event, seq: u32, applied: bool) void { e.view = view; - if (applied or comptime !terminal.enabled) return; + if (applied) return; switch (ev) { // ponytail: a motion or focus report a program asked for could // move its cursor; the judgement catches that. @@ -310,7 +310,6 @@ pub const Echo = struct { } fn screenCell(e: *const Echo, state: *terminal.State, x: u16, row: u64) ?terminal.PageCell { - if (comptime !terminal.enabled) return null; const top = e.tops[e.pane]; if (row < top or row - top >= state.vt.rows) return null; return state.vt.screens.active.pages.getCell(.{ .active = .{ .x = x, .y = @intCast(row - top) } }); @@ -379,7 +378,6 @@ pub const Echo = struct { } fn judge(e: *Echo, c: *Pardes, slack: u64) void { - if (comptime !terminal.enabled) return; if (e.n == 0 and e.cursor == null) return; const now = e.time(); const pane = c.panes[e.pane] orelse return e.drop(); @@ -446,7 +444,6 @@ pub const Echo = struct { /// Over terminal pane `id`'s body, as renderBody drew it: the /// characters predicted and the cursor after them. pub fn paint(e: *const Echo, p: *const Pardes, s: *Surface, pane: *const Pane, id: usize, tx: u16, tw: u16, body_y: u16, body_h: u16, active: bool) void { - if (comptime !terminal.enabled) return; if (e.n == 0 and e.cursor == null) return; if (id != e.pane or pane.serial != e.serial or p.view != e.view or pane.body.mode != .tty) return; if (!e.visible(p)) return; @@ -534,7 +531,6 @@ fn blank(cp: u21) bool { /// since) and the cursor's own, on the primary screen. A shell without /// pardes's marks is trusted only once its echo is confirmed. fn atPrompt(pane: *const Pane) bool { - if (comptime !terminal.enabled) return false; const state = pane.terminal orelse return false; return state.vt.screens.active_key == .primary and state.stream.handler.phase == .input and terminal.promptInputReady(pane); } @@ -655,7 +651,6 @@ const Rig = struct { const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; test "keys typed at a shell's prompt are drawn at once, and the authority's echo takes their place" { - if (comptime !terminal.enabled) return error.SkipZigTest; var g: Rig = undefined; try g.init(); defer g.deinit(); @@ -703,7 +698,6 @@ test "keys typed at a shell's prompt are drawn at once, and the authority's echo } test "a password prompt shows nothing typed, and a full-screen program is not predicted" { - if (comptime !terminal.enabled) return error.SkipZigTest; var g: Rig = undefined; try g.init(); defer g.deinit(); @@ -735,7 +729,6 @@ test "a password prompt shows nothing typed, and a full-screen program is not pr } test "keys still on their way when their predictions go: the next waits for their echo, never predicted where it is about to land" { - if (comptime !terminal.enabled) return error.SkipZigTest; var g: Rig = undefined; try g.init(); defer g.deinit(); @@ -773,7 +766,6 @@ test "keys still on their way when their predictions go: the next waits for thei } test "a misprediction takes every prediction back and shows none until an echo is confirmed; after Tab nothing is predicted until its echo" { - if (comptime !terminal.enabled) return error.SkipZigTest; var g: Rig = undefined; try g.init(); defer g.deinit(); diff --git a/src/edit.zig b/src/edit.zig index c20eac04..99c6d306 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -2208,7 +2208,6 @@ test "a typed edit's known end is where the texts' comparison would find it" { } test "a paste into a terminal is xterm's: bracketed when the program asked, control bytes spaces, so no ESC[201~ ends the brackets early" { - if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); defer p.deinit(); diff --git a/src/effect_sources.zig b/src/effect_sources.zig index 36d62774..02d1f87d 100644 --- a/src/effect_sources.zig +++ b/src/effect_sources.zig @@ -44,7 +44,7 @@ pub const files = switch (backend) { .{ .path = "src/macos/Sources/ScenePostprocessor.swift", .contents = @embedFile("macos/Sources/ScenePostprocessor.swift") }, .{ .path = "shaders/crt.ci.metal", .contents = @embedFile("effect-source-crt.ci.metal") }, }, - .web, .esp32p4 => [_]filesystem.Source{}, + .web => [_]filesystem.Source{}, }; pub fn forSetting(setting: config.Runtime.Setting) ?[]const []const u8 { @@ -53,7 +53,7 @@ pub fn forSetting(setting: config.Runtime.Setting) ?[]const []const u8 { .tui => &.{ "src/layout.zig", "src/pardes.zig", "src/tui/panel_compositor.zig" }, .gui => &.{ "src/layout.zig", "src/pardes.zig", "src/gui/gui.zig", ui_vertex_path, ui_fragment_path, image_vertex_path, image_fragment_path }, .macos => &.{ "src/layout.zig", "src/pardes.zig", "src/macos/Sources/PardesView.swift", "src/macos/Sources/ScenePostprocessor.swift", "shaders/crt.ci.metal" }, - .web, .esp32p4 => null, + .web => null, }, .scene => |effect| switch (backend) { .gui => switch (effect) { @@ -63,7 +63,7 @@ pub fn forSetting(setting: config.Runtime.Setting) ?[]const []const u8 { .grain => &.{ "src/gui/Post.zig", "src/gui/gui.zig", post_vertex_path, post_grain_path }, }, .macos => &.{ "src/macos/Sources/PardesView.swift", "src/macos/Sources/ScenePostprocessor.swift", "shaders/crt.ci.metal" }, - .tui, .web, .esp32p4 => null, + .tui, .web => null, }, else => null, }; diff --git a/src/esp32p4.zig b/src/esp32p4.zig deleted file mode 100644 index 074ca6b3..00000000 --- a/src/esp32p4.zig +++ /dev/null @@ -1,1007 +0,0 @@ -//! The ESP32-P4 firmware shell: pardes as one freestanding object, bytes in and bytes out. -//! -//! `zig build -Dplatform=esp32p4` emits this file as a single object exporting the C -//! ABI below; the sibling `05-zig-p4` toolchain links it beside `_start`, its generated linker script, -//! and its UART driver. Nothing here knows what a UART is. -//! -//! **Why an object and not a module.** The obvious arrangement was for zig-p4 to declare this -//! package in its `build.zig.zon` and import `pardes_p4`. That was built, and it broke every build -//! in that repo: nesting this package's ~30-package graph under one whose own claim is "host -//! dependencies: Zig, that is the whole list" made `std/Build.zig:2091` exceed its 1000-branch -//! comptime quota (through ghostty's `SharedDeps.zig:874` `lazyImport`), dragged in seven cached -//! tree-sitter versions whose `build.zig` uses APIs removed in 0.16, and materialised 2.6 GB across -//! 42,736 files into that repo's working copy. A linked object has none of those properties and one -//! extra virtue: the seam is bytes, so neither side can accidentally depend on the other's types. -//! -//! **Where the terminal is.** On the host. The board writes ANSI and reads ANSI; the terminal -//! emulator at the far end of the serial line does the font rendering, and answers this program's -//! own capability queries. That is why `vaxis` works here unmodified: `Vaxis.render`, -//! `queryTerminalSend` and `enableDetectedFeatures` all take a bare `*std.Io.Writer` -//! (`Vaxis.zig:375,278,329`), so the transport is a parameter. `vaxis.Tty` and `vaxis.Loop` are -//! termios/ioctl/SIGWINCH bound and are not used. -//! -//! **Where the memory is.** Not here either. The firmware measured its own RAM (240 KiB low, -//! 384 KiB high, and a 128 KiB region that turned out to be L2 cache) and owns the allocator; this -//! file receives four function pointers and rebuilds a `std.mem.Allocator` from them. Everything -//! the editor allocates comes from there. -//! -//! **Window size** arrives as DEC mode 2048 in-band resize reports, parsed by `vaxis.Parser` like -//! any other input. Firmware has no `TIOCGWINSZ`, so the host-side bridge synthesises the first one. - -const std = @import("std"); -const builtin = @import("builtin"); -const pardes = @import("pardes.zig"); -const vaxis = @import("vaxis"); -const vaxis_input = @import("vaxis_input.zig"); - -// ------------------------------------------------------------------ what a freestanding root owes -// -// These are ROOT-module declarations: std reads them off whichever file is the compilation root, and -// as of the build change that emits this file as the object, that is this file. They are not -// ceremony - each one was discovered by the build failing without it. - -/// The board has no MMU and no pages, but std derives allocator alignment from these two. 4 KiB is -/// the ESP32-P4's cache and DMA granularity. Without them: "riscv32-freestanding has unknown -/// page_size_min" from std/heap.zig:48. -/// -/// `logFn` is the load-bearing one. std's DEFAULT log implementation reaches `std.debug_io`, which -/// instantiates `std.Io.Threaded` - a thread pool, `getrandom`, `IOV_MAX`, `mremap` - none of which -/// exist on this target, and ONE `log.warn` anywhere in the core or in vaxis is enough to drag the -/// whole thing in and fail the build with "no member named 'getrandom'". -pub const std_options: std.Options = .{ - .page_size_min = 4096, - .page_size_max = 4096, - .logFn = logFn, -}; - -/// Logs go out the same byte sink as the frames, which is the only sink there is. Truncated rather -/// than allocated: a log line is never worth an allocation on a 384 KiB heap, and a logger that can -/// fail on OOM is a logger that disappears exactly when it is needed. -fn logFn( - comptime level: std.log.Level, - comptime scope: @EnumLiteral(), - comptime fmt: []const u8, - args: anytype, -) void { - if (out_ctx == null and @intFromPtr(out_write) == 0) return; - var buf: [256]u8 = undefined; - const line = std.fmt.bufPrint( - &buf, - "\r\n[" ++ level.asText() ++ "/" ++ @tagName(scope) ++ "] " ++ fmt ++ "\r\n", - args, - ) catch "\r\n[log truncated]\r\n"; - out_write(out_ctx, line.ptr, line.len); -} - -pub const panic = std.debug.FullPanic(panicImpl); - -/// A panic here cannot unwind and has nowhere to go, so it reports through the write callback and -/// stops. `@trap` and not a spin: the firmware's own panic handler prints through the mask ROM, -/// which shares nothing with this path but the FIFO, so a trap leaves that diagnostic route intact. -fn panicImpl(msg: []const u8, _: ?usize) noreturn { - const prefix = "\r\nMARK PARDES_CORE_PANIC "; - out_write(out_ctx, prefix.ptr, prefix.len); - out_write(out_ctx, msg.ptr, msg.len); - out_write(out_ctx, "\r\n", 2); - @trap(); -} - -// ---------------------------------------------------------------------------------- the C ABI -// -// Deliberately tiny, and versioned. Linkers do not type-check C symbols, so a signature that drifts -// on one side of this seam links cleanly and then corrupts the stack. `pardes_esp32p4_abi_version` is the -// cheapest possible defence: the firmware calls it first and refuses to continue on a mismatch. - -/// Bumped whenever any signature below changes, including a type. -/// 2 added `GpioFn` to `pardes_esp32p4_init`. A firmware built against 1 passes five arguments where six -/// are read, which is exactly the silent-corruption case this counter exists to turn into a message. -const abi_version: u32 = 2; - -export fn pardes_esp32p4_abi_version() callconv(.c) u32 { - return abi_version; -} - -/// The firmware's allocator, as C function pointers. `alignment` is a log2 value, matching -/// `std.mem.Alignment`'s own representation, so no translation table is needed. -/// -/// `remap` is absent on purpose: this allocator cannot move a block without copying it, so -/// `std.mem.Allocator`'s remap is implemented locally as "resize in place, or fail" and the caller's -/// own alloc/copy/free path handles the rest. -pub const Allocator = extern struct { - ctx: ?*anyopaque, - alloc: *const fn (ctx: ?*anyopaque, len: usize, log2_align: u8) callconv(.c) ?[*]u8, - resize: *const fn (ctx: ?*anyopaque, ptr: [*]u8, len: usize, log2_align: u8, new_len: usize) callconv(.c) bool, - free: *const fn (ctx: ?*anyopaque, ptr: [*]u8, len: usize, log2_align: u8) callconv(.c) void, -}; - -/// How finished runs of ANSI leave this object. -pub const WriteFn = *const fn (ctx: ?*anyopaque, ptr: [*]const u8, len: usize) callconv(.c) void; - -/// Flip one pad and report the level before and after; false if the firmware declines. OPTIONAL on -/// the wire, so a host with no pads (or one that has not implemented them yet) passes null and the -/// `Gpio` word answers "no pads" instead of the object having to know which firmwares exist. -/// -/// The board's side, not the editor's, because a correct toggle is the IO MUX, the GPIO matrix, the -/// pad's own bits and the output enable - four register files behind a per-pin table that the -/// firmware already has and checks against ESP-IDF. See `Host.VTable.gpio_toggle`. -pub const GpioFn = *const fn (ctx: ?*anyopaque, pin: u16, was: *u8, now: *u8) callconv(.c) bool; - -// ------------------------------------------------------------------- the allocator, rebuilt -// One `std.mem.Allocator` whose vtable forwards to the four pointers above. The indirection is the -// price of the seam and it is paid once per allocation, which on a first-fit heap is already the -// cheap part (measured on the die: 8,229 cycles for one allocation across 257 free blocks). - -var host_alloc: Allocator = undefined; - -fn hostAlloc(_: *anyopaque, len: usize, alignment: std.mem.Alignment, _: usize) ?[*]u8 { - return host_alloc.alloc(host_alloc.ctx, len, @backingInt(alignment)); -} - -fn hostResize(_: *anyopaque, mem: []u8, alignment: std.mem.Alignment, new_len: usize, _: usize) bool { - return host_alloc.resize(host_alloc.ctx, mem.ptr, mem.len, @backingInt(alignment), new_len); -} - -fn hostRemap(_: *anyopaque, mem: []u8, alignment: std.mem.Alignment, new_len: usize, _: usize) ?[*]u8 { - return if (host_alloc.resize(host_alloc.ctx, mem.ptr, mem.len, @backingInt(alignment), new_len)) mem.ptr else null; -} - -fn hostFree(_: *anyopaque, mem: []u8, alignment: std.mem.Alignment, _: usize) void { - host_alloc.free(host_alloc.ctx, mem.ptr, mem.len, @backingInt(alignment)); -} - -const host_vtable: std.mem.Allocator.VTable = .{ - .alloc = hostAlloc, - .resize = hostResize, - .remap = hostRemap, - .free = hostFree, -}; - -/// `ptr` is never dereferenced - the four forwarders read the file-scope `host_alloc` - but -/// `std.mem.Allocator` requires a non-null context, so it points at the record itself. -fn gpa() std.mem.Allocator { - return .{ .ptr = @ptrCast(&host_alloc), .vtable = &host_vtable }; -} - -// ------------------------------------------------------------------------------- the ANSI sink -// A `std.Io.Writer` over the firmware's write callback. Buffered, because vaxis emits a frame as a -// long run of small writes - cursor move, SGR run, grapheme, repeat - and an unbuffered writer would -// make a C call per fragment. - -var out_write: WriteFn = undefined; -var out_ctx: ?*anyopaque = null; -var host_gpio: ?GpioFn = null; -var out_buf: [8192]u8 = undefined; -var out: std.Io.Writer = undefined; - -fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { - // The shape std documents at Io/Writer.zig:46-63: buffer first, then every slice of `data`, with - // the LAST slice repeated `splat` times, and the count returned excluding the buffered bytes. - if (w.end > 0) { - out_write(out_ctx, w.buffer.ptr, w.end); - w.end = 0; - } - const head = data[0 .. data.len - 1]; - const pattern = data[head.len]; - var written: usize = 0; - for (head) |bytes| { - if (bytes.len > 0) out_write(out_ctx, bytes.ptr, bytes.len); - written += bytes.len; - } - var i: usize = 0; - while (i < splat) : (i += 1) { - if (pattern.len > 0) out_write(out_ctx, pattern.ptr, pattern.len); - } - return written + pattern.len * splat; -} - -// ------------------------------------------------------------------------------------ the state - -var core: ?*pardes.Pardes = null; -var vx: vaxis.Vaxis = undefined; -var parser: vaxis.Parser = .{}; - -/// vaxis wants an environment map. There is no environment; an empty one is the honest answer and -/// the only thing vaxis reads it for is TERM-derived heuristics, which the capability queries -/// supersede. -var env_map: std.process.Environ.Map = undefined; - -/// Input that arrived mid-sequence. An escape sequence can be split across UART reads, and the -/// parser reports "incomplete" by consuming nothing, so the tail has to survive until more arrives. -var in_buf: [1024]u8 = undefined; -var in_len: usize = 0; - -/// Bracketed paste: between the markers, keys are DATA and never commands. -var paste_buf: std.ArrayListUnmanaged(u8) = .empty; -var in_paste: bool = false; - -/// Set by anything that could change the screen; cleared by a render. The firmware asks before -/// rendering, because on a 115200-baud link an unconditional repaint per loop saturates the wire and -/// starves input. -var dirty: bool = true; - -/// The largest grid this board can render, and the reason it is not just the host's terminal size. -/// -/// A cell is paid for TWICE now, not four times: pardes keeps its `Surface` and this shell keeps a -/// shadow copy of it to diff against. vaxis used to keep a `Screen` and an `InternalScreen` as well, -/// and with `direct_emit` neither is ever read - the emitter diffs against the Surface and writes -/// the wire itself - so `init` sizes vaxis to a single cell and those two grids cost nothing. -/// -/// Set with `-Desp32p4-cols` / `-Desp32p4-rows`, because the ceiling is a measurement rather than a constant -/// and it moves for two independent reasons: the 384 KiB heap, and the round trip, which grows with -/// the cell count because every frame walks the whole grid. See the geometry table in -/// `05-zig-p4/experiments/report.typ` for both curves. -/// -/// Raising these further is what PSRAM would buy: this board has 32 MB fitted and untrained. -pub const max_cols: u16 = @import("pardes_config").esp32p4_cols; -pub const max_rows: u16 = @import("pardes_config").esp32p4_rows; - -var cur_winsize: vaxis.Winsize = .{ .rows = max_rows, .cols = max_cols, .x_pixel = 0, .y_pixel = 0 }; - -/// How big vaxis's own grids need to be. -/// -/// ONE CELL under `direct_emit`, because neither of them is ever read: vaxis keeps a `Screen` and an -/// `InternalScreen`, and the emitter diffs the Surface against its own shadow and writes the escapes -/// itself. Those two grids were the largest single claim on a 384 KiB heap and the reason the board -/// was held to 40x12 - the comment above `max_cols` used to say a cell was paid for four times over, -/// and this is what took it down to two. vaxis is still doing the work only it can do here: entering -/// the alternate screen, asking the terminal what it is, and parsing everything that comes back. -fn vaxisSize() vaxis.Winsize { - return if (direct_emit) - .{ .rows = 1, .cols = 1, .x_pixel = 0, .y_pixel = 0 } - else - cur_winsize; -} - -// -------------------------------------------------------------------------------------- exports - -/// Hand over the allocator and the output sink, state the initial window size, and bring the editor -/// up. Returns 0, or a small non-zero code the firmware can only report. -export fn pardes_esp32p4_init( - alloc: *const Allocator, - write: WriteFn, - gpio: ?GpioFn, - ctx: ?*anyopaque, - cols: u16, - rows: u16, -) callconv(.c) u32 { - host_alloc = alloc.*; - out_write = write; - host_gpio = gpio; - out_ctx = ctx; - out = .{ .vtable = &.{ .drain = drain }, .buffer = &out_buf }; - - const a = gpa(); - env_map = .{ .array_hash_map = .empty, .allocator = a }; - // Clamped, so a firmware asking for more than the heap affords still starts. See `max_cols`. - cur_winsize = .{ - .rows = @min(rows, max_rows), - .cols = @min(cols, max_cols), - .x_pixel = 0, - .y_pixel = 0, - }; - - const allocs = pardes.memory.init(a); - // `std.Io.failing` and not a real Io: every path in the core that would perform I/O is behind - // the Host vtable, and the ones that are not are the ones this platform does not have. - pardes.image.start(std.Io.failing, allocs.image); - pardes.syntax.start(allocs.tree_sitter); - - vx = vaxis.init(std.Io.failing, a, &env_map, .{}) catch |err| return errCode(err); - vx.resize(a, &out, vaxisSize()) catch |err| return errCode(err); - - // Ask the terminal what it is. Both halves are pure byte writers, which is the whole reason this - // works over a serial line: the replies arrive as ordinary input and are parsed like any key. - vx.enterAltScreen(&out) catch |err| return errCode(err); - vx.queryTerminalSend(&out) catch |err| return errCode(err); - - // MOUSE REPORTING, spelled out here rather than taken from `vx.setMouseMode`. - // - // vaxis enables `1002;1003;1004;1006`, and 1003 is ANY-MOTION tracking: the terminal reports - // every cell the pointer crosses with no button held. On a 115200 line that is unaffordable - - // one sweep across this grid is dozens of reports of ~15 bytes each, and each one arrives as - // input that the editor must parse while it is trying to paint. Worse, it arrives whether or not - // anybody wants it, so moving the mouse over the window would starve typing. - // - // 1002 reports presses, releases and motion WHILE A BUTTON IS HELD, which is exactly the set a - // click and a drag-select need. 1004 is focus in/out, which `apply` already handles. 1006 is the - // SGR encoding: unlike the original X10 form it is not limited to column 223, which a grid this - // small does not need today but costs nothing to have and cannot be added later without the - // terminal disagreeing with the editor about where the pointer is. - out.writeAll("\x1b[?1002;1004;1006h") catch |err| return errCode(err); - out.flush() catch |err| return errCode(err); - - // The CLAMPED geometry, because the core and vaxis must agree on the grid and vaxis was just - // sized to `cur_winsize`. - core = pardes.Pardes.init(allocs.pardes, .{ - .cols = cur_winsize.cols, - .rows = cur_winsize.rows, - .frame_allocator = allocs.frame, - .image_allocator = allocs.image, - .tree_sitter_allocator = allocs.tree_sitter, - }) catch |err| return errCode(err); - - dirty = true; - return 0; -} - -/// Raw bytes off the wire: keystrokes, capability replies, and in-band resize reports. All three are -/// the same kind of thing to `vaxis.Parser`, and this function does not distinguish them. -export fn pardes_esp32p4_input(ptr: [*]const u8, len: usize) callconv(.c) void { - const c = core orelse return; - - // Append, dropping the oldest on overflow: a full buffer means the parser is stuck on a - // malformed sequence, and keeping the tail is what lets it resynchronise. - const room = in_buf.len - in_len; - const take = @min(room, len); - if (take < len) { - in_len = 0; - @memcpy(in_buf[0..@min(len, in_buf.len)], ptr[0..@min(len, in_buf.len)]); - in_len = @min(len, in_buf.len); - } else { - @memcpy(in_buf[in_len..][0..take], ptr[0..take]); - in_len += take; - } - - drainInput(c, false); -} - -/// Parse what has accumulated, applying every event it yields. -/// -/// THE LONE ESCAPE IS AMBIGUOUS, and on this transport it is ambiguous constantly. `vaxis.Parser` -/// resolves a buffer containing nothing but `0x1b` as the Escape KEY - deliberately, and correctly -/// for a real terminal, where the kernel hands over a whole escape sequence in one read so a solitary -/// ESC really does mean the key. A 115200 serial line hands over one byte at a time: 87 us apart, -/// which is an eternity to this loop. So the first byte of EVERY escape sequence arrived alone and -/// was resolved as Escape, and the rest arrived as ordinary keys. -/// -/// That is not a mouse bug, though it is why the mouse did not work: a click report came through as -/// ten key presses - Escape, `[`, `<`, `0`, ... - and the `0` among them is "go to column zero" in -/// normal mode, which is exactly where the cursor kept landing. Arrow keys, function keys and the -/// host's in-band resize reports were all being shredded the same way. -/// -/// Longer partial sequences were never affected: the CSI scanner returns `n == 0` for "no final byte -/// yet", and the loop below keeps those bytes. Only the one-byte case needed an answer, because it is -/// the only one the parser answers wrongly instead of declining. -/// -/// `force` is how a real Escape keypress still works: `pardes_esp32p4_tick` calls with it set once the -/// hold has lasted longer than any serial line would take to deliver the next byte. -fn drainInput(c: *pardes.Pardes, force: bool) void { - var off: usize = 0; - while (off < in_len) { - if (!force and in_len - off == 1 and in_buf[off] == 0x1b) break; - const res = parser.parse(in_buf[off..in_len], gpa()) catch break; - if (res.n == 0) break; // incomplete: wait for more bytes - off += res.n; - if (res.event) |ev| apply(c, ev); - } - // Keep whatever was not consumed: the tail of a split escape sequence. - if (off > 0) { - std.mem.copyForwards(u8, in_buf[0 .. in_len - off], in_buf[off..in_len]); - in_len -= off; - } - // Start or clear the hold. `esc_held_at` is only ever set for a buffer that is exactly one ESC, - // so a partial CSI - which the parser already declines - does not start a timer it does not need. - if (in_len == 1 and in_buf[0] == 0x1b) { - if (esc_held_at == null) esc_held_at = last_now_ms; - } else esc_held_at = null; -} - -/// One parsed vaxis event applied to the core. Mirrors the tui shell's `apply` -/// (`src/tui/tui.zig:926-985`), minus everything that needs an OS. -fn apply(c: *pardes.Pardes, ev: vaxis.Event) void { - switch (ev) { - .key_press => |key| if (in_paste) { - // Between the brackets a key is DATA, never a command. vaxis gives control bytes no - // text at all, so a line break inside a paste arrives as a bare CR (Key.enter) or, from - // a terminal that does not translate them, as ctrl+j. - const text = key.text orelse ""; - const cp = vaxis_input.mapKey(vaxis_input.effCp(key)); - const bytes: []const u8 = if (text.len > 0) - text - else if (cp == pardes.Key.tab) - "\t" - else if (cp == pardes.Key.enter or (key.mods.ctrl and cp == 'j')) - "\n" - else - ""; - if (bytes.len > 0) paste_buf.appendSlice(gpa(), bytes) catch {}; - } else { - c.update(.{ .key = .{ - .cp = vaxis_input.mapKey(vaxis_input.effCp(key)), - .text = key.text orelse "", - .ctrl = key.mods.ctrl, - .alt = key.mods.alt, - .shift = key.mods.shift, - } }); - dirty = true; - }, - .paste_start => { - paste_buf.clearRetainingCapacity(); - in_paste = true; - }, - .paste_end => { - in_paste = false; - if (paste_buf.items.len > 0) { - c.update(.{ .paste = paste_buf.items }); - dirty = true; - } - paste_buf.clearRetainingCapacity(); - }, - // OSC 52. The bytes are the parser's, allocated from our own allocator, so they are freed - // here rather than leaked - the core copies whatever it keeps. - .paste => |text| { - c.update(.{ .paste = text }); - gpa().free(text); - dirty = true; - }, - .mouse => |m| { - const button: ?pardes.Mouse.Button = switch (m.button) { - .left => .left, - .middle => .middle, - .right => .right, - .wheel_up => .wheel_up, - .wheel_down => .wheel_down, - .wheel_left => .wheel_left, - .wheel_right => .wheel_right, - .none => .none, - else => null, - }; - if (button) |b| { - c.update(.{ - .mouse = .{ - .button = b, - .kind = switch (m.type) { - .press => .press, - .release => .release, - .motion => .motion, - .drag => .drag, - }, - // Before the first cell (a drag past the edge): the edge. - .col = @intCast(@max(0, m.col)), - .row = @intCast(@max(0, m.row)), - .ctrl = m.mods.ctrl, - }, - }); - dirty = true; - } - }, - // The only way this platform learns its size, and the one place a 384 KiB heap shows through - // to the user. Two things happen here that the tui shell does not need. - // - // CLAMPED, because the grids do not fit an arbitrary terminal: vaxis keeps a `Screen` and an - // `InternalScreen`, pardes keeps its own `Surface` and `previous_cells`, so every cell is - // paid for four times. Measured on the die - 40x12 initialises with room to spare, 80x24 - // exhausts the heap and `Pardes.init` returns OutOfMemory with 9,128 bytes left. The host's - // terminal is normally larger than the board can render, so the editor takes a corner of it - // instead of refusing to start. - // - // ATOMIC, because `Vaxis.resize` deinits both screens BEFORE allocating the replacements - // (Vaxis.zig:194-206), so a failed resize leaves vaxis with freed screens and renders - // nothing at all. That is exactly how this was found: the host bridge injects a size report - // on attach, the 80x24 it reported could not be allocated, and an editor that had just drawn - // its interface went silent. A failure now puts the previous geometry back. - .winsize => |ws| { - const want: vaxis.Winsize = .{ - .rows = @min(ws.rows, max_rows), - .cols = @min(ws.cols, max_cols), - .x_pixel = ws.x_pixel, - .y_pixel = ws.y_pixel, - }; - if (want.cols == cur_winsize.cols and want.rows == cur_winsize.rows) return; - const previous = cur_winsize; - // vaxis is only resized when it is the thing doing the rendering. Under `direct_emit` its - // grids are a single cell and stay that way - see `vaxisSize` - so there is nothing here - // to reallocate, which also means a resize can no longer fail for want of two grids. - if (!direct_emit) { - vx.resize(gpa(), &out, want) catch { - vx.resize(gpa(), &out, previous) catch {}; - return; - }; - } - cur_winsize = want; - c.update(.{ .resize = .{ .cols = want.cols, .rows = want.rows } }); - dirty = true; - }, - // A TTY cannot report a pointer leaving its grid, so losing focus is the only reliable - // pointer-leave signal there is. - .focus_out => { - c.update(.pointer_leave); - dirty = true; - }, - .focus_in, .mouse_leave, .cursor_position => {}, - // Capability replies. vaxis's own Loop sets these fields directly (`Loop.zig:377-403`); - // with no Loop, this is where they land. DA1 is the terminator: every terminal answers it - // last, so it is the signal that the whole handshake is in and the detected features can be - // switched on. - .cap_kitty_keyboard => vx.caps.kitty_keyboard = true, - .cap_kitty_graphics => vx.caps.kitty_graphics = true, - .cap_rgb => vx.caps.rgb = true, - .cap_unicode => { - vx.caps.unicode = .unicode; - vx.screen.width_method = .unicode; - }, - .cap_sgr_pixels => vx.caps.sgr_pixels = true, - .cap_color_scheme_updates => vx.caps.color_scheme_updates = true, - .cap_multi_cursor => vx.caps.multi_cursor = true, - .cap_da1 => { - vx.enableDetectedFeatures(&out) catch {}; - out.flush() catch {}; - dirty = true; - }, - .color_report, .color_scheme => {}, - .key_release => {}, - } -} - -export fn pardes_esp32p4_tick(now_ms: u64) callconv(.c) void { - const c = core orelse return; - last_now_ms = now_ms; - // The held Escape, released. Anything still waiting after this long is a key the human pressed, - // not the head of a sequence: the next byte of a real sequence is 87 us behind on this line, and - // even a slow terminal emulator answers a query in well under a millisecond. Ten is generous by - // two orders of magnitude and imperceptible to the person pressing it - the same trade every - // terminal editor makes for the same reason. - if (esc_held_at) |at| { - if (now_ms -% at >= esc_hold_ms) { - drainInput(c, true); - dirty = true; - } - } - // The core steps its own animations by this clock (`Host.now`). - c.advance(now_ms * std.time.ns_per_ms); - if (c.needs_frame) dirty = true; -} - -/// How long a lone ESC waits for a second byte before it counts as the Escape key. -const esc_hold_ms = 10; - -/// The last timestamp `pardes_esp32p4_tick` was given, so `drainInput` can date a hold without needing a -/// clock of its own - there is no clock on this side of the ABI. -var last_now_ms: u64 = 0; - -/// When the buffer became a lone ESC, or null when it is not holding one. -var esc_held_at: ?u64 = null; - -export fn pardes_esp32p4_wants_frame() callconv(.c) bool { - const c = core orelse return false; - return dirty or c.needs_frame; -} - -export fn pardes_esp32p4_render() callconv(.c) u32 { - const c = core orelse return 0; - c.pump(.{ .ctx = null, .vtable = &pardes_host }) catch |err| return errCode(err); - dirty = false; - return 0; -} - -export fn pardes_esp32p4_quit() callconv(.c) bool { - const c = core orelse return true; - return c.quit; -} - -// ------------------------------------------------------------------------------------ the host - -const pardes_host: pardes.Host.VTable = .{ .now = boardNow, .present = present, .gpio_toggle = gpioToggle }; - -fn boardNow(_: ?*anyopaque) u64 { - return last_now_ms * std.time.ns_per_ms; -} - -/// The `Gpio` word's one seam to the board. Nothing here knows what a pad is; it forwards, and -/// answers false when the firmware brought none, which is what puts "gpio: no pads" on the message -/// row rather than a trap. -fn gpioToggle(_: ?*anyopaque, pin: u16, was: *u8, now: *u8) bool { - const f = host_gpio orelse return false; - return f(out_ctx, pin, was, now); -} - -/// The canonical surface -> the wire. Same shape as the tui shell's (`src/tui/tui.zig:1096`) minus -/// the panel compositor and the kitty image path: neither has a reason to exist on a board with no -/// pixels. Where the tui shell hands every cell to vaxis and lets it diff, this diffs against the -/// Surface itself and can then emit the ANSI directly - see `direct_emit`. -fn present(_: ?*anyopaque, surface: *const pardes.Surface) void { - const t0 = cycles(); - const win = vx.window(); - const n = @as(usize, surface.cols) * @as(usize, surface.rows); - - // THE SHADOW GRID. Copying all 480 cells into vaxis every frame cost 6.75 ms on the die - 57% - // of a keystroke, and it was paid whether or not anything changed: a second render with nothing - // new measured the same as the first. vaxis already diffs its own grid against the terminal, but - // it can only do that AFTER being told every cell, and being told is the expensive part - // (`writeCell` builds a vaxis `Cell`, which carries an always-null image placement). - // - // So keep the previous Surface and tell vaxis only what moved. `Cell.visuallyEqual` is the - // right comparison and already exists for the panel compositor's benefit: it ignores scratch - // bytes past `len` and treats any two default cells as equal, so it cannot manufacture a write. - // - // STATIC, and that is not a micro-optimisation - it is a bug fix. The first version allocated - // this from the editor's heap, and on a board whose 384 KiB is already nearly spoken for that - // was enough to make `vx.resize` fail: a resize then hit its OOM path, restored the previous - // geometry and returned, so the screen was never repainted. Measured as a resize emitting 80 - // bytes where it had emitted 1,392. The grid is bounded by `max_cols` x `max_rows` at comptime, - // so it belongs in `.bss` where it cannot compete with anything. - const full = !shadow_grid or prev_cols != surface.cols or prev_rows != surface.rows; - emit_bytes = 0; - if (full) { - prev_cols = surface.cols; - prev_rows = surface.rows; - if (direct_emit) { - // Reset first: a `2J` while a non-default background is active fills the screen with it. - emitRaw("\x1b[0m\x1b[2J") catch return; - emit_style = .{}; - emit_col = -1; - } else win.clear(); - } - const usable = shadow_grid and n <= prev_cells.len; - - var y: u16 = 0; - while (y < surface.rows) : (y += 1) { - const row0 = @as(usize, y) * @as(usize, surface.cols); - const src = surface.cells[row0..][0..surface.cols]; - - // A ROW AT A TIME FIRST. `Surface.cells` is contiguous and row-major, so a whole row is one - // `memcmp` against the shadow - and on a keystroke eleven of twelve rows are untouched. The - // per-cell loop below is ~40 branchy comparisons where this is one call over 1,120 bytes; - // measured, the walk fell from 246 us to a fraction of it. Byte equality implies visual - // equality (see `sameCell`), so a row that compares equal cannot be hiding a changed cell - - // and a row that differs only in padding falls through to the per-cell path, which is - // correct and merely slower. - if (usable and !full) { - const shadow = prev_cells[row0..][0..surface.cols]; - if (sameBytes(std.mem.sliceAsBytes(src), std.mem.sliceAsBytes(shadow))) continue; - } - - var x: u16 = 0; - while (x < surface.cols) : (x += 1) { - const cell = &src[x]; - const idx = row0 + @as(usize, x); - if (usable) { - if (!full and sameCell(cell, &prev_cells[idx])) continue; - prev_cells[idx] = cell.*; - } else if (cell.default) continue; - - writeOne(win, x, y, cell, surface.cols) catch return; - } - } - if (direct_emit) { - // BOTH branches have to reach the packet boundary, and the second one is easy to forget: - // measured, a frame that only hid the cursor was 6 bytes and cost 4014 us at 640 characters - // against 3863 at 320, because 6 bytes never fills a packet and waited out the bridge's - // timer. Hiding an already-hidden cursor is as idempotent as positioning it twice. - if (surface.cursor) |cur| { - cup(cur.y, cur.x) catch return; - emitRaw("\x1b[?25h") catch return; - emit_col = -1; - while (emit_bytes < emit_min_frame) cup(cur.y, cur.x) catch return; - } else { - while (emit_bytes < emit_min_frame) emitRaw("\x1b[?25l") catch return; - } - } else if (surface.cursor) |cur| { - win.showCursor(cur.x, cur.y); - } else win.hideCursor(); - const t1 = cycles(); - - // vaxis diffs against its own shadow grid, so this writes only what changed - which is what - // makes an editor usable at 11.9 KB/s. With `direct_emit` that diff has already happened, one - // stage earlier and against the Surface itself, so there is nothing left here to do. - if (!direct_emit) vx.render(&out) catch return; - const t2 = cycles(); - out.flush() catch return; - const t3 = cycles(); - - prof_copy_cy = t1 -% t0; - prof_render_cy = t2 -% t1; - prof_flush_cy = t3 -% t2; -} - -/// One cell to the wire, either through vaxis or straight out. -inline fn writeOne(win: vaxis.Window, x: u16, y: u16, cell: *const pardes.Cell, cols: u16) !void { - if (!direct_emit) { - // Changed TO default. `win.clear()` is what used to blank these, and it is not run on an - // incremental frame, so say it explicitly. - if (cell.default) return win.writeCell(x, y, .{ .char = .{ .grapheme = " " }, .style = .{} }); - return win.writeCell(x, y, .{ - .char = .{ .grapheme = cell.grapheme() }, - .style = vaxisStyle(cell.style), - }); - } - - if (emit_row != y or emit_col != x) { - try cup(y, x); - emit_row = y; - emit_col = @intCast(x); - } - - const style: pardes.CellStyle = if (cell.default) .{} else cell.style; - if (!std.meta.eql(emit_style, style)) { - try emitStyle(style); - emit_style = style; - } - - try emitRaw(if (cell.default) " " else cell.grapheme()); - - // Where the terminal's cursor now is. A single printable ASCII byte advanced it exactly one - // column; anything else - a wide glyph, a cluster, the spacer cell pardes writes after a wide - // one - is not worth predicting, so give up and let the next cell emit an absolute CUP. The last - // column is given up on too, because whether the cursor rests on it or has wrapped past it - // depends on the terminal's deferred-wrap behaviour, and the two disagree by a whole row. - if (x + 1 < cols and cell.len == 1 and cell.text[0] >= 0x20 and cell.text[0] < 0x7f) { - emit_col += 1; - } else emit_col = -1; -} - -/// A style as an absolute SGR, always opening with a reset. -/// -/// Absolute rather than a delta from whatever is currently on, and that is what keeps it short -/// enough to be worth having: no per-attribute off-codes, no state to keep beyond the last style -/// emitted, and a frame that gets cut off cannot leave a later cell wearing an earlier one's colour. -/// It costs a few bytes on a style change, against the ~9 of CUP a changed cell is paying anyway. -fn emitStyle(s: pardes.CellStyle) !void { - try emitRaw("\x1b[0"); - if (s.bold) try emitRaw(";1"); - if (s.dim) try emitRaw(";2"); - if (s.italic) try emitRaw(";3"); - if (s.blink) try emitRaw(";5"); - if (s.reverse) try emitRaw(";7"); - if (s.invisible) try emitRaw(";8"); - if (s.strikethrough) try emitRaw(";9"); - try emitRaw(switch (s.ul) { - .off => "", - .single => ";4", - .double => ";4:2", - .curly => ";4:3", - .dotted => ";4:4", - .dashed => ";4:5", - }); - try emitColor(s.fg, 30); - try emitColor(s.bg, 40); - try emitRaw("m"); -} - -/// `base` is 30 for a foreground and 40 for a background, which is the only thing separating the two -/// in every form SGR has for a colour: 30-37 against 40-47, 90-97 against 100-107, 38 against 48. -fn emitColor(c: pardes.Color, comptime base: u16) !void { - var b: [20]u8 = undefined; - var i: usize = 0; - switch (c) { - // Already said by the reset this SGR opens with. - .default => return, - .index => |n| { - b[i] = ';'; - i += 1; - if (n < 8) { - i += dec(b[i..], base + n); - } else if (n < 16) { - i += dec(b[i..], base + 60 + (n - 8)); - } else { - i += dec(b[i..], base + 8); - i += lit(b[i..], ";5;"); - i += dec(b[i..], n); - } - }, - .rgb => |v| { - b[i] = ';'; - i += 1; - i += dec(b[i..], base + 8); - i += lit(b[i..], ";2;"); - for (v, 0..) |component, k| { - if (k != 0) { - b[i] = ';'; - i += 1; - } - i += dec(b[i..], component); - } - }, - } - try emitRaw(b[0..i]); -} - -/// Absolute cursor positioning, hand-rolled rather than through `out.print`. -/// -/// Not for elegance: this is the single most frequent sequence the emitter produces, at least one per -/// changed run, and `std.fmt` brings a whole format-string interpreter to write at most two digits. -/// The grid is bounded by `max_cols` x `max_rows`, so nothing here can exceed three. -fn cup(row: u16, col: u16) !void { - var b: [12]u8 = undefined; - var i: usize = lit(&b, "\x1b["); - i += dec(b[i..], row + 1); - b[i] = ';'; - i += 1; - i += dec(b[i..], col + 1); - b[i] = 'H'; - i += 1; - try emitRaw(b[0..i]); -} - -/// Decimal, least significant digit first into a scratch buffer and then reversed. Five digits is -/// every `u16`, so there is no fallback to `std.fmt` and no value this cannot write. -fn dec(buf: []u8, v: u16) usize { - var digits: [5]u8 = undefined; - var n: usize = 0; - var rest = v; - while (true) { - digits[n] = '0' + @as(u8, @intCast(rest % 10)); - n += 1; - rest /= 10; - if (rest == 0) break; - } - for (0..n) |k| buf[k] = digits[n - 1 - k]; - return n; -} - -inline fn lit(buf: []u8, comptime s: []const u8) usize { - @memcpy(buf[0..s.len], s); - return s.len; -} - -/// Every direct-emit byte goes through here, because the count is what the padding below needs. -inline fn emitRaw(bytes: []const u8) !void { - emit_bytes += bytes.len; - try out.writeAll(bytes); -} - -/// A/B switch for the emitter above, on the same terms as `shadow_grid`: false routes every cell back -/// through vaxis, which is the reference. vaxis's own diff measured 631 us of a 4.37 ms keystroke and -/// all of it was redundant - `present` has already worked out which cells moved, so vaxis was being -/// told the answer and then computing it again from scratch. -const direct_emit = true; - -/// THE FRAME HAS A MINIMUM SIZE, and it is the USB bridge's, not the terminal's. -/// -/// The board is wired to the host through a CH340, and 32 is not a guess: it is `wMaxPacketSize` of -/// endpoint 0x82, the bulk IN, as the device itself reports it - a full-speed 0x0020. The bridge -/// forwards a packet when the packet is FULL, so a frame shorter than that sits there until an -/// internal timer gives up on more, which is worth about a millisecond - a quarter of the budget. -/// -/// Measured, at the same board cost and with the screen byte-identical: a 21-byte frame round-trips -/// in 4817 us and the same frame padded to 49 bytes in 3814 us. MORE BYTES, ARRIVING SOONER. It also -/// explains why routing through vaxis looked competitive - its frames are 81 bytes, so they fill a -/// packet by accident and never wait. -/// -/// So pad to the packet boundary. The filler is repeated absolute cursor positioning: idempotent, -/// already the sequence the emitter ends on, and it cannot alter a cell. This is the same bargain as -/// an Ethernet runt frame - the medium has a minimum and the sender pays it - and it is a real -/// trade, not free: the wasted bytes are wire time that delays a LATER frame, so it is only worth it -/// while the frame is small, which is exactly when it applies. -const emit_min_frame: usize = 32; - -/// Bytes emitted this frame, for `emit_min_frame`. -var emit_bytes: usize = 0; - -/// What the terminal is currently wearing and where its cursor is, so that a run of changed cells in -/// one row costs one CUP and one SGR rather than one of each per cell. `emit_col` is signed because -/// -1 means "no longer known" - see `writeOne`. -var emit_style: pardes.CellStyle = .{}; -var emit_row: u16 = 0; -var emit_col: i32 = -1; - -/// A/B switch, kept because this optimisation is exactly the kind that can be right about latency -/// and wrong about the screen. With it false, `present` behaves as it did before the shadow grid - -/// clear and write every cell - which is the reference any measurement of it should be compared -/// against, and the way to tell a rendering bug from a rendering difference. -const shadow_grid = true; - -/// The previous Surface, cell for cell, sized for the largest grid this board can drive. In `.bss` -/// rather than on the heap: see `present`. `prev_cols`/`prev_rows` being zero on the first frame is -/// what makes that frame a full one. -var prev_cells: [@as(usize, max_cols) * @as(usize, max_rows)]pardes.Cell = if (shadow_grid) @splat(.{}) else undefined; -var prev_cols: u16 = 0; -var prev_rows: u16 = 0; - -/// Cell equality for the shadow grid, as bytes. -/// -/// `Cell.visuallyEqual` is the semantically exact answer and it is too slow to ask 480 times a -/// frame: `std.meta.eql` on a `CellStyle` recurses through a colour union and eight booleans, and -/// the walk measured 1.45 ms - about 270 cycles per comparison of a ~28-byte struct. -/// -/// Byte equality IMPLIES visual equality, so this can never claim two different cells are the same. -/// It can miss an equality - scratch bytes past `len`, or padding - and the only cost of that is one -/// redundant `writeCell` that vaxis then diffs away. Defaults are still handled by meaning rather -/// than by bytes, because an unpainted cell's text and style are whatever the last frame left there. -inline fn sameCell(a: *const pardes.Cell, b: *const pardes.Cell) bool { - if (a.default or b.default) return a.default and b.default; - return sameBytes(std.mem.asBytes(a), std.mem.asBytes(b)); -} - -/// Exact byte equality, a word at a time when both spans are aligned for it. -/// -/// This comparison is the firmware's largest read by a wide margin - two 13 KB streams every frame - -/// and it measured 3.2 cycles per byte, about four times what word-wide loads should need, which is -/// what a byte-at-a-time loop looks like. The answer is identical either way: this is still exact -/// byte equality, so it keeps the property the whole diff rests on, that byte equality implies -/// visual equality. -/// -/// The alignment test is a RUNTIME one because `Cell` has alignment 1 - it is all `u8` fields - so -/// whether a row begins on a word boundary is a property of whoever allocated the Surface and not of -/// the type. A row is 40 cells of 26 bytes, which is divisible by four, so if the base is aligned -/// every row is. When it is not, the byte loop is still here. -inline fn sameBytes(a: []const u8, b: []const u8) bool { - if (a.len != b.len) return false; - if ((@intFromPtr(a.ptr) | @intFromPtr(b.ptr)) & 3 == 0) { - const n = a.len / 4; - const wa: [*]align(4) const u32 = @ptrCast(@alignCast(a.ptr)); - const wb: [*]align(4) const u32 = @ptrCast(@alignCast(b.ptr)); - for (wa[0..n], wb[0..n]) |x, y| { - if (x != y) return false; - } - return std.mem.eql(u8, a[n * 4 ..], b[n * 4 ..]); - } - return std.mem.eql(u8, a, b); -} - -// ------------------------------------------------------------------ where a frame's time goes -// -// A frame has three stages and they want different fixes, so the firmware is given all three rather -// than one total. Measured on the die, a render costs ~11 ms whether or not anything changed, which -// says the cost is the unconditional walk and not the edit - but "the walk" is two walks, the copy -// into vaxis's grid and vaxis's own diff, and only one of them is ours to change. -// -// Two CSR reads per stage. `cycle` is the unprivileged counter, read high-low-high because two -// 32-bit halves can straddle a wrap. -var prof_copy_cy: u64 = 0; -var prof_render_cy: u64 = 0; -var prof_flush_cy: u64 = 0; - -inline fn cycles() u64 { - if (builtin.cpu.arch != .riscv32) return 0; - while (true) { - const hi0 = asm volatile ("csrr %[o], cycleh" - : [o] "=r" (-> u32), - ); - const lo = asm volatile ("csrr %[o], cycle" - : [o] "=r" (-> u32), - ); - const hi1 = asm volatile ("csrr %[o], cycleh" - : [o] "=r" (-> u32), - ); - if (hi0 == hi1) return (@as(u64, hi0) << 32) | lo; - } -} - -/// The last frame's three stages, in cycles. Zero on any platform without the CSR. -export fn pardes_esp32p4_frame_prof(copy: *u64, render: *u64, flush: *u64) callconv(.c) void { - copy.* = prof_copy_cy; - render.* = prof_render_cy; - flush.* = prof_flush_cy; -} - -fn vaxisStyle(s: pardes.CellStyle) vaxis.Style { - return .{ - .fg = vaxisColor(s.fg), - .bg = vaxisColor(s.bg), - .bold = s.bold, - .dim = s.dim, - .italic = s.italic, - .blink = s.blink, - .reverse = s.reverse, - .invisible = s.invisible, - .strikethrough = s.strikethrough, - .ul_style = switch (s.ul) { - .off => .off, - .single => .single, - .double => .double, - .curly => .curly, - .dotted => .dotted, - .dashed => .dashed, - }, - }; -} - -fn vaxisColor(c: pardes.Color) vaxis.Color { - return switch (c) { - .default => .default, - .index => |i| .{ .index = i }, - .rgb => |rgb| .{ .rgb = rgb }, - }; -} - -/// Errors cross the ABI as small non-zero integers. `@intFromError` is not stable across builds, so -/// it is not used: the firmware only reports the number, and a stable-looking value that silently -/// changed meaning would be worse than an opaque one. -fn errCode(err: anyerror) u32 { - return switch (err) { - error.OutOfMemory => 1, - error.WriteFailed => 2, - else => 255, - }; -} diff --git a/src/esp32p4/app.zig b/src/esp32p4/app.zig deleted file mode 100644 index 800e7597..00000000 --- a/src/esp32p4/app.zig +++ /dev/null @@ -1,545 +0,0 @@ -//! pardes, as ESP32-P4 firmware: the reset entry, the heap, the clock, the trap handler and the -//! loop. -//! -//! There is no operating system under this. `_start` is the reset entry the second-stage bootloader -//! jumps to, and this file is the entire platform: a heap, a millisecond clock, and UART0. -//! -//! ## Why the firmware root is in the editor's repository -//! -//! It was written in the `05-zig-p4` toolchain repository, next to the SoC support it uses, and it -//! moved here because everything in it is a statement about the EDITOR. The heap span it hands over -//! is the number that decides how large a grid the board can drive; `input_chunk` is sized against -//! what applying one keystroke costs in `src/pardes.zig`; the loop's shape - read, chunk, tick, -//! render only when dirty - is this editor's loop and no one else's; and the `-Dprof` attribution -//! exists to answer "where did the 34 ms of a keystroke go" about this program. A firmware root that -//! specific to one application belongs beside it. -//! -//! What stayed behind is everything a second application would also want, and none of it is -//! duplicated here: the SoC and HAL, the translate-c register layer, the coalescing heap, `std.Io` -//! for this chip, the app descriptor, the generated linker script, the image builder, the flasher -//! and the interactive console. The sibling `05-zig-p4` build supplies them; this file imports -//! exactly four of its modules - `soc`, `hal`, `heap` and `config` - plus two sibling files, -//! `uart.zig` and `input_rescue.zig`, which are the editor's own. -//! -//! ## Where the editor is -//! -//! On the far side of a C ABI, still, and that is a choice rather than a leftover. `src/esp32p4.zig` in -//! this same repository is compiled as ONE freestanding object (`b.addObject`, rooted at that file) -//! and linked in beside this one; the `extern` declarations below are the near side of that seam. -//! -//! Importing `esp32p4.zig` as a module instead would be shorter to write and worse in every way that -//! matters. It would drag the core's whole module graph - vaxis, the themes, the allocator tiers - -//! into this root, which is the compilation that must stay small enough to reason about. It would -//! give the firmware two ways to reach the editor. And above all it would make the OBJECT path a -//! second arrangement, tested separately: that path is what `05-zig-p4 -Dpardes -Dpardes-obj=...` -//! builds, it is what every measurement in that repository's `experiments/` was taken through, and -//! it is the firmware build path. Its externs link against that object file. -//! The reasons the seam is a file at all - a nested `build.zig.zon` dependency broke every build in -//! the toolchain repository - are recorded in `src/esp32p4.zig:8-15` and `05-zig-p4/build.zig:252-272`. -//! -//! Who owns which symbol: `src/esp32p4.zig` exports all eight `pardes_esp32p4_*` functions and nothing else. -//! This file exports `_start`, `zig_main`, `trapEntry` and `trapReport`. `esp_app_desc` belongs to -//! neither and comes from the toolchain's own appdesc object, which the link adds unconditionally. -//! `abi_version` below is the one constant both sides spell, and its counterpart is -//! `src/esp32p4.zig:98` - one repository now, so a bump is two lines in one diff rather than two commits -//! in two trees. -//! -//! The seam is deliberately **bytes in, bytes out**. Everything that needs to know what a cell is - -//! vaxis, the ANSI encoder, the input parser, the capability handshake - lives on the far side, -//! next to the vaxis it is built against. What crosses is a byte stream in each direction, which is -//! exactly what a serial line is, so this file has no opinion about terminals at all. -//! -//! ## Where the memory is -//! -//! Measured on this die by the toolchain's `examples/memprobe.zig`, not read off a datasheet, and -//! written down once in the generated linker script (`05-zig-p4/build.zig:1569,1576,1581-1582`): -//! -//! 0x4FF00000..0x4FF3F000 252 KiB `l2mem`: .data/.bss/.stack are linked into this -//! 0x4FF3F000..0x4FF40000 4 KiB mask ROM .data/.bss - untouchable, ets_printf needs it -//! 0x4FF40000..0x4FFA0000 384 KiB `l2high`: handed to the editor as its entire heap -//! 0x4FFA0000..0x4FFC0000 128 KiB NOT memory - the L2 cache lives here -//! -//! That last line is why the heap is 384 KiB and not the 512 KiB an earlier version of this comment -//! claimed. The first probe wrote a pattern and read it back one page at a time and reported the -//! whole upper 512 KiB as RAM, because a store followed immediately by a load of the SAME address -//! returns the stored value whether the backing store is real, an address mirror, or merely a dirty -//! cache line. Writing every page before reading any page separates the three, and the top 128 KiB -//! then failed; handing them to an allocator hung the heap on its first free-list walk. ESP-IDF's -//! own arithmetic agrees exactly: SRAM_HIGH_SIZE = 0x80000 - CONFIG_CACHE_L2_CACHE_SIZE, with the -//! Kconfig default of 128 KiB. -//! -//! The span arrives as `__heap_start`/`__heap_end` from that script, so those addresses are written -//! down in exactly one place. The editor owns it outright: it is passed in at init and this file -//! never allocates from it. -//! -//! PSRAM is not used. The board has 32 MB fitted and it would make all of this comfortable, but -//! ESP-IDF's own ESP32-P4 implementation runs past a thousand lines - MPLL, MSPI clocking, pin -//! drive and DQS, CS timing, mode registers, a connectivity check, and an entire timing-calibration -//! subsystem - and the mask ROM offers only MMU mapping, no device init. Touching it untrained -//! faults and hangs the core, which `examples/memprobe.zig` demonstrates on purpose. - -const std = @import("std"); -const soc = @import("soc"); -const config = @import("config"); - -/// `-Dprof`: time the two phases of a keystroke on the board and print the cycle counts. A -/// diagnostic, not a feature - see the loop. -const prof = config.prof; - -/// Every byte this loop has taken off the UART, for `-Dprof`. Ground truth for "did the burst -/// arrive", which a screen reconstruction cannot answer: a character can be missing from the screen -/// because it never arrived, because the editor never applied it, or because the viewport does not -/// show that column. -var rx_total: u32 = 0; - -/// How many input bytes to hand the editor before draining the receiver again. Chosen against the -/// FIFO rather than against the editor: applying one keystroke was measured at 44 us on an empty -/// line and 63 us at 640 characters, so eight of them is at most ~0.5 ms in which nothing empties -/// the receiver, against a 128-byte FIFO that holds 11 ms of wire at 115200. Twenty times the margin -/// needed, and it costs nothing on the wire because one render still happens per loop iteration. -const input_chunk = 8; -const hal = @import("hal"); -const heapmod = @import("heap"); -const uart = @import("uart.zig"); - -// ------------------------------------------------------------------------------------- the ABI -// Eight functions, all `callconv(.c)`, all implemented in the linked object - `src/esp32p4.zig` in this -// repository, compiled for the same target and exporting exactly these names. This is the complete -// interface between this board and the editor, and it is deliberately bytes-and-memory only: the -// editor never learns what a UART is, and this file never learns what a cell is. -// -// The declarations below are a SECOND spelling of the signatures in `src/esp32p4.zig:100-127,259-...`, -// and that duplication is what a C ABI is: each side declares the wire independently, which is -// precisely why `abi_version` has to be checked. Sharing a Zig type between them would mean sharing -// a module, which would mean the core in this compilation - see the header. - -/// How the editor emits bytes. Called with finished runs of ANSI, many times per frame. -const WriteFn = *const fn (ctx: ?*anyopaque, ptr: [*]const u8, len: usize) callconv(.c) void; - -/// The board's pads, offered to the editor. Optional on the wire so a firmware with nothing to -/// toggle passes null and the `Gpio` word reports that rather than the object guessing. -const GpioFn = *const fn (ctx: ?*anyopaque, pin: u16, was: *u8, now: *u8) callconv(.c) bool; - -/// This board's allocator, handed across as plain function pointers. `log2_align` is a log2 value, -/// which is exactly how `std.mem.Alignment` represents itself, so neither side needs a conversion -/// table. -/// -/// The memory belongs to THIS side: only the firmware knows that the heap is the 384 KiB at -/// 0x4FF40000, that the 128 KiB above it is L2 cache, and that PSRAM is untrained. The editor gets -/// an allocator, not an address range. -const Allocator = extern struct { - ctx: ?*anyopaque, - alloc: *const fn (ctx: ?*anyopaque, len: usize, log2_align: u8) callconv(.c) ?[*]u8, - resize: *const fn (ctx: ?*anyopaque, ptr: [*]u8, len: usize, log2_align: u8, new_len: usize) callconv(.c) bool, - free: *const fn (ctx: ?*anyopaque, ptr: [*]u8, len: usize, log2_align: u8) callconv(.c) void, -}; - -/// The one number both sides must agree on. Linkers do not type-check C symbols, so a signature -/// that drifts on one side of this seam links cleanly and then corrupts the stack; checking this -/// before calling anything else turns that into a refusal to boot. -const abi_version: u32 = 2; -extern fn pardes_esp32p4_abi_version() callconv(.c) u32; - -/// Hand over the allocator and the output sink, and state the initial window size. Returns 0, or a -/// small non-zero code this file can only report. -extern fn pardes_esp32p4_init( - alloc: *const Allocator, - write: WriteFn, - gpio: ?GpioFn, - ctx: ?*anyopaque, - cols: u16, - rows: u16, -) callconv(.c) u32; - -/// Raw bytes off the wire: keystrokes, capability-query replies, and the host bridge's in-band -/// resize reports. The editor parses all three; this file distinguishes none of them. -extern fn pardes_esp32p4_input(ptr: [*]const u8, len: usize) callconv(.c) void; - -/// Advance time. Separate from `input` because animations and timeouts must progress on a wire -/// where nothing is arriving. -extern fn pardes_esp32p4_tick(now_ms: u64) callconv(.c) void; - -/// Emit one frame through the write callback. Returns 0 or an error code. -extern fn pardes_esp32p4_render() callconv(.c) u32; - -/// Is there anything to draw - a dirty surface or a running animation? Asked every iteration so a -/// quiet editor costs no bytes on a 115200-baud link. -extern fn pardes_esp32p4_wants_frame() callconv(.c) bool; - -/// Has the user asked to leave? There is nowhere to go, so this only stops the loop. -extern fn pardes_esp32p4_quit() callconv(.c) bool; - -/// The last frame's three stages in CPU cycles: the copy of pardes's Surface into vaxis's grid, -/// vaxis's own diff-and-emit, and the push into the UART. Only meaningful under `-Dprof`; the -/// editor object always exports it, and it costs two CSR reads per stage. -extern fn pardes_esp32p4_frame_prof(copy: *u64, render: *u64, flush: *u64) callconv(.c) void; - -// ------------------------------------------------------------------------------------ the sink - -/// The write callback handed to `pardes_esp32p4_init`. No context is needed - there is one UART. -fn writeOut(_: ?*anyopaque, ptr: [*]const u8, len: usize) callconv(.c) void { - uart.write(ptr[0..len]); -} - -/// Flip one pad and report the level before and after. The editor's `Gpio` word calls this; the -/// editor has no register of its own for it, deliberately. -/// -/// THIS IS WHY THE SEAM IS HERE. A toggle is not a write to GPIO_OUT: `configureOutput` points the -/// pad's IO MUX at the GPIO function, routes the GPIO matrix's output to it, sets the drive strength -/// and input buffer and clears the pulls, and only then enables the driver - four register files, -/// indexed by a per-pin table. That code already exists in the toolchain package's `src/hal/gpio.zig`, -/// it is the same call that package's `src/main.zig` blinks with, and its register numbers are -/// checked against ESP-IDF's own headers by `zig build diff` there. A second copy inside the editor -/// object would be a second copy under no test. -/// -/// `getDrivenLevel` rather than `getLevel`: the answer is the level this board is DRIVING, which is -/// defined for every pin. The pad's own level is what the outside world says, and on an unconnected -/// header pin that is noise. The input buffer is enabled anyway, so `Peek` of GPIO_IN_REG shows the -/// pad for anyone who wants to compare the two. -fn gpioToggle(_: ?*anyopaque, pin: u16, was: *u8, now: *u8) callconv(.c) bool { - if (pin > hal.gpio.max_pin) return false; - const p: u8 = @intCast(pin); - hal.gpio.configureOutput(p, .{ .readback = true }); - const before = hal.gpio.getDrivenLevel(p); - if (before == 1) hal.gpio.setLow(p) else hal.gpio.setHigh(p); - was.* = before; - now.* = hal.gpio.getDrivenLevel(p); - return true; -} - -// ------------------------------------------------------------------------------------- the heap - -/// The span the linker script hands over, from `l2high`'s ORIGIN and LENGTH. -/// -/// Reached with `@extern`, NOT with `extern const __heap_start: anyopaque` plus -/// `@intFromPtr`/`@ptrFromInt`. That spelling was here first and it was silently wrong: declaring a -/// linker symbol as an `anyopaque` OBJECT gives the optimiser a zero-sized object, so a pointer -/// derived from its address carries provenance for zero bytes, and ordinary (non-volatile) stores -/// through it are dead code it may drop. The toolchain's `examples/heapcheck.zig` caught it on the -/// die - the allocator's first block header read back as `size=2988759312 next=0xffffffff`-not, and -/// the free list walk never terminated. A `[*]u8` from `@extern` has no size to lose. -const heap_start = @extern([*]align(heapmod.Heap.granule) u8, .{ .name = "__heap_start" }); -const heap_end = @extern([*]align(heapmod.Heap.granule) u8, .{ .name = "__heap_end" }); - -fn heapSpan() []align(heapmod.Heap.granule) u8 { - return heap_start[0 .. @intFromPtr(heap_end) - @intFromPtr(heap_start)]; -} - -/// The one heap. A K&R coalescing free list over that span, validated on this die by the toolchain's -/// `examples/heapcheck.zig`: 512 blocks fill and free back to a single 393,216-byte block, a holed -/// arena still satisfies a 4 KiB request, and 20,000 random operations drain back to one block. -var gpa_heap: heapmod.Heap = undefined; - -// The four C forwarders the editor is handed. `log2_align` round-trips through -// `std.mem.Alignment`, whose representation IS the log2 value. - -fn cAlloc(_: ?*anyopaque, len: usize, log2_align: u8) callconv(.c) ?[*]u8 { - const a = gpa_heap.allocator(); - return a.vtable.alloc(a.ptr, len, @fromBackingInt(@intCast(log2_align)), @returnAddress()); -} - -fn cResize(_: ?*anyopaque, ptr: [*]u8, len: usize, log2_align: u8, new_len: usize) callconv(.c) bool { - const a = gpa_heap.allocator(); - return a.vtable.resize(a.ptr, ptr[0..len], @fromBackingInt(@intCast(log2_align)), new_len, @returnAddress()); -} - -fn cFree(_: ?*anyopaque, ptr: [*]u8, len: usize, log2_align: u8) callconv(.c) void { - const a = gpa_heap.allocator(); - a.vtable.free(a.ptr, ptr[0..len], @fromBackingInt(@intCast(log2_align)), @returnAddress()); -} - -const editor_allocator: Allocator = .{ - .ctx = null, - .alloc = cAlloc, - .resize = cResize, - .free = cFree, -}; - -// ------------------------------------------------------------------------------------ the clock - -/// Milliseconds since boot, off the systimer - a 16 MHz counter (the toolchain package's -/// `src/hal/systimer.zig:31`), which is the cheapest trustworthy clock on this chip. `read` returns -/// null if the unit is not running, in which case time simply does not advance and the editor stops -/// animating; that is a better failure than a clock that jumps. -fn nowMs() u64 { - const us = hal.systimer.micros(.unit0) orelse return 0; - return us / 1000; -} - -// ------------------------------------------------------------------------------------- the loop - -export fn zig_main() noreturn { - // FIRST, before a single byte of `.rodata` is touched - which means before the marker below, - // because that marker IS a string literal in flash and would read as machine code without this. - soc.flushFlashCache(); - const heap = heapSpan(); - soc.rom.print("\r\nMARK B3 rom.print heap 0x%08x..0x%08x %u KiB\r\n", .{ - @as(u32, @intFromPtr(heap.ptr)), - @as(u32, @intFromPtr(heap.ptr)) + @as(u32, @intCast(heap.len)), - @as(u32, @intCast(heap.len / 1024)), - }); - - // The CPU clock, before anything is timed against it. The bootloader leaves 90 MHz and the - // CPLL is already at 360, so this is a divider change that disturbs neither UART0 (XTAL) nor - // the systimer (XTAL/2.5) nor the flash interface (SPLL). See the toolchain package's - // `src/hal/clkrst.zig:setCpuFreq`. - if (config.cpu_mhz != 90) hal.clkrst.setCpuFreq(switch (config.cpu_mhz) { - 180 => .mhz180, - 360 => .mhz360, - else => .mhz90, - }); - - const rwdt_was_armed = hal.rwdt.disable(); - hal.systimer.init(); - _ = rwdt_was_armed; - - const their_abi = pardes_esp32p4_abi_version(); - if (their_abi != abi_version) { - uart.write("MARK PARDES_ABI_MISMATCH\r\n"); - while (true) {} - } - - gpa_heap = heapmod.Heap.init(heap); - _ = uart.drainInput(); - - // Ask for more than any grid this board will ever render, so the SHELL's own ceiling is what - // governs - it clamps to `-Desp32p4-cols`/`-Desp32p4-rows` and reports the result. Naming 80x24 here made - // the firmware a second opinion about the geometry, which is one opinion too many. - const rc = pardes_esp32p4_init(&editor_allocator, writeOut, gpioToggle, null, 255, 255); - - if (rc != 0) { - soc.rom.print("MARK PARDES_INIT_FAIL rc=%u\r\n", .{rc}); - const s = gpa_heap.stats(); - soc.rom.print("MARK PARDES_HEAP free=%u largest=%u blocks=%u\r\n", .{ - s.free, s.largest_free, s.free_blocks, - }); - while (true) {} - } - - // The HEAP, after the editor has taken what it needs. This is the number that decides how large - // a grid the board can drive, so it is printed on every boot rather than only on failure: a - // geometry that fits with 2 KB to spare and one that fits with 80 KB are not the same answer, - // and the difference is invisible from the host otherwise. - { - const s = gpa_heap.stats(); - soc.rom.print("MARK PARDES_HEAP free=%u largest=%u blocks=%u\r\n", .{ - s.free, s.largest_free, s.free_blocks, - }); - } - - // The CPU clock, measured rather than assumed. Every cycle count this firmware reports is - // divided by it somewhere, and the toolchain's `src/io/chip.zig` records it as "a measured - // ~90 MHz" that nothing here reconfigures - so it is worth printing rather than remembering. The - // systimer is XTAL/2.5 = 16 MHz and is NOT derived from the CPU clock - // (`src/hal/systimer.zig:31`, `clk_tree_defs.h:196-198`), which is exactly what makes it a valid - // reference for measuring it. - if (prof) { - const t_start = hal.systimer.micros(.unit0) orelse 0; - const c_start = soc.cycles(); - // 50 ms is long enough that the systimer's 16 MHz granularity and the loop's own overhead - // are both noise, and short enough to be invisible in a boot. - while ((hal.systimer.micros(.unit0) orelse 0) -% t_start < 50_000) {} - const elapsed_us = (hal.systimer.micros(.unit0) orelse 0) -% t_start; - const elapsed_cy = soc.cycles() - c_start; - soc.rom.print("MARK CPU_HZ cycles=%u us=%u khz=%u\r\n", .{ - @as(u32, @intCast(elapsed_cy)), - @as(u32, @intCast(elapsed_us)), - @as(u32, @intCast(if (elapsed_us > 0) elapsed_cy * 1000 / elapsed_us else 0)), - }); - } - soc.rom.print("MARK PARDES_READY\r\n", .{}); - - var in: [256]u8 = undefined; - while (!pardes_esp32p4_quit()) { - // ATTRIBUTION. The host can time a keystroke's round trip but cannot see what the firmware - // spent it on, and the two candidates - parsing and editing, versus rendering - want - // opposite fixes. `soc.cycles()` is the unprivileged cycle counter, so this costs two CSR - // reads per phase and quantises at one cycle, which is four orders of magnitude below the - // milliseconds being attributed. Gated on `prof` so the shipping build carries none of it. - const n = uart.read(&in); - rx_total +%= @intCast(n); - - var input_cy: u64 = 0; - if (n > 0) { - const t0 = if (prof) soc.cycles() else 0; - // IN CHUNKS, rescuing the receiver between them. Applying a keystroke is not free and - // gets dearer as the line grows - measured at 44 us on an empty line and 63 us at 640 - // characters - so handing over a full 128-byte batch is up to 8 ms in which nothing - // drains the receiver, against a FIFO that holds only 11 ms of wire. A 600-byte paste - // lost 93 bytes to exactly that window even with the transmitter's own rescue in place. - // - // Splitting a burst at an arbitrary byte is safe: `pardes_esp32p4_input` keeps whatever it - // could not parse, which is how it already survives an escape sequence split across two - // UART reads. One render still happens per loop iteration, so this costs no extra wire. - var off: usize = 0; - while (off < n) { - const chunk = @min(input_chunk, n - off); - pardes_esp32p4_input(in[off..].ptr, chunk); - off += chunk; - if (off < n) uart.rescueNow(); - } - if (prof) input_cy = soc.cycles() - t0; - } - - pardes_esp32p4_tick(nowMs()); - - // Only when there is something to show. On a link this slow an unconditional repaint per - // iteration would saturate the wire and starve input. - if (pardes_esp32p4_wants_frame()) { - const t0 = if (prof) soc.cycles() else 0; - const err = pardes_esp32p4_render(); - if (err != 0) soc.rom.print("MARK PARDES_RENDER_FAIL rc=%u\r\n", .{err}); - if (prof) { - const render_cy = soc.cycles() - t0; - // A SECOND render with nothing changed since the first. It splits the cost in two: - // whatever this still costs is the price of walking and diffing the whole editor - // state, paid regardless of output, while the difference between the two is the - // price of the change itself. `wants_frame` is false now, so this only happens - // under -Dprof and never on a shipping build. - const t1 = soc.cycles(); - _ = pardes_esp32p4_render(); - const idle_cy = soc.cycles() - t1; - // Reported in cycles, not microseconds: the divisor is the CPU clock, which this - // firmware does not set and has only ever measured, so converting here would bake a - // guess into the data. The toolchain's `experiments/` divides by the clock it - // measured. - var copy_cy: u64 = 0; - var vx_cy: u64 = 0; - var flush_cy: u64 = 0; - pardes_esp32p4_frame_prof(©_cy, &vx_cy, &flush_cy); - soc.rom.print("PROF in=%u render=%u idle=%u copy=%u vaxis=%u flush=%u rx=%u rxdrop=%u txdrop=%u\r\n", .{ - @as(u32, @intCast(input_cy)), - @as(u32, @intCast(render_cy)), - @as(u32, @intCast(idle_cy)), - @as(u32, @intCast(copy_cy)), - @as(u32, @intCast(vx_cy)), - @as(u32, @intCast(flush_cy)), - rx_total, - uart.inputDropped(), - uart.dropped, - }); - } - } - } - - soc.rom.print("\r\nMARK PARDES_QUIT\r\n", .{}); - while (true) {} -} - -// ------------------------------------------------------------------------------------ the trap - -/// A trap handler, because the absence of one is why this port has been guessing. -/// -/// The mask ROM prints "Guru Meditation" for a trap only while ITS handler is still installed; -/// anything this image does that replaces or outgrows that path fails silently instead, and a silent -/// fault is indistinguishable from an infinite loop over a serial line. This one reports the three -/// registers that name the fault and then stops, using the direct-FIFO writer so it shares nothing -/// with the editor's buffered output. -/// -/// `mtvec` is set in DIRECT mode (low two bits zero), so every trap and every interrupt lands on -/// `trapEntry` regardless of cause - which is what a diagnostic wants. -export fn trapEntry() linksection(".text.entry") callconv(.naked) noreturn { - asm volatile ("j trapReport"); -} - -export fn trapReport() noreturn { - const mcause = asm volatile ("csrr %[o], mcause" - : [o] "=r" (-> u32), - ); - const mepc = asm volatile ("csrr %[o], mepc" - : [o] "=r" (-> u32), - ); - const mtval = asm volatile ("csrr %[o], mtval" - : [o] "=r" (-> u32), - ); - uart.write("\r\nMARK TRAP mcause="); - uart.dumpWord(mcause); - uart.write("MARK TRAP mepc="); - uart.dumpWord(mepc); - uart.write("MARK TRAP mtval="); - uart.dumpWord(mtval); - uart.write("MARK TRAP dropped="); - uart.dumpWord(uart.dropped); - while (true) {} -} - -// --------------------------------------------------------------------------- the root's own duties -// -// These are the FIRMWARE root's declarations, and they are not the same set as `src/esp32p4.zig`'s: that -// file is the root of its own object and carries its own `std_options` and `panic` for the core's -// half of the image. Two roots, two instantiations of std, one per compilation unit - which is -// exactly what the object seam buys, and why a panic in the core prints `PARDES_CORE_PANIC` through -// the write callback while a panic here prints `PARDES_PANIC` through the mask ROM. - -/// `page_size_min`/`max`: the board has no MMU and no pages, but std derives allocator alignment -/// from these. 4 KiB is the ESP32-P4's cache and DMA granularity. -/// -/// `logFn` is not cosmetic. std's default log implementation reaches `std.debug_io`, which -/// instantiates `std.Io.Threaded` - a thread pool, `getrandom`, `IOV_MAX`, `mremap` - none of which -/// exist here, and one `log.warn` from anywhere is enough to drag all of it into the image. -pub const std_options: std.Options = .{ - .page_size_min = 4096, - .page_size_max = 4096, - .logFn = logFn, -}; - -fn logFn( - comptime level: std.log.Level, - comptime scope: @EnumLiteral(), - comptime fmt: []const u8, - args: anytype, -) void { - var buf: [256]u8 = undefined; - const line = std.fmt.bufPrint(&buf, "\r\n[" ++ level.asText() ++ "/" ++ @tagName(scope) ++ "] " ++ fmt ++ "\r\n", args) catch - "\r\n[log overflow]\r\n"; - uart.write(line); -} - -pub const panic = std.debug.FullPanic(panicImpl); - -fn panicImpl(msg: []const u8, first_trace_addr: ?usize) noreturn { - // The fixed text goes out through the ROM deliberately: a panic may BE the console writer - // failing, and `ets_printf` shares nothing with `uart.write` except the FIFO itself. - // - // The MESSAGE does not, and that is a correction rather than a preference. `msg` is a Zig SLICE - // and `%s` reads until a NUL, so handing `msg.ptr` to printf prints the message and then - // whatever happens to sit after it in memory until a zero byte turns up. Literals get away with - // it; std's own panics do not, because they are formatted into a buffer - "index out of bounds: - // index 5, len 3" - and carry no terminator. `uart.write` takes a length. - soc.rom.print("\r\nMARK PARDES_PANIC ", .{}); - uart.write(msg); - // The address is what makes it actionable: addr2line against the ELF in zig-out turns it into a - // source line, and without it a panic message names a KIND of failure with no way to find which - // one of them happened. Zero when the caller had no return address to give. - soc.rom.print("\r\nMARK PARDES_PANIC_AT 0x%08x\r\n", .{@as(u32, @truncate(first_trace_addr orelse 0))}); - while (true) {} -} - -/// Reset entry. The bootloader hands over with an unspecified stack pointer and the FPU off, so: -/// enable the F extension (`mstatus.FS`, which ESP-IDF only ever turns on lazily from a trap handler -/// this image does not have), establish a stack, clear `.bss`, and call into Zig. -/// -/// The cache invalidate that this image also needs is the FIRST thing `zig_main` does, not something -/// done here. Hand-written `la t0, Cache_Invalidate_All` against an absolute linker symbol computed -/// a PC-relative target and jumped into nowhere (measured: PC=0x88b5d788 with the argument stranded -/// in a2); Zig generates the addressing for an `extern fn` correctly, and `zig_main` runs before any -/// `.rodata` is touched anyway. -export fn _start() linksection(".text.entry") callconv(.naked) noreturn { - asm volatile ( - \\ li t0, 1 << 13 - \\ csrs mstatus, t0 - \\ la sp, __stack_top - \\ mv fp, sp - \\ la t0, trapEntry - \\ csrw mtvec, t0 - \\ la t0, __bss_start - \\ la t1, __bss_end - \\ bgeu t0, t1, 2f - \\1: - \\ sw zero, 0(t0) - \\ addi t0, t0, 4 - \\ bltu t0, t1, 1b - \\2: - \\ j zig_main - ); -} diff --git a/src/esp32p4/input_rescue.zig b/src/esp32p4/input_rescue.zig deleted file mode 100644 index d7556d46..00000000 --- a/src/esp32p4/input_rescue.zig +++ /dev/null @@ -1,272 +0,0 @@ -//! Keystrokes rescued from the receive FIFO while the transmitter is busy. -//! -//! THE BUG THIS EXISTS FOR. The firmware's loop is read, apply, render, write, and the write blocks -//! while the transmit FIFO is full - real backpressure, because dropping half an escape sequence -//! would leave the host terminal in the wrong colour for the rest of the session. But nothing -//! drained the RECEIVE FIFO during that wait, and the FIFO is 128 bytes (the toolchain package's -//! `src/hal/uart.zig:52`). A frame of 240 bytes is 21 ms of wire at 115200, and 21 ms of a host -//! sending at line rate is ~240 bytes, so everything past the 128th was silently gone. -//! -//! Measured on the die before the fix, typing a burst in one host write and counting what the editor -//! actually held: 128 bytes arrived intact, 200 bytes lost 88, 300 bytes lost all 300. From a -//! keyboard that is a keystroke that never lands, and it looks like a stuck key - the screen is -//! behind what was typed, and typing more appears to fix it because a later frame repaints the cells -//! the lost keystrokes would have changed. -//! -//! WHY THE POLICY LIVES HERE and not in `uart.zig`: the interesting part is a decision - drain the -//! receiver while spinning on the transmitter, and what to do when even that overflows - and the -//! decision is worth testing. `uart.zig` cannot be tested at all without the chip, because every -//! line of it is an MMIO access. `pump` takes the port as `anytype`, so the same code runs against -//! the real UART on the board and against a fake with a two-byte FIFO on the host. -//! -//! WHY IT IS IN THIS REPOSITORY. It was written in the toolchain repository, next to the UART it -//! spins on, and it moved here because every number in it is the EDITOR's. 4 KiB is sized against -//! the ~1.4 KB full repaint `src/esp32p4.zig` emits; "drop the newest, so what survives is a PREFIX of -//! what was typed" is a statement about documents rather than about UARTs, and it is the editor that -//! would otherwise appear to invent input. A policy whose every constant comes from one application -//! belongs beside that application. -//! -//! It expects NOTHING from the toolchain package - no module, no register, no target. `std` is the -//! whole import list, which is what makes the host tests at the bottom possible and what lets the -//! same source compile for riscv32-freestanding and for the host unchanged. -//! -//! ONE COPY, TWO BUILDS. This file is the only copy; the toolchain repository's is gone. Its build -//! reads this tree across a sibling-relative seam in exactly one place: `zig build selftest` hands -//! this path over as the `input_rescue` module of its on-die root (`05-zig-p4/build.zig:434-435`, -//! the module at `:453`). The editor's own application root needs no such wiring - `app.zig` reads -//! the policy through the `uart.zig` beside it, which imports this file as its sibling - and the -//! toolchain deliberately registers no module for it, because zig hashes every registered module's -//! root source on every compile, so registering one that a root does not use breaks every build in -//! a checkout without this tree. `-Dapp` still defaults under `-Dpardes` to -//! `../02-pardes-code/src/esp32p4/app.zig` (`:168-169`). -//! -//! Host checks run under `zig build unit-test` here. In `../05-zig-p4`, -//! `zig build selftest` flashes and runs the on-die checks against UART0. - -const std = @import("std"); - -/// Capacity, sized for the worst frame this editor emits. -/// -/// A full repaint is ~1.4 KB, which is 121 ms of wire at 115200, and 121 ms of a host pasting at -/// line rate is ~1.4 KB of input. 4 KiB is that with headroom, a power of two so the wrap is a mask -/// rather than a division, and nothing at all against the board's RAM. -pub const capacity = 4096; - -/// A byte queue that drops the NEWEST byte when full. -/// -/// Dropping the newest rather than the oldest is deliberate: what survives is then a PREFIX of what -/// was typed. An editor that loses the end of a paste has done something a person can see and -/// correct; one that silently reorders keystrokes, or keeps the tail and discards the head, has -/// corrupted the document in a way that looks like the editor inventing input. -pub const Ring = struct { - buf: [capacity]u8 = undefined, - head: usize = 0, - len: usize = 0, - /// Bytes lost because even this overflowed. Nonzero means input was dropped; it is the honest - /// version of the bug rather than a cure for it. - dropped: u32 = 0, - - const mask = capacity - 1; - - comptime { - std.debug.assert(capacity & mask == 0); - } - - pub fn push(r: *Ring, b: u8) void { - if (r.len == capacity) { - r.dropped +%= 1; - return; - } - r.buf[(r.head + r.len) & mask] = b; - r.len += 1; - } - - /// Move as much as fits into `out`, oldest first. Returns the count. - pub fn pop(r: *Ring, out: []u8) usize { - const n = @min(out.len, r.len); - for (out[0..n]) |*slot| { - slot.* = r.buf[r.head]; - r.head = (r.head + 1) & mask; - } - r.len -= n; - return n; - } - - pub fn clear(r: *Ring) void { - r.head = 0; - r.len = 0; - } -}; - -/// Drain everything the port has received into `ring`, without waiting. -pub fn rescue(port: anytype, ring: *Ring) void { - var waiting = port.rxCount(); - while (waiting > 0) : (waiting -= 1) ring.push(port.popByte()); -} - -/// Push `bytes` through `port`, rescuing input whenever the transmitter has no room. Returns the -/// number of bytes abandoned because the transmitter stopped making progress altogether. -/// -/// The spin bound is why this returns a count rather than blocking forever: a UART whose core clock -/// has been gated never makes progress, and on a board with no debugger an infinite spin is -/// indistinguishable from a crash. A bounded wait turns that into visibly dropped output plus a -/// counter, which is a diagnosis instead of a mystery. -pub fn pump(port: anytype, ring: *Ring, bytes: []const u8, spin_limit: u32) u32 { - var rest = bytes; - while (rest.len > 0) { - // One status read per burst, not per byte: reading `txFree` once and pushing that many cuts - // the status reads by up to the FIFO depth. - var room = port.txFree(); - var spins: u32 = 0; - while (room == 0) { - // THE FIX. Every iteration of this wait is time the receiver is filling up, and this is - // the only place that can empty it. - rescue(port, ring); - spins += 1; - if (spins > spin_limit) return @intCast(rest.len); - room = port.txFree(); - } - const n = @min(room, rest.len); - for (rest[0..n]) |b| port.pushByte(b); - rest = rest[n..]; - } - return 0; -} - -// ------------------------------------------------------------------------------------ host tests - -test "the ring hands bytes back in order" { - var r: Ring = .{}; - for ("hello") |b| r.push(b); - var out: [8]u8 = undefined; - try std.testing.expectEqual(@as(usize, 5), r.pop(&out)); - try std.testing.expectEqualStrings("hello", out[0..5]); - try std.testing.expectEqual(@as(usize, 0), r.pop(&out)); -} - -test "the ring wraps without reordering" { - var r: Ring = .{}; - var out: [capacity]u8 = undefined; - // Push and pop most of the buffer so head sits near the end, then straddle the wrap. - for (0..capacity - 3) |i| r.push(@intCast(i & 0xff)); - _ = r.pop(out[0 .. capacity - 3]); - for ("straddle") |b| r.push(b); - const n = r.pop(&out); - try std.testing.expectEqualStrings("straddle", out[0..n]); -} - -test "a full ring drops the newest and says so" { - var r: Ring = .{}; - for (0..capacity) |i| r.push(@intCast(i & 0xff)); - try std.testing.expectEqual(@as(u32, 0), r.dropped); - r.push('!'); - r.push('!'); - try std.testing.expectEqual(@as(u32, 2), r.dropped); - // The head is intact: what survived is a prefix of what arrived. - var out: [4]u8 = undefined; - _ = r.pop(&out); - try std.testing.expectEqual(@as(u8, 0), out[0]); - try std.testing.expectEqual(@as(u8, 1), out[1]); -} - -/// A UART with a small transmit FIFO, a small RECEIVE FIFO, and a host that keeps typing into it. -/// -/// The receive FIFO is the part that matters and it is modelled the way the hardware behaves: it has -/// a fixed depth, and a byte that arrives when it is full is *gone*. That is the whole bug. -/// -/// Time advances on each transmitter status read, which is what `pump` does while it waits. The -/// transmitter frees a byte only every fourth tick while a typed byte lands on every one: the -/// transmitter therefore genuinely FILLS, which is the condition the bug needs. A fake whose FIFO -/// drains as fast as it fills never blocks, so `pump` never waits, so the rescue never runs and the -/// test proves nothing - the first version of this fake had exactly that flaw. -const FakePort = struct { - tx_cap: u32, - tx_used: u32 = 0, - sent: std.ArrayList(u8) = .empty, - gpa: std.mem.Allocator, - - incoming: []const u8, - delivered: usize = 0, - rx: [rx_depth]u8 = undefined, - rx_head: usize = 0, - rx_len: usize = 0, - /// Bytes the wire delivered into a full receive FIFO. The hardware has no counter for this, - /// which is exactly why the bug was invisible. - lost: u32 = 0, - - ticks: u32 = 0, - - const rx_depth = 8; - const tx_drain_every = 4; - - fn tick(p: *FakePort) void { - p.ticks += 1; - if (p.ticks % tx_drain_every == 0 and p.tx_used > 0) p.tx_used -= 1; - if (p.delivered < p.incoming.len) { - const b = p.incoming[p.delivered]; - p.delivered += 1; - if (p.rx_len == rx_depth) { - p.lost += 1; - } else { - p.rx[(p.rx_head + p.rx_len) % rx_depth] = b; - p.rx_len += 1; - } - } - } - - fn txFree(p: *FakePort) u32 { - p.tick(); - return p.tx_cap - p.tx_used; - } - - fn pushByte(p: *FakePort, b: u8) void { - p.sent.append(p.gpa, b) catch unreachable; - p.tx_used += 1; - } - - fn rxCount(p: *FakePort) u32 { - return @intCast(p.rx_len); - } - - fn popByte(p: *FakePort) u8 { - const b = p.rx[p.rx_head]; - p.rx_head = (p.rx_head + 1) % rx_depth; - p.rx_len -= 1; - return b; - } -}; - -test "a long transmit does not lose the input that arrives during it" { - // THE REGRESSION. Delete the `rescue` call inside `pump`'s wait and this fails: the receive FIFO - // is eight bytes deep, the typing below is far longer than that, and every byte that arrives - // into a full FIFO is gone with nothing to record it. That is the die's 88-of-200 in miniature. - const typed = "the quick brown fox jumps over the lazy dog, twice over, and then some more"; - var port: FakePort = .{ .tx_cap = 2, .incoming = typed, .gpa = std.testing.allocator }; - defer port.sent.deinit(std.testing.allocator); - var ring: Ring = .{}; - - const frame = "\x1b[1;1H" ++ &@as([400]u8, @splat('x')); - try std.testing.expectEqual(@as(u32, 0), pump(&port, &ring, frame, 1_000_000)); - - // Every output byte went out, in order. - try std.testing.expectEqualStrings(frame, port.sent.items); - // Nothing the wire delivered was dropped, by the FIFO or by the ring. - try std.testing.expectEqual(@as(u32, 0), port.lost); - try std.testing.expectEqual(@as(u32, 0), ring.dropped); - // And what was rescued, plus whatever is still sitting in the FIFO, is exactly what was typed - - // in order, which is the other half of the contract. - var got: [capacity]u8 = undefined; - var n = ring.pop(&got); - while (port.rxCount() > 0) : (n += 1) got[n] = port.popByte(); - try std.testing.expectEqualStrings(typed[0..port.delivered], got[0..n]); - try std.testing.expect(port.delivered == typed.len); -} - -test "a transmitter that never drains gives up and reports what it abandoned" { - var port: FakePort = .{ .tx_cap = 0, .incoming = "", .gpa = std.testing.allocator }; - defer port.sent.deinit(std.testing.allocator); - var ring: Ring = .{}; - // tx_cap 0 means txFree is always 0, so no byte can ever go out. - try std.testing.expectEqual(@as(u32, 5), pump(&port, &ring, "abcde", 32)); - try std.testing.expectEqual(@as(usize, 0), port.sent.items.len); -} diff --git a/src/esp32p4/selftest.zig b/src/esp32p4/selftest.zig deleted file mode 100644 index 19b71e90..00000000 --- a/src/esp32p4/selftest.zig +++ /dev/null @@ -1,347 +0,0 @@ -//! pardes's own test suite for the ESP32-P4, which runs ON THE DIE. -//! -//! WHY THIS EXISTS. Every serious bug this port has produced was invisible to a host test, and two -//! of them were invisible for months. `std.mem.eql` compares a byte at a time on this target and -//! several times faster on the host, so the firmware's largest read was three times slower than it -//! needed to be and nothing on a laptop could tell. A lone ESC resolves to the Escape key, which is -//! right when a kernel hands over a whole escape sequence and wrong when a 115200 line hands over -//! one byte every 87 microseconds. A full transmit FIFO stopped anything draining the receiver, and -//! the FIFO depth is a hardware number. None of those is a logic error you can reason your way to -//! from a host: they are properties of THIS chip, THIS clock and THIS wire. -//! -//! So the checks below are chosen by one rule: a check belongs here only if the die can answer it -//! and a host cannot. Anything that is pure logic - the ring's wrap-around, the mouse coalescer's -//! ordering - already has a deterministic host test in `zig build unit-test`, which is faster, needs -//! no hardware, and is where such a thing belongs. Duplicating those here would make this suite -//! longer and no stronger. -//! -//! ## Why the suite is in the editor's repository -//! -//! It was written in the `05-zig-p4` toolchain repository as `examples/selftest.zig`, and it was -//! never an example of anything. Re-read the paragraph above: every claim it makes is a claim about -//! THIS program on this board. The word-at-a-time `std.mem.eql` it measures against is the reason -//! the editor's frame diff compares rows a `u32` at a time; the lone-ESC decode and the -//! transmit-FIFO backpressure are `input_rescue.zig`, a sibling file in this directory; the heap -//! span and the allocator churn are what decide how large a grid this board can drive; and the -//! clock check is the divisor under every `-Dprof` cycle count the editor reports. A suite that -//! specific to one application belongs beside it, so that changing a source and changing the check -//! which defends it are one diff in one repository rather than two commits in two trees. -//! -//! What stayed behind in the toolchain is the half that is about the CHIP: the image builder's rules, -//! the register layer's field arithmetic, the console bridge's escape matcher. Those still run under -//! `zig build test` over there and need no board. -//! -//! ## What it expects from the toolchain package -//! -//! Four of its modules and no more: `soc` (mask-ROM printf, the cycle counter), `hal` (UART0, the -//! systimer, clock/reset), `config` (this build's `cpu_mhz`) and `heap` (the coalescing allocator). -//! The sibling `05-zig-p4` build supplies these modules and the firmware image tooling. -//! -//! `input_rescue` is the fifth import and is NOT that package's: it is the sibling file in this -//! directory, handed over as a named MODULE rather than imported as a path. Deliberately so - the -//! `pub` on `FakePort`'s methods below is what lets that module reach them by duck typing across the -//! boundary. The toolchain's `selftest` step wires this root and that module together. -//! -//! Not a `zig test` binary, deliberately. Zig's test runner wants an OS, and `std.testing.allocator` -//! is a debug allocator over the page allocator, which on freestanding is either a compile error or -//! a lie. A hand-rolled harness is thirty lines and answers to nobody. -//! -//! From `../05-zig-p4`, `zig build selftest` flashes and runs this suite on hardware. - -const std = @import("std"); -const soc = @import("soc"); -const hal = @import("hal"); -const config = @import("config"); -const heapmod = @import("heap"); -const input_rescue = @import("input_rescue"); - -/// Reset entry. Identical in shape to `src/main.zig`'s and for the same reasons: the bootloader hands -/// over with an unspecified stack pointer and the FPU off, so set `mstatus.FS`, establish a stack, -/// clear `.bss`, and jump. -/// -/// Leaving this out is what made the first draft of this file unbuildable, and the failure said -/// nothing useful: `-fentry=_start` found no such symbol, `--gc-sections` then discarded every -/// function as unreachable, and the image builder reported `NotTwoMappedSegments` because -/// `.flash.text` had nothing left in it. `zig build layout` now prints `entry 0x0` for exactly that, -/// which is the same diagnosis in one line. -export fn _start() linksection(".text.entry") callconv(.naked) noreturn { - asm volatile ( - \\ li t0, 1 << 13 - \\ csrs mstatus, t0 - \\ la sp, __stack_top - \\ mv fp, sp - \\ la t0, __bss_start - \\ la t1, __bss_end - \\ bgeu t0, t1, 2f - \\1: - \\ sw zero, 0(t0) - \\ addi t0, t0, 4 - \\ bltu t0, t1, 1b - \\2: - \\ j zig_main - ); -} - -pub const panic = std.debug.FullPanic(struct { - fn call(msg: []const u8, first_trace_addr: ?usize) noreturn { - // `msg` is a slice and carries no terminator - std's own panics are formatted into a buffer - - // so it goes out with a length rather than through a `%s` that would read past the end of it. - soc.rom.print("\r\nMARK SELFTEST_PANIC at 0x%08x: ", .{@as(u32, @truncate(first_trace_addr orelse 0))}); - hal.uart.Uart.init(0).write(msg); - // A panic is a FAILED RUN, and the host is watching for the summary line. Without this the - // run looks like a board that never answered, which is a different diagnosis entirely. - soc.rom.print("\r\nMARK SELFTEST DONE pass=%u fail=%u\r\n", .{ passed, failed + 1 }); - while (true) {} - } -}.call); - -var passed: u32 = 0; -var failed: u32 = 0; - -/// One claim about the silicon. Printed either way: a suite that only speaks up when it fails gives -/// no way to tell "all good" from "never ran", and on a board that difference matters. -fn check(name: [*:0]const u8, ok: bool) void { - if (ok) { - passed += 1; - soc.rom.print("MARK SELFTEST ok %s\r\n", .{name}); - } else { - failed += 1; - soc.rom.print("MARK SELFTEST FAIL %s\r\n", .{name}); - } -} - -/// Word-at-a-time equality, the same shape the editor's frame diff uses. -fn sameBytesWordwise(a: []const u8, b: []const u8) bool { - if (a.len != b.len) return false; - if ((@intFromPtr(a.ptr) | @intFromPtr(b.ptr)) & 3 == 0) { - const n = a.len / 4; - const wa: [*]align(4) const u32 = @ptrCast(@alignCast(a.ptr)); - const wb: [*]align(4) const u32 = @ptrCast(@alignCast(b.ptr)); - for (wa[0..n], wb[0..n]) |x, y| { - if (x != y) return false; - } - return std.mem.eql(u8, a[n * 4 ..], b[n * 4 ..]); - } - return std.mem.eql(u8, a, b); -} - -/// A UART with a receive FIFO that loses whatever arrives into a full one, as the hardware does. -/// `pub` on the methods because `input_rescue` is a separate module here and reaches them by duck -/// typing across it. -const FakePort = struct { - tx_cap: u32, - tx_used: u32 = 0, - ticks: u32 = 0, - sent: u32 = 0, - incoming: []const u8, - delivered: usize = 0, - rx: [8]u8 = undefined, - rx_head: usize = 0, - rx_len: usize = 0, - lost: u32 = 0, - - fn tick(p: *FakePort) void { - p.ticks += 1; - if (p.ticks % 4 == 0 and p.tx_used > 0) p.tx_used -= 1; - if (p.delivered < p.incoming.len) { - const byte = p.incoming[p.delivered]; - p.delivered += 1; - if (p.rx_len == p.rx.len) { - p.lost += 1; - } else { - p.rx[(p.rx_head + p.rx_len) % p.rx.len] = byte; - p.rx_len += 1; - } - } - } - pub fn txFree(p: *FakePort) u32 { - p.tick(); - return p.tx_cap - p.tx_used; - } - pub fn pushByte(p: *FakePort, _: u8) void { - p.sent += 1; - p.tx_used += 1; - } - pub fn rxCount(p: *FakePort) u32 { - return @intCast(p.rx_len); - } - pub fn popByte(p: *FakePort) u8 { - const byte = p.rx[p.rx_head]; - p.rx_head = (p.rx_head + 1) % p.rx.len; - p.rx_len -= 1; - return byte; - } -}; - -/// Backing store for the heap checks. Static, because the point is to exercise the allocator on real -/// L2MEM rather than to find out where a stack array happens to land. -var heap_area: [64 * 1024]u8 align(16) = undefined; - -export fn zig_main() noreturn { - // THE CLOCK RAISE, performed here rather than assumed, which is what turns the frequency check - // at the end into a test of `setCpuFreq` instead of a tautology. The first version of this file - // read `config.cpu_mhz` and compared the die against it without ever setting it, so - // `-Dcpu-mhz=360` failed with `khz=90001 want=360000` - the check was right and the expectation - // was wrong. Same call, and the same order, as `src/esp32p4/app.zig`. - if (config.cpu_mhz != 90) hal.clkrst.setCpuFreq(switch (config.cpu_mhz) { - 360 => .mhz360, - else => .mhz90, - }); - hal.systimer.init(); - - soc.rom.print("\r\nMARK SELFTEST_START cpu_mhz=%u\r\n", .{@as(u32, config.cpu_mhz)}); - - // ------------------------------------------------ 1. the memory model the memory words assume - // - // `Peek`, `Poke` and `Hexdump` reach the bus through `*allowzero volatile` pointers and refuse an - // unaligned word. Both halves are claims about this core, and neither is checkable on a host. - { - const cell: *volatile u32 = @ptrCast(@alignCast(&heap_area[0])); - cell.* = 0xdeadbeef; - check("an aligned word round-trips through a volatile pointer", cell.* == 0xdeadbeef); - - // Every byte offset in a word, readable and writable: this is what `Hexdump` does, and it is - // why `Hexdump` needs no alignment while `Peek` does. - var all_offsets_ok = true; - for (0..4) |i| { - const at: *volatile u8 = @ptrCast(&heap_area[16 + i]); - at.* = @intCast(0xa0 + i); - if (at.* != 0xa0 + @as(u8, @intCast(i))) all_offsets_ok = false; - } - check("a byte at every offset in a word round-trips", all_offsets_ok); - - // THE VOLATILE PROMISE. Two reads of a running counter must be two reads. Were the optimiser - // allowed to fold them, `Peek` would print one value twice for a register that had changed, - // which is the one thing a memory word must never do. - const first = hal.systimer.micros(.unit0) orelse 0; - var spin: u32 = 0; - while (spin < 4000) : (spin += 1) asm volatile ("" ::: .{ .memory = true }); - const second = hal.systimer.micros(.unit0) orelse 0; - check("two reads of a live counter are two reads", second != first); - check("and that counter runs forwards", second > first); - } - - // --------------------------------------- 2. word-wise equality, on THIS instruction set - // - // The editor's frame diff compares rows a `u32` at a time because `std.mem.eql` compares a byte - // at a time here: 223 us against 66 for the same answer. "The same answer" is the part that has - // to hold on the target rather than on the host, so it is checked against `std.mem.eql` itself, - // at every difference position, at both alignments, and at lengths that are not multiples of 4. - { - var a: [64]u8 align(4) = undefined; - var b: [64]u8 align(4) = undefined; - for (&a, 0..) |*slot, i| slot.* = @intCast(i); - @memcpy(&b, &a); - - var agree = true; - for (0..a.len) |len| { - if (sameBytesWordwise(a[0..len], b[0..len]) != std.mem.eql(u8, a[0..len], b[0..len])) agree = false; - } - check("aligned equality agrees with std.mem.eql at every length", agree); - - agree = true; - for (0..a.len) |i| { - b[i] ^= 0xff; - if (sameBytesWordwise(&a, &b) != std.mem.eql(u8, &a, &b)) agree = false; - if (sameBytesWordwise(a[0..33], b[0..33]) != std.mem.eql(u8, a[0..33], b[0..33])) agree = false; - b[i] ^= 0xff; - } - check("a difference at any position is found, as std.mem.eql finds it", agree); - - agree = true; - // UNALIGNED, which is why `sameBytes` tests alignment at RUNTIME: `Cell` is all u8 fields, so - // whether a row starts on a word boundary belongs to the allocator and not to the type. - for (1..4) |off| { - const ua = a[off..]; - const ub = b[off..]; - if (sameBytesWordwise(ua, ub) != std.mem.eql(u8, ua, ub)) agree = false; - b[off + 5] ^= 0xff; - if (sameBytesWordwise(ua, ub) != std.mem.eql(u8, ua, ub)) agree = false; - b[off + 5] ^= 0xff; - } - check("unaligned spans fall back and still agree", agree); - } - - // ------------------------------------------------- 3. the rescue, on the real codegen - // - // The logic has a host test. What that cannot say is whether it behaves the same compiled for - // this core at this optimisation level, which is a question only a board answers. - { - const typed = "the quick brown fox jumps over the lazy dog, and then some more besides"; - var port: FakePort = .{ .tx_cap = 2, .incoming = typed }; - var ring: input_rescue.Ring = .{}; - const frame = "\x1b[1;1H" ++ &@as([300]u8, @splat('x')); - const abandoned = input_rescue.pump(&port, &ring, frame, 1_000_000); - - check("the frame went out whole", abandoned == 0 and port.sent == frame.len); - check("the receive FIFO never overflowed", port.lost == 0); - check("the ring dropped nothing", ring.dropped == 0); - - var got: [128]u8 = undefined; - var n = ring.pop(&got); - while (port.rxCount() > 0 and n < got.len) : (n += 1) got[n] = port.popByte(); - check("every rescued byte, in order", n == typed.len and std.mem.eql(u8, got[0..n], typed)); - } - - // --------------------------------------------------- 4. the allocator on real L2MEM - // - // The editor's whole geometry ceiling is an allocator question, and this is the allocator, on the - // memory it actually runs in rather than on a host's malloc. - { - var h = heapmod.Heap.init(heap_area[0..]); - const gpa = h.allocator(); - - const one = gpa.alloc(u32, 256) catch null; - check("a modest allocation succeeds", one != null); - if (one) |slice| { - check("and is aligned for its element", @intFromPtr(slice.ptr) % @alignOf(u32) == 0); - for (slice, 0..) |*slot, i| slot.* = @intCast(i * 7); - var intact = true; - for (slice, 0..) |slot, i| { - if (slot != i * 7) intact = false; - } - check("and holds what was written to it", intact); - gpa.free(slice); - } - - // FREE THEN REUSE. A heap that cannot hand the same bytes back is a heap that runs out, which - // on this board is the difference between a 40x12 grid and an 80x24 one. - var churn_ok = true; - for (0..64) |_| { - const block = gpa.alloc(u8, 1024) catch { - churn_ok = false; - break; - }; - gpa.free(block); - } - check("a kilobyte can be taken and returned repeatedly", churn_ok); - - // AND IT REFUSES CLEANLY. An allocator that returns garbage instead of an error when it is - // out is the failure mode that cost an afternoon during bring-up. - const absurd = gpa.alloc(u8, heap_area.len * 4); - check("an impossible allocation returns an error", absurd == error.OutOfMemory); - } - - // ------------------------------------------ 5. the clock, which everything divides by - // - // Every cycle count this firmware reports is divided by the configured frequency somewhere, and - // the systimer is clocked from the crystal rather than from the CPU - which is exactly what makes - // it a reference the CPU cannot flatter. The 90-to-360 MHz raise rested on this comparison. - { - const t0 = hal.systimer.micros(.unit0) orelse 0; - const c0 = soc.cycles(); - while ((hal.systimer.micros(.unit0) orelse 0) -% t0 < 20_000) {} - const us = (hal.systimer.micros(.unit0) orelse 0) -% t0; - const cy = soc.cycles() - c0; - const khz: u32 = if (us > 0) @intCast(cy * 1000 / us) else 0; - const want: u32 = @as(u32, config.cpu_mhz) * 1000; - // Two percent: far wider than either clock's error, far narrower than the 4x a wrong divider - // would produce. - const slack = want / 50; - soc.rom.print("MARK SELFTEST_CLOCK khz=%u want=%u\r\n", .{ khz, want }); - check("the cycle counter and the systimer agree on the CPU frequency", khz > want - slack and khz < want + slack); - } - - soc.rom.print("MARK SELFTEST DONE pass=%u fail=%u\r\n", .{ passed, failed }); - while (true) {} -} diff --git a/src/esp32p4/uart.zig b/src/esp32p4/uart.zig deleted file mode 100644 index a185737d..00000000 --- a/src/esp32p4/uart.zig +++ /dev/null @@ -1,190 +0,0 @@ -//! UART0 transport for the editor and standalone GPIO 9P firmware. -//! -//! This is the whole of the firmware's I/O. There is no framebuffer and no keyboard; the board -//! emits ANSI and consumes ANSI, and the terminal emulator on the far end of the CH340 does the -//! rest of the work - including answering the editor's own capability queries, which travel down -//! this wire like any other bytes. -//! -//! WHY IT IS IN THIS REPOSITORY. It is not a UART driver - that is `hal.uart`, which stays in the -//! toolchain package and is checked against ESP-IDF's own headers by `zig build diff` there. This is -//! the EDITOR's use of one: which instance the console is, that the transmitter is real -//! backpressure because a truncated escape sequence corrupts the host terminal, that rescued -//! keystrokes must come out before FIFO ones, and that the first thing to do at startup is discard -//! the host bridge's synthetic resize report. Every one of those is a statement about the editor, so -//! the file moved to sit beside it. See `app.zig`'s header for the boundary in full. -//! -//! What it expects from the toolchain package is exactly one module: `hal`, for `hal.uart.Uart`. -//! Nothing else here reaches the chip. The sibling `input_rescue.zig` is a plain file, not a module, -//! because it is this repository's own policy. -//! -//! Deliberately not a `std.Io.Writer`. The ANSI encoding lives on the other side of the C ABI, next -//! to the vaxis that produces it (see `app.zig` for why the seam is there and not elsewhere), so -//! what crosses into this file is already a finished run of bytes. A writer here would be a second -//! buffer in front of one that already exists. -//! -//! Two decisions worth stating, because both are measurements rather than preferences. -//! -//! **Batched FIFO access.** The naive push is `while (txFree() == 0) {}` then `pushByte`, once per -//! byte: one MMIO read per byte at best, many while the FIFO is full. Reading `txFree` once and -//! then pushing that many cuts the status reads by up to the FIFO depth (128, the toolchain -//! package's `src/hal/uart.zig:52`). At 115200 the wire costs ~86 us per byte and dwarfs either -//! version, so today this is merely free - and it stops being free the moment the divider is raised. -//! -//! **UART0's configuration is never touched, except by `setBaud`.** Not the format, not the pad -//! routing, and above all not `reset()`. The second-stage bootloader configured this block, and -//! `src/hal/uart.zig:195-211` records what happens if it is reset: UART_CLKDIV returns to its -//! power-on value, the console turns to garbage mid-sentence, and the board takes a watchdog reset -//! with nothing readable left to explain it. Everything else here touches FIFO offset 0x000 and the -//! status register, and nothing else. -//! -//! The editor inherits the bootloader's 115200 divider. `src/esp32p4_9p.zig` -//! calls `setBaud` for its 921600 protocol connection; the host must match it. - -const hal = @import("hal"); -const input_rescue = @import("input_rescue.zig"); - -/// UART0: the instance the CH340 is wired to, and the one the ROM and bootloader configured. -const uart0 = hal.uart.Uart.init(0); - -/// Keystrokes taken off the receiver while the transmitter was full. See `input_rescue`: without -/// this, anything typed into a frame longer than the 128-byte FIFO was silently gone. -var rescued: input_rescue.Ring = .{}; - -/// Push `bytes` into the TX FIFO, blocking while it is full. -/// -/// The spin is normally bounded by the wire - a full 128-byte FIFO drains in 11 ms at 115200 - and -/// dropping instead of waiting would truncate an escape sequence, leaving the host terminal in the -/// wrong colour for the rest of the session. So the wait is real backpressure. -/// -/// But it is BOUNDED, for the reason the toolchain package's `src/hal/uart.zig:182-186` gives about -/// `update()`: a UART whose core clock has been gated never makes progress, and "on a board with no -/// debugger an infinite spin is indistinguishable from a crash". That is not hypothetical here - it -/// is how this port spent an afternoon: output stopped mid-boot with no panic and no watchdog (the -/// RTC watchdog having been correctly disabled), which looked like a hang in whatever code came next -/// rather than a stalled transmitter. A bounded wait turns that into visibly dropped output plus a -/// counter, which is a diagnosis instead of a mystery. -/// -/// The limit is per burst, not per call, and generous: 1,000,000 status reads is far longer than -/// any legitimate drain and still a fraction of a second. -pub fn write(bytes: []const u8) void { - dropped +%= input_rescue.pump(uart0, &rescued, bytes, 1_000_000); -} - -/// Bytes abandoned because the transmitter stopped making progress. Nonzero means the console is -/// lying about what happened, so it is worth printing. -pub var dropped: u32 = 0; - -/// Push as much of `bytes` as the transmitter has room for RIGHT NOW, and answer how much. Never -/// spins, never drops, never rescues — because it never waits for anything. -/// -/// THIS IS THE SANS-IO WRITE, and it exists because `write` above is the wrong primitive for a -/// protocol server. `write` is right for a console: a frame of ANSI is atomic to the terminal on the -/// far end, half an escape sequence leaves it in the wrong colour, so blocking until the whole burst -/// is in the FIFO is real backpressure and worth the stall. A 9P reply is not atomic to anything: -/// every message carries its own length, the reader on the far end reassembles, and -/// `9p.Server.wrote(n)` exists precisely so that a partial write costs nothing but another trip -/// round the loop (`src/9p.zig:2248-2257`). So this hands over what fits and returns, and -/// `src/esp32p4_9p.zig`'s loop keeps the remainder queued in the server where it already was. -/// -/// The difference that matters is DROPPING. `write`'s bounded spin gives up after a million status -/// reads and counts the loss, which turns a stalled transmitter into a diagnosable console; the same -/// behaviour on a 9P stream would truncate a reply mid-message and desynchronise the connection for -/// good. A short count cannot desynchronise anything. -pub fn writeSome(bytes: []const u8) usize { - const n = @min(@as(usize, uart0.txFree()), bytes.len); - for (bytes[0..n]) |b| uart0.pushByte(b); - return n; -} - -/// Reprogram UART0's divider, and answer whether the rate is reachable from the clock this block is -/// running on. Nothing is touched when it is not. -/// -/// THE ONE EXCEPTION to this file's rule, and see the header for who may call it: not this file, not -/// `app.zig`, only an image whose host side is opened at the same rate. `docs/registry.pdf` -/// `BOARD-1` has the numbers — 921600 is one `UART_CLKDIV_SYNC` write on the existing 40 MHz XTAL, -/// int 43 frag 6, +0.064% error, and it takes a byte from 86.8 µs to 10.85 µs. -/// -/// The hazard is worth restating where the call is: the bytes already in the FIFO go out at the OLD -/// rate, so anything written before this and not yet drained is corrupted, and a host that is not -/// reopened sees garbage from here on with no error to report. The 9P image calls this before it -/// answers its first message, which is the one moment when neither of those can have happened yet. -pub fn setBaud(baud: u32) bool { - return uart0.setBaudrate(baud, uart0.clockSource().nominalHz()); -} - -/// One byte, for callers that must not touch `.rodata` to say anything - which during bring-up is -/// the difference between a diagnostic and a second copy of the bug being diagnosed. -pub fn writeByte(b: u8) void { - var spins: u32 = 0; - while (uart0.txFree() == 0) { - spins += 1; - if (spins > 1_000_000) { - dropped +%= 1; - return; - } - } - uart0.pushByte(b); -} - -/// A u32 as eight hex digits, reading no memory at all. -pub fn dumpWord(v: u32) void { - var shift: u5 = 28; - while (true) { - const nib: u8 = @intCast((v >> shift) & 0xf); - writeByte(if (nib < 10) '0' + nib else 'a' + (nib - 10)); - if (shift == 0) break; - shift -= 4; - } - writeByte('\r'); - writeByte('\n'); -} - -/// Move whatever the host has sent into `buf`, without waiting. Returns the count. -/// -/// Non-blocking on purpose: the loop has a frame to render and a core to pump, and the editor must -/// not stall on a keystroke that may never come. `rxCount` is read once per call and the FIFO -/// drained to that mark, so a fast typist or a pasted buffer cannot hold the loop here. -pub fn read(buf: []u8) usize { - // RESCUED BYTES FIRST. They arrived before anything still sitting in the FIFO, and an editor - // that reorders keystrokes is worse than one that drops them. - var n = rescued.pop(buf); - const waiting = @min(uart0.rxCount(), buf.len - n); - for (buf[n..][0..waiting]) |*slot| slot.* = uart0.popByte(); - n += waiting; - return n; -} - -/// Take whatever has arrived off the receiver right now, without waiting and without handing it to -/// anyone. For callers that are about to spend a while not reading: `write` does this while the -/// transmitter is full, and the loop does it between chunks of input, because applying a keystroke -/// gets more expensive as the line grows and 128 bytes of FIFO is only 11 ms at 115200. -pub fn rescueNow() void { - input_rescue.rescue(uart0, &rescued); -} - -/// Input abandoned because even the rescue buffer overflowed. Distinct from `dropped`, which is -/// OUTPUT abandoned by a stalled transmitter. -pub fn inputDropped() u32 { - return rescued.dropped; -} - -/// Discard anything already received, returning how much. Used once at startup: the host-side -/// bridge injects a window-size report before this program exists, and the bootloader's chatter has -/// already been echoed at the host. Neither is user input. -/// -/// Pops rather than calling `resetRxFifo`, which is a CONF0_SYNC read-modify-write plus two commits -/// on the console UART - see this file's header. -pub fn drainInput() u32 { - var discarded: u32 = 0; - while (uart0.rxCount() > 0) : (discarded += 1) _ = uart0.popByte(); - discarded += @intCast(rescued.len); - rescued.clear(); - return discarded; -} - -/// The rate the hardware is actually producing, by reading its dividers back. Reported rather than -/// assumed: the host has to be opened at the same rate, and a mismatch shows up as garbage on the -/// screen rather than as an error anyone can act on. -pub fn baudrate() u32 { - return uart0.baudrate(uart0.clockSource().nominalHz()); -} diff --git a/src/esp32p4_9p.zig b/src/esp32p4_9p.zig deleted file mode 100644 index 5fcab85b..00000000 --- a/src/esp32p4_9p.zig +++ /dev/null @@ -1,186 +0,0 @@ -//! Standalone GPIO 9P firmware over UART0; the editor is not linked. -//! UART0 carries protocol bytes only, including fatal diagnostics. -const std = @import("std"); -const soc = @import("soc"); -const hal = @import("hal"); -const config = @import("config"); -const ninep = @import("9p.zig"); -const gpio = @import("esp32p4_gpio.zig"); -const uart = @import("esp32p4/uart.zig"); - -const Pads = struct { - pub fn level(pin: u8) u1 { - return hal.gpio.getDrivenLevel(pin); - } - - pub fn drive(pin: u8, want: u1) void { - hal.gpio.configureOutput(pin, .{ .readback = true }); - if (want == 1) hal.gpio.setHigh(pin) else hal.gpio.setLow(pin); - } -}; - -comptime { - for (gpio.Header.gpio_pins) |pin| { - if (pin > hal.gpio.max_pin) @compileError("JP1 names a pad this chip package does not have"); - } -} - -const Fs = gpio.Fs(Pads); -const Server = ninep.Server(Fs, ninep.board); - -comptime { - std.debug.assert(@typeInfo(@FieldType(Server, "fids")).array.len == 32); - std.debug.assert(@sizeOf(Server) <= 10 * 1024); -} - -const msize: u32 = 1024; - -var in_buf: [msize]u8 = undefined; - -var out_buf: [2 * msize]u8 = undefined; - -var stage: [128]u8 = undefined; - -const baud: u32 = 921600; - -var srv: Server = undefined; -var fsys: Fs = .{}; - -export fn zig_main() noreturn { - soc.flushFlashCache(); - - if (config.cpu_mhz != 90) hal.clkrst.setCpuFreq(switch (config.cpu_mhz) { - 180 => .mhz180, - 360 => .mhz360, - else => .mhz90, - }); - - _ = hal.rwdt.disable(); - - _ = uart.drainInput(); - - _ = uart.setBaud(baud); - - srv = Server.init(.{ .in = &in_buf, .out = &out_buf, .root = gpio.root }); - - var stage_len: usize = 0; - while (true) { - if (stage_len < stage.len) stage_len += uart.read(stage[stage_len..]); - if (stage_len != 0) { - const took = srv.push(stage[0..stage_len]); - if (took != stage_len) std.mem.copyForwards(u8, stage[0 .. stage_len - took], stage[took..stage_len]); - stage_len -= took; - } - - while (srv.retry()) |req| { - const a = fsys.handle(req); - srv.reply(&a.reply, a.bytes); - } - while (srv.next()) |req| { - const a = fsys.handle(req); - srv.reply(&a.reply, a.bytes); - } - - const queued = srv.output(); - if (queued.len != 0) srv.wrote(uart.writeSome(queued)); - - if (srv.protocol.dead) { - srv.hangup(); - while (srv.next()) |req| { - const a = fsys.handle(req); - srv.reply(&a.reply, a.bytes); - } - _ = uart.drainInput(); - stage_len = 0; - srv = Server.init(.{ .in = &in_buf, .out = &out_buf, .root = gpio.root }); - } - } -} - -fn die(msg: []const u8) noreturn { - var buf: [ninep.errmax + ninep.header_len + 2]u8 = undefined; - const bytes = ninep.encode( - .{ .rerror = .{ .ename = msg[0..@min(msg.len, ninep.errmax)] } }, - ninep.notag, - &buf, - // unreachable: the message is cut to errmax and buf is sized to it - ) catch unreachable; - uart.write(bytes); - while (true) {} -} - -fn hex8(buf: *[8]u8, v: u32) void { - var shift: u5 = 28; - for (buf) |*slot| { - const nib: u8 = @intCast((v >> shift) & 0xf); - slot.* = if (nib < 10) '0' + nib else 'a' + (nib - 10); - shift -%= 4; - } -} - -export fn trapEntry() linksection(".text.entry") callconv(.naked) noreturn { - asm volatile ("j trapReport"); -} - -export fn trapReport() noreturn { - const mcause = asm volatile ("csrr %[o], mcause" - : [o] "=r" (-> u32), - ); - const mepc = asm volatile ("csrr %[o], mepc" - : [o] "=r" (-> u32), - ); - const mtval = asm volatile ("csrr %[o], mtval" - : [o] "=r" (-> u32), - ); - var msg = "trap mcause=00000000 mepc=00000000 mtval=00000000".*; - hex8(msg[12..20], mcause); - hex8(msg[26..34], mepc); - hex8(msg[41..49], mtval); - die(&msg); -} - -pub const std_options: std.Options = .{ - .page_size_min = 4096, - .page_size_max = 4096, - .logFn = logFn, -}; - -fn logFn( - comptime _: std.log.Level, - comptime _: @EnumLiteral(), - comptime _: []const u8, - _: anytype, -) void {} - -pub const panic = std.debug.FullPanic(panicImpl); - -fn panicImpl(msg: []const u8, first_trace_addr: ?usize) noreturn { - var buf: [ninep.errmax]u8 = undefined; - @memcpy(buf[0..7], "panic 0"); - buf[7] = 'x'; - hex8(buf[8..16], @truncate(first_trace_addr orelse 0)); - buf[16] = ' '; - const n = @min(msg.len, buf.len - 17); - @memcpy(buf[17..][0..n], msg[0..n]); - die(buf[0 .. 17 + n]); -} - -export fn _start() linksection(".text.entry") callconv(.naked) noreturn { - asm volatile ( - \\ li t0, 1 << 13 - \\ csrs mstatus, t0 - \\ la sp, __stack_top - \\ mv fp, sp - \\ la t0, trapEntry - \\ csrw mtvec, t0 - \\ la t0, __bss_start - \\ la t1, __bss_end - \\ bgeu t0, t1, 2f - \\1: - \\ sw zero, 0(t0) - \\ addi t0, t0, 4 - \\ bltu t0, t1, 1b - \\2: - \\ j zig_main - ); -} diff --git a/src/esp32p4_gpio.zig b/src/esp32p4_gpio.zig deleted file mode 100644 index d6c29a36..00000000 --- a/src/esp32p4_gpio.zig +++ /dev/null @@ -1,538 +0,0 @@ -//! ESP32-P4 JP1 GPIO data and its freestanding filesystem. -const std = @import("std"); -const ninep = @import("9p.zig"); - -// JP1: JC-ESP32P4-M3-DEV schematic, sheet 2 "Expand IO": -// 01-esp32p4-m3/docs/schematics/2_EXPAND_IO&BAT.png -pub const Header = struct { - pub const Pad = union(enum) { - none, - gpio: u8, - // C6 and power nets are not P4 GPIOs; the schematic gives no GPIO numbers for ES_I2C. - net: []const u8, - - fn label(comptime p: Pad) []const u8 { - return switch (p) { - .none => "--", - .gpio => |n| std.fmt.comptimePrint("GPIO {d}", .{n}), - .net => |s| s, - }; - } - }; - - pub const Row = struct { left: Pad, right: Pad }; - - pub const rows = [13]Row{ - .{ .left = .{ .net = "3V3" }, .right = .{ .net = "5V" } }, - .{ .left = .{ .net = "3V3" }, .right = .{ .net = "5V" } }, - .{ .left = .{ .net = "GND" }, .right = .{ .net = "GND" } }, - .{ .left = .{ .gpio = 1 }, .right = .none }, - .{ .left = .{ .gpio = 2 }, .right = .{ .gpio = 47 } }, - .{ .left = .{ .gpio = 3 }, .right = .{ .gpio = 46 } }, - .{ .left = .{ .gpio = 4 }, .right = .{ .gpio = 45 } }, - .{ .left = .{ .gpio = 5 }, .right = .{ .net = "GND" } }, - .{ .left = .{ .gpio = 20 }, .right = .{ .net = "3V3" } }, - .{ .left = .{ .gpio = 32 }, .right = .{ .net = "C6_U0RXD" } }, - .{ .left = .{ .gpio = 33 }, .right = .{ .net = "C6_U0TXD" } }, - .{ .left = .{ .net = "ES_I2C_SDA" }, .right = .{ .net = "C6_IO9" } }, - .{ .left = .{ .net = "ES_I2C_SCL" }, .right = .{ .net = "C6_CHIP_PU" } }, - }; - - const row_format = "{s:>10} | {d:>2} | {d:>2} | {s}\n"; - - const border = " +---------+\n"; - - pub const text = rendered: { - var out: []const u8 = - \\JP1 header - 26 pins, pin 1 top left. - \\Every number here is DECIMAL. - \\ - \\ - ; - out = out ++ border; - for (rows, 0..) |row, i| out = out ++ std.fmt.comptimePrint( - row_format, - .{ row.left.label(), 2 * i + 1, 2 * i + 2, row.right.label() }, - ); - break :rendered out ++ border ++ - \\ - \\Gpio <pin> flips one: 0->1 or 1->0. - \\ - ; - }; - - pub const gpio_pins = pins: { - var found: [2 * rows.len]u8 = undefined; - var n: usize = 0; - for (rows) |row| for ([2]Pad{ row.left, row.right }) |p| switch (p) { - .gpio => |g| { - found[n] = g; - n += 1; - }, - else => {}, - }; - std.mem.sort(u8, found[0..n], {}, std.sort.asc(u8)); - break :pins found[0..n].*; - }; - - test "the rendered header is the drawing the console has always printed" { - try std.testing.expectEqualStrings( - \\JP1 header - 26 pins, pin 1 top left. - \\Every number here is DECIMAL. - \\ - \\ +---------+ - \\ 3V3 | 1 | 2 | 5V - \\ 3V3 | 3 | 4 | 5V - \\ GND | 5 | 6 | GND - \\ GPIO 1 | 7 | 8 | -- - \\ GPIO 2 | 9 | 10 | GPIO 47 - \\ GPIO 3 | 11 | 12 | GPIO 46 - \\ GPIO 4 | 13 | 14 | GPIO 45 - \\ GPIO 5 | 15 | 16 | GND - \\ GPIO 20 | 17 | 18 | 3V3 - \\ GPIO 32 | 19 | 20 | C6_U0RXD - \\ GPIO 33 | 21 | 22 | C6_U0TXD - \\ES_I2C_SDA | 23 | 24 | C6_IO9 - \\ES_I2C_SCL | 25 | 26 | C6_CHIP_PU - \\ +---------+ - \\ - \\Gpio <pin> flips one: 0->1 or 1->0. - \\ - , text); - } - - test "the header's own GPIOs, and only those" { - try std.testing.expectEqualSlices(u8, &.{ 1, 2, 3, 4, 5, 20, 32, 33, 45, 46, 47 }, &gpio_pins); - try std.testing.expectEqual(Pad.none, rows[3].right); - try std.testing.expectEqualStrings("C6_IO9", rows[11].right.net); - } -}; - -pub const E = ninep.fs.E; - -pub const root: u64 = 1; -const gpio_node: u64 = 16; -const pinout_node: u64 = 17; - -const Entry = struct { - node: u64, - parent: u64, - name: []const u8, - kind: enum { directory, pinout, value }, - pin: u8 = 0, -}; - -const entries = table: { - var result: [3 + 2 * Header.gpio_pins.len]Entry = undefined; - result[0] = .{ .node = root, .parent = root, .name = "/", .kind = .directory }; - result[1] = .{ .node = gpio_node, .parent = root, .name = "gpio", .kind = .directory }; - result[2] = .{ .node = pinout_node, .parent = gpio_node, .name = "pinout", .kind = .pinout }; - for (Header.gpio_pins, 0..) |pin, i| { - const directory = 18 + i; - result[3 + 2 * i] = .{ - .node = directory, - .parent = gpio_node, - .name = std.fmt.comptimePrint("{d}", .{pin}), - .kind = .directory, - }; - result[4 + 2 * i] = .{ - .node = (2 + i) * 16 + 1, - .parent = directory, - .name = "value", - .kind = .value, - .pin = pin, - }; - } - break :table result; -}; - -const dirent_fixed = 10; -const out_capacity = size: { - var result: usize = 2; - for (entries) |directory| { - if (directory.kind != .directory) continue; - var bytes: usize = 0; - for (entries) |entry| { - if (entry.parent == directory.node and entry.node != directory.node) - bytes += dirent_fixed + entry.name.len; - } - result = @max(result, bytes); - } - break :size result; -}; - -pub fn Fs(comptime Pads: type) type { - return struct { - const Self = @This(); - pub const Op = ninep.fs.Op; - pub const Status = ninep.fs.Status; - pub const Req = ninep.fs.Req; - pub const Reply = ninep.fs.Reply; - - // Reply bytes are borrowed until the next handle call. - pub const Answer = struct { reply: Reply, bytes: []const u8 = "" }; - - out: [out_capacity]u8 = undefined, - - fn find(node: u64) ?*const Entry { - for (&entries) |*entry| if (entry.node == node) return entry; - return null; - } - - fn attributes(entry: *const Entry) Reply.Attr { - return .{ - .name = entry.name, - .node = entry.node, - .dir = entry.kind == .directory, - .mode = switch (entry.kind) { - .directory => 0o500, - .pinout => 0o400, - .value => 0o600, - }, - .size = switch (entry.kind) { - .directory => 0, - .pinout => Header.text.len, - .value => 2, - }, - }; - } - - pub fn handle(fs: *Self, req: Req) Answer { - const entry = find(req.node) orelse return .{ .reply = .fail(req.tag, E.NOENT) }; - switch (req.op) { - .lookup => { - if (entry.kind != .directory) return .{ .reply = .fail(req.tag, E.NOTDIR) }; - if (std.mem.eql(u8, req.data, "..")) - return .{ .reply = .{ .tag = req.tag, .attr = attributes(find(entry.parent).?) } }; - for (&entries) |*child| { - if (child.parent != req.node or child.node == req.node) continue; - if (!std.mem.eql(u8, child.name, req.data)) continue; - return .{ .reply = .{ .tag = req.tag, .attr = attributes(child) } }; - } - return .{ .reply = .fail(req.tag, E.NOENT) }; - }, - .getattr => return .{ .reply = .{ .tag = req.tag, .attr = attributes(entry) } }, - .setattr => { - // GPIO register views have no storage to truncate. - if (entry.kind == .directory) return .{ .reply = .fail(req.tag, E.INVAL) }; - return .{ .reply = .{ .tag = req.tag, .attr = attributes(entry) } }; - }, - .open => return .{ .reply = .{ .tag = req.tag, .handle = 1 } }, - .release => return .{ .reply = .{ .tag = req.tag } }, - .read => { - const bytes = switch (entry.kind) { - .directory => return .{ .reply = .fail(req.tag, E.INVAL) }, - .pinout => Header.text, - .value => value: { - fs.out[0] = '0' + @as(u8, Pads.level(entry.pin)); - fs.out[1] = '\n'; - break :value fs.out[0..2]; - }, - }; - const off: usize = @intCast(@min(req.off, bytes.len)); - return .{ .reply = .{ .tag = req.tag }, .bytes = bytes[off..][0..@min(bytes.len - off, req.size)] }; - }, - .write => { - if (entry.kind != .value or req.off != 0) return .{ .reply = .fail(req.tag, E.INVAL) }; - const value = std.mem.trimEnd(u8, req.data, "\r\n"); - if (value.len != 1 or (value[0] != '0' and value[0] != '1')) - return .{ .reply = .fail(req.tag, E.INVAL) }; - Pads.drive(entry.pin, @intCast(value[0] - '0')); - return .{ .reply = .{ .tag = req.tag, .written = @intCast(req.data.len) } }; - }, - .readdir => { - if (entry.kind != .directory) return .{ .reply = .fail(req.tag, E.NOTDIR) }; - var len: usize = 0; - var skip = req.off; - for (entries) |child| { - if (child.parent != req.node or child.node == req.node) continue; - if (skip != 0) { - skip -= 1; - continue; - } - std.mem.writeInt(u64, fs.out[len..][0..8], child.node, .little); - fs.out[len + 8] = @intFromBool(child.kind == .directory); - fs.out[len + 9] = @intCast(child.name.len); - @memcpy(fs.out[len + dirent_fixed ..][0..child.name.len], child.name); - len += dirent_fixed + child.name.len; - } - return .{ .reply = .{ .tag = req.tag }, .bytes = fs.out[0..len] }; - }, - } - } - }; -} - -const testing = std.testing; - -const StubPads = struct { - var driven: [64]u1 = @splat(0); - var log: [16]Call = undefined; - var log_len: usize = 0; - - const Call = struct { pin: u8, level: u1 }; - - fn reset() void { - driven = @splat(0); - log_len = 0; - } - - fn level(pin: u8) u1 { - return driven[pin]; - } - - fn drive(pin: u8, want: u1) void { - driven[pin] = want; - log[log_len] = .{ .pin = pin, .level = want }; - log_len += 1; - } -}; - -const Board = Fs(StubPads); - -fn walk(t: *Board, path: []const []const u8) !Board.Reply.Attr { - var at: u64 = root; - var attr: Board.Reply.Attr = .{ .node = root, .dir = true, .mode = 0o500 }; - for (path) |name| { - const a = t.handle(.{ .tag = 1, .op = .lookup, .node = at, .data = name }); - if (a.reply.status == .err) return switch (a.reply.errno) { - E.NOENT => error.NoEntry, - E.NOTDIR => error.NotDirectory, - else => error.Refused, - }; - attr = a.reply.attr; - at = attr.node; - } - return attr; -} - -fn readAll(t: *Board, node: u64) !Board.Answer { - const open = t.handle(.{ .tag = 1, .op = .open, .node = node }); - try testing.expectEqual(Board.Status.ok, open.reply.status); - return t.handle(.{ .tag = 2, .op = .read, .node = node, .handle = open.reply.handle, .size = 65535 }); -} - -test "GPIO: the generated tree has exactly the header's pins, and nothing else" { - var t: Board = .{}; - - try testing.expect((try walk(&t, &.{"gpio"})).dir); - try testing.expect(!(try walk(&t, &.{ "gpio", "pinout" })).dir); - - for (Header.gpio_pins, 0..) |pin, i| { - var name: [4]u8 = undefined; - const dir = try std.fmt.bufPrint(&name, "{d}", .{pin}); - const directory = try walk(&t, &.{ "gpio", dir }); - try testing.expect(directory.dir); - try testing.expectEqual(@as(u64, 18 + i), directory.node); - const value = try walk(&t, &.{ "gpio", dir, "value" }); - try testing.expect(!value.dir); - try testing.expectEqual(@as(u64, (2 + i) * 16 + 1), value.node); - try testing.expectEqual(@as(u16, 0o600), value.mode); - } - - try testing.expectError(error.NoEntry, walk(&t, &.{ "gpio", "6" })); - try testing.expectError(error.NoEntry, walk(&t, &.{ "gpio", "21" })); - try testing.expectError(error.NoEntry, walk(&t, &.{ "gpio", "20", "level" })); - try testing.expectError(error.NoEntry, walk(&t, &.{"mem"})); -} - -test "GPIO: a read of gpio/pinout is the bytes the Gpio word draws" { - var t: Board = .{}; - const at = try walk(&t, &.{ "gpio", "pinout" }); - const a = try readAll(&t, at.node); - try testing.expectEqualStrings(Header.text, a.bytes); - try testing.expectEqual(Header.text.len, at.size); - try testing.expectEqual(@as(u16, 0o400), at.mode); - const w = t.handle(.{ .tag = 3, .op = .write, .node = at.node, .data = "x" }); - try testing.expectEqual(E.INVAL, w.reply.errno); -} - -test "GPIO: writing 1 then 0 drives the pad twice, through the seam" { - StubPads.reset(); - var t: Board = .{}; - const at = try walk(&t, &.{ "gpio", "20", "value" }); - - const before = try readAll(&t, at.node); - try testing.expectEqualStrings("0\n", before.bytes); - - const one = t.handle(.{ .tag = 4, .op = .write, .node = at.node, .data = "1" }); - try testing.expectEqual(Board.Status.ok, one.reply.status); - try testing.expectEqual(@as(u32, 1), one.reply.written); - try testing.expectEqualStrings("1\n", (try readAll(&t, at.node)).bytes); - - const zero = t.handle(.{ .tag = 5, .op = .write, .node = at.node, .data = "0\n" }); - try testing.expectEqual(@as(u32, 2), zero.reply.written); - try testing.expectEqualStrings("0\n", (try readAll(&t, at.node)).bytes); - - try testing.expectEqual(@as(usize, 2), StubPads.log_len); - try testing.expectEqual(StubPads.Call{ .pin = 20, .level = 1 }, StubPads.log[0]); - try testing.expectEqual(StubPads.Call{ .pin = 20, .level = 0 }, StubPads.log[1]); -} - -test "GPIO: a pad takes 0 and 1 and refuses everything else, without touching the pads" { - StubPads.reset(); - var t: Board = .{}; - const at = try walk(&t, &.{ "gpio", "45", "value" }); - - for ([_][]const u8{ "2", "", "01", "x", "true", "high", "\n", "1 ", " 1", "10" }) |bad| { - const a = t.handle(.{ .tag = 6, .op = .write, .node = at.node, .data = bad }); - try testing.expectEqual(Board.Status.err, a.reply.status); - try testing.expectEqual(E.INVAL, a.reply.errno); - } - try testing.expectEqual(@as(usize, 0), StubPads.log_len); - - const off = t.handle(.{ .tag = 7, .op = .write, .node = at.node, .off = 1, .data = "1" }); - try testing.expectEqual(E.INVAL, off.reply.errno); - try testing.expectEqual(@as(usize, 0), StubPads.log_len); -} - -test "GPIO: node parents are explicit, not derived from node bits" { - for (&entries) |*e| { - const serial = e.node >> 4; - const file = e.node & 0xF; - const derived: u64 = if (e.node == root or serial == 0 or file == 0) root else serial << 4; - if (derived == e.parent) continue; - try testing.expectEqualStrings("value", e.name); - var t: Board = .{}; - const a = t.handle(.{ .tag = 8, .op = .getattr, .node = derived }); - try testing.expectEqual(E.NOENT, a.reply.errno); - } -} - -test "GPIO: parent lookup follows every generated directory" { - var t: Board = .{}; - for (&entries) |*entry| { - if (entry.kind != .directory) continue; - const answer = t.handle(.{ .tag = 1, .op = .lookup, .node = entry.node, .data = ".." }); - try testing.expectEqual(Board.Status.ok, answer.reply.status); - try testing.expectEqual(entry.parent, answer.reply.attr.node); - try testing.expect(answer.reply.attr.dir); - } -} - -test "GPIO: a directory read lists what the table generated, in table order" { - var t: Board = .{}; - - try testing.expectEqualStrings("gpio", (try names(&t, root, 0))[0]); - try testing.expectEqual(@as(usize, 1), (try names(&t, root, 0)).len); - - const gpio = (try walk(&t, &.{"gpio"})).node; - const listing = try names(&t, gpio, 0); - try testing.expectEqual(Header.gpio_pins.len + 1, listing.len); - try testing.expectEqualStrings("pinout", listing[0]); - for (Header.gpio_pins, 0..) |pin, i| { - var buf: [4]u8 = undefined; - try testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{d}", .{pin}), listing[i + 1]); - } - - const rest = try names(&t, gpio, 5); - try testing.expectEqual(Header.gpio_pins.len + 1 - 5, rest.len); - try testing.expectEqualStrings("5", rest[0]); -} - -var name_slots: [32][]const u8 = undefined; -fn names(t: *Board, node: u64, skip: u64) ![][]const u8 { - const a = t.handle(.{ .tag = 9, .op = .readdir, .node = node, .off = skip, .size = 65535 }); - try testing.expectEqual(Board.Status.ok, a.reply.status); - var n: usize = 0; - var i: usize = 0; - while (i < a.bytes.len) { - const len = a.bytes[i + 9]; - name_slots[n] = a.bytes[i + 10 ..][0..len]; - n += 1; - i += 10 + len; - } - return name_slots[0..n]; -} - -test "GPIO: the whole tree costs one buffer, and the table says how big" { - try testing.expectEqual(@as(usize, 143), out_capacity); - try testing.expectEqual(@as(usize, 143), @sizeOf(Board)); - try testing.expectEqual(@as(usize, 28), ninep.board.name_capacity); - try testing.expect(Header.text.len > out_capacity); -} - -test "GPIO: stat and truncation preserve the register value and reads respect offsets" { - StubPads.reset(); - var fs: Board = .{}; - const value = try walk(&fs, &.{ "gpio", "20", "value" }); - for (0..2) |_| { - const written = fs.handle(.{ .tag = 1, .op = .write, .node = value.node, .data = "1\r\n" }); - try testing.expectEqual(@as(u32, 3), written.reply.written); - } - try testing.expectEqual(@as(usize, 2), StubPads.log_len); - const stat = fs.handle(.{ .tag = 2, .op = .getattr, .node = value.node }); - try testing.expectEqual(@as(u64, 2), stat.reply.attr.size); - const truncated = fs.handle(.{ .tag = 3, .op = .setattr, .node = value.node, .truncate = true }); - try testing.expectEqual(Board.Status.ok, truncated.reply.status); - try testing.expectEqual(@as(u1, 1), StubPads.driven[20]); - const part = fs.handle(.{ .tag = 4, .op = .read, .node = value.node, .off = 1, .size = 1 }); - try testing.expectEqualStrings("\n", part.bytes); - const eof = fs.handle(.{ .tag = 5, .op = .read, .node = value.node, .off = 2, .size = 1 }); - try testing.expectEqual(@as(usize, 0), eof.bytes.len); - const pinout = try walk(&fs, &.{ "gpio", "pinout" }); - const text = fs.handle(.{ .tag = 6, .op = .read, .node = pinout.node, .off = 10, .size = 12 }); - try testing.expectEqualStrings(Header.text[10..22], text.bytes); -} - -test "GPIO: a real 9P client reads a pin's value off this tree" { - StubPads.reset(); - const Server = ninep.Server(Board, ninep.board); - var in: [1024]u8 = undefined; - var out: [2048]u8 = undefined; - var fsys: Board = .{}; - var srv = Server.init(.{ .in = &in, .out = &out, .root = root }); - - var scratch: [256]u8 = undefined; - const send = struct { - fn call(s: *Server, f: *Board, buf: []u8, tag: u16, msg: ninep.Msg) !void { - const bytes = try ninep.encode(msg, tag, buf); - try testing.expectEqual(bytes.len, s.push(bytes)); - while (s.retry()) |req| { - const a = f.handle(req); - s.reply(&a.reply, a.bytes); - } - while (s.next()) |req| { - const a = f.handle(req); - s.reply(&a.reply, a.bytes); - } - } - }.call; - const reap = struct { - fn call(s: *Server) !ninep.Decoded { - const queued = s.output(); - const len = ninep.frameLen(queued) orelse return error.NoReply; - const got = try ninep.decode(queued[0..len]); - s.wrote(len); - return got; - } - }.call; - - try send(&srv, &fsys, &scratch, ninep.notag, .{ .tversion = .{ .msize = 8192, .version = "9P2000" } }); - const v = try reap(&srv); - try testing.expectEqual(@as(u32, 1024), v.msg.rversion.msize); - - try send(&srv, &fsys, &scratch, 1, .{ .tattach = .{ .fid = 0, .afid = ninep.nofid, .uname = "goblin", .aname = "" } }); - try testing.expectEqual(root, (try reap(&srv)).msg.rattach.qid.path); - - var wname: [ninep.max_welem][]const u8 = @splat(""); - wname[0] = "gpio"; - wname[1] = "20"; - wname[2] = "value"; - try send(&srv, &fsys, &scratch, 2, .{ .twalk = .{ .fid = 0, .newfid = 1, .nwname = 3, .wname = wname } }); - try testing.expectEqual(@as(u16, 3), (try reap(&srv)).msg.rwalk.nwqid); - - try send(&srv, &fsys, &scratch, 3, .{ .topen = .{ .fid = 1, .mode = ninep.ordwr } }); - _ = try reap(&srv); - - try send(&srv, &fsys, &scratch, 4, .{ .twrite = .{ .fid = 1, .offset = 0, .data = "1\n" } }); - try testing.expectEqual(@as(u32, 2), (try reap(&srv)).msg.rwrite.count); - try testing.expectEqual(@as(u1, 1), StubPads.driven[20]); - - try send(&srv, &fsys, &scratch, 5, .{ .tread = .{ .fid = 1, .offset = 0, .count = 512 } }); - try testing.expectEqualStrings("1\n", (try reap(&srv)).msg.rread.data); - - try send(&srv, &fsys, &scratch, 6, .{ .twrite = .{ .fid = 1, .offset = 0, .data = "on" } }); - try testing.expectEqualStrings(ninep.errString(E.INVAL), (try reap(&srv)).msg.rerror.ename); - try testing.expectEqual(@as(usize, 1), StubPads.log_len); -} diff --git a/src/exec.zig b/src/exec.zig index b1ee55d4..ee9e8ddf 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -721,7 +721,7 @@ pub fn executeFrom(p: *Pardes, id: usize, txt: []const u8, from_body: bool) ?usi /// A pane reused keeps what it showed: the new command runs below a line /// naming it, as acme appends to +Errors and never clears it (util.c:213). fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { - // The board and the web page start no processes: a command pane there + // The web page starts no processes: a command pane there // would say running for ever, and fill the slots. if (comptime !hosted) { p.reportFailure(from, "exec: not a builtin, and this build runs no commands"); @@ -549,7 +549,6 @@ test "bounded reads count rendered directory paths and unknown self lengths" { } test "bounded reads release terminal snapshots after success and size refusal" { - if (!pardes.terminal_panes) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try th.withTerm(gpa); defer p.deinit(); @@ -1099,7 +1098,7 @@ fn findEmbeddedSource(path: []const u8, allow_root_suffix: bool) ?Source { pub const platform_has_fs = !pardes.isolated and switch (pardes.platform) { .tui, .gui, .macos => true, - .web, .esp32p4 => false, + .web => false, }; pub const find_skip = [_][]const u8{ diff --git a/src/gui/gui.zig b/src/gui/gui.zig index dc95a584..28f5e695 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -4564,7 +4564,6 @@ fn readClipboard(ctx: ?*anyopaque) void { } test "the clipboard pasted into a terminal reaches its pty as xterm pastes: bracketed when asked, no ESC[201~ smuggled through" { - if (comptime !pardes.panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); defer core.deinit(); @@ -4768,7 +4767,6 @@ test "a wheel's notch is whole lines, a touchpad's fraction is not" { } test "a click over codex in a terminal reaches its pty with its modifiers; Shift swaps B1 to pardes and B2 to the program" { - if (comptime !pardes.panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); defer core.deinit(); @@ -4816,7 +4814,6 @@ test "a click over codex in a terminal reaches its pty with its modifiers; Shift } test "a wheel over codex in a terminal reaches its pty as the mouse reports it asked for" { - if (comptime !pardes.panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); defer core.deinit(); diff --git a/src/host_io.zig b/src/host_io.zig index d13b7643..6b27141e 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -49,7 +49,6 @@ pub const Host = struct { /// Answered at once, not queued as an effect: Kill asks while the /// job it saw running is still the one in the tty (host_io.killJob). kill_job: ?*const fn (ctx: ?*anyopaque, pane: u8) bool = null, - gpio_toggle: ?*const fn (ctx: ?*anyopaque, pin: u16, was: *u8, now: *u8) bool = null, write_file: ?*const fn (ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void = null, write_dump: ?*const fn (ctx: ?*anyopaque, bytes: []const u8) void = null, watch_file: ?*const fn (ctx: ?*anyopaque, pane: u8, path: []const u8, on: bool, mode: pardes.WatchMode) void = null, diff --git a/src/image.zig b/src/image.zig index e59696f8..09522612 100644 --- a/src/image.zig +++ b/src/image.zig @@ -3,10 +3,8 @@ const std = @import("std"); const builtin = @import("builtin"); const zstbi = @import("zstbi"); /// The 16-colour ANSI table below is the only thing this file ever wanted from -/// the emulator, and a build without one still renders images — see -/// `pardes.terminal_panes`. -const terminal_panes = @import("pardes.zig").terminal_panes; -const ghostty_vt = if (terminal_panes) @import("ghostty-vt") else struct {}; +/// the emulator. +const ghostty_vt = @import("ghostty-vt"); const pdf_enabled = @import("pardes_config").mupdf; const pardes = @import("pardes.zig"); const config = @import("config.zig"); @@ -469,12 +467,12 @@ pub const terminal_palette = [16][3]u8{ }; comptime { - if (terminal_panes) for (terminal_palette, 0..) |rgb, i| { + for (terminal_palette, 0..) |rgb, i| { const c = ghostty_vt.color.default[i]; if (rgb[0] != c.r or rgb[1] != c.g or rgb[2] != c.b) @compileError( "terminal palette differs from the emulator", ); - }; + } } /// cap the longest side before keeping/transmitting: a pane is at most a diff --git a/src/lsp/lsp.zig b/src/lsp/lsp.zig index 758d3042..eccd3ac6 100644 --- a/src/lsp/lsp.zig +++ b/src/lsp/lsp.zig @@ -89,9 +89,9 @@ test "an explain request narrates the query named in its arg, a definition by de } /// Every language, Zig's (zls) included, through the protocol client, which -/// runs its server as a child process. None on the web or the board. +/// runs its server as a child process. None on the web. const has_client = switch (@import("pardes_config").platform) { - .web, .esp32p4 => false, + .web => false, else => true, }; const client = if (has_client) @import("lsp_client.zig") else void; diff --git a/src/main.zig b/src/main.zig index a7c0dcc0..a79a9716 100644 --- a/src/main.zig +++ b/src/main.zig @@ -850,7 +850,7 @@ fn nativeMain(std_init: std.process.Init) !void { else => return err, }, .gui => try @import("gui/gui.zig").run(init, opts, headless), - .web, .macos, .esp32p4 => unreachable, + .web, .macos => unreachable, } daemon.tellStubExit(0); } diff --git a/src/memory.zig b/src/memory.zig index 8ce3ad12..c4e0e6fd 100644 --- a/src/memory.zig +++ b/src/memory.zig @@ -3,7 +3,6 @@ const builtin = @import("builtin"); const walk = @import("walk.zig"); const config = @import("pardes_config"); -const board = config.platform == .esp32p4; const reduced_target = builtin.os.tag == .freestanding; const KiB = 1024; const MiB = 1024 * KiB; @@ -11,59 +10,56 @@ const MiB = 1024 * KiB; pub const limits = struct { pub const max_file_bytes = 256 * MiB; pub const max_stream_bytes = 4 * MiB; - // P4: 384 KiB heap; static buffers and stack share a separate 240 KiB region. - pub const board_heap_bytes = 384 * KiB; - pub const effect_cap = if (board) 128 else 4096; - pub const pending_write_cap: usize = if (board) 0 else 4 * MiB; - pub const wrap_rows = if (board) 128 else 256; - pub const undo_max = if (board) 16 else 256; + pub const effect_cap = 4096; + pub const pending_write_cap: usize = 4 * MiB; + pub const wrap_rows = 256; + pub const undo_max = 256; /// The text a file's undo and redo steps hold together, kept by dropping /// the oldest; the newest step always stays, so the bound per file is /// this plus one snapshot (at most max_file_bytes). - pub const undo_bytes: usize = if (board) 64 * KiB else 64 * MiB; - pub const message_log = if (board) 16 else 128; + pub const undo_bytes: usize = 64 * MiB; + pub const message_log = 128; /// ranges one selection holds; helix has no limit, and a `%s` over a /// file's words wants hundreds - pub const selections = if (board) 64 else 1024; + pub const selections = 1024; /// /log's ring, which records whether or not anyone reads it. - pub const log_bytes: usize = if (board) 4 * KiB else 64 * KiB; - pub const max_tag_tail: usize = if (board) 512 else 4096; + pub const log_bytes: usize = 64 * KiB; + pub const max_tag_tail: usize = 4096; /// Pixels one image may decode to (RGBA, 4 bytes each): checked from its /// header before stb_image allocates them. - pub const image_decode_pixels: usize = if (board) 0 else 64 * 1024 * 1024; + pub const image_decode_pixels: usize = 64 * 1024 * 1024; /// What the core's per-step scratch arena and the frame arena keep /// between steps: a step that needed more (a huge Callstack's sources) /// gives the rest back instead of holding its high-water mark. - pub const scratch_kept: usize = if (board) 4 * KiB else 16 * MiB; - pub const frame_kept: usize = if (board) 4 * KiB else 16 * MiB; + pub const scratch_kept: usize = 16 * MiB; + pub const frame_kept: usize = 16 * MiB; /// The other open files one language query copies for its server, in /// bytes: past it the rest are left out (the asked file always goes). - pub const lsp_snapshot_bytes: usize = if (board) 0 else 64 * MiB; + pub const lsp_snapshot_bytes: usize = 64 * MiB; /// One paste, from any shell: past it, the rest is left out and said. - pub const max_paste_bytes: usize = if (board) 16 * KiB else 4 * MiB; - pub const host_path_cap: usize = if (board) 0 else 4095; + pub const max_paste_bytes: usize = 4 * MiB; + pub const host_path_cap: usize = 4095; /// -Dembed-sources: the editor serves its own sources under /src. pub const embedded_sources = config.embed_sources; - pub const hexdump_row_bytes: u32 = if (board) 8 else 16; /// Each arena's fixed region. On a native target these are address /// space reserved at startup, resident only where used (`Pages`), so /// they are sized for the worst case: the core holds a 256 MiB file, its /// edit's copy and its undo. pub const arena = struct { - pub const pardes = if (board) 4 * KiB else if (reduced_target) 8 * MiB else 1024 * MiB; - pub const frame = if (board) 4 * KiB else if (reduced_target) 4 * MiB else 64 * MiB; - pub const lsp = if (board or reduced_target) 0 else 512 * MiB; + pub const pardes = if (reduced_target) 8 * MiB else 1024 * MiB; + pub const frame = if (reduced_target) 4 * MiB else 64 * MiB; + pub const lsp = if (reduced_target) 0 else 512 * MiB; /// What a native shell allocates itself (`host`): its screen, the /// bytes its ptys read, its 9P connections, its pipe jobs. - pub const host = if (board or reduced_target) 0 else 512 * MiB; - pub const tree_sitter = if (board) 0 else if (reduced_target) 4 * MiB else 256 * MiB; - pub const image = if (board) 0 else if (reduced_target) 64 * KiB else 256 * MiB; - pub const pdf = if (board) 0 else if (reduced_target or !config.mupdf) 64 * KiB else 512 * MiB; + pub const host = if (reduced_target) 0 else 512 * MiB; + pub const tree_sitter = if (reduced_target) 4 * MiB else 256 * MiB; + pub const image = if (reduced_target) 64 * KiB else 256 * MiB; + pub const pdf = if (reduced_target or !config.mupdf) 64 * KiB else 512 * MiB; /// One language query's working memory (its parsed answers, the rows /// it writes): a hard bound, nothing spills. Callstack walks until it /// would leave less than its rendering reserve. - pub const lsp_query = if (board or reduced_target) 0 else 256 * MiB; + pub const lsp_query = if (reduced_target) 0 else 256 * MiB; }; }; @@ -79,7 +75,7 @@ pub const Allocators = struct { pdf: Allocator, }; -/// A freestanding target's arena (web, board): `std.heap.StackFallbackAllocator` +/// A freestanding target's arena (the web's): `std.heap.StackFallbackAllocator` /// with the buffer taken through its lock-free interface. A /// FixedBufferAllocator frees only its last block, so once a big operation /// fills the buffer everything after spills; a native target uses `Pages`. The core's allocator is used from two threads: a 9P @@ -598,7 +594,7 @@ test "a region's runs: aligned first fit, growth in place, release" { } test "memory limits preserve desktop capacities" { - if (board or reduced_target) return error.SkipZigTest; + if (reduced_target) return error.SkipZigTest; try std.testing.expectEqual(4096, limits.effect_cap); try std.testing.expectEqual(@as(usize, 4 * MiB), limits.pending_write_cap); try std.testing.expectEqual(256, limits.wrap_rows); @@ -608,7 +604,6 @@ test "memory limits preserve desktop capacities" { try std.testing.expectEqual(@as(usize, 4096), limits.max_tag_tail); try std.testing.expectEqual(@as(usize, 4095), limits.host_path_cap); try std.testing.expectEqual(config.embed_sources, limits.embedded_sources); - try std.testing.expectEqual(@as(u32, 16), limits.hexdump_row_bytes); try std.testing.expectEqual(1024 * MiB, limits.arena.pardes); try std.testing.expectEqual(64 * MiB, limits.arena.frame); try std.testing.expectEqual(512 * MiB, limits.arena.lsp); diff --git a/src/mouse.zig b/src/mouse.zig index b6650cc5..6cec562d 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -1157,7 +1157,7 @@ fn mirrorTtySelection(p: *Pardes, pane: *Pane) void { /// left. A plain click still puts the caret on its cell. fn doubleClick(p: *Pardes, id: usize, t: *panes.Text, on_tag: bool, row: i32, col: i32) void { // The host's clock, which every host keeps (a libc clock is no clock on - // the web or the board) and a test's virtual one replaces. + // the web) and a test's virtual one replaces. const now: i64 = @intCast(p.now_ns / std.time.ns_per_ms); const prev = p.last_click; p.last_click = .{ .id = id, .on_tag = on_tag, .row = row, .col = col, .ms = now }; @@ -1998,7 +1998,6 @@ test "a chorded exec an event reader holds is told with its argument, and writte } test "a wheel over a program that owns it is the program's, in the form it asked for; a shell's scrolls" { - if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); defer p.deinit(); @@ -2094,7 +2093,6 @@ test "Alt-click is B2 and Super-click B3, kept from the press through the releas } test "a program tracking the mouse gets its clicks, drags and moves over its grid as xterm reports them; Shift and chrome stay pardes's" { - if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 16, .tty_only = true }); defer p.deinit(); diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index b8356681..e212d67d 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -137,8 +137,7 @@ pub fn readStatus(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { // Busy is what a run written now would be told: a command is running // or a line is typed at the prompt. Before the shell's first prompt a // run waits for it rather than answer busy, so that is not busy. - // A build with no terminal panes (the board) has no marks to read. - const marks = if (comptime !pardes.panes.terminal.enabled) null else if (pane.terminal) |state| &state.stream.handler else null; + const marks = if (pane.terminal) |state| &state.stream.handler else null; const busy = p.hostTtyTaken(id) or (!pane.fs.unmarked and (waitingRun(p, pane) != null or (if (marks) |m| m.prompts > 0 and (m.phase != .input or !pardes.panes.terminal.promptInputEmpty(pane)) else false))); const out = p.fs.stage(p.gpa); @@ -219,7 +218,6 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { slot.* = .{}; if (std.mem.trim(u8, line, " \t").len == 0) return tree.failText(req.tag, E.INVAL, e_bad_line); for (line) |c| if (c < ' ' and c != '\t') return tree.failText(req.tag, E.INVAL, e_bad_line); - if (comptime !pardes.panes.terminal.enabled) return tree.failText(req.tag, E.INVAL, e_bad_line); const pf = &pane.fs; const state = pane.terminal orelse return tree.failText(req.tag, E.INVAL, e_bad_line); const marks = &state.stream.handler; @@ -287,7 +285,6 @@ pub fn readRun(p: *Pardes, req: Req) Reply { /// for the prompt means whoever reads the answer can send the next command /// at once instead of finding the shell still drawing it. pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { - if (comptime !pardes.panes.terminal.enabled) return; const state = pane.terminal orelse return; const pf = &pane.fs; const slot = waitingRun(p, pane) orelse return; diff --git a/src/pager.zig b/src/pager.zig index ed3b9c35..9102fb84 100644 --- a/src/pager.zig +++ b/src/pager.zig @@ -7,7 +7,7 @@ const std = @import("std"); const pardes = @import("pardes.zig"); const CellStyle = @import("surface.zig").CellStyle; -const ghostty_vt = if (pardes.terminal_panes) @import("ghostty-vt") else struct {}; +const ghostty_vt = @import("ghostty-vt"); /// Bytes `start..end` of the text, drawn in `style`. A palette colour stays /// `.index`, resolved through the theme as it is drawn (terminal.palColor), @@ -31,9 +31,6 @@ pub const Page = struct { /// `raw`, a program's output for a terminal, as text and, `colour` on /// (PagerColor), its spans. Both are `gpa`'s. pub fn parse(gpa: std.mem.Allocator, raw: []const u8, colour: bool) !Page { - // ponytail: no ghostty-vt on esp32p4 (no terminal panes, no PAGER): - // the text is taken as sent. - if (comptime !pardes.terminal_panes) return .{ .text = try gpa.dupe(u8, raw), .spans = &.{} }; var h: Handler = .{ .gpa = gpa, .colour = colour }; errdefer h.text.deinit(gpa); errdefer h.spans.deinit(gpa); @@ -252,7 +249,6 @@ const testing = std.testing; /// The text `raw` pages to, and its spans as `text[start..end]=style` lines. fn expectPage(raw: []const u8, text: []const u8, spans: []const struct { []const u8, CellStyle }) !void { - if (comptime !pardes.terminal_panes) return error.SkipZigTest; const page = try parse(testing.allocator, raw, true); defer page.deinit(testing.allocator); try testing.expectEqualStrings(text, page.text); @@ -355,7 +351,6 @@ test "bytes that are not UTF-8 page as U+FFFD, the text around them kept" { } test "PagerColor off: the same text, no spans, overstrike included" { - if (comptime !pardes.terminal_panes) return error.SkipZigTest; const page = try parse(testing.allocator, "\x1b[31mred\x1b[m N\x08N\n", false); defer page.deinit(testing.allocator); try testing.expectEqualStrings("red N\n", page.text); diff --git a/src/pardes.zig b/src/pardes.zig index 32bf9cba..c3d12932 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -58,7 +58,7 @@ pub const pdf = panes.Pdf.pdf; pub const memory = @import("memory.zig"); pub const tape = @import("tape.zig"); pub const walk = @import("walk.zig"); -pub const screen_state = if (terminal_panes) @import("screen_state.zig") else struct {}; +pub const screen_state = @import("screen_state.zig"); pub const views = @import("views.zig"); pub const rollback = @import("rollback.zig"); pub const replica = @import("replica.zig"); @@ -102,7 +102,7 @@ pub const hosted = platform == .tui or platform == .gui or platform == .macos; /// is never the syscall's own. /// /// One per process, like the editor it belongs to. A process that never -/// starts it -- a test, the board, the browser -- has no second thread, and +/// starts it -- a test, the browser -- has no second thread, and /// every yield is a no-op. pub var turn: Turn = .{}; @@ -229,8 +229,6 @@ pub const Turn = struct { pub const can_attach = platform == .tui or platform == .gui; -pub const terminal_panes = platform != .esp32p4; - pub const fonts = if (font_picker) @import("fonts.zig") else struct {}; pub const PdfRasterPolicy = panes.Pdf.RasterPolicy; @@ -250,19 +248,19 @@ pub const pdf_raster_policy: PdfRasterPolicy = switch (platform) { // Both pixel shells rasterize for a real display and can afford it; the // wire-bandwidth argument that shapes the Kitty policy does not apply. .gui, .macos => sdl_pdf_raster_policy, - // Neither hostless platform rasterizes a PDF at all (mupdf is compiled - // out), so the cheaper policy is the honest placeholder. - .web, .esp32p4 => kitty_pdf_raster_policy, + // The web rasterizes no PDF at all (mupdf is compiled out), so the + // cheaper policy is the honest placeholder. + .web => kitty_pdf_raster_policy, }; pub const Pane = panes.Pane; const Text = panes.Text; -/// Pane slots: 64 on a desktop, where a session keeps many files and -/// terminals open; the board keeps its 16. A slot costs its share of the -/// fixed tables (MAX_PANES-sized arrays in the core and its surface) whether -/// or not a pane is in it; a pane itself is allocated when it opens. -pub const MAX_PANES = if (platform == .esp32p4) 16 else 64; +/// Pane slots, where a session keeps many files and terminals open. A slot +/// costs its share of the fixed tables (MAX_PANES-sized arrays in the core +/// and its surface) whether or not a pane is in it; a pane itself is +/// allocated when it opens. +pub const MAX_PANES = 64; pub const Layer = @import("Layer.zig"); pub const RowMetrics = Layer.Metrics; pub const TagHit = Layer.TagHit; @@ -275,9 +273,9 @@ pub const MAX_TAG_ROWS = 8; pub const MAX_TAG_LAYERS = MAX_PANES + MAX_COLS + 1 + MAX_PANES * Pane.Notices.max; pub const NOTICE_LAYER_BASE = MAX_PANES + MAX_COLS + 1; pub const PDF_PAGE_GAP_PX = panes.Pdf.page_gap_px; -/// Columns a session holds: 16 on a desktop (each costs about 8 KB of state, -/// a column tag being most of it), 6 on the board. -pub const MAX_COLS = if (platform == .esp32p4) 6 else 16; +/// Columns a session holds (each costs about 8 KB of state, a column tag +/// being most of it). +pub const MAX_COLS = 16; const column_weight_unit = layout.column_weight_unit; pub const MAX_JUMPS = 64; pub const TOPBAR_H: u16 = 1; @@ -2674,45 +2672,6 @@ pub fn pathUnder(a: []const u8, b: []const u8) bool { const tutor_text = @embedFile("tutor.txt"); -const boot_buffer = - \\x selects a line, Tab runs it. 0x optional. - \\ - \\-- flash: this image's rodata, then its code - \\Hexdump 40000020 40 - \\Hexdump 40050000 40 - \\-- L2MEM: firmware data, then the heap - \\Hexdump 4ff00000 40 - \\Hexdump 4ff40000 40 - \\-- the mask ROM - \\Hexdump 4fc00000 20 - \\-- UART0, the console you are reading on - \\Peek 500ca000 4 - \\-- LP_STORE0: write a word, read it back - \\Poke 5011002c deadbeef - \\Peek 5011002c - \\-- RNG_DATA: not memory. Run it twice. - \\Peek 501101a4 - \\Peek 501101a4 - \\-- the pins: Gpio draws JP1, Gpio 33 flips - \\Gpio - \\Gpio 33 -; - -test "every line of the board's boot buffer renders whole" { - const cols: usize = @import("pardes_config").esp32p4_cols; - var it = std.mem.splitScalar(u8, boot_buffer, '\n'); - while (it.next()) |line| { - std.testing.expect(line.len + 8 <= cols) catch |err| { - std.debug.print("boot buffer line is {d} of {d} usable: \"{s}\"\n", .{ line.len, cols - 8, line }); - return err; - }; - } - // and the tour still visits what it says it visits - try std.testing.expect(std.mem.indexOf(u8, boot_buffer, "Hexdump 40000020") != null); - try std.testing.expect(std.mem.indexOf(u8, boot_buffer, "Poke 5011002c deadbeef") != null); - try std.testing.expect(std.mem.indexOf(u8, boot_buffer, "\nGpio\n") != null); -} - test "Tab N draws every pane's tab N cells wide and clicks count past it; bare Tab says the width; the ctl read and a Dump keep it" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 12 }); @@ -3663,8 +3622,6 @@ pub const Boot = enum { missing, /// `pardes -`: stdin's text in a +Pager pane, as `vim -` shows it stdin, - /// the firmware's boot buffer, the only pane a board has - embedded, /// the bare tty startup: one shell in raw tty mode, with an empty text /// pane under it so the editor half is there before you want it tty, @@ -3680,7 +3637,6 @@ pub const Boot = enum { if (opts.file != null) return .document; if (opts.missing != null) return .missing; if (opts.stdin_text != null) return .stdin; - if (comptime platform == .esp32p4) return .embedded; if (opts.tty_only) return .tty_shell; // ponytail: 1 and 3 are the only shell counts anyone asked for return if (opts.shells >= 3) .classic else .shell; @@ -4244,12 +4200,6 @@ pub const Pardes = struct { shown.file.?.pager_spans = page.spans; p.oneColumn(); }, - .embedded => { - const content = try p.gpa.dupe(u8, boot_buffer); - errdefer p.gpa.free(content); - _ = try panes.Output.open(p, 0, "", .{ .cmd = .New }, "", content); - p.oneColumn(); - }, .tty, .tty_shell => { _ = try p.newShell(0, ""); p.panes[0].?.body.mode = .tty; @@ -4314,7 +4264,7 @@ pub const Pardes = struct { /// remembered for want of memory is no failure of what opened it), so /// on a host it takes from the process heap, not the editor's, whose /// every failure must be answered. - // ponytail: a host heap for a best-effort list; the board's gpa there. + // ponytail: a host heap for a best-effort list; the browser's gpa there. pub fn recentGpa(p: *const Pardes) std.mem.Allocator { return if (comptime hosted) std.heap.smp_allocator else p.gpa; } @@ -4841,7 +4791,6 @@ pub const Pardes = struct { } fn parkPendingWrite(p: *Pardes, id: usize, bytes: []const u8) void { - if (comptime limits.pending_write_cap == 0) return; if (p.pending_write_bytes + bytes.len > limits.pending_write_cap) return; if (p.pending_write[id]) |*pw| { // Compact what the drain already sent before growing: a burst that @@ -7222,10 +7171,10 @@ pub const Pardes = struct { // What the terminal answers its program (a cursor report, its // attributes) goes as typed bytes go: behind whatever is still // queued for its pty, never ahead of it nor dropped. - if (comptime terminal_panes) if (pane.terminal) |state| { + if (pane.terminal) |state| { p.emitWrite(id, state.reply[0..state.reply_len]); state.reply_len = 0; - }; + } const r = p.rects[id]; // The session's part of the pane's view geometry (File.geometry), // and its context declarations. @@ -7416,7 +7365,7 @@ pub const Pardes = struct { // A terminal's kitty animation, at its next frame. Only a time still // ahead counts: a pane not drawn keeps the last one it was given, // and a past one would wake every frame for nothing. - if (comptime terminal_panes) for (p.panes) |slot| if (slot) |pane| if (panes.terminal.animationDueMs(pane)) |due_ms| { + for (p.panes) |slot| if (slot) |pane| if (panes.terminal.animationDueMs(pane)) |due_ms| { const due = due_ms *| std.time.ns_per_ms; if (due > p.stepped_ns) { const wait = @max(1, (due - p.stepped_ns + animation.frame_ns - 1) / animation.frame_ns); @@ -7435,8 +7384,8 @@ pub const Pardes = struct { return p.cursor_glide.moving() or p.shell_continuous or panes.Pdf.moving(p); } - /// For shells that only need a yes or no: macOS and the board, which - /// keep their own frame banks. + /// For shells that only need a yes or no: macOS, which keeps its own + /// frame bank. pub fn animationActive(p: *const Pardes) bool { return p.nextWake() != null or p.continuous(); } @@ -7600,7 +7549,6 @@ test "argv naming nothing boots an errors pane rather than failing the launch" { } test "raw terminal cursor obeys visibility without hiding modal and tag cursors" { - if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); @@ -7645,7 +7593,6 @@ test "raw terminal cursor obeys visibility without hiding modal and tag cursors" } test "raw terminal cursor follows its active row only while that row is visible" { - if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; for ([_]bool{ false, true }) |tag_bottom| { const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); @@ -8291,7 +8238,6 @@ test "a paste larger than the effect ring reaches the program whole and in order test "a bracketed paste larger than the ring still closes its bracket" { if (platform == .web) return; - if (comptime !panes.terminal.enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -8315,7 +8261,6 @@ test "a bracketed paste larger than the ring still closes its bracket" { test "a terminal's answer to its program waits behind the paste still queued for its pty" { if (platform == .web) return; - if (comptime !panes.terminal.enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -8474,44 +8419,12 @@ test "entering tty walks the shell cursor to the column clicked past the prompt" try std.testing.expectEqual(@as(usize, 7), lefts); } -const board_cols: u16 = 56; -const board_rows: u16 = 14; - -fn boardBudgetOptions(gpa: std.mem.Allocator, cols: u16, rows: u16) Options { - return .{ - .cols = cols, - .rows = rows, - .tty_only = true, - .frame_allocator = gpa, - .image_allocator = gpa, - .pdf_allocator = gpa, - .tree_sitter_allocator = gpa, - }; -} - -fn bootAndTearDown(gpa: std.mem.Allocator, cols: u16, rows: u16) !void { - const p = try Pardes.init(gpa, boardBudgetOptions(gpa, cols, rows)); +fn bootAndTearDown(gpa: std.mem.Allocator) !void { + const p = try Pardes.init(gpa, .{ .cols = 56, .rows = 14, .tty_only = true, .frame_allocator = gpa, .image_allocator = gpa, .pdf_allocator = gpa, .tree_sitter_allocator = gpa }); p.deinit(); } -test "board heap: every inline ring the board pays for still fits its budget" { - const heap = limits.board_heap_bytes; - - const effect_ring = 128 * @sizeOf(Effect); - // ...and the undo history, the largest in `Pane` once the terminal is out: - // 16 snapshots on the board against 256 on a desktop. - const undo_history = 2 * 16 * @sizeOf(panes.terminal.Snapshot); - const grid = @as(usize, board_cols) * board_rows * (2 * @sizeOf(Cell) + @sizeOf(PanelCellDiff)); - - // Each of the three separately, so a failure names the one that grew - // instead of reporting a total nobody can attribute. - try std.testing.expect(effect_ring <= heap / 8); - try std.testing.expect(undo_history <= heap / 32); - try std.testing.expect(grid <= heap / 8); - try std.testing.expect(effect_ring + undo_history + grid <= heap / 2); -} - -test "board heap: transition grids fit the budget and the surface borrows its snapshots" { +test "transition grids: the surface borrows its snapshots" { const per_cell = 2 * @sizeOf(Cell) + @sizeOf(PanelCellDiff); const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 16, .tty_only = true }); @@ -8538,9 +8451,6 @@ test "board heap: transition grids fit the budget and the surface borrows its sn p.presentation.previous_cells.len * @sizeOf(Cell) + p.presentation.diffs.len * @sizeOf(PanelCellDiff); try std.testing.expectEqual(cells * per_cell, owned); - - try std.testing.expect(@as(usize, board_cols) * board_rows * per_cell <= - limits.board_heap_bytes / 8); } test "LSP failure clears only its matching wait without completion indentation" { @@ -8569,12 +8479,8 @@ test "LSP failure clears only its matching wait without completion indentation" try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col); } -test "board heap: every allocation failure during boot is a clean OutOfMemory" { - try std.testing.checkAllAllocationFailures( - std.testing.allocator, - bootAndTearDown, - .{ board_cols, board_rows }, - ); +test "every allocation failure during boot is a clean OutOfMemory" { + try std.testing.checkAllAllocationFailures(std.testing.allocator, bootAndTearDown, .{}); } test "jump history skips an entry whose pane slot or serial is gone, leaving the selection" { @@ -8692,7 +8598,6 @@ test "Back and Forward take the same steps from the mouse's side buttons and jum } test "jump history terminal rectangle follows output and clears on reflow" { - if (comptime !terminal_panes) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12, .tty_only = true }); defer p.deinit(); const pane = p.panes[0].?; diff --git a/src/replica.zig b/src/replica.zig index 70b7c4bc..858c8e01 100644 --- a/src/replica.zig +++ b/src/replica.zig @@ -3180,7 +3180,6 @@ test "another client's input first: a replica rolls back, replays it and applies } test "a delta applied under a speculation outlives its rollback: the terminal stays the authority's newest" { - if (comptime !terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true); defer a.deinit(); @@ -3269,7 +3268,6 @@ test "a delta applied under a speculation outlives its rollback: the terminal st } test "a closed terminal brought back on a screen-state replica: its emulator on the C heap, never the rollback epoch's" { - if (comptime !terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true); defer a.deinit(); @@ -3294,7 +3292,6 @@ test "a closed terminal brought back on a screen-state replica: its emulator on } test "a view that sized a terminal closing leaves nothing queued: the others' replicas copy, type and agree" { - if (comptime !terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 100, .rows = 30, .boot = .tty }, TestHost.host(), true); defer a.deinit(); @@ -3341,7 +3338,6 @@ test "a view that sized a terminal closing leaves nothing queued: the others' re } test "a terminal sized again by a client's key: the step reads the grid it had, on both sides" { - if (comptime !terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 50, .rows = 20, .boot = .tty }, TestHost.host(), true); defer a.deinit(); @@ -3444,7 +3440,6 @@ fn deliver(a: *Authority, screens: *Screens, peer: u16, r: *Replica, comptime wh } test "pardes's own keys over a terminal's history apply at once: its view moves here, a delta while they wait puts them on top again, the authority's ends the same" { - if (comptime !terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true); defer a.deinit(); @@ -3957,7 +3952,6 @@ fn inputOf(buf: []u8, client: u16, seq: u32, ev: pardes.Event) ![]const u8 { } test "a client leaves, and one joins: what the leave queued (a terminal's resize) is done in its unit, on every side, before the join's dump" { - if (comptime !terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, PtyHost.host(), true); defer a.deinit(); @@ -4121,7 +4115,6 @@ fn sendAs(r: *Replica, a: *Authority, screens: *Screens, rs: []const *Replica, p } test "a step that reads a terminal's rows as the core keeps them sends a new client the ones it holds as holes" { - if (comptime !terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, PtyHost.host(), true); defer a.deinit(); diff --git a/src/terminal.zig b/src/terminal.zig index 7cb429d9..9aa97f71 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -14,19 +14,18 @@ const Pane = panes.Pane; const EditText = panes.EditText; const File = panes.File; -pub const enabled = pardes.terminal_panes; -const ghostty_vt = if (enabled) @import("ghostty-vt") else struct {}; +const ghostty_vt = @import("ghostty-vt"); -pub const history_max = if (enabled) 64 else 8; +pub const history_max = 64; -pub const VtSlot = if (enabled) ghostty_vt.Terminal else void; +pub const VtSlot = ghostty_vt.Terminal; /// A cell of an emulator's pages, as `getCell` reads it (src/echo.zig). -pub const PageCell = if (enabled) ghostty_vt.PageList.Cell else void; +pub const PageCell = ghostty_vt.PageList.Cell; /// Kitty graphics are drawn where pixel geometry is (pdf_enabled, as for /// image panes' native placements). -pub const images_enabled = enabled and pardes.pdf_enabled; +pub const images_enabled = pardes.pdf_enabled; pub const TerminalImages = if (images_enabled) @import("TerminalImages.zig") else void; -pub const StreamSlot = if (enabled) ghostty_vt.Stream(MarkedHandler) else void; +pub const StreamSlot = ghostty_vt.Stream(MarkedHandler); /// The `aid` pardes's injected bash and fish marks carry (host_io.zig). pub const prompt_aid = "pardes"; @@ -36,7 +35,7 @@ pub const prompt_aid = "pardes"; /// it, and /pane/<n>/pty/run waits on exactly that. Only marks carrying /// pardes's own `aid` move it, so fish's native marks, a nested shell's /// and a stray `133;D` in some file being printed all pass it by. -pub const MarkedHandler = if (enabled) struct { +pub const MarkedHandler = struct { inner: ghostty_vt.TerminalStream.Handler, phase: enum { none, prompt, input, running } = .none, /// Counts commands started (C at the input phase). @@ -142,7 +141,7 @@ pub const MarkedHandler = if (enabled) struct { pub fn deinit(self: *@This()) void { self.inner.deinit(); } -} else void; +}; pub const State = struct { /// What the emulator and this struct are allocated with: the core's, @@ -162,7 +161,7 @@ pub const State = struct { reply_dropped: u32 = 0, /// The grid cell the program last heard the mouse at, so motion is /// reported once per cell. - mouse_cell: if (enabled) ?ghostty_vt.Coordinate else void = if (enabled) null else {}, + mouse_cell: ?ghostty_vt.Coordinate = null, /// The kitty graphics its program placed, as drawn (TerminalImages.zig). images: TerminalImages = if (images_enabled) .{} else {}, /// Counts the emulator's writes (output, a resize, its view scrolled): @@ -187,7 +186,6 @@ pub const State = struct { /// a replica's terminal is the authority's screen state from phase 5 /// on (docs/next-daemon.md). pub fn digest(s: *const State, h: *pardes.walk.Hasher) void { - if (comptime !enabled) return; // Under screen-state terminals the emulator is the authority's, and // a replica's is what the last delta made it: compared as screens // (test/replicas.zig), not step by step. @@ -197,7 +195,6 @@ pub const State = struct { /// `view`: where its view is too (a replica's speculation may move it). pub fn digestScreen(s: *const State, h: *pardes.walk.Hasher, view: bool) void { - if (comptime !enabled) return; const screen = s.vt.screens.active; const sb = screen.pages.scrollbar(); const cur = screen.cursor; @@ -244,7 +241,6 @@ pub const State = struct { /// its program had begun and not ended is not kept: the snapshot is at /// the ground state. pub fn dumpWrite(s: *const State, gpa: std.mem.Allocator, w: *std.Io.Writer) !void { - if (comptime !enabled) return; const h = &s.stream.handler; const parts: Parts = .{ .reply = s.reply[0..s.reply_len], @@ -274,7 +270,6 @@ pub const State = struct { /// What `dumpRead` made, freed: a load that failed after it. pub fn dumpFree(s: *State, gpa: std.mem.Allocator) void { - if (comptime !enabled) return; if (comptime images_enabled) s.images.deinit(gpa); s.stream.deinit(); s.vt.deinit(gpa); @@ -282,10 +277,6 @@ pub const State = struct { /// `dumpWrite`'s back into `out`, a new State, as `create` makes one. pub fn dumpRead(out: *State, gpa: std.mem.Allocator, bytes: []const u8) !void { - if (comptime !enabled) { - out.* = .{ .vt = {}, .stream = {} }; - return; - } if (bytes.len < 8) return error.EndOfDump; const n = std.math.cast(usize, std.mem.bytesToValue(u64, bytes[0..8])) orelse return error.EndOfDump; if (bytes.len - 8 < n) return error.EndOfDump; @@ -352,7 +343,7 @@ const FilterPaletteKey = struct { base: [16]GColor.RGB, }; -pub const FilterPalette = if (enabled) LivePalette else struct {}; +pub const FilterPalette = LivePalette; const LivePalette = struct { key: ?FilterPaletteKey = null, @@ -428,7 +419,6 @@ pub const PendingCommand = struct { }; pub fn armShellSpawn(pane: *Pane) void { - if (comptime !enabled) return; std.debug.assert(pane.pending_command.bytes.len == 0); pane.pending_command.wait = .spawn; } @@ -438,7 +428,6 @@ pub fn armShellSpawn(pane: *Pane) void { /// ponytail: of several lines queued for a shell not up yet, only the last /// is remembered, as the first of them. pub fn noteCommand(pane: *Pane, line: []const u8) void { - if (comptime !enabled) return; const state = pane.terminal orelse return; const word = std.mem.trim(u8, line, " \t")[0 .. std.mem.indexOfAny(u8, std.mem.trim(u8, line, " \t"), " \t") orelse std.mem.trim(u8, line, " \t").len]; var sent: @typeInfo(@FieldType(Pane, "sent_command")).optional.child = .{ .seq = state.stream.handler.started +% 1 }; @@ -449,7 +438,6 @@ pub fn noteCommand(pane: *Pane, line: []const u8) void { /// Whether the command pardes last typed here is running now. pub fn commandRunning(pane: *const Pane) bool { - if (comptime !enabled) return false; const state = pane.terminal orelse return false; const sent = pane.sent_command orelse return false; const marks = &state.stream.handler; @@ -525,7 +513,6 @@ pub fn terminalIo() std.Io { pub const Scrollbar = struct { total: usize = 0, offset: usize = 0, len: usize = 0 }; pub fn scrollbar(pane: *const Pane) Scrollbar { - if (comptime !enabled) return .{}; const state = pane.terminal orelse return .{}; const sb = state.vt.screens.active.pages.scrollbar(); return .{ .total = sb.total, .offset = sb.offset, .len = sb.len }; @@ -541,14 +528,12 @@ pub fn gridOffset(pane: *const Pane) i32 { pub const GridCursor = struct { x: u16 = 0, y: u16 = 0 }; pub fn gridCursor(pane: *const Pane) GridCursor { - if (comptime !enabled) return .{}; const state = pane.terminal orelse return .{}; const cur = state.vt.screens.active.cursor; return .{ .x = @intCast(cur.x), .y = @intCast(cur.y) }; } pub fn visibleCursor(pane: *const Pane) ?GridCursor { - if (comptime !enabled) return null; const state = pane.terminal orelse return null; if (!state.vt.modes.get(.cursor_visible)) return null; const cur = state.vt.screens.active.cursor; @@ -563,7 +548,6 @@ pub fn visibleCursor(pane: *const Pane) ?GridCursor { /// many as keep its cursor's row in sight, as tmux pans a bigger window in /// a smaller client. 0 in the view that sizes it, and in one tall enough. pub fn panFor(p: *const Pardes, pane: *const Pane, r: pardes.Rect) u16 { - if (comptime !enabled) return 0; if (pane.sized_by == p.view or pane.collapsed or !pane.isTerminal()) return 0; const shown = r.h -| pane.tag_rows; if (shown == 0 or shown >= pane.rows) return 0; @@ -584,7 +568,6 @@ pub fn panFor(p: *const Pardes, pane: *const Pane, r: pardes.Rect) u16 { pub const marks_len = 1 + 4 * 3 + 2 + 4 + 4; pub fn marksOf(state: *const State, buf: *[marks_len]u8) []const u8 { - if (comptime !enabled) return &.{}; const m = &state.stream.handler; var w: std.Io.Writer = .fixed(buf); w.writeByte(@intFromEnum(m.phase)) catch unreachable; @@ -597,7 +580,6 @@ pub fn marksOf(state: *const State, buf: *[marks_len]u8) []const u8 { /// A replica's terminal takes its authority's marks (`marksOf`). pub fn takeMarks(state: *State, bytes: []const u8) void { - if (comptime !enabled) return; if (bytes.len != marks_len) return; const m = &state.stream.handler; m.phase = @enumFromInt(bytes[0]); @@ -646,7 +628,6 @@ fn viewOnly(comptime why: []const u8) bool { /// history, or null following its output (a replica's rollback copy, /// which holds no emulator, keeps it so). pub fn viewOf(pane: *const Pane) ?usize { - if (comptime !enabled) return null; const state = pane.terminal orelse return null; const pages = &state.vt.screens.active.pages; if (pages.viewport == .active) return null; @@ -654,14 +635,12 @@ pub fn viewOf(pane: *const Pane) ?usize { } pub fn viewTo(pane: *Pane, at: ?usize) void { - if (comptime !enabled) return; const state = pane.terminal orelse return; state.vt.screens.active.scroll(if (at) |row| .{ .row = row } else .active); } /// Move the emulator's viewport by `delta` shell rows (negative scrolls back). pub fn scrollGrid(pane: *Pane, delta: i32) void { - if (comptime !enabled) return; if (viewOnly("scroll a terminal")) return; const state = pane.terminal orelse return; state.vt.screens.active.scroll(.{ .delta_row = delta }); @@ -670,14 +649,12 @@ pub fn scrollGrid(pane: *Pane, delta: i32) void { /// Is the viewport already showing the last row of output? pub fn atBottom(pane: *const Pane) bool { - if (comptime !enabled) return true; const sb = scrollbar(pane); return sb.offset + sb.len >= sb.total; } /// Snap the viewport back onto live output. pub fn followOutput(pane: *Pane) void { - if (comptime !enabled) return; if (viewOnly("follow a terminal")) return; const state = pane.terminal orelse return; const moved = state.vt.screens.active.pages.viewport != .active; @@ -688,7 +665,6 @@ pub fn followOutput(pane: *Pane) void { /// Reflow the grid. A failed reflow keeps the grid it had rather than dropping /// a scrollback; the next resize retries with the same numbers. pub fn resizeGrid(pane: *Pane, cols: u16, rows: u16) void { - if (comptime !enabled) return; if (authorityOnly("resize a terminal")) return; const state = pane.terminal orelse return; if (cols != pane.cols) for (0..pane.sel.len) |button| { @@ -711,7 +687,6 @@ pub fn resizeGrid(pane: *Pane, cols: u16, rows: u16) void { /// The sizes steps gave terminals (`resizeGrid`), made: between units, on an /// authority with screen-state replicas (replica.Peers.unit). pub fn resizeDeferred(p: *Pardes) void { - if (comptime !enabled) return; for (p.panes) |slot| if (slot) |pane| if (pane.terminal) |state| if (state.resize_to) |size| { state.resize_to = null; state.changes +%= 1; @@ -722,14 +697,12 @@ pub fn resizeDeferred(p: *Pardes) void { /// DECSET 2004: the program wants its pastes bracketed. pub fn bracketedPaste(pane: *const Pane) bool { - if (comptime !enabled) return false; const state = pane.terminal orelse return false; return state.vt.modes.get(.bracketed_paste); } /// The program tracks the mouse itself, so a click in its body is its event. pub fn reportsMouse(pane: *const Pane) bool { - if (comptime !enabled) return false; const state = pane.terminal orelse return false; return state.vt.flags.mouse_event != .none; } @@ -740,25 +713,17 @@ pub fn reportsMouse(pane: *const Pane) bool { /// spaces, then the text goes inside the brackets when the program set /// 2004, else with its newlines as Returns. `text` is rewritten in place. pub fn encodePaste(pane: *const Pane, text: []u8) [3][]const u8 { - if (comptime !enabled) { - for (text) |*ch| if (ch.* == '\n') { - ch.* = '\r'; - }; - return .{ "", text, "" }; - } return ghostty_vt.input.encodePaste(text, .{ .bracketed = bracketedPaste(pane) }); } /// DECSET 1004: the program wants to hear when it gains and loses focus. pub fn reportsFocus(pane: *const Pane) bool { - if (comptime !enabled) return false; const state = pane.terminal orelse return false; return state.vt.modes.get(.focus_event); } /// ...every move of it, a button down or not (1003). pub fn tracksAllMotion(pane: *const Pane) bool { - if (comptime !enabled) return false; const state = pane.terminal orelse return false; return state.vt.flags.mouse_event == .any; } @@ -767,7 +732,6 @@ pub fn tracksAllMotion(pane: *const Pane) bool { /// on the alternate screen, which has no scrollback, with alternate scroll /// (DECSET 1007, on unless turned off) asking for arrow keys instead. pub fn ownsWheel(pane: *const Pane) bool { - if (comptime !enabled) return false; const state = pane.terminal orelse return false; return reportsMouse(pane) or (state.vt.screens.active_key == .alternate and state.vt.modes.get(.mouse_alternate_scroll)); @@ -785,7 +749,6 @@ pub const MouseAction = enum { press, release, motion }; /// grid is reported clamped to its edge, motion only when the cell /// changed. Empty when the program does not hear of it. pub fn mouseBytes(pane: *Pane, buf: *[64]u8, action: MouseAction, button: ?MouseButton, mods: MouseMods, col: i32, row: i32, any_pressed: bool) []const u8 { - if (comptime !enabled) return &.{}; const state = pane.terminal orelse return &.{}; const input = ghostty_vt.input; var writer = std.Io.Writer.fixed(buf); @@ -828,7 +791,6 @@ pub fn mouseBytes(pane: *Pane, buf: *[64]u8, action: MouseAction, button: ?Mouse /// alternate screen, an arrow key in the cursor keys' mode (none for a /// sideways turn). Null when the wheel is not the program's (`ownsWheel`). pub fn wheelBytes(pane: *Pane, buf: *[64]u8, wheel: MouseButton, col: u16, row: u16, mods: MouseMods) ?[]const u8 { - if (comptime !enabled) return null; const state = pane.terminal orelse return null; if (!ownsWheel(pane)) return null; const m = &state.vt.modes; @@ -845,7 +807,6 @@ pub fn wheelBytes(pane: *Pane, buf: *[64]u8, wheel: MouseButton, col: u16, row: /// are joined again (ghostty's wrap flags, as pty/run's output is), and /// the last line ends with a newline. pub fn screenTextAlloc(pane: *Pane, gpa: std.mem.Allocator) ![]const u8 { - if (comptime !enabled) return &.{}; var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); try writeScreenText(pane, &out.writer); @@ -853,7 +814,6 @@ pub fn screenTextAlloc(pane: *Pane, gpa: std.mem.Allocator) ![]const u8 { } fn writeScreenText(pane: *Pane, w: *std.Io.Writer) !void { - if (comptime !enabled) return; const state = pane.terminal orelse return; const screen = state.vt.screens.active; const br = screen.pages.getBottomRight(.screen) orelse return; @@ -896,7 +856,6 @@ const TeeWriter = struct { /// How long `screenTextAlloc` would be, counted without keeping it: the /// length a terminal's body reads as, which its ctl line reports. pub fn screenTextLen(pane: *Pane) usize { - if (comptime !enabled) return 0; var buf: [256]u8 = undefined; var counting: std.Io.Writer.Discarding = .init(&buf); writeScreenText(pane, &counting.writer) catch return 0; @@ -905,7 +864,6 @@ pub fn screenTextLen(pane: *Pane) usize { /// Release the emulator's heap. The Pane allocation itself is the core's. pub fn deinitEmulator(pane: *Pane, gpa: std.mem.Allocator) void { - if (comptime !enabled) return; // A pane with none (a file's, a picker's, a preview's) closes in a // speculation as anywhere. const state = pane.terminal orelse return; @@ -941,7 +899,6 @@ pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { if (authorityOnly("open a terminal")) return error.OutOfMemory; const pane = try createDoc(gpa, cols, rows); errdefer gpa.destroy(pane); - if (comptime !enabled) return pane; const own = emulatorGpa(gpa); const state = try own.create(State); errdefer own.destroy(state); @@ -972,7 +929,6 @@ pub const restored_banner = "\x1b[0m\r\n\x1b[2m\u{2500}\u{2500} restored history /// history marked off from what the new shell prints, and the pane waiting /// for it like any new terminal (a line queued for the old one goes to it). pub fn reviveShell(pane: *Pane) void { - if (comptime !enabled) return; if (pane.terminal == null) return; // The primary screen, keys, cursor and mouse as a shell starts with // them, the cursor where it was (a soft reset, or leaving a primary @@ -1004,7 +960,7 @@ test "replay ownership is terminal-only and construction rolls back on allocatio const pane = if (terminal) try create(gpa, 40, 12) else try createDoc(gpa, 40, 12); defer gpa.destroy(pane); defer deinitEmulator(pane, gpa); - try std.testing.expectEqual(terminal and enabled, pane.terminal != null); + try std.testing.expectEqual(terminal, pane.terminal != null); } }; try std.testing.expect(@sizeOf(Pane) < 128 * 1024); @@ -1013,7 +969,6 @@ test "replay ownership is terminal-only and construction rolls back on allocatio } test "a terminal made fresh has no size waiting: one never resized keeps its grid when a unit is cut" { - if (comptime !enabled) return error.SkipZigTest; // Fresh memory as a Debug build's allocator hands it out: 0xAA. A field // `create` left unset read a size of 43690x43690 (fixer 2's, 2026-10-30). const Filling = struct { @@ -1072,7 +1027,6 @@ test "document construction allocates only the pane and has inert terminal defau } test "terminal state keeps parser fragments and sends emulator replies through its owner" { - if (comptime !enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); while (p.nextEffect()) |_| {} @@ -1096,7 +1050,6 @@ test "terminal state keeps parser fragments and sends emulator replies through i } test "a terminal's dump restores the cells it drew, its history and where its view was" { - if (comptime !enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); @@ -1124,7 +1077,7 @@ test "a terminal's dump restores the cells it drew, its history and where its vi } test "a restored command pane comes back finished, its command not run again" { - if (comptime !enabled or pardes.isolated) return error.SkipZigTest; + if (comptime pardes.isolated) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); defer p.deinit(); @@ -1154,7 +1107,7 @@ test "a restored command pane comes back finished, its command not run again" { } test "a restored terminal keeps its history above a marker and gets a shell where it was" { - if (comptime !enabled or pardes.isolated) return error.SkipZigTest; + if (comptime pardes.isolated) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); @@ -1191,7 +1144,6 @@ const positions_lost = "terminal edit position reset: out of memory"; /// follow it only when the body (possibly parked under a tag edit) is raw. pub fn feedOutput(p: *Pardes, pane: *Pane, bytes: []const u8) void { // There are no pty reads at all without an emulator to parse them into. - if (comptime !enabled) return; if (pane.terminal == null) return; if (authorityOnly("a terminal's output")) return; const has_positions = pane.ovl != null or pane.body.cur_pinned or pane.body.vsel.active or @@ -1488,7 +1440,6 @@ fn ingestWithPositions(pane: *Pane, bytes: []const u8) bool { } test "a position that cannot follow the output for want of memory is said on the message row, and logged" { - if (comptime !enabled) return error.SkipZigTest; var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -1509,7 +1460,6 @@ test "a position that cannot follow the output for want of memory is said on the } test "raw terminal output needs no position tracking allocations" { - if (comptime !enabled) return error.SkipZigTest; var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -1527,7 +1477,6 @@ test "raw terminal output needs no position tracking allocations" { /// A full-screen program has the emulator on its alternate screen. pub fn onAlternateScreen(pane: *const Pane) bool { - if (comptime !enabled) return false; const state = pane.terminal orelse return false; return state.vt.screens.active_key == .alternate; } @@ -1539,7 +1488,6 @@ pub fn onAlternateScreen(pane: *const Pane) bool { /// been typed first, and an `ls` then would go into it. A shell pardes /// cannot mark has no first prompt to find, and is never greeted. pub fn greeting(pane: *const Pane) enum { wait, now, never } { - if (comptime !enabled) return .never; if (pane.fs.unmarked) return .never; // Text typed into the edit buffer that stands in for the prompt row. if (pane.ovl) |o| if (o.text.len > 0) return .never; @@ -1557,7 +1505,6 @@ pub fn greeting(pane: *const Pane) enum { wait, now, never } { /// there (htop, `sig KILL`) left the emulator and the shell then drew its /// prompt, marks and all. A full-screen program draws no prompt marks. pub fn promptInputReady(pane: *const Pane) bool { - if (comptime !enabled) return false; const state = pane.terminal orelse return false; return state.vt.screens.active.cursor.semantic_content == .input; } @@ -1580,7 +1527,6 @@ pub const CommandOutput = struct { /// The shell exited in the middle of a command (its `exit 3`): no end mark /// will come, so the command's output ends where the cursor is. pub fn endOutputHere(pane: *Pane) void { - if (comptime !enabled) return; const state = pane.terminal orelse return; const marks = &state.stream.handler; if (marks.phase == .running and marks.out_end == null) marks.pinCursor(&marks.out_end, true); @@ -1589,7 +1535,7 @@ pub fn endOutputHere(pane: *Pane) void { pub fn commandOutput(pane: *Pane, gpa: std.mem.Allocator, max_rows: usize) !CommandOutput { // Unless there is text to read, whether the nothing it printed is the // whole of it. - const whole = if (comptime enabled) printed: { + const whole = printed: { const state = pane.terminal orelse break :printed true; const marks = &state.stream.handler; const start = marks.out_start orelse break :printed false; @@ -1615,7 +1561,7 @@ pub fn commandOutput(pane: *Pane, gpa: std.mem.Allocator, max_rows: usize) !Comm .text = try screen.selectionString(gpa, .{ .sel = ghostty_vt.Selection.init(from, last, false) }), .whole = whole, }; - } else true; + }; return .{ .text = try gpa.dupeSentinel(u8, "", 0), .whole = whole }; } @@ -1624,7 +1570,6 @@ pub fn commandOutput(pane: *Pane, gpa: std.mem.Allocator, max_rows: usize) !Comm /// cursor). Nothing further right counts: that is where fish draws a /// right prompt, and fish suggests nothing on an empty line. pub fn promptInputEmpty(pane: *const Pane) bool { - if (comptime !enabled) return false; if (!promptInputReady(pane)) return false; const cursor = &pane.terminal.?.vt.screens.active.cursor; const row = cursor.page_pin.cells(.all); @@ -1636,107 +1581,75 @@ pub fn promptInputEmpty(pane: *const Pane) bool { /// Encode one key for the program that owns a raw terminal and queue its pty /// write, respecting the application's keyboard protocol and terminal modes. pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { - if (comptime enabled) { - const pane = p.panes[id] orelse return; - const state = pane.terminal orelse return; - const input = ghostty_vt.input; - const function_keys = comptime keys: { - var keys: [Key.f25 - Key.f1 + 1]input.Key = undefined; - for (&keys, 1..) |*k, n| k.* = @field(input.Key, std.fmt.comptimePrint("f{d}", .{n})); - break :keys keys; - }; - const physical: input.Key = switch (key.cp) { - Key.enter => .enter, - Key.backspace => .backspace, - Key.tab => .tab, - Key.escape => .escape, - Key.up => .arrow_up, - Key.down => .arrow_down, - Key.left => .arrow_left, - Key.right => .arrow_right, - Key.home => .home, - Key.end => .end, - Key.page_up => .page_up, - Key.page_down => .page_down, - Key.delete => .delete, - Key.insert => .insert, - Key.print_screen => .print_screen, - Key.scroll_lock => .scroll_lock, - Key.pause => .pause, - Key.menu => .context_menu, - Key.f1...Key.f25 => function_keys[key.cp - Key.f1], - else => if (key.cp < 128) input.Key.fromASCII(@intCast(key.cp)) orelse .unidentified else .unidentified, - }; - var utf8: [4]u8 = undefined; - const text_cp = if (key.shift and key.cp >= 'a' and key.cp <= 'z') key.cp - 'a' + 'A' else key.cp; - // A key with no text of its own types its code point only when that - // is a character: the kitty keyboard protocol numbers function and - // modifier keys in the private use area (F3 is U+E016), and a shell - // was typed those as junk. - const text = if (key.text.len > 0) key.text else if (key.cp >= 32 and key.cp < Key.up and key.cp != Key.backspace and !(key.cp >= 0xE000 and key.cp <= 0xF8FF)) - utf8[0 .. std.unicode.utf8Encode(text_cp, &utf8) catch return] - else - ""; - var buffer: [256]u8 = undefined; - var writer = std.Io.Writer.fixed(&buffer); - input.encodeKey(&writer, .{ - .key = physical, - .mods = .{ .ctrl = key.ctrl, .alt = key.alt, .shift = key.shift }, - .consumed_mods = .{ .shift = key.text.len > 0 and key.shift }, - .utf8 = text, - .unshifted_codepoint = if (key.cp >= 'A' and key.cp <= 'Z') key.cp - 'A' + 'a' else if (key.cp < Key.up) key.cp else 0, - }, options: { - var opts = input.KeyEncodeOptions.fromTerminal(&state.vt); - // fromTerminal cannot know this one and says so, defaulting to - // "option is not alt" — right for an app that lets macOS do the - // unicode translation and hands the encoder the composed text. - // Every pardes shell resolves the modifier itself and hands the - // core the BASE key with the alt bit and no text at all (see - // PardesView.keyDown, and app.mjs doing the same with the same - // two bits), so by the time this runs alt already means alt. - // Left at the default, a macOS build drops the ESC prefix on - // the floor and forwards Alt-n to the child as a bare `n`. - opts.macos_option_as_alt = .true; - break :options opts; - }) catch return; - if (writer.end > 0) p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(writer.buffered()) } }); - return; - } - var control: [1]u8 = undefined; - const bytes: ?[]const u8 = blk: { - if (key.ctrl) { - if (key.cp >= 'a' and key.cp <= 'z') { - control[0] = @intCast(key.cp - 0x60); - break :blk control[0..1]; - } - // ASCII @, A-Z, [, \, ], ^ and _ are one contiguous control range. - if (key.cp >= '@' and key.cp <= '_') { - control[0] = @intCast(key.cp - 0x40); - break :blk control[0..1]; - } - } - if (key.text.len > 0) break :blk key.text; - break :blk switch (key.cp) { - Key.enter => "\r", - Key.backspace => "\x7f", - Key.tab => "\t", - Key.escape => "\x1b", - Key.up => "\x1b[A", - Key.down => "\x1b[B", - Key.right => "\x1b[C", - Key.left => "\x1b[D", - Key.delete => "\x1b[3~", - else => null, - }; + const pane = p.panes[id] orelse return; + const state = pane.terminal orelse return; + const input = ghostty_vt.input; + const function_keys = comptime keys: { + var keys: [Key.f25 - Key.f1 + 1]input.Key = undefined; + for (&keys, 1..) |*k, n| k.* = @field(input.Key, std.fmt.comptimePrint("f{d}", .{n})); + break :keys keys; }; - if (bytes) |encoded| - p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(encoded) } }); + const physical: input.Key = switch (key.cp) { + Key.enter => .enter, + Key.backspace => .backspace, + Key.tab => .tab, + Key.escape => .escape, + Key.up => .arrow_up, + Key.down => .arrow_down, + Key.left => .arrow_left, + Key.right => .arrow_right, + Key.home => .home, + Key.end => .end, + Key.page_up => .page_up, + Key.page_down => .page_down, + Key.delete => .delete, + Key.insert => .insert, + Key.print_screen => .print_screen, + Key.scroll_lock => .scroll_lock, + Key.pause => .pause, + Key.menu => .context_menu, + Key.f1...Key.f25 => function_keys[key.cp - Key.f1], + else => if (key.cp < 128) input.Key.fromASCII(@intCast(key.cp)) orelse .unidentified else .unidentified, + }; + var utf8: [4]u8 = undefined; + const text_cp = if (key.shift and key.cp >= 'a' and key.cp <= 'z') key.cp - 'a' + 'A' else key.cp; + // A key with no text of its own types its code point only when that + // is a character: the kitty keyboard protocol numbers function and + // modifier keys in the private use area (F3 is U+E016), and a shell + // was typed those as junk. + const text = if (key.text.len > 0) key.text else if (key.cp >= 32 and key.cp < Key.up and key.cp != Key.backspace and !(key.cp >= 0xE000 and key.cp <= 0xF8FF)) + utf8[0 .. std.unicode.utf8Encode(text_cp, &utf8) catch return] + else + ""; + var buffer: [256]u8 = undefined; + var writer = std.Io.Writer.fixed(&buffer); + input.encodeKey(&writer, .{ + .key = physical, + .mods = .{ .ctrl = key.ctrl, .alt = key.alt, .shift = key.shift }, + .consumed_mods = .{ .shift = key.text.len > 0 and key.shift }, + .utf8 = text, + .unshifted_codepoint = if (key.cp >= 'A' and key.cp <= 'Z') key.cp - 'A' + 'a' else if (key.cp < Key.up) key.cp else 0, + }, options: { + var opts = input.KeyEncodeOptions.fromTerminal(&state.vt); + // fromTerminal cannot know this one and says so, defaulting to + // "option is not alt" — right for an app that lets macOS do the + // unicode translation and hands the encoder the composed text. + // Every pardes shell resolves the modifier itself and hands the + // core the BASE key with the alt bit and no text at all (see + // PardesView.keyDown, and app.mjs doing the same with the same + // two bits), so by the time this runs alt already means alt. + // Left at the default, a macOS build drops the ESC prefix on + // the floor and forwards Alt-n to the child as a bare `n`. + opts.macos_option_as_alt = .true; + break :options opts; + }) catch return; + if (writer.end > 0) p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(writer.buffered()) } }); } pub fn enterTty(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; const selected = pane.rawPointerText(pane.sel[@backingInt(config.select_button)]) != null; - if (comptime enabled) if (!selected and pane.terminal != null and pane.body.cur_pinned and pane.terminal.?.vt.cursorIsAtPrompt()) handoff: { + if (!selected and pane.terminal != null and pane.body.cur_pinned and pane.terminal.?.vt.cursorIsAtPrompt()) handoff: { const screen = pane.terminal.?.vt.screens.active; const goff: i32 = @intCast(screen.pages.scrollbar().offset); const vp_row = pane.gridRow(pane.body.cur_row) - goff; @@ -1759,7 +1672,7 @@ pub fn enterTty(p: *Pardes, id: usize) void { const moves = screen.promptClickMove(click_pin); for (0..moves.left) |_| p.emitWrite(id, "\x1b[D"); for (0..moves.right) |_| p.emitWrite(id, "\x1b[C"); - }; + } pane.body.mode = .tty; followOutput(pane); // entering raw mode is a request for the live shell @@ -1845,7 +1758,6 @@ fn promptCut(pin: ghostty_vt.Pin) PromptCut { } pub fn promptPrefixBytes(pane: *Pane, row: i32, raw: []const u8) usize { - if (comptime !enabled) return 0; if (row < 0) return 0; const state = pane.terminal orelse return 0; const pin = state.vt.screens.active.pages.pin(.{ .screen = .{ .x = 0, .y = @intCast(row) } }) orelse return 0; @@ -1896,7 +1808,6 @@ fn dumpedBytes(pin: ghostty_vt.Pin, cell: *const ghostty_vt.Cell) usize { } pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 { - if (comptime !enabled) return &empty_grid; if (pane.terminal == null) return &empty_grid; pardes.tape.touchTerminal(); const c = &p.shell_rows; @@ -1924,7 +1835,6 @@ pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 { } test "rows asked for after a pane's cached rows were dropped, before the sweep, leak nothing" { - if (comptime !enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = p.panes[0].?; @@ -2109,7 +2019,7 @@ fn buildRows(alloc: std.mem.Allocator, p: *Pardes, pane: *Pane) !Rows { } pub fn bodyText(arena: std.mem.Allocator, pane: *Pane) ![]const u8 { - const vp: []const []const u8 = if (comptime !enabled) &.{} else vp: { + const vp: []const []const u8 = vp: { const state = pane.terminal orelse break :vp &.{}; const screen = state.vt.screens.active; var tl = screen.pages.getTopLeft(.viewport); @@ -2351,7 +2261,6 @@ const Anchor = struct { pub fn recolorAnsi(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void { // No emulator, no ANSI cells: the whole pass — and the 256-colour theme // projection behind it — is compiled out. - if (comptime !enabled) return; if (pane.terminal == null) return; const body_y = p.bodyTop(pane, r); var filtered_storage: FilteredColors = undefined; @@ -2490,7 +2399,7 @@ fn cellAt(pages: *const ghostty_vt.PageList, row: ghostty_vt.Pin, x: u16) ?ghost // A cell's underline styles are SGR's, in SGR's order (`off` its `none`): a // cast takes one to the other (cellStyle, pager.zig). comptime { - if (enabled) for (@typeInfo(@FieldType(pardes.CellStyle, "ul")).@"enum".field_names, 0..) |name, i| + for (@typeInfo(@FieldType(pardes.CellStyle, "ul")).@"enum".field_names, 0..) |name, i| if (@intFromEnum(@field(ghostty_vt.sgr.Attribute.Underline, if (std.mem.eql(u8, name, "off")) "none" else name)) != i) @compileError("a cell's underline styles are not SGR's"); } @@ -2521,7 +2430,7 @@ fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColor /// A program's colours mapped to the theme (Filter): a terminal's cells, or /// a +Pager's spans (`vt` null, the program's palette xterm's own). -pub const FilteredColors = if (enabled) struct { +pub const FilteredColors = struct { source: GColor.Palette, target: *const GColor.Palette, theme_bg: GColor.RGB, @@ -2660,7 +2569,7 @@ pub const FilteredColors = if (enabled) struct { self.cache_valid[slot] = true; return best; } -} else struct {}; +}; const channel_luminance: [256]f64 = blk: { @setEvalBranchQuota(20000); @@ -3106,7 +3015,6 @@ fn ghostColor(p: *Pardes, color: ghostty_vt.Style.Color, is_bg: bool) pardes.Col pub fn padOutputBelowEdits(p: *Pardes, id: usize) void { // Nothing to pad away from: with no emulator there is no prompt and no // child whose output could land on top of the edit buffer. - if (comptime !enabled) return; const pane = p.panes[id] orelse return; const o = pane.ovl orelse return; if (!pane.isTerminal()) return; @@ -3256,7 +3164,6 @@ fn ptyWritesByPane(p: *Pardes, out: *std.ArrayList(u8)) ![]const u8 { } test "a program that asked for focus reports hears CSI I and CSI O as its pane takes and gives up the keyboard, and as the window does" { - if (comptime !enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 90, .rows = 30, .shells = 3 }); defer p.deinit(); @@ -3397,7 +3304,6 @@ test "ED 3 takes away a kitty placement whose row it erased: it never comes back } test "a finished command's output erased by a later ED 3 is not called whole, and no rows stand in for it" { - if (comptime !enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 6 }); defer p.deinit(); @@ -3420,7 +3326,6 @@ test "a finished command's output erased by a later ED 3 is not called whole, an } test "a selection whose row ED 3 erased goes; one on the screen stays" { - if (comptime !enabled) return error.SkipZigTest; const gpa = std.testing.allocator; for ([_]bool{ true, false }) |in_history| { const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 6 }); diff --git a/src/vaxis_input.zig b/src/vaxis_input.zig index 5cb3c83e..dcad9ef1 100644 --- a/src/vaxis_input.zig +++ b/src/vaxis_input.zig @@ -1,6 +1,6 @@ //! A key as vaxis parses it from a terminal's bytes, as the core's Event: -//! the one map for every shell that reads a terminal (tty, gui's stdin, -//! esp32p4). Three copies had drifted; the gui's had lost the F-keys, +//! the one map for every shell that reads a terminal (tty, gui's stdin). +//! Three copies had drifted; the gui's had lost the F-keys, //! Insert and the keypad. And the other way, a cell's style as vaxis draws //! it. const std = @import("std"); diff --git a/src/wire.zig b/src/wire.zig index c8c4459a..e29a98b4 100644 --- a/src/wire.zig +++ b/src/wire.zig @@ -51,14 +51,14 @@ const family = switch (config.platform) { pub const semantics: u64 = blk: { @setEvalBranchQuota(1_000_000); break :blk std.hash.Wyhash.hash(0, std.fmt.comptimePrint( - "wire {d}\npardes {s} {s}\n{s} grammars {} {} {} {} mupdf {} themes {} workspace_tag {} sources {} board {d}x{d}\nusize {d} {t}\n{s}\n{s}", + "wire {d}\npardes {s} {s}\n{s} grammars {} {} {} {} mupdf {} themes {} workspace_tag {} sources {}\nusize {d} {t}\n{s}\n{s}", .{ version, config.version, config.commit orelse "unstamped", family, config.syntax_highlighting, config.syntax_zig_grammar, config.syntax_minimal_grammars, config.syntax_full_grammars, config.mupdf, config.theme_animation, config.workspace_tag, config.embed_sources, - config.esp32p4_cols, config.esp32p4_rows, @sizeOf(usize), - builtin.cpu.arch.endian(), config.deps, pardes.tape.shape, + @sizeOf(usize), builtin.cpu.arch.endian(), config.deps, + pardes.tape.shape, }, )); }; |
