unit editor;

// M2.5.3: a windowed text editor over the read-only application file API.
//
//   run editor               // interactive, opens `base/child`
//   run editor <file>        // interactive, opens that image file
//   run editor check         // deterministic checks, prints `editor: ok`
//   run editor shot [file]   // draws the file, prints `editor: ready` and
//                            // holds ~5 s for the QMP screenshot harness
//
// The document is one `string[131072]` buffer (valid UTF-8 by construction)
// and the view is derived from it on demand: a byte cursor, a scalar selection
// anchor, a first visible line and a horizontal byte offset. Opening a file
// checks the size first (`core.fs_size`), reads it in the API's 256-byte
// chunks into a staged `bytes[131072]`, and publishes the whole buffer with one
// `core.substr_into` (a `bytes` source is the strict UTF-8 conversion), so a
// missing name, a directory, a malformed path, an over-size file or
// invalid UTF-8 leaves the previous document byte-identical. The buffer limit
// is 131072 bytes (128 KiB, the spec 0008 per-unit source cap); a larger file
// is refused with a status line, not truncated. M9.4 raised the M2.5.3 8 KiB
// limit because every current source sample is larger (the largest, this
// editor, is 81,509 bytes), and the file-open dialog was correctly returning
// paths the editor then refused.
//
// Editing is app-local because the M2.4.1 `str_*` mutators declare a 256-byte
// working capacity while this editor's buffer is 128 KiB. The read-only helpers
// (`str_boundary`, `str_cursor_*`, `str_selection_normalize/all/collapse`) take
// `const string[0]` and are reused unchanged; the one mutator is
// `ed_replace`, the same checked prefix/insert/suffix staging rule as
// `str_insert_into`/`str_delete_into` but with this buffer's capacity. It
// requires both range ends to be code-point boundaries, stages into a local
// `bytes[BufferCapacity]`, converts with `core.substr_into` and publishes with
// one copy, so a rejected edit changes nothing and the document stays valid
// UTF-8.
//
// Saving is enabled by the M6.3 writable home filesystem (spec 0019, E1). The
// whole document is written to a sibling temporary file (`<target>.tmp`), which
// is then renamed over the target; the temporary is removed first, so a leftover
// from a failed save never leaves a longer tail. A document opened from the
// read-only image is saved as a copy under `home/<basename>` and the editor's
// path switches to it. A document opened from a user filesystem mount
// (`net/<keyword>/...`, spec 0032, M22.4) is writable in place: it saves to its
// own path (and `net/<file>.tmp` beside it) and the path does not move.
// Without a home disk the save reports that and leaves the document and path
// unchanged; `no_home` is a home-only condition, so a failing mount target
// reports `not writable` and a later attempt may still succeed. File > New File
// starts an unnamed buffer; its first Save and File > Save As (`Ctrl+Shift+S`)
// run the `/lib` Save File dialog (`lib.file_dialog.save_file`), which refuses
// an existing target and returns a free path under `home/` or a mounted
// `net/<keyword>/`. The editor then writes through the same temp+rename path.
//
// The File menu's Open runs a modal file-open dialog from `/lib`
// (`lib.file_dialog.open_file`, M9.3) instead of re-reading the current path;
// Ctrl+O does the same. The dialog starts in the current document's directory,
// lets the user navigate the image tree and returns a regular-file path, or a
// null-like cancel (`Invalid`) that leaves the document, path, caret,
// selection and scroll untouched. Ctrl+Q quits and Ctrl+A selects all.
// M9.1 adds lexical syntax highlighting for source files and a File > Highlight
// toggle: `unit`, `var`, `if` and the other keywords are blue, type and
// predeclared names dark red, strings dark green, comments gray and numbers
// dark brown. A file opened from `base/`, `lib/` or `system/`, or ending in
// `.ig`, starts highlighted; other text files stay plain and can be toggled on.
// Block comments (`{ ... }`) carry their state across visible lines; UTF-8 code
// points are never split because token runs use whole code points and the
// drawing path still publishes slices through the checked `core.substr_into`.
// The scrollbar uses `ui_scrollbar`/`ui_scrollbar_hit`: a click on the track
// pages the view and the thumb drags (M9.2, matching the browser's M8.9). Tab
// inserts two spaces, the repository's source indentation.
//
// M9.2 keeps the pointer path cheap: a pointer event repaints only when it
// changes visible state (a plain move over the text does nothing, a menu move
// repaints only when the highlight row changes). The M9.1 block-comment state at
// every line start is also cached in `line_states` and refreshed once per
// document publication instead of rescanning from byte 0 on every frame.
// Together these remove the full repaint per pointer move that spent a normal
// task's 10 s CPU budget (`Faulted(BudgetExceeded)`) when the user moved the
// mouse over the editor; the budget itself is unchanged.
//
// M16.8 defers the view while the thumb is held: a pointer move redraws and
// recomposites only the scrollbar strip, and the document view (`top_line`, the
// caret and every text row) changes once, when the button is released. A heavy
// 128 KiB document is therefore never re-rendered per drag step. The line count
// is cached at the press for the same reason: no move rescans the document.
//
// Dark theme: the File menu's `Dark` row (index 4) and Ctrl+D swap the palette
// for the whole client content — menu bar and pull-down, path line, text view
// with brightened syntax colours, selection band, caret, scrollbar and status
// line. `apply_theme` fills the role fields (`bg`, `ink`, `dim`, `sel_bg`,
// `sel_ink`, `rule`) and the five syntax colours; every drawing site reads
// those roles, so a toggle only changes colours. The menu bar, pull-down and
// scrollbar are painted app-locally in dark mode because the `stdlib` helpers
// hard-code the light System 7.5 palette; the geometry matches
// `ui_menu_bar`/`ui_menu_dropdown`/`ui_scrollbar`, so their hit tests keep
// working. Light mode still calls the helpers and is pixel-identical. The
// theme starts light, is independent of the document and is not saved.
//
// Drawing is client content only: the window service owns the frame, this app
// paints inside its content rectangle and never calls `syslib.clear`. Every
// frame is complete before one `window_present`; an owner `Expose` repaints the
// whole content. The interactive loop blocks in `syslib.next_event` while idle.
//
// `langhost` and a kernel without a framebuffer model a disabled screen, so the
// sample runs the same load/edit/line logic there and prints `editor: host ok`.

uses core, stdlib, syslib, lib.out, lib.inject, lib.file_dialog;

const
  WindowX = 180;
  WindowY = 90;
  ContentW = 640;
  ContentH = 480;

  // Document capacity: the spec 0008 per-unit source cap (128 KiB), so every
  // current sample opens. M9.4 raised this from 8 KiB; the file-open dialog was
  // already correct and returned `apps/accessories/calculator` (32,516 B), which the old
  // limit refused with a status line.
  BufferCapacity = 131072;
  // `abi::fs::PATH_MAX` (spec 0013 F2 / spec 0018 L6). The M9.3 file dialog
  // publishes its whole 256-byte result here.
  PathCapacity = 256;
  // A save path is `<target>.tmp`, so it can be four bytes longer than a path.
  TempCapacity = 260;

  // Client layout inside the content rectangle.
  MenuBarH = 22;
  MenuW = 220;
  PathTop = 22;
  PathH = 16;
  TextTop = 38;
  LineH = 16;
  Rows = 26;
  TextLeft = 4;
  TextW = 612;
  VisibleCols = 76;
  ScrollLeft = 620;
  ScrollTop = 38;
  ScrollW = 16;
  ScrollH = 416;
  StatusTop = 456;

  // File menu rows: New File, Open, Save, Save As, separator, Highlight,
  // Dark, Quit.
  FileItemCount = 8;
  FileNewItem = 0;
  FileOpenItem = 1;
  FileSaveItem = 2;
  FileSaveAsItem = 3;
  FileHighlightItem = 5;
  FileDarkItem = 6;
  FileQuitItem = 7;

  // Lexical token classes and the longest word the highlighter compares
  // (`in_stream`/`out_stream` are 10 bytes; 16 leaves headroom).
  ClassDefault = 0;
  ClassKeyword = 1;
  ClassType = 2;
  ClassString = 3;
  ClassComment = 4;
  ClassNumber = 5;
  TokenCapacity = 16;
  KeywordCount = 33;
  TypeCount = 14;
  // One cached block-comment state per line start: a 131072-byte document has
  // at most 131073 lines (one per '\n' plus the final empty line).
  LineStateCapacity = BufferCapacity + 1;
  // A sparse line-start index: one entry per 16 lines (8193 anchors for the
  // worst case), rebuilt in the same publication pass as the comment state.
  // `line_start_of` walks at most 15 lines and `line_of_pos` binary-searches
  // the anchors and then walks at most 15 lines, so a caret move or a frame is
  // O(visible lines) rather than O(document). Without it a held Down key on a
  // 98 KiB source scanned the whole buffer about a dozen times per key and
  // reached `BudgetExceeded` after ~80 presses (M16.10).
  LineIndexStride = 16;
  LineIndexCapacity = (BufferCapacity + LineIndexStride) div LineIndexStride;

  HoldSeconds = 5;
  NanosPerSecond = 1000000000;

var
  // Document and loading.
  text: string[BufferCapacity];
  load_stage: bytes[BufferCapacity];
  save_stage: bytes[BufferCapacity];
  path: string[PathCapacity];
  // True for a File > New File document that has no home name yet. Save (and
  // Ctrl+S) opens the Save File dialog instead of writing.
  untitled: bool;
  dialog_path: string[PathCapacity];
  save_target: string[PathCapacity];
  save_temp: string[TempCapacity];
  status_line: string[128];
  no_home: bool;

  // View state: caret and selection anchor are byte offsets (code-point
  // boundaries); the selection is the ordered pair, normalized on use.
  caret: int;
  anchor: int;
  top_line: int;
  left_byte: int;
  // M9.2 scrollbar thumb drag: the grab offset is `pointer - thumb top`.
  // M16.8 defers the view: `scroll_preview` moves the thumb alone and
  // `top_line` (and the document) changes only on release.
  scroll_dragging: bool;
  scroll_grab_dy: int;
  scroll_preview: int;
  drag_total: int;

  // File menu.
  open_menu: int;
  selected: int;
  file_items: array[string[64], 16];
  file_keys: array[string[32], 16];
  file_disabled: uint;
  file_checked: uint;
  titles: array[string[32], 8];

  // Lexical highlighting (M9.1): the keyword/type tables are built once at
  // startup; `block_open` carries a `{ ... }` comment across visible lines.
  highlight: bool;
  block_open: bool;
  keywords: array[string[16], 40];
  type_names: array[string[16], 20];
  word_buf: string[TokenCapacity];
  // M9.2: the block-comment state at each line start, refreshed when the
  // document is published; `draw_lines` reads one entry per frame.
  line_states: bytes[LineStateCapacity];
  // M16.10: the line count and the sparse start index, refreshed in the same
  // publication pass. Every line lookup below reads these instead of scanning
  // the document; `line_count` returns `total_lines`.
  total_lines: int;
  line_starts: array[int, LineIndexCapacity];

  // Window and absolute layout.
  id: int;
  rect: Rect;
  text_x: int;
  text_y: int;
  scroll_x: int;
  scroll_y: int;
  status_y: int;

  // Theme. The four light/dark roles are the same names in both palettes, so
  // every drawing site and pixel probe is theme-neutral: `bg` is the content
  // and glyph-hole background, `ink` the default text and caret, `dim` the
  // secondary text and scrollbar thumb, `sel_bg` the selection band and the
  // active menu cell, `sel_ink` the text on it, and `rule` every separator,
  // border and thumb outline. `dark` selects the palette in `apply_theme`.
  dark: bool;
  bg: uint;
  ink: uint;
  dim: uint;
  sel_bg: uint;
  sel_ink: uint;
  rule: uint;
  kw_color: uint;
  type_color: uint;
  string_color: uint;
  comment_color: uint;
  number_color: uint;

  // Mode and scratch.
  mode: int;
  running: bool;
  failed: bool;
  step: int;
  step_text: string[16];
  ev: Event;
  st: Status;
  used: int;
  copied: int;
  tail_buf: string[256];
  digits_line: string[24];
  digits_col: string[24];
  slice_buf: string[512];
  one: bytes[2];
  ch: string[8];
  scratch_bytes: bytes[4];
  scratch_text: string[8];

// Silent check: the first failure is printed with its step number and label.
procedure verify(label: const string[0]; passed: bool);
begin
  step := step + 1;
  if not passed then
  begin
    failed := true;
    out.say("editor: failed check ");
    used := core.format_int_into(step_text, step, uint(10), uint(0));
    out.say(step_text);
    out.say(" (");
    out.say(label);
    out.say(")\n");
  end;
end;

// True when any pixel in the rectangle has exactly `color`. The M9.1 syntax
// probes use it on one glyph row (8 px tall) at a time, so the scan is small.
function region_has_color(x: int; y: int; w: int; h: int; color: uint): bool;
var
  px: int;
  py: int;
begin
  py := y;
  while py < y + h do
  begin
    px := x;
    while px < x + w do
    begin
      if syslib.get_pixel(px, py) = color then
        return true;
      px := px + 1;
    end;
    py := py + 1;
  end;
  return false;
end;

// ---- text geometry (pure over any capacity) ------------------------------

function is_continuation(value: byte): bool;
begin
  return value >= byte(0x80) and value <= byte(0xBF);
end;

// One line per '\n', plus a final empty line when the text ends with one; an
// empty document is one empty line. M16.10: the count is cached by
// `refresh_line_states`, so this is O(1) and never scans the document; the
// `t` parameter stays for the call sites that already hold the text.
function line_count(t: const string[0]): int;
begin
  return total_lines;
