Skip to content

tui

LOG_FLUSH_SECONDS module-attribute

Python
LOG_FLUSH_SECONDS = 0.05

How often waiting lines are moved into the log pane. Anything that arrives in between is shown together.

LOG_LINES_PER_FLUSH module-attribute

Python
LOG_LINES_PER_FLUSH = 300

The most lines shown per flush, so a flood can never keep the UI from handling keys and clicks.

LOG_BACKLOG module-attribute

Python
LOG_BACKLOG = 5000

How many lines may wait to be shown. When a producer outruns the screen the oldest are skipped, with a notice, rather than growing without bound.

VIEWER_CHECK_SECONDS module-attribute

Python
VIEWER_CHECK_SECONDS = 0.5

How often to check that the viewer is still open, so closing its window ends the session.

LogItem module-attribute

Python
LogItem = LogRecord | LogEvent | Text

Anything that can wait to be shown in the log pane: a logging record, a controller message, or ready made text.

LOCATION_KEY module-attribute

Python
LOCATION_KEY = 'location'

The key, in the style of a log line's file:line, that holds the text a click copies. That is the full path, while the line shows the shorter one.

CONTROL_ICONS module-attribute

Python
CONTROL_ICONS: dict[str, str] = {
    "gen": "↻",
    "run": "â–¶",
    "pause": "‖",
    "step": "⇥",
    "stop": "â– ",
}

The symbol on each control button, by the command it types. Each must be one cell wide in a monospace font, or the row stops lining up. Plain geometric and arrow characters are used because they exist in nearly every font, unlike the emoji style media symbols.

FieldView dataclass

Python
FieldView(
    key: str,
    label: str,
    value: str,
    style: str,
    kind: FieldKind,
    raw: str = "",
)

How one value of the session appears in the status bar.

raw class-attribute instance-attribute

Python
raw: str = ''

What the editor starts with when an editable field is clicked.

ControllerMessage

Python
ControllerMessage(event: ControllerEvent)

Bases: Message

Carries a controller event onto the app's event loop. Posting is thread safe and never blocks the sender.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def __init__(self, event: ControllerEvent) -> None:
    super().__init__()
    self.event = event

SelectableLog

Bases: RichLog

A RichLog whose lines can be selected with the mouse and copied.

Textual only selects text in widgets that say where each piece of text is, and a plain RichLog does not, so dragging across it just scrolled. This one marks every line with its position and highlights the lines a drag touched in full. A line is either selected or not, so what is highlighted is exactly what gets copied. Copying hands over the text cleaned up for pasting.

LogBuffer dataclass

Python
LogBuffer(capacity: int = LOG_BACKLOG)

Thread safe, bounded queue between everything that writes to the log pane and the UI.

Any thread can put, and it never blocks and never grows past capacity. When it is full the oldest item is dropped and counted. The UI takes a few at a time.

capacity class-attribute instance-attribute

Python
capacity: int = LOG_BACKLOG

How many items may wait. Past this the oldest are dropped.

take

Python
take(limit: int) -> tuple[list[LogItem], int]

Up to limit of the oldest items, and how many were dropped since the last call.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def take(self, limit: int) -> tuple[list[LogItem], int]:
    """Up to `limit` of the oldest items, and how many were dropped since the last call."""
    with self._lock:
        count = min(limit, len(self._items))
        items = [self._items.popleft() for _ in range(count)]
        dropped, self._dropped = self._dropped, 0
    return items, dropped

TuiLogHandler

Python
TuiLogHandler(buffer: LogBuffer)

Bases: Handler

Sends logging records to the log pane in place of the terminal handler, which would otherwise write over the screen.

emit only stores the record. Formatting happens later on the UI side, so a runtime that logs on every physics step pays almost nothing for being watched.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def __init__(self, buffer: LogBuffer) -> None:
    super().__init__()
    self._buffer = buffer

FieldEditor

Bases: Input

Inline editor that replaces a field's value while it is being edited.

Cancelled

Bases: Message

The user pressed Escape.

ParamField

Python
ParamField(key: str, kind: FieldKind)

Bases: Horizontal

One labeled value in the status bar.

Clicking an edit field swaps its value for an editor, and clicking a toggle field flips it. The field only reports what the user did. The app passes it on to the controller, which decides whether the change is allowed.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def __init__(self, key: str, kind: FieldKind) -> None:
    super().__init__(id=f"field-{key}", classes=f"-{kind}")
    self.key = key
    self.kind: FieldKind = kind
    self._raw = ""

