Skip to content

Running an App

app runs an application. Give it the root component, already called with its arguments, and run it on an event loop with asyncio.run:

import asyncio

from counterweight import app
from counterweight.components import component
from counterweight.elements import Text


@component
def root(name: str) -> Text:
    return Text(content=f"Hello, {name}!")


if __name__ == "__main__":
    asyncio.run(app(root("world")))

It switches the terminal to its alternate screen, reads input raw and turns on mouse reporting, then renders the root and handles input until something returns Quit, which by default Ctrl+C does. It restores the terminal before it returns, and before an error raised in a component, a handler or an effect propagates out of it.

Where it draws

app's viewport says where on the terminal the app draws. FullScreen(), the default, fills the alternate screen, as vim or htop do, and leaves the main screen as it found it. Inline() draws in a region below the prompt, as tall as the root's content, which leaves its last frame in the terminal when the app stops (see Inline Apps).

What else it takes

The rest of app's parameters each belong to a part of the framework, with its own page:

To Pass See
Title the terminal window title SetTitle
Change what Ctrl+C and Ctrl+Z do, or give other keys defaults unclaimed_keys Keys the terminal would act on
Read the time in another time zone, or freeze it clock use_clock
Drive it without a person, or without a terminal autopilot, headless, dimensions Autopilot
Record it as an asciicast recording Recording
Catch components that go stale check_purity Performance
Let garbage collection run in the middle of a frame collect_garbage_between_frames Performance
See other libraries' debug logs in the devlog log_levels The devlog
Match a font that isn't twice as tall as it is wide cell_aspect_ratio Gradients
Draw on a terminal other than standard input and output input_stream, output_stream Running programs
Print to streams other than standard output and standard error stdout, stderr Printing
Leave sys.stdout and sys.stderr alone capture_output Stray prints

Which version is running

counterweight.__version__ is the version installed, which counterweight version prints too.

API

counterweight.app async

app(
    root: Component,
    output_stream: TextIO = stdout,
    input_stream: TextIO = stdin,
    headless: bool = False,
    dimensions: tuple[int, int] | None = None,
    autopilot: Iterable[AutopilotStep] = (),
    check_purity: bool = False,
    clock: Clock = SystemClock(),
    log_levels: Mapping[str, int] = frozendict(),
    title: str | None = None,
    unclaimed_keys: Mapping[
        str, AnyControl
    ] = DEFAULT_UNCLAIMED_KEYS,
    cell_aspect_ratio: float = DEFAULT_CELL_ASPECT_RATIO,
    recording: Recording | None = None,
    clipboard_handler: Callable[[str], object]
    | None = None,
    collect_garbage_between_frames: bool = True,
    viewport: FullScreen | Inline = FullScreen(),
    stdout: TextIO = stdout,
    stderr: TextIO = stderr,
    capture_output: bool = True,
) -> None
PARAMETER DESCRIPTION
root

The root component of the application, already called with its arguments, such as app(root(path)).

TYPE: Component

output_stream

The stream to which the application will write its output. To draw on the terminal while standard output is a pipe, as a picker run in vim $(picker) does, pass /dev/tty opened for writing.

TYPE: TextIO DEFAULT: stdout

input_stream

The stream from which the application will read its input.

TYPE: TextIO DEFAULT: stdin

headless

If True, the application will not attempt to read from the input stream or write to the output stream. This is primarily useful when combined with the autopilot parameter.

TYPE: bool DEFAULT: False

dimensions

The dimensions of the terminal window, in characters. If None, the size of the terminal output_stream writes to, read again on each resize, or 80 by 24 if it isn't a terminal. The COLUMNS and LINES environment variables are ignored.

TYPE: tuple[int, int] | None DEFAULT: None

autopilot