end;

// Byte offset of the first byte of `line` (0-based); past the last line yields
// the text length. M16.10: jump to the nearest 16-line anchor and walk at most
// `LineIndexStride - 1` lines, never the document from byte 0.
function line_start_of(t: const string[0]; line: int): int;
var
  length: int;
  i: int;
  seen: int;
  anchor: int;
  wanted: int;
begin
  length := int(core.len(t));
  if line <= 0 then
    return 0;
  if line >= total_lines then
    return length;
  anchor := line div LineIndexStride;
  i := line_starts[anchor];
  seen := 0;
  wanted := line - anchor * LineIndexStride;
  while i < length and seen < wanted do
  begin
    if t[i] = byte(10) then
      seen := seen + 1;
    i := i + 1;
  end;
  return i;
end;

// Byte offset of the line's terminating '\n', or the text length.
function line_end_of(t: const string[0]; start: int): int;
var
  length: int;
  i: int;
begin
  length := int(core.len(t));
  if start >= length then
    return length;
  i := start;
  while i < length do
  begin
    if t[i] = byte(10) then
      return i;
    i := i + 1;
  end;
  return length;
end;

// 0-based line containing byte offset `pos`. M16.10: binary-search the anchors
// for the last one at or before `pos`, then count newlines only within that
// 16-line block. A click, a caret move and every frame therefore cost O(log
// anchors + LineIndexStride lines), not O(document).
function line_of_pos(t: const string[0]; pos: int): int;
var
  length: int;
  i: int;
  line: int;
  lo: int;
  hi: int;
  mid: int;
  anchors: int;
begin
  length := int(core.len(t));
  if pos > length then
    pos := length;
  if pos < 0 then
    pos := 0;
  anchors := (total_lines + LineIndexStride - 1) div LineIndexStride;
  if anchors < 1 then
    anchors := 1;
  lo := 0;
  hi := anchors - 1;
  while lo < hi do
  begin
    mid := (lo + hi + 1) div 2;
    if line_starts[mid] <= pos then
      lo := mid
    else
      hi := mid - 1;
  end;
  line := lo * LineIndexStride;
  i := line_starts[lo];
  while i < pos and i < length do
  begin
    if t[i] = byte(10) then
      line := line + 1;
    i := i + 1;
  end;
  if line > total_lines - 1 then
    line := total_lines - 1;
  if line < 0 then
    line := 0;
  return line;
end;

// Code-point column (draw_text advances one cell per byte; this is the
// human-readable column used by the Ln/Col readout).
function column_of(t: const string[0]; start: int; pos: int): int;
var
  length: int;
  i: int;
  column: int;
begin
  length := int(core.len(t));
  if pos > length then
    pos := length;
  column := 0;
  i := start;
  while i < pos do
  begin
    if not is_continuation(t[i]) then
      column := column + 1;
    i := i + 1;
  end;
  return column;
end;

// Moves `at` back to the nearest code-point boundary at or after `from`.
function snap_boundary(t: const string[0]; from: int; at: int): int;
var
  length: int;
  i: int;
begin
  length := int(core.len(t));
  i := at;
  if i > length then
    i := length;
  while i > from and i < length and is_continuation(t[i]) do
    i := i - 1;
  return i;
end;

// ---- lexical highlighting (M9.1) ----------------------------------------

// The keyword and type tables are fixed arrays built once at startup; no
// allocation, no generic container and no new language feature.

function is_digit(value: byte): bool;
begin
  return value >= byte(48) and value <= byte(57);
end;

function is_hex_digit(value: byte): bool;
begin
  return is_digit(value) or
    (value >= byte(97) and value <= byte(102)) or
    (value >= byte(65) and value <= byte(70));
end;

function is_letter(value: byte): bool;
begin
  return (value >= byte(65) and value <= byte(90)) or
    (value >= byte(97) and value <= byte(122));
end;

function is_ident_start(value: byte): bool;
begin
  return is_letter(value) or value = byte(95);
end;

function is_ident_char(value: byte): bool;
begin
  return is_ident_start(value) or is_digit(value);
end;

// Byte length of the UTF-8 code point at `at` (the text is valid UTF-8, so a
// lead byte always has its full sequence before the line's '\n'); clamped to
// `stop` anyway. Used so a default token never begins or ends inside a code
// point.
function codepoint_length(t: const string[0]; at: int; stop: int): int;
var
  value: byte;
  length: int;
begin
  value := t[at];
  length := 1;
  if value >= byte(0xF0) then
    length := 4
  else if value >= byte(0xE0) then
    length := 3
  else if value >= byte(0xC0) then
    length := 2;
  if at + length > stop then
    length := stop - at;
  return length;
end;

procedure setup_highlight();
begin
  keywords[0] := "unit";
  keywords[1] := "uses";
  keywords[2] := "const";
  keywords[3] := "var";
  keywords[4] := "type";
  keywords[5] := "record";
  keywords[6] := "end";
  keywords[7] := "procedure";
  keywords[8] := "function";
  keywords[9] := "begin";
  keywords[10] := "if";
  keywords[11] := "then";
  keywords[12] := "else";
  keywords[13] := "while";
  keywords[14] := "do";
  keywords[15] := "case";
  keywords[16] := "of";
  keywords[17] := "return";
  keywords[18] := "array";
  keywords[19] := "ring";
  keywords[20] := "map";
  keywords[21] := "in_stream";
  keywords[22] := "out_stream";
  keywords[23] := "value";
  keywords[24] := "and";
  keywords[25] := "or";
  keywords[26] := "not";
  keywords[27] := "div";
  keywords[28] := "mod";
  keywords[29] := "fault";
  keywords[30] := "exit";
  keywords[31] := "true";
  keywords[32] := "false";

  type_names[0] := "int";
  type_names[1] := "uint";
  type_names[2] := "byte";
  type_names[3] := "bool";
  type_names[4] := "f64";
  type_names[5] := "string";
  type_names[6] := "bytes";
  type_names[7] := "Status";
  type_names[8] := "FaultCode";
  type_names[9] := "Diagnostic";
  type_names[10] := "ExitReason";
  type_names[11] := "Rect";
  type_names[12] := "Event";
  type_names[13] := "EventKind";
end;

function classify_word(t: const string[0]; at: int; stop: int): int;
var
  length: int;
  got: int;
  i: int;
begin
  length := stop - at;
  if length > TokenCapacity then
    return ClassDefault;
  got := core.substr_into(word_buf, t, at, length);
  if got <> length then
    return ClassDefault;
  i := 0;
  while i < KeywordCount do
  begin
    if word_buf = keywords[i] then
      return ClassKeyword;
    i := i + 1;
  end;
  i := 0;
  while i < TypeCount do
  begin
    if word_buf = type_names[i] then
      return ClassType;
    i := i + 1;
  end;
  return ClassDefault;
end;

// Classifies the token starting at `at` and sets its exclusive end, its class
// and the block-comment state after it. `//` runs to the line end, `{` opens a
// block comment that ends at the first `}` (no nesting, as the lexer), a
// string runs to its closing quote (with `\"` skipped) or the line end, and
// any other byte is one default code point. A `//` or `{` inside a string is
// string content, and strings/comments skip their interior.
procedure scan_token(t: const string[0]; at: int; stop: int; in_block: bool;
                    out_end: var int; out_class: var int; out_block: var bool);
var
  value: byte;
  i: int;
  exponent: int;
begin
  out_end := at;
  out_class := ClassDefault;
  out_block := in_block;
  if at >= stop then
    return;
  value := t[at];
  if in_block then
  begin
    out_class := ClassComment;
    i := at;
    while i < stop do
    begin
      if t[i] = byte(125) then
      begin
        out_end := i + 1;
        out_block := false;
        return;
      end;
      i := i + 1;
    end;
    out_end := stop;
    out_block := true;
    return;
  end;
  if value = byte(47) and at + 1 < stop and t[at + 1] = byte(47) then
  begin
    out_class := ClassComment;
    out_end := stop;
    return;
  end;
  if value = byte(123) then
  begin
    out_class := ClassComment;
    i := at + 1;
    while i < stop do
    begin
      if t[i] = byte(125) then
      begin
        out_end := i + 1;
        out_block := false;
        return;
      end;
      i := i + 1;
    end;
    out_end := stop;
    out_block := true;
    return;
  end;
  if value = byte(34) then
  begin
    out_class := ClassString;
    i := at + 1;
    while i < stop do
    begin
      if t[i] = byte(92) then
        i := i + 2
      else if t[i] = byte(34) then
      begin
        out_end := i + 1;
        return;
      end
      else
        i := i + 1;
    end;
    out_end := stop;
    return;
  end;
  if is_digit(value) then
  begin
    out_class := ClassNumber;
    i := at;
    if value = byte(48) and i + 1 < stop and
       (t[i + 1] = byte(120) or t[i + 1] = byte(88)) and
       i + 2 < stop and is_hex_digit(t[i + 2]) then
    begin
      i := i + 2;
      while i < stop and is_hex_digit(t[i]) do
        i := i + 1;
    end
    else
    begin
      while i < stop and is_digit(t[i]) do
        i := i + 1;
      if i + 1 < stop and t[i] = byte(46) and is_digit(t[i + 1]) then
      begin
        i := i + 2;
        while i < stop and is_digit(t[i]) do
          i := i + 1;
      end;
      if i < stop and (t[i] = byte(101) or t[i] = byte(69)) then
      begin
        exponent := i + 1;
        if exponent < stop and
           (t[exponent] = byte(43) or t[exponent] = byte(45)) then
          exponent := exponent + 1;
        if exponent < stop and is_digit(t[exponent]) then
        begin
          i := exponent + 1;
          while i < stop and is_digit(t[i]) do
            i := i + 1;
        end;
      end;
    end;
    out_end := i;
    return;
  end;
  if is_ident_start(value) then
  begin
    i := at + 1;
    while i < stop and is_ident_char(t[i]) do
      i := i + 1;
    out_end := i;
    out_class := classify_word(t, at, i);
    return;
  end;
  out_end := at + codepoint_length(t, at, stop);
end;

// Recomputes the block-comment state and the sparse line index (M9.2/M16.10).
// This is one allocation-free scan of the whole document - a `//` comment ends
// at its own line's '\n', so one line's `//` never swallows a later line's `{`
// - and it runs once whenever the text is published (`publish_staged` from an
// open or a check-mode load, `ed_replace` from an edit), not once per frame.
// The same pass writes one start anchor per `LineIndexStride` lines and the
// total line count, so later caret moves, frames and scrollbar math are
// O(visible lines) instead of O(document).
procedure refresh_line_states();
var
  length: int;
  total: int;
  start: int;
  stop: int;
  i: int;
  finish: int;
  cls: int;
  state: bool;
  next_state: bool;
  line: int;
begin
  length := int(core.len(text));
  total := 0;
  state := false;
  start := 0;
  line := 0;
  while line < LineStateCapacity do
  begin
    if line mod LineIndexStride = 0 then
      line_starts[line div LineIndexStride] := start;
    if state then
      line_states[line] := byte(1)
    else
      line_states[line] := byte(0);
    stop := line_end_of(text, start);
    i := start;
    while i < stop do
    begin
      scan_token(text, i, stop, state, finish, cls, next_state);
      if finish <= i then
        finish := i + 1;
      state := next_state;
      i := finish;
    end;
    total := line + 1;
    if stop < length then
    begin
      start := stop + 1;
      line := line + 1;
    end
    else
      line := LineStateCapacity;
  end;
  total_lines := total;
end;

function class_color(cls: int): uint;
begin
  if cls = ClassKeyword then
    return kw_color;
  if cls = ClassType then
    return type_color;
  if cls = ClassString then
    return string_color;
  if cls = ClassComment then
    return comment_color;
  if cls = ClassNumber then
    return number_color;
  return ink;
end;

// A source path is highlighted by default: `base/`, `lib/` and `system/` hold
// source, and a `.ig` suffix names source anywhere. Other text files (for
// example `home/*.txt`) stay plain until the File > Highlight toggle turns
// colouring on.
function is_source_path(name: const string[0]): bool;
var
  length: int;
begin
  if stdlib.starts_with(name, "base/") or stdlib.starts_with(name, "lib/") or
     stdlib.starts_with(name, "system/") then
    return true;
  length := int(core.len(name));
  if length >= 3 and name[length - 3] = byte(46) and
     name[length - 2] = byte(105) and name[length - 1] = byte(103) then
    return true;
  return false;
end;

// ---- editing over the 128 KiB buffer --------------------------------------

// The single checked mutator: replaces `count` bytes at boundary `at` with
// `ins` (any valid `string`). Both range ends must be boundaries; the result
// is staged in a local `bytes[BufferCapacity]`, converted with
// `core.substr_into` (strict UTF-8) and published with one whole-buffer copy.
// `Invalid` and `CapacityExceeded` change nothing.
function ed_replace(buf: var string[BufferCapacity]; at: int; count: int;
                    ins: const string[0]): Status;
var
  length: int;
  add: int;
  new_length: int;
  i: int;
  raw: bytes[BufferCapacity];
begin
  length := int(core.len(buf));
  if at < 0 or at > length then
    return Invalid;
  if count < 0 or count > length - at then
    return Invalid;
  if not stdlib.str_boundary(buf, at) then
    return Invalid;
  if not stdlib.str_boundary(buf, at + count) then
    return Invalid;
  add := int(core.len(ins));
  new_length := length - count + add;
  if new_length > BufferCapacity then
    return CapacityExceeded;

  i := 0;
  while i < at do
  begin
    raw[i] := buf[i];
    i := i + 1;
  end;
  i := 0;
  while i < add do
  begin
    raw[at + i] := ins[i];
    i := i + 1;
  end;
  i := at + count;
  while i < length do
  begin
    raw[i - count + add] := buf[i];
    i := i + 1;
  end;

  copied := core.substr_into(buf, raw, 0, new_length);
  if copied <> new_length then
    return Invalid;
  // The editor's one document is `text`; refresh the cached per-line block
  // states once per edit, never per frame (M9.2).
  refresh_line_states();
  return Ok;
