Redraw cleanly when the window is resized
Resizing the terminal during a scan left the screen full of wreckage: box corners in the middle of a line, borders twice the width of the window, a "receiver" header printed eight times down the left edge. Four separate defects, which is why it looked so bad. Live rendering works by moving the cursor back over the frame it drew last time and overwriting it. That is only correct while the frame is still where it was put, and none of these programs noticed when it was not. 1. Nothing detected a resize. Both the scan display and saunterbrowse now compare the console size on every frame and clear the screen when it changes -- polled rather than handled as a signal, because the display is redrawn several times a second anyway and a signal handler that runs in the middle of a write has to be right about far more than this does. Anything printed before the scan started scrolls away at that point, which the manual now says. 2. The layout's model of its own height was wrong, in two places that cancelled. The sweep panel was counted as one line shorter than it is, the hit list as one line taller. The sum came out right whenever both were drawn and wrong on a terminal too short for the hit list -- where the frame then overflowed by one line on every refresh and the top of it marched down the screen. That is what the eight headers were. Each panel height is a named constant now, and a test checks every one of them against what is actually rendered. 3. Lines inside the panels could wrap. A band name, a long status line or a decoded message made a panel a row taller than the arithmetic allowed for, with the same result. Every one is drawn on a single line and ellipsised now. The receiver panel drops its optional parts instead, keeping the tuner and the flags: "SIMULATED" disappearing off the end of a narrow line is how somebody comes to believe they are listening to the air. 4. saunterbrowse's full-screen views did not fill the screen. Nothing erases the alternate screen between frames -- the cursor is sent home and the new frame written over the old one -- so pressing t or ? on a tall window left most of the recording list visible underneath. Both are wrapped in a layout now, which fills the terminal exactly. The layout also gives up the receiver panel on a very short terminal, which it previously had no way to do: on eight rows the smallest frame it could describe was nine lines. Testing this by rendering to a wide Console and reading the text back cannot work -- whether the cursor lands where it should is a property of the terminal, not of the renderable. So tests/terminal.py runs the program in a pty, resizes the window underneath it the way a window manager does, and feeds what it writes to a terminal emulator whose screen is then read. Every fix above has a test that fails without it, checked by reverting each one in turn. pyte is a dev dependency and those tests skip without it; the arithmetic ones need nothing. Also: t now opens the reader for a capture that carries decoded data rather than speech, because the decoded panel already told the reader to press it. 869 -> 949 tests.
This commit is contained in:
parent
68b05a031c
commit
d6ae6d0c22
12 changed files with 625 additions and 46 deletions
116
tests/terminal.py
Normal file
116
tests/terminal.py
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
"""A real terminal, for tests that have to see what a resize leaves behind.
|
||||
|
||||
Rendering to a wide `Console` and reading the text back cannot show this class
|
||||
of bug at all. Live rendering works by moving the cursor over the frame it
|
||||
drew last time and overwriting it, and whether that lands where it should is a
|
||||
property of the terminal, not of the renderable. So the program is run in a
|
||||
pty, the window is resized underneath it the way a window manager would, and
|
||||
the bytes it writes are fed to a terminal emulator whose screen is then read.
|
||||
"""
|
||||
import codecs
|
||||
import fcntl
|
||||
import os
|
||||
import pty
|
||||
import select
|
||||
import signal
|
||||
import struct
|
||||
import termios
|
||||
import time
|
||||
|
||||
|
||||
class Terminal:
|
||||
"""One program running in a pty, with a screen that can be read back."""
|
||||
|
||||
def __init__(self, argv, cols=100, rows=30, env=None):
|
||||
import pyte
|
||||
|
||||
self.cols, self.rows = cols, rows
|
||||
self.screen = pyte.Screen(cols, rows)
|
||||
self.stream = pyte.Stream(self.screen)
|
||||
# Incremental, because a read can land in the middle of a multi-byte
|
||||
# character: decoding each chunk on its own turns the second half of a
|
||||
# box-drawing character into a replacement character, which then looks
|
||||
# exactly like the debris these tests are here to find.
|
||||
self._decoder = codecs.getincrementaldecoder("utf8")("replace")
|
||||
self.pid, self.fd = pty.fork()
|
||||
if self.pid == 0: # pragma: no cover -- the child
|
||||
child = dict(os.environ, TERM="xterm-256color",
|
||||
PYTHONUNBUFFERED="1")
|
||||
# rich reads COLUMNS and LINES in preference to asking the
|
||||
# terminal, so leaving them set would make every resize invisible
|
||||
# and every one of these tests pass for the wrong reason.
|
||||
child.pop("COLUMNS", None)
|
||||
child.pop("LINES", None)
|
||||
os.execvpe(argv[0], argv, child)
|
||||
self._set_size(cols, rows)
|
||||
|
||||
def _set_size(self, cols: int, rows: int) -> None:
|
||||
fcntl.ioctl(self.fd, termios.TIOCSWINSZ,
|
||||
struct.pack("HHHH", rows, cols, 0, 0))
|
||||
|
||||
def resize(self, cols: int, rows: int) -> None:
|
||||
"""Resize the window, exactly as a window manager does."""
|
||||
self.cols, self.rows = cols, rows
|
||||
self._set_size(cols, rows)
|
||||
os.kill(self.pid, signal.SIGWINCH)
|
||||
self.screen.resize(rows, cols)
|
||||
|
||||
def pump(self, seconds: float = 1.0) -> None:
|
||||
"""Read whatever the program writes for a while."""
|
||||
end = time.time() + seconds
|
||||
while time.time() < end:
|
||||
ready, _, _ = select.select([self.fd], [], [], 0.05)
|
||||
if not ready:
|
||||
continue
|
||||
try:
|
||||
data = os.read(self.fd, 65536)
|
||||
except OSError:
|
||||
break
|
||||
if not data:
|
||||
break
|
||||
self.stream.feed(self._decoder.decode(data))
|
||||
|
||||
def send(self, text: str) -> None:
|
||||
os.write(self.fd, text.encode())
|
||||
|
||||
def display(self) -> list[str]:
|
||||
return [line.rstrip() for line in self.screen.display]
|
||||
|
||||
def text(self) -> str:
|
||||
return "\n".join(self.display())
|
||||
|
||||
def close(self) -> None:
|
||||
for action in (lambda: os.kill(self.pid, signal.SIGKILL),
|
||||
lambda: os.close(self.fd),
|
||||
lambda: os.waitpid(self.pid, 0)):
|
||||
try:
|
||||
action()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
self.close()
|
||||
return False
|
||||
|
||||
|
||||
def stray_rows(lines: list[str], width: int) -> list[str]:
|
||||
"""Rows that belong to a frame drawn for some other window size.
|
||||
|
||||
A panel drawn at the current width starts and ends at the edges of the
|
||||
screen. A row carrying box-drawing characters that does neither is a
|
||||
piece of a frame drawn when the window was a different shape -- the debris
|
||||
a resize leaves when nothing erases it.
|
||||
"""
|
||||
out = []
|
||||
for line in lines:
|
||||
stripped = line.strip()
|
||||
if not stripped or not any(c in line for c in "╭╮╰╯│─"):
|
||||
continue
|
||||
starts = stripped[0] in "╭╰│─"
|
||||
ends = stripped[-1] in "╮╯│─"
|
||||
if not (starts and ends) or len(line) > width:
|
||||
out.append(line)
|
||||
return out
|
||||
|
|
@ -273,7 +273,19 @@ def test_the_reader_refuses_when_there_is_nothing_to_read(library):
|
|||
b.index = [i for i, c in enumerate(b.view) if c.mode == "fsk"][0]
|
||||
b.handle("t")
|
||||
assert not b.reading
|
||||
assert "no transcript" in b.message
|
||||
assert "nothing to read" in b.message
|
||||
|
||||
|
||||
def test_the_reader_opens_on_a_decoded_capture_too(tmp_path):
|
||||
"""The decoded panel says "press t to read it all", so t has to work."""
|
||||
make_capture(tmp_path, 929.6125, "2026-08-22_11_00_00", "fsk", 4.0,
|
||||
meta={"category": "digital", "data_protocol": "POCSAG 1200",
|
||||
"data_messages": ["[1234568D] ENGINE 4 RESPOND"]})
|
||||
b = browser(tmp_path)
|
||||
assert not b.current.transcript and b.current.decoded
|
||||
b.handle("t")
|
||||
assert b.reading, b.message
|
||||
assert "ENGINE 4 RESPOND" in frame(b)
|
||||
|
||||
|
||||
# -- the frame ---------------------------------------------------------------
|
||||
|
|
|
|||
269
tests/test_resize.py
Normal file
269
tests/test_resize.py
Normal file
|
|
@ -0,0 +1,269 @@
|
|||
"""Resizing the window, and the debris it used to leave behind.
|
||||
|
||||
Live rendering moves the cursor back over the frame it drew last time and
|
||||
overwrites it. That is only correct while the frame is still where it was
|
||||
put, and resizing the window reflows everything on the screen, so what is left
|
||||
is half of the old frame in pieces -- box corners in the middle of a line, a
|
||||
border twice the width of the window, a header printed eight times.
|
||||
|
||||
Two kinds of test here. The first are arithmetic: every frame has to be
|
||||
exactly as tall as the terminal, or never taller, because that is the property
|
||||
the overwriting depends on and it can be checked without a terminal at all.
|
||||
The second run the programs in a real pty and resize them.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
from rich.console import Console
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
from terminal import Terminal, stray_rows # noqa: E402
|
||||
from bandsaunter.browse import Browser, Player # noqa: E402
|
||||
from bandsaunter.config import ScanConfig # noqa: E402
|
||||
from bandsaunter.ranges import parse_range_list # noqa: E402
|
||||
from bandsaunter.recorder import HitRecord # noqa: E402
|
||||
from bandsaunter.scanner import Scanner # noqa: E402
|
||||
from bandsaunter.simulator import SimulatedDevice # noqa: E402
|
||||
from bandsaunter.ui import ScanDisplay # noqa: E402
|
||||
|
||||
pyte = pytest.importorskip("pyte", reason="terminal emulator not installed")
|
||||
|
||||
SIZES = [(120, 40), (100, 30), (100, 24), (90, 20), (80, 24), (70, 18),
|
||||
(64, 16), (60, 12), (50, 10), (40, 8), (200, 60)]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The arithmetic the overwriting depends on
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _scan_display(width: int, height: int, busy: bool = True) -> ScanDisplay:
|
||||
console = Console(width=width, height=height, force_terminal=True,
|
||||
file=open(os.devnull, "w"))
|
||||
cfg = ScanConfig(ranges=parse_range_list("144M-148M"),
|
||||
output_dir=tempfile.mkdtemp())
|
||||
scanner = Scanner(cfg, device=SimulatedDevice().open())
|
||||
scanner.prepare()
|
||||
display = ScanDisplay(scanner, console=console)
|
||||
display.attach()
|
||||
if busy:
|
||||
step = scanner.plan[3]
|
||||
display.on_step(3, 6, step, np.full(1024, -70.0),
|
||||
np.linspace(step.low, step.high, 1024))
|
||||
display._rec.active = True
|
||||
display._rec.frequency = 146.520555e6
|
||||
display._rec.mode = "nfm"
|
||||
display._rec.present = True
|
||||
display._rec.snr = 50.4
|
||||
display._rec.elapsed = 3.0
|
||||
display.on_status("decoded 146.52 MHz: a status line long enough to "
|
||||
"run off the end of a narrow window")
|
||||
for i in range(8):
|
||||
hit = HitRecord(frequency=146e6 + i * 1e5, started_at=0,
|
||||
duration=5.0, snr_db=20.0,
|
||||
classification="Narrowband FM voice "
|
||||
"(CTCSS 100.0 Hz)")
|
||||
display.hits.appendleft(hit)
|
||||
return display
|
||||
|
||||
|
||||
def _rendered_height(renderable, width: int, height: int) -> int:
|
||||
probe = Console(width=width, height=height, force_terminal=True,
|
||||
record=True, file=open(os.devnull, "w"))
|
||||
probe.print(renderable)
|
||||
return len(probe.export_text().rstrip("\n").split("\n"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("width,height", SIZES)
|
||||
@pytest.mark.parametrize("busy", [False, True])
|
||||
def test_the_scan_frame_never_outgrows_the_terminal(width, height, busy):
|
||||
"""A frame taller than the window cannot be redrawn where it was drawn."""
|
||||
display = _scan_display(width, height, busy)
|
||||
drawn = _rendered_height(display.render(), width, height)
|
||||
assert drawn <= height, f"{width}x{height}: frame is {drawn} lines"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("width,height", SIZES)
|
||||
def test_the_frame_is_exactly_as_tall_as_the_layout_says(width, height):
|
||||
"""The number the whole thing depends on, checked against reality.
|
||||
|
||||
The layout counts each panel as a fixed number of lines when it decides
|
||||
what fits, and rich moves the cursor back over exactly that many. A model
|
||||
one line out overflows by one line on every refresh, and the top of the
|
||||
frame marches down the screen -- which is what a column of "receiver"
|
||||
headers was. Two ways to be wrong: a panel counted at the wrong height,
|
||||
or a long band name or status message wrapping inside one.
|
||||
"""
|
||||
display = _scan_display(width, height)
|
||||
probe = Console(width=width, height=400, force_terminal=True, record=True,
|
||||
file=open(os.devnull, "w"))
|
||||
probe.print(display.render())
|
||||
lines = probe.export_text().rstrip("\n").split("\n")
|
||||
assert len(lines) == display._layout_height(), \
|
||||
"the frame is not the height the layout budgeted for"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("width,height", SIZES)
|
||||
@pytest.mark.parametrize("view", ["list", "reader", "help"])
|
||||
def test_every_browser_screen_fills_the_terminal_exactly(width, height, view,
|
||||
tmp_path):
|
||||
"""Nothing erases the alternate screen between frames.
|
||||
|
||||
The cursor is sent home and the new frame written over the old one, so a
|
||||
frame shorter than the screen leaves the tail of the last one visible
|
||||
underneath it.
|
||||
"""
|
||||
console = Console(width=width, height=height, force_terminal=True,
|
||||
file=open(os.devnull, "w"))
|
||||
browser = Browser(tmp_path, console=console, player=Player([]))
|
||||
browser.reading = view == "reader"
|
||||
browser.show_help = view == "help"
|
||||
drawn = _rendered_height(browser.render(), width, height)
|
||||
assert drawn == height, f"{width}x{height} {view}: {drawn} lines"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Noticing the change
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class _Resizable(Console):
|
||||
"""A console whose size can be changed the way a window can."""
|
||||
|
||||
def __init__(self, width, height):
|
||||
super().__init__(width=width, height=height, force_terminal=True,
|
||||
file=open(os.devnull, "w"))
|
||||
|
||||
def become(self, width, height):
|
||||
self.width = width
|
||||
self.height = height
|
||||
|
||||
|
||||
def test_a_size_change_is_noticed_once_and_only_once():
|
||||
console = _Resizable(100, 30)
|
||||
display = _scan_display(100, 30, busy=False)
|
||||
display.console = console
|
||||
display._size = console.size
|
||||
assert not display.resized(), "reported a resize that never happened"
|
||||
console.become(70, 20)
|
||||
assert display.resized(), "did not notice the window changing"
|
||||
assert not display.resized(), "reported the same resize twice"
|
||||
console.become(70, 40)
|
||||
assert display.resized(), "a change in height is a change"
|
||||
|
||||
|
||||
def test_the_browser_notices_a_size_change_too(tmp_path):
|
||||
console = _Resizable(100, 30)
|
||||
browser = Browser(tmp_path, console=console, player=Player([]))
|
||||
assert not browser.resized()
|
||||
console.become(64, 18)
|
||||
assert browser.resized()
|
||||
assert not browser.resized()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# In a real terminal
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _scan_argv(directory: Path) -> list[str]:
|
||||
return [sys.executable, "-m", "bandsaunter", "scan", "--simulate",
|
||||
"--no-config", "-r", "144M-148M", "-o", str(directory),
|
||||
"--duration", "90"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("after", [(70, 20), (120, 40), (60, 12), (100, 30)])
|
||||
def test_resizing_a_running_scan_leaves_nothing_behind(tmp_path, after):
|
||||
cols, rows = after
|
||||
with Terminal(_scan_argv(tmp_path), cols=100, rows=30) as term:
|
||||
term.pump(4.0)
|
||||
term.resize(cols, rows)
|
||||
term.pump(3.0)
|
||||
lines = term.display()
|
||||
assert any("sweep" in line for line in lines), \
|
||||
"the display did not redraw at all"
|
||||
stray = stray_rows(lines, cols)
|
||||
assert not stray, "left behind:\n" + "\n".join(stray)
|
||||
|
||||
|
||||
def test_a_scan_survives_being_resized_over_and_over(tmp_path):
|
||||
"""A window being dragged sends a great many of these in a row."""
|
||||
with Terminal(_scan_argv(tmp_path), cols=110, rows=34) as term:
|
||||
term.pump(3.0)
|
||||
for cols, rows in ((90, 28), (70, 20), (64, 16), (100, 30),
|
||||
(120, 40), (80, 24)):
|
||||
term.resize(cols, rows)
|
||||
term.pump(0.6)
|
||||
term.pump(2.0)
|
||||
lines = term.display()
|
||||
stray = stray_rows(lines, term.cols)
|
||||
assert not stray, "left behind:\n" + "\n".join(stray)
|
||||
|
||||
|
||||
def test_the_header_is_never_drawn_more_than_once(tmp_path):
|
||||
"""It used to march down the screen, one copy per refresh."""
|
||||
with Terminal(_scan_argv(tmp_path), cols=100, rows=30) as term:
|
||||
term.pump(4.0)
|
||||
term.resize(78, 22)
|
||||
term.pump(3.0)
|
||||
headers = [ln for ln in term.display() if " receiver " in ln]
|
||||
assert len(headers) <= 1, f"{len(headers)} copies of the header"
|
||||
|
||||
|
||||
def _browse_argv(directory: Path) -> list[str]:
|
||||
return [sys.executable, "-m", "bandsaunter.browse", str(directory)]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def library(tmp_path):
|
||||
"""A directory with something in it for the browser to show."""
|
||||
import json
|
||||
import wave
|
||||
stem = "0146.520000MHz--2026-08-22_10_00_00-nfm"
|
||||
with wave.open(str(tmp_path / f"{stem}.wav"), "wb") as w:
|
||||
w.setnchannels(1)
|
||||
w.setsampwidth(2)
|
||||
w.setframerate(16000)
|
||||
w.writeframes(b"\0\0" * 16000)
|
||||
(tmp_path / f"{stem}_transcription.txt").write_text(
|
||||
"Net control, this is W1AW. " * 30)
|
||||
(tmp_path / f"{stem}.json").write_text(json.dumps({"hit": {
|
||||
"frequency": 146.52e6, "started_at": 1755856800.0,
|
||||
"category": "voice", "classification": "Narrowband FM voice",
|
||||
"confidence": 0.88, "mode": "nfm", "duration": 1.0}}))
|
||||
return tmp_path
|
||||
|
||||
|
||||
@pytest.mark.parametrize("after", [(70, 20), (130, 44), (60, 10)])
|
||||
def test_resizing_the_browser_leaves_nothing_behind(library, after):
|
||||
cols, rows = after
|
||||
with Terminal(_browse_argv(library), cols=100, rows=30) as term:
|
||||
term.pump(2.5)
|
||||
term.resize(cols, rows)
|
||||
term.pump(2.0)
|
||||
lines = term.display()
|
||||
stray = stray_rows(lines, cols)
|
||||
assert not stray, "left behind:\n" + "\n".join(stray)
|
||||
|
||||
|
||||
def test_the_reader_covers_the_list_it_was_opened_from(library):
|
||||
"""Opening a full-screen view must not leave the list showing under it."""
|
||||
with Terminal(_browse_argv(library), cols=100, rows=30) as term:
|
||||
term.pump(2.5)
|
||||
term.send("t")
|
||||
term.pump(1.5)
|
||||
text = term.text()
|
||||
assert "transcript" in text
|
||||
assert "recordings in" not in text, \
|
||||
"the list is still visible under the reader"
|
||||
|
||||
|
||||
def test_the_help_screen_covers_the_list_too(library):
|
||||
with Terminal(_browse_argv(library), cols=100, rows=30) as term:
|
||||
term.pump(2.5)
|
||||
term.send("?")
|
||||
term.pump(1.5)
|
||||
text = term.text()
|
||||
assert "move through the recordings" in text
|
||||
assert "recordings in" not in text
|
||||
Loading…
Add table
Add a link
Reference in a new issue