Edited

Python
Edited(key: str, text: str)

Bases: Message

An edit was committed with Enter.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def __init__(self, key: str, text: str) -> None:
    super().__init__()
    self.key = key
    self.text = text

Toggled

Python
Toggled(key: str)

Bases: Message

A toggle field was clicked.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def __init__(self, key: str) -> None:
    super().__init__()
    self.key = key

StatusBar

Python
StatusBar(
    status: ControllerStatus,
    *,
    title: str,
    subtitle: str = "",
    id: str | None = None,
)

Bases: Horizontal

State badge and the session's parameters, with the editable ones a click away.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def __init__(
    self,
    status: ControllerStatus,
    *,
    title: str,
    subtitle: str = "",
    id: str | None = None,
) -> None:
    super().__init__(id=id)
    self._status = status
    self._title = title
    self._subtitle = subtitle

ExplainButton

Python
ExplainButton()

Bases: Button

Shows and hides the short hint, on the command line, that says what the command being typed will do. It never takes focus, so typing carries on.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def __init__(self) -> None:
    super().__init__("?", id="explain-button")
    self.tooltip = "Say what the command you have typed will do"

ControlButton

Python
ControlButton(
    command: str,
    label: str,
    tooltip: str,
    *,
    disabled: bool,
)

Bases: Button

One of the buttons that control a run. Pressing it types its command. It never takes focus, so typing carries on.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def __init__(
    self, command: str, label: str, tooltip: str, *, disabled: bool
) -> None:
    super().__init__(
        label, id=f"control-{command}", compact=True, disabled=disabled
    )
    self.command = command
    self.tooltip = tooltip

ControlBar

Python
ControlBar(
    shortcuts: list[Binding],
    state: RunState,
    has_runtime: bool,
    *,
    id: str | None = None,
)

Bases: Horizontal

The row of buttons that start, hold, step, and stop a run, each showing its key and lit only when it applies.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def __init__(
    self,
    shortcuts: list[Binding],
    state: RunState,
    has_runtime: bool,
    *,
    id: str | None = None,
) -> None:
    super().__init__(id=id)
    self._shortcuts = shortcuts
    self._enabled = control_states(state, has_runtime)

CommandSuggester

Python
CommandSuggester(commands: Iterable[str])

Bases: Suggester

Completes the command being typed, and also the command after explain, so explain hel becomes explain help.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def __init__(self, commands: Iterable[str]) -> None:
    super().__init__(case_sensitive=False)
    self._commands = tuple(commands)

CommandInput

Python
CommandInput(
    suggestions: Iterable[str], *, id: str | None = None
)

Bases: Input

Command line with Up and Down history and Tab completion.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def __init__(self, suggestions: Iterable[str], *, id: str | None = None) -> None:
    super().__init__(
        placeholder=self.PLACEHOLDER,
        suggester=CommandSuggester(suggestions),
        id=id,
    )
    self._history: list[str] = []
    self._cursor: int | None = None
    self._draft = ""

action_complete

Python
action_complete() -> None

Accepts the suggested completion, the same as pressing Right at the end of the line.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def action_complete(self) -> None:
    """Accepts the suggested completion, the same as pressing Right at the end of the line."""
    self.action_end()
    self.action_cursor_right()

HelpScreen

Python
HelpScreen(
    commands: list[tuple[str, str]],
    keys: list[tuple[str, str]],
    close_keys: list[str],
)

Bases: ModalScreen[None]

Lists the commands and key bindings.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def __init__(
    self,
    commands: list[tuple[str, str]],
    keys: list[tuple[str, str]],
    close_keys: list[str],
) -> None:
    """`close_keys` are the keys that opened the help, which close it too. A modal screen does not pass keys on to the app, so it has to bind them itself."""
    super().__init__()
    self._commands = commands
    self._keys = keys
    self._close_keys = close_keys

ReloadedApp

Python
ReloadedApp(
    controller: ReloadedController,
    backend: ViewerBackend,
    *,
    keys: ReloadedKeySettings | None = None,
    subtitle: str = "",
    watch_css: bool = False,
    explain: bool = True,
    rain_seconds: float = 1.5,
    logs: LogBuffer | None = None,
)

Bases: App[None]

Terminal UI for a Reloaded session.

