Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ jobs:
timeout-minutes: 5
run: ./.lake/build/bin/gen_site --out "$RUNNER_TEMP/docs-site"

- name: TUI widget kit (layout, combinators, elements, app loop, raw-mode ANSI, wide chars, input decoding, mouse, repaint; 67 LSpec assertions)
- name: TUI widget kit (layout, combinators, elements, app loop, raw-mode ANSI, wide chars, input decoding, mouse, repaint, SIGWINCH resizes; 73 LSpec assertions)
run: ./.lake/build/bin/tui_spec
- name: "WebSocket server (RFC 6455 codec + handshake, live echo server: fragments, ping/pong, close codes, concurrency; 29 LSpec assertions)"
run: ./.lake/build/bin/websocket_spec
Expand Down
89 changes: 75 additions & 14 deletions LeanTea/Tui/App.lean
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import LeanTea.Tui.Core
import LeanTea.Tui.Combinator
import LeanTea.Tui.Input
import Std.Async.Signal

/-! # LeanTea.Tui.App — the IO side: terminal setup, repaint, input loop

Expand All @@ -25,13 +26,16 @@ becomes a running app via `App.run`. The app:
pointer leaves it.
- A returned `msg` goes through `update`.
4. Wakes up every 100 ms without input to fire `onTick` when
`tickMs` is set, and re-measures the terminal every 500 ms (one
`stty size`, ~15 ms) to follow window resizes.
`tickMs` is set. The terminal is measured once at start (one
`stty size`, 6–15 ms) and again only after a `SIGWINCH`
(`ResizeWatch`), so following window resizes costs nothing while
the size stays put.
5. Repeats until `App.quitWhen state` is true or Ctrl+C.

Everything goes through `stty` and stdin/stdout — no C — so an app
also runs under `lake env lean --run`. Terminal teardown lives in a
`try ... finally`, so a crash leaves the user's shell intact.
Everything goes through `stty`, `Std.Async.Signal` and stdin/stdout —
no C — so an app also runs under `lake env lean --run`. Terminal
teardown lives in a `try ... finally`, so a crash leaves the user's
shell intact.
-/

namespace LeanTea.Tui
Expand Down Expand Up @@ -237,7 +241,11 @@ def App.handle (app : App s m) (focusOrder : List String) (width height : Nat)
let path := w.hitPath width height e.row e.col
apply st (w.routeMouse width height path e).msg?

/-! ## Raw terminal mode (POSIX, via stty) -/
/-! ## Raw terminal mode (POSIX, via stty)

Lean has no API for terminal attributes (termios), so raw mode still
spawns `stty`: twice per run, at start and at exit. An API for it is
requested upstream in leanprover/lean4#16868. -/

/-- Run an stty command, tolerating failure (e.g. no controlling TTY): the
app then simply runs without raw mode instead of crashing. -/
Expand Down Expand Up @@ -267,15 +275,59 @@ def terminalSize : IO (Option (Nat × Nat)) := do
| _ => return none
catch _ => return none

/-! ## Following window resizes -/

/-- Notes `SIGWINCH`, which the terminal sends when its window changes
size, so the loop re-measures only then instead of spawning
`stty size` on a timer. The signal is handled by the runtime's
event loop; the handler only sets `flag`, which the loop reads. -/
structure ResizeWatch where
flag : IO.Ref Bool
/-- `none` when the signal handler could not be set up; the loop
then falls back to re-measuring every 500 ms. -/
waiter : Option Std.Async.Signal.Waiter

/-- Wait for the next signal, set `flag`, and wait again. Each round
registers a callback on the signal's task; no thread blocks. -/
private partial def ResizeWatch.arm (w : Std.Async.Signal.Waiter) (flag : IO.Ref Bool) :
IO Unit := do
let next ← w.wait
discard <| next.mapIO fun _ => do
flag.set true
ResizeWatch.arm w flag

/-- Start listening for `SIGWINCH`. Never fails: without a handler the
watch has `waiter := none`. -/
def ResizeWatch.start : IO ResizeWatch := do
let flag ← IO.mkRef false
try
let w ← Std.Async.Signal.Waiter.mk .sigwinch (repeating := true)
ResizeWatch.arm w flag
return { flag, waiter := some w }
catch _ =>
return { flag, waiter := none }

/-- Whether a resize arrived since the last call; clears the flag, so a
burst of signals is one re-measure. -/
def ResizeWatch.take (r : ResizeWatch) : IO Bool :=
r.flag.modifyGet fun b => (b, false)

