click_extra.capture.recording module¶

Record the screens a terminal shows while a command writes at it.

A command that animates does not print its frames one after another: it prints one, returns the cursor to the start of the line, and prints the next over it. A full-screen program goes further and redraws any cell it likes. The stream therefore says what changed, and the frames only exist once something replays those changes against a screen. TerminalScreen is that screen, and this module notes what it shows over time.

click_extra.capture.recording.CSI_RE = re.compile('\\x1b\\[[0-?]*[ -/]*[@-~]')¶

One control sequence, from the escape that opens it to the final byte ending it.

Broad on purpose: a typed prompt is cut between two characters, never inside an escape, so every sequence has to be recognized whole, see ansi_prefix(). The grammar is the one CSI_PATTERN states, so a sequence with an intermediate byte, like the ESC [ 2 SP q setting the cursor’s shape, counts as one too.

click_extra.capture.recording.DEFAULT_QUANTUM = 0.01¶

Grid a recording’s frame durations are rounded onto, in seconds.

Ten milliseconds is coarser than the jitter two runs of one unchanged command differ by, and finer than any frame worth picturing: the fastest bundled spinner holds one for eighty. See quantize().

click_extra.capture.recording.DEFAULT_RECORDING_HOLD: float | Literal['auto'] = 'auto'¶

How long a recorded animation holds its last frame before starting over.

A recording ends somewhere, and the end is usually its point: the trail filled in, the bar run out, the outcome landed. Looping straight back gives a reader no time to read any of it, and how much time reading takes depends on how much the ending shows, so the default scales with it: see auto_hold(). A declared animation cycles in place and ends nowhere, so it holds for nothing unless a page asks.

click_extra.capture.recording.DEFAULT_RECORDING_BLANK = 0.6¶

Seconds of empty screen closing a recorded animation’s cycle.

Long enough to read as the loop turning over, short enough not to read as the image going blank.

click_extra.capture.recording.DEFAULT_ROWS = 24¶

Height of the terminal a recording runs its command in, in characters.

A width is what a CLI wraps to and therefore what a capture pictures, so it is stated per recording. A height only has to be tall enough that nothing scrolls away before the screen is read, which this is.

click_extra.capture.recording.DEFAULT_SUBMIT = 0.4¶

Seconds a finished command line waits before its output starts, by default.

The beat between the last character and the return key. Long enough that the two read as separate acts, short enough that the animation does not appear to have stalled. See type_line().

click_extra.capture.recording.DEFAULT_TYPING = 0.05¶

Seconds one character of a typed command line takes to appear, by default.

A brisk but readable rate: a reader follows what is being typed rather than watching a line materialize. Slower than any real typist, which is the point, since the line is there to be read and not to be raced. See type_line().

click_extra.capture.recording.READ_POLL = 0.02¶

Seconds a recording waits on the terminal before checking the command again.

Short enough to time a frame of the fastest bundled spinner, whose interval is 80 milliseconds, and long enough that waiting costs no measurable spin.

click_extra.capture.recording.READ_SIZE = 65536¶

Bytes read from the terminal at once.

Well past any single frame, but a pseudo-terminal still hands a large redraw back in several reads, see REDRAW_GAP. The screen holds a sequence split across two reads until its tail arrives.

click_extra.capture.recording.RECORDING_TERM = 'xterm-256color'¶

Terminal a recording names to its command, through TERM.

A full-screen program looks its terminal up in the terminfo database and writes the sequences that entry lists, so the name decides the vocabulary TerminalScreen has to read. Stating it keeps a recording from inheriting whatever terminal it runs from, and gives a program run where TERM is unset, like a CI runner, an entry to find at all.

click_extra.capture.recording.REDRAW_GAP = 0.01¶

Seconds of quiet that close a redraw, in a recording read off a terminal.

A program draws a screen in one write, which a pseudo-terminal hands back in as many reads as its buffer takes. A screen noted between two of them would picture a half-drawn frame. The reads of one redraw follow each other within a fraction of a millisecond, while a program redrawing ten times a second leaves 100 milliseconds between two redraws, so this gap tells them apart.

click_extra.capture.recording.TERMINATE_GRACE = 2.0¶

Seconds a recording waits for the command to exit after SIGTERM.

A command still running when the recording ends, by its duration or by a Ctrl+C, gets SIGTERM first, to clean up after itself. One that ignores it is killed with its descendants once this grace runs out, so the recording never waits forever: see click_extra.execution._stop_process.

class click_extra.capture.recording.Frame(text, duration)[source]¶

Bases: NamedTuple

One screen a recording held, and how long it held it.

Create new instance of Frame(text, duration)

text: str¶

What the terminal showed, ANSI escape sequences included.

duration: float¶

Seconds the screen stayed that way before the next frame replaced it.

class click_extra.capture.recording.ScreenRecorder(*, clock=<built-in function monotonic>, columns=None, rows=None, onlcr=True)[source]¶

Bases: TextIOBase

A stream that keeps every screen written at it, and when.

Stands in for a terminal without being one. It answers isatty() in the affirmative, which is the whole question a spinner or a progress bar asks before deciding to animate, so handing one to a stream argument records an animation in-process: no pseudo-terminal, and therefore every platform.

Note

This is the path a documentation build takes. record_command() is for a command this process does not host, which has no such stream to be handed and needs a pseudo-terminal instead.

Start on a blank screen, with nothing recorded.

Parameters:
  • clock (Callable[[], float]) – what the recorder reads the time off. Stated so a test can hand it a clock that does not depend on how busy the machine is.

  • columns (int | None) – width of the terminal, see TerminalScreen.

  • rows (int | None) – height of the terminal, see TerminalScreen.

  • onlcr (bool) – whether a newline returns the cursor to the start of its row, see TerminalScreen.

isatty()[source]¶

Claim to be a terminal, which is what makes a CLI animate at all.

Return type:

bool

writable()[source]¶

Claim to be writable, as a terminal is.

Return type:

bool

write(text)[source]¶

Replay what was written and note the screen it leaves behind.

A write changing nothing on screen is not noted: a cursor hidden or a style opened leaves the picture as it was, and the screen it did not change keeps the time it first appeared. What is kept is one sample per distinct screen, so a long animation costs as much memory as it has screens rather than as many as it has writes.

Parameters:

text (str) – the stream, control sequences and all.

Return type:

int

Returns:

how much was written, as a stream is expected to report.

frames(*, end=None)[source]¶

Coalesce what was recorded into the frames the screen held.

A write changing nothing on screen is not a frame, see write(), and neither is a screen holding nothing but blanks: an animation erases its line before printing the result underneath, and neither that erasure nor the newline ending it is a picture. Neither is a screen holding nothing but the prompt a recording drew before its command started. What is left is one frame per distinct screen, each lasting until the next replaced it.

Caution

The durations are wall-clock, so they answer to how busy the machine was and differ a little between two runs of the same command. Quantize them before committing what they time.

Parameters:

end (float | None) – when the recording stopped, which is how long the last frame lasted. Defaults to now.

Return type:

tuple[Frame, ...]

Returns:

the frames, in the order they were drawn.

click_extra.capture.recording.record_command(args, *, columns=80, rows=24, background=TerminalBackground.DARK, duration=None, clock=<built-in function monotonic>)[source]¶

Run a command under a pseudo-terminal and record the screens it draws.

An animation is the one thing a pipe cannot capture. A spinner asks whether its stream is a terminal and stays silent when it is not, so a command run the ordinary way prints its result and none of the frames leading to it. Forcing color through the environment does not help: that answers a different question. Only a pseudo-terminal answers this one.

Caution

Unix only. A pseudo-terminal is termios and pty, neither of which Windows ships, and reaching ConPTY means a dependency. Recording a spinner this process hosts needs none of that: hand a ScreenRecorder to its stream and it animates on any platform.

The terminal this runs from is hidden from the command, see CAPTURE_HIDDEN_TERMINAL_VARS, so one machine’s recording matches another’s.

Both the command’s output and its errors are read, the spinner drawing on the latter. What comes back is timed by the wall clock and therefore differs a little between two runs: quantize the durations before committing them.

Parameters:
Return type:

tuple[Frame, ...]

Returns:

the frames the terminal held, in order.

Raises:
  • NotImplementedError – on a platform with no pseudo-terminal.

  • OSError – when the command cannot start. subprocess.Popen raises a FileNotFoundError for a program it cannot find, and a PermissionError for a file it cannot run.

click_extra.capture.recording.quantize(frames, quantum=0.01)[source]¶

Round each frame’s duration onto a grid, so a rerun times it the same.

A recording is timed by the wall clock, so two runs of one unchanged command differ by a few milliseconds a frame. Rounding onto a grid coarser than that jitter lands both on the same numbers, which is what an asset rewritten on every build needs to stay byte-identical.

Caution

This settles jitter and nothing else. A frame the scheduler dropped leaves a shorter recording of the same frames, which no rounding recovers. That case is answered a layer up, by animation_digest(), which fingerprints the frames a cycle holds rather than how many of them were caught.

Parameters:
  • frames (Sequence[Frame]) – what was recorded.

  • quantum (float) – seconds per grid step.

Return type:

tuple[Frame, ...]

Returns:

the same frames, timed on the grid.

Raises:

ValueError – when the grid step is not positive.

click_extra.capture.recording.start_at(frames, start)[source]¶

Drop what a recording showed before start seconds into it.

The animation then opens on the screen that stood at that moment, as a player told where to start does: mpv’s --start and the startAt option of asciinema’s player name the same move. It cuts the seconds a command spends warming up, like a profiler’s tables filling in from nothing.

The time counts from the first frame, which is where the animation starts too, and not from the moment the command was launched. The frame on screen at start keeps what remains of its duration.

Parameters:
  • frames (Sequence[Frame]) – what was recorded.

  • start (float) – seconds to drop. Zero keeps every frame.

Return type:

tuple[Frame, ...]

Returns:

the frames from start on.

Raises:

ValueError – when start is negative, or when it reaches past the last frame, which would leave nothing to draw.

click_extra.capture.recording.end_at(frames, end)[source]¶

Drop what a recording showed after end seconds into it.

The mirror of start_at(), on the same clock: mpv pairs --start with an --end that stops at a time counted from the beginning, not from the start. start_at(end_at(frames, 10), 6) therefore keeps the four seconds between 6 and 10.

The frame on screen at end keeps the part of its duration before it. A recording ending sooner is kept whole.

Parameters:
  • frames (Sequence[Frame]) – what was recorded.

  • end (float) – seconds after the first frame to stop at.

Return type:

tuple[Frame, ...]

Returns:

the frames up to end.

Raises:

ValueError – when end is not positive.

click_extra.capture.recording.ansi_prefix(text, count)[source]¶

The first count printable characters of text, its styling kept.

Slicing a styled line by index cuts an escape sequence in half, and the remains land on the screen as the digits and brackets they are made of. Counting the printable characters alone and keeping every escape passed on the way is what avoids that, and it is also correct rather than merely safe: an escape is drawn nowhere, so the ones before a character are exactly the styling in force at it.

Parameters:
  • text (str) – the line to cut, ANSI escape sequences included.

  • count (int) – how many printable characters to keep. Counted as characters rather than as cells, a keystroke producing one of either.

Return type:

str

Returns:

the prefix, closed by a reset so the styling it opened ends with it.

click_extra.capture.recording.type_line(line, *, typing=0.05, submit=0.4)[source]¶

Frames of a command line appearing one keystroke at a time.

The opening act a terminal recording is usually missing. A command records what it drew and never the invocation that drew it, so an animation starts on output arriving from nowhere. Typing the line first says where it came from, and reads as a session rather than as a clip.

Note

Ordinary frames, carrying no mechanism of their own: they prepend to a recording’s and travel through render_svg() like any others. Everything the picture does for a frame therefore reaches these too, the gutter numbering them and the cursor following the text along, see cursor_cell().

The last frame holds the finished line for submit, which is the beat before the return key. A recording’s own frames follow it.

Parameters:
  • line (str) – the command line to type, already styled as a prompt draws it, see format_cli_prompt().

  • typing (float) – seconds each character takes to appear.

  • submit (float) – seconds the finished line waits before whatever follows.

Return type:

tuple[Frame, ...]

Returns:

one frame per character, in the order they are typed. Empty for an empty line, there being nothing to type.

Raises:

ValueError – when either duration is not positive.

click_extra.capture.recording.record_and_render(args, *, columns=80, rows=24, background=TerminalBackground.DARK, prompt=None, duration=None, start=0.0, end=None, quantum=0.01, hold='auto', blank=0.6, speed=1.0, typing=0.0, submit=0.4, line_numbers=False, emphasize=(), cursor=None, closing_prompt=False, title='', unique_id=None, preset=None, palette=None, font_stack=None, chrome=Chrome(border=None, border_width=1, radius=None, backdrop='none', shadow=None, margin=48, padding=8, opacity=1.0, watermark='generated with click-extra', watermark_color=None))[source]¶

Record a command under a pseudo-terminal and render it as an animated SVG.

Chains record_command(), end_at(), start_at(), quantize() and render(), the way capture() chains the still pipeline. The invocation stands on the screen as a shell prompt before the command starts, styled by the active theme through format_cli_prompt(), so the recording shows what to type to reproduce it. The command’s output lands under it, and a full-screen program’s alternate screen covers it, as on a terminal.

Parameters:
  • args (str | Path | None | Iterable[str | Path | None | Iterable[Iterable[str | Path | None | Iterable[TNestedArgs]]]]) – the command line to record.

  • columns (int) – width of the terminal it runs in, in characters. A recording pins its width up front, so there is no auto here: the pseudo-terminal must exist before the command draws its first line.

  • rows (int) – height of that terminal, in characters.

  • background (TerminalBackground) – chrome the recording is headed for, stated to the command the way a terminal would.

  • prompt (str | None) – command line to display, when it differs from the one run. An empty string draws no prompt at all.

  • duration (float | None) – seconds to record before stopping the command. None records until it exits on its own.

  • start (float) – seconds of the recording to drop, counted from the first screen the command drew, see start_at(). Zero keeps them all.

  • end (float | None) – seconds after that first screen to stop the recording and the command at, see end_at(). None records until duration runs out or the command exits.

  • quantum (float) – grid the frame durations are rounded onto, see quantize().

  • hold (float | Literal['auto']) – extra seconds the last frame stays up, or AUTO_HOLD (the default here) to scale them to that frame’s line count.

  • blank (float) – seconds of empty screen closing the cycle.

  • speed (float) – how much faster to play than recorded. The typed opening is replayed at the same rate as everything else, being part of what the animation shows rather than a pause laid over it.

  • typing (float) – seconds each character of the prompt takes to appear, opening the animation by typing the command out. Zero draws the prompt whole from the first frame, which is what a recording carrying no opening shows. See type_line().

  • submit (float) – seconds the finished command line waits before its output starts. Unused when nothing is typed.

  • line_numbers (bool) – draw each line’s number in a gutter, the prompt counting as the first of them. Every frame takes the gutter of the tallest, see number_frames().

  • emphasize (Sequence[int]) – lines to draw a band behind, see render_svg().

  • cursor (Cursor | None) – the terminal cursor to draw, see Cursor. It follows the text from screen to screen on its own, so a typed opening gets its caret from this and nothing else.

  • closing_prompt (bool) – draw the shell’s prompt under the last frame, which is where it comes back once the command exits, see append_prompt(). Only that frame carries it: the shell has not returned while the command is still drawing. A command stopped with the alternate screen still up gets none, as its screen is no shell’s.

  • title (str) – see render().

  • unique_id (str | None) – see render().

  • preset (TerminalPreset | None) – see render().

  • palette (TerminalPalette | None) – see render().

  • font_stack (str | None) – see render().

  • chrome (Chrome) – see render().

Return type:

tuple[str, int]

Returns:

the rendered SVG document, and the command’s exit code.

Raises:
  • NotImplementedError – on a platform with no pseudo-terminal.

  • OSError – when the command cannot start, see record_command().

  • ValueError – when the command drew nothing to record, when end is not after start, when start reaches past the last screen, or when a stated typing or submit is not positive.