From 98744236d5ed1407852fe713f56409166b5350b1 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:35:49 -0500 Subject: [PATCH 1/3] Add an example of a bottom toolbar drawn by Textual which stays while commands run cmd2's bottom toolbar is part of the prompt, so it is only on the screen while the prompt is. examples/textual_tty_toolbar.py shows one way to have a toolbar which stays, and keeps refreshing, while a command runs: a small Textual application owns the terminal and shows the cmd2 application in a textual-tty terminal pane with the toolbar in a widget docked below it. The cmd2 application gives prompt-toolkit no toolbar to draw, and a thread in it sends what get_bottom_toolbar() returns to the Textual application over a Unix socket. It is a sibling of textual_tty_embed.py and needs the same things: a POSIX system and textual-tty, which is already in the development environment. Nothing in the cmd2 package changes. The Embedding in Textual page of the documentation gains a section on it, which also says what the approach costs: no scrollback, no Windows, no Ctrl-Z, and the mouse belongs to Textual. --- CHANGELOG.md | 6 + docs/examples/embedding_in_textual.md | 73 ++++- docs/features/prompt.md | 5 + examples/README.md | 4 + examples/textual_tty_embed.py | 2 + examples/textual_tty_toolbar.py | 400 ++++++++++++++++++++++++++ 6 files changed, 487 insertions(+), 3 deletions(-) create mode 100755 examples/textual_tty_toolbar.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 926036b48..2a4552eb9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,12 @@ [Updating Output in Place](docs/features/generating_output.md#updating-output-in-place) documentation for details, including why a carriage return embedded in a string passed to `poutput()` does not move the cursor. + - Added the + [textual_tty_toolbar.py](https://github.com/python-cmd2/cmd2/blob/main/examples/textual_tty_toolbar.py) + example, which shows how to keep a bottom toolbar on the screen while commands run by running + a `cmd2` application inside a Textual application which draws the toolbar. See + [Embedding in Textual](docs/examples/embedding_in_textual.md#a-bottom-toolbar-which-stays-while-commands-run) + for how it works and what it costs. ## 4.4.2 (November 11, 2026) diff --git a/docs/examples/embedding_in_textual.md b/docs/examples/embedding_in_textual.md index d00e95807..935a8d234 100644 --- a/docs/examples/embedding_in_textual.md +++ b/docs/examples/embedding_in_textual.md @@ -13,13 +13,15 @@ The [textual_tty_embed.py](https://github.com/python-cmd2/cmd2/blob/main/examples/textual_tty_embed.py) example shows how to do this. It has a `cmd2` application in a terminal pane on the left. On the right, a status panel shows whether the `cmd2` application is idle or running a command, how many -commands it has run, and how long the last one took, and a clock is updated by Textual on its own. +commands it has run, and how long the last one took, and a clock is updated by Textual on its own. A +second example uses the same technique for +[a bottom toolbar which stays while commands run](#a-bottom-toolbar-which-stays-while-commands-run). !!! warning - textual-tty is still pre-alpha software, so its API may change. The example was written for + textual-tty is still pre-alpha software, so its API may change. The examples were written for textual-tty 0.4. Also, on Windows textual-tty can only start a program by name and can't pass - it arguments, so the example's Textual application requires a POSIX system such as Linux or + it arguments, so the examples' Textual applications require a POSIX system such as Linux or macOS. ## Running the Example @@ -115,3 +117,68 @@ The example handles several details which are easy to miss when building somethi rows than are visible and its prompt can end up hidden. - The focused `Terminal` sends almost every key press to the `cmd2` application. Textual's built-in ++ctrl+q++ binding to quit is a priority binding, so it still works. + +## A Bottom Toolbar Which Stays While Commands Run + +A [bottom toolbar](../features/prompt.md#bottom-toolbar) is drawn by `prompt-toolkit` as part of the +prompt, so it is only on the screen while the prompt is. The same embedding technique gives you one +which stays, and keeps refreshing, while a command runs. The +[textual_tty_toolbar.py](https://github.com/python-cmd2/cmd2/blob/main/examples/textual_tty_toolbar.py) +example is a Textual application which is nothing but a terminal pane running a `cmd2` application +and a toolbar docked below it, so it looks like the `cmd2` application running on its own: + +```shell +uv run examples/textual_tty_toolbar.py +``` + +Try `slow`, `burst 2000 1`, or resizing the window while a command runs. Pass `--cmd2-only` to see +what `cmd2` does without Textual, where the toolbar disappears for as long as a command runs. + +Here the `cmd2` application doesn't draw the toolbar at all. It passes `enable_bottom_toolbar=False` +to [cmd2.Cmd.__init__][] when it is running inside the Textual application, and sends what +`get_bottom_toolbar()` returns to the Textual application, which shows it in a widget of its own: + +```py +def compose(self) -> ComposeResult: + yield Terminal(command=self._cmd2_command, id="cmd2") + yield Static("", id="toolbar") + + +def on_toolbar_changed(self, message: ToolbarChanged) -> None: + self.query_one("#toolbar", Static).update(Text.from_ansi(message.rendered)) +``` + +Command output can't overwrite the toolbar or make it flicker, because it goes to a different +widget, and a toolbar of more than one row simply takes rows from the terminal pane. + +The first example sends its status through the window title, from hooks which run between one +command's output and the next. A toolbar which refreshes _during_ a command has to be sent from +another thread, and a window title written into the terminal's stream from another thread could land +in the middle of the command's output. So this example uses a Unix socket instead: + +- The Textual application listens on a socket in a temporary directory before it starts the `cmd2` + application, and passes it the path with `--toolbar-socket`. +- In the `cmd2` application, a thread calls `get_bottom_toolbar()` every half second, and at once + when a postparsing or command finalization hook says a command has started or ended. It renders + the result to text with ANSI style sequences using `prompt-toolkit`, so anything + `get_bottom_toolbar()` is allowed to return works, and sends it as a line of JSON when it has + changed. +- `get_bottom_toolbar()` is therefore called on that thread while a command is running on the main + thread, so it must only read state which is safe to read from another thread. + +This approach has costs which are easy to overlook, and they are why `cmd2` doesn't do it for you: + +- There is no scrollback. The terminal pane keeps none, so output which scrolls off its top is gone, + and Textual uses the terminal's alternate screen, so none of the session is in the scrollback of + the user's own terminal either. +- It doesn't work on Windows, for the reason given in the warning above. +- ++ctrl+z++ does nothing, because inside the terminal pane there is no shell to return to. +- Textual takes the mouse, so selecting text the way the user's terminal does it needs that + terminal's modifier key. +- All output passes through a second terminal emulator, and the program is started twice: once as + the Textual application and once, inside it, as the `cmd2` application. + +Pull request [#1816](https://github.com/python-cmd2/cmd2/pull/1816) is a prototype which goes +further, with measurements: it moves the technique into `cmd2` behind a single function call and +adds a scrollback to the terminal pane. It is kept for reference and isn't intended to be merged, +because of the costs above and because it relies on parts of textual-tty which aren't public. diff --git a/docs/features/prompt.md b/docs/features/prompt.md index 59aeeed05..482499c1c 100644 --- a/docs/features/prompt.md +++ b/docs/features/prompt.md @@ -133,3 +133,8 @@ example for a demonstration of this technique. `cmd2` application inside a [Textual](https://textual.textualize.io/) application, next to widgets which display that information. See [Embedding in Textual](../examples/embedding_in_textual.md). + + The same technique can keep a toolbar on the screen while a command runs, which this one is + not: it is part of the prompt. See + [A Bottom Toolbar Which Stays While Commands Run](../examples/embedding_in_textual.md#a-bottom-toolbar-which-stays-while-commands-run) + for an example, and for what it costs. diff --git a/examples/README.md b/examples/README.md index 128080a32..955e8cbd4 100644 --- a/examples/README.md +++ b/examples/README.md @@ -100,6 +100,10 @@ each: application using [textual-tty](https://github.com/ttygroup/textual-tty), with a realtime status panel next to the terminal. Requires a POSIX system such as Linux or macOS and `textual-tty`, which is part of the `cmd2` development environment but not a `cmd2` dependency +- [textual_tty_toolbar.py](https://github.com/python-cmd2/cmd2/blob/main/examples/textual_tty_toolbar.py) + - Shows how to keep a bottom toolbar on the screen while commands run, by running a `cmd2` + application inside a [Textual](https://textual.textualize.io/) application which draws the + toolbar. Requires a POSIX system and `textual-tty`, like `textual_tty_embed.py` - [tmux_launch.sh](https://github.com/python-cmd2/cmd2/blob/main/examples/tmux_launch.sh) - Shell script that launches two applications using tmux in different windows/tabs - [tmux_split.sh](https://github.com/python-cmd2/cmd2/blob/main/examples/tmux_split.sh) diff --git a/examples/textual_tty_embed.py b/examples/textual_tty_embed.py index 2b306ab76..52d050924 100755 --- a/examples/textual_tty_embed.py +++ b/examples/textual_tty_embed.py @@ -30,6 +30,8 @@ python examples/textual_tty_embed.py --cmd2-only Use the ``quit`` command in the embedded cmd2 application, or press Ctrl-Q, to exit. + +See ``textual_tty_toolbar.py`` for the same technique used to keep a bottom toolbar on the screen while commands run. """ import argparse diff --git a/examples/textual_tty_toolbar.py b/examples/textual_tty_toolbar.py new file mode 100755 index 000000000..7322dd9eb --- /dev/null +++ b/examples/textual_tty_toolbar.py @@ -0,0 +1,400 @@ +#!/usr/bin/env python3 +"""Keep a bottom toolbar on the screen while commands run, by letting Textual draw it using textual-tty. + +cmd2's bottom toolbar is drawn by prompt-toolkit as part of the prompt, so it is only there while the prompt is. +This example shows a way to have one which stays, and keeps refreshing, while a command runs: the cmd2 +application doesn't draw the toolbar at all. A small Textual application owns the terminal instead. It shows the +cmd2 application in a terminal pane which fills the screen except for the bottom, where it draws the toolbar. + +How it works: + - [textual-tty](https://github.com/ttygroup/textual-tty) provides the ``Terminal`` widget, a terminal + emulator (built on bittty) which runs a child process attached to a pseudo-terminal. + - The child process is this script run with ``--cmd2-only --toolbar-socket PATH``. It is a normal cmd2 + application which uses prompt-toolkit, except that it gives prompt-toolkit no toolbar to draw. + - A thread in the cmd2 application calls ``get_bottom_toolbar()`` every half second, and at once when a + command starts or ends, and sends what it returns to the Textual application over a Unix socket. Since it + is a thread, it keeps doing so while a command has the main thread. + - The Textual application puts what it receives in a widget docked below the terminal pane. Command output + can't overwrite the toolbar, or make it flicker, because it goes to a different widget. + +The sibling example ``textual_tty_embed.py`` sends its status through the terminal's window title instead of a +socket, which is simpler. That works there because the status is only sent from hooks, between a command's +output. A toolbar which refreshes during a command is sent from another thread, and a window title written into +the terminal's stream from another thread could land in the middle of the command's output. + +Things this approach gives up, which is why cmd2 doesn't do it for you: + - Scrollback. The terminal pane keeps none, so output which scrolls off its top is gone, and Textual uses + the terminal's alternate screen, so none of the session is in your terminal's own scrollback either. + Pipe long output to a pager. + - Windows. On Windows textual-tty can only start a program by name and can't pass it arguments. + - Ctrl-Z does nothing, because inside the pane there is no shell to return to. + - Textual takes the mouse, so selecting text the way your terminal does it needs your terminal's modifier key. + +Neither textual nor textual-tty are dependencies of cmd2. In a cmd2 checkout, textual-tty is part of the +development environment on POSIX systems, so run this example with: + + uv run examples/textual_tty_toolbar.py + +Otherwise, install textual-tty into your own environment with ``pip install textual-tty`` and then run +``python examples/textual_tty_toolbar.py``. + +Things to try: ``slow``, ``burst 2000 1``, ``page``, ``ask``, resizing the window while a command runs, and +Ctrl-C during ``slow``. To compare with what cmd2 does on its own, run just the cmd2 application, on any platform: + + python examples/textual_tty_toolbar.py --cmd2-only + +Use the ``quit`` command in the cmd2 application, or press Ctrl-Q, to exit. +""" + +import argparse +import contextlib +import io +import json +import re +import shutil +import socket +import sys +import tempfile +import threading +import time +from collections.abc import Callable + +from prompt_toolkit.data_structures import Size +from prompt_toolkit.formatted_text import AnyFormattedText, to_formatted_text +from prompt_toolkit.output import ColorDepth +from prompt_toolkit.output.vt100 import Vt100_Output +from prompt_toolkit.renderer import print_formatted_text +from prompt_toolkit.styles import DynamicStyle, default_ui_style, merge_styles + +import cmd2 +from cmd2.theme import get_pt_theme + +# Control sequences other than "select graphic rendition", which is how a style is written +NOT_A_STYLE = re.compile(r"\x1b\[[0-?]*[ -/]*[@-ln-~]") + + +def render_toolbar(content: AnyFormattedText) -> str: + """Render a toolbar's content as text with ANSI style sequences, which is what gets sent to the Textual application. + + prompt-toolkit does the rendering, so everything ``get_bottom_toolbar()`` is allowed to return is understood, + and style classes mean what cmd2's theme says they mean. + + :param content: what ``get_bottom_toolbar()`` returned + :return: the text, with a newline between rows + """ + stream = io.StringIO() + output = Vt100_Output( + stream, + lambda: Size(rows=1, columns=10_000), + term="xterm-256color", + default_color_depth=ColorDepth.TRUE_COLOR, + enable_bell=False, + enable_cpr=False, + ) + # cmd2's theme over prompt-toolkit's default style, which is how a prompt-toolkit application combines them + style = merge_styles([default_ui_style(), DynamicStyle(get_pt_theme)]) + print_formatted_text(output, to_formatted_text(content), style, color_depth=ColorDepth.TRUE_COLOR) + # The renderer also sets up the terminal around the text, which is none of the Textual application's business + return NOT_A_STYLE.sub("", stream.getvalue()).replace("\r\n", "\n") + + +class ToolbarReporter: + """Sends a toolbar's content to the Textual application whenever it changes, from a thread of its own.""" + + def __init__(self, get_toolbar: Callable[[], AnyFormattedText], socket_path: str, interval: float) -> None: + """Connect to the Textual application. + + :param get_toolbar: returns the toolbar's content, like ``cmd2.Cmd.get_bottom_toolbar()`` + :param socket_path: the Unix socket which the Textual application listens on + :param interval: seconds between looks at the toolbar's content + """ + self._get_toolbar = get_toolbar + self._interval = interval + self._socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self._socket.connect(socket_path) + self._wake = threading.Event() + self._stopping = False + self._last_sent: str | None = None + self._thread = threading.Thread(target=self._run, name="toolbar-reporter", daemon=True) + + def start(self) -> None: + """Send the toolbar once, then keep it up to date.""" + self._report() + self._thread.start() + + def poke(self) -> None: + """Look at the toolbar's content now rather than at the next interval, because something has changed.""" + self._wake.set() + + def stop(self) -> None: + """Stop reporting and close the connection.""" + self._stopping = True + self._wake.set() + if self._thread.is_alive(): + self._thread.join(timeout=2) + self._socket.close() + + def _run(self) -> None: + while not self._stopping: + self._wake.wait(self._interval) + self._wake.clear() + if self._stopping or not self._report(): + return + + def _report(self) -> bool: + """Send the toolbar's content if it has changed. + + :return: False if the Textual application has gone away + """ + try: + rendered = render_toolbar(self._get_toolbar()) + except Exception: # noqa: BLE001 + # This runs application code on a thread nobody is watching. Keep showing the last good toolbar. + return True + if rendered == self._last_sent: + return True + try: + # One JSON document per line + self._socket.sendall(json.dumps({"toolbar": rendered}).encode() + b"\n") + except OSError: + return False + self._last_sent = rendered + return True + + +class ToolbarApp(cmd2.Cmd): + """A cmd2 application with a bottom toolbar which says what it is doing.""" + + def __init__(self, toolbar_socket: str | None) -> None: + """Initialize the cmd2 application. + + :param toolbar_socket: the Unix socket of the Textual application which draws the toolbar, or None if this + application isn't running inside one. Then prompt-toolkit draws the toolbar as usual, + which means only while the prompt is on the screen. + """ + refresh_interval = 0.5 + super().__init__( + allow_cli_args=False, + # Inside the Textual application, don't have prompt-toolkit draw a second toolbar in the terminal pane + enable_bottom_toolbar=toolbar_socket is None, + refresh_interval=refresh_interval, + ) + self.prompt = "toolbar-demo> " + self._commands_run = 0 + self._running_command = "" + + self._reporter: ToolbarReporter | None = None + if toolbar_socket is not None: + self._reporter = ToolbarReporter(self.get_bottom_toolbar, toolbar_socket, refresh_interval) + + self.register_postparsing_hook(self._on_command_start) + self.register_cmdfinalization_hook(self._on_command_end) + + def get_bottom_toolbar(self) -> AnyFormattedText: + """Return the toolbar's content. Inside the Textual application this is called on the reporter's thread.""" + if self._running_command: + state = ("fg:ansiyellow bold", f"running {self._running_command}") + else: + state = ("fg:ansigreen bold", "idle") + return [("", " "), state, ("", f" | commands run: {self._commands_run} | {time.strftime('%H:%M:%S')} ")] + + def preloop(self) -> None: + """Start sending the toolbar before the first prompt.""" + if self._reporter is not None: + self._reporter.start() + + def postloop(self) -> None: + """Stop sending the toolbar once the command loop has ended.""" + if self._reporter is not None: + self._reporter.stop() + + def _on_command_start(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData: + """Note which command is about to run, and show it in the toolbar without waiting for the next interval.""" + self._running_command = data.statement.command + if self._reporter is not None: + self._reporter.poke() + return data + + def _on_command_end(self, data: cmd2.plugin.CommandFinalizationData) -> cmd2.plugin.CommandFinalizationData: + """Note that the command is done, even when it failed.""" + # Finalization hooks also run for blank lines, comments, and syntax errors, which never became a statement + if data.statement is not None: + self._commands_run += 1 + self._running_command = "" + if self._reporter is not None: + self._reporter.poke() + return data + + @cmd2.with_argument_list + def do_slow(self, args: list[str]) -> None: + """Print a line every quarter of a second: slow [COUNT].""" + for number in range(int(args[0]) if args else 12): + self.poutput(f"line {number}") + time.sleep(0.25) + self.poutput("slow done") + + @cmd2.with_argument_list + def do_burst(self, args: list[str]) -> None: + """Print numbered lines with an optional pause between them: burst [COUNT [DELAY_MS]].""" + count = int(args[0]) if args else 1000 + delay = int(args[1]) / 1000 if len(args) > 1 else 0 + started = time.perf_counter() + for number in range(count): + self.poutput(f"burst {number}") + if delay: + time.sleep(delay) + self.poutput(f"burst done in {time.perf_counter() - started:.2f} s") + + @cmd2.with_argument_list + def do_page(self, args: list[str]) -> None: + """Show numbered rows in a pager: page [COUNT].""" + self.ppaged("\n".join(f"row {number}" for number in range(int(args[0]) if args else 300))) + + def do_ask(self, _: cmd2.Statement) -> None: + """Ask for a line of input in the middle of a command.""" + self.poutput(f"got {self.read_input('Value: ')}") + + def do_fail(self, _: cmd2.Statement) -> bool: + """End the application with exit code 3.""" + self.exit_code = 3 + return True + + +def run_textual_app() -> int: + """Run the Textual application with the cmd2 application in a terminal pane and its toolbar below it. + + Textual is imported here rather than at the top of the module so the cmd2 application can run without it. + + :return: the exit code of the cmd2 application + """ + import asyncio + + from rich.text import Text + from textual.app import App, ComposeResult + from textual.message import Message + from textual.widgets import Static + from textual_tty import Terminal + + class ToolbarChanged(Message): + """The cmd2 application sent new content for its toolbar.""" + + def __init__(self, rendered: str) -> None: + self.rendered = rendered + super().__init__() + + class ToolbarHost(App[None]): + """A Textual application which is nothing but a terminal pane running cmd2 and a toolbar below it.""" + + CSS = """ + #cmd2 { + height: 1fr; + } + #toolbar { + dock: bottom; + /* As tall as its content, so a toolbar of two rows takes two rows from the terminal pane */ + height: auto; + min-height: 1; + background: $foreground; + color: $background; + } + """ + # All there is to see is the cmd2 application, so there is nothing for a command palette to do + ENABLE_COMMAND_PALETTE = False + + def __init__(self, cmd2_command: list[str], listener: socket.socket) -> None: + """Initialize the Textual application. + + :param cmd2_command: the command which runs the cmd2 application + :param listener: the listening Unix socket which the cmd2 application sends its toolbar to + """ + super().__init__() + self.cmd2_exit_code = 0 + self._cmd2_command = cmd2_command + self._listener = listener + self._server: asyncio.Server | None = None + + def compose(self) -> ComposeResult: + """Create the layout: the terminal running cmd2, and the toolbar docked below it.""" + yield Terminal(command=self._cmd2_command, id="cmd2") + yield Static("", id="toolbar") + + async def on_mount(self) -> None: + """Start reading the toolbar, and give the keyboard focus to the terminal.""" + self._server = await asyncio.start_unix_server(self._read_toolbar, sock=self._listener) + self.query_one(Terminal).focus() + + async def on_unmount(self) -> None: + """Stop accepting connections.""" + if self._server is not None: + self._server.close() + + async def _read_toolbar(self, reader: asyncio.StreamReader, _writer: asyncio.StreamWriter) -> None: + """Read the toolbar from the cmd2 application, which sends one JSON document per line.""" + while line := await reader.readline(): + # Ignore anything which isn't a valid document rather than letting it crash the application + with contextlib.suppress(TypeError, ValueError, RecursionError): + document = json.loads(line) + if isinstance(document, dict) and isinstance(document.get("toolbar"), str): + self.post_message(ToolbarChanged(document["toolbar"])) + + def on_toolbar_changed(self, message: ToolbarChanged) -> None: + """Show the new toolbar. The text arrived with ANSI style sequences, which Rich understands.""" + self.query_one("#toolbar", Static).update(Text.from_ansi(message.rendered)) + + def on_terminal_process_exited(self, event: Terminal.ProcessExited) -> None: + """Exit when the cmd2 application exits, for example due to the quit command.""" + if event.exit_code == 0: + self.exit() + return + if event.exit_code < 0: + # The exit code of a process killed by a signal is the negated signal number. Shells report 128 + signal. + outcome = f"was killed by signal {-event.exit_code}" + self.cmd2_exit_code = 128 - event.exit_code + else: + outcome = f"exited with code {event.exit_code}" + self.cmd2_exit_code = event.exit_code + # Keep the terminal on the screen so the cmd2 application's error output, like a traceback, can be read + self.query_one("#toolbar", Static).update(Text(f" The cmd2 application {outcome}. Press Ctrl-Q to close. ")) + + async def action_quit(self) -> None: + """Exit with the cmd2 application's exit code, so the shell can tell whether it failed.""" + self.exit(return_code=self.cmd2_exit_code) + + # A Unix socket's path is limited to about a hundred bytes, so make a short one + directory = tempfile.mkdtemp(prefix="cmd2-") + listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + socket_path = f"{directory}/toolbar.sock" + # Listen before the cmd2 application is started, so its connection is never refused + listener.bind(socket_path) + listener.listen(1) + app = ToolbarHost([sys.executable, __file__, "--cmd2-only", "--toolbar-socket", socket_path], listener) + app.run() + return app.return_code or app.cmd2_exit_code + finally: + listener.close() + shutil.rmtree(directory, ignore_errors=True) + + +def main() -> int: + """Run the Textual application, or just the cmd2 application if --cmd2-only is given.""" + parser = argparse.ArgumentParser(description="Run a cmd2 application whose bottom toolbar is drawn by Textual.") + parser.add_argument("--cmd2-only", action="store_true", help="run just the cmd2 application, without Textual") + parser.add_argument( + "--toolbar-socket", + metavar="PATH", + help="with --cmd2-only, send the toolbar to this Unix socket, which the Textual application listens on", + ) + cli_args = parser.parse_args() + if cli_args.toolbar_socket and not cli_args.cmd2_only: + parser.error("--toolbar-socket can only be used with --cmd2-only") + + if cli_args.cmd2_only: + return ToolbarApp(toolbar_socket=cli_args.toolbar_socket).cmdloop() + if sys.platform == "win32": + parser.error("the Textual application requires a POSIX system, use --cmd2-only to run just the cmd2 application") + return run_textual_app() + + +if __name__ == "__main__": + sys.exit(main()) From a161b362de0f92e79244468a337b6ecb6a30a84d Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:30:49 -0500 Subject: [PATCH 2/3] Spell out the final bytes in the toolbar example's control sequence pattern CodeQL reported the range "@-l" as overly permissive, since it runs from the uppercase letters through punctuation into the lowercase ones. It was meant to: with "n-~" it is every final byte of a control sequence except the "m" of "select graphic rendition". Write the same set without a range which crosses those classes, and say what the class is. --- examples/textual_tty_toolbar.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/examples/textual_tty_toolbar.py b/examples/textual_tty_toolbar.py index 7322dd9eb..7c46e760f 100755 --- a/examples/textual_tty_toolbar.py +++ b/examples/textual_tty_toolbar.py @@ -69,8 +69,10 @@ import cmd2 from cmd2.theme import get_pt_theme -# Control sequences other than "select graphic rendition", which is how a style is written -NOT_A_STYLE = re.compile(r"\x1b\[[0-?]*[ -/]*[@-ln-~]") +# Control sequences other than "select graphic rendition", which is how a style is written. A control sequence ends with +# a final byte from "@" to "~" which says what it does, and the last character class is every one of those except the "m" +# of "select graphic rendition". +NOT_A_STYLE = re.compile(r"\x1b\[[0-?]*[ -/]*[@A-Z\[\\\]^_`a-ln-~]") def render_toolbar(content: AnyFormattedText) -> str: From b9a9993c70ae25f85570ccde28468c00421f01b2 Mon Sep 17 00:00:00 2001 From: Todd Leonhardt <2812720+tleonhardt@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:30:49 -0500 Subject: [PATCH 3/3] Remove the reference to the Textual toolbar prototype from the docs --- docs/examples/embedding_in_textual.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/docs/examples/embedding_in_textual.md b/docs/examples/embedding_in_textual.md index 935a8d234..25924bc83 100644 --- a/docs/examples/embedding_in_textual.md +++ b/docs/examples/embedding_in_textual.md @@ -177,8 +177,3 @@ This approach has costs which are easy to overlook, and they are why `cmd2` does terminal's modifier key. - All output passes through a second terminal emulator, and the program is started twice: once as the Textual application and once, inside it, as the `cmd2` application. - -Pull request [#1816](https://github.com/python-cmd2/cmd2/pull/1816) is a prototype which goes -further, with measurements: it moves the technique into `cmd2` behind a single function call and -adds a scrollback to the terminal pane. It is kept for reference and isn't intended to be merged, -because of the costs above and because it relies on parts of textual-tty which aren't public.