end;

// Deletes the code point before the clamped cursor and moves it to that code
// point's first byte; at 0 it is an Ok no-op.
function ed_backspace(buf: var string[BufferCapacity]; cursor: var int): Status;
var
  at: int;
  previous: int;
  result: Status;
begin
  at := stdlib.str_cursor_clamp(buf, cursor);
  if at = 0 then
  begin
    cursor := 0;
    return Ok;
  end;
  previous := at - 1;
  while previous > 0 and is_continuation(buf[previous]) do
    previous := previous - 1;
  result := ed_replace(buf, previous, at - previous, "");
  if result = Ok then
    cursor := previous;
  return result;
end;

// Deletes the code point after the cursor; at the end it is an Ok no-op.
function ed_delete_forward(buf: var string[BufferCapacity]; cursor: var int): Status;
var
  at: int;
  next: int;
  value: Status;
begin
  at := stdlib.str_cursor_clamp(buf, cursor);
  if at >= int(core.len(buf)) then
  begin
    cursor := at;
    return Ok;
  end;
  next := at;
  next := stdlib.str_cursor_right(buf, next);
  if next <= at then
  begin
    cursor := at;
    return Ok;
  end;
  value := ed_replace(buf, at, next - at, "");
  return value;
end;

// ---- document load --------------------------------------------------------

procedure set_error(value: Status);
begin
  if value = NotFound then
    status_line := "no such file"
  else if value = Invalid then
    status_line := "not a readable file"
  else if value = CapacityExceeded then
    status_line := "too large (131072 max)"
  else
    status_line := "read error";
end;

// Publishes the first `size` bytes of the staged read as the document. The
// conversion is the API's only bytes -> string path, so invalid UTF-8 leaves
// the old document untouched.
function publish_staged(size: int): Status;
var
  got: int;
begin
  got := core.substr_into(text, load_stage, 0, size);
  if got = size then
  begin
    refresh_line_states();
    return Ok;
  end;
  if got = -6 then
    return CapacityExceeded;
  return Invalid;
end;

// Loads one image file. On success it replaces the document and the path; on
// every failure the document and the path are unchanged and the status line
// names the class of failure.
function open_path(name: const string[0]): Status;
var
  size: uint;
  offset: uint;
  read: int;
  value: Status;
  chunk: bytes[256];
  i: int;
  total: int;
begin
  if int(core.len(name)) > PathCapacity then
  begin
    status_line := "path too long";
    return CapacityExceeded;
  end;
  value := core.fs_size(name, size);
  if value <> Ok then
  begin
    set_error(value);
    return value;
  end;
  if size > uint(BufferCapacity) then
  begin
    status_line := "too large (131072 max)";
    return CapacityExceeded;
  end;
  total := int(size);
  offset := uint(0);
  value := Ok;
  while offset < size and value = Ok do
  begin
    value := core.fs_read(name, offset, chunk, read);
    if value = Ok then
    begin
      if read <= 0 then
        value := IoError
      else
      begin
        i := 0;
        while i < read do
        begin
          load_stage[int(offset) + i] := chunk[i];
          i := i + 1;
        end;
        offset := offset + uint(read);
      end;
    end;
  end;
  if value <> Ok then
  begin
    set_error(value);
    return value;
  end;
  if int(offset) <> total then
  begin
    status_line := "read error";
    return IoError;
  end;
  value := publish_staged(total);
  if value <> Ok then
  begin
    status_line := "invalid UTF-8";
    return value;
  end;
  used := core.substr_into(path, name, 0, int(core.len(name)));
  highlight := is_source_path(path);
  file_checked := stdlib.ui_menu_set(
    file_checked, FileHighlightItem, highlight);
  caret := 0;
  anchor := 0;
  top_line := 0;
  left_byte := 0;
  untitled := false;
  status_line := "opened";
  return Ok;
end;

// Builds `save_target` (the document when it already lives in a writable tree,
// or `home/<basename>` for a read-only source) and `save_temp` (`save_target`
// plus `.tmp`) from `path`. `home/` (spec 0019) and `net/` (a mount, spec 0032)
// are writable in place; every other source keeps the copy rule.
function build_save_paths(): Status;
var
  length: int;
  start: int;
  name_len: int;
  total: int;
  i: int;
  got: int;
  stage: bytes[TempCapacity];
begin
  length := int(core.len(path));
  if length = 0 then
    return Invalid;
  if stdlib.starts_with(path, "home/") or stdlib.starts_with(path, "net/") then
  begin
    got := core.substr_into(save_target, path, 0, length);
    if got <> length then
      return CapacityExceeded;
  end
  else
  begin
    // The basename of the image path becomes `home/<basename>`.
    start := length;
    while start > 0 and path[start - 1] <> byte(47) do
      start := start - 1;
    name_len := length - start;
    total := 5 + name_len;
    if total > PathCapacity then
      return CapacityExceeded;
    stage[0] := byte(104);  // h
    stage[1] := byte(111);  // o
    stage[2] := byte(109);  // m
    stage[3] := byte(101);  // e
    stage[4] := byte(47);   // /
    i := 0;
    while i < name_len do
    begin
      stage[5 + i] := path[start + i];
      i := i + 1;
    end;
    got := core.substr_into(save_target, stage, 0, total);
    if got <> total then
      return CapacityExceeded;
  end;

  // The temporary sits beside the target so the rename stays in one directory.
  length := int(core.len(save_target));
  total := length + 4;
  if total > TempCapacity then
    return CapacityExceeded;
  i := 0;
  while i < length do
  begin
    stage[i] := save_target[i];
    i := i + 1;
  end;
  stage[length] := byte(46);      // .
  stage[length + 1] := byte(116); // t
  stage[length + 2] := byte(109); // m
  stage[length + 3] := byte(112); // p
  got := core.substr_into(save_temp, stage, 0, total);
  if got <> total then
    return CapacityExceeded;
  return Ok;
end;

// The failure status line. `Invalid` is the one status whose meaning depends
// on the target tree: on the home disk it is the absent-home answer (and it
// sets `no_home`, which stops later home attempts); on a mount it is an honest
// per-operation refusal and the mount may recover, so it must not touch
// `no_home` (spec 0032, M22.4). `home_target` is true only for a `home/...`
// save target.
procedure set_save_error(value: Status; home_target: bool);
begin
  if value = Invalid then
  begin
    if home_target then
    begin
      no_home := true;
      status_line := "no writable home";
    end
    else
      status_line := "not writable";
  end
  else if value = NotFound then
    status_line := "no such directory"
  else if value = CapacityExceeded then
    status_line := "no space left"
  else
    status_line := "save failed";
end;

// Compares the saved target with the document, byte for byte.
function saved_matches(): bool;
var
  length: int;
  offset: int;
  read: int;
  i: int;
  size: uint;
  same: bool;
  value: Status;
  chunk: bytes[256];
begin
  length := int(core.len(text));
  value := core.fs_size(save_target, size);
  if value <> Ok or int(size) <> length then
    return false;
  offset := 0;
  same := true;
  while offset < length and same do
  begin
    value := core.fs_read(save_target, uint(offset), chunk, read);
    if value <> Ok or read <= 0 then
      same := false
    else
    begin
      i := 0;
      while i < read do
      begin
        if chunk[i] <> text[offset + i] then
          same := false;
        i := i + 1;
      end;
      offset := offset + read;
    end;
  end;
  return same and offset = length;
end;

// Sets `saved` or `saved <target>` in the status line.
procedure set_saved_status(copied: bool);
var
  total: int;
  i: int;
  got: int;
  stage: bytes[128];
begin
  if not copied then
    status_line := "saved"
  else
  begin
    total := 6 + int(core.len(save_target));
    if total > 128 then
      total := 128;
    stage[0] := byte(115); // s
    stage[1] := byte(97);  // a
    stage[2] := byte(118); // v
    stage[3] := byte(101); // e
    stage[4] := byte(100); // d
    stage[5] := byte(32);  // space
    i := 0;
    while i < total - 6 do
    begin
      stage[6 + i] := save_target[i];
      i := i + 1;
    end;
    got := core.substr_into(status_line, stage, 0, total);
    if got <> total then
      status_line := "saved";
  end;
end;

// Writes the document to the current `path` through a sibling temporary and a
// rename. The caller has already resolved a writable target: `home/...` or a
// mount path (`net/...`); every other source resolved to `home/<basename>`.
procedure save_document();
var
  length: int;
  staged: int;
  written: int;
  value: Status;
  source_writable: bool;
  home_target: bool;
begin
  no_home := false;
  value := build_save_paths();
  if value <> Ok then
  begin
    status_line := "path too long";
    return;
  end;
  source_writable := stdlib.starts_with(path, "home/")
    or stdlib.starts_with(path, "net/");
  home_target := stdlib.starts_with(save_target, "home/");

  length := int(core.len(text));
  staged := core.substr_into(save_stage, text, 0, length);
  if staged <> length then
  begin
    status_line := "save failed";
    return;
  end;

  // Remove a leftover temporary first: without truncate, a stale, longer file
  // would keep its tail after the shorter write.
  value := core.fs_remove(save_temp);
  if value <> Ok and value <> NotFound then
  begin
    set_save_error(value, home_target);
    return;
  end;

  written := -1;
  value := core.fs_write(save_temp, uint(0), save_stage, written);
  if value <> Ok or written <> length then
  begin
    if value = Ok then
      status_line := "save failed"
    else
      set_save_error(value, home_target);
    return;
  end;
  value := core.fs_rename(save_temp, save_target);
  if value <> Ok then
  begin
    set_save_error(value, home_target);
    return;
  end;

  if not source_writable then
  begin
    // The copy is the document now.
    copied := core.substr_into(path, save_target, 0, int(core.len(save_target)));
    if copied <> int(core.len(save_target)) then
    begin
      status_line := "path too long";
      return;
    end;
    set_saved_status(true);
  end
  else
    set_saved_status(false);
end;

// File > Save As and Ctrl+Shift+S, and the first save of an unnamed New File:
// run the `/lib` Save File dialog, then write through the same temp+rename
// path. The suggested name is the current document's home target (or empty,
// which starts at `home/untitled.txt`). A cancel leaves every document and
// path field untouched.
procedure save_as();
var
  start: string[PathCapacity];
  chosen: string[PathCapacity];
  value: Status;
  copied: int;
begin
  start := "";
  if int(core.len(path)) > 0 then
  begin
    value := build_save_paths();
    if value = Ok then
      copied := core.substr_into(
        start, save_target, 0, int(core.len(save_target)));
  end;
  value := file_dialog.save_file(start, chosen);
  if value = Ok then
  begin
    copied := core.substr_into(path, chosen, 0, int(core.len(chosen)));
    if copied <> int(core.len(chosen)) then
    begin
      status_line := "path too long";
      return;
    end;
    untitled := false;
    save_document();
  end
  else if value = Invalid then
    status_line := "save cancelled"
  else if value = CapacityExceeded then
    status_line := "path too long"
  else
    status_line := "save failed";
end;

// Save and Ctrl+S: an unnamed new document gets the Save File dialog; every
// other document writes its current home target.
procedure try_save();
begin
  if untitled or int(core.len(path)) = 0 then
    save_as()
  else
    save_document();
end;

// ---- selection and cursor movement ---------------------------------------

procedure selection_bounds(out_first: var int; out_last: var int);
var
  first: int;
  last: int;
begin
  first := anchor;
  last := caret;
  used := stdlib.str_selection_normalize(text, first, last);
  out_first := first;
  out_last := last;
end;

procedure collapse_to(position: int);
begin
  caret := position;
  anchor := position;
end;

// Keeps the caret line inside the vertical window and the caret column inside
// the horizontal window; both offsets snap back to code-point boundaries.
procedure ensure_visible();
var
  length: int;
  line: int;
  start: int;
  column: int;
  absolute: int;
  i: int;
  total: int;
begin
  length := int(core.len(text));
  line := line_of_pos(text, caret);
  start := line_start_of(text, line);
  column := caret - start;
  if column < left_byte then
    left_byte := column;
  if column - left_byte >= VisibleCols then
    left_byte := column - VisibleCols + 1;
  if left_byte < 0 then
    left_byte := 0;
  absolute := start + left_byte;
  i := absolute;
  while i > start and i < length and is_continuation(text[i]) do
    i := i - 1;
  left_byte := i - start;

  if line < top_line then
    top_line := line;
  if line >= top_line + Rows then
    top_line := line - Rows + 1;
  total := line_count(text);
  top_line := stdlib.ui_scrollbar_clamp(top_line, Rows, total);
  if top_line < 0 then
    top_line := 0;
end;

// Replaces the ordered selection with `ins` and collapses the selection just
// past the inserted text. The failure paths leave everything untouched.
procedure replace_selection(ins: const string[0]);
var
  first: int;
  last: int;
  value: Status;
begin
  selection_bounds(first, last);
  value := ed_replace(text, first, last - first, ins);
  if value = Ok then
  begin
    caret := first + int(core.len(ins));
    anchor := caret;
    status_line := "";
  end
  else if value = CapacityExceeded then
    status_line := "buffer full (131072 bytes)"
  else
    status_line := "edit refused";
  ensure_visible();
