hamingjurv0.1.3

Open source / Python terminal library

Hamingjur

Portable terminal text and input, Kitty graphics, and Silkie extensions for pen, touch, typography, and display control.

licenseMITpython≥ 3.9version0.1.3dependencieswcwidth · jinxed
hamingjur / terminal preview↗
❯ python hello.py
Hello from Hamingjur.
Text. Color. Input. A place to begin.
Illustration of colored vector curves over a terminal grid
Illustrative browser preview · actual rendering happens in your terminal
from hamingjur import Terminal

term = Terminal()
print(term.bold_green("Hello from Hamingjur."))

with term.cbreak():
    key = term.inkey(timeout=1)
    if key:
        print(f"You pressed {key!r}")
Adaptive images and vector fallbackKitty protocols + Silkie extensionsImport namespace: hamingjur

01 / PROJECT OVERVIEW

How Hamingjur fits together.

Start with readable text and ordinary input. Add graphics, richer devices, or precise display feedback through the same Terminal object. Discover capabilities before depending on them.

01 — PORTABLE FOUNDATIONS

Text is still first class.

Colors, cursor movement, Unicode width, full-screen contexts, keyboard input, mouse events, and a headless line editor.

02 — RICHER PROTOCOLS

Pixels, paths, and pens.

Kitty image transport and Silkie vector scenes, shaped text, tablet pressure, multitouch, gestures, and terminal-local ink.

03 — EXPLICIT CONTROL

Ask, then act.

Read capability replies and granted modes. Scope reporting with context managers and release the resources your application owns.

Your Python applicationstate · content · event loop
HamingjurTerminal · encoders · clients
The terminalrendering · shaping · hardware

Silkie renders vector scenes directly. Hamingjur rasterizes compatible scenes locally for Kitty and sixel terminals.

Hamingjur is maintained by Adam DePrince. It is an independent MIT-licensed fork, with inherited work and notices from Jeff Quast, Erik Rose, Avram Lubkin, and other Blessed contributors. Its hamingjur namespace can coexist with upstream blessed.

02 / GET STARTED

Installation & a first program.

A standard install from PyPI or a source checkout includes image preparation and vector rasterization.

Install from PyPI

SHELL
python -m pip install hamingjur

# Or, from a source checkout
python -m pip install -e .

The editable command is for development from the repository root.

Run in a terminal

PYTHON · hello.py
from hamingjur import Terminal

term = Terminal()
with term.fullscreen(), term.cbreak(), term.hidden_cursor():
    print(term.home + term.clear, end="")
    print(term.bold_green("Hello from Hamingjur."))
    print("Press q to exit.")

    while True:
        key = term.inkey(timeout=0.1)
        if key == "q" or key.name == "KEY_ESCAPE":
            break
Rendering follows the output stream. Terminal writers respect term.does_styling. Redirected output can stay escape-free, and NO_COLOR disables styling. Run visual demos interactively with terminal input and output.

03 / FEATURE MAP

Features & terminal support.

The APIs cover both familiar terminal behavior and newer extensions. Encoding a request establishes what your application sent; the terminal’s reply establishes what it supports.

What you needStart hereTerminal requirement
Text, color & layoutTerminal
bold, color_rgb(), move_xy(), length(), wrap()
Terminfo-backed capabilities; Unicode width through wcwidth.
Keyboard, mouse & editinginkey(), async_inkey(), mouse_enabled(), LineEditorReporting modes depend on the terminal. The line editor is headless.
Widget libraryhamingjur.uiOverlapping windows, keyboard and mouse controls, modal dialogs, and themes that follow the terminal’s display preference.
Desktop guide
Raster & adaptive imagesterm.graphics.draw(), prepare(), negotiate()KITTY / SILKIE / SIXEL
Pillow prepares images for the available terminal graphics protocol.
Vectors & shaped textgraphics.scene(), patch(), text_record(), measure_text()SILKIE · f=200
Rendering and shaping happen in the terminal.
Pen, touch, pads & gesturesterm.tablet, term.scroll, term.gesture, key.tabletSILKIE · OSC 777
Discover selector support, capabilities, and granted reporting bits.
Ink & hapticsterm.ink, term.hapticSILKIE
Local ink needs a vector image and a brush; haptics need a permitted device.
Typography & spatial stylingselect_font(), term.depth(), foreground_brightness(), color_gamut(), background_alpha()SILKIE
Visible effects depend on fonts, display headroom, gamut, and spatial settings.
Geometry & presentationterm.window, get_cell_size(), term.display, term.latency, term.frameVT/xterm geometry; Silkie for display reports and presentation feedback.
Clipboard, drops & notificationshamingjur.kitty, term.kitty, ProtocolEventKITTY / SILKIE
Applications own transfer state and policy. Silkie adds notification return routes.
Remote commands & SSH-agent packetsterm.remote_control.call(), term.ssh_agentExplicit terminal permission. Remote control and SSH-agent transport are separate APIs.

04 / WORKING EXAMPLES

From a request to a result.

Each example makes support and ownership explicit. Use the reference below for every argument, return type, and source docstring.

01 — Discover and read tablet events

Aggregate discovery identifies understood selectors. Query the channel for device-related capabilities, then use the reporting mode that the terminal actually grants.

PYTHON · tablet input
from hamingjur import Terminal
from hamingjur.silkie import TabletMode

term = Terminal()
with term.cbreak():
    caps = term.silkie.capabilities(timeout=0.5)
    if caps and caps.supports("tablet-pointer"):
        mode = TabletMode.TOOLS | TabletMode.TOUCH
        with term.tablet.enabled(mode) as granted:
            while granted:
                key = term.inkey(timeout=0.1)
                if key == "q":
                    break
                if key.tablet is not None:
                    event = key.tablet
                    print(event.position, event.pressure, event.tilt)
    else:
        print("Tablet reporting: not supported")

Touchpad coordinates are available through touchpad_position; they are normalized values, rather than physical screen pixels. Reporting contexts restore the previous mode on exit.

02 — Draw an image and release it

The adaptive image API fits your source and negotiates formats and transfer media. Kitty and Silkie acknowledge the upload. Keep the source image if you plan to redraw after a resize.

PYTHON · uses a local photo.png
from PIL import Image
from hamingjur import Terminal

term = Terminal()
result = None
with Image.open("photo.png") as source, term.cbreak():
    try:
        result = term.graphics.draw(
            source, x=0, y=0, columns=40, rows=12
        )
        term.inkey()
    finally:
        if result and result.acknowledged:
            term.graphics.send(
                term.graphics.delete(result.image_id)
            )
        elif result:
            term.graphics.forget(result.image_id)

Use pixel width/height or cell columns/rows, never both. Source formats include packed grayscale, RGB565, RGB/RGBA, PNG, and HDR half-float RGBA where supported. GPU surfaces require an application-owned descriptor.

03 — Send a retained vector scene

Silkie renders this path scene directly. Kitty and sixel receive a rasterized copy. Shaped text, gradients and pressure strokes require native Silkie.

PYTHON · Silkie vector images
from hamingjur import Terminal, graphics

term = Terminal()
with term.cbreak():
    if term.graphics.supports(200):
        records = [
            graphics.vector_record(
                "p", id=1, d="M0,0H240V100H0Z", fill="#183e35"
            ),
            graphics.vector_record(
                "p", id=2, d="M24,76L76,24L128,76Z", fill="#c4e6a8"
            ),
        ]
        try:
            term.graphics.send(graphics.scene(
                records, image_id=7, width=240, height=100, q=1
            ))
            term.inkey()
        finally:
            if term.does_kitty_graphics():
                term.graphics.send(graphics.delete(7, q=2))
            else:
                term.graphics.forget(7)
    else:
        print("Vector graphics: not supported")

04 — Keep input and application state separate

LineEditor handles editing, history, suggestions, grapheme movement, and optional password masking. Your application decides where and when to render.

PYTHON · a headless editor in an event loop
from hamingjur import Terminal, LineEditor, LineHistory

term = Terminal()
editor = LineEditor(history=LineHistory(), max_width=term.width)
with term.cbreak():
    while True:
        print(editor.render(term, row=0, width=term.width),
              end="", flush=True)
        result = editor.feed_key(term.inkey())
        if result.line is not None:
            break
        if result.interrupt or result.eof:
            break

Feed bracketed-paste contents through insert_text(). For asynchronous applications, use await term.async_inkey() in your own async event loop.

05 / API CONTRACTS

Read the reply you received.

Query APIs return different objects. This distinction matters when decoding responses or handling unsupported features.

Terminal.query(sequence, response, timeout)str | None

The full matched response string, or None. It is not a regular-expression match object. Parse the returned string with the appropriate decoder.

Channel.query(timeout)ProtocolEvent | None

A structured Silkie capability report. Inspect fields, integer(), or number(). A selector’s support does not imply attached hardware.

Graphics.query(data, ...)ProtocolEvent | None

A graphics reply. A successful probe has event.payload == "OK". supports() turns a format probe into a boolean.

Terminal.inkey() / async_inkey()Keystroke

A string-compatible key with name and structured protocol_event or tablet properties. Empty input can indicate a timeout.

Graphics.draw(source, ...)DrawnImage | None

An acknowledged image placement; disabled styling returns None. Upload errors raise, and missing acknowledgements raise TimeoutError.

RemoteControl.call(name, payload, ...)decoded response data

Returns the terminal’s JSON data. Refusal raises RemoteControlError; a missing complete reply raises TimeoutError. Terminal permission is required.

  • Restore modes. enabled() reads the existing mode, checks granted bits, and restores the previous value in finally. Leave contexts before suspending and re-enter after resuming.
  • Own resource lifetimes. Release images and uploaded font handles. GPU surface allocation stays with your application. File, shared-memory, and direct transports have different lifecycles.
  • Serialize shared terminal I/O. Complete a chunked transmission before starting another command on that protocol. Queries preserve unrelated keyboard input.
  • Interpret payloads by protocol. event.data decodes base64 only where the protocol defines it. Graphics errors and notification activations may carry plain text.
  • Preserve complete data. Image transmissions, event reports, and retained editing state do not have arbitrary total-size caps. Actual wire ranges and packet sizes still apply; allocation failures propagate.

06 / INTERACTIVE EXAMPLES

Test your terminal.

The interactive showcase probes the current terminal and puts visual samples, live input counters, and capability status together. Unavailable features are marked not supported.

Run the Silkie showcase

From the checkout, with its dependencies installed:

SHELL
PYTHONPATH=. .venv/bin/python bin/silkie_showcase.py

# Keep complete events in a JSONL file
PYTHONPATH=. .venv/bin/python bin/silkie_showcase.py \
    --events events.jsonl
qExitTabInspect detailshHaptic tapcClear inkj / kScroll on small screens

A 120 × 30 terminal leaves room for the visual areas. The script adapts to smaller windows and preserves ink on resize. Use --font or --gpu-surface to provide resources for those optional demonstrations.

For a dedicated drawing application, try python bin/tablet_canvas.py --mode tiles, --mode vectors, or --mode ink after installation. Visual results depend on terminal support, attached hardware, user permissions, and display settings.

07 / SOURCE-DERIVED REFERENCE

The API, in detail.

32 modules · 749 declarations · v0.1.3

Search public functions, methods, properties, and classes. Expand an entry for its exact source signature, complete docstring, fields, and source location.

749 declarations across 32 modules
hamingjur.terminal144 entries

Module containing :class:`Terminal`, the primary API entry point.

terminal.Terminal classAn abstraction for color, style, positioning, and input in the terminal.
Permalink Source ↗
hamingjur.terminal.Terminal(kind: Optional[str]=None, stream: Optional[IO[str]]=None, force_styling: Union[bool, None]=False, kind_fallback: str='xterm-256color', _xtgettcap_data: Optional[TermcapResponse]=None) -> None
An abstraction for color, style, positioning, and input in the terminal.

This keeps the endless calls to ``tigetstr()`` and ``tparm()`` out of your code, acts
intelligently when somebody pipes your output to a non-terminal, and abstracts over the
complexity of unbuffered keyboard input. It uses the terminfo database to remain portable across
terminal types.

Constructor
-----------
Initialize the terminal.

:arg str kind: A terminal string used for capability database, defaults to the value of the
    ``TERM`` environment variable when undefined. If the terminal supports XTGETTCAP
    extension, the 'TN' capability name reported has precedence over 'kind'.

:arg file stream: A file-like object representing the Terminal output.
    Defaults to the original value of :obj:`sys.__stdout__`, like
    :func:`curses.initscr` does.

    If ``stream`` is not a tty, empty Unicode strings are returned for
    all capability values, so things like piping your program output to
    a pipe or file does not emit terminal sequences.

:arg bool force_styling: Whether to force the emission of capabilities
    even if :obj:`sys.__stdout__` does not seem to be connected to a
    terminal. If you want to force styling to not happen, use
    ``force_styling=None``.

    This comes in handy if users are trying to pipe your output through
    something like ``less -r`` or build systems which support decoding
    of terminal sequences.

    When the OS Environment variable FORCE_COLOR_ or CLICOLOR_FORCE_ is
    *non-empty*, styling is used no matter the value specified by
    ``force_styling``.

    Conversely, When OS Environment variable NO_COLOR_ is *non-empty*,
    styling is **not** used no matter the value specified by
    ``force_styling``, FORCE_COLOR_, or CLICOLOR_FORCE_.

    .. _FORCE_COLOR: https://force-color.org/
    .. _CLICOLOR_FORCE: https://bixense.com/clicolors/
    .. _NO_COLOR: https://no-color.org/

:arg str kind_fallback: Terminal kind to use as fallback when the requested ``kind`` is not
    found in jinxed_ virtual terminfo database.  Defaults to ``'xterm-256color'`` which is
    well supported for all capabilities used by hamingjur on all modern terminals.

.. _jinxed: https://github.com/rockhopper-Technologies/jinxed
Fields & constants
CursorShape = _CursorShape
Decrqss = Decrqss
DecPrivateMode = _DecPrivateMode
terminal.Terminal.send methodWrite terminal commands or streamed packets and flush at completion.
Permalink Source ↗
hamingjur.terminal.Terminal.send(sequences: Union[str, Iterable[str]]) -> None
Write terminal commands or streamed packets and flush at completion.
terminal.Terminal.remote_control propertyExplicit Kitty/Silkie remote control, requiring the terminal's permission.
Permalink Source ↗
hamingjur.terminal.Terminal.remote_control -> RemoteControl
Explicit Kitty/Silkie remote control, requiring the terminal's permission.
terminal.Terminal.shell propertyWorking directory and prompt/command integration.
Permalink Source ↗
hamingjur.terminal.Terminal.shell -> Shell
Working directory and prompt/command integration.
terminal.Terminal.query methodQuery a protocol with a response regex, preserving unrelated keyboard input.
Permalink Source ↗
hamingjur.terminal.Terminal.query(sequence: str, response: str, timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS) -> Optional[str]
Query a protocol with a response regex, preserving unrelated keyboard input.
terminal.Terminal.window propertyWindow geometry, sizing requests, screen queries, and title stack.
Permalink Source ↗
hamingjur.terminal.Terminal.window -> Window
Window geometry, sizing requests, screen queries, and title stack.
terminal.Terminal.cell_width propertyPhysical pixels per cell horizontally, or -1 if unavailable.
Permalink Source ↗
hamingjur.terminal.Terminal.cell_width -> int
Physical pixels per cell horizontally, or -1 if unavailable.
terminal.Terminal.cell_height propertyPhysical pixels per cell vertically, or -1 if unavailable.
Permalink Source ↗
hamingjur.terminal.Terminal.cell_height -> int
Physical pixels per cell vertically, or -1 if unavailable.
terminal.Terminal.get_cell_size methodReturn named physical pixel dimensions for a cell, or None if unavailable.
Permalink Source ↗
hamingjur.terminal.Terminal.get_cell_size(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, *, force: bool=False) -> Optional[Size]
Return named physical pixel dimensions for a cell, or None if unavailable.
terminal.Terminal.request_size methodRequest text-area cells or pixels; the terminal may refuse the preference.
Permalink Source ↗
hamingjur.terminal.Terminal.request_size(*, columns: Optional[int]=None, rows: Optional[int]=None, width: Optional[int]=None, height: Optional[int]=None) -> None
Request text-area cells or pixels; the terminal may refuse the preference.
terminal.Terminal.tablet propertyPen, touch, tablet-pad, and tool-action input.
Permalink Source ↗
hamingjur.terminal.Terminal.tablet -> Channel
Pen, touch, tablet-pad, and tool-action input.
terminal.Terminal.scroll propertySmooth scrolling input.
Permalink Source ↗
hamingjur.terminal.Terminal.scroll -> Channel
Smooth scrolling input.
terminal.Terminal.gesture propertyTrackpad and touchscreen gestures.
Permalink Source ↗
hamingjur.terminal.Terminal.gesture -> Channel
Trackpad and touchscreen gestures.
terminal.Terminal.haptic propertyDevice and pointer haptic feedback.
Permalink Source ↗
hamingjur.terminal.Terminal.haptic -> Channel
Device and pointer haptic feedback.
terminal.Terminal.ink propertyTerminal-local pen drawing.
Permalink Source ↗
hamingjur.terminal.Terminal.ink -> Channel
Terminal-local pen drawing.
terminal.Terminal.font propertyFont selection and font state.
Permalink Source ↗
hamingjur.terminal.Terminal.font -> Channel
Font selection and font state.
terminal.Terminal.display propertySilkie display capabilities, desktop preferences, and change reporting.
Permalink Source ↗
hamingjur.terminal.Terminal.display -> DisplayChannel
Silkie display capabilities, desktop preferences, and change reporting.
terminal.Terminal.latency propertyLow-latency rendering control.
Permalink Source ↗
hamingjur.terminal.Terminal.latency -> Channel
Low-latency rendering control.
terminal.Terminal.frame propertyFrame presentation timing.
Permalink Source ↗
hamingjur.terminal.Terminal.frame -> Channel
Frame presentation timing.
terminal.Terminal.accessibility propertySilkie image and text annotations and screen-reader announcements.
Permalink Source ↗
hamingjur.terminal.Terminal.accessibility -> Accessibility
Silkie image and text annotations and screen-reader announcements.
terminal.Terminal.speech propertyProgram-controlled speech and Voice Lock styles on the Silkie host.
Permalink Source ↗
hamingjur.terminal.Terminal.speech -> SpeechChannel
Program-controlled speech and Voice Lock styles on the Silkie host.
terminal.Terminal.ssh_agent propertyExplicit SSH-agent queries and packet exchanges over the terminal.
Permalink Source ↗
hamingjur.terminal.Terminal.ssh_agent -> AgentChannel
Explicit SSH-agent queries and packet exchanges over the terminal.
terminal.Terminal.depth methodStyle stereo text depth/phase; calling the style resets both after the text.
Permalink Source ↗
hamingjur.terminal.Terminal.depth(millidegrees: Optional[int]=None, *, pixels: Optional[float]=None, phase: Optional[float]=None) -> FormattingString
Style stereo text depth/phase; calling the style resets both after the text.
terminal.Terminal.kitty propertyKitty protocol output and restoring contexts.
Permalink Source ↗
hamingjur.terminal.Terminal.kitty -> Kitty
Kitty protocol output and restoring contexts.
terminal.Terminal.silkie propertySilkie capability discovery, input, typography, ink and timing channels.
Permalink Source ↗
hamingjur.terminal.Terminal.silkie -> Silkie
Silkie capability discovery, input, typography, ink and timing channels.
terminal.Terminal.graphics propertyStreaming image/scene commands and capability/service queries.
Permalink Source ↗
hamingjur.terminal.Terminal.graphics -> Graphics
Streaming image/scene commands and capability/service queries.
terminal.Terminal.foreground_brightness methodSet HDR foreground brightness as a percentage of SDR white.
Permalink Source ↗
hamingjur.terminal.Terminal.foreground_brightness(percent: int=100) -> FormattingString
Set HDR foreground brightness as a percentage of SDR white.
terminal.Terminal.background_brightness methodSet HDR background brightness as a percentage of SDR white.
Permalink Source ↗
hamingjur.terminal.Terminal.background_brightness(percent: int=100) -> FormattingString
Set HDR background brightness as a percentage of SDR white.
terminal.Terminal.background_alpha methodSet cell background opacity (0 transparent, 100 opaque).
Permalink Source ↗
hamingjur.terminal.Terminal.background_alpha(percent: int=100) -> FormattingString
Set cell background opacity (0 transparent, 100 opaque).
terminal.Terminal.color_gamut methodSelect an RGB color in sRGB (0), Display P3 (1), or Rec2020 (2).
Permalink Source ↗
hamingjur.terminal.Terminal.color_gamut(red: int, green: int, blue: int, *, gamut: int=0, background: bool=False) -> FormattingString
Select an RGB color in sRGB (0), Display P3 (1), or Rec2020 (2).
terminal.Terminal.underline_style methodSet underline style: off, single, double, curly, dotted or dashed (0–5).
Permalink Source ↗
hamingjur.terminal.Terminal.underline_style(style: int=1) -> FormattingString
Set underline style: off, single, double, curly, dotted or dashed (0–5).
terminal.Terminal.underline_color methodSet the independent underline color using RGB components.
Permalink Source ↗
hamingjur.terminal.Terminal.underline_color(red: int, green: int, blue: int) -> FormattingString
Set the independent underline color using RGB components.
terminal.Terminal.unscroll methodBring lines back from scrollback using Kitty's SD extension.
Permalink Source ↗
hamingjur.terminal.Terminal.unscroll(lines: int=1) -> str
Bring lines back from scrollback using Kitty's SD extension.
terminal.Terminal.clear_to_scrollback methodMove the screen's text and images into scrollback, then clear it.
Permalink Source ↗
hamingjur.terminal.Terminal.clear_to_scrollback() -> str
Move the screen's text and images into scrollback, then clear it.
terminal.Terminal.reset_bold methodReset bold independently of faint.
Permalink Source ↗
hamingjur.terminal.Terminal.reset_bold() -> str
Reset bold independently of faint.
terminal.Terminal.reset_faint methodReset faint independently of bold.
Permalink Source ↗
hamingjur.terminal.Terminal.reset_faint() -> str
Reset faint independently of bold.
terminal.Terminal.kind propertyRead-only property: Terminal kind determined on class initialization.
Permalink Source ↗
hamingjur.terminal.Terminal.kind -> str
Read-only property: Terminal kind determined on class initialization.

:rtype: str
terminal.Terminal.does_styling propertyRead-only property: Whether this class instance may emit sequences.
Permalink Source ↗
hamingjur.terminal.Terminal.does_styling -> bool
Read-only property: Whether this class instance may emit sequences.

:rtype: bool
terminal.Terminal.is_a_tty propertyRead-only property: Whether :attr:`~.stream` is a terminal.
Permalink Source ↗
hamingjur.terminal.Terminal.is_a_tty -> bool
Read-only property: Whether :attr:`~.stream` is a terminal.

:rtype: bool
terminal.Terminal.height propertyRead-only property: Height of the terminal (in number of lines).
Permalink Source ↗
hamingjur.terminal.Terminal.height -> int
Read-only property: Height of the terminal (in number of lines).

:rtype: int
terminal.Terminal.width propertyRead-only property: Width of the terminal (in number of columns).
Permalink Source ↗
hamingjur.terminal.Terminal.width -> int
Read-only property: Width of the terminal (in number of columns).

:rtype: int
terminal.Terminal.pixel_height propertyRead-only property: Height of the terminal (in pixels).
Permalink Source ↗
hamingjur.terminal.Terminal.pixel_height -> int
Read-only property: Height of the terminal (in pixels).

:rtype: int
terminal.Terminal.pixel_width propertyRead-only property: Width of terminal (in pixels).
Permalink Source ↗
hamingjur.terminal.Terminal.pixel_width -> int
Read-only property: Width of terminal (in pixels).

:rtype: int
terminal.Terminal.location context managerContext manager for temporarily moving the cursor.
Permalink Source ↗
hamingjur.terminal.Terminal.location(x: Optional[int]=None, y: Optional[int]=None) -> Generator[None, None, None]
Context manager for temporarily moving the cursor.

:arg int x: horizontal position, from left, *0*, to right edge of screen, *self.width - 1*.
:arg int y: vertical position, from top, *0*, to bottom of screen, *self.height - 1*.
:return: a context manager.
:rtype: Iterator

Move the cursor to a certain position on entry, do any kind of I/O, and upon exit
let you print stuff there, then return the cursor to its original position:


.. code-block:: python

    term = Terminal()
    with term.location(y=0, x=0):
        for row_num in range(term.height-1):
            print('Row #{row_num}')
    print(term.clear_eol + 'Back to original location.')

Specify ``x`` to move to a certain column, ``y`` to move to a certain
row, both, or neither. If you specify neither, only the saving and
restoration of cursor position will happen. This can be useful if you
simply want to restore your place after doing some manual cursor
movement.

Calls cannot be nested: only one should be entered at a time.

.. note:: The argument order *(x, y)* differs from the return value order *(y, x)*
    of :meth:`get_location`, or argument order *(y, x)* of :meth:`move`. This is
    for API Compatibility with the blessings library, sorry for the trouble!
terminal.Terminal.get_location methodReturn tuple (row, column) of cursor position.
Permalink Source ↗
hamingjur.terminal.Terminal.get_location(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS) -> Tuple[int, int]
Return tuple (row, column) of cursor position.

When :attr:`is_a_tty` is False, no sequences are transmitted or response
awaited, and the value ``(-1, -1)`` is returned without inquiry.

:arg float timeout: Return after time elapsed in seconds with value ``(-1, -1)`` indicating
    that the remote end did not respond.
:rtype: tuple
:returns: cursor position as tuple in form of ``(y, x)``.  Always ensure the return value is
    checked for ``(-1, -1)``.

The location of the cursor is determined by emitting the ``u7`` terminal capability for the
VT100 `Query Cursor Position
<https://www2.ccs.neu.edu/research/gpc/VonaUtils/vona/terminal/vtansi.htm#status>`_.
This elicits a response from a reply string described by capability ``u6`` for the VT100
response.

The ``(y, x)`` return value matches the parameter order of the :meth:`move_yx` capability.
The following sequence should cause the cursor to not move at all::

    >>> term = Terminal()
    >>> term.move_yx(*term.get_location())

And the following should assert True with a terminal:

    >>> term = Terminal()
    >>> given_y, given_x = 10, 20
    >>> with term.location(y=given_y, x=given_x):
    ...     result_y, result_x = term.get_location()
    ...
    >>> assert given_x == result_x, (given_x, result_x)
    >>> assert given_y == result_y, (given_y, result_y)
terminal.Terminal.get_fgcolor methodReturn tuple (r, g, b) of default foreground color.
Permalink Source ↗
hamingjur.terminal.Terminal.get_fgcolor(timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS, bits: int=16) -> Tuple[int, int, int]
Return tuple (r, g, b) of default foreground color.

This returns the terminal's default color for uncolored text, not any
currently active color set by escape sequences.

When :attr:`is_a_tty` is False, no sequences are transmitted or response
awaited, and the value ``(-1, -1, -1)`` is returned without inquiry.

:arg float timeout: Return after time elapsed in seconds with value ``(-1, -1, -1)``
    indicating that the remote end did not respond.
:arg int bits: Bits per channel: 16 (default, 0-65535, 48-bit total) or
    8 (0-255, 24-bit total).
:rtype: tuple
:returns: foreground color as tuple in form of ``(r, g, b)``.  When a timeout is specified,
    always ensure the return value is checked for ``(-1, -1, -1)``.
:raises ValueError: When bits is not 8 or 16.

The foreground color is determined by emitting an `OSC 10 color query
<https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands>`_.

See also :meth:`~.Terminal.get_bgcolor` for querying the background color.

.. note::

    The default return value is 16-bit, matching the XParseColor specification of the
    underlying protocol. For most uses, 8-bit values are preferred::

        rgb = term.get_fgcolor(bits=8)
        term.color_rgb(*rgb)  # reset foreground to default
terminal.Terminal.get_bgcolor methodReturn tuple (r, g, b) of default background color.
Permalink Source ↗
hamingjur.terminal.Terminal.get_bgcolor(timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS, bits: int=16) -> Tuple[int, int, int]
Return tuple (r, g, b) of default background color.

This returns the terminal's default background color, not any currently
active color set by escape sequences.

When :attr:`is_a_tty` is False, no sequences are transmitted or response
awaited, and the value ``(-1, -1, -1)`` is returned without inquiry.

:arg float timeout: Return after time elapsed in seconds with value ``(-1, -1, -1)``
    indicating that the remote end did not respond.
:arg int bits: Bits per channel: 16 (default, 0-65535, 48-bit total) or
    8 (0-255, 24-bit total).
:rtype: tuple
:returns: background color as tuple in form of ``(r, g, b)``.  When a timeout is specified,
    always ensure the return value is checked for ``(-1, -1, -1)``.
:raises ValueError: If bits is not 8 or 16.

The background color is determined by emitting an `OSC 11 color query
<https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands>`_.

See also :meth:`~.Terminal.get_fgcolor` for querying the foreground color.

.. note::

    The default return value is 16-bit, matching the XParseColor specification of the
    underlying protocol. For most uses, 8-bit values are preferred::

        rgb = term.get_bgcolor(bits=8)
        term.on_color_rgb(*rgb)  # reset background to default
terminal.Terminal.get_fgcolor_hex methodReturn default foreground color as hex string.
Permalink Source ↗
hamingjur.terminal.Terminal.get_fgcolor_hex(timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS, maybe_short: bool=False) -> str
Return default foreground color as hex string.

:arg float timeout: Return after time elapsed in seconds with empty string
    if the remote end did not respond.
:arg bool maybe_short: If True, return ``#RGB`` when possible.
:returns: Hex color string (``#RRGGBB`` or ``#RGB``), or empty string on
    timeout or when :attr:`is_a_tty` is False.

Convenience wrapper combining :meth:`get_fgcolor` and
:func:`~hamingjur.colorspace.rgb_to_hex`.
terminal.Terminal.get_bgcolor_hex methodReturn default background color as hex string.
Permalink Source ↗
hamingjur.terminal.Terminal.get_bgcolor_hex(timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS, maybe_short: bool=False) -> str
Return default background color as hex string.

:arg float timeout: Return after time elapsed in seconds with empty string
    if the remote end did not respond.
:arg bool maybe_short: If True, return ``#RGB`` when possible.
:returns: Hex color string (``#RRGGBB`` or ``#RGB``), or empty string on
    timeout or when :attr:`is_a_tty` is False.

Convenience wrapper combining :meth:`get_bgcolor` and
:func:`~hamingjur.colorspace.rgb_to_hex`.
terminal.Terminal.get_device_attributes methodQuery the terminal's Device Attributes (DA1).
Permalink Source ↗
hamingjur.terminal.Terminal.get_device_attributes(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> Optional[DeviceAttribute]
Query the terminal's Device Attributes (DA1).

When :attr:`is_a_tty` is False, no sequences are transmitted or response
awaited, and ``None`` is returned without inquiry.

If a Device Attributes query fails to respond within the ``timeout``
specified, ``None`` is returned. If this was the first query for device
attributes, all subsequent queries return ``None`` unless ``force=True``
is set (sticky failure).

**Responses are cached indefinitely** unless ``force=True`` is
specified.

.. note:: A ``timeout`` value should be set to avoid blocking when the
    terminal does not respond to DA1 queries, which may happen with some
    kinds of "dumb" terminals.

:arg float timeout: Timeout in seconds to await terminal response
:arg bool force: Force active terminal inquiry even if cached result exists
    or previous query failed
:rtype: DeviceAttribute or None
:returns: DeviceAttribute instance with terminal capabilities, or None
    if unsupported/timeout

.. code-block:: python

    term = Terminal()

    # Query device attributes
    da = term.get_device_attributes(timeout=TERMINAL_QUERY_TIMEOUT_SECONDS)
    if da is not None:
        print(f"Service class: {da.service_class}")
        print(f"Supports sixel: {da.supports_sixel}")
        print(f"Extensions: {sorted(da.extensions)}")
terminal.Terminal.get_software_version methodReturn the terminal's software name and version.
Permalink Source ↗
hamingjur.terminal.Terminal.get_software_version(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> Optional[SoftwareVersion]
Return the terminal's software name and version.

A non-empty ``TERM_PROGRAM`` value takes precedence and no inquiry is made,
otherwise an XTVERSION query is sent to the terminal and the response is
returned as a :class:`SoftwareVersion` instance. Returns ``None`` only if both
methods fail.

**Only Successful responses are cached indefinitely** unless ``force=True`` is specified.
Unlike other query methods, there is no "sticky failure", failed queries are not cached and
are retried.

.. note:: A ``timeout`` value should be set to avoid blocking when the
    terminal does not respond to XTVERSION queries, which may happen with
    some kinds of "dumb" terminals.

:arg float timeout: Timeout in seconds to await terminal response
:arg bool force: Force active terminal inquiry even if cached result exists
:rtype: SoftwareVersion or None
:returns: SoftwareVersion instance with terminal name and version, or None
    if unsupported/timeout

.. code-block:: python

    term = Terminal()

    # Query software version
    sv = term.get_software_version(timeout=TERMINAL_QUERY_TIMEOUT_SECONDS)
    if sv is not None:
        print(f"Terminal: {sv.name} {sv.version}")
terminal.Terminal.does_sixel methodQuery whether the terminal supports sixel graphics.
Permalink Source ↗
hamingjur.terminal.Terminal.does_sixel(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> bool
Query whether the terminal supports sixel graphics.

Sixel is a bitmap graphics format supported by some modern terminal
emulators, allowing applications to display inline images.

When :attr:`is_a_tty` is False, no sequences are transmitted or response
awaited, and ``False`` is returned without inquiry.

This method calls :meth:`get_device_attributes` to query the terminal's
capabilities and checks for sixel support (extension 4 in the DA1 response).
Results are cached, so subsequent calls are fast.

:arg float timeout: Timeout in seconds to await terminal response. When
    ``None`` (default), the query may block indefinitely.
:arg bool force: Bypass cache and re-query the terminal
:rtype: bool
:returns: ``True`` if terminal supports sixel graphics, ``False`` otherwise
terminal.Terminal.detect_ambiguous_width methodDetect whether the terminal renders ambiguous width characters as width 1 or 2.
Permalink Source ↗
hamingjur.terminal.Terminal.detect_ambiguous_width(timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS, fallback: int=1, force: bool=False) -> int
Detect whether the terminal renders ambiguous width characters as width 1 or 2.

:arg float timeout: Timeout in seconds for any single cursor position response.
:arg int fallback: Value to return on timeout, invalid measurement, or not a tty.
:arg bool force: Measure again, bypassing the cache and the ``AMBIGUOUS_WIDE`` override.
:rtype: int
:returns: 1 for "Ambiguous width as narrow", 2 is "Ambiguous width as wide"

East Asian ambiguous width characters render as either single (1) or double width (2)
depending on terminal settings.  This measures the rendered width of U+00A7 (SECTION SIGN),
an early Unicode character with East Asian Width property "Ambiguous", by drawing and
erasing it at the current cursor position. Ambiguous width is used in "legacy" contexts,
like with BIG5, gbk, or shift-jis encoding, and most especially in mathematics or artwork,
like on terminal bulletin board systems, https://bbs.modem.xyz/encodings.html#big5, and
sometimes simply as a user preference, for neat and tidy vertical alignment. `configuration
<https://wezterm.org/config/lua/config/treat_east_asian_ambiguous_width_as_wide.html>`_ is
usually required to enable "ambiguous width as wide".

The result is cached, assigned to :attr:`ambiguous_width`, and returned, and used
automatically by subsequent alignment methods, :meth:`length`, :meth:`wrap`, :meth:`ljust`,
:meth:`rjust`, and :meth:`center`.

Example usage::

    >>> term = Terminal()
    >>> term.length('\u00a7')
    1
    >>> term.detect_ambiguous_width()
    2
    >>> term.length('\u00a7')
    2

When :attr:`is_a_tty` is False, no sequences are transmitted or response awaited, and
``fallback`` is returned without inquiry.
terminal.Terminal.detect_term_program methodDetect the terminal software name applied to python wcwidth correction tables.
Permalink Source ↗
hamingjur.terminal.Terminal.detect_term_program(timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> str
Detect the terminal software name applied to python wcwidth correction tables.

:arg float timeout: Timeout in seconds to await an XTVERSION response.
:arg bool force: Detect again, bypassing the cache.
:rtype: str
:returns: Terminal name, wcwidth alias, or an empty string when unknown.

A non-empty ``TERM_PROGRAM`` environment value or a unique ``TERM`` that matches wcwidth
other than 'xterm' returns that value. Otherwise, an in-band XTVERSION query is made and its
software name is returned if responded.

The result is cached, assigned to :attr:`term_program`, and used automatically by width or
alignment methods, :meth:`length`, :meth:`wrap`, :meth:`ljust`, :meth:`rjust`, and
:meth:`center`.

When :attr:`is_a_tty` or :attr:`does_styling` is False, or no keyboard is available,
XTVERSION inquiries are not made and timeout does not apply, and the result is not cached.
terminal.Terminal.get_dec_mode methodQuery the state of a DEC Private Mode (DECRQM).
Permalink Source ↗
hamingjur.terminal.Terminal.get_dec_mode(mode: Union[int, _DecPrivateMode], timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> DecModeResponse
Query the state of a DEC Private Mode (DECRQM).

Sends a DECRQM query to the terminal and returns a
:class:`DecModeResponse` instance. Use the helper methods like
:meth:`DecModeResponse.is_supported` or
:meth:`DecModeResponse.is_enabled` and others to interpret the result.

When :attr:`is_a_tty` is False, no sequences are transmitted or response
awaited, and the :class:`DecModeResponse` value returned is always
:attr:`DecModeResponse.NOT_QUERIED`.

In some cases a ``timeout`` value should be set, as it is possible for a
terminal that succeeds :attr:`is_a_tty` to fail to respond to DEC Private
Modes, such as in a CI Build Service or other "dumb" terminal, even a few
popular modern ones such as Konsole.  The first query may also make an XTVERSION
query, :meth:`get_software_version`, to avoid a DECRQM query to terminals with
leaky output (Terminal.app), so the total elapsed time may exceed *timeout*.

If a DEC Private mode query fails to respond within the ``timeout``
specified, the :class:`DecModeResponse` value returned is
:attr:`DecModeResponse.NO_RESPONSE`. If this was the first DEC Private
mode query, all subsequent queries return a :class:`DecModeResponse`
value of :attr:`DecModeResponse.NOT_QUERIED` unless ``force=True`` is
set.

**Repeat queries return the (cached) known state immediately** without
re-inquiry unless ``force=True``.  Although there are special cases
where a user may re-configure their terminal settings after the state
was requested by an application, the application is generally restarted
to recognize the new settings rather than to repeatedly re-inquire about
their latest value!

:arg mode: DEC Private Mode to query
:type mode: DecPrivateMode | int
:arg float timeout: Timeout in seconds to await terminal response
:arg bool force: Force active terminal inquery in all cases
:rtype: DecModeResponse
:returns: DecModeResponse instance
:raises TypeError: If mode is not DecPrivateMode or int

.. code-block:: python

    term = Terminal()

    # Query synchronized output support
    response = term.get_dec_mode(DecPrivateMode.SYNCHRONIZED_OUTPUT)
    if response.supported:
        print("Synchronized output is available")
terminal.Terminal.dec_modes_enabled context managerContext manager for temporarily enabling DEC Private Modes.
Permalink Source ↗
hamingjur.terminal.Terminal.dec_modes_enabled(*modes: Union[int, _DecPrivateMode], timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS) -> Generator[None, None, None]
Context manager for temporarily enabling DEC Private Modes.

On entry, queries each mode's current state using get_dec_mode().

For modes that are supported but currently disabled, enables them
and tracks them for restoration. On exit, disables all modes that
were enabled by this context manager, restoring original state.

Unsupported modes are silently ignored.

:arg modes: One or more DEC Private Mode numbers or enum members
:arg float timeout: Timeout in seconds for get_dec_mode calls
:raises TypeError: If mode is not DecPrivateMode or int

.. code-block:: python

    term = Terminal()

    # Enable synchronized output temporarily
    with term.dec_modes_enabled(DecPrivateMode.SYNCHRONIZED_OUTPUT):
        # All output will be atomic
        print("Frame 1")
        print("Frame 2")
terminal.Terminal.dec_modes_disabled context managerContext manager for temporarily disabling DEC Private Modes.
Permalink Source ↗
hamingjur.terminal.Terminal.dec_modes_disabled(*modes: Union[int, _DecPrivateMode], timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS) -> Generator[None, None, None]
Context manager for temporarily disabling DEC Private Modes.

Uses the same logic as dec_modes_enabled but inverted: disables
supported modes that are currently enabled on entry, then restores
them on exit.

:arg modes: One or more DEC Private Mode numbers or enum members
:arg float timeout: Timeout in seconds for get_dec_mode calls
:raises TypeError: If mode is not DecPrivateMode or int
terminal.Terminal.does_mouse methodCheck if the terminal supports the specified mouse tracking features.
Permalink Source ↗
hamingjur.terminal.Terminal.does_mouse(*, clicks: bool=True, report_pixels: bool=False, report_drag: bool=False, report_motion: bool=False, timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS) -> bool
Check if the terminal supports the specified mouse tracking features.

This method queries terminal support for the same DEC modes that
:meth:`mouse_enabled` would enable with the given parameters.

:arg bool clicks: Check for basic click reporting (default True)
:arg bool report_pixels: Check for pixel coordinate reporting
:arg bool report_drag: Check for drag reporting
:arg bool report_motion: Check for motion reporting
:arg float timeout: Timeout for mode queries (default 1.0s)
:returns: True if all required modes are supported
:rtype: bool

Example::

    if term.does_mouse(report_drag=True, report_pixels=True):
        with term.mouse_enabled(report_drag=True, report_pixels=True):
            # Use mouse tracking with drag and pixel support
            pass
terminal.Terminal.does_inband_resize methodCheck if the terminal supports in-band window resize notifications.
Permalink Source ↗
hamingjur.terminal.Terminal.does_inband_resize(timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS) -> bool
Check if the terminal supports in-band window resize notifications.

This method queries whether the terminal supports DEC mode 2048
(IN_BAND_WINDOW_RESIZE), which allows receiving resize events as
in-band sequences through :meth:`inkey` instead of relying on
SIGWINCH signals.

:arg float timeout: Timeout for mode query (default 1.0s)
:returns: True if in-band resize notifications are supported
:rtype: bool

Example::

    if term.does_inband_resize():
        with term.notify_on_resize():
            # Use in-band resize events
            pass
    else:
        # Fall back to SIGWINCH or other methods
        pass
terminal.Terminal.does_bracketed_paste methodCheck if the terminal supports bracketed paste mode.
Permalink Source ↗
hamingjur.terminal.Terminal.does_bracketed_paste(timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS) -> bool
Check if the terminal supports bracketed paste mode.

Bracketed paste mode (DEC mode 2004) wraps pasted text in special
sequences so applications can distinguish pasted text from typed input.

.. seealso:: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Bracketed-Paste-Mode

:arg float timeout: Timeout for mode query (default 1.0s).
:returns: True if bracketed paste mode is supported.
:rtype: bool
terminal.Terminal.does_synchronized_output methodCheck if the terminal supports synchronized output.
Permalink Source ↗
hamingjur.terminal.Terminal.does_synchronized_output(timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS) -> bool
Check if the terminal supports synchronized output.

Synchronized output (DEC mode 2026) allows applications to batch
screen updates, preventing tearing during rapid redraws.

.. seealso:: https://gist.github.com/christianparpart/d8a62cc1ab659194571ec44c8e0a7085

:arg float timeout: Timeout for mode query (default 1.0s).
:returns: True if synchronized output is supported.
:rtype: bool
terminal.Terminal.does_grapheme_clustering methodCheck if the terminal supports grapheme clustering.
Permalink Source ↗
hamingjur.terminal.Terminal.does_grapheme_clustering(timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS) -> bool
Check if the terminal supports grapheme clustering.

Grapheme clustering (DEC mode 2027) enables Unicode grapheme cluster
aware cursor movement and display.

.. seealso:: https://mitchellh.com/writing/grapheme-clusters-in-terminals

:arg float timeout: Timeout for mode query (default 1.0s).
:returns: True if grapheme clustering is supported.
:rtype: bool
terminal.Terminal.does_focus_events methodCheck if the terminal supports focus in/out event reporting.
Permalink Source ↗
hamingjur.terminal.Terminal.does_focus_events(timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS) -> bool
Check if the terminal supports focus in/out event reporting.

Focus event reporting (DEC mode 1004) sends escape sequences when
the terminal window gains or loses focus.

.. seealso:: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-FocusIn_FocusOut

:arg float timeout: Timeout for mode query (default 1.0s).
:returns: True if focus event reporting is supported.
:rtype: bool
terminal.Terminal.get_xtgettcap methodQuery terminal capabilities via XTGETTCAP (DCS +q).
Permalink Source ↗
hamingjur.terminal.Terminal.get_xtgettcap(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False, caps: Optional[Iterable[str]]=None) -> Optional[TermcapResponse]
Query terminal capabilities via XTGETTCAP (DCS +q).

When *caps* is specified, only those capabilities are returned. When unspecified, all known
XTGETTCAP capabilities are queried and returned.  All results from XTGETTCAP are memoized
permanently, unlike DECRQSS :meth:`get_decrqss` which may change. Using ``force=True`` to
re-retrieve any request.

:arg float timeout: Timeout in seconds.
:arg bool force: Always re-query for latest values.
:arg caps: Capability names to query.  When specified, only these additional capabilities
    may queried (incremental on cache).  when unspecified, it as though `all=True` was used.
:rtype: TermcapResponse
terminal.Terminal.does_xtgettcap methodWhether the terminal supports XTGETTCAP (DCS +q) queries.
Permalink Source ↗
hamingjur.terminal.Terminal.does_xtgettcap(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> bool
Whether the terminal supports XTGETTCAP (DCS +q) queries.

Support is determined at class initialization and so this call is always non-blocking unless
the *force* argument is used.

:arg float timeout: Timeout in seconds.
:arg bool force: Bypass cached result.
:rtype: bool
terminal.Terminal.get_font_coverage methodQuery which codepoints of *text* the terminal font has a glyph for.
Permalink Source ↗
hamingjur.terminal.Terminal.get_font_coverage(text: str, timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> FontCoverage
Query which codepoints of *text* the terminal font has a glyph for.

:arg str text: Text whose codepoints to query.  Each distinct codepoint is asked
    about once, in batches, however long *text* is and however often it repeats.
:arg float timeout: Seconds to wait for each round-trip.  A long *text* takes
    several, so this bounds a single exchange and not the call.
:arg bool force: Discard the cached protocol probe and every cached codepoint
    result, and query the terminal again.
:rtype: FontCoverage
:returns: Per-codepoint coverage.  When *text* is empty, or when neither
    protocol answers, an empty result whose :attr:`~.FontCoverage.supported`
    is False, which is falsey.  A codepoint the terminal declined to answer
    for is reported through :attr:`~.FontCoverage.unknown` and is not asked
    about again until ``force``.

Two protocols are tried, mintty's *Font Glyph Coverage Enquiry* (``OSC 7771``)
first, then the *Glyph Protocol* ``'q'`` verb (``APC 25a1``) of rio.  The
protocol that answers is remembered, as is the result for every codepoint
queried, so repeated calls over overlapping text cost no further round-trips.

    >>> coverage = term.get_font_coverage('─│')
    >>> if not coverage:
    ...     print('terminal cannot say')
    ... elif not coverage.covers('─│'):
    ...     print('falling back to ASCII box drawing')

.. warning:: This reports *coverage of codepoints by a font*, and nothing more.
    Neither protocol can be asked about a grapheme cluster, and neither reports
    on the shaping that turns codepoints into drawn glyphs: ligatures, mark
    positioning, ``ZWJ`` joining, ``VS-15``/``VS-16`` presentation, contextual
    forms, or fallback to another font.  A cluster whose codepoints are all
    covered may still fail to draw, and one with uncovered codepoints may draw
    perfectly.  The text presentation watch, ``'⌚︎'``, renders correctly
    on terminals whose font has no glyph for ``U+FE0E``, as no font does.
    Deciding what will render is a heuristic built on this answer, and hamingjur
    does not make it for you: see :ref:`detect-tofus.py` for one such heuristic.

.. seealso::
    https://github.com/mintty/mintty/wiki/CtrlSeqs#font-glyph-coverage-enquiry
    and https://rapha.land/introducing-glyph-protocol-for-terminals/
terminal.Terminal.does_kitty_graphics methodCheck if the terminal supports the Kitty graphics protocol.
Permalink Source ↗
hamingjur.terminal.Terminal.does_kitty_graphics(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> bool
Check if the terminal supports the Kitty graphics protocol.

Sends a minimal Kitty graphics query and checks for an ``OK``
response.  Supported by kitty and WezTerm.

.. seealso:: https://sw.kovidgoyal.net/kitty/graphics-protocol/

:arg float timeout: Timeout in seconds.
:arg bool force: Bypass cached result.
:rtype: bool
terminal.Terminal.get_iterm2_capabilities methodQuery iTerm2 capabilities via OSC 1337;Capabilities.
Permalink Source ↗
hamingjur.terminal.Terminal.get_iterm2_capabilities(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> Optional['ITerm2Capabilities']
Query iTerm2 capabilities via OSC 1337;Capabilities.

When :attr:`is_a_tty` is False, returns ``None``.

Responses are cached unless *force* is True.

.. seealso:: https://iterm2.com/documentation-escape-codes.html

:arg float timeout: Timeout in seconds for each sub-query.  On the
    first call, an additional CPR probe may be performed to enable
    fast negative detection, so total elapsed time may exceed
    *timeout* for terminals that do not respond.
:arg bool force: Bypass cached result.
:rtype: ITerm2Capabilities or None
terminal.Terminal.does_iterm2 methodCheck if the terminal answers the ``OSC 1337`` capabilities report.
Permalink Source ↗
hamingjur.terminal.Terminal.does_iterm2(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> bool
Check if the terminal answers the ``OSC 1337`` capabilities report.

:arg float timeout: Timeout in seconds.
:arg bool force: Bypass cached result.
:rtype: bool
terminal.Terminal.does_iterm2_graphics methodCheck if the terminal supports the iTerm2 inline image protocol.
Permalink Source ↗
hamingjur.terminal.Terminal.does_iterm2_graphics(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> bool
Check if the terminal supports the iTerm2 inline image protocol.

Draws a transparent image using iTerm2 protocol and detects for expected cursor position
advance.  Uses two CPR requests, before and after, for fast negative detection.

.. seealso:: https://iterm2.com/documentation-images.html

:arg float timeout: Timeout in seconds for each cursor position query.
:arg bool force: Bypass cached result.
:rtype: bool
:returns: True when the cursor advanced a single column, False when the terminal is
    1-column width or did not answer a cursor position report within timeout.
terminal.Terminal.does_kitty_notifications methodCheck if the terminal supports Kitty desktop notifications (OSC 99).
Permalink Source ↗
hamingjur.terminal.Terminal.does_kitty_notifications(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> bool
Check if the terminal supports Kitty desktop notifications (OSC 99).

Sends an OSC 99 query with a CPR boundary guard for fast negative
detection.  Currently supported only by kitty.

.. seealso:: https://sw.kovidgoyal.net/kitty/desktop-notifications/

:arg float timeout: Timeout in seconds for each sub-query.  On the
    first call, an additional CPR probe may be performed to enable
    fast negative detection, so total elapsed time may exceed
    *timeout* for terminals that do not respond.
:arg bool force: Bypass cached result.
:rtype: bool
terminal.Terminal.does_kitty_clipboard methodCheck if the terminal supports the Kitty clipboard protocol (mode 5522).
Permalink Source ↗
hamingjur.terminal.Terminal.does_kitty_clipboard(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> bool
Check if the terminal supports the Kitty clipboard protocol (mode 5522).

Queries DEC private mode 5522 (Bracketed Paste MIME) by :meth:`get_dec_mode`.

:arg float timeout: Timeout in seconds.
:arg bool force: Bypass cached result.
:rtype: bool
terminal.Terminal.does_kitty_pointer_shapes methodQuery Kitty mouse pointer shape support (OSC 22).
Permalink Source ↗
hamingjur.terminal.Terminal.does_kitty_pointer_shapes(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> Optional[str]
Query Kitty mouse pointer shape support (OSC 22).

Returns the current pointer shape name if supported, or ``None``
if the terminal does not respond.  Uses a CPR boundary guard for
fast negative detection.

.. seealso:: https://sw.kovidgoyal.net/kitty/pointer-shapes/

:arg float timeout: Timeout in seconds.
:arg bool force: Bypass cached result.
:rtype: str or None
terminal.Terminal.does_osc52_clipboard methodDetect OSC 52 clipboard support without reading the clipboard.
Permalink Source ↗
hamingjur.terminal.Terminal.does_osc52_clipboard(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> bool
Detect OSC 52 clipboard support without reading the clipboard.

This method uses non-intrusive detection to avoid triggering user-facing clipboard
permission prompts, **DA1 extension 52** and **XTGETTCAP ``Ms``** fields.  These methods are
preferred over sending an actual OSC 52 read request (``\x1b]52;c;?\a``), which may trigger
a clipboard permission dialog in many modern terminals.

:arg float timeout: Timeout in seconds for each sub-query.
:arg bool force: Bypass cached result.
:rtype: bool
terminal.Terminal.clipboard_copy methodCopy text to the system clipboard via OSC 52.
Permalink Source ↗
hamingjur.terminal.Terminal.clipboard_copy(text: str, selection: str='c') -> None
Copy text to the system clipboard via OSC 52.

Writes an OSC 52 set sequence to the terminal output stream.
Most modern terminals accept clipboard writes without any user
prompt.

The sequence is written unconditionally when :attr:`does_styling` is ``True``.  If the
terminal does not support OSC 52, the sequence should be ignored by the terminal.

:arg str text: The text to copy to the clipboard.
:arg str selection: The X11 selection target -- ``'c'`` for
    clipboard (default), ``'p'`` for primary selection, or
    ``'s'`` for secondary.  Most terminals only honor ``'c'``.
terminal.Terminal.clipboard_paste methodRead the system clipboard via OSC 52.
Permalink Source ↗
hamingjur.terminal.Terminal.clipboard_paste(timeout: Optional[float]=10, selection: str='c') -> Optional[str]
Read the system clipboard via OSC 52.

Sends an OSC 52 query (``\x1b]52;c;?\a``) and waits for the terminal to respond with the
clipboard contents.

.. warning::

    Many modern terminals display a permission dialog when an application reads the
    clipboard.  The user must approve the dialog before the terminal sends a response.

    The default timeout of 10 seconds allows time for human interaction.  If the user denies
    the dialog, or no response is received within given timeout, this method returns
    ``None``.

:arg float timeout: Timeout in seconds.  A generous timeout is recommended because the user
    may need to interact with a permission dialog.
:arg str selection: The X11 selection target -- ``'c'`` for clipboard (default),
    ``'p'`` for primary.
:rtype: str or None
:returns: The clipboard text, or ``None`` if denied or timeout is reached.
terminal.Terminal.get_color_scheme methodQuery the terminal's color scheme preference (dark or light mode).
Permalink Source ↗
hamingjur.terminal.Terminal.get_color_scheme(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> Optional[str]
Query the terminal's color scheme preference (dark or light mode).

Sends a ``CSI ? 996 n`` Device Status Report query.  Terminals that support color-scheme
reporting respond with ``CSI ? 997 ; Ps n`` where *Ps* is ``1`` for dark mode or ``2`` for
light mode.  Uses a CPR boundary guard for fast negative detection.

This relates to Mode 2031 (``COLOR_PALETTE_UPDATES``) (not implemented).

.. seealso::

    `Color palette update notifications
    <https://contour-terminal.org/vt-extensions/color-palette-update-notifications/>`_

:arg float timeout: Timeout in seconds.
:arg bool force: Bypass cached result.
:rtype: str or None
:returns: ``'dark'``, ``'light'``, or ``None`` if unsupported.
terminal.Terminal.does_kitty_query methodDetect Kitty with XTGETTCAP query extensions.
Permalink Source ↗
hamingjur.terminal.Terminal.does_kitty_query(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> bool
Detect Kitty with XTGETTCAP query extensions.

This is a trifle convenience wrapper of :meth:`get_xtgettcap()`.

This method probes for ``kitty-query-name`` support.  A successful response indicates that
some set of Kitty query extensions are available.

To retrieve their values, follow up with :meth:`get_xtgettcap` directly, for example:

.. code-block:: python

    >>> term = Terminal()
    >>> term.does_kitty_query()
    True
    >>> term.get_xtgettcap(caps=[f"kitty-query-{key}" for key in [
        "font_family", "font_size", "dpi_x", "dpi_y"]])
    TermcapResponse(supported=True, capabilities={
        'kitty-query-font_family': 'NotoSansMono-Regular',
        'kitty-query-font_size': '19',
        'kitty-query-dpi_x': '96',
        'kitty-query-dpi_y': '96'})

:arg float timeout: Timeout in seconds.
:arg bool force: Bypass cached result.
:rtype: bool
terminal.Terminal.get_decrqss methodQuery terminal state via DECRQSS (Request Status String).
Permalink Source ↗
hamingjur.terminal.Terminal.get_decrqss(setting_id: str=Decrqss.SGR, timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS) -> Optional[str]
Query terminal state via DECRQSS (Request Status String).

Sends ``DCS $ q <setting_id> ST`` and decodes the response.
Returns the parameter value string on success, with the echoed
setting identifier stripped.  Returns ``None`` when the terminal
does not support DECRQSS or the setting is invalid.

Results are not cached -- DECRQSS queries runtime state that
may change between calls (cursor style, margins, SGR, etc.).

Use :class:`~hamingjur.Terminal.Decrqss` for setting
identifiers::

    term = Terminal()
    term.get_decrqss(term.Decrqss.DECSCUSR)  # cursor style
    term.get_decrqss(term.Decrqss.DECSTBM)   # scroll region

.. seealso::

    `DECRQSS specification
    <https://vt100.net/docs/vt510-rm/DECRQSS.html>`_

The first query may also make an XTVERSION query, :meth:`get_software_version`,
to avoid a DECRQSS query to terminals with leaky output (Terminal.app).

:arg str setting_id: Setting identifier to query (default: SGR).
:arg float timeout: Timeout in seconds.
:rtype: str or None
terminal.Terminal.does_decrqss methodDetect DECRQSS (Request Status String) support.
Permalink Source ↗
hamingjur.terminal.Terminal.does_decrqss(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> bool
Detect DECRQSS (Request Status String) support.

Sends a ``DECRQSS`` query for the current SGR state.  A valid
response indicates the terminal supports status string queries.

.. seealso::

    `DECRQSS specification
    <https://vt100.net/docs/vt510-rm/DECRQSS.html>`_

:arg float timeout: Timeout in seconds.
:arg bool force: Bypass cached result.
:rtype: bool
terminal.Terminal.does_styled_underlines methodDetect extended underline style support (curly, dotted, dashed).
Permalink Source ↗
hamingjur.terminal.Terminal.does_styled_underlines(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> bool
Detect extended underline style support (curly, dotted, dashed).

Queries the terminal's ``Smulx`` terminfo capability via XTGETTCAP.
When supported, the terminal can render underline styles beyond the
standard single underline, such as ``CSI 4:3 m`` (curly).

:arg float timeout: Timeout in seconds for XTGETTCAP query.
:arg bool force: Bypass cached result.
:rtype: bool
terminal.Terminal.does_colored_underlines methodDetect colored underline support (``CSI 58;2;r;g;b m``).
Permalink Source ↗
hamingjur.terminal.Terminal.does_colored_underlines(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> bool
Detect colored underline support (``CSI 58;2;r;g;b m``).

Queries the terminal's ``Setulc`` terminfo capability via XTGETTCAP.

:arg float timeout: Timeout in seconds for XTGETTCAP query.
:arg bool force: Bypass cached result.
:rtype: bool
terminal.Terminal.does_text_sizing methodDetect Kitty text sizing protocol support (OSC 66).
Permalink Source ↗
hamingjur.terminal.Terminal.does_text_sizing(timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> TextSizingResult
Detect Kitty text sizing protocol support (OSC 66).

Tests width and scale text sizing by sending OSC 66 probes and
measuring cursor position delta.  Supported terminals may write
up to 2 destructive spaces at the current cursor position, while
unsupported terminals typically produce no output.

Responses are cached unless *force* is True.

:arg float timeout: Timeout in seconds for each cursor position query.
:arg bool force: Bypass cached result.
:rtype: TextSizingResult
:returns: Result with ``.width`` and ``.scale`` boolean attributes.
terminal.Terminal.mouse_enabled context managerContext manager for enabling mouse tracking with various reporting modes.
Permalink Source ↗
hamingjur.terminal.Terminal.mouse_enabled(*, clicks: bool=True, report_pixels: bool=False, report_drag: bool=False, report_motion: bool=False, timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS) -> Generator[None, None, None]
Context manager for enabling mouse tracking with various reporting modes.

Enables mouse event reporting with sensible defaults, and always
enables SGR extended mouse mode (1006).

:arg bool clicks: Enable basic click reporting (default True)
:arg bool report_pixels: Report pixel coordinates instead of cell coordinates
:arg bool report_drag: Report mouse drag events (button held while moving)
:arg bool report_motion: Report all mouse motion events
:arg float timeout: Timeout for mode queries (default 1.0s)

The reporting modes have precedence: motion > drag > clicks. Enabling
a higher-precedence mode automatically includes lower modes.

Example::

    with term.mouse_enabled():
        # Basic click tracking
        inp = term.inkey()
        if inp.name and inp.name.startswith('MOUSE_'):
            print(f"Clicked at {inp.x}, {inp.y}")

    with term.mouse_enabled(report_drag=True):
        # Track clicks and drags
        pass

    with term.mouse_enabled(report_motion=True, report_pixels=True):
        # Track all motion with pixel coordinates
        pass
terminal.Terminal.bracketed_paste context managerContext manager for enabling bracketed paste mode.
Permalink Source ↗
hamingjur.terminal.Terminal.bracketed_paste(timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS) -> Generator[None, None, None]
Context manager for enabling bracketed paste mode.

When enabled, pasted text is wrapped with special escape sequences,
allowing applications to distinguish pasted content from typed input.

:arg float timeout: Timeout for mode query (default 1.0s)

Example::

    with term.bracketed_paste():
        inp = term.inkey()
        if inp.name == 'BRACKETED_PASTE':
            pasted_text = inp.text
            print(f"You pasted: {pasted_text}")
terminal.Terminal.synchronized_output context managerContext manager for enabling synchronized output mode.
Permalink Source ↗
hamingjur.terminal.Terminal.synchronized_output(timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS) -> Generator[None, None, None]
Context manager for enabling synchronized output mode.

Buffers all terminal output until the context exits, eliminating screen flicker during
redraws. Perfect for animations and full-screen updates.

:arg float timeout: Timeout for mode query (default 1.0s)
terminal.Terminal.focus_events context managerContext manager for enabling focus event reporting.
Permalink Source ↗
hamingjur.terminal.Terminal.focus_events(timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS) -> Generator[None, None, None]
Context manager for enabling focus event reporting.

Reports when the terminal window gains or loses focus, useful for pausing animations or
updating status indicators.

:arg float timeout: Timeout for mode query (default 1.0s)
terminal.Terminal.notify_on_resize context managerReceive resize events through inline reports or a scoped SIGWINCH fallback.
Permalink Source ↗
hamingjur.terminal.Terminal.notify_on_resize(timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS) -> Generator[None, None, None]
Receive resize events through inline reports or a scoped SIGWINCH fallback.

When enabled, the terminal will automatically send resize events as in-band sequences
whenever the window size changes. These events are received by :meth:`inkey` as
keystroke events with :attr:`~.Keystroke.name` equal to ``'RESIZE_EVENT'``.

The new dimensions are automatically cached and available immediately through the
standard :attr:`height`, :attr:`width`, :attr:`pixel_height`, and :attr:`pixel_width`
properties without additional ioctl system calls.

When inline reporting is unavailable on Unix, a pipe wakes both inkey() and
async_inkey() on SIGWINCH and synthesizes the same RESIZE_EVENT. Enter the signal
fallback on the main thread. The previous signal handler is chained and restored.

:arg float timeout: Timeout for mode query (default 1.0s)

Example::

    with term.notify_on_resize():
        while True:
            inp = term.inkey(timeout=0.1)
            if inp.name == 'RESIZE_EVENT':
                # Dimensions updated automatically
                redraw_display(term.height, term.width)
            elif inp == 'q':
                break
terminal.Terminal.get_sixel_height_and_width methodQuery sixel graphics pixel dimensions.
Permalink Source ↗
hamingjur.terminal.Terminal.get_sixel_height_and_width(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> Tuple[int, int]
Query sixel graphics pixel dimensions.

Returns the maximum height and width in pixels for sixel graphics
rendering. Detection order (from most to least reliable):

1. XTWINOPS 16t (CSI 16 t) - Character cell size, multiplied by rows/cols
2. XTWINOPS 14t (CSI 14 t) - Text area size in pixels
3. XTSMGRAPHICS - Sixel graphics query
4. TIOCSWINSZ / In-band resize - System ioctl / event pixel dimensions

The cell-based calculation (method 1) is preferred because it accounts
for the actual drawable text area, excluding window margins and
decorations.

When :attr:`is_a_tty` is False, no sequences are transmitted or response
awaited, and ``(-1, -1)`` is returned without inquiry.

:arg float timeout: Timeout in seconds for queries
:arg bool force: Bypass cache and re-query the terminal
:rtype: tuple
:returns: ``(height, width)`` in pixels, or ``(-1, -1)`` if unsupported/timeout
terminal.Terminal.get_sixel_colors methodQuery number of sixel color registers (XTSMGRAPHICS).
Permalink Source ↗
hamingjur.terminal.Terminal.get_sixel_colors(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> int
Query number of sixel color registers (XTSMGRAPHICS).

Returns the maximum number of color registers available for sixel
graphics rendering. If XTSMGRAPHICS query fails but the terminal
advertises Sixel support via DA1 (Device Attributes), returns 256
as a sensible default.

When :attr:`is_a_tty` is False, no sequences are transmitted or response
awaited, and ``-1`` is returned without inquiry.

:arg float timeout: Timeout in seconds for both possible queries
:arg bool force: Bypass cache and re-query the terminal
:rtype: int
:returns: Number of color registers, 256 if DA1 advertises sixel but
    XTSMGRAPHICS fails, or ``-1`` if unsupported/timeout
terminal.Terminal.get_cell_height_and_width methodQuery character cell pixel dimensions (XTWINOPS).
Permalink Source ↗
hamingjur.terminal.Terminal.get_cell_height_and_width(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> Tuple[int, int]
Query character cell pixel dimensions (XTWINOPS).

Returns the height and width in pixels of a single character cell.

When :attr:`is_a_tty` is False, no sequences are transmitted or response
awaited, and ``(-1, -1)`` is returned without inquiry.

:arg float timeout: Timeout in seconds for the query
:arg bool force: Bypass cache and re-query the terminal
:rtype: tuple
:returns: ``(height, width)`` in pixels, or ``(-1, -1)`` if unsupported/timeout
terminal.Terminal.invalidate_geometry methodForget cached cell/window pixels after a resize, font change, or reconnection.
Permalink Source ↗
hamingjur.terminal.Terminal.invalidate_geometry() -> None
Forget cached cell/window pixels after a resize, font change, or reconnection.
terminal.Terminal.get_kitty_keyboard_state methodQuery the current Kitty keyboard protocol flags.
Permalink Source ↗
hamingjur.terminal.Terminal.get_kitty_keyboard_state(timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> Optional[KittyKeyboardProtocol]
Query the current Kitty keyboard protocol flags.

Sends a Kitty keyboard protocol query to the terminal and returns a
:class:`KittyKeyboardProtocol` instance with the current flags. This
method is not normally used directly, rather it is used by the
:meth:`enable_kitty_keyboard` context manager on entrance to discover
and restore the previous state on exit.

When :attr:`is_a_tty` is False, no sequences are transmitted or response
awaited, and ``None`` is returned.

In many cases a ``timeout`` value (in seconds) should be set, as it is
possible for a terminal that succeeds :attr:`is_a_tty` to fail to respond
to either Kitty keyboard protocol state request, or the simple device
attribute request query carried with it! And not just "dumb" terminals
fail to respond, even some fairly modern terminals like Konsole.

If a Kitty keyboard protocol query fails to respond within the
``timeout`` specified, ``None`` is returned. If this was the first Kitty
keyboard protocol query, all subsequent queries return ``None`` unless
``force=True`` is set.

**No state caching is performed** - each call re-queries the terminal unless
the first query previously failed (sticky failure) and ``force=False``.

:arg float timeout: Timeout in seconds to await terminal response
:arg bool force: Force active terminal inquiry in all cases
:rtype: KittyKeyboardProtocol or None
:returns: KittyKeyboardProtocol instance with current flags, or None if unsupported/timeout
terminal.Terminal.enable_kitty_keyboard context managerContext manager that enables Kitty keyboard protocol features.
Permalink Source ↗
hamingjur.terminal.Terminal.enable_kitty_keyboard(*, disambiguate: bool=True, report_events: bool=False, report_alternates: bool=False, report_all_keys: bool=False, report_text: bool=False, mode: int=1, timeout: Optional[float]=TERMINAL_QUERY_TIMEOUT_SECONDS, force: bool=False) -> Generator[None, None, None]
Context manager that enables Kitty keyboard protocol features.

:arg bool disambiguate: Enable disambiguated escape codes (fixes issues
    with Esc vs sequences)
:arg bool report_events: Report key repeat and release events
:arg bool report_alternates: Report shifted and base layout keys for shortcuts
:arg bool report_all_keys: Report all keys as escape codes (including text keys)
:arg bool report_text: Report associated text with key events (requires report_all_keys)
:arg int mode: Protocol mode (1=set/clear specified flags, 2=set only, 3=clear only)
:arg float timeout: Timeout for querying current flags before setting new ones
:arg bool force: Force sequences to be emitted even if timeout previously occurred

Always queries current state before setting new flags and restores previous state on exit.

Example::

    with term.enable_kitty_keyboard(disambiguate=True):
        # Now Alt+C won't conflict with Ctrl+C
        key = term.inkey()
        if key.alt and key.is_alt('c'):
            print("Alt+C pressed")

.. note:: A ``timeout`` value should be set to avoid blocking when the
    terminal does not respond to DA1 or kitty protocol queries, which
    may happen with some kinds of "dumb" terminals, even some modern
    terminals like Konsole.
terminal.Terminal.fullscreen context managerContext manager that switches to secondary screen, restoring on exit.
Permalink Source ↗
hamingjur.terminal.Terminal.fullscreen() -> Generator[None, None, None]
Context manager that switches to secondary screen, restoring on exit.

Under the hood, this switches between the primary screen buffer and
the secondary one. The primary one is saved on entry and restored on
exit.  Likewise, the secondary contents are also stable and are
faithfully restored on the next entry::

    with term.fullscreen():
        main()

.. note:: There is only one primary and one secondary screen buffer.
   :meth:`fullscreen` calls cannot be nested, only one should be
   entered at a time.
terminal.Terminal.hidden_cursor context managerContext manager that hides the cursor, setting visibility on exit.
Permalink Source ↗
hamingjur.terminal.Terminal.hidden_cursor() -> Generator[None, None, None]
Context manager that hides the cursor, setting visibility on exit.

    with term.hidden_cursor():
        main()

.. note:: :meth:`hidden_cursor` calls cannot be nested: only one
    should be entered at a time.
terminal.Terminal.cursor_shape context managerContext manager that sets cursor shape, restoring default on exit.
Permalink Source ↗
hamingjur.terminal.Terminal.cursor_shape(style: Union[int, str]=_CursorShape.STEADY_BLOCK) -> Generator[None, None, None]
Context manager that sets cursor shape, restoring default on exit.

:arg style: A :class:`CursorShape` constant or string name
    (e.g. ``'blinking_bar'``).

Uses DECSCUSR (DEC Set Cursor Style) escape sequences::

    with term.cursor_shape(term.CursorShape.BLINKING_BAR):
        main()

String names are also accepted::

    with term.cursor_shape('steady_underline'):
        main()

On exit, the cursor is reset to the terminal default (DECSCUSR 0).

.. note:: DECSCUSR is supported by most modern terminals including
    xterm, VTE-based terminals, iTerm2, Windows Terminal, kitty,
    ghostty, alacritty, and WezTerm.
terminal.Terminal.no_line_wrap context managerContext manager that disables line wrapping, enabling on exit.
Permalink Source ↗
hamingjur.terminal.Terminal.no_line_wrap() -> Generator[None, None, None]
Context manager that disables line wrapping, enabling on exit.

Uses DEC Auto Wrap Mode (DECAWM) to control whether text reaching the
right edge wraps to the next line::

    with term.no_line_wrap():
        print(term.move_x(0) + 'x' * 200)  # Clips, doesn't wrap

On exit, line wrapping is unconditionally enabled as terminals should
prefer line-wrapping mode for normal operation.

.. note:: :meth:`no_line_wrap` calls cannot be nested: only one
    should be entered at a time.
terminal.Terminal.scroll_region context managerContext manager that sets a scrolling region, resetting on exit.
Permalink Source ↗
hamingjur.terminal.Terminal.scroll_region(top: int=0, height: Optional[int]=None) -> Generator[None, None, None]
Context manager that sets a scrolling region, resetting on exit.

:arg int top: Top row of the scrolling region (0-indexed). Defaults to 0.
:arg int height: Number of rows in the scrolling region. Defaults to
    ``self.height - top`` (extending to the bottom of the screen).
:return: a context manager.
:rtype: Iterator

A scrolling region restricts scrolling to a portion of the screen. When text
scrolls within the region, content outside the region remains fixed. This is
useful for creating interfaces with fixed headers, footers, or status bars::

    with term.fullscreen(), term.scroll_region(top=1, height=term.height - 2):
        # row 0 and the last row remain fixed
        # scrolling happens only in the middle region
        for i in range(100):
            print(f'Line {i}')

The cursor position may be reset to the home position when the scroll region
changes. Use :meth:`move_yx` to reposition as needed after entering the
context.

.. note:: :meth:`scroll_region` calls cannot be nested: only one
    should be entered at a time.
terminal.Terminal.move_xy methodA callable string that moves the cursor to the given ``(x, y)`` screen coordinates.
Permalink Source ↗
hamingjur.terminal.Terminal.move_xy(x: int, y: int) -> str
A callable string that moves the cursor to the given ``(x, y)`` screen coordinates.

:arg int x: horizontal position, from left, *0*, to right edge of screen, *self.width - 1*.
:arg int y: vertical position, from top, *0*, to bottom of screen, *self.height - 1*.
:rtype: ParameterizingString
:returns: Callable string that moves the cursor to the given coordinates
terminal.Terminal.move_yx methodA callable string that moves the cursor to the given ``(y, x)`` screen coordinates.
Permalink Source ↗
hamingjur.terminal.Terminal.move_yx(y: int, x: int) -> str
A callable string that moves the cursor to the given ``(y, x)`` screen coordinates.

:arg int y: vertical position, from top, *0*, to bottom of screen, *self.height - 1*.
:arg int x: horizontal position, from left, *0*, to right edge of screen, *self.width - 1*.
:rtype: ParameterizingString
:returns: Callable string that moves the cursor to the given coordinates
terminal.Terminal.move_left propertyMove cursor 1 cells to the left, or callable string for n>1 cells.
Permalink Source ↗
hamingjur.terminal.Terminal.move_left -> FormattingOtherString
Move cursor 1 cells to the left, or callable string for n>1 cells.
terminal.Terminal.move_right propertyMove cursor 1 or more cells to the right, or callable string for n>1 cells.
Permalink Source ↗
hamingjur.terminal.Terminal.move_right -> FormattingOtherString
Move cursor 1 or more cells to the right, or callable string for n>1 cells.
terminal.Terminal.move_up propertyMove cursor 1 or more cells upwards, or callable string for n>1 cells.
Permalink Source ↗
hamingjur.terminal.Terminal.move_up -> FormattingOtherString
Move cursor 1 or more cells upwards, or callable string for n>1 cells.
terminal.Terminal.move_down propertyMove cursor 1 or more cells downwards, or callable string for n>1 cells.
Permalink Source ↗
hamingjur.terminal.Terminal.move_down -> FormattingOtherString
Move cursor 1 or more cells downwards, or callable string for n>1 cells.
terminal.Terminal.color propertyA callable string that sets the foreground color.
Permalink Source ↗
hamingjur.terminal.Terminal.color -> Union[NullCallableString, ParameterizingString]
A callable string that sets the foreground color.

:rtype: ParameterizingString

The capability is unparameterized until called and passed a number, at which point it
returns another string which represents a specific color change. This second string can
further be called to color a piece of text and set everything back to normal afterward.

This should not be used directly, but rather a specific color by name or
:meth:`~.Terminal.color_rgb` value.
terminal.Terminal.color_rgb methodProvides callable formatting string to set foreground color to the specified RGB color.
Permalink Source ↗
hamingjur.terminal.Terminal.color_rgb(red: int, green: int, blue: int) -> FormattingString
Provides callable formatting string to set foreground color to the specified RGB color.

:arg int red: 8-bit RGB value of Red (0-255).
:arg int green: 8-bit RGB value of Green (0-255).
:arg int blue: 8-bit RGB value of Blue (0-255).
:rtype: FormattingString
:returns: Callable string that sets the foreground color.

If the terminal does not support RGB color, the nearest supported
color will be determined using :py:attr:`color_distance_algorithm`.
terminal.Terminal.color_hex methodProvides callable formatting string to set foreground color from hex.
Permalink Source ↗
hamingjur.terminal.Terminal.color_hex(hex_color: str) -> FormattingString
Provides callable formatting string to set foreground color from hex.

:arg str hex_color: Hex color in ``#RGB``, ``#RRGGBB``, or ``#RRRRGGGGBBBB`` format.
    The ``#`` prefix is optional.
:rtype: FormattingString
:returns: Callable string that sets the foreground color.

If the terminal does not support RGB color, the nearest supported
color will be determined using :py:attr:`color_distance_algorithm`.

See :func:`~hamingjur.colorspace.hex_to_rgb` for supported hex formats.
terminal.Terminal.on_color propertyA callable capability that sets the background color.
Permalink Source ↗
hamingjur.terminal.Terminal.on_color -> Union[NullCallableString, ParameterizingString]
A callable capability that sets the background color.

:rtype: ParameterizingString
terminal.Terminal.on_color_rgb methodProvides callable formatting string to set background color to the specified RGB color.
Permalink Source ↗
hamingjur.terminal.Terminal.on_color_rgb(red: int, green: int, blue: int) -> FormattingString
Provides callable formatting string to set background color to the specified RGB color.

:arg int red: 8-bit RGB value of Red (0-255).
:arg int green: 8-bit RGB value of Green (0-255).
:arg int blue: 8-bit RGB value of Blue (0-255).
:rtype: FormattingString
:returns: Callable string that sets the background color.

If the terminal does not support RGB color, the nearest supported
color will be determined using :py:attr:`color_distance_algorithm`.
terminal.Terminal.on_color_hex methodProvides callable formatting string to set background color from hex.
Permalink Source ↗
hamingjur.terminal.Terminal.on_color_hex(hex_color: str) -> FormattingString
Provides callable formatting string to set background color from hex.

:arg str hex_color: Hex color in ``#RGB``, ``#RRGGBB``, or ``#RRRRGGGGBBBB`` format.
    The ``#`` prefix is optional.
:rtype: FormattingString
:returns: Callable string that sets the background color.

If the terminal does not support RGB color, the nearest supported
color will be determined using :py:attr:`color_distance_algorithm`.

See :func:`~hamingjur.colorspace.hex_to_rgb` for supported hex formats.
terminal.Terminal.formatter methodProvides callable formatting string to set color and other text formatting options.
Permalink Source ↗
hamingjur.terminal.Terminal.formatter(value: str) -> Union[NullCallableString, FormattingString]
Provides callable formatting string to set color and other text formatting options.

:arg str value: Sugary, ordinary, or compound formatted terminal capability,
    such as "red_on_white", "normal", "red", or "bold_on_black".
:rtype: :class:`FormattingString` or :class:`NullCallableString`
:returns: Callable string that sets color and other text formatting options

Calling ``term.formatter('bold_on_red')`` is equivalent to ``term.bold_on_red``, but a
string that is not a valid text formatter will return a :class:`NullCallableString`.
This is intended to allow validation of text formatters without the possibility of
inadvertently returning another terminal capability.
terminal.Terminal.rgb_downconvert methodTranslate an RGB color to a color code of the terminal's color depth.
Permalink Source ↗
hamingjur.terminal.Terminal.rgb_downconvert(red: int, green: int, blue: int) -> int
Translate an RGB color to a color code of the terminal's color depth.

This method is only be used to downconvert for terminals of 256 or fewer colors.

:arg int red: RGB value of Red (0-255).
:arg int green: RGB value of Green (0-255).
:arg int blue: RGB value of Blue (0-255).
:rtype: int
:returns: Color code of downconverted RGB color
terminal.Terminal.normal propertyA capability that resets all video attributes.
Permalink Source ↗
hamingjur.terminal.Terminal.normal -> str
A capability that resets all video attributes.

:rtype: str

``normal`` is an alias for ``sgr0`` or ``exit_attribute_mode``. Any
styling attributes previously applied, such as foreground or
background colors, reverse video, or bold are reset to defaults.
terminal.Terminal.link methodDisplay ``text`` that when touched or clicked, navigates to ``url``.
Permalink Source ↗
hamingjur.terminal.Terminal.link(url: str, text: str, url_id: str='') -> str
Display ``text`` that when touched or clicked, navigates to ``url``.

Optional ``url_id`` may be specified, so that non-adjacent cells can reference a single
target, all cells painted with the same "id" will highlight on hover, rather than any
individual one, as described in "Hovering and underlining the id parameter" of gist
https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda.

:param str url: Hyperlink URL.
:param str text: Clickable text.
:param str url_id: Optional 'id'.
:rtype: str
:returns: String of ``text`` as a hyperlink to ``url``.

:raises ValueError: If a URL or ID contains control characters or an ID contains delimiters.
terminal.Terminal.set_window_title methodReturn sequence to set the terminal title.
Permalink Source ↗
hamingjur.terminal.Terminal.set_window_title(title: str, mode: int=0) -> str
Return sequence to set the terminal title.

Uses xterm OSC (Operating System Command) sequences to set the
window and/or icon title.

:param str title: Title text. Any embedded escape or BEL characters
    are stripped to prevent sequence injection.
:param int mode: OSC mode -- 0 sets both icon name and window title,
    1 sets icon name only, 2 sets window title only.
:rtype: str
:returns: Escape sequence string that sets the terminal title,
    or empty string when :attr:`does_styling` is ``False``.
terminal.Terminal.window_title context managerContext manager that sets terminal title, restoring on exit.
Permalink Source ↗
hamingjur.terminal.Terminal.window_title(title: str, mode: int=0) -> Generator[None, None, None]
Context manager that sets terminal title, restoring on exit.

Uses the xterm title stack (XTWINOPS push/pop) to save and
restore the previous title. Not all terminals support the title
stack -- those that do not will simply set the title without
restoring it on exit.

:param str title: Title text.
:param int mode: OSC mode -- 0 sets both icon name and window title,
    1 sets icon name only, 2 sets window title only.
terminal.Terminal.progress_bar methodReturn OSC 9;4 sequence for terminal progress bar support.
Permalink Source ↗
hamingjur.terminal.Terminal.progress_bar(state: Union[str, int], value: Optional[int]=None) -> str
Return OSC 9;4 sequence for terminal progress bar support.

Support for 'OSC 9;4' cannot be detected. It is generally safe to write to unsupported
terminals. Some terminals display a graphical progress indicator in the taskbar and window
menu or status bar matching the given value (0-100).  Supported by at least Windows
Terminal.exe, ConEmu, Ghostty, kitty, and iTerm2.

:param state: Progress state. Accepts either an integer or a string name:

    - ``0`` or ``'clear'``: Remove progress indicator
    - ``1`` or ``'normal'``: Set progress to *value* (0 to 100)
    - ``2`` or ``'error'``: Error state (typically red)
    - ``3`` or ``'indeterminate'``: Indeterminate / pulsing
    - ``4`` or ``'paused'``: Paused state (typically yellow)

:param int value: Progress value as integer of percent (0 to 100).  Required when state is
    ``'normal'`` or ``1``.  Terminals are expected to ignore 'value' for all other states.
:rtype: str
:returns: OSC 9;4 escape sequence, or ``''`` when :attr:`does_styling` is ``False``.
:raises ValueError: on bad ``state`` identifier or invalid or out of bounds ``value``.

.. seealso:: https://ghostty.org/docs/vt/osc/conemu#change-progress-state-(osc-94)
terminal.Terminal.stream propertyRead-only property: stream the terminal outputs to.
Permalink Source ↗
hamingjur.terminal.Terminal.stream -> IO[str]
Read-only property: stream the terminal outputs to.

This is a convenience attribute. It is used internally for implied
writes performed by context managers :meth:`~.hidden_cursor`,
:meth:`~.fullscreen`, :meth:`~.location`, and :meth:`~.keypad`.
terminal.Terminal.number_of_colors propertyNumber of colors supported by terminal.
Permalink Source ↗
hamingjur.terminal.Terminal.number_of_colors -> int
Number of colors supported by terminal.

Common return values are 0, 8, 16, 256, or 1 << 24.

This may be used to test whether the terminal supports colors, and at what depth, if that's
a concern.

If this property is assigned a value of 88, the value 16 will be saved. This is due to the
the rarity of 88 color support and the inconsistency of behavior between implementations.

Assigning this property to a value other than 0, 4, 8, 16, 88, 256, or 1 << 24 will raise an
:py:exc:`AssertionError`.
terminal.Terminal.color_distance_algorithm propertyColor distance algorithm used by :meth:`rgb_downconvert`.
Permalink Source ↗
hamingjur.terminal.Terminal.color_distance_algorithm -> str
Color distance algorithm used by :meth:`rgb_downconvert`.

The slowest, but most accurate, 'cie2000', is default. Other available options are 'rgb',
'rgb-weighted', 'cie76', and 'cie94'. This function is only be used to downconvert for
terminals of 256 or fewer colors.
terminal.Terminal.ljust methodLeft-align ``text``, which may contain terminal sequences.
Permalink Source ↗
hamingjur.terminal.Terminal.ljust(text: str, width: Optional[SupportsIndex]=None, fillchar: str=' ') -> str
Left-align ``text``, which may contain terminal sequences.

:arg str text: String to be aligned
:arg int width: Total width to fill with aligned text. If
    unspecified, the whole width of the terminal is filled.
:arg str fillchar: String for padding the right of ``text``
:rtype: str
:returns: String of ``text``, left-aligned by ``width``.
terminal.Terminal.rjust methodRight-align ``text``, which may contain terminal sequences.
Permalink Source ↗
hamingjur.terminal.Terminal.rjust(text: str, width: Optional[SupportsIndex]=None, fillchar: str=' ') -> str
Right-align ``text``, which may contain terminal sequences.

:arg str text: String to be aligned
:arg int width: Total width to fill with aligned text. If
    unspecified, the whole width of the terminal is used.
:arg str fillchar: String for padding the left of ``text``
:rtype: str
:returns: String of ``text``, right-aligned by ``width``.
terminal.Terminal.center methodCenter ``text``, which may contain terminal sequences.
Permalink Source ↗
hamingjur.terminal.Terminal.center(text: str, width: Optional[SupportsIndex]=None, fillchar: str=' ') -> str
Center ``text``, which may contain terminal sequences.

:arg str text: String to be centered
:arg int width: Total width in which to center text. If
    unspecified, the whole width of the terminal is used.
:arg str fillchar: String for padding the left and right of ``text``
:rtype: str
:returns: String of ``text``, centered by ``width``
terminal.Terminal.text_sized methodWrap ``text`` in a text sizing escape sequence (OSC 66).
Permalink Source ↗
hamingjur.terminal.Terminal.text_sized(text: str, scale: int=1, *, width: int=0, numerator: int=0, denominator: int=0, vertical_align: Union[int, str]=0, horizontal_align: Union[int, str]=0) -> str
Wrap ``text`` in a text sizing escape sequence (OSC 66).

Returns ``text`` unchanged when the terminal does not support text sizing, providing
graceful degradation.

:arg str text: Text payload.
:arg int scale: Scale factor (1 to 7).
:arg int width: Width in cells (0 to 7). 0 means auto-calculate
    from the inner text.
:arg int numerator: Fractional scaling numerator (0 to 15).
:arg int denominator: Fractional scaling denominator (0 to 15).
:arg vertical_align: Vertical alignment: ('top', 'bottom', 'center'), or protocol code
    (0=top, 1=bottom, 2=center).
:arg horizontal_align: Horizontal alignment. ('left', 'right', 'center') or protocol code
    (0=left, 1=right, 2=center).
:rtype: str
:returns: Text wrapped in an OSC 66 escape sequence, or plain
    ``text`` on unsupported terminals.
:raises ValueError: when the encoded ``text`` exceeds 4096 bytes.
:raises ValueError: when ``vertical_align`` or ``horizontal_align`` is an
    unrecognized string value.

.. seealso:: `Kitty Text Sizing Protocol
    <https://sw.kovidgoyal.net/kitty/text-sizing-protocol/>`_

.. note:: Because the first call to :meth:`Terminal.text_sized` will cause the side effect
    of writing destructive spaces to the columns and row following the current cursor
    position as required for detection of `kitty text sizing protocol`_, it is suggested
    to first call :meth:`Terminal.does_text_sizing` during program initialization.

    The result is permanently cached and all further calls to these methods return
    immediately without this side effect.
terminal.Terminal.clip methodReturn a window of ``text`` spanning display columns ``start`` to ``end``.
Permalink Source ↗
hamingjur.terminal.Terminal.clip(text: str, start: SupportsIndex=0, end: SupportsIndex=-1, **kwargs: object) -> str
Return a window of ``text`` spanning display columns ``start`` to ``end``.

Terminal sequences are retained, wide characters split at a boundary are
replaced by ``fillchar``, and horizontal cursor movement is interpreted by
:func:`wcwidth.clip`. The detected :attr:`ambiguous_width` and
:attr:`term_program` are applied.

:arg str text: Text to clip, may contain terminal sequences
:arg int start: Absolute starting column, inclusive (default 0)
:arg int end: Absolute ending column, exclusive; -1 (default) means
    "to the end of the line"
:arg \**kwargs: See :func:`wcwidth.clip`
:rtype: str
:returns: ``text`` clipped to display columns (start, end)

>>> term.clip('hello world', 6)
'world'
terminal.Terminal.truncate methodTruncate ``text`` to ``width`` printable characters, retaining terminal sequences.
Permalink Source ↗
hamingjur.terminal.Terminal.truncate(text: str, width: Optional[SupportsIndex]=None) -> str
Truncate ``text`` to ``width`` printable characters, retaining terminal sequences.

Wide characters (such as CJK or emoji) that would partially exceed
``width`` are replaced with space padding to maintain exact width.

:arg str text: Text to truncate
:arg int width: The width to truncate to. If unspecified, the whole
    width of the terminal is used.
:rtype: str
:returns: ``text`` truncated to exactly ``width`` printable characters

>>> term.truncate('xyz\x1b[0;3m', 2)
'xy\x1b[0;3m'
terminal.Terminal.length methodReturn printable length of a string containing sequences.
Permalink Source ↗
hamingjur.terminal.Terminal.length(text: str) -> int
Return printable length of a string containing sequences.

Returns the maximum horizontal cursor extent reached while processing
the string. Backspace and cursor-left movements do not reduce the
length below the maximum position reached.

:arg str text: String to measure. May contain terminal sequences.
:rtype: int
:returns: The maximum terminal character cell position reached

Wide characters that consume 2 character cells are supported:

>>> term = Terminal()
>>> term.length(term.clear + term.red('コンニチハ'))
10

.. note:: Sequences such as 'clear', which is considered as a
    "movement sequence" because it would move the cursor to
    (y, x)(0, 0), are evaluated as a printable length of
    *0*.
terminal.Terminal.strip methodReturn ``text`` without sequences and leading or trailing whitespace.
Permalink Source ↗
hamingjur.terminal.Terminal.strip(text: str, chars: Optional[str]=None) -> str
Return ``text`` without sequences and leading or trailing whitespace.

:rtype: str
:returns: Text with leading and trailing whitespace removed

>>> term.strip(' \x1b[0;3m xyz ')
'xyz'
terminal.Terminal.rstrip methodReturn ``text`` without terminal sequences or trailing whitespace.
Permalink Source ↗
hamingjur.terminal.Terminal.rstrip(text: str, chars: Optional[str]=None) -> str
Return ``text`` without terminal sequences or trailing whitespace.

:rtype: str
:returns: Text with terminal sequences and trailing whitespace removed

>>> term.rstrip(' \x1b[0;3m xyz ')
'  xyz'
terminal.Terminal.lstrip methodReturn ``text`` without terminal sequences or leading whitespace.
Permalink Source ↗
hamingjur.terminal.Terminal.lstrip(text: str, chars: Optional[str]=None) -> str
Return ``text`` without terminal sequences or leading whitespace.

:rtype: str
:returns: Text with terminal sequences and leading whitespace removed

>>> term.lstrip(' \x1b[0;3m xyz ')
'xyz '
terminal.Terminal.strip_seqs methodReturn ``text`` stripped of only its terminal sequences.
Permalink Source ↗
hamingjur.terminal.Terminal.strip_seqs(text: str) -> str
Return ``text`` stripped of only its terminal sequences.

:rtype: str
:returns: Text with terminal sequences removed

>>> term.strip_seqs('\x1b[0;3mxyz')
'xyz'
>>> term.strip_seqs(term.cuf(5) + term.red('test'))
'     test'

.. note:: Non-destructive sequences that adjust horizontal distance
    (such as ``\b`` or ``term.cuf(5)``) are replaced by destructive
    space or erasing.
terminal.Terminal.split_seqs methodReturn ``text`` split by individual character elements and sequences.
Permalink Source ↗
hamingjur.terminal.Terminal.split_seqs(text: str, maxsplit: int=0) -> List[str]
Return ``text`` split by individual character elements and sequences.

:arg str text: String containing sequences
:arg int maxsplit: When maxsplit is nonzero, at most maxsplit splits
    occur, and the remainder of the string is returned as the final element
    of the list (same meaning is argument for :func:`re.split`).
:rtype: list[str]
:returns: List of sequences and individual characters

>>> term.split_seqs(term.underline('xyz'))
['\x1b[4m', 'x', 'y', 'z', '\x1b(B', '\x1b[m']

>>> term.split_seqs(term.underline('xyz'), 1)
['\x1b[4m', r'xyz\x1b(B\x1b[m']
terminal.Terminal.wrap methodText-wrap a string, returning a list of wrapped lines.
Permalink Source ↗
hamingjur.terminal.Terminal.wrap(text: str, width: Optional[int]=None, **kwargs: object) -> List[str]
Text-wrap a string, returning a list of wrapped lines.

:arg str text: Unlike :func:`textwrap.wrap`, ``text`` may contain
    terminal sequences, such as colors, bold, or underline. By
    default, tabs in ``text`` are expanded by
    :func:`string.expandtabs`.
:arg int width: Unlike :func:`textwrap.wrap`, ``width`` will
    default to the width of the attached terminal.
:arg \**kwargs: See :py:class:`textwrap.TextWrapper`
:rtype: list
:returns: List of wrapped lines
:raises ValueError: for non-positive values of ``width``.

See :class:`textwrap.TextWrapper` for keyword arguments that can
customize wrapping behaviour.
terminal.Terminal.getch methodRead, decode, and return the next byte from the keyboard stream.
Permalink Source ↗
hamingjur.terminal.Terminal.getch(decode_latin1: bool=False) -> str
Read, decode, and return the next byte from the keyboard stream.

:arg bool decode_latin1: If True, decode byte as latin-1 (for legacy mouse
    sequences with 8-bit coordinates).
:rtype: unicode
:returns: a single unicode character, or ``''`` if a multi-byte
    sequence has not yet been fully received.
:raises EOFError: When the keyboard stream has reached end-of-file.

This method name and behavior mimics curses ``getch(void)``, and
it supports :meth:`inkey`, reading only one byte from
the keyboard string at a time. This method should always return
without blocking if called after :meth:`kbhit` has returned True.

Implementers of alternate input stream methods should override
this method.
terminal.Terminal.ungetch methodBuffer input data to be discovered by next call to :meth:`~.inkey`.
Permalink Source ↗
hamingjur.terminal.Terminal.ungetch(text: str) -> None
Buffer input data to be discovered by next call to :meth:`~.inkey`.

:arg str text: String to be buffered as keyboard input.
terminal.Terminal.kbhit methodReturn whether a keypress has been detected on the keyboard.
Permalink Source ↗
hamingjur.terminal.Terminal.kbhit(timeout: Optional[float]=None) -> bool
Return whether a keypress has been detected on the keyboard.

This method is used by :meth:`inkey` to determine if a byte may
be read using :meth:`getch` without blocking.  The standard
implementation simply uses the :func:`select.select` call on stdin.

:arg float timeout: When ``timeout`` is 0, this call is
    non-blocking, otherwise blocking indefinitely until keypress
    is detected when None (default). When ``timeout`` is a
    positive number, returns after ``timeout`` seconds have
    elapsed (float).
:rtype: bool
:returns: True if a keypress is awaiting to be read on the keyboard
    attached to this terminal.  When input is not a terminal, False is
    always returned.
terminal.Terminal.cbreak context managerAllow each keystroke to be read immediately after it is pressed.
Permalink Source ↗
hamingjur.terminal.Terminal.cbreak() -> Generator[None, None, None]
Allow each keystroke to be read immediately after it is pressed.

This is a context manager for :func:`tty.setcbreak`.

This context manager activates 'rare' mode, the opposite of 'cooked'
mode: On entry, :func:`tty.setcbreak` mode is activated disabling
line-buffering of keyboard input and turning off automatic echo of
input as output.

.. note:: You must explicitly print any user input you would like
    displayed.  If you provide any kind of editing, you must handle
    backspace and other line-editing control functions in this mode
    as well!

**Normally**, characters received from the keyboard cannot be read
by Python until the *Return* key is pressed. Also known as *cooked* or
*canonical input* mode, it allows the tty driver to provide
line-editing before shuttling the input to your program and is the
(implicit) default terminal mode set by most unix shells before
executing programs.

Technically, this context manager sets the :mod:`termios` attributes
of the terminal attached to :obj:`sys.__stdin__`.

.. note:: :func:`tty.setcbreak` sets ``VMIN = 1`` and ``VTIME = 0``,
    see http://www.unixwiz.net/techtips/termios-vmin-vtime.html
terminal.Terminal.raw context managerA context manager for :func:`tty.setraw`.
Permalink Source ↗
hamingjur.terminal.Terminal.raw() -> Generator[None, None, None]
A context manager for :func:`tty.setraw`.

Although both :meth:`cbreak` and :meth:`raw` modes allow each keystroke
to be read immediately after it is pressed, Raw mode disables
processing of input and output by the terminal driver.

In cbreak mode, special input characters such as ``^C`` or ``^S`` are
interpreted by the terminal driver and excluded from the stdin stream.
In raw mode these values are received by the :meth:`inkey` method.

Because output processing is not done by the terminal driver, the
newline ``'\n'`` is not enough, you must also print carriage return to
ensure that the cursor is returned to the first column::

    with term.raw():
        print("printing in raw mode", end="\r\n")
terminal.Terminal.keypad context managerContext manager that enables directional keypad input.
Permalink Source ↗
hamingjur.terminal.Terminal.keypad() -> Generator[None, None, None]
Context manager that enables directional keypad input.

On entry, this puts the terminal into "keyboard_transmit" mode by
emitting the keypad_xmit (smkx) capability. On exit, it emits
keypad_local (rmkx).

On an IBM-PC keyboard with numeric keypad of terminal-type *xterm*,
with numlock off, the lower-left diagonal key transmits sequence
``\\x1b[F``, translated to :class:`~.Terminal` attribute
``KEY_END``.

However, upon entering :meth:`keypad`, ``\\x1b[OF`` is transmitted,
translating to ``KEY_LL`` (lower-left key), allowing you to determine
diagonal direction keys.
terminal.Terminal.flushinp methodUnbuffer and return all input available within ``timeout``.
Permalink Source ↗
hamingjur.terminal.Terminal.flushinp(timeout: float=0) -> str
Unbuffer and return all input available within ``timeout``.

When legacy mouse sequence ``'\x1b[M'`` is detected in input stream,
all remaining bytes are decoded as latin1 to handle 8-bit coordinates.
terminal.Terminal.inkey methodRead and return the next keyboard event within given timeout.
Permalink Source ↗
hamingjur.terminal.Terminal.inkey(timeout: Optional[float]=None, esc_delay: float=DEFAULT_ESCDELAY, capture_cpr: bool=False) -> Keystroke
Read and return the next keyboard event within given timeout.

Generally, this should be used inside the :meth:`raw` or :meth:`cbreak` context manager.

:arg float timeout: Number of seconds to wait for a keystroke before
    returning.  When ``None`` (default), this method may block
    indefinitely.
:arg float esc_delay: Time in seconds to block after Escape key
   is received to await another key sequence beginning with
   escape such as *KEY_LEFT*, sequence ``'\x1b[D'``, before returning a
   :class:`~.Keystroke` instance for ``KEY_ESCAPE``.

   Users may override the default value of ``esc_delay`` in seconds,
   using environment value of ``ESCDELAY`` as milliseconds, see
   `ncurses(3)`_ section labeled *ESCDELAY* for details.  Setting
   the value as an argument to this function will override any
   such preference.
:arg bool capture_cpr: Prefer matches of ``CPR_RESPONSE`` over conflicting vt220 Legacy
    function keys (eg. ``KEY_F3``, ``KEY_SHIFT_F3``).
:rtype: :class:`~.Keystroke`.
:returns: :class:`~.Keystroke`, which may be empty (``''``) if
   ``timeout`` is specified and keystroke is not received.

.. note:: When used without the context manager :meth:`cbreak`, or
    :meth:`raw`, :obj:`sys.__stdin__` remains line-buffered, and this
    function will block until the return key is pressed!

.. note:: On Windows, a 10 ms sleep is added to the key press detection loop to reduce CPU
    load. Due to the behavior of :py:func:`time.sleep` on Windows, this will actually
    result in a 15.6 ms delay when using the default `time resolution
    <https://docs.microsoft.com/en-us/windows/win32/api/timeapi/nf-timeapi-timebeginperiod>`_.
    Decreasing the time resolution will reduce this to 10 ms, while increasing it, which
    is rarely done, will have a perceptable impact on the behavior.

_`ncurses(3)`: https://www.man7.org/linux/man-pages/man3/ncurses.3x.html
terminal.Terminal.async_inkey methodAsynchronous version of :meth:`inkey` for use with :mod:`asyncio`.
Permalink Source ↗
async hamingjur.terminal.Terminal.async_inkey(timeout: Optional[float]=None, esc_delay: float=DEFAULT_ESCDELAY, capture_cpr: bool=False) -> Keystroke
Asynchronous version of :meth:`inkey` for use with :mod:`asyncio`.

Read and return the next keyboard event within given timeout, yielding
control to the asyncio event loop while waiting for input rather than
blocking the thread.

Uses :meth:`asyncio.AbstractEventLoop.add_reader` on the keyboard file
descriptor, reusing the same :func:`~.resolve_sequence`, keymap, and
:class:`~.Keystroke` internals as the synchronous :meth:`inkey`.

Must be called within a :meth:`cbreak` or :meth:`raw` context, just
like :meth:`inkey`.

:arg float timeout: Number of seconds to wait for a keystroke before
    returning.  When ``None`` (default), this method may block
    indefinitely.
:arg float esc_delay: Time in seconds to wait after Escape key
    is received to disambiguate bare Escape from escape sequences.
:arg bool capture_cpr: Prefer matches of ``CPR_RESPONSE`` over conflicting vt220 Legacy
    function keys (eg. ``KEY_F3``, ``KEY_SHIFT_F3``).
:rtype: :class:`~.Keystroke`
:returns: :class:`~.Keystroke`, which may be empty (``''``) if
    ``timeout`` is specified and keystroke is not received.
terminal.WINSZ classStructure represents return value of :const:`termios.TIOCGWINSZ`.
Permalink Source ↗
hamingjur.terminal.WINSZ
Bases: collections.namedtuple('WINSZ', ('ws_row', 'ws_col', 'ws_xpixel', 'ws_ypixel'))
Structure represents return value of :const:`termios.TIOCGWINSZ`.

.. py:attribute:: ws_row

    rows, in characters

.. py:attribute:: ws_col

    columns, in characters

.. py:attribute:: ws_xpixel

    horizontal size, pixels

.. py:attribute:: ws_ypixel

    vertical size, pixels
hamingjur.graphics30 entries

Streaming Kitty raster, animation, placement and Silkie vector/GPU commands.

graphics.chunks functionReblock input without a total-size limit, including streams with short reads.
Permalink Source ↗
hamingjur.graphics.chunks(data: Data, size: int) -> Iterator[bytes]
Reblock input without a total-size limit, including streams with short reads.

:raises TypeError: If a payload has the wrong type.
graphics.command functionEncode a control-only command, including placement, animation and deletion.
Permalink Source ↗
hamingjur.graphics.command(**fields: Field) -> str
Encode a control-only command, including placement, animation and deletion.
graphics.transmit functionEncode all graphics actions and transports, streaming direct payloads.
Permalink Source ↗
hamingjur.graphics.transmit(data: Data, *, compress: bool=False, **fields: Field) -> Iterator[str]
Encode all graphics actions and transports, streaming direct payloads.

Keys use the protocol's spelling. This supports raster formats 24/32/100, Silkie
packed grayscale (301/302/304/308), RGB565 (516), palette (401/402/404/408),
high precision (316/632/664), HDR (64), vectors (200) and SVG (201),
animation frames (a=f), vector patches (a=e), and services (a=v). For t=f/t=t/t=s/t=g, data
names a resource already owned by the caller; this function never allocates or deletes
operating-system resources.

:raises ValueError: If arguments or protocol data are invalid.
graphics.image functionTransmit an image. PNG and SVG can use their intrinsic dimensions.
Permalink Source ↗
hamingjur.graphics.image(data: Data, *, image_id: int, format: int=100, width: Optional[int]=None, height: Optional[int]=None, display: bool=True, compress: bool=False, **placement: Field) -> Iterator[str]
Transmit an image. PNG and SVG can use their intrinsic dimensions.

Grayscale formats 301/302/304/308 pack pixels most-significant first, padding
each row to a byte boundary. Format 516 is little-endian RGB565. Palette
formats 401/402/404/408 start with all 2**bits straight RGBA palette slots,
followed by rows of packed indices. Formats 8/16 index the terminal palette,
with per-pixel alpha in format 16. High precision formats 316/632/664 carry
little-endian gray16/RGB10A2/RGBA16. Data is already packed; no conversion is
performed. Source formats do not depend on the display's color precision.

:raises ValueError: If arguments or protocol data are invalid.
graphics.place functionPlace a stored image; supports cropping, offsets, z-order and relative placements.
Permalink Source ↗
hamingjur.graphics.place(image_id: int, **fields: Field) -> str
Place a stored image; supports cropping, offsets, z-order and relative placements.
graphics.delete functionDelete an image's placements or all visible placements, optionally freeing data.
Permalink Source ↗
hamingjur.graphics.delete(image_id: Optional[int]=None, *, free: bool=True, **fields: Field) -> str
Delete an image's placements or all visible placements, optionally freeing data.
graphics.json_bytes functionEncode UTF-8 JSON, rejecting non-finite values.
Permalink Source ↗
hamingjur.graphics.json_bytes(value: Mapping[str, Any]) -> bytes
Encode UTF-8 JSON, rejecting non-finite values.
graphics.vector_record functionBuild any vector record, including groups, paths, symbols, ink and gradients.
Permalink Source ↗
hamingjur.graphics.vector_record(kind: str, **fields: Any) -> str
Build any vector record, including groups, paths, symbols, ink and gradients.

Sequence values become comma-separated lists. Use text_record() for text; path data must already
use the protocol's whitespace-free SVG syntax.

:raises ValueError: If arguments or protocol data are invalid.
graphics.text_record functionEncode shaped/styled vector text with arbitrary Unicode and layout properties.
Permalink Source ↗
hamingjur.graphics.text_record(element_id: int, layout: Mapping[str, Any], *, group: int=0, **fields: Any) -> str
Encode shaped/styled vector text with arbitrary Unicode and layout properties.
graphics.scene functionStream a vector scene without accumulating all its records in memory.
Permalink Source ↗
hamingjur.graphics.scene(records: Iterable[str], *, image_id: int, width: int, height: int, compress: bool=False, **fields: Field) -> Iterator[str]
Stream a vector scene without accumulating all its records in memory.
graphics.svg functionStream a static SVG document in Silkie's retained graphics format.
Permalink Source ↗
hamingjur.graphics.svg(document: Union[str, Data], *, image_id: int, width: Optional[int]=None, height: Optional[int]=None, display: bool=True, compress: bool=False, **fields: Field) -> Iterator[str]
Stream a static SVG document in Silkie's retained graphics format.
graphics.patch functionAtomically edit a stored vector scene, including appending live pen strokes.
Permalink Source ↗
hamingjur.graphics.patch(image_id: int, records: Iterable[str], *, compress: bool=False, **fields: Field) -> Iterator[str]
Atomically edit a stored vector scene, including appending live pen strokes.
graphics.vector_service functionList/inspect/upload/release fonts or measure text through Silkie's vector service.
Permalink Source ↗
hamingjur.graphics.vector_service(request_id: int, operation: str, **fields: Any) -> Iterator[str]
List/inspect/upload/release fonts or measure text through Silkie's vector service.
graphics.service_result functionDecode a vector service reply, raising ValueError for terminal errors.
Permalink Source ↗
hamingjur.graphics.service_result(response: str) -> Mapping[str, Any]
Decode a vector service reply, raising ValueError for terminal errors.

:raises ValueError: If the terminal reports an error or the result is malformed.
graphics.placeholder functionYield Unicode placeholder rows for a virtual placement (a=p,U=1).
Permalink Source ↗
hamingjur.graphics.placeholder(image_id: int, rows: int, columns: int, *, placement_id: int=0) -> Iterator[str]
Yield Unicode placeholder rows for a virtual placement (a=p,U=1).
graphics.Graphics classImage encoders and terminal queries, available as ``term.graphics``.
Permalink Source ↗
hamingjur.graphics.Graphics(terminal: 'Terminal')
Image encoders and terminal queries, available as ``term.graphics``.

Constructor
-----------
Bind graphics output and queries to a terminal.
Fields & constants
command = staticmethod(command)
transmit = staticmethod(transmit)
image = staticmethod(image)
place = staticmethod(place)
delete = staticmethod(delete)
scene = staticmethod(scene)
svg = staticmethod(svg)
patch = staticmethod(patch)
vector_service = staticmethod(vector_service)
placeholder = staticmethod(placeholder)
graphics.Graphics.negotiate methodDiscover formats and probe local file/SHM access on this connection.
Permalink Source ↗
hamingjur.graphics.Graphics.negotiate(timeout: Optional[float]=1.0, *, force: bool=False) -> ImageSupport
Discover formats and probe local file/SHM access on this connection.

Successful negotiation is cached; force=True refreshes after reconnection.
GPU support is advertised only: gpu_surface() still requires an external descriptor.
A remote connection cannot gain a local transport merely by advertising it.

:raises OSError: If resource allocation fails beyond permission/platform refusal.
graphics.Graphics.transfers methodReturn usable enum-valued image transfers, probing actual local resource access.
Permalink Source ↗
hamingjur.graphics.Graphics.transfers(timeout: Optional[float]=1.0, *, force: bool=False) -> frozenset[Transfer]
Return usable enum-valued image transfers, probing actual local resource access.
graphics.Graphics.observe methodUpdate adaptive drawing state from an incoming display report.
Permalink Source ↗
hamingjur.graphics.Graphics.observe(event: Optional[ProtocolEvent]) -> None
Update adaptive drawing state from an incoming display report.
graphics.Graphics.prepare methodFit a PIL image to pixels or cells and choose its smallest cheap lossless payload.
Permalink Source ↗
hamingjur.graphics.Graphics.prepare(source: Any, *, width: Optional[int]=None, height: Optional[int]=None, columns: Optional[int]=None, rows: Optional[int]=None, match_display: bool=True, timeout: Optional[float]=1.0) -> PreparedImage
Fit a PIL image to pixels or cells and choose its smallest cheap lossless payload.

With no target, fit the current viewport. Resizes invalidate cell geometry;
display reports update precision. The source image remains available for redraw.

:raises ValueError: If pixel and cell units are mixed.
:raises RuntimeError: If graphics support or required pixel geometry is unavailable.
graphics.Graphics.draw methodDraw a PIL image, choosing packing, compression and a negotiated transfer.
Permalink Source ↗
hamingjur.graphics.Graphics.draw(source: Any, *, image_id: Optional[int]=None, transfer: Optional[Transfer]=None, x: Optional[int]=None, y: Optional[int]=None, width: Optional[int]=None, height: Optional[int]=None, columns: Optional[int]=None, rows: Optional[int]=None, match_display: bool=True, placement_id: Optional[int]=None, timeout: Optional[float]=1.0) -> Optional[DrawnImage]
Draw a PIL image, choosing packing, compression and a negotiated transfer.

x/y are zero-based cell coordinates; omit both to use the cursor. Local resources
survive until acknowledgement and are cleaned on failures. A timeout raises rather
than silently redrawing. Returns None without styling.
Supply a nonzero placement_id to attach Silkie accessibility metadata afterwards.

:raises ValueError: If geometry, prepared formats or requested transfers are invalid.
graphics.Graphics.forget methodRelease a locally retained image or scene after the application is done with it.
Permalink Source ↗
hamingjur.graphics.Graphics.forget(image_id: int) -> None
Release a locally retained image or scene after the application is done with it.

:raises ValueError: If the image ID is outside the protocol's range.
graphics.Graphics.adaptive context managerTrack window and display changes during an input loop, restoring reporting on exit.
Permalink Source ↗
hamingjur.graphics.Graphics.adaptive(timeout: Optional[float]=1.0) -> Iterator['Graphics']
Track window and display changes during an input loop, restoring reporting on exit.
graphics.Graphics.send methodWrite graphics packets, translating them when the terminal needs a fallback.
Permalink Source ↗
hamingjur.graphics.Graphics.send(sequences: Union[str, Iterable[str]]) -> None
Write graphics packets, translating them when the terminal needs a fallback.
graphics.Graphics.query methodProbe a format/medium/gamut with sample data, without storing an image.
Permalink Source ↗
hamingjur.graphics.Graphics.query(data: Data, *, request_id: int=31, timeout: Optional[float]=1.0, **fields: Field) -> Optional[ProtocolEvent]
Probe a format/medium/gamut with sample data, without storing an image.
graphics.Graphics.supports methodCheck a raster or vector format, including local rendering where available.
Permalink Source ↗
hamingjur.graphics.Graphics.supports(format: int=24, *, timeout: Optional[float]=1.0, **fields: Field) -> bool
Check a raster or vector format, including local rendering where available.

:raises ValueError: If arguments or protocol data are invalid.
graphics.Graphics.service methodRun a vector font/measurement request and decode its result or terminal error.
Permalink Source ↗
hamingjur.graphics.Graphics.service(operation: str, *, request_id: int=31, timeout: Optional[float]=1.0, **fields: Any) -> Optional[Mapping[str, Any]]
Run a vector font/measurement request and decode its result or terminal error.
graphics.Graphics.upload_font methodUpload an outline font for this PTY; retained text survives release of the handle.
Permalink Source ↗
hamingjur.graphics.Graphics.upload_font(font_id: str, data: bytes, *, index: int=0, timeout: Optional[float]=1.0) -> Optional[Mapping[str, Any]]
Upload an outline font for this PTY; retained text survives release of the handle.

:raises ValueError: If arguments or protocol data are invalid.
graphics.Graphics.measure_text methodMeasure vector text with exactly the layout object used by text_record().
Permalink Source ↗
hamingjur.graphics.Graphics.measure_text(layout: Mapping[str, Any], *, timeout: Optional[float]=1.0) -> Optional[Mapping[str, Any]]
Measure vector text with exactly the layout object used by text_record().
graphics.Graphics.gpu_surface methodReference an existing IOSurface/dma-buf; allocation remains with the caller.
Permalink Source ↗
hamingjur.graphics.Graphics.gpu_surface(descriptor: str, *, image_id: int, **fields: Field) -> Iterator[str]
Reference an existing IOSurface/dma-buf; allocation remains with the caller.

:raises ValueError: If arguments or protocol data are invalid.
hamingjur.imaging8 entries

Adaptive Pillow image preparation and owned graphics transport resources.

imaging.Transfer classKitty/Silkie image transfer media, using their wire values.
Permalink Source ↗
hamingjur.imaging.Transfer
Bases: str, Enum
Kitty/Silkie image transfer media, using their wire values.
Fields & constants
DIRECT = 'd'
FILE = 'f'
TEMPORARY_FILE = 't'
SHARED_MEMORY = 's'
GPU_SURFACE = 'g'
imaging.ImageSupport classAccepted source formats and usable transports for this terminal connection.
Permalink Source ↗
hamingjur.imaging.ImageSupport
Accepted source formats and usable transports for this terminal connection.
Fields & constants
formats: frozenset[int]
transfers: frozenset[Transfer]
imaging.PreparedImage classA fitted image and the smallest measured cheap lossless wire encoding.
Permalink Source ↗
hamingjur.imaging.PreparedImage
A fitted image and the smallest measured cheap lossless wire encoding.
Fields & constants
data: bytes
format: int
size: Size
compressed: bool
imaging.PreparedImage.wire_size propertyDirect upload bytes with image ID 1, including base64, fields and chunk framing.
Permalink Source ↗
hamingjur.imaging.PreparedImage.wire_size -> int
Direct upload bytes with image ID 1, including base64, fields and chunk framing.
imaging.DrawnImage classA written image placement and its chosen representation.
Permalink Source ↗
hamingjur.imaging.DrawnImage
A written image placement and its chosen representation.
Fields & constants
image_id: int
image: PreparedImage
transfer: Transfer
acknowledged: bool = True
imaging.prepare_image functionFit a PIL image without upscaling, then compare cheap lossless encodings.
Permalink Source ↗
hamingjur.imaging.prepare_image(source: Any, formats: Iterable[int], *, width: Optional[int]=None, height: Optional[int]=None, display: Optional[Mapping[str, str]]=None, match_display: bool=True) -> PreparedImage
Fit a PIL image without upscaling, then compare cheap lossless encodings.

Display matching is the only color reduction; set match_display=False to keep
source precision. Alpha is retained. PNG palettes, packed grayscale, RGB565,
gray16, raw RGB/RGBA and fast zlib are compared where accepted, without JPEG or dithering.
The original image is never modified.

:raises TypeError: If source is not a PIL image.
:raises ValueError: If no accepted format represents the resulting pixels losslessly.
imaging.image_resource context managerOwn a local resource until its query/upload is acknowledged, including error cleanup.
Permalink Source ↗
hamingjur.imaging.image_resource(data: bytes, transfer: Transfer) -> Iterator[bytes]
Own a local resource until its query/upload is acknowledged, including error cleanup.

:raises ValueError: If the transfer does not use a local file or SHM allocation.
imaging.decode_image functionDecode a portable wire image to RGBA for another graphics backend.
Permalink Source ↗
hamingjur.imaging.decode_image(data: bytes, pixel_format: int, width: int, height: int) -> Any
Decode a portable wire image to RGBA for another graphics backend.
hamingjur.silkie58 entries

Silkie discovery, tablet/touch input, gestures, ink, haptics, fonts and timing.

silkie.TabletMode classTablet reporting bits; unsupported or refused bits are read back as off.
Permalink Source ↗
hamingjur.silkie.TabletMode
Bases: IntFlag
Tablet reporting bits; unsupported or refused bits are read back as off.
Fields & constants
TOOLS = 1
TOUCH = 2
PAD = 4
HARDWARE_IDS = 8
TOOL_ACTIONS = 16
ESTIMATES = 32
ACCIDENTAL_TOUCH = 64
silkie.command functionEncode any version-one Silkie operation, preserving extension-specific fields.
Permalink Source ↗
hamingjur.silkie.command(selector: str, operation: str, **fields: Field) -> str
Encode any version-one Silkie operation, preserving extension-specific fields.

:raises ValueError: If arguments or protocol data are invalid.
silkie.depth functionSet stereo text depth and/or vertical phase, or reset both with no arguments.
Permalink Source ↗
hamingjur.silkie.depth(millidegrees: Optional[int]=None, *, pixels: Optional[float]=None, phase: Optional[float]=None) -> str
Set stereo text depth and/or vertical phase, or reset both with no arguments.

Pixel depth uses reference pixels at 1920 pixels per eye; phase uses physical
pixels. Omitted attributes are preserved. The terminal applies user limits.

:raises ValueError: If depth forms conflict or values exceed their wire representation.
silkie.agent_request functionEncode one SSH-agent request; expires is an absolute Unix millisecond deadline.
Permalink Source ↗
hamingjur.silkie.agent_request(packet: bytes, *, identifier: str, connection: str, generation: str, expires: int) -> str
Encode one SSH-agent request; expires is an absolute Unix millisecond deadline.
silkie.ImageAnnotation classA plain-text description of an image placement.
Permalink Source ↗
hamingjur.silkie.ImageAnnotation
A plain-text description of an image placement.
Fields & constants
name: str = ''
description: str = ''
details: str = ''
purpose: Optional[str] = None
silkie.annotate_image functionEncode an annotation which replaces all metadata on an existing placement.
Permalink Source ↗
hamingjur.silkie.annotate_image(image_id: int, placement_id: int, annotation: ImageAnnotation, *, request_id: Optional[int]=None) -> str
Encode an annotation which replaces all metadata on an existing placement.
silkie.clear_image_annotation functionEncode a request to remove metadata from an existing placement.
Permalink Source ↗
hamingjur.silkie.clear_image_annotation(image_id: int, placement_id: int, *, request_id: Optional[int]=None) -> str
Encode a request to remove metadata from an existing placement.
silkie.annotate_text functionLabel a screen range with one-based (row, column) coordinates.
Permalink Source ↗
hamingjur.silkie.annotate_text(range_id: int, start: tuple[int, int], end: tuple[int, int], *, role: str, label: str='', request_id: Optional[int]=None) -> str
Label a screen range with one-based (row, column) coordinates.

The start is inclusive and the end is exclusive. The end column can be one past
the last column. The terminal checks the range against the active screen grid.

:raises ValueError: If the ID, coordinates, role or label are invalid.
silkie.clear_text_annotation functionEncode a request to remove a previously annotated text range.
Permalink Source ↗
hamingjur.silkie.clear_text_annotation(range_id: int, *, request_id: Optional[int]=None) -> str
Encode a request to remove a previously annotated text range.

:raises ValueError: If a supplied ID is outside the protocol range.
silkie.announce functionEncode one screen-reader announcement with optional assertive priority.
Permalink Source ↗
hamingjur.silkie.announce(text: str, *, priority: str='polite', request_id: Optional[int]=None) -> str
Encode one screen-reader announcement with optional assertive priority.

:raises ValueError: If the text, priority or request ID is invalid.
silkie.SpeechStyle classVoice Lock settings for a reusable style or an individual utterance.
Permalink Source ↗
hamingjur.silkie.SpeechStyle
Voice Lock settings for a reusable style or an individual utterance.
Fields & constants
voice: str | None = None
language: str | None = None
rate: int | None = None
pitch: int | None = None
pitch_range: int | None = None
volume: int | None = None
punctuation: str | None = None
split_caps: bool | None = None
silkie.speech_command functionEncode an OSC 777 speech command with unescaped text and the documented field names.
Permalink Source ↗
hamingjur.silkie.speech_command(operation: str, **fields: Field) -> str
Encode an OSC 777 speech command with unescaped text and the documented field names.

Numeric fields take integers, and the optional wire field ``id`` requests an acknowledgement.

:raises ValueError: If speech fields are outside their wire ranges or contain invalid text.
silkie.Capabilities classThe selector versions, graphics media and formats advertised by a terminal.
Permalink Source ↗
hamingjur.silkie.Capabilities(event: ProtocolEvent)
The selector versions, graphics media and formats advertised by a terminal.

Constructor
-----------
Parse a capability report, retaining its original fields.
silkie.Capabilities.supports methodCheck the advertised version of a selector, not its current hardware support.
Permalink Source ↗
hamingjur.silkie.Capabilities.supports(selector: str, version: int=1) -> bool
Check the advertised version of a selector, not its current hardware support.
silkie.Channel classOne OSC 777 selector, with commands, queries and restoring mode contexts.
Permalink Source ↗
hamingjur.silkie.Channel(client: 'Silkie', selector: str)
One OSC 777 selector, with commands, queries and restoring mode contexts.

Constructor
-----------
Bind a selector to the shared client and query transport.
silkie.Channel.command methodReturn a sequence without performing I/O.
Permalink Source ↗
hamingjur.silkie.Channel.command(operation: str, **fields: Field) -> str
Return a sequence without performing I/O.
silkie.Channel.send methodWrite and flush an operation when terminal styling is enabled.
Permalink Source ↗
hamingjur.silkie.Channel.send(operation: str, **fields: Field) -> None
Write and flush an operation when terminal styling is enabled.
silkie.Channel.query methodRead capability and current-mode fields; return None if unsupported.
Permalink Source ↗
hamingjur.silkie.Channel.query(timeout: Optional[float]=1.0) -> Optional[ProtocolEvent]
Read capability and current-mode fields; return None if unsupported.
silkie.Channel.read_mode methodRead the granted mode rather than assuming every requested bit was accepted.
Permalink Source ↗
hamingjur.silkie.Channel.read_mode(timeout: Optional[float]=1.0) -> Optional[int]
Read the granted mode rather than assuming every requested bit was accepted.
silkie.Channel.enabled context managerSet a reporting mode, yield granted bits, and restore its previous value.
Permalink Source ↗
hamingjur.silkie.Channel.enabled(mode: int=1, *, timeout: Optional[float]=1.0) -> Iterator[int]
Set a reporting mode, yield granted bits, and restore its previous value.

Raises RuntimeError when the mode cannot be read. Nested contexts restore the enclosing
mode. Cleanup runs even if read-back or application code fails.

:raises RuntimeError: If the mode is unavailable or read-back times out.
silkie.DisplayChannel classReport host display capabilities and desktop preferences over the terminal stream.
Permalink Source ↗
hamingjur.silkie.DisplayChannel(client: 'Silkie')
Bases: Channel
Report host display capabilities and desktop preferences over the terminal stream.

Constructor
-----------
Bind the display selector.
silkie.DisplayChannel.query methodQuery display capabilities and the current desktop preferences.
Permalink Source ↗
hamingjur.silkie.DisplayChannel.query(timeout: Optional[float]=1.0) -> Optional[DisplayEvent]
Query display capabilities and the current desktop preferences.
silkie.AgentChannel classExplicit SSH-agent packet transport; no sockets, key caching or automatic retries.
Permalink Source ↗
hamingjur.silkie.AgentChannel
Bases: Channel
Explicit SSH-agent packet transport; no sockets, key caching or automatic retries.
silkie.AgentChannel.query methodProbe provider availability; caps=1 requires a generation token in g.
Permalink Source ↗
hamingjur.silkie.AgentChannel.query(timeout: Optional[float]=1.0, *, identifier: Optional[str]=None) -> Optional[ProtocolEvent]
Probe provider availability; caps=1 requires a generation token in g.
silkie.AgentChannel.exchange methodExchange one complete packet, matching ID, connection and provider generation.
Permalink Source ↗
hamingjur.silkie.AgentChannel.exchange(packet: bytes, *, connection: str, generation: str, expires: int, identifier: Optional[str]=None, timeout: Optional[float]=120.0) -> Optional[ProtocolEvent]
Exchange one complete packet, matching ID, connection and provider generation.

Keep connection and generation stable for a local agent connection, probe before
each packet, and close on generation changes or timeouts. Requests are never retried.
A transport failure is returned as an agent failure packet plus an error field.
silkie.AgentChannel.close methodClose a pinned provider connection; its token must never be reused.
Permalink Source ↗
hamingjur.silkie.AgentChannel.close(connection: str, generation: str, *, identifier: Optional[str]=None) -> None
Close a pinned provider connection; its token must never be reused.
silkie.SpeechChannel classDirect a terminal host's speech queue and Voice Lock styles for the current pane.
Permalink Source ↗
hamingjur.silkie.SpeechChannel(client: 'Silkie')
Bases: Channel
Direct a terminal host's speech queue and Voice Lock styles for the current pane.

Constructor
-----------
Bind the speech selector to the terminal connection.
silkie.SpeechChannel.command methodEncode a speech command, percent-encoding utterance text and voice names.
Permalink Source ↗
hamingjur.silkie.SpeechChannel.command(operation: str, **fields: Field) -> str
Encode a speech command, percent-encoding utterance text and voice names.
silkie.SpeechChannel.query methodRead native backend capabilities, returning None if the host does not reply.
Permalink Source ↗
hamingjur.silkie.SpeechChannel.query(timeout: Optional[float]=1.0) -> Optional[SpeechCapabilities]
Read native backend capabilities, returning None if the host does not reply.
silkie.SpeechChannel.supported methodReturn whether the terminal reports an available speech backend.
Permalink Source ↗
hamingjur.silkie.SpeechChannel.supported(timeout: Optional[float]=1.0) -> bool
Return whether the terminal reports an available speech backend.
silkie.SpeechChannel.speak methodSend an utterance for playback, optionally clearing the pane's speech first.
Permalink Source ↗
hamingjur.silkie.SpeechChannel.speak(text: str, *, style: str | None=None, options: SpeechStyle | None=None, interrupt: bool=False, wait: bool=False, timeout: Optional[float]=1.0) -> Optional[SpeechAck]
Send an utterance for playback, optionally clearing the pane's speech first.
silkie.SpeechChannel.queue methodQueue a styled utterance for the next dispatch.
Permalink Source ↗
hamingjur.silkie.SpeechChannel.queue(text: str, *, style: str | None=None, options: SpeechStyle | None=None, interrupt: bool=False, wait: bool=False, timeout: Optional[float]=1.0) -> Optional[SpeechAck]
Queue a styled utterance for the next dispatch.
silkie.SpeechChannel.character methodSpeak one Unicode character using the host's character-echo behavior.
Permalink Source ↗
hamingjur.silkie.SpeechChannel.character(text: str, *, style: str | None=None, options: SpeechStyle | None=None, interrupt: bool=False, queued: bool=False, wait: bool=False, timeout: Optional[float]=1.0) -> Optional[SpeechAck]
Speak one Unicode character using the host's character-echo behavior.
silkie.SpeechChannel.sound methodPlay a native sound by name, or enqueue it for dispatch.
Permalink Source ↗
hamingjur.silkie.SpeechChannel.sound(name: str, *, queued: bool=False, interrupt: bool=False, wait: bool=False, timeout: Optional[float]=1.0) -> Optional[SpeechAck]
Play a native sound by name, or enqueue it for dispatch.
silkie.SpeechChannel.silence methodInsert a duration in milliseconds into playback, or enqueue it for dispatch.
Permalink Source ↗
hamingjur.silkie.SpeechChannel.silence(duration: int, *, queued: bool=False, interrupt: bool=False, wait: bool=False, timeout: Optional[float]=1.0) -> Optional[SpeechAck]
Insert a duration in milliseconds into playback, or enqueue it for dispatch.
silkie.SpeechChannel.set_style methodDefine or replace a named Voice Lock style in the pane.
Permalink Source ↗
hamingjur.silkie.SpeechChannel.set_style(name: str, options: SpeechStyle, *, wait: bool=False, timeout: Optional[float]=1.0) -> Optional[SpeechAck]
Define or replace a named Voice Lock style in the pane.
silkie.SpeechChannel.clear_style methodRemove a previously defined style.
Permalink Source ↗
hamingjur.silkie.SpeechChannel.clear_style(name: str, *, wait: bool=False, timeout: Optional[float]=1.0) -> Optional[SpeechAck]
Remove a previously defined style.
silkie.SpeechChannel.dispatch methodSend the queued utterances, sounds, and silence to playback in order.
Permalink Source ↗
hamingjur.silkie.SpeechChannel.dispatch(*, wait: bool=False, timeout: Optional[float]=1.0) -> Optional[SpeechAck]
Send the queued utterances, sounds, and silence to playback in order.
silkie.SpeechChannel.pause methodPause playback in the current pane.
Permalink Source ↗
hamingjur.silkie.SpeechChannel.pause(*, wait: bool=False, timeout: Optional[float]=1.0) -> Optional[SpeechAck]
Pause playback in the current pane.
silkie.SpeechChannel.resume methodResume paused speech in the current pane.
Permalink Source ↗
hamingjur.silkie.SpeechChannel.resume(*, wait: bool=False, timeout: Optional[float]=1.0) -> Optional[SpeechAck]
Resume paused speech in the current pane.
silkie.SpeechChannel.stop methodInterrupt playback and clear the pane's speech queues.
Permalink Source ↗
hamingjur.silkie.SpeechChannel.stop(*, wait: bool=False, timeout: Optional[float]=1.0) -> Optional[SpeechAck]
Interrupt playback and clear the pane's speech queues.
silkie.SpeechChannel.reset methodStop playback, clear the queues, and remove the pane's Voice Lock styles.
Permalink Source ↗
hamingjur.silkie.SpeechChannel.reset(*, wait: bool=False, timeout: Optional[float]=1.0) -> Optional[SpeechAck]
Stop playback, clear the queues, and remove the pane's Voice Lock styles.
silkie.Accessibility classSilkie image and text annotations and screen-reader announcements.
Permalink Source ↗
hamingjur.silkie.Accessibility(client: 'Silkie')
Silkie image and text annotations and screen-reader announcements.

Constructor
-----------
Bind annotation writes and acknowledgements to a Silkie client.
silkie.Accessibility.supported methodCheck discovery for the required accessibility version.
Permalink Source ↗
hamingjur.silkie.Accessibility.supported(timeout: Optional[float]=1.0, *, force: bool=False, version: int=1) -> bool
Check discovery for the required accessibility version.
silkie.Accessibility.set_image methodAnnotate a placed image and optionally return the correlated terminal reply.
Permalink Source ↗
hamingjur.silkie.Accessibility.set_image(image_id: int, placement_id: int, annotation: ImageAnnotation, *, wait: bool=True, timeout: Optional[float]=1.0) -> Optional[AccessibilityAck]
Annotate a placed image and optionally return the correlated terminal reply.
silkie.Accessibility.clear_image methodClear a placement's annotation and optionally return the correlated terminal reply.
Permalink Source ↗
hamingjur.silkie.Accessibility.clear_image(image_id: int, placement_id: int, *, wait: bool=True, timeout: Optional[float]=1.0) -> Optional[AccessibilityAck]
Clear a placement's annotation and optionally return the correlated terminal reply.
silkie.Accessibility.set_text methodLabel a screen range and optionally return the correlated terminal reply.
Permalink Source ↗
hamingjur.silkie.Accessibility.set_text(range_id: int, start: tuple[int, int], end: tuple[int, int], *, role: str, label: str='', wait: bool=True, timeout: Optional[float]=1.0) -> Optional[AccessibilityAck]
Label a screen range and optionally return the correlated terminal reply.
silkie.Accessibility.clear_text methodClear a screen range's annotation and optionally return the terminal reply.
Permalink Source ↗
hamingjur.silkie.Accessibility.clear_text(range_id: int, *, wait: bool=True, timeout: Optional[float]=1.0) -> Optional[AccessibilityAck]
Clear a screen range's annotation and optionally return the terminal reply.
silkie.Accessibility.announce methodRequest one screen-reader announcement and optionally return the terminal reply.
Permalink Source ↗
hamingjur.silkie.Accessibility.announce(text: str, *, priority: str='polite', wait: bool=True, timeout: Optional[float]=1.0) -> Optional[AccessibilityAck]
Request one screen-reader announcement and optionally return the terminal reply.
silkie.Silkie classBound Silkie protocol client, available as ``term.silkie``.
Permalink Source ↗
hamingjur.silkie.Silkie(terminal: 'Terminal')
Bound Silkie protocol client, available as ``term.silkie``.

Every selector has a named channel. Commands use documented field names,
including device descriptions/labels, brush configuration and haptic patterns.
Received messages are available through ``term.inkey().protocol_event``.

Constructor
-----------
Create channels and per-terminal discovery state.
silkie.Silkie.channel methodAccess a future selector without waiting for a library update.
Permalink Source ↗
hamingjur.silkie.Silkie.channel(selector: str) -> Channel
Access a future selector without waiting for a library update.
silkie.Silkie.next_id methodAllocate a correlation ID, rejecting exhaustion of the protocol's 31-bit space.
Permalink Source ↗
hamingjur.silkie.Silkie.next_id() -> int
Allocate a correlation ID, rejecting exhaustion of the protocol's 31-bit space.
silkie.Silkie.write methodWrite an explicit command; redirected plain-text output remains escape-free.
Permalink Source ↗
hamingjur.silkie.Silkie.write(sequence: str) -> None
Write an explicit command; redirected plain-text output remains escape-free.
silkie.Silkie.request methodMatch only this reply, retaining keyboard input and unrelated extension events.
Permalink Source ↗
hamingjur.silkie.Silkie.request(sequence: str, selector: str, operation: str, timeout: Optional[float], request_id: Optional[Union[int, str]]=None, **reply_fields: Field) -> Optional[ProtocolEvent]
Match only this reply, retaining keyboard input and unrelated extension events.
silkie.Silkie.capabilities methodDiscover selectors/formats/media; cache successful discovery only.
Permalink Source ↗
hamingjur.silkie.Silkie.capabilities(timeout: Optional[float]=1.0, *, force: bool=False) -> Optional[Capabilities]
Discover selectors/formats/media; cache successful discovery only.
silkie.Silkie.reset methodExplicitly disable all Silkie reporting modes in this terminal window.
Permalink Source ↗
hamingjur.silkie.Silkie.reset() -> None
Explicitly disable all Silkie reporting modes in this terminal window.
silkie.Silkie.select_font methodSelect terminal-cell typography; slant is in hundredths of a degree.
Permalink Source ↗
hamingjur.silkie.Silkie.select_font(*, role: Optional[str]=None, weight: Optional[int]=None, slant: Optional[Union[str, int]]=None, italic: Optional[bool]=None) -> str
Select terminal-cell typography; slant is in hundredths of a degree.
silkie.Silkie.label_button methodLabel a tablet-pad button with Unicode text.
Permalink Source ↗
hamingjur.silkie.Silkie.label_button(device: int, button: int, text: str) -> str
Label a tablet-pad button with Unicode text.
hamingjur.protocols44 entries

Pure Python framing and events for Kitty and Silkie terminal protocols.

protocols.integer functionValidate an integer, with upper bounds only where the protocol requires them.
Permalink Source ↗
hamingjur.protocols.integer(value: int, name: str, minimum: int=0, maximum: Optional[int]=None) -> int
Validate an integer, with upper bounds only where the protocol requires them.

:raises ValueError: If the value is not an integer in the protocol range.
protocols.token functionValidate a protocol selector or field name without restricting its length.
Permalink Source ↗
hamingjur.protocols.token(value: str) -> str
Validate a protocol selector or field name without restricting its length.

:raises ValueError: If the name contains characters outside the protocol alphabet.
protocols.safe functionValidate an ASCII field so it cannot inject another field or escape sequence.
Permalink Source ↗
hamingjur.protocols.safe(value: Field, forbidden: str=':;') -> str
Validate an ASCII field so it cannot inject another field or escape sequence.

:raises ValueError: If a field contains control characters or delimiters.
protocols.encode_fields functionEncode fields, retaining insertion order and unknown extension keys.
Permalink Source ↗
hamingjur.protocols.encode_fields(fields: Mapping[str, Field], separator: str=':') -> str
Encode fields, retaining insertion order and unknown extension keys.
protocols.parse_fields functionDecode fields; reject duplicate keys and malformed framing.
Permalink Source ↗
hamingjur.protocols.parse_fields(text: str, separator: str=':', *, repeated: bool=False) -> Dict[str, str]
Decode fields; reject duplicate keys and malformed framing.

:raises ValueError: If fields are malformed or contain forbidden duplicate keys.
protocols.b64 functionEncode binary data for terminal transport.
Permalink Source ↗
hamingjur.protocols.b64(data: bytes) -> str
Encode binary data for terminal transport.
protocols.unb64 functionDecode base64, accepting the optional padding used by Kitty protocols.
Permalink Source ↗
hamingjur.protocols.unb64(data: str) -> bytes
Decode base64, accepting the optional padding used by Kitty protocols.
protocols.agent_token functionValidate an SSH-agent ID, connection or generation, with no length cap.
Permalink Source ↗
hamingjur.protocols.agent_token(value: str) -> str
Validate an SSH-agent ID, connection or generation, with no length cap.

:raises ValueError: If the token is empty or outside its wire alphabet.
protocols.agent_packet functionValidate exactly one SSH agent packet, including its unsigned 32-bit length.
Permalink Source ↗
hamingjur.protocols.agent_packet(data: bytes) -> bytes
Validate exactly one SSH agent packet, including its unsigned 32-bit length.

:raises ValueError: If the packet is truncated or has trailing data.
protocols.notification_hops functionDecode an OSC 99 return route, ordered from application to outer terminal.
Permalink Source ↗
hamingjur.protocols.notification_hops(route: str) -> tuple[tuple[str, str, int], ...]
Decode an OSC 99 return route, ordered from application to outer terminal.

:raises ValueError: If a hop has invalid components, delimiters or a window ID.
protocols.ProtocolEvent classA complete terminal message, preserving all fields and its wire representation.
Permalink Source ↗
hamingjur.protocols.ProtocolEvent
A complete terminal message, preserving all fields and its wire representation.
Fields & constants
protocol: str
fields: Mapping[str, str]
payload: str = ''
raw: str = ''
protocols.ProtocolEvent.integer methodRead a decimal integer field without losing missing-value information.
Permalink Source ↗
hamingjur.protocols.ProtocolEvent.integer(key: str, default: Optional[int]=None) -> Optional[int]
Read a decimal integer field without losing missing-value information.

:raises ValueError: If the value is not an integer in the protocol range.
protocols.ProtocolEvent.number methodRead a finite numeric field, such as display headroom or scale.
Permalink Source ↗
hamingjur.protocols.ProtocolEvent.number(key: str) -> Optional[float]
Read a finite numeric field, such as display headroom or scale.

:raises ValueError: If the field is not a finite number.
protocols.ProtocolEvent.data propertyDecode a binary payload (call only for payload types defined as base64).
Permalink Source ↗
hamingjur.protocols.ProtocolEvent.data -> bytes
Decode a binary payload (call only for payload types defined as base64).
protocols.ProtocolEvent.values methodAll values for a repeated notification metadata key, in wire order.
Permalink Source ↗
hamingjur.protocols.ProtocolEvent.values(key: str) -> tuple[str, ...]
All values for a repeated notification metadata key, in wire order.
protocols.ProtocolEvent.operation propertyReturn the Silkie operation or Kitty message type/action.
Permalink Source ↗
hamingjur.protocols.ProtocolEvent.operation -> str
Return the Silkie operation or Kitty message type/action.
protocols.ProtocolEvent.notification_route propertyNotification return hops; effective actions remain in fields['a'].
Permalink Source ↗
hamingjur.protocols.ProtocolEvent.notification_route -> tuple[tuple[str, str, int], ...]
Notification return hops; effective actions remain in fields['a'].
protocols.ProtocolEvent.timestamp propertySilkie monotonic event time in seconds, including microsecond precision.
Permalink Source ↗
hamingjur.protocols.ProtocolEvent.timestamp -> Optional[float]
Silkie monotonic event time in seconds, including microsecond precision.
protocols.ProtocolEvent.position propertySilkie physical pixel position; raw 1/256-pixel values remain in fields.
Permalink Source ↗
hamingjur.protocols.ProtocolEvent.position -> Optional[tuple[float, float]]
Silkie physical pixel position; raw 1/256-pixel values remain in fields.
protocols.TabletEvent classPen, touch, tablet-pad, device and tool reports, including future fields.
Permalink Source ↗
hamingjur.protocols.TabletEvent
Bases: ProtocolEvent
Pen, touch, tablet-pad, device and tool reports, including future fields.
protocols.TabletEvent.position propertyPhysical pixels for screen reports; touchpad reports use touchpad_position.
Permalink Source ↗
hamingjur.protocols.TabletEvent.position -> Optional[tuple[float, float]]
Physical pixels for screen reports; touchpad reports use touchpad_position.
protocols.TabletEvent.touchpad_position propertyNormalized finger position on a touchpad, distinct from screen pixels.
Permalink Source ↗
hamingjur.protocols.TabletEvent.touchpad_position -> Optional[tuple[float, float]]
Normalized finger position on a touchpad, distinct from screen pixels.
protocols.TabletEvent.pressure propertyNormalized pressure, or None when the report does not mark it valid.
Permalink Source ↗
hamingjur.protocols.TabletEvent.pressure -> Optional[float]
Normalized pressure, or None when the report does not mark it valid.
protocols.TabletEvent.tilt propertyPen tilt in degrees, or None when absent or not valid.
Permalink Source ↗
hamingjur.protocols.TabletEvent.tilt -> Optional[tuple[float, float]]
Pen tilt in degrees, or None when absent or not valid.
protocols.TabletEvent.device_name propertyDecode a device report's UTF-8 name.
Permalink Source ↗
hamingjur.protocols.TabletEvent.device_name -> Optional[str]
Decode a device report's UTF-8 name.
protocols.DisplayAppearance classDesktop appearance preferences reported by the host terminal.
Permalink Source ↗
hamingjur.protocols.DisplayAppearance
Bases: str, Enum
Desktop appearance preferences reported by the host terminal.
Fields & constants
LIGHT = 'light'
DARK = 'dark'
NO_PREFERENCE = 'no_preference'
protocols.DisplayEvent classA Silkie display capability report or change event.
Permalink Source ↗
hamingjur.protocols.DisplayEvent
Bases: ProtocolEvent
A Silkie display capability report or change event.
protocols.DisplayEvent.appearance propertyReturn the host desktop preference, including when the field is unknown.
Permalink Source ↗
hamingjur.protocols.DisplayEvent.appearance -> DisplayAppearance
Return the host desktop preference, including when the field is unknown.
protocols.DisplayEvent.eink_scheme propertyReturn Silkie's effective e-paper palette when it is reported.
Permalink Source ↗
hamingjur.protocols.DisplayEvent.eink_scheme -> Optional[DisplayAppearance]
Return Silkie's effective e-paper palette when it is reported.
protocols.DisplayEvent.high_contrast propertyReturn whether the host requests high contrast.
Permalink Source ↗
hamingjur.protocols.DisplayEvent.high_contrast -> bool
Return whether the host requests high contrast.
protocols.DisplayEvent.differentiate_without_color propertyReturn whether the host requests color-independent distinctions.
Permalink Source ↗
hamingjur.protocols.DisplayEvent.differentiate_without_color -> bool
Return whether the host requests color-independent distinctions.
protocols.DisplayEvent.languages propertyReturn reported language tags in preference order, or an empty tuple.
Permalink Source ↗
hamingjur.protocols.DisplayEvent.languages -> tuple[str, ...]
Return reported language tags in preference order, or an empty tuple.
protocols.AgentEvent classSSH-agent transport reply, retaining generation, connection and failure fields.
Permalink Source ↗
hamingjur.protocols.AgentEvent
Bases: ProtocolEvent
SSH-agent transport reply, retaining generation, connection and failure fields.
protocols.AgentEvent.data propertyDecode and validate the complete packet in the data field of a reply.
Permalink Source ↗
hamingjur.protocols.AgentEvent.data -> bytes
Decode and validate the complete packet in the data field of a reply.
protocols.AccessibilityAck classA Silkie accessibility acknowledgement.
Permalink Source ↗
hamingjur.protocols.AccessibilityAck
Bases: ProtocolEvent
A Silkie accessibility acknowledgement.
protocols.AccessibilityAck.status propertyReturn the terminal's status, including errors such as ENOENT or ENOMEM.
Permalink Source ↗
hamingjur.protocols.AccessibilityAck.status -> str
Return the terminal's status, including errors such as ENOENT or ENOMEM.
protocols.SpeechAck classAcknowledgement of a Silkie speech command.
Permalink Source ↗
hamingjur.protocols.SpeechAck
Bases: ProtocolEvent
Acknowledgement of a Silkie speech command.
protocols.SpeechAck.status propertyReturn the terminal's command status.
Permalink Source ↗
hamingjur.protocols.SpeechAck.status -> str
Return the terminal's command status.
protocols.SpeechCapabilities classSpeech backend capabilities reported by the terminal host.
Permalink Source ↗
hamingjur.protocols.SpeechCapabilities
Bases: ProtocolEvent
Speech backend capabilities reported by the terminal host.
protocols.SpeechCapabilities.available propertyReturn whether the terminal reports a speech backend.
Permalink Source ↗
hamingjur.protocols.SpeechCapabilities.available -> bool
Return whether the terminal reports a speech backend.
protocols.SpeechCapabilities.engine propertyReturn the host backend identifier.
Permalink Source ↗
hamingjur.protocols.SpeechCapabilities.engine -> str
Return the host backend identifier.
protocols.SpeechCapabilities.pitch_range propertyReturn whether the backend accepts pitch range adjustments.
Permalink Source ↗
hamingjur.protocols.SpeechCapabilities.pitch_range -> bool
Return whether the backend accepts pitch range adjustments.
protocols.incomplete_frame functionWhether text starts with a recognized but unfinished string protocol.
Permalink Source ↗
hamingjur.protocols.incomplete_frame(text: str) -> bool
Whether text starts with a recognized but unfinished string protocol.
protocols.parse_event functionParse one complete protocol frame, rejecting incomplete or trailing data.
Permalink Source ↗
hamingjur.protocols.parse_event(raw: str) -> ProtocolEvent
Parse one complete protocol frame, rejecting incomplete or trailing data.

:raises ValueError: If framing, fields, or the protocol version are invalid.
hamingjur.kitty22 entries

Kitty terminal protocol commands, including clipboard, DnD and file transfer.

kitty.notification_route functionEncode Silkie notification return hops for the r metadata field, without a hop cap.
Permalink Source ↗
hamingjur.kitty.notification_route(hops: Iterable[tuple[str, str, int]]) -> str
Encode Silkie notification return hops for the r metadata field, without a hop cap.
kitty.notification_packet functionEncode notification controls with repeated keys (such as multiple icon names/types).
Permalink Source ↗
hamingjur.kitty.notification_packet(payload: str='', *, metadata: Iterable[tuple[str, Field]]=()) -> str
Encode notification controls with repeated keys (such as multiple icon names/types).

:raises ValueError: If arguments or protocol data are invalid.
kitty.packet functionEncode an OSC metadata/payload packet, rejecting terminal control injection.
Permalink Source ↗
hamingjur.kitty.packet(code: int, payload: str='', **fields: Field) -> str
Encode an OSC metadata/payload packet, rejecting terminal control injection.

:raises ValueError: If arguments or protocol data are invalid.
kitty.clipboard_read functionRequest MIME types (or '.' to list types); responses arrive as protocol events.
Permalink Source ↗
hamingjur.kitty.clipboard_read(mime_types: Iterable[str]=('text/plain',), **fields: Field) -> str
Request MIME types (or '.' to list types); responses arrive as protocol events.
kitty.clipboard_write functionStream a multi-format clipboard transaction, then commit it.
Permalink Source ↗
hamingjur.kitty.clipboard_write(content: Mapping[str, Data], **fields: Field) -> Iterator[str]
Stream a multi-format clipboard transaction, then commit it.
kitty.clipboard_alias functionAdd MIME aliases between a clipboard write's opening and commit packets.
Permalink Source ↗
hamingjur.kitty.clipboard_alias(mime: str, aliases: Iterable[str]) -> str
Add MIME aliases between a clipboard write's opening and commit packets.
kitty.notification functionStream a notification payload, including text, icons and buttons, using base64.
Permalink Source ↗
hamingjur.kitty.notification(payload: Data, *, identifier: str, kind: str='title', done: bool=True, **fields: Field) -> Iterator[str]
Stream a notification payload, including text, icons and buttons, using base64.

:raises ValueError: If arguments or protocol data are invalid.
kitty.notify functionCreate a desktop notification with arbitrarily long Unicode title and body.
Permalink Source ↗
hamingjur.kitty.notify(title: str, body: str='', *, identifier: Optional[str]=None, **fields: Field) -> Iterator[str]
Create a desktop notification with arbitrarily long Unicode title and body.
kitty.dnd functionEncode any drag/drop operation with its documented t/x/y/X/Y/o/i keys.
Permalink Source ↗
hamingjur.kitty.dnd(operation: str, payload: str='', **fields: Field) -> str
Encode any drag/drop operation with its documented t/x/y/X/Y/o/i keys.

:raises ValueError: If arguments or protocol data are invalid.
kitty.dnd_data functionStream base64 DnD data/images, preserving metadata only on the first chunk.
Permalink Source ↗
hamingjur.kitty.dnd_data(operation: str, data: Data, **fields: Field) -> Iterator[str]
Stream base64 DnD data/images, preserving metadata only on the first chunk.

:raises ValueError: If arguments or protocol data are invalid.
kitty.file_transfer functionEncode a file-transfer command using descriptive field names.
Permalink Source ↗
hamingjur.kitty.file_transfer(action: str, **fields: object) -> str
Encode a file-transfer command using descriptive field names.

Handles all commands and transports, including rsync signature/delta bytes. Applications own the
transfer state, filesystem decisions and rsync algorithm. No local files are opened as a side
effect of receiving a terminal message.

:raises TypeError: If a payload has the wrong type.
:raises ValueError: If arguments or protocol data are invalid.
kitty.file_data functionStream one file/signature/delta, ending with end_data (no total-size cap).
Permalink Source ↗
hamingjur.kitty.file_data(data: Data, **fields: object) -> Iterator[str]
Stream one file/signature/delta, ending with end_data (no total-size cap).
kitty.pointer functionSet, push (>), pop (<) or query (?) shapes, including Silkie image:i:x:y pointers.
Permalink Source ↗
hamingjur.kitty.pointer(shape: str='', *, action: str='=') -> str
Set, push (>), pop (<) or query (?) shapes, including Silkie image:i:x:y pointers.

:raises ValueError: If arguments or protocol data are invalid.
kitty.colors functionSet/query/reset colors; values are color specs, '?' for queries or '' for resets.
Permalink Source ↗
hamingjur.kitty.colors(values: Mapping[Union[str, int], str]) -> str
Set/query/reset colors; values are color specs, '?' for queries or '' for resets.
kitty.cursors functionEncode multi-cursor shapes/colors/queries; coordinate groups use the wire syntax.
Permalink Source ↗
hamingjur.kitty.cursors(shape: int, coordinates: Iterable[Iterable[int]]=()) -> str
Encode multi-cursor shapes/colors/queries; coordinate groups use the wire syntax.
kitty.region_style functionSet SGR attributes in a 1-based inclusive rectangle using extended DECCARA.
Permalink Source ↗
hamingjur.kitty.region_style(top: int, left: int, bottom: int, right: int, sgr: str) -> str
Set SGR attributes in a 1-based inclusive rectangle using extended DECCARA.

:raises ValueError: If arguments or protocol data are invalid.
kitty.Kitty classExplicit output and restoring contexts, bound to a Terminal instance.
Permalink Source ↗
hamingjur.kitty.Kitty(terminal: 'Terminal')
Explicit output and restoring contexts, bound to a Terminal instance.

Constructor
-----------
Bind explicit output operations to a terminal's stream.
kitty.Kitty.send methodWrite one sequence or an iterator of chunks, flushing at completion.
Permalink Source ↗
hamingjur.kitty.Kitty.send(sequences: Union[str, Iterable[str]]) -> None
Write one sequence or an iterator of chunks, flushing at completion.
kitty.Kitty.pointer context managerPush a pointer shape and pop it on exit.
Permalink Source ↗
hamingjur.kitty.Kitty.pointer(shape: str) -> Iterator[None]
Push a pointer shape and pop it on exit.
kitty.Kitty.colors_saved context managerSave and restore dynamic colors and the ANSI palette.
Permalink Source ↗
hamingjur.kitty.Kitty.colors_saved() -> Iterator[None]
Save and restore dynamic colors and the ANSI palette.
kitty.Kitty.modes_saved context managerSave and restore all side-effect-free private modes (Kitty XTSAVE/XTRESTORE).
Permalink Source ↗
hamingjur.kitty.Kitty.modes_saved() -> Iterator[None]
Save and restore all side-effect-free private modes (Kitty XTSAVE/XTRESTORE).
kitty.Kitty.drops_enabled context managerAccept drops during this context; disables acceptance on exit.
Permalink Source ↗
hamingjur.kitty.Kitty.drops_enabled(mime_types: Iterable[str]=()) -> Iterator[None]
Accept drops during this context; disables acceptance on exit.
hamingjur.ui.desktop51 entries

Terminal desktop, overlapping windows, commands and menus.

ui.desktop.MenuItem classA command, submenu or separator. Mark a mnemonic with an ampersand.
Permalink Source ↗
hamingjur.ui.desktop.MenuItem
A command, submenu or separator. Mark a mnemonic with an ampersand.
Fields & constants
label: str
action: Action | None = None
shortcut: str = ''
items: tuple[MenuItem, ...] = ()
enabled: bool = True
ui.desktop.MenuItem.submenu methodBuild a submenu from a sequence of commands.
Permalink Source ↗
hamingjur.ui.desktop.MenuItem.submenu(label: str, *items: MenuItem) -> MenuItem
Build a submenu from a sequence of commands.
ui.desktop.MenuItem.text propertyReturn the label without its mnemonic marker.
Permalink Source ↗
hamingjur.ui.desktop.MenuItem.text -> str
Return the label without its mnemonic marker.
ui.desktop.MenuItem.mnemonic propertyReturn the access key, if one was marked.
Permalink Source ↗
hamingjur.ui.desktop.MenuItem.mnemonic -> str
Return the access key, if one was marked.
ui.desktop.StatusItem classA visible, clickable shortcut in the status line.
Permalink Source ↗
hamingjur.ui.desktop.StatusItem
A visible, clickable shortcut in the status line.
Fields & constants
shortcut: str
label: str
action: Action
ui.desktop.MenuBar classPull-down and cascading menus shared by keyboard and pointer input.
Permalink Source ↗
hamingjur.ui.desktop.MenuBar(menus: Iterable[MenuItem]=())
Pull-down and cascading menus shared by keyboard and pointer input.

Constructor
-----------
Set the top-level menus.
ui.desktop.MenuBar.open propertyReturn whether a menu is taking input.
Permalink Source ↗
hamingjur.ui.desktop.MenuBar.open -> bool
Return whether a menu is taking input.
ui.desktop.MenuBar.close methodDismiss the current menu hierarchy.
Permalink Source ↗
hamingjur.ui.desktop.MenuBar.close() -> None
Dismiss the current menu hierarchy.
ui.desktop.MenuBar.show methodOpen a top-level menu.
Permalink Source ↗
hamingjur.ui.desktop.MenuBar.show(index: int=0) -> bool
Open a top-level menu.
ui.desktop.MenuBar.popup methodOpen a context menu independently of the menu bar.
Permalink Source ↗
hamingjur.ui.desktop.MenuBar.popup(items: Iterable[MenuItem], x: int, y: int) -> None
Open a context menu independently of the menu bar.
ui.desktop.MenuBar.draw_bar methodDraw the menu bar and remember its clickable spans.
Permalink Source ↗
hamingjur.ui.desktop.MenuBar.draw_bar(surface: Surface) -> None
Draw the menu bar and remember its clickable spans.
ui.desktop.MenuBar.draw_dropdowns methodDraw the active submenu chain above the windows.
Permalink Source ↗
hamingjur.ui.desktop.MenuBar.draw_dropdowns(canvas: Canvas, area: Rect) -> None
Draw the active submenu chain above the windows.
ui.desktop.MenuBar.on_key methodOpen by mnemonic or navigate the active menu.
Permalink Source ↗
hamingjur.ui.desktop.MenuBar.on_key(key: Keystroke | str) -> bool
Open by mnemonic or navigate the active menu.
ui.desktop.MenuBar.on_pointer methodPress or hover over menus and invoke commands with a click.
Permalink Source ↗
hamingjur.ui.desktop.MenuBar.on_pointer(pointer: Pointer) -> bool
Press or hover over menus and invoke commands with a click.
ui.desktop.MenuBar.dispatch_shortcut methodDispatch a shortcut from any enabled menu branch.
Permalink Source ↗
hamingjur.ui.desktop.MenuBar.dispatch_shortcut(name: str) -> bool
Dispatch a shortcut from any enabled menu branch.
ui.desktop.Window classAn overlapping desktop window with its own focus and child layout.
Permalink Source ↗
hamingjur.ui.desktop.Window(title: str, content: Widget, bounds: Rect=Rect(3, 2, 48, 14), *, minimum: tuple[int, int]=(12, 4), resizable: bool=True, closable: bool=True, on_close: Callable[[object], None] | None=None, help_topic: str | None=None, framed: bool=True)
An overlapping desktop window with its own focus and child layout.

Constructor
-----------
Create a window whose requested bounds are fitted to the desktop.
Fields & constants
modal = False
ui.desktop.Window.layout methodFit the window to the current screen and update focus.
Permalink Source ↗
hamingjur.ui.desktop.Window.layout(area: Rect) -> None
Fit the window to the current screen and update focus.
ui.desktop.Window.cycle_focus methodMove focus between enabled controls.
Permalink Source ↗
hamingjur.ui.desktop.Window.cycle_focus(step: int) -> None
Move focus between enabled controls.
ui.desktop.Window.draw methodDraw the frame, chrome, and clipped window content.
Permalink Source ↗
hamingjur.ui.desktop.Window.draw(canvas: Canvas, active: bool) -> None
Draw the frame, chrome, and clipped window content.
ui.desktop.Window.close methodClose this window and report a result to its callback.
Permalink Source ↗
hamingjur.ui.desktop.Window.close(result: object=None) -> None
Close this window and report a result to its callback.
ui.desktop.Window.on_key methodHandle a key left unconsumed by the focused widget.
Permalink Source ↗
hamingjur.ui.desktop.Window.on_key(key: Keystroke | str) -> bool
Handle a key left unconsumed by the focused widget.
ui.desktop.Dialog classA modal window with a default action and cancellation.
Permalink Source ↗
hamingjur.ui.desktop.Dialog(title: str, content: Widget, bounds: Rect=Rect(0, 0, 50, 12), *, default: Action | None=None, **options)
Bases: Window
A modal window with a default action and cancellation.

Constructor
-----------
Set the Return action for fields that do not consume Return themselves.
Fields & constants
modal = True
ui.desktop.Dialog.on_key methodCancel on Escape or run the default action on Return.
Permalink Source ↗
hamingjur.ui.desktop.Dialog.on_key(key: Keystroke | str) -> bool
Cancel on Escape or run the default action on Return.
ui.desktop.Application classDrive a themed desktop with Hamingjur's keyboard, mouse and resize APIs.
Permalink Source ↗
hamingjur.ui.desktop.Application(terminal: Terminal | None=None, *, theme: Theme | None=None, appearance: Appearance | None=None, menus: Iterable[MenuItem]=(), status: Iterable[StatusItem]=(), mouse: bool | None=None, bars: bool=True)
Drive a themed desktop with Hamingjur's keyboard, mouse and resize APIs.

Constructor
-----------
Bind a terminal and configure the desktop's appearance and commands.
ui.desktop.Application.theme propertyReturn the explicit palette or the palette for the reported display preference.
Permalink Source ↗
hamingjur.ui.desktop.Application.theme -> Theme
Return the explicit palette or the palette for the reported display preference.
ui.desktop.Application.follows_display_appearance propertyReturn whether the palette follows the terminal's display reports.
Permalink Source ↗
hamingjur.ui.desktop.Application.follows_display_appearance -> bool
Return whether the palette follows the terminal's display reports.
ui.desktop.Application.display_appearance propertyReturn the last reported desktop appearance.
Permalink Source ↗
hamingjur.ui.desktop.Application.display_appearance -> DisplayAppearance
Return the last reported desktop appearance.
ui.desktop.Application.display_report propertyReturn the most recent display report, if one was received.
Permalink Source ↗
hamingjur.ui.desktop.Application.display_report -> DisplayEvent | None
Return the most recent display report, if one was received.
ui.desktop.Application.language propertyReturn the language selected for the desktop's built-in controls.
Permalink Source ↗
hamingjur.ui.desktop.Application.language -> str
Return the language selected for the desktop's built-in controls.
ui.desktop.Application.active_window propertyReturn the topmost window.
Permalink Source ↗
hamingjur.ui.desktop.Application.active_window -> Window | None
Return the topmost window.
ui.desktop.Application.work_area propertyReturn the area below the menu and above the status line.
Permalink Source ↗
hamingjur.ui.desktop.Application.work_area -> Rect
Return the area below the menu and above the status line.
ui.desktop.Application.bind methodBind a shortcut using names such as Ctrl+O, Alt+F, or F5.
Permalink Source ↗
hamingjur.ui.desktop.Application.bind(shortcut: str, action: Action) -> None
Bind a shortcut using names such as Ctrl+O, Alt+F, or F5.
ui.desktop.Application.set_status methodSet the application message in the bottom bar.
Permalink Source ↗
hamingjur.ui.desktop.Application.set_status(message: str, *, error: bool=False) -> None
Set the application message in the bottom bar.
ui.desktop.Application.add methodShow a new window, automatically centering modal dialogs.
Permalink Source ↗
hamingjur.ui.desktop.Application.add(window: Window, *, center: bool=False) -> Window
Show a new window, automatically centering modal dialogs.
ui.desktop.Application.close methodRemove a window and call its close handler after restoring focus.
Permalink Source ↗
hamingjur.ui.desktop.Application.close(window: Window, result: object=None) -> None
Remove a window and call its close handler after restoring focus.
ui.desktop.Application.activate methodBring a modeless window to front when no modal dialog owns input.
Permalink Source ↗
hamingjur.ui.desktop.Application.activate(window: Window) -> None
Bring a modeless window to front when no modal dialog owns input.
ui.desktop.Application.next_window methodCycle between desktop windows.
Permalink Source ↗
hamingjur.ui.desktop.Application.next_window(step: int=1) -> None
Cycle between desktop windows.
ui.desktop.Application.tile methodArrange windows into a responsive grid with no overlap.
Permalink Source ↗
hamingjur.ui.desktop.Application.tile() -> None
Arrange windows into a responsive grid with no overlap.
ui.desktop.Application.cascade methodArrange windows with successively offset title bars.
Permalink Source ↗
hamingjur.ui.desktop.Application.cascade() -> None
Arrange windows with successively offset title bars.
ui.desktop.Application.maximize methodToggle maximization while preserving the normal window bounds.
Permalink Source ↗
hamingjur.ui.desktop.Application.maximize(window: Window | None=None) -> None
Toggle maximization while preserving the normal window bounds.
ui.desktop.Application.move_window methodEnter keyboard move or resize mode for a window.
Permalink Source ↗
hamingjur.ui.desktop.Application.move_window(window: Window | None=None, *, resize: bool=False) -> None
Enter keyboard move or resize mode for a window.
ui.desktop.Application.stop methodEnd the event loop and return a caller-provided result.
Permalink Source ↗
hamingjur.ui.desktop.Application.stop(result: object=None) -> None
End the event loop and return a caller-provided result.
ui.desktop.Application.draw methodCompose and present the current screen, returning the rendered cells.
Permalink Source ↗
hamingjur.ui.desktop.Application.draw() -> Canvas
Compose and present the current screen, returning the rendered cells.
ui.desktop.Application.visible_images propertyReturn fully visible image views from the last frame in reading order.
Permalink Source ↗
hamingjur.ui.desktop.Application.visible_images -> tuple[ImageView, ...]
Return fully visible image views from the last frame in reading order.
ui.desktop.Application.review_image methodOpen one image's full text description in a keyboard-accessible dialog.
Permalink Source ↗
hamingjur.ui.desktop.Application.review_image(view: ImageView) -> Dialog
Open one image's full text description in a keyboard-accessible dialog.
ui.desktop.Application.review_images methodReview the desktop's visible image descriptions, including on text-only terminals.
Permalink Source ↗
hamingjur.ui.desktop.Application.review_images(*, include_decorative: bool=False) -> Dialog
Review the desktop's visible image descriptions, including on text-only terminals.
ui.desktop.Application.release_images methodRelease terminal placements when using a custom event loop.
Permalink Source ↗
hamingjur.ui.desktop.Application.release_images() -> None
Release terminal placements when using a custom event loop.
ui.desktop.Application.dispatch methodProcess an input or display event independently of the terminal loop.
Permalink Source ↗
hamingjur.ui.desktop.Application.dispatch(event: Keystroke | str | Pointer | DisplayEvent) -> bool
Process an input or display event independently of the terminal loop.
ui.desktop.Application.choose_history methodChoose a previous entry for an input field in a modal history window.
Permalink Source ↗
hamingjur.ui.desktop.Application.choose_history(field: InputLine) -> None
Choose a previous entry for an input field in a modal history window.
ui.desktop.Application.screen_reader context managerExpose native screen-reader text roles in an interactive screen context.
Permalink Source ↗
hamingjur.ui.desktop.Application.screen_reader() -> Iterator[bool]
Expose native screen-reader text roles in an interactive screen context.
ui.desktop.Application.run methodEnter terminal modes until stop is called, then restore them on exit.
Permalink Source ↗
hamingjur.ui.desktop.Application.run() -> object
Enter terminal modes until stop is called, then restore them on exit.
hamingjur.ui.widgets88 entries

Reusable controls, containers, list views and scrolling.

ui.widgets.key_name functionNormalize Hamingjur key names and ASCII fallback chords.
Permalink Source ↗
hamingjur.ui.widgets.key_name(key: Keystroke | str) -> str
Normalize Hamingjur key names and ASCII fallback chords.
ui.widgets.typed_text functionReturn printable text, excluding command chords and key releases.
Permalink Source ↗
hamingjur.ui.widgets.typed_text(key: Keystroke | str) -> str
Return printable text, excluding command chords and key releases.
ui.widgets.Pointer classA mouse event in absolute screen cells.
Permalink Source ↗
hamingjur.ui.widgets.Pointer
A mouse event in absolute screen cells.
Fields & constants
x: int
y: int
button: str = 'LEFT'
kind: str = 'press'
ui.widgets.Widget classBase for themed, focusable views. Override draw and event handlers.
Permalink Source ↗
hamingjur.ui.widgets.Widget(*, width: int=1, height: int=1, grow: int=0, enabled: bool=True)
Base for themed, focusable views. Override draw and event handlers.

Constructor
-----------
Set preferred dimensions and the weight used when distributing spare cells.
Fields & constants
focusable = False
track_terminal_focus = False
ui.widgets.Widget.layout methodReceive the rectangle assigned by the parent.
Permalink Source ↗
hamingjur.ui.widgets.Widget.layout(bounds: Rect) -> None
Receive the rectangle assigned by the parent.
ui.widgets.Widget.draw methodDraw onto the supplied clipped area.
Permalink Source ↗
hamingjur.ui.widgets.Widget.draw(surface: Surface, focused: Widget | None=None) -> None
Draw onto the supplied clipped area.
ui.widgets.Widget.on_key methodHandle a key and return whether it was consumed.
Permalink Source ↗
hamingjur.ui.widgets.Widget.on_key(key: Keystroke | str, app: Application) -> bool
Handle a key and return whether it was consumed.
ui.widgets.Widget.on_pointer methodHandle a mouse event and return whether it was consumed.
Permalink Source ↗
hamingjur.ui.widgets.Widget.on_pointer(pointer: Pointer, app: Application) -> bool
Handle a mouse event and return whether it was consumed.
ui.widgets.Widget.input_modes methodEnter scoped terminal modes while this widget owns interactive input.
Permalink Source ↗
hamingjur.ui.widgets.Widget.input_modes(terminal, stack) -> None
Enter scoped terminal modes while this widget owns interactive input.
ui.widgets.Widget.on_frame methodAdvance a focused widget and return its next monotonic deadline.
Permalink Source ↗
hamingjur.ui.widgets.Widget.on_frame(now: float) -> float | None
Advance a focused widget and return its next monotonic deadline.
ui.widgets.Widget.on_blur methodCancel transient interaction when this widget loses input ownership.
Permalink Source ↗
hamingjur.ui.widgets.Widget.on_blur() -> None
Cancel transient interaction when this widget loses input ownership.
ui.widgets.Widget.caret_position methodReturn the editor caret in screen cells when the widget has one.
Permalink Source ↗
hamingjur.ui.widgets.Widget.caret_position() -> tuple[int, int] | None
Return the editor caret in screen cells when the widget has one.
ui.widgets.Widget.focus_order methodYield eligible widgets in keyboard traversal order.
Permalink Source ↗
hamingjur.ui.widgets.Widget.focus_order() -> Iterator[Widget]
Yield eligible widgets in keyboard traversal order.
ui.widgets.Widget.hit methodReturn the enabled view at a cell.
Permalink Source ↗
hamingjur.ui.widgets.Widget.hit(x: int, y: int) -> Widget | None
Return the enabled view at a cell.
ui.widgets.Widget.reveal methodBring this widget into view inside any scrolling ancestors.
Permalink Source ↗
hamingjur.ui.widgets.Widget.reveal() -> None
Bring this widget into view inside any scrolling ancestors.
ui.widgets.Widget.reveal_child methodAdjust layout to reveal a descendant, where supported.
Permalink Source ↗
hamingjur.ui.widgets.Widget.reveal_child(child: Widget) -> None
Adjust layout to reveal a descendant, where supported.
ui.widgets.Group classA container with child ownership and clipped child drawing.
Permalink Source ↗
hamingjur.ui.widgets.Group(*children: Widget, **options)
Bases: Widget
A container with child ownership and clipped child drawing.

Constructor
-----------
Attach children in drawing and tab order.
ui.widgets.Group.add methodAttach a widget, which can have only one parent.
Permalink Source ↗
hamingjur.ui.widgets.Group.add(child: Widget) -> Widget
Attach a widget, which can have only one parent.
ui.widgets.Group.remove methodDetach a child from this group.
Permalink Source ↗
hamingjur.ui.widgets.Group.remove(child: Widget) -> None
Detach a child from this group.
ui.widgets.Group.layout methodStack children at their preferred height unless specialized.
Permalink Source ↗
hamingjur.ui.widgets.Group.layout(bounds: Rect) -> None
Stack children at their preferred height unless specialized.
ui.widgets.Group.draw methodDraw visible children from back to front.
Permalink Source ↗
hamingjur.ui.widgets.Group.draw(surface: Surface, focused: Widget | None=None) -> None
Draw visible children from back to front.
ui.widgets.Group.focus_order methodYield descendants in tab order.
Permalink Source ↗
hamingjur.ui.widgets.Group.focus_order() -> Iterator[Widget]
Yield descendants in tab order.
ui.widgets.Group.hit methodReturn the frontmost child at a cell.
Permalink Source ↗
hamingjur.ui.widgets.Group.hit(x: int, y: int) -> Widget | None
Return the frontmost child at a cell.
ui.widgets.Stack classLay out controls in a row or column with optional growing slots.
Permalink Source ↗
hamingjur.ui.widgets.Stack(*children: Widget, horizontal: bool=False, gap: int=0, **options)
Bases: Group
Lay out controls in a row or column with optional growing slots.

Constructor
-----------
Set the stack's orientation and spacing.
ui.widgets.Stack.layout methodAllocate each child along the configured axis.
Permalink Source ↗
hamingjur.ui.widgets.Stack.layout(bounds: Rect) -> None
Allocate each child along the configured axis.
ui.widgets.Panel classPlace widgets in local cell rectangles with optional resize anchors.
Permalink Source ↗
hamingjur.ui.widgets.Panel(*, width: int, height: int, **options)
Bases: Group
Place widgets in local cell rectangles with optional resize anchors.

Constructor
-----------
Set the initial layout dimensions used by anchors.
ui.widgets.Panel.place methodAttach a child with fixed, end-anchored, or stretching edges.
Permalink Source ↗
hamingjur.ui.widgets.Panel.place(child: Widget, bounds: Rect, *, right: bool=False, bottom: bool=False, grow_x: bool=False, grow_y: bool=False) -> Widget
Attach a child with fixed, end-anchored, or stretching edges.
ui.widgets.Panel.remove methodRemove a child and discard its layout options.
Permalink Source ↗
hamingjur.ui.widgets.Panel.remove(child: Widget) -> None
Remove a child and discard its layout options.
ui.widgets.Panel.layout methodApply the difference from the reference size and clip children to the panel.
Permalink Source ↗
hamingjur.ui.widgets.Panel.layout(bounds: Rect) -> None
Apply the difference from the reference size and clip children to the panel.
ui.widgets.Label classStatic text, with a semantic style role.
Permalink Source ↗
hamingjur.ui.widgets.Label(text: str, *, role: str='text', accessibility_role: str | None=None, **options)
Bases: Widget
Static text, with a semantic style role.

Constructor
-----------
Set the text and optional style role.
ui.widgets.Label.draw methodDraw lines within the allocated area.
Permalink Source ↗
hamingjur.ui.widgets.Label.draw(surface: Surface, focused: Widget | None=None) -> None
Draw lines within the allocated area.
ui.widgets.Button classA push button activated by Return, Space, or a mouse click.
Permalink Source ↗
hamingjur.ui.widgets.Button(label: str, action: Callable[[], None], **options)
Bases: Widget
A push button activated by Return, Space, or a mouse click.

Constructor
-----------
Bind a label to an action.
Fields & constants
focusable = True
ui.widgets.Button.draw methodDraw the button with visible keyboard focus.
Permalink Source ↗
hamingjur.ui.widgets.Button.draw(surface: Surface, focused: Widget | None=None) -> None
Draw the button with visible keyboard focus.
ui.widgets.Button.on_key methodActivate the button from the keyboard.
Permalink Source ↗
hamingjur.ui.widgets.Button.on_key(key: Keystroke | str, app: Application) -> bool
Activate the button from the keyboard.
ui.widgets.Button.on_pointer methodActivate on a left press.
Permalink Source ↗
hamingjur.ui.widgets.Button.on_pointer(pointer: Pointer, app: Application) -> bool
Activate on a left press.
ui.widgets.Checkbox classAn independent Boolean option.
Permalink Source ↗
hamingjur.ui.widgets.Checkbox(label: str, checked: bool=False, *, on_change: Callable[[bool], None] | None=None, **options)
Bases: Button
An independent Boolean option.

Constructor
-----------
Set the initial check state and change callback.
ui.widgets.Checkbox.toggle methodFlip the check state and notify the application.
Permalink Source ↗
hamingjur.ui.widgets.Checkbox.toggle() -> None
Flip the check state and notify the application.
ui.widgets.Checkbox.draw methodDraw the marker and label.
Permalink Source ↗
hamingjur.ui.widgets.Checkbox.draw(surface: Surface, focused: Widget | None=None) -> None
Draw the marker and label.
ui.widgets.InputLine classSingle-line editable input backed by Hamingjur's LineEditor.
Permalink Source ↗
hamingjur.ui.widgets.InputLine(value: str='', *, history: LineHistory | None=None, password: bool=False, validator: Callable[[str], str | None] | None=None, on_submit: Callable[[str], None] | None=None, **options)
Bases: Widget
Single-line editable input backed by Hamingjur's LineEditor.

Constructor
-----------
Set the initial value, optional validator, and submit action.
Fields & constants
focusable = True
ui.widgets.InputLine.value propertyReturn the current input text.
Permalink Source ↗
hamingjur.ui.widgets.InputLine.value -> str
Return the current input text.
ui.widgets.InputLine.validate methodReturn a validation message or None.
Permalink Source ↗
hamingjur.ui.widgets.InputLine.validate() -> str | None
Return a validation message or None.
ui.widgets.InputLine.draw methodDraw the editor's Unicode-aware viewport and cell cursor.
Permalink Source ↗
hamingjur.ui.widgets.InputLine.draw(surface: Surface, focused: Widget | None=None) -> None
Draw the editor's Unicode-aware viewport and cell cursor.
ui.widgets.InputLine.on_key methodEdit, paste, recall history, or submit the field.
Permalink Source ↗
hamingjur.ui.widgets.InputLine.on_key(key: Keystroke | str, app: Application) -> bool
Edit, paste, recall history, or submit the field.
ui.widgets.InputLine.caret_position methodReturn the visible input caret for terminal magnification.
Permalink Source ↗
hamingjur.ui.widgets.InputLine.caret_position() -> tuple[int, int]
Return the visible input caret for terminal magnification.
ui.widgets.InputLine.on_pointer methodMove the insertion point to a clicked column.
Permalink Source ↗
hamingjur.ui.widgets.InputLine.on_pointer(pointer: Pointer, app: Application) -> bool
Move the insertion point to a clicked column.
ui.widgets.ScrollBar classA vertical or horizontal range control with keyboard and mouse input.
Permalink Source ↗
hamingjur.ui.widgets.ScrollBar(total: int=1, page: int=1, value: int=0, *, horizontal: bool=False, on_change: Callable[[int], None] | None=None, **options)
Bases: Widget
A vertical or horizontal range control with keyboard and mouse input.

Constructor
-----------
Bind the scrollbar to a count, viewport size, and offset.
Fields & constants
focusable = True
ui.widgets.ScrollBar.set_range methodSynchronize range and thumb position without calling the change handler.
Permalink Source ↗
hamingjur.ui.widgets.ScrollBar.set_range(total: int, page: int, value: int=0) -> None
Synchronize range and thumb position without calling the change handler.
ui.widgets.ScrollBar.maximum propertyReturn the last valid offset.
Permalink Source ↗
hamingjur.ui.widgets.ScrollBar.maximum -> int
Return the last valid offset.
ui.widgets.ScrollBar.draw methodDraw a thumb sized to the visible fraction.
Permalink Source ↗
hamingjur.ui.widgets.ScrollBar.draw(surface: Surface, focused: Widget | None=None) -> None
Draw a thumb sized to the visible fraction.
ui.widgets.ScrollBar.on_key methodScroll by a cell, a page, or to either edge.
Permalink Source ↗
hamingjur.ui.widgets.ScrollBar.on_key(key: Keystroke | str, app: Application) -> bool
Scroll by a cell, a page, or to either edge.
ui.widgets.ScrollBar.on_pointer methodJump or drag to a position on the track.
Permalink Source ↗
hamingjur.ui.widgets.ScrollBar.on_pointer(pointer: Pointer, app: Application) -> bool
Jump or drag to a position on the track.
ui.widgets.ScrollView classA vertical viewport for a widget or form larger than its parent.
Permalink Source ↗
hamingjur.ui.widgets.ScrollView(child: Widget, **options)
Bases: Group
A vertical viewport for a widget or form larger than its parent.

Constructor
-----------
Set the content and its preferred viewport dimensions.
ui.widgets.ScrollView.content propertyReturn the view contained in the viewport.
Permalink Source ↗
hamingjur.ui.widgets.ScrollView.content -> Widget
Return the view contained in the viewport.
ui.widgets.ScrollView.layout methodLay out the full content and set the visible slice.
Permalink Source ↗
hamingjur.ui.widgets.ScrollView.layout(bounds: Rect) -> None
Lay out the full content and set the visible slice.
ui.widgets.ScrollView.reveal_child methodScroll just enough to expose the focused control.
Permalink Source ↗
hamingjur.ui.widgets.ScrollView.reveal_child(child: Widget) -> None
Scroll just enough to expose the focused control.
ui.widgets.ScrollView.draw methodDraw the clipped content and scrollbar.
Permalink Source ↗
hamingjur.ui.widgets.ScrollView.draw(surface: Surface, focused: Widget | None=None) -> None
Draw the clipped content and scrollbar.
ui.widgets.ScrollView.on_pointer methodScroll using the wheel or the scrollbar.
Permalink Source ↗
hamingjur.ui.widgets.ScrollView.on_pointer(pointer: Pointer, app: Application) -> bool
Scroll using the wheel or the scrollbar.
ui.widgets.ListBox classScrollable rows with incremental search and item activation.
Permalink Source ↗
hamingjur.ui.widgets.ListBox(items: Iterable[T]=(), *, label: Callable[[T], str]=str, on_activate: Callable[[T], None] | None=None, on_change: Callable[[T], None] | None=None, accessibility_role: str | None=None, **options)
Bases: Widget, Generic[T]
Scrollable rows with incremental search and item activation.

Constructor
-----------
Set items, item formatting, and optional selection callbacks.
Fields & constants
focusable = True
ui.widgets.ListBox.value propertyGet the item at the selection, if any.
Permalink Source ↗
hamingjur.ui.widgets.ListBox.value -> T | None
Get the item at the selection, if any.
ui.widgets.ListBox.set_items methodReplace the list and bring the current selection back into view.
Permalink Source ↗
hamingjur.ui.widgets.ListBox.set_items(items: Iterable[T]) -> None
Replace the list and bring the current selection back into view.
ui.widgets.ListBox.select methodSelect a row and ensure it is scrolled into view.
Permalink Source ↗
hamingjur.ui.widgets.ListBox.select(index: int) -> None
Select a row and ensure it is scrolled into view.
ui.widgets.ListBox.layout methodUpdate viewport and scrollbar geometry.
Permalink Source ↗
hamingjur.ui.widgets.ListBox.layout(bounds: Rect) -> None
Update viewport and scrollbar geometry.
ui.widgets.ListBox.draw methodDraw visible rows, highlighting the selection and exposing a scrollbar.
Permalink Source ↗
hamingjur.ui.widgets.ListBox.draw(surface: Surface, focused: Widget | None=None) -> None
Draw visible rows, highlighting the selection and exposing a scrollbar.
ui.widgets.ListBox.on_key methodMove the selection, activate it, or seek a typed prefix.
Permalink Source ↗
hamingjur.ui.widgets.ListBox.on_key(key: Keystroke | str, app: Application) -> bool
Move the selection, activate it, or seek a typed prefix.
ui.widgets.ListBox.on_pointer methodScroll, select a row, or activate a double-clicked row.
Permalink Source ↗
hamingjur.ui.widgets.ListBox.on_pointer(pointer: Pointer, app: Application) -> bool
Scroll, select a row, or activate a double-clicked row.
ui.widgets.RadioGroup classA mutually exclusive set of options, navigated with arrow keys.
Permalink Source ↗
hamingjur.ui.widgets.RadioGroup(items: Iterable[T], *, label: Callable[[T], str]=str, **options)
Bases: ListBox[T]
A mutually exclusive set of options, navigated with arrow keys.

Constructor
-----------
Default to showing one row per option.
ui.widgets.RadioGroup.draw methodDraw radio markers and their current selection.
Permalink Source ↗
hamingjur.ui.widgets.RadioGroup.draw(surface: Surface, focused: Widget | None=None) -> None
Draw radio markers and their current selection.
ui.widgets.TextView classA scrollable, read-only text area with horizontal and vertical navigation.
Permalink Source ↗
hamingjur.ui.widgets.TextView(text: str='', **options)
Bases: Widget
A scrollable, read-only text area with horizontal and vertical navigation.

Constructor
-----------
Store the text as unbounded logical lines.
Fields & constants
focusable = True
ui.widgets.TextView.text propertyReturn the entire text.
Permalink Source ↗
hamingjur.ui.widgets.TextView.text -> str
Return the entire text.
ui.widgets.TextView.scroll methodMove the viewport without changing the text.
Permalink Source ↗
hamingjur.ui.widgets.TextView.scroll(rows: int, columns: int=0) -> None
Move the viewport without changing the text.
ui.widgets.TextView.draw methodDraw the visible section with an optional scroll guide.
Permalink Source ↗
hamingjur.ui.widgets.TextView.draw(surface: Surface, focused: Widget | None=None) -> None
Draw the visible section with an optional scroll guide.
ui.widgets.TextView.on_key methodScroll by rows, columns, or pages.
Permalink Source ↗
hamingjur.ui.widgets.TextView.on_key(key: Keystroke | str, app: Application) -> bool
Scroll by rows, columns, or pages.
ui.widgets.TextView.on_pointer methodScroll with the mouse wheel or click the scroll guide.
Permalink Source ↗
hamingjur.ui.widgets.TextView.on_pointer(pointer: Pointer, app: Application) -> bool
Scroll with the mouse wheel or click the scroll guide.
ui.widgets.ProgressBar classA determinate progress indicator.
Permalink Source ↗
hamingjur.ui.widgets.ProgressBar(value: float=0, **options)
Bases: Widget
A determinate progress indicator.

Constructor
-----------
Set the completed fraction between zero and one.
ui.widgets.ProgressBar.draw methodShow progress as a filled track and percentage.
Permalink Source ↗
hamingjur.ui.widgets.ProgressBar.draw(surface: Surface, focused: Widget | None=None) -> None
Show progress as a filled track and percentage.
ui.widgets.CheckGroup classA vertical group of independent checkbox options.
Permalink Source ↗
hamingjur.ui.widgets.CheckGroup(items: Iterable[str], *, checked: Iterable[str]=(), **options)
Bases: Stack
A vertical group of independent checkbox options.

Constructor
-----------
Create one checkbox per option.
ui.widgets.CheckGroup.values propertyReturn checked labels in display order.
Permalink Source ↗
hamingjur.ui.widgets.CheckGroup.values -> tuple[str, ...]
Return checked labels in display order.
ui.widgets.SplitView classTwo panes with a mouse-draggable and keyboard-adjustable divider.
Permalink Source ↗
hamingjur.ui.widgets.SplitView(first: Widget, second: Widget, *, horizontal: bool=True, fraction: float=0.5, **options)
Bases: Group
Two panes with a mouse-draggable and keyboard-adjustable divider.

Constructor
-----------
Split a viewport by columns or rows.
Fields & constants
focusable = True
ui.widgets.SplitView.layout methodReflow both panes around a one-cell divider.
Permalink Source ↗
hamingjur.ui.widgets.SplitView.layout(bounds: Rect) -> None
Reflow both panes around a one-cell divider.
ui.widgets.SplitView.draw methodDraw both panes and the divider between them.
Permalink Source ↗
hamingjur.ui.widgets.SplitView.draw(surface: Surface, focused: Widget | None=None) -> None
Draw both panes and the divider between them.
ui.widgets.SplitView.on_key methodMove the focused divider by one cell.
Permalink Source ↗
hamingjur.ui.widgets.SplitView.on_key(key: Keystroke | str, app: Application) -> bool
Move the focused divider by one cell.
ui.widgets.SplitView.on_pointer methodDrag the divider along its axis.
Permalink Source ↗
hamingjur.ui.widgets.SplitView.on_pointer(pointer: Pointer, app: Application) -> bool
Drag the divider along its axis.
ui.widgets.TreeNode classAn outline node with optional descendants and application data.
Permalink Source ↗
hamingjur.ui.widgets.TreeNode
An outline node with optional descendants and application data.
Fields & constants
label: str
children: tuple[TreeNode, ...] = ()
expanded: bool = False
value: object = None
ui.widgets.TreeView classAn expandable outline with keyboard and mouse navigation.
Permalink Source ↗
hamingjur.ui.widgets.TreeView(nodes: Iterable[TreeNode], *, on_select: Callable[[TreeNode], None] | None=None, **options)
Bases: ListBox[_TreeRow]
An expandable outline with keyboard and mouse navigation.

Constructor
-----------
Create an outline from the supplied root nodes.
ui.widgets.TreeView.selection propertyGet the currently selected node.
Permalink Source ↗
hamingjur.ui.widgets.TreeView.selection -> TreeNode | None
Get the currently selected node.
ui.widgets.TreeView.refresh methodRebuild the visible outline while preserving the selection by identity.
Permalink Source ↗
hamingjur.ui.widgets.TreeView.refresh() -> None
Rebuild the visible outline while preserving the selection by identity.
ui.widgets.TreeView.draw methodDraw indentation and disclosure markers ahead of node labels.
Permalink Source ↗
hamingjur.ui.widgets.TreeView.draw(surface: Surface, focused: Widget | None=None) -> None
Draw indentation and disclosure markers ahead of node labels.
ui.widgets.TreeView.on_key methodExpand or collapse branches with Right or Left.
Permalink Source ↗
hamingjur.ui.widgets.TreeView.on_key(key: Keystroke | str, app: Application) -> bool
Expand or collapse branches with Right or Left.
hamingjur.ui.layout41 entries

Cell geometry, semantic styles and clipped terminal drawing.

ui.layout.Rect classA zero-based rectangle in terminal cells.
Permalink Source ↗
hamingjur.ui.layout.Rect
A zero-based rectangle in terminal cells.
Fields & constants
x: int
y: int
width: int
height: int
ui.layout.Rect.right propertyReturn the first column beyond the rectangle.
Permalink Source ↗
hamingjur.ui.layout.Rect.right -> int
Return the first column beyond the rectangle.
ui.layout.Rect.bottom propertyReturn the first row beyond the rectangle.
Permalink Source ↗
hamingjur.ui.layout.Rect.bottom -> int
Return the first row beyond the rectangle.
ui.layout.Rect.contains methodTest whether a cell is inside the rectangle.
Permalink Source ↗
hamingjur.ui.layout.Rect.contains(x: int, y: int) -> bool
Test whether a cell is inside the rectangle.
ui.layout.Rect.intersection methodReturn the area common to both rectangles.
Permalink Source ↗
hamingjur.ui.layout.Rect.intersection(other: Rect) -> Rect
Return the area common to both rectangles.
ui.layout.Rect.inset methodRemove padding from both sides of each axis.
Permalink Source ↗
hamingjur.ui.layout.Rect.inset(columns: int=1, rows: int=1) -> Rect
Remove padding from both sides of each axis.
ui.layout.Rect.fit methodClamp size and position to the available area.
Permalink Source ↗
hamingjur.ui.layout.Rect.fit(area: Rect, minimum: tuple[int, int]=(1, 1)) -> Rect
Clamp size and position to the available area.
ui.layout.Style classForeground and background hex colors, with optional text emphasis.
Permalink Source ↗
hamingjur.ui.layout.Style
Foreground and background hex colors, with optional text emphasis.
Fields & constants
fg: str | None = None
bg: str | None = None
bold: bool = False
reverse: bool = False
ui.layout.Theme classSemantic color roles. Override any role while inheriting the others.
Permalink Source ↗
hamingjur.ui.layout.Theme(styles: Mapping[str, Style] | None=None, *, light: bool=False)
Semantic color roles. Override any role while inheriting the others.

Constructor
-----------
Create a palette based on the dark or light defaults.
ui.layout.Theme.roles propertyReturn the names of the configurable roles.
Permalink Source ↗
hamingjur.ui.layout.Theme.roles -> tuple[str, ...]
Return the names of the configurable roles.
ui.layout.Theme.with_styles methodReturn this theme with the supplied role replacements.
Permalink Source ↗
hamingjur.ui.layout.Theme.with_styles(**styles: Style) -> Theme
Return this theme with the supplied role replacements.
ui.layout.Theme.from_mapping methodApply partial styles from a JSON-compatible mapping keyed by role.
Permalink Source ↗
hamingjur.ui.layout.Theme.from_mapping(config: Mapping[str, Mapping[str, Any]], *, light: bool=False) -> Theme
Apply partial styles from a JSON-compatible mapping keyed by role.
ui.layout.Theme.high_contrast methodCreate a high-contrast palette with a dark or light background.
Permalink Source ↗
hamingjur.ui.layout.Theme.high_contrast(*, light: bool=False) -> Theme
Create a high-contrast palette with a dark or light background.
ui.layout.Theme.grayscale methodReturn a palette with the same luminance and emphasis for every role.
Permalink Source ↗
hamingjur.ui.layout.Theme.grayscale() -> Theme
Return a palette with the same luminance and emphasis for every role.
ui.layout.Appearance classTerminal drawing characters and visual treatment, independent of color.
Permalink Source ↗
hamingjur.ui.layout.Appearance
Terminal drawing characters and visual treatment, independent of color.
Fields & constants
frame: tuple[str, str, str, str, str, str]
close: str
grip: str
arrow: str
check: str
track: str
thumb: str
shadow: bool = False
ascii_only: bool = False
ui.layout.Appearance.for_terminal methodChoose rounded single-cell Unicode frames and enable shadows on Kitty and Silkie.
Permalink Source ↗
hamingjur.ui.layout.Appearance.for_terminal(term: Terminal) -> Appearance
Choose rounded single-cell Unicode frames and enable shadows on Kitty and Silkie.
ui.layout.plain functionRemove characters that can execute terminal controls.
Permalink Source ↗
hamingjur.ui.layout.plain(text: str) -> str
Remove characters that can execute terminal controls.
ui.layout.GraphicLayer classA retained graphics producer composited with ordinary cell drawing.
Permalink Source ↗
hamingjur.ui.layout.GraphicLayer
A retained graphics producer composited with ordinary cell drawing.
ui.layout.GraphicLayer.present methodPresent placements after all windows have drawn.
Permalink Source ↗
hamingjur.ui.layout.GraphicLayer.present(canvas: Canvas) -> None
Present placements after all windows have drawn.
ui.layout.GraphicLayer.graphics_error methodHandle a terminal error addressed to an image this producer owns.
Permalink Source ↗
hamingjur.ui.layout.GraphicLayer.graphics_error(image_id: int, reason: str) -> None
Handle a terminal error addressed to an image this producer owns.
ui.layout.GraphicLayer.release methodRelease this producer's terminal resources.
Permalink Source ↗
hamingjur.ui.layout.GraphicLayer.release() -> None
Release this producer's terminal resources.
ui.layout.Canvas classOne screen of cells, composited back to front and presented by changed row.
Permalink Source ↗
hamingjur.ui.layout.Canvas(size: Rect, appearance: Appearance, term: Terminal, *, translate: Callable[[str], str]=str, accessibility: bool=False)
One screen of cells, composited back to front and presented by changed row.

Constructor
-----------
Allocate cells to match the current physical terminal dimensions.
ui.layout.Canvas.text methodPrepare safe terminal text using the selected character set.
Permalink Source ↗
hamingjur.ui.layout.Canvas.text(text: str) -> str
Prepare safe terminal text using the selected character set.
ui.layout.Canvas.width methodMeasure columns with Hamingjur's configured terminal width rules.
Permalink Source ↗
hamingjur.ui.layout.Canvas.width(text: str) -> int
Measure columns with Hamingjur's configured terminal width rules.
ui.layout.Canvas.put methodReplace a span, clearing complete graphemes when layers overlap.
Permalink Source ↗
hamingjur.ui.layout.Canvas.put(x: int, y: int, text: str, span: int, role: str, accessibility_role: str | None=None) -> None
Replace a span, clearing complete graphemes when layers overlap.
ui.layout.Canvas.surface methodCreate a drawing surface clipped to the visible screen.
Permalink Source ↗
hamingjur.ui.layout.Canvas.surface(bounds: Rect) -> Surface
Create a drawing surface clipped to the visible screen.
ui.layout.Canvas.present methodWrite changed rows with the terminal's native color capabilities.
Permalink Source ↗
hamingjur.ui.layout.Canvas.present(theme: Theme, previous: list[Row] | None, *, cursor: tuple[int, int] | None=None, previous_cursor: tuple[int, int] | None=None) -> None
Write changed rows with the terminal's native color capabilities.
ui.layout.Surface classA clipped area with local, zero-based drawing coordinates.
Permalink Source ↗
hamingjur.ui.layout.Surface(canvas: Canvas, bounds: Rect, clip: Rect)
A clipped area with local, zero-based drawing coordinates.

Constructor
-----------
Bind local coordinates to the compositor.
ui.layout.Surface.appearance propertyReturn the character and chrome choices for this drawing surface.
Permalink Source ↗
hamingjur.ui.layout.Surface.appearance -> Appearance
Return the character and chrome choices for this drawing surface.
ui.layout.Surface.width_options propertyReturn ambiguous-width and terminal settings for external text measurements.
Permalink Source ↗
hamingjur.ui.layout.Surface.width_options -> tuple[int, str | bool]
Return ambiguous-width and terminal settings for external text measurements.
ui.layout.Surface.width propertyReturn the surface width in cells.
Permalink Source ↗
hamingjur.ui.layout.Surface.width -> int
Return the surface width in cells.
ui.layout.Surface.height propertyReturn the surface height in cells.
Permalink Source ↗
hamingjur.ui.layout.Surface.height -> int
Return the surface height in cells.
ui.layout.Surface.measure methodReturn the displayed width of plain text.
Permalink Source ↗
hamingjur.ui.layout.Surface.measure(text: str) -> int
Return the displayed width of plain text.
ui.layout.Surface.translate methodResolve a localized message before combining it with other text.
Permalink Source ↗
hamingjur.ui.layout.Surface.translate(text: str) -> str
Resolve a localized message before combining it with other text.
ui.layout.Surface.clip propertyAbsolute visible rectangle before later widgets draw.
Permalink Source ↗
hamingjur.ui.layout.Surface.clip -> Rect
Absolute visible rectangle before later widgets draw.
ui.layout.Surface.terminal propertyTerminal that owns the current surface and its graphics resources.
Permalink Source ↗
hamingjur.ui.layout.Surface.terminal -> Terminal
Terminal that owns the current surface and its graphics resources.
ui.layout.Surface.graphic methodMark a placement in paint order. Later cell writes can occlude it.
Permalink Source ↗
hamingjur.ui.layout.Surface.graphic(layer: GraphicLayer) -> int
Mark a placement in paint order. Later cell writes can occlude it.
ui.layout.Surface.sub methodRestrict drawing to the supplied absolute rectangle.
Permalink Source ↗
hamingjur.ui.layout.Surface.sub(bounds: Rect) -> Surface
Restrict drawing to the supplied absolute rectangle.
ui.layout.Surface.write methodWrite text clipped at grapheme boundaries, with an optional screen-reader role.
Permalink Source ↗
hamingjur.ui.layout.Surface.write(x: int, y: int, text: str, role: str='text', *, end: int | None=None, accessibility_role: str | None=None) -> None
Write text clipped at grapheme boundaries, with an optional screen-reader role.
ui.layout.Surface.fill methodPaint the clipped surface with a background role.
Permalink Source ↗
hamingjur.ui.layout.Surface.fill(role: str='window') -> None
Paint the clipped surface with a background role.
ui.layout.Surface.highlight methodChange the style of one cell or the complete grapheme covering it.
Permalink Source ↗
hamingjur.ui.layout.Surface.highlight(x: int, y: int, role: str) -> None
Change the style of one cell or the complete grapheme covering it.
hamingjur.ui.dialogs19 entries

Standard forms, file selectors, help and theme dialogs.

ui.dialogs.RegexValidator classValidate an input field using an entire-value regular expression.
Permalink Source ↗
hamingjur.ui.dialogs.RegexValidator(pattern: str, message: str)
Validate an input field using an entire-value regular expression.

Constructor
-----------
Set the expression and the message shown on validation failure.
ui.dialogs.RegexValidator.__call__ methodReturn the configured error message when the value does not match.
Permalink Source ↗
hamingjur.ui.dialogs.RegexValidator.__call__(text: str) -> str | None
Return the configured error message when the value does not match.
ui.dialogs.IntegerValidator classAn inclusive integer range validator.
Permalink Source ↗
hamingjur.ui.dialogs.IntegerValidator
An inclusive integer range validator.
Fields & constants
minimum: int
maximum: int
ui.dialogs.IntegerValidator.__call__ methodReturn an error when the value is outside the range.
Permalink Source ↗
hamingjur.ui.dialogs.IntegerValidator.__call__(text: str) -> str | None
Return an error when the value is outside the range.
ui.dialogs.FormDialog classA modal form that validates its input fields before returning values.
Permalink Source ↗
hamingjur.ui.dialogs.FormDialog(title: str, fields: Mapping[str, InputLine], *, on_submit: Callable[[dict[str, str]], None] | None=None, bounds: Rect | None=None)
Bases: Dialog
A modal form that validates its input fields before returning values.

Constructor
-----------
Lay out named fields in order, with OK and Cancel actions.
ui.dialogs.FormDialog.submit methodValidate, remember non-password history, and return the form data.
Permalink Source ↗
hamingjur.ui.dialogs.FormDialog.submit() -> None
Validate, remember non-password history, and return the form data.
ui.dialogs.message_box functionOpen a modal message with caller-defined buttons and return their labels.
Permalink Source ↗
hamingjur.ui.dialogs.message_box(app: Application, title: str, message: str, *, choices: Iterable[str] | None=None, on_close: Callable[[object], None] | None=None) -> Dialog
Open a modal message with caller-defined buttons and return their labels.
ui.dialogs.prompt functionOpen a single-field modal prompt.
Permalink Source ↗
hamingjur.ui.dialogs.prompt(app: Application, title: str, label: str, *, value: str='', validator: Callable[[str], str | None] | None=None, on_submit: Callable[[str], None] | None=None) -> FormDialog
Open a single-field modal prompt.
ui.dialogs.FileDialog classA keyboard and mouse file selector for open, save, or directory selection.
Permalink Source ↗
hamingjur.ui.dialogs.FileDialog(title: str=Message('Open file'), *, directory: str | Path='.', mode: str='open', pattern: str='*', on_select: Callable[[Path], None] | None=None)
Bases: Dialog
A keyboard and mouse file selector for open, save, or directory selection.

Constructor
-----------
Start in the specified directory and filter files with a glob pattern.
ui.dialogs.FileDialog.up methodNavigate to the parent directory.
Permalink Source ↗
hamingjur.ui.dialogs.FileDialog.up() -> None
Navigate to the parent directory.
ui.dialogs.FileDialog.submit methodValidate the typed path or selected entry and return it.
Permalink Source ↗
hamingjur.ui.dialogs.FileDialog.submit() -> None
Validate the typed path or selected entry and return it.
ui.dialogs.DirectoryDialog classA file selector restricted to directories.
Permalink Source ↗
hamingjur.ui.dialogs.DirectoryDialog(title: str=Message('Choose directory'), **options)
Bases: FileDialog
A file selector restricted to directories.

Constructor
-----------
Open a directory selector.
ui.dialogs.HelpTopic classA context-help page with links to related topics.
Permalink Source ↗
hamingjur.ui.dialogs.HelpTopic
A context-help page with links to related topics.
Fields & constants
title: str
text: str
links: tuple[str, ...] = ()
ui.dialogs.HelpBook classContext-sensitive help topics displayed in a standard modal viewer.
Permalink Source ↗
hamingjur.ui.dialogs.HelpBook(topics: Mapping[str, HelpTopic], start: str)
Context-sensitive help topics displayed in a standard modal viewer.

Constructor
-----------
Store topics and their default page.
ui.dialogs.HelpBook.install methodHandle F1 and Ctrl+H using the active window's help context.
Permalink Source ↗
hamingjur.ui.dialogs.HelpBook.install(app: Application) -> None
Handle F1 and Ctrl+H using the active window's help context.
ui.dialogs.HelpBook.open methodOpen a page with related topics and a Back command.
Permalink Source ↗
hamingjur.ui.dialogs.HelpBook.open(app: Application, topic: str | None=None) -> Dialog
Open a page with related topics and a Back command.
ui.dialogs.ThemeDialog classEdit a desktop's semantic palette one foreground or background at a time.
Permalink Source ↗
hamingjur.ui.dialogs.ThemeDialog(app: Application)
Bases: Dialog
Edit a desktop's semantic palette one foreground or background at a time.

Constructor
-----------
Create a color editor with a live preview and a reversible Cancel action.
ui.dialogs.ThemeDialog.preview methodPreview the current color in the desktop.
Permalink Source ↗
hamingjur.ui.dialogs.ThemeDialog.preview() -> None
Preview the current color in the desktop.
ui.dialogs.ThemeDialog.apply methodKeep all previewed colors and close the dialog.
Permalink Source ↗
hamingjur.ui.dialogs.ThemeDialog.apply() -> None
Keep all previewed colors and close the dialog.
hamingjur.ui.editor16 entries

A Unicode multiline text editor for desktop windows and dialogs.

ui.editor.TextEditor classEdit, select, search, and scroll a text document with undo and redo.
Permalink Source ↗
hamingjur.ui.editor.TextEditor(text: str='', **options)
Bases: TextView
Edit, select, search, and scroll a text document with undo and redo.

Constructor
-----------
Create an editor with a fresh history and insertion point.
ui.editor.TextEditor.text propertyReturn the document with logical newline separators.
Permalink Source ↗
hamingjur.ui.editor.TextEditor.text -> str
Return the document with logical newline separators.
ui.editor.TextEditor.modified propertyReturn whether the current contents differ from the saved text.
Permalink Source ↗
hamingjur.ui.editor.TextEditor.modified -> bool
Return whether the current contents differ from the saved text.
ui.editor.TextEditor.selected_text propertyReturn the text covered by the current selection.
Permalink Source ↗
hamingjur.ui.editor.TextEditor.selected_text -> str
Return the text covered by the current selection.
ui.editor.TextEditor.replace_selection methodReplace the highlighted range or insert at the cursor.
Permalink Source ↗
hamingjur.ui.editor.TextEditor.replace_selection(text: str) -> None
Replace the highlighted range or insert at the cursor.
ui.editor.TextEditor.undo methodReverse the last edit and restore its selection.
Permalink Source ↗
hamingjur.ui.editor.TextEditor.undo() -> None
Reverse the last edit and restore its selection.
ui.editor.TextEditor.redo methodReapply the last reverted edit.
Permalink Source ↗
hamingjur.ui.editor.TextEditor.redo() -> None
Reapply the last reverted edit.
ui.editor.TextEditor.load methodLoad a document into this editor.
Permalink Source ↗
hamingjur.ui.editor.TextEditor.load(path: str | Path, *, encoding: str='utf-8') -> None
Load a document into this editor.
ui.editor.TextEditor.save methodAtomically write the document with the line endings detected on load.
Permalink Source ↗
hamingjur.ui.editor.TextEditor.save(path: str | Path | None=None, *, encoding: str='utf-8') -> None
Atomically write the document with the line endings detected on load.
ui.editor.TextEditor.select_all methodSelect the entire document.
Permalink Source ↗
hamingjur.ui.editor.TextEditor.select_all() -> None
Select the entire document.
ui.editor.TextEditor.find methodSelect the next occurrence, wrapping at the end of the document.
Permalink Source ↗
hamingjur.ui.editor.TextEditor.find(phrase: str) -> bool
Select the next occurrence, wrapping at the end of the document.
ui.editor.TextEditor.replace_all methodReplace occurrences in one undoable operation and return the count.
Permalink Source ↗
hamingjur.ui.editor.TextEditor.replace_all(phrase: str, replacement: str) -> int
Replace occurrences in one undoable operation and return the count.
ui.editor.TextEditor.caret_position methodReturn the visible editor caret for terminal magnification.
Permalink Source ↗
hamingjur.ui.editor.TextEditor.caret_position() -> tuple[int, int]
Return the visible editor caret for terminal magnification.
ui.editor.TextEditor.draw methodDraw the viewport, selection and insertion point.
Permalink Source ↗
hamingjur.ui.editor.TextEditor.draw(surface: Surface, focused: Widget | None=None) -> None
Draw the viewport, selection and insertion point.
ui.editor.TextEditor.on_key methodHandle movement, editing, selection, clipboard, undo and repeated search.
Permalink Source ↗
hamingjur.ui.editor.TextEditor.on_key(key: Keystroke | str, app: Application) -> bool
Handle movement, editing, selection, clipboard, undo and repeated search.
ui.editor.TextEditor.on_pointer methodScroll or use a pointer to position and select text.
Permalink Source ↗
hamingjur.ui.editor.TextEditor.on_pointer(pointer: Pointer, app: Application) -> bool
Scroll or use a pointer to position and select text.
hamingjur.keyboard41 entries

Sub-module providing 'keyboard awareness'.

keyboard.KittyModifierBits classStandard modifier bit flags (compatible with Kitty keyboard protocol).
Permalink Source ↗
hamingjur.keyboard.KittyModifierBits
Standard modifier bit flags (compatible with Kitty keyboard protocol).
Fields & constants
shift = 1
alt = 2
ctrl = 4
super = 8
hyper = 16
meta = 32
caps_lock = 64
num_lock = 128
names = ('shift', 'alt', 'ctrl', 'super', 'hyper', 'meta', 'caps_lock', 'num_lock')
names_modifiers_only = ('ctrl', 'alt', 'shift', 'super', 'hyper', 'meta')
modifier_key_base_names = frozenset({'LEFT_SHIFT', 'RIGHT_SHIFT', 'LEFT_CONTROL', 'RIGHT_CONTROL', 'LEFT_ALT', 'RIGHT_ALT', 'LEFT_SUPER', 'RIGHT_SUPER', 'LEFT_HYPER', 'RIGHT_HYPER', 'LEFT_META', 'RIGHT_META'})
keyboard.Keystroke classA unicode-derived class for describing a single "keystroke".
Permalink Source ↗
hamingjur.keyboard.Keystroke
Bases: str
A unicode-derived class for describing a single "keystroke".

A class instance describes a single keystroke received on input, which may
contain multiple characters as a multibyte sequence, which is indicated by
properties :attr:`is_sequence` returning ``True``. Note that keystrokes may
also represent mouse input, bracketed paste, or focus in/out events
depending on enabled terminal modes.

The string :attr:`name` of the sequence is used to identify in code logic,
such as ``'KEY_LEFT'`` to represent a common and human-readable form of
the Keystroke this class instance represents.
keyboard.Keystroke.protocol_event propertyStructured Kitty/Silkie message, or None for ordinary keyboard/mouse input.
Permalink Source ↗
hamingjur.keyboard.Keystroke.protocol_event -> Optional[ProtocolEvent]
Structured Kitty/Silkie message, or None for ordinary keyboard/mouse input.
keyboard.Keystroke.tablet propertyTablet/touch/device report, or None for another kind of input.
Permalink Source ↗
hamingjur.keyboard.Keystroke.tablet -> Optional[TabletEvent]
Tablet/touch/device report, or None for another kind of input.
keyboard.Keystroke.is_sequence propertyWhether the value represents a multibyte sequence (bool).
Permalink Source ↗
hamingjur.keyboard.Keystroke.is_sequence -> bool
Whether the value represents a multibyte sequence (bool).
keyboard.Keystroke.name propertySpecial application key name.
Permalink Source ↗
hamingjur.keyboard.Keystroke.name -> Optional[str]
Special application key name.

This is the best equality attribute to use for special keys, as raw string value of the 'F1'
key can be received in many different values.

The 'name' property will return a reliable constant, eg. ``'KEY_F1'``.

The name supports "modifiers", such as ``'KEY_CTRL_F1'``,
``'KEY_CTRL_ALT_F1'``, ``'KEY_CTRL_ALT_SHIFT_F1'``

When using a keyboard protocol with event reporting, names include an
event-type suffix: ``'KEY_CTRL_J_REPEATED'`` for repeat and
``'KEY_CTRL_J_RELEASED'`` for release events.  Press events have no
suffix.  See :attr:`key_name` for the same name without the suffix.

For mouse events, the name includes the ``'MOUSE_'`` prefix followed by the
button/action name, such as ``'MOUSE_LEFT'``, ``'MOUSE_MOTION'``,
``'MOUSE_RIGHT_MOTION'``, ``'MOUSE_LEFT_RELEASED'``.

For other DEC events:

- Focus events: 'FOCUS_IN' or 'FOCUS_OUT'
- Bracketed paste: 'BRACKETED_PASTE'
- Resize events: 'RESIZE_EVENT'

For terminal query responses:

- Cursor position report: 'CPR_RESPONSE' (row >= 2 only;
  row 1 is ambiguous with F3+modifier)

When non-None, all phrases begin with either 'KEY', 'MOUSE', 'FOCUS_IN', 'FOCUS_OUT',
'BRACKETED_PASTE', or 'RESIZE_EVENT', with one exception: 'CSI' is returned for '\\x1b['
in legacy (non-kitty-protocol) mode to indicate the beginning of a presumed unsupported
input sequence. In kitty keyboard protocol mode, the '[' key uses the name
'KEY_LEFT_SQUARE_BRACKET' (with modifier and event-type suffixes as appropriate).

If this value is None, then it can probably be assumed that the value is an unsurprising
textual character without any modifiers, like the letter ``'a'``.
keyboard.Keystroke.key_name propertyKey identity without event-type suffix.
Permalink Source ↗
hamingjur.keyboard.Keystroke.key_name -> Optional[str]
Key identity without event-type suffix.

Like :attr:`name`, but without ``_RELEASED`` and ``_REPEATED``
suffixes, so that press, repeat, and release events for the same
key all return the same value.  Useful for key-map lookups when
tracking press/release pairs.

:rtype: str or None
keyboard.Keystroke.code propertyLegacy curses-alike keycode value (int).
Permalink Source ↗
hamingjur.keyboard.Keystroke.code -> Optional[int]
Legacy curses-alike keycode value (int).
keyboard.Keystroke.modifiers propertyModifier flags in standard keyboard protocol format.
Permalink Source ↗
hamingjur.keyboard.Keystroke.modifiers -> int
Modifier flags in standard keyboard protocol format.

:rtype: int
:returns: Standard-style modifiers value (1 means no modifiers)

The value is 1 + bitwise OR of modifier flags:

- shift: 0b1 (1)
- alt: 0b10 (2)
- ctrl: 0b100 (4)
- super: 0b1000 (8)
- hyper: 0b10000 (16)
- meta: 0b100000 (32)
- caps_lock: 0b1000000 (64)
- num_lock: 0b10000000 (128)
keyboard.Keystroke.modifiers_bits propertyRaw modifier bit flags without the +1 offset.
Permalink Source ↗
hamingjur.keyboard.Keystroke.modifiers_bits -> int
Raw modifier bit flags without the +1 offset.

:rtype: int
:returns: Raw bitwise OR of modifier flags (0 means no modifiers)
keyboard.Keystroke.uses_keyboard_protocol propertyWhether this keystroke uses a special keyboard protocol mode.
Permalink Source ↗
hamingjur.keyboard.Keystroke.uses_keyboard_protocol -> bool
Whether this keystroke uses a special keyboard protocol mode.

Returns True for Kitty, ModifyOtherKeys, or LegacyCSIModifier protocols, which use negative
mode values (SpecialInternalKitty=-1, SpecialInternalModifyOtherKeys=-2,
SpecialInternalLegacyCSIModifier=-3).

:rtype: bool
:returns: True if using special keyboard protocol mode
keyboard.Keystroke.pressed propertyWhether this is a key press event.
Permalink Source ↗
hamingjur.keyboard.Keystroke.pressed -> bool
Whether this is a key press event.

:rtype: bool
:returns: True if this is a key press event (event_type=1 or not specified), False for
    repeat or release events
keyboard.Keystroke.repeated propertyWhether this is a key repeat event.
Permalink Source ↗
hamingjur.keyboard.Keystroke.repeated -> bool
Whether this is a key repeat event.

:rtype: bool
:returns: True if this is a key repeat event (event_type=2), False otherwise
keyboard.Keystroke.released propertyWhether this is a key release event.
Permalink Source ↗
hamingjur.keyboard.Keystroke.released -> bool
Whether this is a key release event.

:rtype: bool
:returns: True if this is a key release event (event_type=3), False otherwise
keyboard.Keystroke.value propertyThe textual character represented by this keystroke.
Permalink Source ↗
hamingjur.keyboard.Keystroke.value -> str
The textual character represented by this keystroke.

:rtype: str
:returns: For text keys, returns the base character (ignoring modifiers).
          For application keys and sequences, returns empty string ''.
          For release events, always returns empty string.

Some Examples,

- Plain text: 'a', 'A', '1', ';', ' ', 'Ω', emoji with ZWJ sequences
- Alt+printable: Alt+a -> 'a', Alt+A -> 'A'
- Ctrl+letter: Ctrl+A -> 'a', Ctrl+Z -> 'z'
- Ctrl+symbol: Ctrl+@ -> '@', Ctrl+? -> '?', Ctrl+[ → '['
- Control chars: '\t', '\n', '\x08', '\x1b' (for Enter/Tab/Backspace/Escape keycodes)
- Application keys: KEY_UP, KEY_F1, etc. → ''
- Release events: always -> ''
keyboard.Keystroke.key_value propertyCharacter for this key, even for release events.
Permalink Source ↗
hamingjur.keyboard.Keystroke.key_value -> str
Character for this key, even for release events.

Like :attr:`value`, but does not suppress the character for
release events.  For press and repeat events, identical to
:attr:`value`.

:rtype: str
keyboard.Keystroke.mode propertyDEC Private Mode associated with this keystroke, if any.
Permalink Source ↗
hamingjur.keyboard.Keystroke.mode -> Optional['DecPrivateMode']
DEC Private Mode associated with this keystroke, if any.

:rtype: hamingjur.dec_modes.DecPrivateMode or None
:returns: The :class:`~hamingjur.dec_modes.DecPrivateMode` enum value
    associated with this keystroke, or ``None`` if this is not a DEC mode event.

.. note:: Mode names beginning SpecialInternal with negative values (-1,
    -2, -3) are used to track how some kinds of application keys are
    matched.
keyboard.Keystroke.mouse_yx propertyMouse position as (y, x) tuple for mouse events.
Permalink Source ↗
hamingjur.keyboard.Keystroke.mouse_yx -> Tuple[int, int]
Mouse position as (y, x) tuple for mouse events.

This is particularly useful with terminal movement functions:
``term.move_yx(*keystroke.mouse_yx)``

:rtype: tuple of (int, int)
:returns: (y, x) coordinate tuple (0-indexed) for mouse events,
          or ``(-1, -1)`` if not a mouse event
keyboard.Keystroke.mouse_xy propertyMouse position as (x, y) tuple for mouse events.
Permalink Source ↗
hamingjur.keyboard.Keystroke.mouse_xy -> Tuple[int, int]
Mouse position as (x, y) tuple for mouse events.

:rtype: tuple of (int, int)
:returns: (x, y) coordinate tuple (0-indexed) for mouse events,
          or ``(-1, -1)`` if not a mouse event
keyboard.Keystroke.cpr_yx propertyCursor position as (y, x) tuple for Cursor Position Report.
Permalink Source ↗
hamingjur.keyboard.Keystroke.cpr_yx -> Tuple[int, int]
Cursor position as (y, x) tuple for Cursor Position Report.

:rtype: tuple of (int, int)
:returns: (y, x) coordinate tuple (0-indexed) for cursor position report,
    or ``(-1, -1)`` if not a CPR_RESPONSE
keyboard.Keystroke.cpr_xy propertyCursor position as (x, y) tuple for Cursor Position Report.
Permalink Source ↗
hamingjur.keyboard.Keystroke.cpr_xy -> Tuple[int, int]
Cursor position as (x, y) tuple for Cursor Position Report.

:rtype: tuple of (int, int)
:returns: (x, y) coordinate tuple (0-indexed) for cursor position report,
    or ``(-1, -1)`` if not a CPR_RESPONSE
keyboard.Keystroke.xtgettcap propertyCapabilities reported by an XTGETTCAP response.
Permalink Source ↗
hamingjur.keyboard.Keystroke.xtgettcap -> Dict[str, str]
Capabilities reported by an XTGETTCAP response.

:rtype: dict
:returns: mapping of terminal capability name to value.
keyboard.Keystroke.text propertyPasted text for bracketed paste events.
Permalink Source ↗
hamingjur.keyboard.Keystroke.text -> Optional[str]
Pasted text for bracketed paste events.

:rtype: str or None
:returns: The pasted text for ``BRACKETED_PASTE`` events,
          or ``None`` if not a bracketed paste event
keyboard.get_curses_keycodes functionReturn mapping of curses key-names paired by their keycode integer value.
Permalink Source ↗
hamingjur.keyboard.get_curses_keycodes() -> Dict[str, int]
Return mapping of curses key-names paired by their keycode integer value.

:rtype: dict
:returns: Dictionary of (name, code) pairs for curses keyboard constant
    values and their mnemonic name. Such as code ``260``, with the value of
    its key-name identity, ``'KEY_LEFT'``.
keyboard.get_keyboard_codes functionReturn mapping of keycode integer values paired by their curses key name.
Permalink Source ↗
hamingjur.keyboard.get_keyboard_codes() -> Dict[int, str]
Return mapping of keycode integer values paired by their curses key name.

:rtype: dict
:returns: Dictionary of (code, name) pairs for curses keyboard constant
    values and their mnemonic name. Such as key ``260``, with the value of
    its identity, ``'KEY_LEFT'``.

These keys are derived from the attributes by the same of the curses(jinxed) module,
with the following exceptions:

* ``KEY_DELETE`` in place of ``KEY_DC``
* ``KEY_INSERT`` in place of ``KEY_IC``
* ``KEY_PGUP`` in place of ``KEY_PPAGE``
* ``KEY_PGDOWN`` in place of ``KEY_NPAGE``
* ``KEY_ESCAPE`` in place of ``KEY_EXIT``
* ``KEY_SUP`` in place of ``KEY_SR``
* ``KEY_SDOWN`` in place of ``KEY_SF``

This function is the inverse of :func:`get_curses_keycodes`.  With the
given override "mixins" listed above, the keycode for the delete key will
map to our imaginary ``KEY_DELETE`` mnemonic, effectively erasing the
phrase ``KEY_DC`` from our code vocabulary for anyone that wishes to use
the return value to determine the key-name by keycode.
keyboard.get_keyboard_sequences functionReturn mapping of keyboard sequences paired by keycodes.
Permalink Source ↗
hamingjur.keyboard.get_keyboard_sequences(term: 'Terminal') -> typing.OrderedDict[str, int]
Return mapping of keyboard sequences paired by keycodes.

:arg hamingjur.Terminal term: :class:`~.Terminal` instance.
:returns: mapping of keyboard unicode sequences paired by keycodes
    as integer.  This is used as the argument ``mapper`` to
    the supporting function :func:`resolve_sequence`.
:rtype: OrderedDict

Initialize and return a keyboard map and sequence lookup table,
(sequence, keycode) from :class:`~.Terminal` instance ``term``,
where ``sequence`` is a multibyte input sequence of unicode
characters, such as ``'\x1b[D'``, and ``keycode`` is an integer
value, matching curses constant such as term.KEY_LEFT.

The return value is an OrderedDict instance, with their keys
sorted longest-first.
keyboard.get_leading_prefixes functionReturn a set of proper prefixes for given sequence of strings.
Permalink Source ↗
hamingjur.keyboard.get_leading_prefixes(sequences: typing.Iterable[str]) -> Set[str]
Return a set of proper prefixes for given sequence of strings.

:arg iterable sequences
:rtype: set
:return: Set of all string prefixes

Given an iterable of strings, all textparts leading up to the final
string is returned as a unique set.  This function supports the
:meth:`~.Terminal.inkey` method by determining whether the given
input is a sequence that **may** lead to a final matching pattern.

>>> prefixes(['abc', 'abdf', 'e', 'jkl'])
set(['a', 'ab', 'abd', 'j', 'jk'])
keyboard.resolve_sequence functionReturn a single :class:`Keystroke` instance for given sequence ``text``.
Permalink Source ↗
hamingjur.keyboard.resolve_sequence(text: str, mapper: typing.Mapping[str, int], codes: typing.Mapping[int, str], prefixes: Optional[Set[str]]=None, final: bool=False, dec_mode_cache: Optional[Dict[int, int]]=None, capture_cpr: bool=False) -> Keystroke
Return a single :class:`Keystroke` instance for given sequence ``text``.

:arg str text: string of characters received from terminal input stream.
:arg OrderedDict mapper: unicode multibyte sequences, such as ``'\x1b[D'``
    paired by their integer value (260)
:arg dict codes: a :type:`dict` of integer values (such as 260) paired
    by their mnemonic name, such as ``'KEY_LEFT'``.
:arg set prefixes: Set of all valid sequence prefixes for quick matching
:arg bool final: Whether this is the final resolution attempt (no more input expected)
:arg dict dec_mode_cache: Dictionary of DEC private mode states (mode number -> state value)
:arg bool capture_cpr: Prefer matches of ``CPR_RESPONSE`` over conflicting vt220 Legacy
    function keys (eg. ``KEY_F3``, ``KEY_SHIFT_F3``).
:rtype: Keystroke
:returns: Keystroke instance for the given sequence

The given ``text`` may extend beyond a matching sequence, such as
``u\x1b[Dxxx`` returns a :class:`Keystroke` instance of attribute
:attr:`Keystroke.sequence` valued only ``u\x1b[D``.  It is up to
calls to determine that ``xxx`` remains unresolved.

In an ideal world, we could detect and resolve only for key sequences
expected in the current terminal mode. For example, only the enabling of
mode 1036 (META_SENDS_ESC) would match for 2-character ESC+char sequences.

But terminals are unpredictable, the popular terminal "Konsole" does
not negotiate about any DEC Private modes but transmits metaSendsEscape
anyway, so exhaustive match is performed in all cases.
keyboard.DeviceAttribute classRepresents a terminal's Device Attributes (DA1) response.
Permalink Source ↗
hamingjur.keyboard.DeviceAttribute(raw: str, service_class: int, extensions: typing.Optional[typing.List[int]]) -> None
Represents a terminal's Device Attributes (DA1) response.

Device Attributes queries allow discovering terminal capabilities and type.
The primary DA1 query sends CSI c and expects a response like::

    CSI ? Psc ; Ps1 ; Ps2 ; ... ; Psn c

Where Psc is the service class (architectural class) and Ps1...Psn are
supported extensions/capabilities.

Constructor
-----------
Initialize DeviceAttribute instance.

:arg str raw: Original response string from terminal
:arg int service_class: Service class number (first parameter)
:arg list extensions: List of extension numbers (remaining parameters)
Fields & constants
RE_RESPONSE = re.compile('\\x1b\\[\\?([0-9]+)((?:;[0-9]+)*);*c')
RE_RESPONSE_CTERM = re.compile('\\x1b\\[=' + ';'.join(map(str, map(ord, 'CTerm'))) + '(?:;[0-9]+)*;*c')
keyboard.DeviceAttribute.supports_sixel propertyWhether the terminal supports sixel graphics.
Permalink Source ↗
hamingjur.keyboard.DeviceAttribute.supports_sixel -> bool
Whether the terminal supports sixel graphics.

:rtype: bool
:returns: True if extension 4 (sixel) is present in device attributes
keyboard.DeviceAttribute.supports_osc52 propertyWhether the terminal advertises OSC 52 clipboard support.
Permalink Source ↗
hamingjur.keyboard.DeviceAttribute.supports_osc52 -> bool
Whether the terminal advertises OSC 52 clipboard support.

Extension 52 in DA1 indicates the terminal supports writing to the system clipboard via the
OSC 52 protocol.

:rtype: bool
:returns: True if extension 52 is present in device attributes
keyboard.DeviceAttribute.from_match methodCreate DeviceAttribute from regex match object.
Permalink Source ↗
hamingjur.keyboard.DeviceAttribute.from_match(match: Match[str]) -> 'DeviceAttribute'
Create DeviceAttribute from regex match object.

:arg re.Match match: Regex match object with groups for service_class and extensions
:rtype: DeviceAttribute
:returns: DeviceAttribute instance parsed from match
keyboard.SoftwareVersion classRepresents a terminal's software name and version from XTVERSION response.
Permalink Source ↗
hamingjur.keyboard.SoftwareVersion(raw: str, name: str, version: str) -> None
Represents a terminal's software name and version from XTVERSION response.

Constructor
-----------
Initialize SoftwareVersion instance.

:arg str raw: Original response string from terminal
:arg str name: Software name (e.g., "kitty", "XTerm")
:arg str version: Version string (e.g., "0.24.2", "367") or empty string if no version
Fields & constants
RE_RESPONSE = re.compile('\\x1bP>\\|(.+?)\\x1b\\\\')
keyboard.SoftwareVersion.from_match methodCreate SoftwareVersion from regex match object.
Permalink Source ↗
hamingjur.keyboard.SoftwareVersion.from_match(match: Match[str]) -> 'SoftwareVersion'
Create SoftwareVersion from regex match object.

:arg re.Match match: Regex match object with group for software text
:rtype: SoftwareVersion
:returns: SoftwareVersion instance parsed from match
keyboard.KittyKeyboardProtocol classRepresents Kitty keyboard protocol flags.
Permalink Source ↗
hamingjur.keyboard.KittyKeyboardProtocol(value: int) -> None
Represents Kitty keyboard protocol flags.

Encapsulates the integer flag value returned by Kitty keyboard protocol queries and provides
properties for individual flag bits and a method to convert back to enable_kitty_keyboard()
arguments.

Constructor
-----------
Initialize with raw integer flag value.

:arg int value: Raw integer flags value from Kitty keyboard protocol query
keyboard.KittyKeyboardProtocol.disambiguate propertyWhether disambiguated escape codes are enabled (bit 1).
Permalink Source ↗
hamingjur.keyboard.KittyKeyboardProtocol.disambiguate -> bool
Whether disambiguated escape codes are enabled (bit 1).
keyboard.KittyKeyboardProtocol.report_events propertyWhether key repeat and release events are reported (bit 2).
Permalink Source ↗
hamingjur.keyboard.KittyKeyboardProtocol.report_events -> bool
Whether key repeat and release events are reported (bit 2).
keyboard.KittyKeyboardProtocol.report_alternates propertyWhether shifted and base layout keys are reported for shortcuts (bit 4).
Permalink Source ↗
hamingjur.keyboard.KittyKeyboardProtocol.report_alternates -> bool
Whether shifted and base layout keys are reported for shortcuts (bit 4).
keyboard.KittyKeyboardProtocol.report_all_keys propertyWhether all keys are reported as escape codes (bit 8).
Permalink Source ↗
hamingjur.keyboard.KittyKeyboardProtocol.report_all_keys -> bool
Whether all keys are reported as escape codes (bit 8).
keyboard.KittyKeyboardProtocol.report_text propertyWhether associated text is reported with key events (bit 16).
Permalink Source ↗
hamingjur.keyboard.KittyKeyboardProtocol.report_text -> bool
Whether associated text is reported with key events (bit 16).
keyboard.KittyKeyboardProtocol.make_arguments methodReturn dictionary of arguments suitable for enable_kitty_keyboard().
Permalink Source ↗
hamingjur.keyboard.KittyKeyboardProtocol.make_arguments() -> Dict[str, bool]
Return dictionary of arguments suitable for enable_kitty_keyboard().

:rtype: dict
:returns: Dictionary with boolean flags suitable for passing as keyword arguments to
    enable_kitty_keyboard()
hamingjur.mouse5 entries

Sub-module providing mouse event handling.

mouse.MouseEvent classMouse event with button, coordinates, and modifier information.
Permalink Source ↗
hamingjur.mouse.MouseEvent(button_value: int, x: int, y: int, released: bool, shift: bool, meta: bool, ctrl: bool, is_motion: bool, is_wheel: bool)
Mouse event with button, coordinates, and modifier information.

A unified mouse event structure that supports both legacy and SGR mouse protocols. Provides a
dynamic button property that returns human-readable button names like "LEFT", "SCROLL_UP",
"CTRL_LEFT", etc.

:ivar int button_value: Raw button number with modifiers stripped (0=left, 1=middle, 2=right,
    3=none, 64=scroll up, 65=scroll down, 66-67 for buttons 6-7, and 128-131 for buttons 8-11).
:ivar int x: Horizontal position (0-indexed, in cells or pixels depending on mode).
:ivar int y: Vertical position (0-indexed, in cells or pixels depending on mode).
:ivar bool released: True if this is a button release event.
:ivar bool shift: True if Shift modifier is pressed.
:ivar bool meta: True if Meta/Alt modifier is pressed.
:ivar bool ctrl: True if Ctrl modifier is pressed.
:ivar bool is_motion: True if motion is being reported (drag or all- motion mode).
:ivar bool is_wheel: True if this is a scroll wheel event.

Constructor
-----------
Initialize a MouseEvent.

:param int button_value: Raw button number.
:param int x: Horizontal position.
:param int y: Vertical position.
:param bool released: Whether this is a button release event.
:param bool shift: Whether Shift modifier is pressed.
:param bool meta: Whether Meta/Alt modifier is pressed.
:param bool ctrl: Whether Ctrl modifier is pressed.
:param bool is_motion: Whether motion is being reported.
:param bool is_wheel: Whether this is a scroll wheel event.
mouse.MouseEvent.is_leave propertyKitty SGR pixel mouse-leave event; coordinates and buttons must be ignored.
Permalink Source ↗
hamingjur.mouse.MouseEvent.is_leave -> bool
Kitty SGR pixel mouse-leave event; coordinates and buttons must be ignored.
mouse.MouseEvent.button propertyReturn human-readable button name.
Permalink Source ↗
hamingjur.mouse.MouseEvent.button -> str
Return human-readable button name.

Generates button names that include modifiers, button type, motion/release state:

- "LEFT", "MIDDLE", "RIGHT" for standard mouse buttons
- "LEFT_RELEASED", "MIDDLE_RELEASED", "RIGHT_RELEASED" for button releases
- "RELEASED" for a legacy release, which does not report which button was released
- "SCROLL_UP", "SCROLL_DOWN" for wheel events
- "MOTION" for mouse movement with no button pressed
- "LEFT_MOTION", "MIDDLE_MOTION", "RIGHT_MOTION" for drag events
- "CTRL_LEFT", "SHIFT_SCROLL_UP", "CTRL_SHIFT_META_MOTION" with modifiers
- "BUTTON_6" through "BUTTON_11" for extended mouse buttons

:rtype: str
:returns: Button name with modifiers, button type, and motion/release state.
mouse.MouseEvent.from_sgr_match methodParse SGR mouse event from regex match.
Permalink Source ↗
hamingjur.mouse.MouseEvent.from_sgr_match(match: Match[str]) -> 'MouseEvent'
Parse SGR mouse event from regex match.

Handles both SGR (mode 1006) and SGR-Pixels (mode 1016) since they
use identical wire formats: CSI < b;x;y m/M. The difference is semantic:

- Mode 1006: coordinates represent character cell positions
- Mode 1016: coordinates represent pixel positions

Applications must interpret x,y coordinates based on which mode was enabled.

The protocol sends 1-indexed coordinates (top-left is 1,1), but we convert
to 0-indexed (top-left is 0,0) to match hamingjur's terminal movement functions.

:param Match match: Regex match object with groups 'b', 'x', 'y', 'type'.
:rtype: MouseEvent
:returns: Parsed MouseEvent instance.
mouse.MouseEvent.from_legacy_match methodParse legacy mouse event (X10/1000/1002/1003) from regex match.
Permalink Source ↗
hamingjur.mouse.MouseEvent.from_legacy_match(match: Match[str]) -> 'MouseEvent'
Parse legacy mouse event (X10/1000/1002/1003) from regex match.

The protocol sends 1-indexed coordinates (top-left is 1,1), but we convert to 0-indexed
(top-left is 0,0) to match hamingjur's terminal movement functions.

Each coordinate is transmitted as a single byte of ``value + 32``, so no position beyond
223 can be expressed.  Windows Terminal and the console host (``conhost.exe``) share a VT
input layer that *discards* any legacy mouse event where either coordinate exceeds 95,
rather than transmit a byte above 127.  Both are limitations of the terminal without
workaround, the SGR protocol is the only remedy.

:param Match match: Regex match object with groups 'cb', 'cx', 'cy'.
:rtype: MouseEvent
:returns: Parsed MouseEvent instance.
hamingjur.line_editor22 entries

Headless line editor with history, auto-suggest, and grapheme-aware editing. This module provides :class:`LineEditor` for single-line input with readline-style editing and :class:`LineHistory` for command recall.

line_editor.LineEditResult classResult of processing a keystroke.
Permalink Source ↗
hamingjur.line_editor.LineEditResult
Result of processing a keystroke.
Fields & constants
line: Optional[str] = None
eof: bool = False
interrupt: bool = False
changed: bool = False
bell: str = ''
line_editor.DisplayState classCurrent visual state of the editor for rendering.
Permalink Source ↗
hamingjur.line_editor.DisplayState
Current visual state of the editor for rendering.
Fields & constants
text: str = ''
cursor: int = 0
suggestion: str = ''
overflow_left: bool = False
overflow_right: bool = False
text_sgr: str = ''
suggestion_sgr: str = ''
bg_sgr: str = ''
ellipsis_sgr: str = ''
line_editor.LineHistory classIn-memory command history with navigation and prefix search.
Permalink Source ↗
hamingjur.line_editor.LineHistory(max_entries: Optional[int]=None) -> None
In-memory command history with navigation and prefix search.

:param max_entries: Optional maximum history size; None retains all entries.

Constructor
-----------
Initialize history, with an optional caller-selected retention limit.
line_editor.LineHistory.add methodAppend *line* to history, skipping empty and consecutive duplicates.
Permalink Source ↗
hamingjur.line_editor.LineHistory.add(line: str) -> None
Append *line* to history, skipping empty and consecutive duplicates.
line_editor.LineHistory.search_prefix methodReturn the most recent entry starting with *prefix*, or ``None``.
Permalink Source ↗
hamingjur.line_editor.LineHistory.search_prefix(prefix: str) -> Optional[str]
Return the most recent entry starting with *prefix*, or ``None``.
line_editor.LineHistory.nav_start methodBegin history navigation, saving *current_line*.
Permalink Source ↗
hamingjur.line_editor.LineHistory.nav_start(current_line: str) -> None
Begin history navigation, saving *current_line*.
line_editor.LineHistory.nav_up methodNavigate to the previous (older) history entry.
Permalink Source ↗
hamingjur.line_editor.LineHistory.nav_up() -> Optional[str]
Navigate to the previous (older) history entry.
line_editor.LineHistory.nav_down methodNavigate to the next (newer) history entry.
Permalink Source ↗
hamingjur.line_editor.LineHistory.nav_down() -> Optional[str]
Navigate to the next (newer) history entry.
line_editor.LineEditor classHeadless single-line editor with grapheme-aware cursor movement.
Permalink Source ↗
hamingjur.line_editor.LineEditor(history: Optional[LineHistory]=None, password: bool=False, password_char: str=PASSWORD_CHAR, max_width: int=0, ellipsis: str='…', limit: int=0, limit_bell: str='\x07', scroll_jump: float=0.5, text_sgr: str='\x1b[38;2;230;225;220m', suggestion_sgr: str='\x1b[30m', bg_sgr: str='', ellipsis_sgr: str='', keymap: Optional[Dict[str, Optional[Callable[..., LineEditResult]]]]=None, ambiguous_width: int=1, term_program: Union[bool, str]=False) -> None
Headless single-line editor with grapheme-aware cursor movement.

Feed keystrokes via :meth:`feed_key`, read display state via
:attr:`display`.  Accepts hamingjur :class:`~.Keystroke` objects
directly (dispatching on ``.name``), or plain strings for testing.

Custom keymap handlers must be callables accepting a single
:class:`LineEditor` argument and returning a :class:`LineEditResult`::

    def my_handler(editor: LineEditor) -> LineEditResult:
        ...

Constructor
-----------
Initialize editor with optional history, display, and keymap settings.
line_editor.LineEditor.history propertyReturn the attached :class:`LineHistory` instance.
Permalink Source ↗
hamingjur.line_editor.LineEditor.history -> LineHistory
Return the attached :class:`LineHistory` instance.
line_editor.LineEditor.line propertyReturn the current buffer contents as a string.
Permalink Source ↗
hamingjur.line_editor.LineEditor.line -> str
Return the current buffer contents as a string.
line_editor.LineEditor.cursor_column propertyReturn the insertion point as a display column before scrolling.
Permalink Source ↗
hamingjur.line_editor.LineEditor.cursor_column -> int
Return the insertion point as a display column before scrolling.
line_editor.LineEditor.move_to_column methodMove the insertion point to the closest grapheme boundary at a display column.
Permalink Source ↗
hamingjur.line_editor.LineEditor.move_to_column(column: int) -> None
Move the insertion point to the closest grapheme boundary at a display column.
line_editor.LineEditor.password_mode propertyReturn whether password mode is currently active.
Permalink Source ↗
hamingjur.line_editor.LineEditor.password_mode -> bool
Return whether password mode is currently active.
line_editor.LineEditor.display propertyReturn the current :class:`DisplayState` for rendering.
Permalink Source ↗
hamingjur.line_editor.LineEditor.display -> DisplayState
Return the current :class:`DisplayState` for rendering.
line_editor.LineEditor.render methodBuild escape sequences to render the current display state.
Permalink Source ↗
hamingjur.line_editor.LineEditor.render(term: Terminal, row: int, width: int, col: int=0) -> str
Build escape sequences to render the current display state.

:param term: Hamingjur :class:`~.Terminal` instance for cursor/SGR.
:param row: Terminal row for the input line.
:param width: Available columns.
:param col: Starting column offset (default 0).
:returns: Escape-sequence string; caller writes/encodes it.
line_editor.LineEditor.render_insert methodFast-path render for a single grapheme inserted at end of buffer.
Permalink Source ↗
hamingjur.line_editor.LineEditor.render_insert(term: Terminal, row: int, grapheme: str) -> Optional[str]
Fast-path render for a single grapheme inserted at end of buffer.

:param term: Hamingjur :class:`~.Terminal` instance.
:param row: Terminal row for the input line.
:param grapheme: The grapheme cluster just inserted.
:returns: Escape-sequence string, or ``None`` if a full redraw is needed.
line_editor.LineEditor.render_backspace methodFast-path render after a backspace at end of buffer.
Permalink Source ↗
hamingjur.line_editor.LineEditor.render_backspace(term: Terminal, row: int) -> Optional[str]
Fast-path render after a backspace at end of buffer.

:param term: Hamingjur :class:`~.Terminal` instance.
:param row: Terminal row for the input line.
:returns: Escape-sequence string, or ``None`` if a full redraw is needed.
line_editor.LineEditor.feed_key methodProcess one keystroke and return a :class:`LineEditResult`.
Permalink Source ↗
hamingjur.line_editor.LineEditor.feed_key(key: Union['Keystroke', str]) -> LineEditResult
Process one keystroke and return a :class:`LineEditResult`.
line_editor.LineEditor.insert_text methodInsert *text* at cursor position (for bracketed paste).
Permalink Source ↗
hamingjur.line_editor.LineEditor.insert_text(text: str) -> LineEditResult
Insert *text* at cursor position (for bracketed paste).
line_editor.LineEditor.clear methodClear the buffer and reset cursor to start.
Permalink Source ↗
hamingjur.line_editor.LineEditor.clear() -> None
Clear the buffer and reset cursor to start.
line_editor.LineEditor.set_password_mode methodToggle password masking on or off.
Permalink Source ↗
hamingjur.line_editor.LineEditor.set_password_mode(enabled: bool) -> None
Toggle password masking on or off.
hamingjur.window12 entries

Window geometry, cell pixels, and VT/xterm window operations.

window.Size classDimensions with named width and height, in the units requested.
Permalink Source ↗
hamingjur.window.Size
Bases: NamedTuple
Dimensions with named width and height, in the units requested.
Fields & constants
width: int
height: int
window.command functionEncode an XTWINOPS operation, retaining omitted parameters and zero values.
Permalink Source ↗
hamingjur.window.command(operation: int, *parameters: Optional[int]) -> str
Encode an XTWINOPS operation, retaining omitted parameters and zero values.

This includes queries, resize/move requests, stacking, fullscreen/maximize, and title-stack
operations. Support and permission are terminal-dependent.

:raises ValueError: If an operation or parameter is not a nonnegative integer.
window.resize functionRequest a text area size in cells or pixels, leaving omitted dimensions unchanged.
Permalink Source ↗
hamingjur.window.resize(*, columns: Optional[int]=None, rows: Optional[int]=None, width: Optional[int]=None, height: Optional[int]=None) -> str
Request a text area size in cells or pixels, leaving omitted dimensions unchanged.

Zero requests the screen's corresponding dimension. Kitty/Silkie reject these standard resize
requests; their OS windows require opt-in remote control.

:raises ValueError: If units are mixed, no size is supplied, or values are invalid.
window.Window classTerminal window queries and explicit requests, available as ``term.window``.
Permalink Source ↗
hamingjur.window.Window(terminal: Terminal)
Terminal window queries and explicit requests, available as ``term.window``.

Constructor
-----------
Bind to the terminal's stream and input-preserving query transport.
window.Window.send methodSend an XTWINOPS command; it does not imply that the request was granted.
Permalink Source ↗
hamingjur.window.Window.send(operation: int, *parameters: Optional[int]) -> None
Send an XTWINOPS command; it does not imply that the request was granted.
window.Window.cell_size methodReturn physical pixels per cell, or None when the terminal does not answer.
Permalink Source ↗
hamingjur.window.Window.cell_size(timeout: Optional[float]=1.0, *, force: bool=False) -> Optional[Size]
Return physical pixels per cell, or None when the terminal does not answer.
window.Window.size methodQuery actual text-area cells/pixels or the outer window's pixels.
Permalink Source ↗
hamingjur.window.Window.size(timeout: Optional[float]=1.0, *, pixels: bool=False, outer: bool=False) -> Optional[Size]
Query actual text-area cells/pixels or the outer window's pixels.

:raises ValueError: If outer window dimensions are requested in cells.
window.Window.screen_size methodQuery the available screen dimensions in cells or physical pixels.
Permalink Source ↗
hamingjur.window.Window.screen_size(timeout: Optional[float]=1.0, *, pixels: bool=False) -> Optional[Size]
Query the available screen dimensions in cells or physical pixels.
window.Window.position methodQuery window or text-area position, returning (x, y) or None.
Permalink Source ↗
hamingjur.window.Window.position(timeout: Optional[float]=1.0, *, text_area: bool=False) -> Optional[tuple[int, int]]
Query window or text-area position, returning (x, y) or None.
window.Window.state methodQuery window state: 1 is open, 2 is iconified, None is unanswered.
Permalink Source ↗
hamingjur.window.Window.state(timeout: Optional[float]=1.0) -> Optional[int]
Query window state: 1 is open, 2 is iconified, None is unanswered.
window.Window.request_size methodSend a size preference; query size() or watch resize events for the actual result.
Permalink Source ↗
hamingjur.window.Window.request_size(*, columns: Optional[int]=None, rows: Optional[int]=None, width: Optional[int]=None, height: Optional[int]=None) -> None
Send a size preference; query size() or watch resize events for the actual result.
window.Window.title_saved context managerPush and restore both titles (0), icon title (1), or window title (2).
Permalink Source ↗
hamingjur.window.Window.title_saved(which: int=0) -> Iterator[None]
Push and restore both titles (0), icon title (1), or window title (2).
hamingjur.remote_control10 entries

Explicit Kitty/Silkie remote control over the terminal or a configured socket.

remote_control.RemoteControlError classThe terminal refused a command or reported its failure.
Permalink Source ↗
hamingjur.remote_control.RemoteControlError(reply: Mapping[str, Any])
Bases: RuntimeError
The terminal refused a command or reported its failure.

Constructor
-----------
Preserve the complete response, including optional diagnostic fields.
remote_control.packet functionEncode a JSON envelope, escaping control characters and rejecting non-finite numbers.
Permalink Source ↗
hamingjur.remote_control.packet(message: Mapping[str, Any]) -> str
Encode a JSON envelope, escaping control characters and rejecting non-finite numbers.
remote_control.command functionEncode any remote-control command, including async and streaming envelope fields.
Permalink Source ↗
hamingjur.remote_control.command(name: str, payload: Optional[Mapping[str, Any]]=None, *, version: tuple[int, int, int]=PROTOCOL_VERSION, no_response: bool=False, **fields: Any) -> str
Encode any remote-control command, including async and streaming envelope fields.

The terminal must permit remote control. Password authentication requires an externally
encrypted envelope passed to packet(); plaintext passwords are rejected.

:raises ValueError: If command/envelope fields are invalid or include a plaintext password.
remote_control.response functionDecode a complete response and return its data, preserving terminal errors.
Permalink Source ↗
hamingjur.remote_control.response(frame: str) -> Any
Decode a complete response and return its data, preserving terminal errors.

:raises ValueError: If the response is malformed.
:raises RemoteControlError: If the terminal rejects or fails the request.
remote_control.RemoteControl classExplicit remote-control client; construction never connects or changes settings.
Permalink Source ↗
hamingjur.remote_control.RemoteControl(terminal: Optional[Terminal]=None, *, address: Optional[str]=None, version: tuple[int, int, int]=PROTOCOL_VERSION)
Explicit remote-control client; construction never connects or changes settings.

Use term.remote_control for the current terminal, or RemoteControl(address=...)
for an explicitly configured Unix/TCP listener. Calls must be serialized when
sharing a terminal: ordinary synchronous replies have no correlation ID.

Constructor
-----------
Choose a terminal or socket transport, without reading environment addresses.

:raises ValueError: If neither or both transports are specified.
remote_control.RemoteControl.call methodSend an explicit command and return its data; no subprocess is invoked.
Permalink Source ↗
hamingjur.remote_control.RemoteControl.call(name: str, payload: Optional[Mapping[str, Any]]=None, *, timeout: Optional[float]=1.0, no_response: bool=False, **fields: Any) -> Any
Send an explicit command and return its data; no subprocess is invoked.

:raises RuntimeError: If terminal output is disabled.
:raises TimeoutError: If no complete reply arrives within the deadline.
:raises RemoteControlError: If the terminal reports failure or refusal.
remote_control.RemoteControl.resize_window methodResize the calling OS window, or an explicitly matched window, in cells or pixels.
Permalink Source ↗
hamingjur.remote_control.RemoteControl.resize_window(*, width: int=0, height: int=0, unit: str='cells', incremental: bool=False, match: Optional[str]=None, timeout: Optional[float]=1.0) -> Any
Resize the calling OS window, or an explicitly matched window, in cells or pixels.

Zero leaves a dimension unchanged. Incremental sizes may be negative. Successful
acknowledgement is not a guarantee that the window manager used the requested size.

:raises ValueError: If units/dimensions are invalid or no size is specified.
remote_control.RemoteControl.magnify_pane methodAsk Silkie to zoom or pan the calling pane over its terminal connection.
Permalink Source ↗
hamingjur.remote_control.RemoteControl.magnify_pane(operation: str | float='in', *, row: Optional[int]=None, column: Optional[int]=None, timeout: Optional[float]=1.0) -> Any
Ask Silkie to zoom or pan the calling pane over its terminal connection.
remote_control.RemoteControl.review_images methodAsk Silkie to open the current pane's native image review.
Permalink Source ↗
hamingjur.remote_control.RemoteControl.review_images(*, include_decorative: bool=False, timeout: Optional[float]=1.0) -> Any
Ask Silkie to open the current pane's native image review.
remote_control.RemoteControl.set_minimum_contrast methodSet the calling pane's contrast threshold, or restore its default with None.
Permalink Source ↗
hamingjur.remote_control.RemoteControl.set_minimum_contrast(percent: Optional[float], *, timeout: Optional[float]=1.0) -> Any
Set the calling pane's contrast threshold, or restore its default with None.
hamingjur.control4 entries

ECMA-48 control-sequence encoders for terminal operations and future protocols.

control.csi functionEncode a CSI instruction with numeric/subparameters, private and intermediate bytes.
Permalink Source ↗
hamingjur.control.csi(final: str, *parameters: Optional[Union[int, str]], private: str='', intermediate: str='') -> str
Encode a CSI instruction with numeric/subparameters, private and intermediate bytes.

None preserves an omitted parameter. Strings allow colon-separated subparameters, such as SGR
underline styles. No arbitrary parameter-count or string-size limit applies.

:raises ValueError: If fields do not follow ECMA-48 CSI grammar.
control.osc functionEncode an OSC string, including Unicode, without allowing control injection.
Permalink Source ↗
hamingjur.control.osc(code: int, payload: str='') -> str
Encode an OSC string, including Unicode, without allowing control injection.

:raises ValueError: If the code or payload is invalid.
control.dcs functionEncode a DCS string, such as a terminal capability query or encoded data.
Permalink Source ↗
hamingjur.control.dcs(payload: str) -> str
Encode a DCS string, such as a terminal capability query or encoded data.

:raises ValueError: If the payload contains terminal controls.
control.apc functionEncode an APC string for an application-defined protocol.
Permalink Source ↗
hamingjur.control.apc(payload: str) -> str
Encode an APC string for an application-defined protocol.

:raises ValueError: If the payload contains terminal controls.
hamingjur.shell5 entries

Shell working-directory and prompt/command markers.

shell.working_directory functionEncode an absolute working directory as an OSC 7 file URI.
Permalink Source ↗
hamingjur.shell.working_directory(path: str, *, host: str='') -> str
Encode an absolute working directory as an OSC 7 file URI.

:raises ValueError: If the path is relative or the host contains URI delimiters.
shell.mark functionEncode OSC 133 prompt (A), input (B), output (C), or command completion (D).
Permalink Source ↗
hamingjur.shell.mark(kind: str, *, status: Optional[int]=None, **fields: str) -> str
Encode OSC 133 prompt (A), input (B), output (C), or command completion (D).

Optional protocol fields are preserved. A prompt marker can reset Silkie input modes;
applications using those modes should enable them after marking their prompt.

:raises ValueError: If marker fields contain delimiters or status is misplaced.
shell.Shell classExplicit shell integration output, available as ``term.shell``.
Permalink Source ↗
hamingjur.shell.Shell(terminal: Terminal)
Explicit shell integration output, available as ``term.shell``.

Constructor
-----------
Bind shell markers to a terminal.
shell.Shell.working_directory methodReport the shell's working directory without changing the Python process directory.
Permalink Source ↗
hamingjur.shell.Shell.working_directory(path: str, *, host: str='') -> None
Report the shell's working directory without changing the Python process directory.
shell.Shell.mark methodReport a prompt or command boundary.
Permalink Source ↗
hamingjur.shell.Shell.mark(kind: str, *, status: Optional[int]=None, **fields: str) -> None
Report a prompt or command boundary.
hamingjur.color10 entries

Sub-module providing color functions. References, - https://en.wikipedia.org/wiki/Color_difference - http://www.easyrgb.com/en/math.php - Measuring Colour by R.W.G. Hunt and M.R. Pointer

color.rgb_to_xyz functionConvert standard RGB color to XYZ color.
Permalink Source ↗
hamingjur.color.rgb_to_xyz(red: int, green: int, blue: int) -> Tuple[float, float, float]
Convert standard RGB color to XYZ color.

D65/2° standard illuminant.

:arg int red: RGB value of Red.
:arg int green: RGB value of Green.
:arg int blue: RGB value of Blue.
:returns: Tuple (X, Y, Z) representing XYZ color
:rtype: tuple
color.xyz_to_lab functionConvert XYZ color to CIE-Lab color.
Permalink Source ↗
hamingjur.color.xyz_to_lab(x_val: float, y_val: float, z_val: float) -> Tuple[float, float, float]
Convert XYZ color to CIE-Lab color.

:arg float x_val: XYZ value of X.
:arg float y_val: XYZ value of Y.
:arg float z_val: XYZ value of Z.
:returns: Tuple (L, a, b) representing CIE-Lab color
:rtype: tuple  D65/2° standard illuminant
color.rgb_to_lab functionConvert RGB color to CIE-Lab color.
Permalink Source ↗
hamingjur.color.rgb_to_lab(red: int, green: int, blue: int) -> Tuple[float, float, float]
Convert RGB color to CIE-Lab color.

:arg int red: RGB value of Red.
:arg int green: RGB value of Green.
:arg int blue: RGB value of Blue.
:returns: Tuple (L, a, b) representing CIE-Lab color
:rtype: tuple  D65/2° standard illuminant
color.dist_rgb functionDetermine distance between two rgb colors.
Permalink Source ↗
hamingjur.color.dist_rgb(rgb1: _RGB, rgb2: _RGB) -> float
Determine distance between two rgb colors.

:arg tuple rgb1: RGB color definition
:arg tuple rgb2: RGB color definition
:returns: Square of the distance between provided colors
:rtype: float

This works by treating RGB colors as coordinates in three dimensional
space and finding the closest point within the configured color range
using the formula::

    d^2 = (r2 - r1)^2 + (g2 - g1)^2 + (b2 - b1)^2

For efficiency, the square of the distance is returned
which is sufficient for comparisons
color.dist_rgb_weighted functionDetermine the weighted distance between two rgb colors.
Permalink Source ↗
hamingjur.color.dist_rgb_weighted(rgb1: _RGB, rgb2: _RGB) -> float
Determine the weighted distance between two rgb colors.

:arg tuple rgb1: RGB color definition
:arg tuple rgb2: RGB color definition
:returns: Square of the distance between provided colors
:rtype: float Similar to a standard distance formula, the values are weighted to approximate
    human perception of color differences For efficiency, the square of the distance is returned
    which is sufficient for comparisons
color.dist_cie76 functionDetermine distance between two rgb colors using the CIE76 algorithm.
Permalink Source ↗
hamingjur.color.dist_cie76(rgb1: _RGB, rgb2: _RGB) -> float
Determine distance between two rgb colors using the CIE76 algorithm.

:arg tuple rgb1: RGB color definition
:arg tuple rgb2: RGB color definition
:returns: Square of the distance between provided colors
:rtype: float For efficiency, the square of the distance is returned which is sufficient for
    comparisons
color.dist_cie94 functionDetermine distance between two rgb colors using the CIE94 algorithm.
Permalink Source ↗
hamingjur.color.dist_cie94(rgb1: _RGB, rgb2: _RGB) -> float
Determine distance between two rgb colors using the CIE94 algorithm.

:arg tuple rgb1: RGB color definition
:arg tuple rgb2: RGB color definition
:returns: Square of the distance between provided colors
:rtype: float For efficiency, the square of the distance is returned which is sufficient for
    comparisons
color.dist_cie2000 functionDetermine distance between two rgb colors using the CIE2000 algorithm.
Permalink Source ↗
hamingjur.color.dist_cie2000(rgb1: _RGB, rgb2: _RGB) -> float
Determine distance between two rgb colors using the CIE2000 algorithm.

:arg tuple rgb1: RGB color definition
:arg tuple rgb2: RGB color definition
:returns: Square of the distance between provided colors
:rtype: float For efficiency, the square of the distance is returned which is sufficient for
    comparisons
color.xterm256color_from_rgb functionConvert RGB values to xterm 256-color cube index and RGB approximation.
Permalink Source ↗
hamingjur.color.xterm256color_from_rgb(red: int, green: int, blue: int) -> Tuple[int, _RGB]
Convert RGB values to xterm 256-color cube index and RGB approximation.

Uses the 6x6x6 color cube (indices 16-231) with levels [0,95,135,175,215,255].

:arg int red: RGB value of Red (0-255).
:arg int green: RGB value of Green (0-255).
:arg int blue: RGB value of Blue (0-255).
:returns: Tuple (cube_index, (r, g, b)) representing the xterm cube index and RGB approximation
:rtype: tuple
color.xterm256gray_from_rgb functionConvert RGB values to xterm 256-color grayscale index and RGB approximation.
Permalink Source ↗
hamingjur.color.xterm256gray_from_rgb(red: int, green: int, blue: int) -> Tuple[int, _RGB]
Convert RGB values to xterm 256-color grayscale index and RGB approximation.

Uses the 24 grayscale entries (indices 232-255) with values 8+10*i.

:arg int red: RGB value of Red (0-255).
:arg int green: RGB value of Green (0-255).
:arg int blue: RGB value of Blue (0-255).
:returns: Tuple (gray_index, (r, g, b)) representing the xterm gray index and RGB approximation
:rtype: tuple
hamingjur.colorspace4 entries

Color reference data. References, - https://github.com/freedesktop/xorg-rgb/blob/master/rgb.txt - https://github.com/ThomasDickey/xterm-snapshots/blob/master/256colres.h - https://github.com/ThomasDickey/xterm-snapshots/blob/master/XTerm-col.ad - https://en.wikipedia.org/wiki/ANSI_escape_code#Colors - https://gist.github.com/XVilka/8346728 - https://devblogs.microsoft.com/commandline/24-bit-color-in-the-windows-console/ - http://jdebp.uk/Softwares/nosh/guide/TerminalCapabilities.html

colorspace.RGBColor classNamed tuple for an RGB color definition.
Permalink Source ↗
hamingjur.colorspace.RGBColor
Bases: collections.namedtuple('RGBColor', ['red', 'green', 'blue'])
Named tuple for an RGB color definition.
colorspace.hex_to_rgb functionConvert hex color to RGB tuple.
Permalink Source ↗
hamingjur.colorspace.hex_to_rgb(hex_color: str) -> Tuple[int, int, int]
Convert hex color to RGB tuple.

:arg str hex_color: Hex color string. Accepts 3-digit (``#RGB``), 6-digit
    (``#RRGGBB``), or 12-digit (``#RRRRGGGGBBBB``, 16-bit per channel,
    converted to 8-bit). The ``#`` prefix is optional.
:returns: Tuple (r, g, b) with 8-bit values (0-255).
:raises ValueError: If hex_color is not a valid hex color string.
colorspace.rgb_to_hex functionConvert RGB values to hex color string.
Permalink Source ↗
hamingjur.colorspace.rgb_to_hex(red: int, green: int, blue: int, maybe_short: bool=False) -> str
Convert RGB values to hex color string.

:arg int red: Red component (0-255).
:arg int green: Green component (0-255).
:arg int blue: Blue component (0-255).
:arg bool maybe_short: If True, return ``#RGB`` when possible.
    Shortening is only possible when each component has repeating hex digits
    (e.g., ``0xaa`` -> ``a``).
:returns: Hex color string in ``#RRGGBB`` format (or ``#RGB`` if maybe_short).
colorspace.xparse_color functionScale a hex color component to 16-bit or 8-bit per XParseColor specification.
Permalink Source ↗
hamingjur.colorspace.xparse_color(hex_component: str, bits: int=16) -> int
Scale a hex color component to 16-bit or 8-bit per XParseColor specification.

XParseColor is the X11 color parsing standard used by terminals when responding
to OSC 10/11 color queries. Each color component in the ``rgb:R/G/B`` response
can be 1-4 hex digits, representing 4-bit to 16-bit precision.

XParseColor uses **scaling** (bit replication) to expand shorter values to
16-bit. This differs from HTML/CSS shorthand which uses digit doubling:

- XParseColor ``rgb:`` format (scaling): ``f`` -> ``ffff``, ``0f`` -> ``0f0f``
- HTML/CSS shorthand (doubling): ``#f`` -> ``#ff``, ``#0f`` -> ``#0f``

Scaling examples:

- 1 hex digit (4-bit): ``f`` -> ``ffff`` (15 -> 65535)
- 2 hex digits (8-bit): ``e5`` -> ``e5e5`` (229 -> 58853)
- 3 hex digits (12-bit): ``abc`` -> ``abca`` (2748 -> 43978)
- 4 hex digits (16-bit): ``e5e5`` -> ``e5e5`` (unchanged)

:arg str hex_component: A single hex color component (1-4 hex digits).
:arg int bits: Output precision: 16 (default, 0-65535) or 8 (0-255).
:returns: Scaled integer value at the requested bit depth.
:raises ValueError: If hex_component length is not 1-4 or bits is invalid.
hamingjur.cursor_shape2 entries

Module providing DECSCUSR cursor shape support.

cursor_shape.CursorShape classDECSCUSR (DEC Set Cursor Style) cursor shape constants.
Permalink Source ↗
hamingjur.cursor_shape.CursorShape
DECSCUSR (DEC Set Cursor Style) cursor shape constants.

Each constant corresponds to a cursor style parameter (0-6) used in
the DECSCUSR escape sequence ``CSI Ps SP q``.

Usage with the :meth:`~.Terminal.cursor_shape` context manager::

    with term.cursor_shape(term.CursorShape.BLINKING_BAR):
        # cursor is a blinking bar
        main()
    # cursor is restored to terminal default

String names are also accepted::

    with term.cursor_shape('blinking_bar'):
        main()

Available shapes:

====================== =====  ============================
Constant               Value  Description
====================== =====  ============================
``DEFAULT``            0      Reset to terminal default
``BLINKING_BLOCK``     1      Blinking block cursor
``STEADY_BLOCK``       2      Steady (non-blinking) block
``BLINKING_UNDERLINE`` 3      Blinking underline cursor
``STEADY_UNDERLINE``   4      Steady underline cursor
``BLINKING_BAR``       5      Blinking bar (line) cursor
``STEADY_BAR``         6      Steady bar (line) cursor
=====================  =====  ============================
Fields & constants
DEFAULT = 0
BLINKING_BLOCK = 1
STEADY_BLOCK = 2
BLINKING_UNDERLINE = 3
STEADY_UNDERLINE = 4
BLINKING_BAR = 5
STEADY_BAR = 6
DEFAULT_STYLE = 2
COLOR_RESET_OSC = '\x1b]112\x07'
STYLES: dict[str, int] = {'blinking_block': BLINKING_BLOCK, 'steady_block': STEADY_BLOCK, 'blinking_underline': BLINKING_UNDERLINE, 'steady_underline': STEADY_UNDERLINE, 'blinking_bar': BLINKING_BAR, 'steady_bar': STEADY_BAR, 'default': DEFAULT}
cursor_shape.CursorShape.sequence methodReturn the DECSCUSR escape sequence for the given cursor style.
Permalink Source ↗
hamingjur.cursor_shape.CursorShape.sequence(style: int | str) -> str
Return the DECSCUSR escape sequence for the given cursor style.

:arg style: An integer constant (0-6) or a string name (e.g. ``'blinking_bar'``).
:returns: The escape sequence string.
:raises ValueError: If *style* is not a valid cursor shape.
hamingjur.dec_modes14 entries

Class definitions for DEC Private Modes and their Response values.

dec_modes.DecModeResponse classContainer for DEC Private Mode query response.
Permalink Source ↗
hamingjur.dec_modes.DecModeResponse(mode: Union[int, 'DecPrivateMode'], value: int)
Container for DEC Private Mode query response.

Use helper properties :attr:`~DecModeResponse.supported`,
:attr:`~DecModeResponse.enabled`, :attr:`~DecModeResponse.permanent`,
and :attr:`~DecModeResponse.failed` to interpret responses rather than
checking numeric values directly.

Constructor
-----------
Initialize response for a DEC private mode query.

:param mode: DEC private mode number
:type mode: int
:param value: Response value from terminal
:type value: int
:raises TypeError: If mode is not an integer
Fields & constants
NOT_QUERIED = -2
NO_RESPONSE = -1
NOT_RECOGNIZED = 0
SET = 1
RESET = 2
PERMANENTLY_SET = 3
PERMANENTLY_RESET = 4
dec_modes.DecModeResponse.mode propertyThe :class:`DecPrivateMode` instance for this response.
Permalink Source ↗
hamingjur.dec_modes.DecModeResponse.mode -> 'DecPrivateMode'
The :class:`DecPrivateMode` instance for this response.

:rtype: DecPrivateMode
dec_modes.DecModeResponse.description propertyDescription of what this mode controls.
Permalink Source ↗
hamingjur.dec_modes.DecModeResponse.description -> str
Description of what this mode controls.

:rtype: str
dec_modes.DecModeResponse.value propertyNumeric response value for compatibility.
Permalink Source ↗
hamingjur.dec_modes.DecModeResponse.value -> int
Numeric response value for compatibility.

Prefer using helper properties like :attr:`~DecModeResponse.enabled`
instead of checking this value directly.

:rtype: int
dec_modes.DecModeResponse.recognized propertyCheck if the terminal recognizes this mode.
Permalink Source ↗
hamingjur.dec_modes.DecModeResponse.recognized -> bool
Check if the terminal recognizes this mode.

True for any DECRPM response value > 0 (SET, RESET, PERMANENTLY_SET, or PERMANENTLY_RESET).
This indicates the terminal knows about the mode, but does not guarantee the application can
use or control it.

:rtype: bool
:returns: True if terminal acknowledges this mode
dec_modes.DecModeResponse.supported propertyCheck if the mode is supported and usable by the terminal.
Permalink Source ↗
hamingjur.dec_modes.DecModeResponse.supported -> bool
Check if the mode is supported and usable by the terminal.

True for values SET (1), RESET (2), and PERMANENTLY_SET (3). PERMANENTLY_RESET (4) is
excluded: the terminal acknowledges the mode but it is permanently off and cannot be
enabled, so it is not usable by applications.  See also xterm patch #395 and the Contour
synchronized-output spec which both treat value 4 as effectively unsupported.

:rtype: bool
:returns: True if mode is usable (changeable or permanently enabled)
dec_modes.DecModeResponse.enabled propertyCheck if the mode is currently enabled.
Permalink Source ↗
hamingjur.dec_modes.DecModeResponse.enabled -> bool
Check if the mode is currently enabled.

:rtype: bool
:returns: True if mode is set (temporarily or permanently)
dec_modes.DecModeResponse.disabled propertyCheck if the mode is currently disabled.
Permalink Source ↗
hamingjur.dec_modes.DecModeResponse.disabled -> bool
Check if the mode is currently disabled.

:rtype: bool
:returns: True if mode is reset (temporarily or permanently)
dec_modes.DecModeResponse.changeable propertyCheck if the mode setting can be changed.
Permalink Source ↗
hamingjur.dec_modes.DecModeResponse.changeable -> bool
Check if the mode setting can be changed.

:rtype: bool
:returns: True if mode can be toggled by applications
dec_modes.DecModeResponse.permanent propertyCheck if the mode setting is permanent.
Permalink Source ↗
hamingjur.dec_modes.DecModeResponse.permanent -> bool
Check if the mode setting is permanent.

:rtype: bool
:returns: True if mode cannot be changed by applications
dec_modes.DecModeResponse.failed propertyCheck if the query failed.
Permalink Source ↗
hamingjur.dec_modes.DecModeResponse.failed -> bool
Check if the query failed.

:rtype: bool
:returns: True if response indicates timeout or query failure
dec_modes.DecModeResponse.to_dict methodReturn response as a dictionary.
Permalink Source ↗
hamingjur.dec_modes.DecModeResponse.to_dict() -> Dict[str, Any]
Return response as a dictionary.

:rtype: dict
:returns: Dictionary with keys ``value``, ``value_description``,
    ``mode_description``, ``mode_name``, ``supported``, ``enabled``,
    and ``changeable``.
dec_modes.DecPrivateMode classDEC Private Mode with mnemonic name and description.
Permalink Source ↗
hamingjur.dec_modes.DecPrivateMode(value: int)
DEC Private Mode with mnemonic name and description.

Each instance provides:

- :attr:`~DecPrivateMode.value`: Numeric private mode identifier
- :attr:`~DecPrivateMode.name`: Mnemonic name or "UNKNOWN" for unrecognized modes
- :attr:`~DecPrivateMode.long_description`: Full description of mode functionality

Constructor
-----------
Initialize DEC Private Mode with numeric identifier.

:param value: Numeric DEC private mode identifier
:type value: int
Fields & constants
SpecialInternalLegacyCSIModifier = -3
SpecialInternalModifyOtherKeys = -2
SpecialInternalKitty = -1
DECCKM = 1
DECANM = 2
DECCOLM = 3
DECSCLM = 4
DECSCNM = 5
DECOM = 6
DECAWM = 7
DECARM = 8
DECINLM = 9
DECEDM = 10
DECLTM = 11
DECKANAM = 12
DECSCFDM = 13
DECTEM = 14
DECEKEM = 16
DECPFF = 18
DECPEX = 19
OV1 = 20
BA1 = 21
BA2 = 22
PK1 = 23
AH1 = 24
DECTCEM = 25
DECPSP = 27
DECPSM = 29
SHOW_SCROLLBAR_RXVT = 30
DECRLM = 34
DECHEBM = 35
DECHEM = 36
DECTEK = 38
DECCRNLM = 40
DECUPM = 41
DECNRCM = 42
DECGEPM = 43
DECGPCM = 44
DECGPCS = 45
DECGPBM = 46
DECGRPM = 47
DECTHAIM = 49
DECTHAICM = 50
DECBWRM = 51
DECOPM = 52
DEC131TM = 53
DECBPM = 55
DECNAKB = 57
DECIPEM = 58
DECKKDM = 59
DECHCCM = 60
DECVCCM = 61
DECPCCM = 64
DECBCMM = 65
DECNKM = 66
DECBKM = 67
DECKBUM = 68
DECVSSM = 69
DECFPM = 70
DECXRLM = 73
DECSDM = 80
DECKPM = 81
WY_52_LINE = 83
WYENAT_OFF = 84
REPLACEMENT_CHAR_COLOR = 85
DECTHAISCM = 90
DECNCSM = 95
DECRLCM = 96
DECCRTSM = 97
DECARSM = 98
DECMCM = 99
DECAAM = 100
DECCANSM = 101
DECNULM = 102
DECHDPXM = 103
DECESKM = 104
DECOSCNM = 106
DECNUMLK = 108
DECCAPSLK = 109
DECKLHIM = 110
DECFWM = 111
DECRPL = 112
DECHWUM = 113
DECATCUM = 114
DECATCBM = 115
DECBBSM = 116
DECECM = 117
MOUSE_REPORT_CLICK = 1000
MOUSE_HILITE_TRACKING = 1001
MOUSE_REPORT_DRAG = 1002
MOUSE_ALL_MOTION = 1003
FOCUS_IN_OUT_EVENTS = 1004
MOUSE_EXTENDED_UTF8 = 1005
MOUSE_EXTENDED_SGR = 1006
ALT_SCROLL_XTERM = 1007
SCROLL_ON_TTY_OUTPUT_RXVT = 1010
SCROLL_ON_KEYPRESS_RXVT = 1011
FAST_SCROLL = 1014
MOUSE_URXVT = 1015
MOUSE_SGR_PIXELS = 1016
BOLD_ITALIC_HIGH_INTENSITY = 1021
META_SETS_EIGHTH_BIT = 1034
MODIFIERS_ALT_NUMLOCK = 1035
META_SENDS_ESC = 1036
KP_DELETE_SENDS_DEL = 1037
ALT_SENDS_ESC = 1039
KEEP_SELECTION_NO_HILITE = 1040
USE_CLIPBOARD_SELECTION = 1041
URGENCY_ON_CTRL_G = 1042
RAISE_ON_CTRL_G = 1043
REUSE_CLIPBOARD_DATA = 1044
EXTENDED_REVERSE_WRAPAROUND = 1045
ALT_SCREEN_BUFFER_SWITCH = 1046
ALT_SCREEN_BUFFER_XTERM = 1047
SAVE_CURSOR_DECSC = 1048
ALT_SCREEN_AND_SAVE_CLEAR = 1049
TERMINFO_FUNC_KEY_MODE = 1050
SUN_FUNC_KEY_MODE = 1051
HP_FUNC_KEY_MODE = 1052
SCO_FUNC_KEY_MODE = 1053
LEGACY_KBD_X11R6 = 1060
VT220_KBD_EMULATION = 1061
SIXEL_PRIVATE_PALETTE = 1070
BIDI_ARROW_KEY_SWAPPING = 1243
ITERM2_REPORT_KEY_UP = 1337
READLINE_MOUSE_BUTTON_1 = 2001
READLINE_MOUSE_BUTTON_2 = 2002
READLINE_MOUSE_BUTTON_3 = 2003
BRACKETED_PASTE = 2004
READLINE_CHARACTER_QUOTING = 2005
READLINE_NEWLINE_PASTING = 2006
SYNCHRONIZED_OUTPUT = 2026
GRAPHEME_CLUSTERING = 2027
TEXT_REFLOW = 2028
PASSIVE_MOUSE_TRACKING = 2029
REPORT_GRID_CELL_SELECTION = 2030
COLOR_PALETTE_UPDATES = 2031
IN_BAND_WINDOW_RESIZE = 2048
BRACKETED_PASTE_MIME = 5522
MIRROR_BOX_DRAWING = 2500
BIDI_AUTODETECTION = 2501
AMBIGUOUS_WIDTH_REPORTING = 7700
SCROLL_MARKERS = 7711
REWRAP_ON_RESIZE_MINTTY = 7723
APPLICATION_ESCAPE_KEY = 7727
ESC_KEY_SENDS_BACKSLASH = 7728
GRAPHICS_POSITION = 7730
ALT_MODIFIED_MOUSEWHEEL = 7765
SHOW_HIDE_SCROLLBAR = 7766
FONT_CHANGE_REPORTING = 7767
GRAPHICS_POSITION_2 = 7780
SHORTCUT_KEY_MODE = 7783
MOUSEWHEEL_REPORTING = 7786
APPLICATION_MOUSEWHEEL = 7787
BIDI_CURRENT_LINE = 7796
TTCTH = 8200
SIXEL_SCROLLING_LEAVES_CURSOR = 8452
CHARACTER_MAPPING_SERVICE = 8800
AMBIGUOUS_WIDTH_DOUBLE_WIDTH = 8840
WIN32_INPUT_MODE = 9001
KITTY_HANDLE_CTRL_C_Z = 19997
MINTTY_BIDI = 77096
INPUT_METHOD_EDITOR = 737769
dec_modes.DecPrivateMode.long_description propertyFull description of this DEC private mode's functionality.
Permalink Source ↗
hamingjur.dec_modes.DecPrivateMode.long_description -> str
Full description of this DEC private mode's functionality.

:rtype: str
:returns: Detailed description or "Unknown mode" for unrecognized modes
hamingjur.formatters15 entries

Sub-module providing sequence-formatting functions.

formatters.ParameterizingString classA Unicode string which can be called as a parameterizing termcap.
Permalink Source ↗
hamingjur.formatters.ParameterizingString
Bases: str
A Unicode string which can be called as a parameterizing termcap.

For example::

    >>> from hamingjur import Terminal
    >>> term = Terminal()
    >>> color = ParameterizingString(term.color, term.normal, 'color')
    >>> color(9)('color #9')
    '\x1b[91mcolor #9\x1b(B\x1b[m'
formatters.ParameterizingString.__call__ methodReturning :class:`FormattingString` instance for given parameters.
Permalink Source ↗
hamingjur.formatters.ParameterizingString.__call__(*args: object) -> 'FormattingString'
Returning :class:`FormattingString` instance for given parameters.

Return evaluated terminal capability (self), receiving arguments
``*args``, followed by the terminating sequence (self.normal) into
a :class:`FormattingString` capable of being called.

:raises TypeError: Mismatch between capability and arguments
:raises jinxed.error: :func:`jinxed.tparm` raised an exception
:rtype: :class:`FormattingString` or :class:`NullCallableString`
:returns: Callable string for given parameters
formatters.ParameterizingProxyString classA Unicode string which can be called to proxy missing termcap entries.
Permalink Source ↗
hamingjur.formatters.ParameterizingProxyString
Bases: str
A Unicode string which can be called to proxy missing termcap entries.

.. deprecated 1.40::

    All previously-proxied terminfo(5) capabilities are now provided directly by the capability
    database in jinxed.  This class is unused by hamingjur but kept for API compatibility.

This class mirrors the behavior of :class:`ParameterizingString`, except that instead of a
capability name, receives a format string, and callable to filter the given positional ``*args``
of :meth:`ParameterizingProxyString.__call__` into a terminal sequence.

For example::

    >>> from hamingjur import Terminal
    >>> term = Terminal('screen')
    >>> hpa = ParameterizingString(term.hpa, term.normal, 'hpa')
    >>> hpa(9)
    ''
    >>> fmt = '\x1b[{0}G'
    >>> fmt_arg = lambda *arg: (arg[0] + 1,)
    >>> hpa = ParameterizingProxyString((fmt, fmt_arg), term.normal, 'hpa')
    >>> hpa(9)
    '\x1b[10G'
formatters.ParameterizingProxyString.__call__ methodReturning :class:`FormattingString` instance for given parameters.
Permalink Source ↗
hamingjur.formatters.ParameterizingProxyString.__call__(*args: object) -> 'FormattingString'
Returning :class:`FormattingString` instance for given parameters.

Arguments are determined by the capability.  For example, ``hpa``
(move_x) receives only a single integer, whereas ``cup`` (move)
receives two integers.  See documentation in terminfo(5) for the
given capability.

:rtype: FormattingString
:returns: Callable string for given parameters
formatters.FormattingString classA Unicode string which doubles as a callable.
Permalink Source ↗
hamingjur.formatters.FormattingString
Bases: str
A Unicode string which doubles as a callable.

This is used for terminal attributes, so that it may be used both
directly, or as a callable.  When used directly, it simply emits
the given terminal sequence.  When used as a callable, it wraps the
given (string) argument with the 2nd argument used by the class
constructor::

    >>> from hamingjur import Terminal
    >>> term = Terminal()
    >>> style = FormattingString(term.bright_blue, term.normal)
    >>> print(repr(style))
    '\x1b[94m'
    >>> style('Big Blue')
    '\x1b[94mBig Blue\x1b(B\x1b[m'
formatters.FormattingString.__call__ methodReturn ``text`` joined by ``sequence`` and ``normal``.
Permalink Source ↗
hamingjur.formatters.FormattingString.__call__(*args: str) -> str
Return ``text`` joined by ``sequence`` and ``normal``.

:raises TypeError: Not a string type
:rtype: str
:returns: Arguments wrapped in sequence and normal
formatters.FormattingOtherString classA Unicode string which doubles as a callable for another sequence when called.
Permalink Source ↗
hamingjur.formatters.FormattingOtherString
Bases: str
A Unicode string which doubles as a callable for another sequence when called.

This is used for the :meth:`~.Terminal.move_up`, ``down``, ``left``, and ``right()``
family of functions::

    >>> from hamingjur import Terminal
    >>> term = Terminal()
    >>> move_right = FormattingOtherString(term.cuf1, term.cuf)
    >>> print(repr(move_right))
    '\x1b[C'
    >>> print(repr(move_right(666)))
    '\x1b[666C'
    >>> print(repr(move_right()))
    '\x1b[C'
formatters.FormattingOtherString.__call__ methodReturn ``text`` by ``target``.
Permalink Source ↗
hamingjur.formatters.FormattingOtherString.__call__(*args: object) -> str
Return ``text`` by ``target``.
formatters.NullCallableString classA dummy callable Unicode alternative to :class:`FormattingString`.
Permalink Source ↗
hamingjur.formatters.NullCallableString
Bases: str
A dummy callable Unicode alternative to :class:`FormattingString`.

This is used for colors on terminals that do not support colors, it is just a basic form of
unicode that may also act as a callable.
formatters.NullCallableString.__call__ methodAllow empty string to be callable, returning given string, if any.
Permalink Source ↗
hamingjur.formatters.NullCallableString.__call__(*args: str) -> str
Allow empty string to be callable, returning given string, if any.

When called with an int as the first arg, return an empty Unicode. An int is a good hint
that I am a :class:`ParameterizingString`, as there are only about half a dozen string-
returning capabilities listed in terminfo(5) which accept non-int arguments, they are seldom
used.

When called with a non-int as the first arg (no no args at all), return the first arg,
acting in place of :class:`FormattingString` without any attributes.
formatters.get_proxy_string functionProxy and return callable string for proxied attributes.
Permalink Source ↗
hamingjur.formatters.get_proxy_string(term: 'Terminal', attr: str) -> None
Proxy and return callable string for proxied attributes.

.. deprecated 1.40::

    All previously-proxied terminfo(5) capabilities are now provided directly by the capability
    database in jinxed as "patches" in
    https://github.com/Rockhopper-Technologies/jinxed/blob/main/terminals.toml.

    This function always returns ``None``.
formatters.split_compound functionSplit compound formatting string into segments.
Permalink Source ↗
hamingjur.formatters.split_compound(compound: str) -> List[str]
Split compound formatting string into segments.

>>> split_compound('bold_underline_bright_blue_on_red')
['bold', 'underline', 'bright_blue', 'on_red']

:arg str compound: a string that may contain compounds, separated by
    underline (``_``).
:rtype: list
:returns: List of formatting string segments
formatters.resolve_capability functionResolve a raw terminal capability using :func:`tigetstr`.
Permalink Source ↗
hamingjur.formatters.resolve_capability(term: 'Terminal', attr: str) -> str
Resolve a raw terminal capability using :func:`tigetstr`.

:arg Terminal term: :class:`~.Terminal` instance.
:arg str attr: terminal capability name.
:returns: string of the given terminal capability named by ``attr``,
   which may be empty ('') if not found or not supported by the
   given :attr:`~.Terminal.kind`.
:rtype: str
formatters.resolve_color functionResolve a simple color name to a callable capability.
Permalink Source ↗
hamingjur.formatters.resolve_color(term: 'Terminal', color: str) -> Union[NullCallableString, FormattingString]
Resolve a simple color name to a callable capability.

This function supports :func:`resolve_attribute`.

:arg Terminal term: :class:`~.Terminal` instance.
:arg str color: any string found in set :const:`COLORS`.
:returns: a string class instance which emits the terminal sequence
    for the given color, and may be used as a callable to wrap the
    given string with such sequence.
:returns: :class:`NullCallableString` when
    :attr:`~.Terminal.number_of_colors` is 0,
    otherwise :class:`FormattingString`.
:rtype: :class:`NullCallableString` or :class:`FormattingString`
formatters.resolve_attribute functionResolve a terminal attribute name into a capability class.
Permalink Source ↗
hamingjur.formatters.resolve_attribute(term: 'Terminal', attr: str) -> Union[ParameterizingString, FormattingString]
Resolve a terminal attribute name into a capability class.

:arg Terminal term: :class:`~.Terminal` instance.
:arg str attr: Sugary, ordinary, or compound formatted terminal
    capability, such as "red_on_white", "normal", "red", or
    "bold_on_black".
:returns: a string class instance which emits the terminal sequence
    for the given terminal capability, or may be used as a callable to
    wrap the given string with such sequence.
:returns: :class:`NullCallableString` when
    :attr:`~.Terminal.number_of_colors` is 0,
    otherwise :class:`FormattingString`.
:rtype: :class:`NullCallableString` or :class:`FormattingString`
hamingjur.sequences20 entries

Module providing 'sequence awareness'.

sequences.Termcap classTerminal capability of given variable name and pattern.
Permalink Source ↗
hamingjur.sequences.Termcap(name: str, pattern: str, attribute: str, nparams: int=0) -> None
Terminal capability of given variable name and pattern.

Constructor
-----------
Class initializer.

:arg str name: name describing capability.
:arg str pattern: regular expression string.
:arg str attribute: :class:`~.Terminal` attribute used to build
    this terminal capability.
:arg int nparams: number of positional arguments for callable.
sequences.Termcap.named_pattern propertyRegular expression pattern for capability with named group.
Permalink Source ↗
hamingjur.sequences.Termcap.named_pattern -> str
Regular expression pattern for capability with named group.
sequences.Termcap.re_compiled propertyCompiled regular expression pattern for capability.
Permalink Source ↗
hamingjur.sequences.Termcap.re_compiled -> Pattern[str]
Compiled regular expression pattern for capability.
sequences.Termcap.will_move propertyWhether capability causes cursor movement.
Permalink Source ↗
hamingjur.sequences.Termcap.will_move -> bool
Whether capability causes cursor movement.
sequences.Termcap.horizontal_distance methodHorizontal carriage adjusted by capability, may be negative.
Permalink Source ↗
hamingjur.sequences.Termcap.horizontal_distance(text: str) -> int
Horizontal carriage adjusted by capability, may be negative.

:rtype: int
:arg str text: for capabilities *parm_left_cursor*, *parm_right_cursor*, provide the
    matching sequence text, its interpreted distance is returned.
:returns: 0 except for matching '
:raises ValueError: ``text`` does not match regex for capability
sequences.Termcap.build methodClass factory builder for given capability definition.
Permalink Source ↗
hamingjur.sequences.Termcap.build(name: str, capability: str, attribute: str, nparams: int=0, numeric: int=99, match_grouped: bool=False, match_any: bool=False, match_optional: bool=False) -> 'Termcap'
Class factory builder for given capability definition.

:arg str name: Variable name given for this pattern.
:arg str capability: A unicode string representing a terminal
    capability to build for. When ``nparams`` is non-zero, it
    must be a callable unicode string, such as the result from
    ``getattr(term, 'bold')``.
:arg str attribute: The terminfo(5) capability name by which this
    pattern is known.
:arg int nparams: number of positional arguments for callable.
:arg int numeric: Value to substitute into capability to when generating pattern
:arg bool match_grouped: If the numeric pattern should be
    grouped, ``(\d+)`` when ``True``, ``\d+`` default.
:arg bool match_any: When keyword argument ``nparams`` is given,
    *any* numeric found in output is suitable for building as
    pattern ``(\d+)``.  Otherwise, only the first matching value of
    range *(numeric - 1)* through *(numeric + 1)* will be replaced by
    pattern ``(\d+)`` in builder.
:arg bool match_optional: When ``True``, building of numeric patterns
    containing ``(\d+)`` will be built as optional, ``(\d+)?``.
:rtype: hamingjur.sequences.Termcap
:returns: Terminal capability instance for given capability definition
sequences.Sequence classA "sequence-aware" version of the base :class:`str` class.
Permalink Source ↗
hamingjur.sequences.Sequence
Bases: str
A "sequence-aware" version of the base :class:`str` class.

This unicode-derived class understands the effect of escape sequences
of printable length, allowing a properly implemented :meth:`rjust`,
:meth:`ljust`, :meth:`center`, and :meth:`length`.

.. note:: that other than :meth:`Sequence.padd`, this is just a thin layer
    over :mod:`wcwidth`, kept by name for API compatibility.
sequences.Sequence.ljust methodReturn string containing sequences, left-adjusted.
Permalink Source ↗
hamingjur.sequences.Sequence.ljust(width: SupportsIndex, fillchar: str=' ') -> str
Return string containing sequences, left-adjusted.

:arg int width: Total width given to left-adjust ``text``.
:arg str fillchar: String for padding right-of ``text``.
:returns: String of ``text``, left-aligned by ``width``.
:rtype: str
sequences.Sequence.rjust methodReturn string containing sequences, right-adjusted.
Permalink Source ↗
hamingjur.sequences.Sequence.rjust(width: SupportsIndex, fillchar: str=' ') -> str
Return string containing sequences, right-adjusted.

:arg int width: Total width given to right-adjust ``text``.
:arg str fillchar: String for padding left-of ``text``.
:returns: String of ``text``, right-aligned by ``width``.
:rtype: str
sequences.Sequence.center methodReturn string containing sequences, centered.
Permalink Source ↗
hamingjur.sequences.Sequence.center(width: SupportsIndex, fillchar: str=' ') -> str
Return string containing sequences, centered.

:arg int width: Total width given to center ``text``.
:arg str fillchar: String for padding left and right-of ``text``.
:returns: String of ``text``, centered by ``width``.
:rtype: str
sequences.Sequence.clip methodReturn a window of this string spanning display columns ``start`` to ``end``.
Permalink Source ↗
hamingjur.sequences.Sequence.clip(start: SupportsIndex=0, end: SupportsIndex=-1, *, fillchar: str=' ', tabsize: int=8, propagate_sgr: bool=True, control_codes: Literal['parse', 'strict', 'ignore']='parse', overtyping: Optional[bool]=None) -> str
Return a window of this string spanning display columns ``start`` to ``end``.

Like :meth:`~.Terminal.clip`, which documents the arguments. Cursor movement
is interpreted by :func:`wcwidth.clip`, and the terminal's detected
``ambiguous_width`` and ``term_program`` are applied.

:rtype: str
:returns: This string clipped to display columns (start, end)
sequences.Sequence.truncate methodTruncate a string in a sequence-aware manner.
Permalink Source ↗
hamingjur.sequences.Sequence.truncate(width: SupportsIndex) -> str
Truncate a string in a sequence-aware manner.

Any printable characters beyond ``width`` are removed, while all
sequences remain in place. Horizontal cursor movement is interpreted
by :func:`wcwidth.clip`.

Wide characters (such as CJK or emoji) that would partially exceed
``width`` are replaced with space padding to maintain exact width.

SGR (terminal styling) sequences are propagated: the result begins
with any active style at the start position and ends with a reset
sequence if styles were active.

:arg int width: The printable width to truncate the string to.
:rtype: str
:returns: String truncated to exactly ``width`` printable characters.
sequences.Sequence.length methodReturn the printable length of string containing sequences.
Permalink Source ↗
hamingjur.sequences.Sequence.length() -> int
Return the printable length of string containing sequences.

Returns the maximum horizontal cursor extent reached while processing
the string. Backspace and cursor-left movements do not reduce the
length below the maximum position reached.

Some characters may consume more than one cell, mainly CJK (Chinese,
Japanese, Korean) and Emojis and some kinds of symbols.

For example:

    >>> from hamingjur import Terminal
    >>> from hamingjur.sequences import Sequence
    >>> term = Terminal()
    >>> msg = term.clear + term.red('コンニチハ')
    >>> Sequence(msg, term).length()
    10

.. note:: Although accounted for, strings containing sequences such
    as ``term.clear`` will not give accurate returns, it is not
    considered lengthy (a length of 0).
sequences.Sequence.strip methodReturn string of sequences, leading and trailing whitespace removed.
Permalink Source ↗
hamingjur.sequences.Sequence.strip(chars: Optional[str]=None) -> str
Return string of sequences, leading and trailing whitespace removed.

:arg str chars: Remove characters in chars instead of whitespace.
:rtype: str
:returns: string of sequences with leading and trailing whitespace removed.
sequences.Sequence.lstrip methodReturn string of all sequences and leading whitespace removed.
Permalink Source ↗
hamingjur.sequences.Sequence.lstrip(chars: Optional[str]=None) -> str
Return string of all sequences and leading whitespace removed.

:arg str chars: Remove characters in chars instead of whitespace.
:rtype: str
:returns: string of sequences with leading removed.
sequences.Sequence.rstrip methodReturn string of all sequences and trailing whitespace removed.
Permalink Source ↗
hamingjur.sequences.Sequence.rstrip(chars: Optional[str]=None) -> str
Return string of all sequences and trailing whitespace removed.

:arg str chars: Remove characters in chars instead of whitespace.
:rtype: str
:returns: string of sequences with trailing removed.
sequences.Sequence.strip_seqs methodReturn ``text`` stripped of only its terminal sequences.
Permalink Source ↗
hamingjur.sequences.Sequence.strip_seqs() -> str
Return ``text`` stripped of only its terminal sequences.

:rtype: str
:returns: Text with terminal sequences removed
sequences.Sequence.padd methodReturn non-destructive horizontal movement as destructive spacing.
Permalink Source ↗
hamingjur.sequences.Sequence.padd(strip: bool=False) -> str
Return non-destructive horizontal movement as destructive spacing.

:arg bool strip: Strip terminal sequences
:rtype: str
:returns: Text adjusted for horizontal movement
sequences.iter_parse functionGenerator yields (text, capability) for characters of ``text``.
Permalink Source ↗
hamingjur.sequences.iter_parse(term: 'Terminal', text: str) -> Iterator[Tuple[str, Optional[Termcap]]]
Generator yields (text, capability) for characters of ``text``.

value for ``capability`` may be ``None``, where ``text`` is
:class:`str` of length 1.  Otherwise, ``text`` is a full
matching sequence of given capability.

.. note:: Previously used by SequenceTextWrapper, sequence-aware text
   wrapping now exists in wcwidth as :func:`wcwidth.wrap`. This function
   is kept for API compatibility and used by :func:`measure_length`.
sequences.measure_length functionKept for API compatibility.
Permalink Source ↗
hamingjur.sequences.measure_length(text: str, term: 'Terminal') -> int
Kept for API compatibility.

:rtype: int
:returns: Length of the first sequence in the string

.. deprecated:: 1.30.0
hamingjur.win_terminal9 entries

Module containing Windows version of :class:`Terminal`.

win_terminal.Terminal classWindows subclass of :class:`Terminal`.
Permalink Source ↗
hamingjur.win_terminal.Terminal(kind: Optional[str]=None, stream: Optional[IO[str]]=None, force_styling: Union[bool, None]=False, kind_fallback: str='vtwin10', _xtgettcap_data: Optional[TermcapResponse]=None) -> None
Bases: _Terminal
Windows subclass of :class:`Terminal`.

Constructor
-----------
Initialize Windows terminal instance.
win_terminal.Terminal.getch methodRead, decode, and return the next byte from the keyboard stream.
Permalink Source ↗
hamingjur.win_terminal.Terminal.getch(decode_latin1: bool=False) -> str
Read, decode, and return the next byte from the keyboard stream.

:arg bool decode_latin1: If True, decode byte as latin-1 (for legacy mouse
    sequences with 8-bit coordinates).
:rtype: unicode
:returns: a single unicode character, or ``''`` if a multi-byte
    sequence has not yet been fully received.

For versions of Windows 10.0.10586 and later, the console is expected
to be in ENABLE_VIRTUAL_TERMINAL_INPUT mode and the default method is
called.

For older versions of Windows, msvcrt.getwch() is used. If the received
character is ``\x00`` or ``\xe0``, the next character is
automatically retrieved.

When native console events (mouse, resize) have been synthesized
into escape sequences, buffered characters are returned first.
win_terminal.Terminal.kbhit methodReturn whether a keypress has been detected on the keyboard.
Permalink Source ↗
hamingjur.win_terminal.Terminal.kbhit(timeout: Optional[float]=None) -> bool
Return whether a keypress has been detected on the keyboard.

This method is used by :meth:`inkey` to determine if a byte may
be read using :meth:`getch` without blocking.

Uses :class:`jinxed.win32.ConsoleInput` for efficient, non-polling
input detection.  Non-key-down events (key-up releases, resize)
are consumed so they do not cause spurious returns.

When native event handling is enabled, ``MOUSE_EVENT`` and
``WINDOW_BUFFER_SIZE_EVENT`` records are converted to escape
sequences and buffered for :meth:`getch`.

:arg float timeout: When ``timeout`` is 0, this call is
    non-blocking, otherwise blocking indefinitely until keypress
    is detected when None (default). When ``timeout`` is a
    positive number, returns after ``timeout`` seconds have
    elapsed (float).
:rtype: bool
:returns: True if a keypress is awaiting to be read on the keyboard
    attached to this terminal within the given ``timeout``.
win_terminal.Terminal.mouse_enabled context managerContext manager for enabling mouse tracking.
Permalink Source ↗
hamingjur.win_terminal.Terminal.mouse_enabled(*, clicks: bool=True, report_pixels: bool=False, report_drag: bool=False, report_motion: bool=False, timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS) -> Generator[None, None, None]
Context manager for enabling mouse tracking.

Probes the terminal for DEC private mode support (SGR mouse,
mode 1006).  If supported, delegates to the base class so that
escape-sequence-based mouse tracking is used natively.

Otherwise, falls back to enabling ``ENABLE_MOUSE_INPUT`` on
the console handle and converting native ``MOUSE_EVENT``
records into SGR escape sequences so that :meth:`inkey`
returns standard :class:`~.Keystroke` objects with
``MOUSE_*`` names.

Accepts the same keyword arguments as
:meth:`~hamingjur.terminal.Terminal.mouse_enabled`.
win_terminal.Terminal.does_mouse methodCheck if the terminal supports mouse tracking.
Permalink Source ↗
hamingjur.win_terminal.Terminal.does_mouse(*, clicks: bool=True, report_pixels: bool=False, report_drag: bool=False, report_motion: bool=False, timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS) -> bool
Check if the terminal supports mouse tracking.

Returns ``True`` on Windows when connected to a real console
with styling enabled.  The terminal may support DEC private
modes for mouse (probed at enable time), but the native
console API is always available as a fallback.
win_terminal.Terminal.notify_on_resize context managerContext manager for enabling in-band window resize notifications.
Permalink Source ↗
hamingjur.win_terminal.Terminal.notify_on_resize(timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS) -> Generator[None, None, None]
Context manager for enabling in-band window resize notifications.

Probes the terminal for DEC private mode 2048 support.  If
supported, delegates to the base class.  Otherwise, falls back
to enabling ``ENABLE_WINDOW_INPUT`` on the console handle and
converting native ``WINDOW_BUFFER_SIZE_EVENT`` records into
DEC mode 2048 escape sequences so that :meth:`inkey` returns
a :class:`~.Keystroke` with ``name == 'RESIZE_EVENT'``.

DEC mode 2048 is not yet supported by Windows Terminal
(`microsoft/terminal#19618
<https://github.com/microsoft/terminal/issues/19618>`_),
so the native fallback is currently always used.

Accepts the same keyword arguments as
:meth:`~hamingjur.terminal.Terminal.notify_on_resize`.
win_terminal.Terminal.does_inband_resize methodCheck if the terminal supports in-band window resize notifications.
Permalink Source ↗
hamingjur.win_terminal.Terminal.does_inband_resize(timeout: float=TERMINAL_QUERY_TIMEOUT_SECONDS) -> bool
Check if the terminal supports in-band window resize notifications.

Returns ``True`` on Windows when connected to a real console
with styling enabled.  The terminal may support DEC mode 2048
(probed at enable time), but the native console
``WINDOW_BUFFER_SIZE_EVENT`` is always available as a fallback.
win_terminal.Terminal.cbreak context managerAllow each keystroke to be read immediately after it is pressed.
Permalink Source ↗
hamingjur.win_terminal.Terminal.cbreak() -> Generator[None, None, None]
Allow each keystroke to be read immediately after it is pressed.

This is a context manager for ``jinxed.w32.setcbreak()``.

.. note:: You must explicitly print any user input you would like
    displayed.  If you provide any kind of editing, you must handle
    backspace and other line-editing control functions in this mode
    as well!

**Normally**, characters received from the keyboard cannot be read
by Python until the *Return* key is pressed. Also known as *cooked* or
*canonical input* mode, it allows the tty driver to provide
line-editing before shuttling the input to your program and is the
(implicit) default terminal mode set by most unix shells before
executing programs.
win_terminal.Terminal.raw context managerA context manager for ``jinxed.w32.setcbreak()``.
Permalink Source ↗
hamingjur.win_terminal.Terminal.raw() -> Generator[None, None, None]
A context manager for ``jinxed.w32.setcbreak()``.

Although both :meth:`break` and :meth:`raw` modes allow each keystroke
to be read immediately after it is pressed, Raw mode disables
processing of input and output.

In cbreak mode, special input characters such as ``^C`` are
interpreted by the terminal driver and excluded from the stdin stream.
In raw mode these values are receive by the :meth:`inkey` method.
hamingjur.game.nav4 entries

Deterministic four-neighbour navigation on caller-defined tile costs.

game.nav.distance_field functionMinimum cost from each reachable tile to any goal, including directed costs.
Permalink Source ↗
hamingjur.game.nav.distance_field(bounds: Rect, goals: Iterable[Tile], cost: Cost) -> dict[Tile, float]
Minimum cost from each reachable tile to any goal, including directed costs.
game.nav.find_path functionReturn a lowest-cost path including both endpoints, or None if unreachable.
Permalink Source ↗
hamingjur.game.nav.find_path(bounds: Rect, start: Tile, goal: Tile, cost: Cost) -> list[Tile] | None
Return a lowest-cost path including both endpoints, or None if unreachable.
game.nav.line_tiles functionYield cells touched by a center-to-center segment, including both corner neighbours.
Permalink Source ↗
hamingjur.game.nav.line_tiles(start: Tile, end: Tile) -> Iterator[Tile]
Yield cells touched by a center-to-center segment, including both corner neighbours.
game.nav.line_clear functionTest line of sight through cells using the caller's visibility rules.
Permalink Source ↗
hamingjur.game.nav.line_clear(start: Tile, end: Tile, passable: Callable[[Tile], bool]) -> bool
Test line of sight through cells using the caller's visibility rules.
hamingjur.game.render6 entries

Retained Kitty atlas placements clipped against the desktop's final paint order.

game.render.fragments functionMerge contiguous visible cell runs into pixel rectangles.
Permalink Source ↗
hamingjur.game.render.fragments(box, clip, cell, cover, stamp)
Merge contiguous visible cell runs into pixel rectangles.
game.render.Placement classPublic declaration.
Permalink Source ↗
hamingjur.game.render.Placement
Fields & constants
asset: tuple[Atlas, int, int]
source: Rect
x: int
y: int
z: int
cell: tuple[int, int]
game.render.Renderer classPublic declaration.
Permalink Source ↗
hamingjur.game.render.Renderer(term) -> None
Bases: GraphicLayer
game.render.Renderer.present methodPublic declaration.
Permalink Source ↗
hamingjur.game.render.Renderer.present(canvas: Canvas) -> None
game.render.Renderer.graphics_error methodPublic declaration.
Permalink Source ↗
hamingjur.game.render.Renderer.graphics_error(image_id: int, reason: str) -> None
game.render.Renderer.release methodPublic declaration.
Permalink Source ↗
hamingjur.game.render.Renderer.release() -> None
hamingjur.game.scene13 entries

World coordinates, sprite sheets, and declarative game frames.

game.scene.Camera classWorld rectangle mapped to a viewport, in logical terminal-cell units.
Permalink Source ↗
hamingjur.game.scene.Camera
World rectangle mapped to a viewport, in logical terminal-cell units.
Fields & constants
x: float
y: float
width: float
height: float
game.scene.Camera.fit methodShow the entire supplied world rectangle.
Permalink Source ↗
hamingjur.game.scene.Camera.fit(bounds: Rect) -> Camera
Show the entire supplied world rectangle.
game.scene.Camera.follow methodCenter on a target, clamping the view inside the supplied world.
Permalink Source ↗
hamingjur.game.scene.Camera.follow(target: Point, *, bounds: Rect) -> Camera
Center on a target, clamping the view inside the supplied world.
game.scene.Camera.transform methodReturn the origin and uniform world-to-cell scale.
Permalink Source ↗
hamingjur.game.scene.Camera.transform(viewport: Rect) -> tuple[float, float, float]
Return the origin and uniform world-to-cell scale.
game.scene.Camera.project methodMap a world point to absolute screen cells, retaining its fractional offset.
Permalink Source ↗
hamingjur.game.scene.Camera.project(point: Point, viewport: Rect) -> Point
Map a world point to absolute screen cells, retaining its fractional offset.
game.scene.Camera.unproject methodConvert a screen cell position back to world coordinates.
Permalink Source ↗
hamingjur.game.scene.Camera.unproject(point: Point, viewport: Rect) -> Point
Convert a screen cell position back to world coordinates.
game.scene.Atlas classA Pillow sheet of equal-sized frames in row-major order. Treat pixels as immutable.
Permalink Source ↗
hamingjur.game.scene.Atlas
A Pillow sheet of equal-sized frames in row-major order. Treat pixels as immutable.
Fields & constants
image: Image
width: int
height: int
game.scene.Atlas.origin methodPublic declaration.
Permalink Source ↗
hamingjur.game.scene.Atlas.origin(index: int) -> tuple[int, int]
game.scene.Sprite classPublic declaration.
Permalink Source ↗
hamingjur.game.scene.Sprite
Fields & constants
key: Hashable
at: Point
size: Point
glyph: str
atlas: Atlas | None
index: int
layer: int
sort_y: float
game.scene.Frame classOne desired scene. Sprite positions are top-left points in world units.
Permalink Source ↗
hamingjur.game.scene.Frame(camera: Camera)
One desired scene. Sprite positions are top-left points in world units.
game.scene.Frame.sprite methodPlace an atlas frame or text glyph under a unique key for this draw.
Permalink Source ↗
hamingjur.game.scene.Frame.sprite(key: Hashable, at: Point, *, atlas: Atlas | None=None, index: int=0, size: Point=(1, 1), glyph: str='*', layer: int=0, sort_y: float | None=None) -> None
Place an atlas frame or text glyph under a unique key for this draw.
game.scene.Frame.label methodDraw a themed text label above the scene at a world point.
Permalink Source ↗
hamingjur.game.scene.Frame.label(at: Point, text: str, role: str='text') -> None
Draw a themed text label above the scene at a world point.
game.scene.Frame.tiles methodRequest only the visible world tiles from a caller-owned map or chunk cache.
Permalink Source ↗
hamingjur.game.scene.Frame.tiles(key: Hashable, visible: Callable[[Rect], Iterable[tuple[int, int, int]]], *, atlas: Atlas, glyph: str | Callable[[int], str]='.', layer: int=-1) -> None
Request only the visible world tiles from a caller-owned map or chunk cache.
hamingjur.game.session17 entries

Fixed-step simulation and terminal-independent action input.

game.session.Action classOne game-defined command, optionally carrying a world position or path.
Permalink Source ↗
hamingjur.game.session.Action
One game-defined command, optionally carrying a world position or path.
Fields & constants
name: str
value: object = None
game.session.Actions classOrdered one-shot commands and the controls held during this tick.
Permalink Source ↗
hamingjur.game.session.Actions
Ordered one-shot commands and the controls held during this tick.
Fields & constants
events: tuple[Action, ...] = ()
held: frozenset[str] = frozenset()
game.session.Game classA simulation can also be stepped without creating a terminal.
Permalink Source ↗
hamingjur.game.session.Game
Bases: Protocol
A simulation can also be stepped without creating a terminal.
game.session.Game.step methodPublic declaration.
Permalink Source ↗
hamingjur.game.session.Game.step(tick: int, actions: Actions) -> None
game.session.Game.draw methodPublic declaration.
Permalink Source ↗
hamingjur.game.session.Game.draw(frame: Frame, alpha: float) -> None
game.session.Bindings classMap terminal keys and pointer gestures to game-defined actions.
Permalink Source ↗
hamingjur.game.session.Bindings() -> None
Map terminal keys and pointer gestures to game-defined actions.
game.session.Bindings.press methodQueue each press, optionally accepting reported repeats.
Permalink Source ↗
hamingjur.game.session.Bindings.press(action: str, key: str, *, repeat: bool=False) -> None
Queue each press, optionally accepting reported repeats.
game.session.Bindings.hold methodExpose the action on every tick while its key is held.
Permalink Source ↗
hamingjur.game.session.Bindings.hold(action: str, key: str) -> None
Expose the action on every tick while its key is held.
game.session.Bindings.remember methodLatch this action until another key in the same group replaces it.
Permalink Source ↗
hamingjur.game.session.Bindings.remember(action: str, key: str, *, group: str='direction') -> None
Latch this action until another key in the same group replaces it.
game.session.Bindings.click methodQueue the world position of a pointer press.
Permalink Source ↗
hamingjur.game.session.Bindings.click(action: str, button: str='LEFT') -> None
Queue the world position of a pointer press.
game.session.Bindings.stroke methodQueue the complete world-space path when the pointer is released.
Permalink Source ↗
hamingjur.game.session.Bindings.stroke(action: str, button: str='LEFT') -> None
Queue the complete world-space path when the pointer is released.
game.session.GameSession classOwn one simulation, its tick counter, and its pending controls.
Permalink Source ↗
hamingjur.game.session.GameSession(game: Game, bindings: Bindings | None=None, *, tick_hz: int=60, legacy_hold_seconds: float=0.25, on_tick: Callable[[int, Actions], None] | None=None)
Own one simulation, its tick counter, and its pending controls.
game.session.GameSession.submit methodAppend an action for the next simulation tick.
Permalink Source ↗
hamingjur.game.session.GameSession.submit(action: str, value: object=None) -> None
Append an action for the next simulation tick.
game.session.GameSession.key methodAccept a normalized press, repeat or release. Return whether bound.
Permalink Source ↗
hamingjur.game.session.GameSession.key(key: str, kind: str='press', *, releases: bool=True) -> bool
Accept a normalized press, repeat or release. Return whether bound.
game.session.GameSession.clear_input methodCancel queued and held controls when input ownership changes.
Permalink Source ↗
hamingjur.game.session.GameSession.clear_input() -> None
Cancel queued and held controls when input ownership changes.
game.session.GameSession.step methodAdvance one tick. The returned input can be streamed to a recorder.
Permalink Source ↗
hamingjur.game.session.GameSession.step(actions: Actions | None=None) -> Actions
Advance one tick. The returned input can be streamed to a recorder.
game.session.GameSession.replay methodAdvance once per recorded tick from a lazily consumed input stream.
Permalink Source ↗
hamingjur.game.session.GameSession.replay(stream: Iterable[Actions]) -> None
Advance once per recorded tick from a lazily consumed input stream.
hamingjur.game.view9 entries

Widget and full-screen hosts for terminal games.

game.view.GameView classRun a session while focused. Menus, dialogs and focus loss pause its clock.
Permalink Source ↗
hamingjur.game.view.GameView(session: GameSession, *, camera: Camera | None=None, frame_hz: float | None=None, **options)
Bases: Widget
Run a session while focused. Menus, dialogs and focus loss pause its clock.
Fields & constants
focusable = True
track_terminal_focus = True
game.view.GameView.strokes propertyWorld-space paths currently being drawn, for live previews.
Permalink Source ↗
hamingjur.game.view.GameView.strokes
World-space paths currently being drawn, for live previews.
game.view.GameView.input_modes methodPublic declaration.
Permalink Source ↗
hamingjur.game.view.GameView.input_modes(terminal, stack)
game.view.GameView.on_blur methodPublic declaration.
Permalink Source ↗
hamingjur.game.view.GameView.on_blur()
game.view.GameView.on_frame methodPublic declaration.
Permalink Source ↗
hamingjur.game.view.GameView.on_frame(now)
game.view.GameView.on_key methodPublic declaration.
Permalink Source ↗
hamingjur.game.view.GameView.on_key(key, app)
game.view.GameView.on_pointer methodPublic declaration.
Permalink Source ↗
hamingjur.game.view.GameView.on_pointer(pointer, app)
game.view.GameView.draw methodPublic declaration.
Permalink Source ↗
hamingjur.game.view.GameView.draw(surface, focused=None)
game.view.run functionRun a borderless game with the same widget host. Escape exits by default.
Permalink Source ↗
hamingjur.game.view.run(session: GameSession, *, camera: Camera | None=None, frame_hz: float | None=None, terminal=None)
Run a borderless game with the same widget host. Escape exits by default.
hamingjur.resizing1 entries

Scoped SIGWINCH wakeups for synchronous and asynchronous terminal input.

resizing.signal_resizes context managerWake input with a pipe; signals coalesce into the current OS window size.
Permalink Source ↗
hamingjur.resizing.signal_resizes(terminal: Terminal) -> Iterator[None]
Wake input with a pipe; signals coalesce into the current OS window size.

:raises RuntimeError: If signal fallback is entered outside the main thread.
hamingjur.ui.images5 entries

Annotated desktop images with readable text on portable terminals.

ui.images.ImageView classA raster widget whose description is available as text and Silkie metadata.
Permalink Source ↗
hamingjur.ui.images.ImageView(image: Image, annotation: ImageAnnotation, **options)
Bases: Widget
A raster widget whose description is available as text and Silkie metadata.

Constructor
-----------
Set the source image and the text explaining what it communicates.
Fields & constants
focusable = True
ui.images.ImageView.image propertyReturn the original raster, retained for terminal density changes.
Permalink Source ↗
hamingjur.ui.images.ImageView.image -> Image
Return the original raster, retained for terminal density changes.
ui.images.ImageView.refresh methodMark a modified source image for upload on the next frame.
Permalink Source ↗
hamingjur.ui.images.ImageView.refresh() -> None
Mark a modified source image for upload on the next frame.
ui.images.ImageView.draw methodDraw a caption and text fallback before offering the image to the compositor.
Permalink Source ↗
hamingjur.ui.images.ImageView.draw(surface: Surface, focused: Widget | None=None) -> None
Draw a caption and text fallback before offering the image to the compositor.
ui.images.ImageView.on_key methodOpen a scrollable description from the keyboard.
Permalink Source ↗
hamingjur.ui.images.ImageView.on_key(key: Keystroke | str, app: Application) -> bool
Open a scrollable description from the keyboard.

This reference is generated from the checkout’s public Python declarations, without importing platform-specific modules. Constructor signatures, keyword-only arguments, return annotations, enums, and fields come directly from source. Original docstrings retain reStructuredText notation and examples. Inherited methods live under their defining class; dynamic terminal capabilities such as term.bold_green are resolved at runtime.

Common exports: hamingjur.Terminal, LineEditor, LineHistory, Transfer, ImageSupport, PreparedImage, DrawnImage, and the graphics, kitty, protocols, and silkie modules. Definitions are linked under their source modules above. The platform selects the terminal implementation on import.

08 / OPEN SOURCE

Contributing & upstream.

Work on Hamingjur

Contributions are welcome through GitHub pull requests. The contribution guide covers editable installs, tox, code style, and test coverage. Include a regression test with a bug fix and tests for a new feature.

Maintainer
Adam DePrince
License
MIT
Language
Python 3.9+

Credit where it belongs

Hamingjur is an independent fork of Blessed, building on work by Jeff Quast, Avram Lubkin, and the Blessed community. Blessed was forked from Erik Rose’s blessings.

The MIT license retains the copyright notices for Jeff Quast (2014) and Erik Rose (2011), alongside Adam DePrince’s fork contributions (2026). The portable terminal foundation comes from that shared work.