An iterable of events and controls to be processed by the application, and of Wait and WaitFor, which hold the rest back until real time has passed or the screen shows something. This is primarily useful for testing or generating screenshots and recordings programmatically. Each step is handled once the renders the last one caused are painted, and the effects they started have run up to where each first waits on something, as a person's next key press would be. An app that never settles, such as one showing a program that prints without pause, holds a step back for at most SETTLE_LIMIT passes of the render loop, after which the autopilot takes it anyway. A Wait or WaitFor is checked on every pass, settled or not, so a WaitFor times out on time. Note that the autopilot will not be processed until after the initial render cycle, and that using the autopilot does not automatically cause the application to quit!

TYPE: Iterable[AutopilotStep] DEFAULT: ()

check_purity

If True, check that components are pure: that their output depends only on their arguments and their hooks. A render keeps the previous output of every component it doesn't re-run (because its state didn't change and its parent didn't re-run, or because it's a memo component whose arguments didn't change), so an impure one goes stale. With this on, each frame's tree, once its focus and measurements settle, is built a second time, re-running every component against copies of its hooks, and if that builds a different tree, the application raises ImpureComponent, naming the first component whose output differs. Elements are compared with ==, and where that fails, piece by piece, so handlers are compared by their code and the values they captured, since a re-run builds new ones. The second run also raises InconsistentHookExecution for a component that calls a different number of hooks, and computes each use_memo that keeps its cached value again, raising StaleMemo if the result differs, naming the component and the hook. A frame whose use_rects and use_scroll reads don't settle before it paints raises UnsettledMeasurements, rather than logging a warning and settling in the next frame. It costs as much as a render that re-runs everything, so turn it on in tests rather than in production.

TYPE: bool DEFAULT: False

clock

Where use_clock reads the time, once per render. The SystemClock reads the time in UTC unless it's given a timezone. Pass a FrozenClock to make output that doesn't depend on when the application runs, such as a screenshot, and move it with the AdvanceClock control.

TYPE: Clock DEFAULT: SystemClock()

log_levels

Levels by logger name, with "" the root logger, as in logging.config, for the records the devlog captures while the app runs. They're merged over a base that captures counterweight's records and the app's own at every level, and everyone else's from INFO up, where the app's own are those of the top-level package of the module that defines root's function (__main__ for an app run as a script). Pass {"some_library": logging.DEBUG} to see a library's debug records too, or {"my_app": logging.INFO} to hide the app's own. An app that runs while another has the devlog open, such as one run headless in another's handler, writes its records into that devlog, at the levels the other app set.

TYPE: Mapping[str, int] DEFAULT: frozendict()

title

The title to give the terminal window when the application starts, as SetTitle would, before the first frame is drawn. If None, the terminal keeps the title it has.

TYPE: str | None DEFAULT: None

unclaimed_keys

What a key press does when no handler claims it, by its key, as a browser takes a key's default action unless a listener prevents it. The application reads the terminal raw, so every key reaches it as a key press, including Ctrl+C and Ctrl+Z, which a terminal otherwise turns into signals, and the defaults, DEFAULT_UNCLAIMED_KEYS, give those two what they'd do there: Ctrl+C returns Quit, and Ctrl+Z Suspend.to_shell(). A handler that claims one of those keys, such as one that passes keys on to a program, keeps it from taking its default. Pass {} to give unclaimed keys no defaults, or merge onto the defaults to change some, as in DEFAULT_UNCLAIMED_KEYS | {Key.ControlQ: Quit()}.

TYPE: Mapping[str, AnyControl] DEFAULT: DEFAULT_UNCLAIMED_KEYS

cell_aspect_ratio

How many times taller than it is wide a cell of the terminal's font is, which gradients compute their angles and circles with, so that a 45 degree gradient or a circle looks like one. Most terminal fonts are about 2.

TYPE: float DEFAULT: DEFAULT_CELL_ASPECT_RATIO

recording

Where and how to record the application as an asciicast, which asciinema-player plays back, whether it's headless or not. If None, the application isn't recorded.

TYPE: Recording | None DEFAULT: None

clipboard_handler

What a CopyToClipboard without a handler of its own does with its text, awaited if it returns an awaitable, such as copied.append in a test, which can't reach the controls the app's handlers return. If None, the text goes to the terminal's clipboard over OSC 52, or nowhere when headless. An error it raises is logged rather than stopping the app.