end;

// One printable byte from a key event, converted through the checked
// bytes -> string path (ASCII, so it is always valid).
procedure type_char(value: byte);
var
  got: int;
begin
  one[0] := value;
  got := core.substr_into(ch, one, 0, 1);
  if got = 1 then
    replace_selection(ch)
  else
    status_line := "bad character";
end;

// Plain left/right: collapse a live selection to the edge in that direction,
// otherwise move one whole code point.
procedure move_horizontal(delta: int);
var
  first: int;
  last: int;
begin
  selection_bounds(first, last);
  if first <> last then
  begin
    if delta < 0 then
      collapse_to(first)
    else
      collapse_to(last);
  end
  else if delta < 0 then
    caret := stdlib.str_cursor_left(text, caret)
  else
    caret := stdlib.str_cursor_right(text, caret);
  anchor := caret;
  ensure_visible();
end;

// Shift+left/right: keep the anchor and move the active end.
procedure extend_horizontal(delta: int);
begin
  if delta < 0 then
    caret := stdlib.str_cursor_left(text, caret)
  else
    caret := stdlib.str_cursor_right(text, caret);
  ensure_visible();
end;

// Moves the caret `delta` lines, keeping the byte column when it fits; a
// target inside a multi-byte code point snaps back to its first byte.
procedure move_vertical(delta: int; extend: bool);
var
  line: int;
  start: int;
  column: int;
  total: int;
  target: int;
  target_start: int;
  target_end: int;
  position: int;
begin
  line := line_of_pos(text, caret);
  start := line_start_of(text, line);
  column := caret - start;
  total := line_count(text);
  target := line + delta;
  if target < 0 then
    target := 0;
  if target > total - 1 then
    target := total - 1;
  target_start := line_start_of(text, target);
  target_end := line_end_of(text, target_start);
  position := target_start + column;
  if position > target_end then
    position := target_end;
  position := snap_boundary(text, target_start, position);
  if not extend then
    anchor := position;
  caret := position;
  ensure_visible();
end;

// Home/End; `to_file` jumps to the document ends (Ctrl+Home/Ctrl+End).
procedure line_home(extend: bool; to_file: bool);
var
  line: int;
  start: int;
begin
  if to_file then
    start := 0
  else
  begin
    line := line_of_pos(text, caret);
    start := line_start_of(text, line);
  end;
  if not extend then
    anchor := start;
  caret := start;
  ensure_visible();
end;

procedure line_end_move(extend: bool; to_file: bool);
var
  line: int;
  start: int;
  stop: int;
begin
  if to_file then
    stop := int(core.len(text))
  else
  begin
    line := line_of_pos(text, caret);
    start := line_start_of(text, line);
    stop := line_end_of(text, start);
  end;
  if not extend then
    anchor := stop;
  caret := stop;
  ensure_visible();
end;

procedure delete_selection_or_backspace();
var
  first: int;
  last: int;
  value: Status;
begin
  if anchor <> caret then
  begin
    selection_bounds(first, last);
    value := ed_replace(text, first, last - first, "");
    if value = Ok then
      collapse_to(first)
    else
      status_line := "edit refused";
  end
  else
  begin
    value := ed_backspace(text, caret);
    if value = CapacityExceeded then
      status_line := "buffer full"
    else if value <> Ok then
      status_line := "edit refused";
    anchor := caret;
  end;
  ensure_visible();
end;

procedure delete_selection_or_next();
var
  first: int;
  last: int;
  value: Status;
begin
  if anchor <> caret then
  begin
    selection_bounds(first, last);
    value := ed_replace(text, first, last - first, "");
    if value = Ok then
      collapse_to(first)
    else
      status_line := "edit refused";
  end
  else
  begin
    value := ed_delete_forward(text, caret);
    if value = CapacityExceeded then
      status_line := "buffer full"
    else if value <> Ok then
      status_line := "edit refused";
    anchor := caret;
  end;
  ensure_visible();
end;

// ---- menu model ----------------------------------------------------------

// The two palettes. Light is the System 7.5 set the editor always used; dark
// keeps the same role names with a near-black content base and brightened
// syntax inks, so every caller and pixel probe reads the current theme through
// `bg`/`ink`/`dim`/`sel_bg`/`sel_ink`/`rule` and the five `*_color` fields.
// Switching only changes these fields; no layout or text state is touched.
procedure apply_theme();
begin
  if dark then
  begin
    bg := uint(0x001E1E1E);
    ink := uint(0x00D4D4D4);
    dim := uint(0x00808080);
    sel_bg := uint(0x00264F78);
    sel_ink := uint(0x00FFFFFF);
    rule := uint(0x00484848);
    kw_color := uint(0x00569CD6);
    type_color := uint(0x004EC9B0);
    string_color := uint(0x00CE9178);
    comment_color := uint(0x006A9955);
    number_color := uint(0x00B5CEA8);
  end
  else
  begin
    bg := stdlib.ui_white();
    ink := stdlib.ui_black();
    dim := stdlib.ui_gray();
    sel_bg := stdlib.ui_accent();
    sel_ink := stdlib.ui_white();
    rule := stdlib.ui_black();
    kw_color := uint(0x000080);
    type_color := uint(0x800000);
    string_color := uint(0x008000);
    comment_color := uint(0x808080);
    number_color := uint(0x804000);
  end;
end;

procedure setup_menu();
begin
  titles[0] := "File";
  file_items[0] := "New File";
  file_items[1] := "Open";
  file_items[2] := "Save";
  file_items[3] := "Save As...";
  file_items[4] := "-";
  file_items[5] := "Highlight";
  file_items[6] := "Dark";
  file_items[7] := "Quit";
  file_keys[0] := "Ctrl+N";
  file_keys[1] := "Ctrl+O";
  file_keys[2] := "Ctrl+S";
  file_keys[3] := "Ctrl+Shift+S";
  file_keys[4] := "";
  file_keys[5] := "";
  file_keys[6] := "Ctrl+D";
  file_keys[7] := "Ctrl+Q";
  // Every row is enabled now that the home filesystem is writable; the
  // separator is never selectable regardless of the mask.
  file_disabled := uint(0);
end;

procedure close_menu();
begin
  open_menu := stdlib.ui_menu_close();
  selected := -1;
end;

procedure open_file_menu();
begin
  open_menu := stdlib.ui_menu_open(
    0, FileItemCount, file_items, file_disabled, selected);
end;

// The File > Highlight toggle: lexical colouring on/off and the menu check
// mark stay in step. The caller redraws the frame.
procedure toggle_highlight();
begin
  highlight := not highlight;
  file_checked := stdlib.ui_menu_set(
    file_checked, FileHighlightItem, highlight);
  if highlight then
    status_line := "syntax on"
  else
    status_line := "syntax off";
end;

// File > Dark and Ctrl+D: swap the palette, keep the menu check mark in step
// and leave the document, caret, selection, scroll and highlighting alone.
// The caller redraws the whole frame (menu bar, pull-down and scrollbar
// included) from the new palette.
procedure toggle_dark();
begin
  dark := not dark;
  apply_theme();
  file_checked := stdlib.ui_menu_set(file_checked, FileDarkItem, dark);
  if dark then
    status_line := "dark on"
  else
    status_line := "dark off";
end;

// File > New File and Ctrl+N: replace the document with an unnamed, empty
// buffer. Nothing is written yet; the first Save or Ctrl+S opens the Save File
// dialog created by `lib.file_dialog.save_file`, so the user chooses the home
// name and directory instead of the editor inventing one.
procedure new_file();
begin
  text := "";
  used := 0;
  caret := 0;
  anchor := 0;
  top_line := 0;
  left_byte := 0;
  scroll_dragging := false;
  scroll_preview := 0;
  path := "";
  untitled := true;
  highlight := false;
  file_checked := stdlib.ui_menu_set(file_checked, FileHighlightItem, false);
  refresh_line_states();
  status_line := "new file (unnamed)";
end;

// File > Open and Ctrl+O (M9.3): run the `/lib` modal file-open dialog with
// the current path as its start, then load the chosen regular file. A cancel
// or any dialog failure leaves the document, path, caret, selection and view
// untouched; the dialog's window close returns focus, and the editor raises
// itself in case another window was above it when the dialog opened.
procedure browse_open();
var
  value: Status;
begin
  value := file_dialog.open_file(path, dialog_path);
  if value = Ok then
  begin
    st := open_path(dialog_path);
    st := syslib.window_raise(id);
  end
  else if value = Invalid then
    status_line := "open cancelled"
  else
    status_line := "open failed";
end;

procedure activate_menu(index: int);
begin
  if index = FileNewItem then
  begin
    close_menu();
    new_file();
  end
  else if index = FileOpenItem then
  begin
    close_menu();
    browse_open();
  end
  else if index = FileSaveItem then
  begin
    close_menu();
    try_save();
  end
  else if index = FileSaveAsItem then
  begin
    close_menu();
    save_as();
  end
  else if index = FileHighlightItem then
  begin
    close_menu();
    toggle_highlight();
  end
  else if index = FileDarkItem then
  begin
    close_menu();
    toggle_dark();
  end
  else if index = FileQuitItem then
  begin
    close_menu();
    running := false;
  end;
end;

// ---- key handling --------------------------------------------------------

procedure handle_key();
var
  key: int;
  mods: int;
  ctrl: bool;
  shift: bool;
  action: int;
  text_byte: byte;
begin
  key := stdlib.ui_key_code(ev.code);
  mods := stdlib.ui_key_modifiers(ev.code);
  ctrl := (mods div 2) mod 2 = 1;
  shift := mods mod 2 = 1;

  if open_menu >= 0 then
  begin
    action := stdlib.ui_menu_key(ev.code, true);
    if action = 6 then
      close_menu()
    else if action = 1 then
      selected := stdlib.ui_menu_move(
        selected, FileItemCount, -1, file_items, file_disabled)
    else if action = 2 then
      selected := stdlib.ui_menu_move(
        selected, FileItemCount, 1, file_items, file_disabled)
    else if action = 5 then
    begin
      if selected >= 0 and
         stdlib.ui_menu_selectable(file_items[selected], file_disabled, selected) then
        activate_menu(selected);
    end;
    return;
  end;

  if ctrl then
  begin
    if key = 0x6E or key = 0x4E then
    begin
      new_file();
      return;
    end;
    if key = 0x73 or key = 0x53 then
    begin
      if shift then
        save_as()
      else
        try_save();
      return;
    end;
    if key = 0x71 or key = 0x51 then
    begin
      running := false;
      return;
    end;
    if key = 0x6F or key = 0x4F then
    begin
      browse_open();
      return;
    end;
    if key = 0x64 or key = 0x44 then
    begin
      toggle_dark();
      return;
    end;
    if key = 0x61 or key = 0x41 then
    begin
      used := stdlib.str_selection_all(text, anchor, caret);
      ensure_visible();
      return;
    end;
  end;

  if key = 0x100 then
    return;

  if stdlib.ui_key_is_backspace(ev.code) then
    delete_selection_or_backspace()
  else if stdlib.ui_key_is_delete(ev.code) then
    delete_selection_or_next()
  else if stdlib.ui_key_is_enter(ev.code) then
    replace_selection("\n")
  else if stdlib.ui_key_is_tab(ev.code) then
    replace_selection("  ")
  else if stdlib.ui_key_is_left(ev.code) then
  begin
    if shift then
      extend_horizontal(-1)
    else
      move_horizontal(-1);
  end
  else if stdlib.ui_key_is_right(ev.code) then
  begin
    if shift then
      extend_horizontal(1)
    else
      move_horizontal(1);
  end
  else if stdlib.ui_key_is_up(ev.code) then
    move_vertical(-1, shift)
  else if stdlib.ui_key_is_down(ev.code) then
    move_vertical(1, shift)
  else if key = 0x116 then
    move_vertical(0 - Rows, shift)
  else if key = 0x117 then
    move_vertical(Rows, shift)
  else if stdlib.ui_key_is_home(ev.code) then
    line_home(shift, ctrl)
  else if stdlib.ui_key_is_end(ev.code) then
    line_end_move(shift, ctrl)
  else
  begin
    text_byte := stdlib.ui_key_text(ev.code);
    if text_byte >= byte(32) and text_byte < byte(127) then
      type_char(text_byte);
  end;
end;

// ---- pointer handling ----------------------------------------------------

// Sets the caret to the first line of the view when a scrollbar action moved
// the view past it, or to the last visible line when it moved above it; the
// selection collapses. Without this a page click or a thumb drag could leave
// the caret line off screen and the next key would jump the view back (M9.2).
procedure clamp_caret_to_view();
var
  line: int;
begin
  line := line_of_pos(text, caret);
  if line < top_line then
  begin
    caret := line_start_of(text, top_line);
    anchor := caret;
  end
  else if line >= top_line + Rows then
  begin
    line := top_line + Rows - 1;
    caret := line_start_of(text, line);
    anchor := caret;
  end;
end;

// The thumb height and travel for `total` lines against `Rows` visible rows,
// matching `stdlib.ui_scrollbar`: the track is `ScrollH - 4` tall, the thumb
// the visible fraction with an 8-pixel floor (clamped to the track), and it
// travels over `track - thumb`. The drag preview passes the line count cached
// at the press, so no pointer move rescans the document (M16.8).
procedure thumb_metrics(total: int; thumb_h: var int; travel: var int);
var
  track_h: int;
begin
  track_h := ScrollH - 4;
  if total <= 0 then
    thumb_h := track_h
  else
  begin
    if Rows <= 0 then
      thumb_h := 8
    else
      thumb_h := (track_h * Rows) div total;
    if thumb_h < 8 then
      thumb_h := 8;
    if thumb_h > track_h then
      thumb_h := track_h;
  end;
  travel := track_h - thumb_h;
