Skip to content

Commit 712f353

Browse files
committed
Merge branch 'reserved_row_toolbar' into stage4-handoffs-integration
2 parents 91463a2 + 56d57f5 commit 712f353

2 files changed

Lines changed: 204 additions & 7 deletions

File tree

‎cmd2/command_toolbar.py‎

Lines changed: 58 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -144,10 +144,15 @@ class _ContextStdoutProxy(StdoutProxy):
144144
a row of its own, and it is continued from where it stopped when more output arrives.
145145
"""
146146

147-
def __init__(self) -> None:
147+
def __init__(self, toolbar_rows: Callable[[], int] = lambda: 1) -> None:
148+
"""Start printing above a toolbar.
149+
150+
:param toolbar_rows: returns how many rows the toolbar takes below the output
151+
"""
148152
# The line which output last left unfinished, exactly as written. Set before the
149153
# base class starts the thread which reads it.
150154
self._unfinished = ""
155+
self._toolbar_rows = toolbar_rows
151156
# The worker already combines queued writes. A batching sleep would also delay
152157
# close(), which runs at each command finalization boundary.
153158
super().__init__(raw=True, sleep_between_writes=0)
@@ -175,10 +180,12 @@ def write_and_flush() -> None:
175180
line = self._last_line(self._unfinished + text)
176181
if line:
177182
output.write_raw("\r\n")
178-
size = output.get_size()
179183
# A line whose start has scrolled off the screen can't be found again, so it
180-
# stays ended where it is.
181-
self._unfinished = line if self._width(line) <= size.rows * size.columns else ""
184+
# stays ended where it is. Its first row scrolls off once the screen has no
185+
# room for the whole line and the toolbar below it. A row is needed below the
186+
# line even with no toolbar, for the cursor which ended it.
187+
room = output.get_size().rows - max(1, self._toolbar_rows())
188+
self._unfinished = line if self._rows(line) <= room else ""
182189
output.flush()
183190

184191
if loop is None:
@@ -205,8 +212,34 @@ def _last_line(text: str) -> str:
205212

206213
def _rows(self, line: str) -> int:
207214
"""Return how many rows below its start the cursor was left after line was ended."""
208-
columns = max(1, self._output.get_size().columns)
209-
return max(1, -(-self._width(line) // columns))
215+
width = self._width(line)
216+
columns = self._wrap_columns()
217+
if self._wraps_at_once():
218+
# A line which has just filled a row has put the cursor on the next one.
219+
return width // columns + 1
220+
return max(1, -(-width // columns))
221+
222+
def _wraps_at_once(self) -> bool:
223+
"""Return whether the terminal moves to the next row as soon as a row is full.
224+
225+
A terminal which understands escape sequences waits for the next character. A legacy
226+
Windows console does not wait. It gets prompt-toolkit's Win32Output which, unlike its
227+
other Windows outputs, has no vt100 output to write escape sequences with.
228+
"""
229+
output = self._output
230+
return hasattr(output, "get_win32_screen_buffer_info") and not hasattr(output, "vt100_output")
231+
232+
def _wrap_columns(self) -> int:
233+
"""Return how many columns the terminal fits on a row before it wraps a line.
234+
235+
prompt-toolkit's Windows outputs report one column fewer than the console has, which
236+
keeps what prompt-toolkit draws out of the last column. Text written raw is wrapped by
237+
the console itself, at the width of its screen buffer.
238+
"""
239+
screen_buffer_info = getattr(self._output, "get_win32_screen_buffer_info", None)
240+
if screen_buffer_info is not None:
241+
return max(1, int(screen_buffer_info().dwSize.X))
242+
return max(1, self._output.get_size().columns)
210243

211244
@staticmethod
212245
def _width(line: str) -> int:
@@ -343,6 +376,13 @@ def __init__(self, cmd: "Cmd") -> None:
343376
and self.toolbar.content.style == "class:bottom-toolbar"
344377
):
345378
raise RuntimeError("Cannot locate PromptSession bottom toolbar")
379+
self._toolbar_window = self.toolbar.content
380+
# The rows the toolbar took when it was last drawn, to begin with by the main prompt.
381+
# Each run of the application forgets what it drew, and prompt-toolkit leaves the
382+
# toolbar out until the terminal has reported where its cursor is, which can be after
383+
# a command's first output. The toolbar is about to take these rows again.
384+
self._toolbar_height = 0
385+
self._note_toolbar_height()
346386
# In reserved mode the command display has nothing of its own to draw -- the toolbar
347387
# is painted independently into rows outside the scroll region. A full-height filler
348388
# window would make the renderer reserve the whole usable region and scroll to claim
@@ -401,6 +441,7 @@ def _suspend_to_background(suspend_group: bool = True) -> None:
401441

402442
def _display_started(self, app: Application[str]) -> None: # noqa: ARG002
403443
"""Report that the display is up and has finished its first frame."""
444+
self._note_toolbar_height()
404445
self._ready.set()
405446

406447
def _display_started_without_app(self) -> None:
@@ -422,6 +463,16 @@ def _reserved_bridge(self) -> Any:
422463
return None
423464
return reserved.bridge
424465

466+
def _note_toolbar_height(self) -> None:
467+
"""Remember how many rows the toolbar took, if the last frame drew it."""
468+
info = self._toolbar_window.render_info
469+
if info is not None:
470+
self._toolbar_height = info.window_height
471+
472+
def _toolbar_rows(self) -> int:
473+
"""Return how many rows the toolbar took when it was last drawn."""
474+
return self._toolbar_height
475+
425476
def start(self) -> None:
426477
"""Start rendering and protect terminal output."""
427478
stack = contextlib.ExitStack()
@@ -532,7 +583,7 @@ def _install_legacy_proxy(self) -> None:
532583
# and, on a console-less Windows runner, raise.
533584
token = _current_app_session.set(self._app_session) if self._app_session is not None else None
534585
try:
535-
proxy = _ContextStdoutProxy()
586+
proxy = _ContextStdoutProxy(self._toolbar_rows)
536587
finally:
537588
if token is not None:
538589
_current_app_session.reset(token)

‎tests/test_command_toolbar.py‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,16 @@ def cursor_up(self, amount: int) -> None:
404404
"z" * (24 * 80 + 1) + "\r\nEND\n",
405405
id="a line longer than the screen stays ended",
406406
),
407+
pytest.param(
408+
["z" * (23 * 80 + 1), "END\n"],
409+
"z" * (23 * 80 + 1) + "\r\nEND\n",
410+
id="a line which reaches the last row stays ended",
411+
),
412+
pytest.param(
413+
["z" * (23 * 80), "END\n"],
414+
"z" * (23 * 80) + "\r\n<up 23>" + "z" * (23 * 80) + "END\n",
415+
id="a line which stops above the last row is continued",
416+
),
407417
],
408418
)
409419
def test_stdout_proxy_continues_unfinished_lines(writes, expected) -> None:
@@ -421,6 +431,115 @@ def test_stdout_proxy_continues_unfinished_lines(writes, expected) -> None:
421431
assert stream.getvalue() == expected
422432

423433

434+
@pytest.mark.parametrize(
435+
("width", "expected"),
436+
[
437+
pytest.param(22 * 80, "\r\n<up 22>" + "z" * (22 * 80) + "END\n", id="continued while the toolbar fits below it"),
438+
pytest.param(22 * 80 + 1, "\r\nEND\n", id="stays ended once the toolbar would scroll its first row off"),
439+
],
440+
)
441+
def test_stdout_proxy_leaves_room_for_every_row_of_the_toolbar(width, expected) -> None:
442+
"""A toolbar of several rows scrolls the screen sooner than one row does."""
443+
stream = Terminal()
444+
with create_pipe_input() as pipe, create_app_session(input=pipe, output=CursorOutput(stream)):
445+
proxy = command_toolbar._ContextStdoutProxy(lambda: 2)
446+
try:
447+
proxy._write_and_flush(None, "z" * width)
448+
proxy._write_and_flush(None, "END\n")
449+
finally:
450+
proxy.close()
451+
452+
assert stream.getvalue() == "z" * width + expected
453+
454+
455+
def test_command_toolbar_tells_the_proxy_how_many_rows_it_takes(toolbar_app) -> None:
456+
app, _, _ = toolbar_app
457+
app.main_session.bottom_toolbar = "one\ntwo"
458+
# Nothing has been drawn yet.
459+
assert command_toolbar.CommandToolbar(app)._toolbar_rows() == 0
460+
with app._command_toolbar_context():
461+
assert app._command_toolbar._toolbar_rows() == 2
462+
assert app._command_toolbar._proxy._toolbar_rows() == 2
463+
464+
465+
class LegacyConsoleOutput(CursorOutput):
466+
"""Report a size the way prompt-toolkit's Windows outputs do, one column short of the console's.
467+
468+
Like prompt-toolkit's Win32Output, which a legacy console gets, it has no vt100 output.
469+
"""
470+
471+
def __init__(self, stream: Terminal) -> None:
472+
super().__init__(stream)
473+
self.size = Size(rows=24, columns=79)
474+
475+
def get_win32_screen_buffer_info(self) -> SimpleNamespace:
476+
return SimpleNamespace(dwSize=SimpleNamespace(X=80, Y=24))
477+
478+
479+
class WindowsConsoleOutput(LegacyConsoleOutput):
480+
"""A console which understands escape sequences, as prompt-toolkit's Windows10_Output writes to."""
481+
482+
def __init__(self, stream: Terminal) -> None:
483+
super().__init__(stream)
484+
self.vt100_output = self
485+
486+
487+
@pytest.mark.parametrize(
488+
("width", "rows"),
489+
[
490+
pytest.param(80, 1, id="a line as wide as the console"),
491+
pytest.param(159, 2, id="a line one column short of two rows"),
492+
pytest.param(160, 2, id="a line which fills two rows"),
493+
pytest.param(161, 3, id="a line which reaches a third row"),
494+
],
495+
)
496+
def test_stdout_proxy_counts_rows_by_the_width_a_windows_console_wraps_at(width, rows) -> None:
497+
"""A line which fills the last column of a Windows console is continued from its own row.
498+
499+
prompt-toolkit reports such a console as one column narrower than the width it wraps at.
500+
Counting rows by that size went up one row too many, and wrote over the line above.
501+
"""
502+
stream = Terminal()
503+
with create_pipe_input() as pipe, create_app_session(input=pipe, output=WindowsConsoleOutput(stream)):
504+
proxy = command_toolbar._ContextStdoutProxy()
505+
try:
506+
proxy._write_and_flush(None, "x" * width)
507+
proxy._write_and_flush(None, "END\n")
508+
finally:
509+
proxy.close()
510+
511+
assert stream.getvalue() == "x" * width + f"\r\n<up {rows}>" + "x" * width + "END\n"
512+
513+
514+
@pytest.mark.parametrize(
515+
("width", "rows"),
516+
[
517+
pytest.param(79, 1, id="a line one column short of the console's width"),
518+
pytest.param(80, 2, id="a line as wide as the console has already wrapped"),
519+
pytest.param(81, 2, id="a line which reaches a second row"),
520+
pytest.param(159, 2, id="a line one column short of two rows"),
521+
pytest.param(160, 3, id="a line which fills two rows has already wrapped"),
522+
],
523+
)
524+
def test_stdout_proxy_counts_the_row_a_legacy_windows_console_has_wrapped_to(width, rows) -> None:
525+
"""A legacy console moves to the next row as soon as a row is full, not at the next character.
526+
527+
Ending a line which exactly fills its rows therefore leaves the cursor a row lower than
528+
on a terminal which waits. Going up one row too few wrote the line again a row below
529+
itself, which showed its last row twice.
530+
"""
531+
stream = Terminal()
532+
with create_pipe_input() as pipe, create_app_session(input=pipe, output=LegacyConsoleOutput(stream)):
533+
proxy = command_toolbar._ContextStdoutProxy()
534+
try:
535+
proxy._write_and_flush(None, "x" * width)
536+
proxy._write_and_flush(None, "END\n")
537+
finally:
538+
proxy.close()
539+
540+
assert stream.getvalue() == "x" * width + f"\r\n<up {rows}>" + "x" * width + "END\n"
541+
542+
424543
@pytest.mark.parametrize("flushed", [True, False])
425544
def test_command_toolbar_keeps_an_unfinished_line(toolbar_app, flushed) -> None:
426545
"""An unfinished line is continued by later output, and ended when the toolbar stops."""
@@ -490,6 +609,33 @@ async def expire_cpr() -> None:
490609
assert "last words\n" in output.getvalue()
491610