It owns no session logic. Everything the user types or clicks goes to the ReloadedController, and everything the controller reports comes back as events.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def __init__(
    self,
    controller: ReloadedController,
    backend: ViewerBackend,
    *,
    keys: ReloadedKeySettings | None = None,
    subtitle: str = "",
    watch_css: bool = False,
    explain: bool = True,
    rain_seconds: float = 1.5,
    logs: LogBuffer | None = None,
) -> None:
    """`keys` are the keyboard shortcuts, `watch_css` re-applies `tui.tcss` the moment it is saved, for working on the layout, `explain` sets whether the hint on what the typed command does starts out showing, `rain_seconds` is how long the digital rain plays on the way out, where 0 skips it, and `logs` is a buffer that already holds what was logged before the app started, which the log pane shows first and the app goes on filling."""
    super().__init__(watch_css=watch_css)
    self.shortcuts = shortcut_bindings(keys or ReloadedKeySettings())
    """The keys bound to actions, in the order the footer shows them."""
    for binding in self.shortcuts:
        self.bind(
            binding.key,
            binding.action,
            description=binding.description,
            show=binding.show,
            key_display=binding.key_display,
        )
    self._explain_at_start = explain
    self._rain_seconds = rain_seconds
    self._controller = controller
    self._backend = backend
    self.sub_title = subtitle
    self._saved_handlers: list[logging.Handler] = []
    self._log_handler: TuiLogHandler | None = None
    self._logs = logs if logs is not None else LogBuffer()
    self._quitting = False
    controller.sink = self._deliver

shortcuts instance-attribute

Python
shortcuts = shortcut_bindings(keys or ReloadedKeySettings())

The keys bound to actions, in the order the footer shows them.

action_help_quit

Python
action_help_quit() -> None

Ctrl+C is left for copying text, so say how to quit rather than let Textual name Ctrl+Q, which some terminals never pass along.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def action_help_quit(self) -> None:
    """Ctrl+C is left for copying text, so say how to quit rather than let Textual name Ctrl+Q, which some terminals never pass along."""
    quit_key = next(
        (
            binding.key_display or key_label(binding.key)
            for binding in self.shortcuts
            if binding.action == "quit" and binding.show
        ),
        None,
    )
    message = (
        "Type [b]quit[/b] to quit."
        if quit_key is None
        else f"Press [b]{quit_key}[/b], or type [b]quit[/b], to quit."
    )
    self.notify(
        message,
        title="Do you want to quit?",
    )

render_markup

Python
render_markup(message: str) -> Text

Rich markup to Text, falling back to the literal string if the markup is malformed (e.g. an array repr with square brackets).

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def render_markup(message: str) -> Text:
    """Rich markup to `Text`, falling back to the literal string if the markup is malformed (e.g. an array repr with square brackets)."""
    try:
        return Text.from_markup(message)
    except MarkupError:
        return Text(message)

key_label

Python
key_label(key: str) -> str

Display form of a Textual key name, e.g. ctrl+q becomes Ctrl+Q and f1 becomes F1.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def key_label(key: str) -> str:
    """Display form of a Textual key name, e.g. `ctrl+q` becomes `Ctrl+Q` and `f1` becomes `F1`."""
    return "+".join(part.capitalize() for part in key.split("+"))

shortcut_bindings

Python
shortcut_bindings(
    keys: ReloadedKeySettings,
) -> list[Binding]

One binding per configured key. The first key of an action is shown in the footer, and any others only work.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def shortcut_bindings(keys: ReloadedKeySettings) -> list[Binding]:
    """One binding per configured key. The first key of an action is shown in the footer, and any others only work."""
    actions = (
        ("Generate", "submit('gen')", keys.generate),
        ("Run", "submit('run')", keys.run),
        ("Pause", "toggle_pause", keys.pause),
        ("Step", "submit('step')", keys.step),
        ("Watch", "submit('watch')", keys.watch),
        ("Record", "submit('record')", keys.record),
        ("Explain", "toggle_explain", keys.explain),
        ("Help", "help", keys.help),
        ("Stop", "submit('stop')", keys.stop),
        ("Quit", "quit", keys.quit),
    )
    return [
        Binding(
            key,
            action,
            description,
            show=position == 0,
            key_display="Esc" if key == "escape" else key_label(key),
        )
        for description, action, names in actions
        for position, key in enumerate(names)
    ]

status_fields

Python
status_fields(status: ControllerStatus) -> list[FieldView]