end;

// The current scrollbar thumb geometry for `total` lines, matching
// `stdlib.ui_scrollbar`. The press, the check-mode proof and the preview use
// the same arithmetic (M9.2).
procedure scrollbar_thumb(total: int; thumb_y: var int; thumb_h: var int);
var
  max: int;
  pos: int;
  travel: int;
begin
  thumb_metrics(total, thumb_h, travel);
  max := total - Rows;
  if max < 0 then
    max := 0;
  pos := stdlib.ui_scrollbar_clamp(top_line, Rows, total);
  thumb_y := scroll_y + 2;
  if max > 0 and travel > 0 then
    thumb_y := scroll_y + 2 + (travel * pos) div max;
end;

// Ends a thumb drag and applies the preview to the view: the document jumps
// to the dropped position once, here, not on every pointer move (M16.8).
// Returns whether the view or the clamped caret changed.
function end_scroll_drag(): bool;
begin
  scroll_dragging := false;
  if scroll_preview = top_line then
    return false;
  top_line := scroll_preview;
  clamp_caret_to_view();
  return true;
end;

// Places the caret and returns true only when the caret, the selection or the
// view actually changed, so a click that lands where the caret already is does
// not repaint (M9.2).
function click_text(px: int; py: int): bool;
var
  row: int;
  line: int;
  total: int;
  start: int;
  stop: int;
  column: int;
  position: int;
  was_caret: int;
  was_anchor: int;
  was_top: int;
  was_left: int;
begin
  was_caret := caret;
  was_anchor := anchor;
  was_top := top_line;
  was_left := left_byte;
  row := (py - text_y) div LineH;
  if row < 0 then
    row := 0;
  line := top_line + row;
  total := line_count(text);
  if line > total - 1 then
    line := total - 1;
  if line < 0 then
    line := 0;
  start := line_start_of(text, line);
  stop := line_end_of(text, start);
  column := (px - text_x) div 8 + left_byte;
  if column < left_byte then
    column := left_byte;
  position := start + column;
  if position > stop then
    position := stop;
  if position < start then
    position := start;
  position := snap_boundary(text, start, position);
  collapse_to(position);
  ensure_visible();
  return caret <> was_caret or anchor <> was_anchor or
    top_line <> was_top or left_byte <> was_left;
end;

// A track click pages by `action`; returns whether the view (or the clamped
// caret) moved.
function page_scroll(action: int): bool;
var
  total: int;
  was_top: int;
  was_caret: int;
  was_anchor: int;
begin
  total := line_count(text);
  was_top := top_line;
  was_caret := caret;
  was_anchor := anchor;
  if action = 1 then
    top_line := stdlib.ui_scrollbar_clamp(top_line - Rows, Rows, total)
  else if action = 2 then
    top_line := stdlib.ui_scrollbar_clamp(top_line + Rows, Rows, total);
  clamp_caret_to_view();
  return top_line <> was_top or caret <> was_caret or anchor <> was_anchor;
end;

// Handles one pointer event and returns whether a whole frame is needed
// (M9.2/M16.8). A thumb drag never returns true while held: it redraws and
// recomposites only the scrollbar strip, leaving the document view where it
// was, and applies the dropped position on release. A no-button move over the
// text and a move that keeps the same menu row are free; a press on the thumb
// itself starts the drag without repainting; release repaints only when the
// preview moved the view.
function handle_pointer(): bool;
var
  bar: int;
  row: int;
  action: int;
  was_menu: int;
  was_selected: int;
  thumb_y: int;
  thumb_h: int;
  travel: int;
  max_top: int;
  desired: int;
  preview: int;
begin
  // A grabbed thumb follows the pointer while the primary button is held; a
  // release or a move without the button ends the drag (M9.2, like M8.9).
  if scroll_dragging then
  begin
    if ev.kind = PointerUp then
      return end_scroll_drag();
    if ev.kind = PointerMove then
    begin
      if ev.code mod uint(2) <> uint(1) then
        return end_scroll_drag();
      thumb_metrics(drag_total, thumb_h, travel);
      max_top := drag_total - Rows;
      if max_top < 0 then
        max_top := 0;
      if travel > 0 and max_top > 0 then
      begin
        desired := ev.y - scroll_grab_dy;
        if desired < scroll_y + 2 then
          desired := scroll_y + 2;
        if desired > scroll_y + 2 + travel then
          desired := scroll_y + 2 + travel;
        preview := ((desired - (scroll_y + 2)) * max_top) div travel;
        preview := stdlib.ui_scrollbar_clamp(preview, Rows, drag_total);
        if preview <> scroll_preview then
        begin
          scroll_preview := preview;
          // M16.8: only the strip. The retained canvas keeps the old text
          // rows, and `syslib.present` recomposites just this rectangle.
          draw_scrollbar_at(scroll_preview, drag_total);
          // `present` takes a screen rectangle (spec 0026 C7): the one call
          // that still adds the content origin.
          st := syslib.present(rect.x + scroll_x, rect.y + scroll_y, ScrollW, ScrollH);
        end;
      end;
      return false;
    end;
    return false;
  end;

  if ev.kind = PointerDown then
  begin
    bar := stdlib.ui_menu_bar_hit(0, 0, ContentW, titles, 1, ev.x, ev.y);
    if bar = 0 then
    begin
      if open_menu = 0 then
        close_menu()
      else
        open_file_menu();
      return true;
    end;
    if open_menu >= 0 then
    begin
      was_selected := selected;
      row := stdlib.ui_menu_hit(
        4, MenuBarH, MenuW, file_items, FileItemCount,
        ev.x, ev.y);
      if row >= 0 then
      begin
        if stdlib.ui_menu_selectable(file_items[row], file_disabled, row) then
          selected := row;
      end
      else
        close_menu();
      return open_menu < 0 or selected <> was_selected;
    end;
    if stdlib.ui_rect_hit(text_x, text_y, TextW, ScrollH, ev.x, ev.y) then
      return click_text(ev.x, ev.y);
    if stdlib.ui_rect_hit(scroll_x, scroll_y, ScrollW, ScrollH, ev.x, ev.y) then
    begin
      action := stdlib.ui_scrollbar_hit(
        scroll_x, scroll_y, ScrollW, ScrollH, ev.x, ev.y,
        top_line, Rows, line_count(text));
      if action = 3 then
      begin
        drag_total := line_count(text);
        scrollbar_thumb(drag_total, thumb_y, thumb_h);
        scroll_dragging := true;
        scroll_preview := top_line;
        scroll_grab_dy := ev.y - thumb_y;
        return false;
      end;
      return page_scroll(action);
    end;
    return false;
  end
  else if ev.kind = PointerUp then
  begin
    if open_menu >= 0 then
    begin
      was_menu := open_menu;
      row := stdlib.ui_menu_hit(
        4, MenuBarH, MenuW, file_items, FileItemCount,
        ev.x, ev.y);
      if row >= 0 and row = selected and
         stdlib.ui_menu_selectable(file_items[row], file_disabled, row) then
        activate_menu(row)
      else if row < 0 then
        close_menu();
      return open_menu <> was_menu;
    end;
    return false;
  end
  else if ev.kind = PointerMove then
  begin
    if open_menu >= 0 then
    begin
      was_selected := selected;
      row := stdlib.ui_menu_hit(
        4, MenuBarH, MenuW, file_items, FileItemCount,
        ev.x, ev.y);
      if row >= 0 and stdlib.ui_menu_selectable(file_items[row], file_disabled, row) then
        selected := row;
      return selected <> was_selected;
    end;
    return false;
  end;
  return false;
end;

// ---- drawing -------------------------------------------------------------

procedure compute_layout();
begin
  text_x := TextLeft;
  text_y := TextTop;
  scroll_x := ScrollLeft;
  scroll_y := ScrollTop;
  status_y := StatusTop;
end;

// Re-reads the content rectangle. Drawing and hit-testing are window-local
// (spec 0026 C8), so the layout never changes with a move; only
// `syslib.present`'s screen rectangle needs the origin.
procedure refresh_layout();
begin
  st := syslib.window_content_rect(id, rect);
  if st = Ok then
    compute_layout();
end;

// One horizontal slice of the current line, from `left` (the byte shown at
// text_x, used for x) to `to`; both ends are boundaries and the range is at
// most `VisibleCols` bytes.
procedure draw_segment(left: int; from: int; to: int; y: int; color: uint);
var
  got: int;
  at: int;
begin
  if to <= from then
    return;
  at := snap_boundary(text, from, to);
  if at <= from then
    return;
  got := core.substr_into(slice_buf, text, from, at - from);
  if got > 0 then
    st := syslib.draw_text(text_x + (from - left) * 8, y + 4, slice_buf, color);
end;

// One document line with its selection band. The selection background is
// painted behind the glyphs and the selected cells are redrawn in `sel_ink`,
// so the band and its text stay readable; the unselected parts use `ink`.
procedure draw_line(start: int; stop: int; y: int);
var
  from: int;
  to: int;
  first: int;
  last: int;
  band_from: int;
  band_to: int;
begin
  from := start + left_byte;
  if from > stop then
    from := stop;
  to := stop;
  if to > from + VisibleCols then
    to := from + VisibleCols;
  to := snap_boundary(text, from, to);
  if to < from then
    to := from;
  selection_bounds(first, last);
  band_from := from;
  if first > band_from then
    band_from := first;
  band_to := to;
  if last < band_to then
    band_to := last;
  if band_from < band_to then
  begin
    st := syslib.fill_rect(
      text_x + (band_from - from) * 8, y + 2,
      (band_to - band_from) * 8, 12, sel_bg);
    draw_segment(from, from, band_from, y, ink);
    draw_segment(from, band_from, band_to, y, sel_ink);
    draw_segment(from, band_to, to, y, ink);
  end
  else
    draw_segment(from, from, to, y, ink);
end;

// One line with lexical colours (M9.1). `block_open` is the block-comment
// state at the line start and is left at the line end, so `draw_lines` carries
// it to the next visible line. The whole line is scanned (even the part left
// of `left_byte`) so a comment opened before the visible span still colours
// it; only the visible span is drawn, in at most three pieces around the
// selection band. Runs of default bytes are merged into one draw call, so a
// line of plain text costs one `draw_text`.
procedure draw_syntax_line(start: int; stop: int; y: int);
var
  from: int;
  to: int;
  first: int;
  last: int;
  band_from: int;
  band_to: int;
  i: int;
  finish: int;
  cls: int;
  step: int;
  state: bool;
  next_state: bool;
  grouping: bool;
  a: int;
  b: int;
  ink: uint;
  part_from: int;
  part_to: int;
begin
  from := start + left_byte;
  if from > stop then
    from := stop;
  to := stop;
  if to > from + VisibleCols then
    to := from + VisibleCols;
  to := snap_boundary(text, from, to);
  if to < from then
    to := from;
  selection_bounds(first, last);
  band_from := from;
  if first > band_from then
    band_from := first;
  band_to := to;
  if last < band_to then
    band_to := last;
  if band_from < band_to then
    st := syslib.fill_rect(
      text_x + (band_from - from) * 8, y + 2,
      (band_to - band_from) * 8, 12, sel_bg);

  state := block_open;
  i := start;
  while i < stop do
  begin
    scan_token(text, i, stop, state, finish, cls, next_state);
    state := next_state;
    if finish <= i then
      finish := i + 1;
    if cls = ClassDefault then
    begin
      // Merge all following default bytes (whitespace, punctuation, whole
      // non-ASCII code points) until a token that needs its own colour.
      grouping := true;
      while finish < stop and grouping do
      begin
        if text[finish] = byte(47) and finish + 1 < stop and
           text[finish + 1] = byte(47) then
          grouping := false
        else if text[finish] = byte(123) or text[finish] = byte(34) or
                is_digit(text[finish]) or is_ident_start(text[finish]) then
          grouping := false
        else
        begin
          step := codepoint_length(text, finish, stop);
          if step <= 0 then
            grouping := false
          else
            finish := finish + step;
        end;
      end;
    end;

    ink := class_color(cls);
    a := i;
    if a < from then
      a := from;
    b := finish;
    if b > to then
      b := to;
    if a < b then
    begin
      // The unselected span before the band keeps the token colour.
      part_from := a;
      part_to := b;
      if part_to > band_from then
        part_to := band_from;
      if part_to > part_from then
        draw_segment(from, part_from, part_to, y, ink);

      // Selected cells use the selection ink on the band.
      part_from := a;
      if part_from < band_from then
        part_from := band_from;
      part_to := b;
      if part_to > band_to then
        part_to := band_to;
      if part_to > part_from then
        draw_segment(from, part_from, part_to, y, sel_ink);

      // The unselected span after the band.
      part_from := a;
      if part_from < band_to then
        part_from := band_to;
      part_to := b;
      if part_to > part_from then
        draw_segment(from, part_from, part_to, y, ink);
    end;
    i := finish;
  end;
  block_open := state;
end;

procedure draw_lines();
var
  total: int;
  length: int;
  start: int;
  stop: int;
  row: int;
  line: int;
  y: int;
  column: int;
  caret_line: int;
  caret_start: int;