492611

612+
def test_command_toolbar_remembers_the_rows_its_toolbar_took_before_it_is_drawn_again() -> None:
613+
"""A command's first output can arrive before the toolbar has been drawn for that command.
614+
615+
Each run of the application forgets what it drew, and prompt-toolkit leaves the toolbar
616+
out until the terminal has reported where its cursor is. Until then the toolbar counts
617+
for the rows the main prompt drew it with, which are the rows it is about to take again.
618+
"""
619+
app = Cmd(allow_cli_args=False)
620+
output = Terminal()
621+
app.stdout = output
622+
623+
with create_pipe_input() as pipe:
624+
app.main_session = PromptSession(
625+
input=pipe,
626+
output=CprOutput(output),
627+
bottom_toolbar="one\ntwo",
628+
refresh_interval=0.01,
629+
)
630+
window = app.main_session.layout.container.children[-1].content
631+
# What the main prompt leaves behind after drawing a toolbar of two rows.
632+
window.render_info = SimpleNamespace(window_height=2)
633+
with app._command_toolbar_context():
634+
assert window.render_info is None
635+
assert app._command_toolbar._toolbar_rows() == 2
636+
assert app._command_toolbar._proxy._toolbar_rows() == 2
637+
638+
493639
def test_command_toolbar_suspension_waits_for_in_flight_writes(toolbar_app, monkeypatch) -> None:
494640
app, _, output = toolbar_app
495641
writing = threading.Event()

0 commit comments

Comments
 (0)