TYPE: Callable[[str], object] | None DEFAULT: None

collect_garbage_between_frames

If True, the default, Python's cyclic garbage collector doesn't run while a frame is generated, from re-running components to writing the frame to the terminal, and runs once after the frame is written instead, if the objects the frame allocated and didn't free call for it, as a browser schedules garbage collection in the idle time between frames. The temporary objects a frame frees before it ends then never trigger a collection, a frame that keeps enough for several triggers one, and the older generations, collected once every so many collections of the youngest, are collected less often, so cyclic garbage is freed later than it would be. Nothing frees the cyclic garbage a frame makes until the frame is written, so memory grows with every cycle a frame drops. The collector is paused for every thread of the process, not just the app's, and isn't touched by a frame that starts with it disabled, such as by gc.disable(), though a frame that paused it enables it again once it's written, even if another thread disabled it meanwhile. Pass False to let it run whenever it would, as an app whose frames make and drop a lot of cyclic garbage should (see When not to pause it).

TYPE: bool DEFAULT: True

viewport

Where the application draws on its terminal: FullScreen, the whole of the alternate screen, or Inline, a region below the prompt as tall as the root's content, which stays in the terminal when the application stops.

TYPE: FullScreen | Inline DEFAULT: FullScreen()

stdout

Where a Print to "stdout" goes, as print writes to sys.stdout. A stream that's the application's terminal, output_stream itself or the same terminal device, shows what's printed above an inline application's region, and any other gets it as it is, as plain text if it isn't a terminal.

TYPE: TextIO DEFAULT: stdout

stderr

Where a Print to "stderr" goes, as stdout does for "stdout".

TYPE: TextIO DEFAULT: stderr

capture_output

If True, the default, sys.stdout and sys.stderr are replaced while the application runs, unless it's headless, with streams that print each line written to them, as a Print of its text to stdout or stderr, from any thread, so a stray print or a warning doesn't land in the middle of what the application draws. They're put back while it's suspended, and when it stops, which writes out any line left unfinished. A program that writes to the terminal itself, rather than through sys.stdout, isn't caught.

TYPE: bool DEFAULT: True

counterweight.FullScreen dataclass

FullScreen(mouse: bool = True)

Draw on the terminal's alternate screen, which the app fills, as a full-screen program like vim does, and hand the main screen back unchanged when the app stops.

mouse class-attribute instance-attribute

mouse: bool = True

Whether to track the mouse, so the app receives mouse events. Tracking takes the mouse from the terminal, so turn it off to leave the terminal's own selection and scrolling to the user.

counterweight.Inline dataclass

Inline(keep_last_frame: bool = True, mouse: bool = False)

Draw in a region below the prompt, as tall as the root's content, at most the terminal's height, with what the app prints above it, in the terminal's scrollback.

The region's top row is the row the cursor is on when the app starts, from its first column, so it draws over the end of a line printed without a newline. The root is a flex item of a column as wide as the terminal, at most as tall as it, so a root taller than the terminal is cut off at the bottom, unless it can shrink, as on the web: keep content that grows in a scroll_area that sticks to the end, and give the root min_height(0), so the scroll area shrinks to fit and shows its newest lines.

keep_last_frame class-attribute instance-attribute

keep_last_frame: bool = True

Whether to leave the region's last frame on the screen when the app stops, with the prompt below it, or to erase it, so the prompt comes back where the region started, as a picker whose result belongs on the next line does.

mouse class-attribute instance-attribute

mouse: bool = False

Whether to track the mouse, so the app receives mouse events over its region. Tracking takes the wheel from the terminal, which is how a user scrolls back through what the app printed, so it's off by default. The terminal reports the mouse on the screen, not the region, so an app that tracks it asks the terminal where the cursor is (CSI 6 n) when it starts and after each resize, and works out where the region is in between. Mouse events above the region are over the terminal's scrollback, so the app drops them.

counterweight.__version__ module-attribute

__version__ = metadata.version(PACKAGE_NAME)

The version of counterweight that's installed, such as "0.1.0".