begin
  length := int(core.len(text));
  total := line_count(text);
  start := line_start_of(text, top_line);
  if highlight then
  begin
    // M9.2: the block-comment state at the first visible line was cached when
    // the document was published; only the visible lines are scanned per
    // frame, not the document from byte 0.
    line := top_line;
    if line < 0 then
      line := 0;
    if line >= total then
      line := total - 1;
    block_open := line_states[line] <> byte(0);
  end;
  row := 0;
  while row < Rows do
  begin
    line := top_line + row;
    if line < total then
    begin
      stop := line_end_of(text, start);
      y := text_y + row * LineH;
      if highlight then
        draw_syntax_line(start, stop, y)
      else
        draw_line(start, stop, y);
      if stop < length then
        start := stop + 1
      else
        start := length;
    end;
    row := row + 1;
  end;

  caret_line := line_of_pos(text, caret);
  if caret_line >= top_line and caret_line < top_line + Rows then
  begin
    caret_start := line_start_of(text, caret_line);
    column := caret - caret_start;
    if column >= left_byte and column - left_byte <= VisibleCols then
    begin
      y := text_y + (caret_line - top_line) * LineH;
      st := syslib.fill_rect(
        text_x + (column - left_byte) * 8, y + 3, 1, 10, ink);
    end;
  end;
end;

procedure draw_path_line();
var
  width: int;
begin
  if int(core.len(path)) = 0 then
    st := syslib.draw_text(8, PathTop + 4, "(no file)", dim)
  else
    st := syslib.draw_text(8, PathTop + 4, path, ink);
  width := stdlib.ui_text_width("Ctrl+S save");
  st := syslib.draw_text(
    ContentW - 8 - width, PathTop + 4, "Ctrl+S save", dim);
  // The separator is a palette pixel in both themes, not the fixed black
  // `stdlib.ui_separator` (which would vanish on the dark base).
  st := syslib.fill_rect(0, PathTop + PathH - 1, ContentW, 1, rule);
end;

procedure draw_status();
var
  line: int;
  start: int;
  column: int;
  label_w: int;
  x: int;
begin
  st := syslib.fill_rect(0, status_y - 2, ContentW, 1, rule);
  st := syslib.draw_text(8, status_y + 4, status_line, ink);

  line := line_of_pos(text, caret);
  start := line_start_of(text, line);
  column := column_of(text, start, caret);
  used := core.format_int_into(digits_line, line + 1, uint(10), uint(0));
  used := core.format_int_into(digits_col, column + 1, uint(10), uint(0));
  label_w := (3 + int(core.len(digits_line)) + 6 + int(core.len(digits_col))) * 8;
  x := ContentW - 8 - label_w;
  st := syslib.draw_text(x, status_y + 4, "Ln ", dim);
  st := syslib.draw_text(x + 24, status_y + 4, digits_line, ink);
  st := syslib.draw_text(
    x + 24 + int(core.len(digits_line)) * 8, status_y + 4, ", Col ", dim);
  st := syslib.draw_text(
    x + 24 + int(core.len(digits_line)) * 8 + 48, status_y + 4, digits_col, ink);
end;

// ---- dark chrome ---------------------------------------------------------
//
// `stdlib.ui_menu_bar`, `ui_menu_dropdown` and `ui_scrollbar` hard-code the
// light System 7.5 palette, so dark mode paints the same geometry here. The
// hit-test helpers stay the library ones: the bar label starts at `x + 8`,
// pull-down rows are 16 pixels with the check column at `x + 8` and the label
// at `x + 22`, and the scrollbar uses `thumb_metrics` (track `ScrollH - 4`,
// 8-pixel floor). Light mode still calls the `stdlib` helpers unchanged.

// The seven-pixel check mark, at the same offsets as `ui_menu_dropdown`.
procedure draw_check_theme(x: int; y: int; color: uint);
begin
  st := syslib.fill_rect(x + 2, y + 5, 1, 1, color);
  st := syslib.fill_rect(x + 3, y + 6, 1, 1, color);
  st := syslib.fill_rect(x + 4, y + 7, 1, 1, color);
  st := syslib.fill_rect(x + 5, y + 6, 1, 1, color);
  st := syslib.fill_rect(x + 6, y + 5, 1, 1, color);
  st := syslib.fill_rect(x + 7, y + 4, 1, 1, color);
  st := syslib.fill_rect(x + 8, y + 3, 1, 1, color);
end;

// The one-title menu bar. The active cell is `label width + 8` wide over the
// 18-pixel interior, matching `ui_menu_bar`.
procedure draw_menu_bar_themed();
var
  label_w: int;
begin
  if not dark then
    st := stdlib.ui_menu_bar(0, 0, ContentW, titles, 1, open_menu)
  else
  begin
    st := syslib.fill_rect(0, 0, ContentW, MenuBarH, bg);
    label_w := stdlib.ui_text_width(titles[0]);
    if open_menu = 0 then
    begin
      st := syslib.fill_rect(
        4, 2, label_w + 8, MenuBarH - 4, sel_bg);
      st := syslib.draw_text(8, 7, titles[0], sel_ink);
    end
    else
      st := syslib.draw_text(8, 7, titles[0], ink);
    st := syslib.fill_rect(0, MenuBarH - 1, ContentW, 1, rule);
  end;
end;

// The pull-down in the dark palette. Separators are palette rules, the chosen
// row is `sel_bg`/`sel_ink`, the check mark follows the row ink, labels sit at
// `x + 22` and shortcuts are right-aligned at `x + w - 8`.
procedure draw_dark_dropdown();
var
  x: int;
  y: int;
  height: int;
  row: int;
  row_y: int;
  text_y: int;
  ink_color: uint;
  shortcut_w: int;
begin
  x := 4;
  y := MenuBarH;
  height := FileItemCount * 16 + 2;
  st := syslib.fill_rect(x + 1, y + 1, MenuW - 2, height - 2, bg);
  st := syslib.draw_rect(x, y, MenuW, height, rule);
  row := 0;
  while row < FileItemCount do
  begin
    row_y := y + 1 + row * 16;
    text_y := row_y + 4;
    if file_items[row] = "-" then
      st := syslib.fill_rect(x + 8, row_y + 8, MenuW - 16, 1, rule)
    else
    begin
      ink_color := ink;
      if row = selected then
      begin
        st := syslib.fill_rect(x + 1, row_y, MenuW - 2, 16, sel_bg);
        ink_color := sel_ink;
      end;
      if stdlib.ui_menu_has(file_checked, row) then
        draw_check_theme(x + 8, row_y, ink_color);
      shortcut_w := stdlib.ui_text_width(file_keys[row]);
      if shortcut_w > 0 then
      begin
        if row = selected then
          st := syslib.draw_text(
            x + MenuW - 8 - shortcut_w, text_y, file_keys[row], sel_ink)
        else
          st := syslib.draw_text(
            x + MenuW - 8 - shortcut_w, text_y, file_keys[row], dim);
      end;
      st := syslib.draw_text(x + 22, text_y, file_items[row], ink_color);
    end;
    row := row + 1;
  end;
end;

procedure draw_dropdown();
begin
  if dark then
    draw_dark_dropdown()
  else
    st := stdlib.ui_menu_dropdown(
      4, MenuBarH, MenuW, file_items, file_keys,
      FileItemCount, selected, file_checked, file_disabled, true);
end;

// The scrollbar strip alone, at `position` over `total` lines. It is redrawn
// without the document rows during a drag preview (M16.8): the canvas keeps
// the rest of the frame, so only this rectangle changes. Dark mode paints the
// same `ui_scrollbar` geometry from the palette.
procedure draw_scrollbar_at(position: int; total: int);
var
  thumb_h: int;
  travel: int;
  max: int;
  pos: int;
  thumb_y: int;
begin
  st := syslib.window_begin(id);
  if not dark then
    st := stdlib.ui_scrollbar(
      scroll_x, scroll_y, ScrollW, ScrollH, position, Rows, total, false)
  else
  begin
    st := syslib.fill_rect(
      scroll_x + 1, scroll_y + 1, ScrollW - 2, ScrollH - 2, bg);
    st := syslib.draw_rect(scroll_x, scroll_y, ScrollW, ScrollH, rule);
    thumb_metrics(total, thumb_h, travel);
    max := total - Rows;
    if max < 0 then
      max := 0;
    pos := stdlib.ui_scrollbar_clamp(position, Rows, total);
    thumb_y := scroll_y + 2;
    if max > 0 and travel > 0 then
      thumb_y := scroll_y + 2 + (travel * pos) div max;
    st := syslib.fill_rect(
      scroll_x + 2, thumb_y, ScrollW - 4, thumb_h, dim);
    st := syslib.draw_rect(
      scroll_x + 2, thumb_y, ScrollW - 4, thumb_h, rule);
  end;
end;

// One complete frame: background, menu, path line, text view, carets,
// scrollbar, status line, then the open pull-down on top. The caller presents
// once afterwards. While a thumb is held the scrollbar shows the preview
// position and the document stays at `top_line` (M16.8).
procedure draw_all();
begin
  // The file dialog is a second window of this task, and opening it takes the
  // one per-task draw scope (spec 0026, C3/C20). Re-opening our own window at
  // the start of every frame keeps the editor drawable after the dialog closes.
  st := syslib.window_begin(id);
  st := syslib.fill_rect(0, 0, ContentW, ContentH, bg);
  draw_menu_bar_themed();
  draw_path_line();
  draw_lines();
  if scroll_dragging then
    draw_scrollbar_at(scroll_preview, drag_total)
  else
    draw_scrollbar_at(top_line, line_count(text));
  draw_status();
  if open_menu >= 0 then
    draw_dropdown();
end;

procedure present_frame();
begin
  st := syslib.window_present(id);
end;

// ---- shared checks -------------------------------------------------------

// Loads `child`, checks the chunked read and size agreement, then proves that
// every error class leaves the document intact.
procedure file_checks();
var
  keep_length: int;
  size: uint;
  value: Status;
begin
  value := open_path("base/child");
  verify("open child",
    value = Ok and path = "base/child" and int(core.len(text)) > 0);
  verify("child prefix", stdlib.starts_with(text, "unit child;"));
  keep_length := int(core.len(text));
  value := core.fs_size("base/child", size);
  verify("child size", value = Ok and int(core.len(text)) = int(size));
  verify("child lines", line_count(text) > 5);

  value := open_path("no_such_file");
  verify("missing file",
    value = NotFound and int(core.len(text)) = keep_length);
  value := open_path(".");
  verify("directory", value = Invalid and int(core.len(text)) = keep_length);
  value := open_path("base/child/x");
  verify("file as directory",
    value = Invalid and int(core.len(text)) = keep_length);

  // M9.4: every current source sample now fits the 128 KiB buffer; the largest
  // is this editor (81,509 B). `apps/accessories/calculator` (32,516 B) is the file the
  // user opened through the dialog and the old 8 KiB limit refused.
  value := open_path("apps/accessories/calculator");
  verify("large source",
    value = Ok and path = "apps/accessories/calculator" and int(core.len(text)) > 8192);
  value := core.fs_size("apps/accessories/calculator", size);
  verify("large source complete",
    value = Ok and int(core.len(text)) = int(size));
  verify("large source valid",
    stdlib.starts_with(text, "unit calculator;") and
      stdlib.str_boundary(text, int(core.len(text))) and line_count(text) > 1);

  value := open_path("base/child");
  verify("large restore",
    value = Ok and int(core.len(text)) = keep_length);
  verify("child intact", stdlib.starts_with(text, "unit child;"));
end;

// Line geometry, app-local editing (insert, delete, backspace, Enter, a 2-byte
// code point), the capacity boundary and invalid UTF-8.
procedure buffer_checks();
var
  i: int;
  value: Status;
begin
  text := "alpha\nbeta\ngamma";
  refresh_line_states();
  verify("line count", line_count(text) = 3);
  verify("line starts",
    line_start_of(text, 0) = 0 and line_start_of(text, 1) = 6
      and line_start_of(text, 2) = 11 and line_start_of(text, 3) = 16);
  verify("line ends",
    line_end_of(text, 0) = 5 and line_end_of(text, 6) = 10
      and line_end_of(text, 11) = 16);
  verify("line of pos",
    line_of_pos(text, 0) = 0 and line_of_pos(text, 6) = 1
      and line_of_pos(text, 16) = 2);
  verify("column", column_of(text, 0, 5) = 5 and column_of(text, 6, 10) = 4);

  collapse_to(0);
  replace_selection("X");
  verify("insert char",
    int(core.len(text)) = 17 and text[0] = byte(88) and caret = 1);
  delete_selection_or_backspace();
  verify("backspace char",
    text = "alpha\nbeta\ngamma" and caret = 0);

  move_vertical(1, false);
  verify("vertical down", caret = 6);
  move_vertical(1, false);
  verify("vertical down again", caret = 11);
  line_end_move(false, false);
  verify("end of line", caret = 16);
  replace_selection("\n");
  verify("enter splits", int(core.len(text)) = 17 and line_count(text) = 4);
  delete_selection_or_backspace();
  verify("backspace joins", int(core.len(text)) = 16 and line_count(text) = 3);
  line_home(false, false);
  verify("home line", caret = 11);
  line_end_move(false, true);
  verify("file end", caret = 16);

  text := "héllo";
  refresh_line_states();
  verify("multibyte length", int(core.len(text)) = 6);
  verify("boundary start",
    stdlib.str_boundary(text, 0) and stdlib.str_boundary(text, 1));
  verify("boundary inside", not stdlib.str_boundary(text, 2));
  verify("boundary after", stdlib.str_boundary(text, 3));
  collapse_to(3);
  value := ed_backspace(text, caret);
  anchor := caret;
  verify("backspace code point",
    value = Ok and text = "hllo" and caret = 1);
  scratch_bytes[0] := byte(0xC3);
  scratch_bytes[1] := byte(0xA9);
  copied := core.substr_into(scratch_text, scratch_bytes, 0, 2);
  verify("code point staged", copied = 2 and int(core.len(scratch_text)) = 2);
  replace_selection(scratch_text);
  verify("insert code point",
    int(core.len(text)) = 6 and text = "héllo" and caret = 3);
  collapse_to(3);
  verify("cursor left codepoint",
    stdlib.str_cursor_left(text, caret) = 1);
  verify("cursor right codepoint",
    stdlib.str_cursor_right(text, caret) = 3);

  i := 0;
  while i < BufferCapacity do
  begin
    load_stage[i] := byte(97);
    i := i + 1;
  end;
  value := publish_staged(BufferCapacity);
  verify("full buffer",
    value = Ok and int(core.len(text)) = BufferCapacity);
  value := ed_replace(text, 0, 0, "x");
  verify("capacity refused", value = CapacityExceeded);
  verify("capacity intact",
    int(core.len(text)) = BufferCapacity and text[0] = byte(97));

  text := "keep";
  refresh_line_states();
  load_stage[0] := byte(0xC3);
  load_stage[1] := byte(0x28);
  value := publish_staged(2);
  verify("invalid utf8", value = Invalid);
  verify("invalid kept", text = "keep");