The values shown in the status bar, in order. Fields marked edit open an editor when clicked and toggle fields flip.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def status_fields(status: ControllerStatus) -> list[FieldView]:
    """The values shown in the status bar, in order. Fields marked `edit` open an editor when clicked and `toggle` fields flip."""

    def on_off(on: bool) -> tuple[str, str]:
        return ("on", f"bold {LINK}") if on else ("off", str(INK_MUTED))

    watch, watch_style = on_off(status.watch)
    record, record_style = on_off(status.record)
    speed = f"{status.playback_speed:g}"
    speed_shown = speed_label(status.playback_speed)

    fields = [
        FieldView(
            "seed",
            "seed",
            "none" if status.seed is None else str(status.seed),
            str(INK_MUTED) if status.seed is None else str(INK_STRONG),
            "edit",
            raw="" if status.seed is None else str(status.seed),
        ),
        FieldView(
            "trial",
            "trial",
            str(status.trial_num),
            str(INK_STRONG),
            "edit",
            raw=str(status.trial_num),
        ),
        FieldView("speed", "speed", speed_shown, str(INK_STRONG), "edit", raw=speed),
        FieldView("watch", "watch", watch, watch_style, "toggle"),
        FieldView("record", "record", record, record_style, "toggle"),
        FieldView("last", "last", status.last_command, str(INK_STRONG), "info"),
    ]
    return fields

control_states

Python
control_states(
    state: RunState, has_runtime: bool
) -> dict[str, bool]

Which control buttons apply in state, by the command each one types. A button that does not apply is greyed out.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def control_states(state: RunState, has_runtime: bool) -> dict[str, bool]:
    """Which control buttons apply in `state`, by the command each one types. A button that does not apply is greyed out."""
    idle = state is RunState.IDLE
    running = state is RunState.RUNNING
    paused = state is RunState.PAUSED
    return {
        "gen": idle,
        "run": has_runtime and (idle or paused),
        "pause": running,
        "step": running or paused,
        "stop": running or paused,
    }

run_summary

Python
run_summary(status: ControllerStatus) -> Text | None

How the most recent run ended, or None before the first one. Shown on the log's bottom border, where it has room.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def run_summary(status: ControllerStatus) -> Text | None:
    """How the most recent run ended, or `None` before the first one. Shown on the log's bottom border, where it has room."""
    if status.last_duration is None or status.last_outcome is None:
        return None
    return Text.assemble(
        (" last run ", INK_SECONDARY),
        (
            f"{status.last_duration:.2f}s {status.last_outcome.value} ",
            _OUTCOME_STYLES[status.last_outcome],
        ),
    )

fit_title

Python
fit_title(
    title: str, subtitle: str, available: int
) -> Text

The app title for a status bar with available spare columns: with its subtitle if both fit, alone if only it fits, and nothing otherwise, so it is never cut in half.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def fit_title(title: str, subtitle: str, available: int) -> Text:
    """The app title for a status bar with `available` spare columns: with its subtitle if both fit, alone if only it fits, and nothing otherwise, so it is never cut in half."""
    brand = Text(title, style=f"bold {ACCENT}")
    full = Text.assemble(brand, (f"  {subtitle}", INK_MUTED)) if subtitle else brand
    if full.cell_len <= available:
        return full
    if brand.cell_len <= available:
        return brand
    return Text("")

record_location

Python
record_location(record: LogRecord) -> str

Where a record was logged, as path:line. Pasted into an editor's quick open (Ctrl+P in VS Code) it jumps to that line.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def record_location(record: logging.LogRecord) -> str:
    """Where a record was logged, as `path:line`. Pasted into an editor's quick open (Ctrl+P in VS Code) it jumps to that line."""
    return f"{_path_for_editor(record.pathname, os.getcwd())}:{record.lineno}"

right_aligned

Python
right_aligned(
    text: Text, tail: Text, width: int | None
) -> Text

text followed by tail flush with the right edge of a pane width cells wide: on the last row text takes up once it is wrapped if there is room, and on a row of its own if there is not. With no width to go by, tail just follows after two spaces.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def right_aligned(text: Text, tail: Text, width: int | None) -> Text:
    """`text` followed by `tail` flush with the right edge of a pane `width` cells wide: on the last row `text` takes up once it is wrapped if there is room, and on a row of its own if there is not. With no width to go by, `tail` just follows after two spaces."""
    if not width:
        return Text("  ").append_text(tail)
    rows = text.wrap(_WRAP_CONSOLE, width)
    used = rows[-1].cell_len if rows else 0
    room = width - used - tail.cell_len
    if room >= 2:
        return Text(" " * room).append_text(tail)
    return Text("\n" + " " * max(0, width - tail.cell_len)).append_text(tail)