/-- Stop listening. -/
def ResizeWatch.stop (r : ResizeWatch) : IO Unit := do
if let some w := r.waiter then w.stop

/-! ## Main loop -/

partial def App.runWith (app : App s m) (opts : RunOpts) : IO Unit := do
let stdout ← IO.getStdout
let stdin ← IO.getStdin
let fixedSize := opts.width > 0 && opts.height > 0
let measure : IO (Nat × Nat) := do
if opts.width > 0 && opts.height > 0 then return (opts.width, opts.height)
if fixedSize then return (opts.width, opts.height)
let (tw, th) := (← terminalSize).getD (100, 30)
return (if opts.width > 0 then opts.width else tw, if opts.height > 0 then opts.height else th)
-- listen before the first measure, so a resize in between is not missed
let resize? ← if fixedSize then pure none else some <$> ResizeWatch.start
stdout.putStr (altScreenOn ++ hideCursor ++ clearScreen ++ (if opts.mouse then mouseOn else ""))
stdout.flush
sttyRawTimedOn
Expand Down Expand Up @@ -311,21 +363,30 @@ partial def App.runWith (app : App s m) (opts : RunOpts) : IO Unit := do
for ev in evs do
st := app.handle opts.focusOrder width height st ev
dirty := true
let mut remeasure := false
if let some r := resize? then
if r.waiter.isSome then
remeasure ← r.take
if b.size == 0 then
let now ← IO.monoMsNow
if let some ms := app.tickMs then
if now - lastTick ≥ ms then
st := { st with state := ← app.onTick st.state }
lastTick := now
dirty := true
if now - lastMeasure ≥ 500 then
lastMeasure := now
let (w', h') ← measure
if w' != width || h' != height then
width := w'
height := h'
dirty := true
-- no signal handler: fall back to polling the size
if let some r := resize? then
if r.waiter.isNone && now - lastMeasure ≥ 500 then
lastMeasure := now
remeasure := true
if remeasure then
let (w', h') ← measure
if w' != width || h' != height then
width := w'
height := h'
dirty := true
finally
if let some r := resize? then r.stop
sttyRawOff
stdout.putStr ((if opts.mouse then mouseOff else "") ++ showCursor ++ altScreenOff ++ reset)
stdout.flush
Expand Down
45 changes: 44 additions & 1 deletion examples/Tests/TuiSpec.lean
Original file line number Diff line number Diff line change
Expand Up @@ -519,6 +519,48 @@ def run : IO LSpec := do

end DiffGroup

/-! ## Group 10 — Following resizes (`ResizeWatch`, SIGWINCH) -/

namespace ResizeGroup

/-- Poll `r.take` every 10 ms for up to `ms` milliseconds. -/
partial def takeWithin (r : ResizeWatch) (ms : Nat) : IO Bool := do
if ← r.take then return true
if ms == 0 then return false
IO.sleep 10
takeWithin r (ms - min ms 10)

/-- Send SIGWINCH to this process, as a terminal does on a resize. -/
def sendWinch : IO Unit := do
let pid ← IO.Process.getPID
let _ ← IO.Process.output { cmd := "kill", args := #["-WINCH", toString pid] }

def run : IO LSpec := do
let r ← ResizeWatch.start
let idle ← r.take
sendWinch
let first ← takeWithin r 2000
let cleared ← r.take
-- the handler is re-armed after each signal
sendWinch
let second ← takeWithin r 2000
sendWinch
sendWinch
IO.sleep 300
let burst ← r.take
let afterBurst ← r.take
r.stop
return group "Tui — following resizes" [
it "the SIGWINCH handler is set up" r.waiter.isSome,
it "no resize reported before a signal" (!idle),
it "a SIGWINCH is reported" first,
it "taking it clears the flag" (!cleared),
it "a second SIGWINCH is reported too" second,
it "a burst of signals is one re-measure" (burst && !afterBurst)
]

end ResizeGroup

/-! ## main -/

def main : IO Unit := do
Expand All @@ -531,6 +573,7 @@ def main : IO Unit := do
let i ← InputGroup.run
let mo ← MouseGroup.run
let d ← DiffGroup.run
let tree := group "LeanTea.Tui widget kit" [b, c, e, a, r, wd, i, mo, d]
let rs ← ResizeGroup.run
let tree := group "LeanTea.Tui widget kit" [b, c, e, a, r, wd, i, mo, d, rs]
let code ← lspecIO tree
if code != 0 then IO.Process.exit code.toUInt8
Loading