end;

// The M6.3 save proof (spec 0019, E1): edit `base/child` and save it as the
// home copy, read it back and compare, then save again over the same path. A
// missing home disk reports the error and leaves the document and path alone.
procedure save_checks();
var
  value: Status;
  length: int;
begin
  value := open_path("base/child");
  verify("save open", value = Ok and path = "base/child");
  line_end_move(false, true);
  replace_selection("\n// saved by the M6.3 check\n");
  length := int(core.len(text));

  try_save();
  if no_home then
  begin
    verify("save no home", status_line = "no writable home");
    verify("save keeps document",
      int(core.len(text)) = length and path = "base/child");
  end
  else
  begin
    verify("save copied",
      status_line = "saved home/child" and path = "home/child");
    verify("saved contents", saved_matches());

    // The second save takes the sibling temporary path over the same target.
    length := int(core.len(text));
    try_save();
    verify("replace saved", status_line = "saved" and path = "home/child");
    verify("replace contents", saved_matches());
    verify("replace kept size", int(core.len(text)) = length);
  end;

  // M22.4: a `net/` source is writable in place. The path rules are
  // deterministic; an unmounted keyword then fails without touching the
  // document or the path and without setting the home-only `no_home` flag. The
  // status depends on the host: the kernel router answers `NotFound` for an
  // unmounted keyword, `langhost` answers `Invalid` (spec 0032, H4).
  path := "net/share/x.txt";
  no_home := false;
  value := build_save_paths();
  verify("mount save target",
    value = Ok and save_target = "net/share/x.txt"
      and save_temp = "net/share/x.txt.tmp");
  text := "mount document";
  length := int(core.len(text));
  save_document();
  verify("mount save failed honestly",
    status_line = "not writable" or status_line = "no such directory");
  verify("mount save keeps document",
    int(core.len(text)) = length and path = "net/share/x.txt");
  verify("mount save no home flag", not no_home);

  // Leave a normal document for the drawing probes.
  value := open_path("base/child");
  verify("save restore", value = Ok and path = "base/child");
end;

// File > New File (Ctrl+N): create a fresh empty home file, clear the document and
// point the editor at it, then save an edit through the same path. Without a
// writable home the current document and path stay untouched.
procedure new_file_checks();
var
  value: Status;
begin
  value := open_path("base/child");
  verify("new open", value = Ok and path = "base/child");
  new_file();
  verify("new item", file_items[FileNewItem] = "New File");
  verify("new rows", FileNewItem = 0 and FileOpenItem = 1
    and FileSaveItem = 2 and FileSaveAsItem = 3);
  verify("new empty", int(core.len(text)) = 0 and caret = 0 and anchor = 0);
  verify("new unnamed", untitled and int(core.len(path)) = 0);
  verify("new status", status_line = "new file (unnamed)");
  verify("new plain", not highlight and
    not stdlib.ui_menu_has(file_checked, FileHighlightItem));
  value := open_path("base/child");
  verify("new restore", value = Ok and path = "base/child" and not untitled);
end;

// Vertical scrolling on `base/child` (28 lines in 26 rows) and horizontal scrolling
// on a 100-byte line.
procedure scroll_checks();
var
  total: int;
  i: int;
  value: Status;
begin
  total := line_count(text);
  verify("child scrollable", total > Rows);
  caret := int(core.len(text));
  anchor := caret;
  ensure_visible();
  verify("view follows caret", top_line = total - Rows);

  move_vertical(0 - Rows, false);
  verify("page up caret", line_of_pos(text, caret) < total - 1);
  verify("page up view", top_line >= 0 and top_line <= total - Rows);

  line_home(false, true);
  verify("home top", caret = 0 and top_line = 0);

  i := 0;
  while i < 100 do
  begin
    load_stage[i] := byte(97);
    i := i + 1;
  end;
  value := publish_staged(100);
  verify("long line", value = Ok and int(core.len(text)) = 100);
  caret := int(core.len(text));
  anchor := caret;
  ensure_visible();
  verify("horizontal scroll",
    left_byte > 0 and caret - left_byte <= VisibleCols);
  verify("horizontal boundary", stdlib.str_boundary(text, left_byte));
  line_home(false, true);
  verify("horizontal reset", caret = 0 and left_byte = 0);
end;

// Drop queued events and any coalesced owner expose.
procedure drain_quiet();
var
  i: int;
begin
  i := 0;
  while i < 8 do
  begin
    st := syslib.poll_event(ev);
    if st <> Ok then
      i := 8
    else
      i := i + 1;
  end;
end;

// ---- injection (the deterministic test hook) ------------------------------

// Drains queued pointer events through the same handler the interactive loop
// uses. The redraw result is ignored because check mode draws explicitly; an
// owner `Expose` still refreshes the cached absolute layout.
procedure pump_pointer_events();
var
  active: bool;
  count: int;
begin
  active := true;
  count := 0;
  while active and count < 64 do
  begin
    st := syslib.poll_event(ev);
    if st = Ok then
    begin
      count := count + 1;
      if ev.kind = Expose then
      begin
        if ev.window = id then
          refresh_layout();
      end
      else if ev.window = id then
      begin
        if ev.kind = PointerDown or ev.kind = PointerUp or
           ev.kind = PointerMove then
          handle_pointer();
      end;
    end
    else
      active := false;
  end;
end;

// Sends Ctrl+D through the injected-key queue and drains up to eight events,
// routing the KeyDown through the same `handle_key` as the interactive loop.
// Returns whether a KeyDown addressed to this window arrived (the theme
// toggle itself is asserted by the caller).
function pump_ctrl_d(): bool;
var
  i: int;
  arrived: bool;
begin
  arrived := false;
  drain_quiet();
  st := inject.inject_key_mods(0x64, 0, 2);
  i := 0;
  while i < 8 and not arrived do
  begin
    st := syslib.poll_event(ev);
    if st = Ok then
    begin
      if ev.kind = Expose then
      begin
        if ev.window = id then
          refresh_layout();
      end
      else if ev.kind = KeyDown then
      begin
        arrived := ev.window = id;
        if arrived then
          handle_key();
      end;
    end
    else
      i := 8;
    i := i + 1;
  end;
  return arrived;
end;

procedure pointer_to(px: int; py: int);
begin
  // `px`/`py` are window-local; the pointer state is screen-coordinate
  // (spec 0010 I35), so the content origin is added here.
  st := inject.pointer_to(rect.x + px, rect.y + py);
  pump_pointer_events();
end;

procedure pointer_down();
begin
  st := inject.pointer_down();
  pump_pointer_events();
end;

procedure pointer_up();
begin
  st := inject.pointer_up();
  pump_pointer_events();
end;

// Moves with the primary button held. `inject.pointer_to` would release the
// button, so the delta goes directly through the debug pointer hook (M9.2).
procedure pointer_drag_to(px: int; py: int);
begin
  // `px`/`py` are window-local; the pointer state is screen-coordinate, so the
  // content origin is added before the delta is computed (spec 0010 I35).
  st := syslib.inject_pointer(
    rect.x + px - syslib.pointer_x(), rect.y + py - syslib.pointer_y(), uint(1));
  pump_pointer_events();
end;

// ---- modes ---------------------------------------------------------------

// The disabled-screen path: the same file, editing and view logic without a
// window or a pixel.
procedure host_path();
begin
  file_checks();
  scroll_checks();
  buffer_checks();
  save_checks();
  new_file_checks();
  if failed then
    out.say("editor: host failed\n")
  else
    out.say("editor: host ok\n");
end;

procedure check_mode();
var
  i: int;
  found: bool;
  a: int;
  b: int;
  value: Status;
  total: int;
  thumb_y: int;
  thumb_h: int;
  travel: int;