record_full_location

Python
record_full_location(record: LogRecord) -> str

Where a record was logged, as path:line with the file's full path. This is what a click copies, so it works from any folder, while the log shows the shorter record_location.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def record_full_location(record: logging.LogRecord) -> str:
    """Where a record was logged, as `path:line` with the file's full path. This is what a click copies, so it works from any folder, while the log shows the shorter `record_location`."""
    return f"{os.path.abspath(record.pathname)}:{record.lineno}"

format_record

Python
format_record(
    record: LogRecord, width: int | None = None
) -> Text

One logging record as a line for the log pane: time, level, the message, then where it was logged, flush right when the pane's width is known. Clicking the location copies it.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def format_record(record: logging.LogRecord, width: int | None = None) -> Text:
    """One logging record as a line for the log pane: time, level, the message, then where it was logged, flush right when the pane's `width` is known. Clicking the location copies it."""
    text = Text()
    text.append(
        time.strftime("%H:%M:%S ", time.localtime(record.created)), style=INK_MUTED
    )
    text.append(f"{record.levelname:<9}", style=_LEVEL_STYLES.get(record.levelno, ""))
    text.append_text(render_markup(record.getMessage()))
    location = record_location(record)
    where = Text(
        location,
        style=Style(
            color=str(INK_MUTED), meta={LOCATION_KEY: record_full_location(record)}
        ),
    )
    text.append_text(right_aligned(text, where, width))
    if record.exc_info:
        text.append(
            "\n" + _FORMATTER.formatException(record.exc_info), style=str(DANGER)
        )
    return text

render_log_item

Python
render_log_item(
    item: LogItem, width: int | None = None
) -> Text

Turns whatever was waiting into text, on the UI side so the thread that logged never pays for it. width is how wide the log pane is, which lets a record's location sit flush right.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def render_log_item(item: LogItem, width: int | None = None) -> Text:
    """Turns whatever was waiting into text, on the UI side so the thread that logged never pays for it. `width` is how wide the log pane is, which lets a record's location sit flush right."""
    try:
        if isinstance(item, Text):
            return item
        if isinstance(item, LogEvent):
            return render_markup(item.message) if item.markup else Text(item.message)
        return format_record(item, width)
    except Exception as error:
        return Text(f"(a log line could not be shown: {error})", style=str(DANGER))

selected_text

Python
selected_text(strip: Strip, start: int, end: int) -> str

The text of strip from character start to end (to the end of the line if end is -1), the way it should be pasted.

The log pads a record out so its location sits flush right. That padding is for the eye, so a selection that takes in the location gets the message and the location with two spaces between them, and trailing spaces never come along.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def selected_text(strip: Strip, start: int, end: int) -> str:
    """
    The text of `strip` from character `start` to `end` (to the end of the line if `end` is -1), the way it should be pasted.

    The log pads a record out so its location sits flush right. That padding is for the eye, so a selection that takes in the location gets the message and the location with two spaces between them, and trailing spaces never come along.
    """
    text = strip.text
    end = len(text) if end < 0 else min(end, len(text))
    location_at: int | None = None
    offset = 0
    for segment in strip:
        if location_at is None and segment.style and LOCATION_KEY in segment.style.meta:
            location_at = offset
        offset += len(segment.text)
    if location_at is None:
        return text[start:end].rstrip()
    body_end = len(text[:location_at].rstrip())
    body = text[start : min(end, body_end)] if start < body_end else ""
    location = text[max(start, location_at) : end] if end > location_at else ""
    return "  ".join(part for part in (body, location) if part).rstrip()

highlighted

Python
highlighted(strip: Strip, style: Style) -> Strip

strip with style laid over every segment. Strip.apply_style puts a style underneath what a segment already has, which would leave a line's own colors showing.

Source code in src/mujoco_mojo/utils/layers/reloaded/tui.py
Python
def highlighted(strip: Strip, style: Style) -> Strip:
    """`strip` with `style` laid over every segment. `Strip.apply_style` puts a style underneath what a segment already has, which would leave a line's own colors showing."""
    return Strip(
        [
            Segment(segment.text, segment.style + style if segment.style else style)
            for segment in strip
        ],
        strip.cell_length,
    )