Skip to content

Commit 56d57f5

Browse files
committed
Merge branch 'consolidated_toolbar' into reserved_row_toolbar
2 parents 32e6cec + 2f4b5dd commit 56d57f5

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:
@@ -341,6 +374,13 @@ def __init__(self, cmd: "Cmd") -> None:
341374
and self.toolbar.content.style == "class:bottom-toolbar"
342375
):
343376
raise RuntimeError("Cannot locate PromptSession bottom toolbar")
377+
self._toolbar_window = self.toolbar.content
378+
# The rows the toolbar took when it was last drawn, to begin with by the main prompt.
379+
# Each run of the application forgets what it drew, and prompt-toolkit leaves the
380+
# toolbar out until the terminal has reported where its cursor is, which can be after
381+
# a command's first output. The toolbar is about to take these rows again.
382+
self._toolbar_height = 0
383+
self._note_toolbar_height()
344384
# In reserved mode the command display has nothing of its own to draw -- the toolbar
345385
# is painted independently into rows outside the scroll region. A full-height filler
346386
# window would make the renderer reserve the whole usable region and scroll to claim
@@ -399,6 +439,7 @@ def _suspend_to_background(suspend_group: bool = True) -> None:
399439

400440
def _display_started(self, app: Application[str]) -> None: # noqa: ARG002
401441
"""Report that the display is up and has finished its first frame."""
442+
self._note_toolbar_height()
402443
self._ready.set()
403444

404445
def _display_started_without_app(self) -> None:
@@ -420,6 +461,16 @@ def _reserved_bridge(self) -> Any:
420461
return None
421462
return reserved.bridge
422463

464+
def _note_toolbar_height(self) -> None:
465+
"""Remember how many rows the toolbar took, if the last frame drew it."""
466+
info = self._toolbar_window.render_info
467+
if info is not None:
468+
self._toolbar_height = info.window_height
469+
470+
def _toolbar_rows(self) -> int:
471+
"""Return how many rows the toolbar took when it was last drawn."""
472+
return self._toolbar_height
473+
423474
def start(self) -> None:
424475
"""Start rendering and protect terminal output."""
425476
stack = contextlib.ExitStack()
@@ -530,7 +581,7 @@ def _install_legacy_proxy(self) -> None:
530581
# and, on a console-less Windows runner, raise.
531582
token = _current_app_session.set(self._app_session) if self._app_session is not None else None
532583
try:
533-
proxy = _ContextStdoutProxy()
584+
proxy = _ContextStdoutProxy(self._toolbar_rows)
534585
finally:
535586
if token is not None:
536587
_current_app_session.reset(token)

‎tests/test_command_toolbar.py‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,16 @@ def cursor_up(self, amount: int) -> None:
385385
"z" * (24 * 80 + 1) + "\r\nEND\n",
386386
id="a line longer than the screen stays ended",
387387
),
388+
pytest.param(
389+
["z" * (23 * 80 + 1), "END\n"],
390+
"z" * (23 * 80 + 1) + "\r\nEND\n",
391+
id="a line which reaches the last row stays ended",
392+
),
393+
pytest.param(
394+
["z" * (23 * 80), "END\n"],
395+
"z" * (23 * 80) + "\r\n<up 23>" + "z" * (23 * 80) + "END\n",
396+
id="a line which stops above the last row is continued",
397+
),
388398
],
389399
)
390400
def test_stdout_proxy_continues_unfinished_lines(writes, expected) -> None:
@@ -402,6 +412,115 @@ def test_stdout_proxy_continues_unfinished_lines(writes, expected) -> None:
402412
assert stream.getvalue() == expected
403413

404414

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

473592

593+
def test_command_toolbar_remembers_the_rows_its_toolbar_took_before_it_is_drawn_again() -> None:
594+
"""A command's first output can arrive before the toolbar has been drawn for that command.
595+
596+
Each run of the application forgets what it drew, and prompt-toolkit leaves the toolbar
597+
out until the terminal has reported where its cursor is. Until then the toolbar counts
598+
for the rows the main prompt drew it with, which are the rows it is about to take again.
599+
"""
600+
app = Cmd(allow_cli_args=False)
601+
output = Terminal()
602+
app.stdout = output
603+
604+
with create_pipe_input() as pipe:
605+
app.main_session = PromptSession(
606+
input=pipe,
607+
output=CprOutput(output),
608+
bottom_toolbar="one\ntwo",
609+
refresh_interval=0.01,
610+
)
611+
window = app.main_session.layout.container.children[-1].content
612+
# What the main prompt leaves behind after drawing a toolbar of two rows.
613+
window.render_info = SimpleNamespace(window_height=2)
614+
with app._command_toolbar_context():
615+
assert window.render_info is None
616+
assert app._command_toolbar._toolbar_rows() == 2
617+
assert app._command_toolbar._proxy._toolbar_rows() == 2
618+
619+
474620
def test_command_toolbar_suspension_waits_for_in_flight_writes(toolbar_app, monkeypatch) -> None:
475621
app, _, output = toolbar_app
476622
writing = threading.Event()

0 commit comments

Comments
 (0)