begin
  file_checks();
  scroll_checks();
  buffer_checks();
  save_checks();
  new_file_checks();

  // M9.1: source paths start highlighted, plain text files do not, and the
  // File > Highlight row is present and checked.
  value := open_path("home/readme.txt");
  verify("plain file plain", value = Ok and not highlight);
  verify("plain menu clear", not stdlib.ui_menu_has(file_checked, FileHighlightItem));
  value := open_path("base/child");
  verify("source file highlighted", value = Ok and highlight);
  verify("highlight item", file_items[FileHighlightItem] = "Highlight");
  verify("highlight checked", stdlib.ui_menu_has(file_checked, FileHighlightItem));

  // Lexical colours on deterministic source lines: keyword, comment, type,
  // number and string; then a block comment that starts on one line and ends
  // on the next.
  text := "unit child; // note\nvar n: int; const k := 1;\nconst s := \"x\";";
  refresh_line_states();
  highlight := true;
  file_checked := stdlib.ui_menu_set(file_checked, FileHighlightItem, true);
  collapse_to(int(core.len(text)));
  top_line := 0;
  left_byte := 0;
  draw_all();
  present_frame();
  verify("syntax keyword",
    region_has_color(text_x, text_y + 4, 320, 8, kw_color));
  verify("syntax comment",
    region_has_color(text_x, text_y + 4, 320, 8, comment_color));
  verify("syntax type",
    region_has_color(text_x, text_y + 4 + LineH, 320, 8, type_color));
  verify("syntax number",
    region_has_color(text_x, text_y + 4 + LineH, 320, 8, number_color));
  verify("syntax string",
    region_has_color(text_x, text_y + 4 + 2 * LineH, 320, 8, string_color));

  text := "unit c; { note\nstill note } var n: int;";
  refresh_line_states();
  collapse_to(int(core.len(text)));
  top_line := 0;
  left_byte := 0;
  draw_all();
  present_frame();
  verify("block comment continues",
    region_has_color(text_x, text_y + 4 + LineH, 320, 8, comment_color));
  verify("block comment ends",
    region_has_color(text_x, text_y + 4 + LineH, 320, 8, type_color));

  // The state at the first visible line must be computed line by line: the
  // earlier `//` ends at its newline and does not swallow the `{` on line 1.
  text := "// lead\n{ note\nstill note } var n: int;";
  refresh_line_states();
  collapse_to(int(core.len(text)));
  top_line := 2;
  left_byte := 0;
  draw_all();
  present_frame();
  verify("scrolled block comment",
    region_has_color(text_x, text_y + 4, 320, 8, comment_color));
  verify("scrolled block ends",
    region_has_color(text_x, text_y + 4, 320, 8, type_color));

  // The toggle off leaves only black/white/accent in the text area and clears
  // the menu check. Use the same three coloured lines as the on-probes.
  text := "unit child; // note\nvar n: int; const k := 1;\nconst s := \"x\";";
  refresh_line_states();
  collapse_to(int(core.len(text)));
  top_line := 0;
  left_byte := 0;
  highlight := false;
  file_checked := stdlib.ui_menu_set(file_checked, FileHighlightItem, false);
  draw_all();
  present_frame();
  verify("off keyword",
    not region_has_color(text_x, text_y + 4, 320, 8, kw_color));
  verify("off comment",
    not region_has_color(text_x, text_y + 4 + LineH, 320, 8, comment_color));
  verify("off type",
    not region_has_color(text_x, text_y + 4 + LineH, 320, 8, type_color));
  verify("off string",
    not region_has_color(text_x, text_y + 4 + 2 * LineH, 320, 8, string_color));
  verify("highlight menu off", not stdlib.ui_menu_has(file_checked, FileHighlightItem));
  highlight := true;
  file_checked := stdlib.ui_menu_set(file_checked, FileHighlightItem, true);

  // A deterministic document for the drawing probes.
  text := "IGIS editor\nline two\nline three";
  refresh_line_states();
  status_line := "check mode";
  collapse_to(0);
  top_line := 0;
  left_byte := 0;
  draw_all();
  present_frame();

  verify("menu rule", syslib.get_pixel(300, 21) = rule);
  verify("path rule", syslib.get_pixel(300, 37) = rule);
  verify("glyph ink", syslib.get_pixel(text_x + 1, text_y + 4) = ink);
  verify("glyph hole", syslib.get_pixel(text_x + 4, text_y + 5) = bg);
  verify("caret", syslib.get_pixel(text_x, text_y + 8) = ink);

  anchor := 0;
  caret := 2;
  draw_all();
  present_frame();
  verify("selection band", syslib.get_pixel(text_x + 8, text_y + 2) = sel_bg);
  collapse_to(0);
  draw_all();
  present_frame();

  verify("scrollbar border", syslib.get_pixel(scroll_x, scroll_y) = rule);
  verify("scrollbar thumb", syslib.get_pixel(scroll_x + 4, scroll_y + 3) = dim);
  verify("status rule", syslib.get_pixel(300, status_y - 2) = rule);

  // Dark theme: the row and its check bit, then every themed region by exact
  // pixel. The direct toggle is exercised here; Ctrl+D goes through the
  // injected-key path below.
  verify("dark item", file_items[FileDarkItem] = "Dark");
  verify("dark row", FileDarkItem = 6 and FileQuitItem = 7);
  verify("dark starts off", not dark and
    not stdlib.ui_menu_has(file_checked, FileDarkItem));
  toggle_dark();
  verify("dark toggled on", dark and
    stdlib.ui_menu_has(file_checked, FileDarkItem));
  verify("dark status", status_line = "dark on");
  verify("dark keeps document", int(core.len(text)) > 0 and
    caret = 0 and anchor = 0 and highlight);
  draw_all();
  present_frame();
  verify("dark base", bg = uint(0x001E1E1E) and ink = uint(0x00D4D4D4));
  verify("dark background",
    syslib.get_pixel(text_x + 500, text_y + 300) = bg);
  verify("dark menu rule", syslib.get_pixel(300, 21) = rule);
  verify("dark path rule", syslib.get_pixel(300, 37) = rule);
  verify("dark glyph ink", syslib.get_pixel(text_x + 1, text_y + 4) = ink);
  verify("dark glyph hole", syslib.get_pixel(text_x + 4, text_y + 5) = bg);
  verify("dark caret", syslib.get_pixel(text_x, text_y + 8) = ink);

  anchor := 0;
  caret := 2;
  draw_all();
  present_frame();
  verify("dark selection", syslib.get_pixel(text_x + 8, text_y + 2) = sel_bg);
  collapse_to(0);
  draw_all();
  present_frame();
  verify("dark scrollbar border", syslib.get_pixel(scroll_x, scroll_y) = rule);
  verify("dark scrollbar thumb",
    syslib.get_pixel(scroll_x + 4, scroll_y + 3) = dim);
  verify("dark status rule",
    syslib.get_pixel(300, status_y - 2) = rule);

  // The dark menu bar and pull-down: the active "File" cell is the selection
  // colour, the open pull-down frames a dark interior, the chosen Dark row is
  // filled and its check mark uses the selection ink, and a plain row keeps
  // the base colour. `ui_menu_hit` still answers for the same geometry.
  open_menu := 0;
  selected := FileDarkItem;
  draw_all();
  present_frame();
  verify("dark menu active cell",
    syslib.get_pixel(6, 10) = sel_bg);
  verify("dark dropdown frame",
    syslib.get_pixel(4, MenuBarH) = rule);
  verify("dark dropdown row",
    syslib.get_pixel(84, MenuBarH + 1 + FileDarkItem * 16 + 8) = sel_bg);
  verify("dark dropdown plain row",
    syslib.get_pixel(120, MenuBarH + 1 + 8) = bg);
  verify("dark dropdown check",
    syslib.get_pixel(12 + 4, MenuBarH + 1 + FileDarkItem * 16 + 7) = sel_ink);
  verify("dark dropdown hit",
    stdlib.ui_menu_hit(
      4, MenuBarH, MenuW, file_items, FileItemCount,
      84, MenuBarH + 1 + FileDarkItem * 16 + 8) = FileDarkItem);
  close_menu();
  draw_all();
  present_frame();

  // The five syntax classes keep their distinction in the dark palette.
  text := "unit child; // note\nvar n: int; const k := 1;\nconst s := \"x\";";
  refresh_line_states();
  collapse_to(int(core.len(text)));
  top_line := 0;
  left_byte := 0;
  draw_all();
  present_frame();
  verify("dark syntax keyword",
    region_has_color(text_x, text_y + 4, 320, 8, kw_color));
  verify("dark syntax comment",
    region_has_color(text_x, text_y + 4, 320, 8, comment_color));
  verify("dark syntax type",
    region_has_color(text_x, text_y + 4 + LineH, 320, 8, type_color));
  verify("dark syntax number",
    region_has_color(text_x, text_y + 4 + LineH, 320, 8, number_color));
  verify("dark syntax string",
    region_has_color(text_x, text_y + 4 + 2 * LineH, 320, 8, string_color));

  // Toggling back restores the light palette and drawing exactly.
  toggle_dark();
  verify("dark toggled off", not dark and
    not stdlib.ui_menu_has(file_checked, FileDarkItem));
  verify("light palette", bg = stdlib.ui_white() and ink = stdlib.ui_black());
  text := "IGIS editor\nline two\nline three";
  refresh_line_states();
  status_line := "check mode";
  collapse_to(0);
  top_line := 0;
  left_byte := 0;
  draw_all();
  present_frame();
  verify("light background",
    syslib.get_pixel(text_x + 500, text_y + 300) = bg);
  verify("light glyph ink", syslib.get_pixel(text_x + 1, text_y + 4) = ink);

  // One injected key event proves the queue/routing path: it must arrive with
  // this window's id and flow through handle_key.
  drain_quiet();
  ev.kind := KeyDown;
  ev.x := 0;
  ev.y := 0;
  ev.code := uint(0x58 + 0x58 * 65536);
  ev.window := 0;
  st := syslib.inject_event(ev);
  verify("event injected", st = Ok);
  found := false;
  i := 0;
  while i < 8 and not found do
  begin
    st := syslib.poll_event(ev);
    if st = Ok then
    begin
      if ev.kind = Expose then
      begin
        if ev.window = id then
        begin
          refresh_layout();
          draw_all();
          present_frame();
        end;
      end
      else if ev.kind = KeyDown then
      begin
        verify("event routed", ev.window = id);
        handle_key();
        found := true;
      end;
    end
    else
      i := 8;
    i := i + 1;
  end;
  verify("event handled", found);
  verify("event text", stdlib.starts_with(text, "XIGIS"));
  delete_selection_or_backspace();
  verify("event undone", stdlib.starts_with(text, "IGIS"));

  // Ctrl+D reaches the same toggle through the routed key path, twice: on and
  // back off, so the drag proof below runs on the light palette.
  verify("dark key routed", pump_ctrl_d());
  verify("dark key on", dark and
    stdlib.ui_menu_has(file_checked, FileDarkItem) and status_line = "dark on");
  verify("dark key routed off", pump_ctrl_d());
  verify("dark key off", not dark and
    not stdlib.ui_menu_has(file_checked, FileDarkItem) and
    status_line = "dark off");

  // M9.2: the scrollbar thumb drags through the real pointer path, matching the
  // browser's M8.9. M16.8 defers the view: the held drag moves the thumb strip
  // only and the release applies the dropped position.
  // `base/child` has more lines than the 26-row view.
  value := open_path("base/child");
  verify("drag open", value = Ok and highlight);
  top_line := 0;
  left_byte := 0;
  caret := 0;
  anchor := 0;
  draw_all();
  present_frame();
  total := line_count(text);
  verify("drag scrollable", total > Rows);
  scrollbar_thumb(total, thumb_y, thumb_h);
  verify("drag starts on thumb",
    stdlib.ui_scrollbar_hit(
      scroll_x, scroll_y, ScrollW, ScrollH,
      scroll_x + 8, thumb_y + thumb_h div 2,
      top_line, Rows, total) = 3);
  pointer_to(scroll_x + 8, thumb_y + thumb_h div 2);
  pointer_down();
  verify("drag grabs thumb", scroll_dragging and scroll_preview = top_line);
  pointer_drag_to(scroll_x + 8, scroll_y + ScrollH - 4);
  // The document view did not move; only the thumb strip did, and the
  // strip's own recomposite already shows the preview on screen.
  verify("drag preview", top_line = 0 and scroll_preview = total - Rows);
  verify("preview thumb leaves the top",
    syslib.get_pixel(scroll_x + 4, scroll_y + 4) = bg);
  verify("preview thumb at the bottom",
    syslib.get_pixel(scroll_x + 4, scroll_y + ScrollH - 6) = dim);
  pointer_up();
  verify("scrollbar drag applies",
    not scroll_dragging and top_line = total - Rows);
  draw_all();
  present_frame();
  scrollbar_thumb(total, thumb_y, thumb_h);
  travel := (ScrollH - 4) - thumb_h;
  verify("scrollbar thumb moved",
    travel > 0 and syslib.get_pixel(scroll_x + 4, thumb_y + 2) = dim);

  st := syslib.window_close(id);
  if failed then
    out.say("editor: failed\n")
  else
    out.say("editor: ok\n");
end;

procedure interactive_mode();
begin
  st := open_path(path);
  draw_all();
  present_frame();
  running := true;
  while running do
  begin
    st := syslib.next_event(ev);
    if st <> Ok then
      running := false
    else if ev.kind = Expose then
    begin
      if ev.window = id then
      begin
        refresh_layout();
        draw_all();
        present_frame();
      end;
    end
    else if ev.kind = Close then
    begin
      // The close box requests a close; only this window goes (spec 0011,
      // W23). The loop then closes it and returns.
      if ev.window = id then
        running := false;
    end
    else if ev.kind = KeyDown then
    begin
      if ev.window = id then
      begin
        handle_key();
        if running then
        begin
          draw_all();
          present_frame();
        end;
      end;
    end
    else if ev.kind = PointerDown or ev.kind = PointerUp or ev.kind = PointerMove then
    begin
      if ev.window = id then
      begin
        // M9.2: only a pointer event that changed visible state repaints.
        if handle_pointer() and running then
        begin
          draw_all();
          present_frame();
        end;
      end;
    end;
  end;
  st := syslib.window_close(id);
end;

procedure shot_mode();
var
  deadline: uint;
  dirty: bool;
  i: int;
begin
  st := open_path(path);
  draw_all();
  present_frame();
  out.say("editor: ready\n");
  deadline := core.clock() + uint(HoldSeconds) * uint(NanosPerSecond);
  while core.clock() < deadline and running do
  begin
    dirty := false;
    i := 0;
    while i < 16 do
    begin
      st := syslib.poll_event(ev);
      if st <> Ok then
        i := 16
      else
      begin
        i := i + 1;
        if ev.kind = Expose then
        begin
          if ev.window = id then
          begin
            refresh_layout();
            dirty := true;
          end;
        end
        else if ev.kind = KeyDown then
        begin
          if ev.window = id then
          begin
            handle_key();
            dirty := true;
          end;
        end
        else if ev.kind = PointerDown or ev.kind = PointerUp
                or ev.kind = PointerMove then
        begin
          if ev.window = id then
          begin
            if handle_pointer() then
              dirty := true;
          end;
        end;
        if not running then
          i := 16;
      end;
    end;
    if dirty then
    begin
      draw_all();
      present_frame();
    end;
    // Hold the frame without a spin. A 5 s busy poll is a single continuous
    // run and, on a large document, would spend the whole watchdog budget just
    // waiting for the harness; blocking in `core.sleep` keeps the task idle
    // and lets its per-run budget reset (ADR 0061).
    st := core.sleep(uint(50));
  end;
  st := syslib.window_close(id);
  out.say("editor: done\n");
end;

procedure parse_args(args: const string[1024]);
var
  space: int;
  trimmed: string[256];
  got: int;
begin
  mode := 0;
  path := "base/child";
  if stdlib.starts_with(args, "check") then
    mode := 1
  else if stdlib.starts_with(args, "shot") then
  begin
    mode := 2;
    space := core.find(args, byte(32));
    if space >= 0 and space + 1 < int(core.len(args)) then
    begin
      used := core.substr_into(
        tail_buf, args, space + 1, int(core.len(args)) - space - 1);
      got := stdlib.trim_into(trimmed, tail_buf);
      if got > 0 and got <= PathCapacity then
        used := core.substr_into(path, trimmed, 0, got)
      else if got > PathCapacity then
        status_line := "path too long";
    end;
  end
  else if int(core.len(args)) > 0 then
  begin
    used := core.substr_into(tail_buf, args, 0, int(core.len(args)));
    got := stdlib.trim_into(trimmed, tail_buf);
    if got > 0 and got <= PathCapacity then
      used := core.substr_into(path, trimmed, 0, got)
    else if got > PathCapacity then
      status_line := "path too long";
  end;
end;

procedure main(args: const string[1024]);
var
  screen_w: uint;
  screen_h: uint;
begin
  failed := false;
  step := 0;
  running := true;
  open_menu := -1;
  selected := -1;
  caret := 0;
  anchor := 0;
  top_line := 0;
  left_byte := 0;
  text := "";
  untitled := false;
  dialog_path := "";
  refresh_line_states();
  status_line := "";
  // The theme starts light on every launch. `apply_theme` fills the role
  // fields and the five syntax colours; the M9.1 light palette (keyword blue,
  // type dark red, string dark green, comment medium gray, number dark brown)
  // and the System 7.5 role colours are its light branch.
  dark := false;
  apply_theme();
  highlight := true;
  block_open := false;
  file_checked := uint(0);
  setup_highlight();
  setup_menu();
  parse_args(args);

  screen_w := syslib.screen_width();
  screen_h := syslib.screen_height();
  if screen_w = uint(0) then
    host_path()
  else if screen_w < uint(WindowX + ContentW + 40) or
          screen_h < uint(WindowY + ContentH + 60) then
    out.say("editor: screen too small\n")
  else
  begin
    st := syslib.window_open(WindowX, WindowY, ContentW, ContentH, "Editor", id);
    if st <> Ok then
      out.say("editor: no window\n")
    else
    begin
      st := syslib.window_content_rect(id, rect);
      if st <> Ok then
        out.say("editor: no content rect\n")
      else
      begin
        compute_layout();
        if mode = 1 then
          check_mode()
        else if mode = 2 then
          shot_mode()
        else
          interactive_mode();
      end;
    end;
  end;
end;
