Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
b754f91
Point the install command and the homepage at beeware/toga-console
kattni Oct 17, 2026
059a414
Match toga-code-editor's tooling: tox, pre-commit, towncrier, setupto…
kattni Oct 17, 2026
01ca6c7
Add the change note for #1
kattni Oct 17, 2026
d179b65
Minor reorg and cleanup.
freakboy3742 Oct 17, 2026
209e728
Add GTK 3 and Qt backends, with the demo's self-test run on both in CI
kattni Oct 17, 2026
b5063c0
Name the change note after #2
kattni Oct 17, 2026
b8da24e
Merge branch 'align-with-toga-code-editor' of https://github.com/beew…
kattni Oct 17, 2026
cd2938d
Merge remote-tracking branch 'origin/main' into gtk-qt-backends
kattni Oct 18, 2026
09a0fa9
Add a Windows backend on the Winforms RichTextBox, and read pipes on …
kattni Oct 17, 2026
fa6d8fb
Run the demo's self-test on Windows in CI
kattni Oct 18, 2026
fa3e85d
Name the change note after #4
kattni Oct 18, 2026
ba67330
Run the unit tests on Windows in CI, with per-platform coverage exclu…
kattni Oct 18, 2026
a1950f4
Winforms: delete with EM_REPLACESEL, since SelectedText = "" sends WM…
kattni Oct 18, 2026
516d301
Merge remote-tracking branch 'origin/main' into windows-backend
kattni Oct 18, 2026
e722130
Accept typed input on macOS: readonly=False makes the tail editable, …
kattni Oct 17, 2026
272fc78
Deliver typed input as bytes to on_input: each line on Return, and Ct…
kattni Oct 18, 2026
009fac5
Accept typed input on iOS and Android: the input area, Return, and ha…
kattni Oct 18, 2026
63f81bc
Run the demo on Qt as a second Briefcase app, and its self-test throu…
kattni Oct 18, 2026
a5c0630
Merge branch 'gtk-qt-backends' of https://github.com/beeware/toga-con…
kattni Oct 18, 2026
b94bad9
Merge branch 'console-input' into console-input-desktop
kattni Oct 18, 2026
03f14e3
Accept typed input on GTK, Qt, and Windows: the input area, Return, a…
kattni Oct 18, 2026
1ae823a
Name the change note after #5
kattni Oct 18, 2026
38d194c
Windows: enter a line on the Return key, which the control acts on be…
kattni Oct 18, 2026
99624dc
Merge branch 'main' into windows-backend
freakboy3742 Nov 9, 2026
2d71f24
Correct the project name for PEP 621 compliance.
freakboy3742 Nov 9, 2026
6b8b3ff
Merge branch 'main' of https://github.com/beeware/toga-console into w…
kattni Nov 9, 2026
7d6038b
Merge branch 'windows-backend' of https://github.com/beeware/toga-con…
kattni Nov 9, 2026
46f4c6b
Merge branch 'main' of https://github.com/beeware/toga-console into c…
kattni Nov 9, 2026
ce0dc82
Light cleanup of README.
freakboy3742 Nov 10, 2026
ac73d7d
Clarify handling of multiple app entry points.
freakboy3742 Nov 10, 2026
fa28f12
Clean up usage of double backticks.
freakboy3742 Nov 10, 2026
f404b5e
Cocoa: take the event modifier flags from toga_cocoa.libs
kattni Nov 10, 2026
8b42ed3
Make the demo's keyboard part of the Console: type(), press() with a …
kattni Nov 10, 2026
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
54 changes: 51 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,22 @@ Anything running on the event loop can also call `console.write(data, stream="st

| Member | Meaning |
|---|---|
| `Console(id=None, style=None, *, max_lines=2000, encoding="utf-8", errors="replace", follow=True, styles=None, placeholder=None, on_change=None, **style_properties)` | Always read-only and selectable; monospace unless a font family is given. |
| `Console(id=None, style=None, *, max_lines=2000, encoding="utf-8", errors="replace", follow=True, styles=None, readonly=True, placeholder=None, on_change=None, on_input=None, **style_properties)` | Selectable, and monospace unless a font family is given. With `readonly=False`, the user can type after the last output; see [Input](#input). |
| `write(data, *, stream="stdout")` | Append bytes or text on a named stream. Each stream has its own decoder and escape parser; all streams share one cursor and scrollback. |
| `attach(source, *, stream="stdout")` | Read a source until it ends: an `asyncio.StreamReader`, an async iterable of bytes or text, a file-like object with `fileno()`, or a file descriptor. Returns an `Attachment`. A regular file is read to its current end. On Android, descriptors are read on a helper thread so end-of-file arrives. On Windows, a descriptor must be a pipe or a regular file, and a pipe is read on a helper thread, because Toga's Windows event loop cannot watch a descriptor; `cancel` leaves whatever arrives later in the pipe. Everywhere else the descriptor is switched to non-blocking for good. The widget never closes a descriptor it was given. |
| `clear()` | Empty the scrollback and the display at once. |
| `flush()` | Apply pending output to the display now instead of after the 50 ms interval. |
| `type(text)` | Type text at the caret, as the user would, through the native view's own handling of typing: a line break enters the line. |
| `press(key)` | Press a key, as the user would: `Key.ENTER`, `Key.BACKSPACE`, or Ctrl-C or Ctrl-D, `CONTROL + Key.C` and `CONTROL + Key.D`, with `CONTROL` from `toga_console.console`: `Key.MOD_3` on macOS and iOS, where `Key.MOD_1` is Command, and `Key.MOD_1` elsewhere. Any other key raises `ValueError`. |
| `caret_to(index)` | Move the caret to `index` in `text()`. |
| `text()` | The text the view shows: the output, then the line being typed. |
| `value` | The scrollback text. Assigning clears, then writes the text on `stdout`. |
| `max_lines` | Committed lines kept; assigning trims at once. |
| `follow` | Scroll to the newest output after each update. |
| `readonly` | Boolean; does the console accepts keyboard input when it has focus? |
| `styles` | A dict from stream name to `Style`; by default `stderr` is red. A change applies to text written afterwards. |
| `on_change` | Fires once per display update that changed what is shown. Use it to show a "new output" hint while the console is hidden. |
| `on_input` | Called as `on_input(widget, data)` with the bytes the user enters: the line on Return, `b"\x03"` on Ctrl-C, `b"\x04"` on Ctrl-D. See [Input](#input). |
| `on_change` | Fires once per display update that changed what is shown; typing does not fire it. Use it to show a "new output" hint while the console is hidden. |
| `Attachment` | `cancel()` stops the source; `await wait()` returns at its end or after cancel and raises the error the source raised; `done`, `error`, `stream`. |
| `Style(color=None, bold=False, italic=False)` | `color` is any Toga colour value; `None` is the widget's own text colour. |

Expand All @@ -73,6 +79,48 @@ Anything running on the event loop can also call `console.write(data, stream="st

A line reaching 4096 characters is split, a sequence of 256 characters without its terminator is abandoned, and the oldest lines drop past `max_lines`. Long lines wrap at the view's width. Each stream's decoder and escape parser keep their state across writes, so a character or sequence may span two chunks. When an attachment ends and no other live attachment shares its stream, that stream's decoder and parser are reset, so a source that dies mid-sequence cannot swallow the next source's text.

## Input

When `readonly=True`, the console does not accept keyboard input. When `readonly=False`, the console accepts typing after the last output, the way a terminal does: Backspace stops at the output, and a key pressed with the caret in the output types at the end of the input. Output that arrives while you type goes in before your input, which stays where it is.

What the user enters reaches the `on_input` handler as bytes, encoded with the console's encoding:

| Key | Delivered |
|---|---|
| Return | the line and `b"\n"`, after it is echoed into the scrollback on stream `"stdin"` (unstyled unless `styles` says otherwise) |
| a paste with line breaks | all its complete lines in one call; the text after the last break stays in the input |
| Ctrl-C | `b"\x03"`, at once; the line being typed stays |
| Ctrl-D | `b"\x04"`, at once; the line being typed stays |

The console gives these bytes no meaning of its own, and does not echo the control keys: the handler decides what they do. A handler should not assume that one call is one line. Feeding a subprocess:

```python
process = await asyncio.create_subprocess_exec(
sys.executable,
"-i",
"-u",
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)


def on_input(widget, data, **kwargs):
if data == b"\x04":
process.stdin.close() # end of input
elif data == b"\x03":
process.send_signal(signal.SIGINT)
else:
process.stdin.write(data)


console = Console(readonly=False, on_input=on_input)
console.attach(process.stdout)
console.attach(process.stderr, stream="stderr")
```

Typing works on every backend. Ctrl-C and Ctrl-D come from a hardware keyboard; an on-screen keyboard has no Control key, so an app that needs them on a phone offers its own buttons, which can pass the same bytes to its handler. Where Ctrl-C would copy (Android, GTK, Qt on Linux and Windows, and Windows), a console that takes input sends `b"\x03"` instead; a read-only console copies as usual. On macOS, Command-C copies either way. The demo app's REPL button runs a Python REPL inside the app, on a thread fed from `on_input`, where Ctrl-C raises `KeyboardInterrupt` and Ctrl-D at the prompt ends the REPL; see `examples/console_demo/src/console_demo/repl.py`.

## Threads

`write` and every other method run on the event loop thread. From another thread, use `loop.call_soon_threadsafe(console.write, data)`. Sources given to `attach` are delivered to `write` on the loop; on Android, and for a pipe on Windows, a helper thread does the reading.
Expand All @@ -87,7 +135,7 @@ uv pip install -e . --group dev

The test suite runs against Toga's dummy backend with warnings as errors, and requires 100% coverage of everything except the native backends. CI runs it on Ubuntu and Windows. Code that only one of them runs is marked `# pragma: no-cover-if-is-windows` or `# pragma: no-cover-if-not-windows`, which leaves it out of the other platform's report; the combined report counts every line. `.venv/bin/pre-commit install` runs the same lint and format checks as CI before each commit.

The native backends are checked with the Briefcase project in `examples/console_demo`. Its demo app has a self-test that compares the native view's text with the model's. The project has two apps: `console_demo` uses the platform's own backend, and `console_demo_qt` runs the same demo on Qt on any desktop platform:
The native backends are checked with the Briefcase project in `examples/console_demo`. Its demo app has a self-test that compares the native view's text with the model's, then types into the native view and checks the in-app REPL's answers, its Ctrl-C, and its Ctrl-D. The project has two apps: `console_demo` uses the platform's own backend, and `console_demo_qt` runs the same demo on Qt on any desktop platform:

```console
cd examples/console_demo
Expand Down
1 change: 1 addition & 0 deletions changes/5.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A console created with `readonly=False` accepts typed input after its output, and passes each line entered, and Ctrl-C and Ctrl-D as single bytes, to its new `on_input` handler.
3 changes: 2 additions & 1 deletion examples/console_demo/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ name = "console_demo"

[tool.briefcase]
project_name = "console_demo"
default_app = "console_demo"
bundle = "org.beeware.examples"
url = "https://beeware.org"
license = "BSD-3-Clause"
Expand Down Expand Up @@ -75,7 +76,7 @@ build_gradle_dependencies = [
root = "../../"

[tool.briefcase.app.console_demo_qt]
formal_name = "Console Demo"
formal_name = "Console Demo (Qt)"
sources = [
"src/console_demo_qt",
"src/console_demo",
Expand Down
113 changes: 108 additions & 5 deletions examples/console_demo/src/console_demo/app.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
"""Console Demo: feeds the toga-console widget from a burst, a pipe, and a subprocess.

The REPL button starts a Python REPL inside the app, fed with the bytes the
console's `on_input` handler receives: typed lines, Ctrl-C, and Ctrl-D.

The self-test runs at startup and from its button: it writes the burst directly,
then streams the same bytes through an OS pipe until the pipe's attachment sees
the end, and compares the native view's text with the model's text and with the
expected text. It then trims the console to seven lines and compares the native
view's text with the model's text and with the last seven expected lines. The
verdict is printed as ``SELFTEST OK`` or ``SELFTEST FAIL`` so a log reader can
check a backend without eyes on the screen.
verdict is printed as `SELFTEST OK` or `SELFTEST FAIL` so a log reader can
check a backend without eyes on the screen. The self-test then types `6 * 7`
into the native view, as a user would, and checks that the REPL answers, that
Ctrl-C interrupts a busy loop and a prompt, and that Ctrl-D ends the REPL.
"""

import asyncio
Expand All @@ -17,11 +22,15 @@

import toga
from toga.constants import COLUMN, ROW
from toga.keys import Key
from toga.platform import current_platform

from toga_console import Console
from toga_console.console import CONTROL
from toga_console.model import DEFAULT_MAX_LINES

from .repl import ConsoleRepl

BURST = [
b"Hello from the burst\r\n",
b"Progress: 0%\r",
Expand Down Expand Up @@ -56,7 +65,13 @@

class ConsoleDemo(toga.App):
def startup(self):
self.console = Console(flex=1, placeholder="Press a button.")
self.console = Console(
flex=1,
readonly=False,
placeholder="Press a button.",
on_input=self.on_input,
)
self.repl = None
self.result = toga.Label("", flex=1)
self.follow = toga.Switch("Follow", value=True, on_change=self.set_follow)
buttons = [
Expand All @@ -74,7 +89,11 @@ def startup(self):
children=[
toga.Box(children=buttons, direction=ROW, gap=5),
toga.Box(
children=[self.follow, self.result],
children=[
toga.Button("REPL", on_press=self.start_repl),
self.follow,
self.result,
],
direction=ROW,
align_items="center",
gap=5,
Expand Down Expand Up @@ -132,6 +151,20 @@ async def subprocess(self, widget=None, **kwargs):
self.console.attach(process.stderr, stream="stderr")
await process.wait()

def start_repl(self, widget=None, **kwargs):
if self.repl is None:
self.repl = ConsoleRepl(self.console, {"app": self})
self.repl.start().add_done_callback(self._repl_ended)
self.console.focus()
return self.repl

def _repl_ended(self, future):
self.repl = None

def on_input(self, widget, data, **kwargs):
if self.repl is not None:
self.repl.feed(data)

def clear(self, widget=None, **kwargs):
self.console.clear()

Expand All @@ -141,6 +174,66 @@ def set_follow(self, widget, **kwargs):
async def run_self_test(self, widget=None, **kwargs):
await self.self_test()

async def input_test(self):
"""Type into the native view and check the REPL's answers."""
console = self.console

def ends(text):
return lambda: self.console.value.endswith(text)

self.console.clear()
repl = self.start_repl()
if not await until(ends(">>> ")):
return False
# Typed before the prompt reaches the view: the input area must stay after
# the output once it arrives.
console.type("6 * ")
console.flush()
# Backspace at the start of the input must not reach the prompt.
console.caret_to(len(console.value))
console.press(Key.BACKSPACE)
# Typing with the caret in the output goes to the end of the input.
console.caret_to(0)
console.type("7")
await asyncio.sleep(0.1)
console.press(Key.ENTER)
answered = await until(ends(">>> 6 * 7\n42\n>>> "))

# Ctrl-C interrupts running code...
console.type("while True: pass")
console.press(Key.ENTER)
await until(ends("... "))
console.press(Key.ENTER) # the blank line that ends the block
await asyncio.sleep(0.3)
console.press(CONTROL + Key.C)
busy_interrupted = await until(ends("KeyboardInterrupt\n>>> "))
# ...and a prompt.
console.press(CONTROL + Key.C)
prompt_interrupted = await until(ends(">>> \nKeyboardInterrupt\n>>> "))

# Ctrl-D at the prompt is the end of input.
console.press(CONTROL + Key.D)
ended = await until(lambda: repl.done.done())
self.console.flush()
verdict = (
answered
and busy_interrupted
and prompt_interrupted
and ended
and self.console.value.endswith(">>> \nREPL ended.\n")
and self.console._impl.get_value() == self.console.value
and console.text() == self.console.value # nothing left in the input
)
if not verdict:
print(
f"INPUT answered={answered} busy={busy_interrupted} "
f"prompt={prompt_interrupted} ended={ended} "
f"value={self.console.value[-200:]!r} "
f"native={console.text()[-200:]!r}",
flush=True,
)
return verdict

async def self_test(self):
self.console.clear()
self.burst()
Expand All @@ -163,15 +256,25 @@ async def self_test(self):
trimmed_model = self.console.value
self.console.max_lines = DEFAULT_MAX_LINES
ok = ok and trimmed_native == trimmed_model == TRIMMED
input_ok = await self.input_test()
ok = ok and input_ok is not False
verdict = "OK" if ok else "FAIL"
self.result.text = f"Self-test {verdict}"
print(
f"SELFTEST {verdict} native={native!r} model={model!r} "
f"trimmed_native={trimmed_native!r} trimmed_model={trimmed_model!r} "
f"pipe_done={pipe_done}",
f"pipe_done={pipe_done} input_ok={input_ok}",
flush=True,
)


def main():
return ConsoleDemo("Console Demo", "org.beeware.examples.console_demo")


async def until(predicate, timeout=3.0): # noqa: ASYNC109
for _ in range(int(timeout / 0.05)):
if predicate():
return True
await asyncio.sleep(0.05)
return False
Loading
Loading