kittygraphics

package
v0.4.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 27, 2026 License: GPL-3.0 Imports: 12 Imported by: 0

Documentation

Overview

Package kittygraphics implements the bounded Kitty graphics protocol adapter. It parses APC graphics commands independently of terminal text state and applies accepted image and placement operations to a graphics scene.

Index

Constants

View Source
const (
	// DefaultMaxAPCBytes bounds the complete framed APC, including its
	// controls and encoded payload.
	DefaultMaxAPCBytes = uint64(32 << 20)
	// DefaultMaxPayloadBytes bounds encoded bytes in one image, before base64
	// decoding. The graphics scene applies its own encoded-byte budget too.
	DefaultMaxPayloadBytes = uint64(24 << 20)
	DefaultMaxUploadBytes  = uint64(16 << 20)
	DefaultMaxChunks       = uint64(1024)
	DefaultMaxPixels       = uint64(128 << 20)
	DefaultMaxDecodedBytes = uint64(256 << 20)
	DefaultMaxDimension    = uint64(1 << 20)
)
View Source
const (
	QuietNever   Quiet = 0
	QuietSuccess Quiet = 1
	QuietAll     Quiet = 2

	QuietNone       = QuietNever
	QuietErrorsOnly = QuietSuccess
	QuietEverything = QuietAll
)
View Source
const MaxInt64 = int64(math.MaxInt64)

MaxInt64 is exported for callers constructing checked protocol geometry.

View Source
const MaxKittyID = uint64(^uint32(0))

MaxKittyID is the largest protocol image or placement identifier.

Variables

View Source
var (
	ErrInvalidAPC        = errors.New("invalid kitty graphics APC")
	ErrAPCTooLarge       = errors.New("kitty graphics APC is too large")
	ErrAPCTruncated      = errors.New("truncated kitty graphics APC")
	ErrInvalidCommand    = errors.New("invalid kitty graphics command")
	ErrUnknownAction     = errors.New("unknown kitty graphics action")
	ErrUnknownControl    = errors.New("unknown kitty graphics control")
	ErrDuplicateControl  = errors.New("duplicate kitty graphics control")
	ErrInvalidInteger    = errors.New("invalid kitty graphics integer")
	ErrIntegerOverflow   = errors.New("kitty graphics integer overflow")
	ErrInvalidBase64     = errors.New("invalid kitty graphics base64")
	ErrInvalidPNG        = errors.New("invalid kitty graphics PNG")
	ErrPayloadTooLarge   = errors.New("kitty graphics payload is too large")
	ErrTooManyChunks     = errors.New("too many kitty graphics continuation chunks")
	ErrInterleavedUpload = errors.New("interleaved kitty graphics upload")
	ErrUnsupported       = errors.New("unsupported kitty graphics command")
	ErrImageNotFound     = errors.New("kitty graphics image not found")
	ErrPlacementNotFound = errors.New("kitty graphics placement not found")
	ErrNoScene           = errors.New("kitty graphics scene is nil")
)

Functions

func DecodeBase64

func DecodeBase64(encoded []byte) ([]byte, error)

DecodeBase64 accepts both padded standard base64 and unpadded raw standard base64. It deliberately does not accept URL-safe alphabets or non-base64 whitespace other than the CR/LF ignored by the standard encoding.

func DecodePayload

func DecodePayload(encoded []byte) ([]byte, error)

DecodePayload is a descriptive alias for DecodeBase64.

func MakeResponse

func MakeResponse(imageID uint64, code string) []byte

MakeResponse constructs the canonical Kitty response used by Session.

Types

type Action

type Action byte

Action is the closed set of Kitty graphics actions understood by this adapter. The underlying byte values are the protocol values.

const (
	ActionTransmit        Action = 't'
	ActionTransmitDisplay Action = 'T'
	ActionPut             Action = 'p'
	ActionQuery           Action = 'q'
	ActionDelete          Action = 'd'
	ActionFrame           Action = 'f'
	ActionCompose         Action = 'a'

	// Descriptive aliases used by callers that prefer the protocol names.
	ActionTransmitAndDisplay = ActionTransmitDisplay
	ActionDisplay            = ActionPut
)

func (Action) String

func (a Action) String() string

func (Action) Valid

func (a Action) Valid() bool

type Adapter

type Adapter = Session

Adapter is an alias for the stateful Kitty graphics session.

type Child

type Child struct {
	ID      uint64
	ImageID uint64
	AssetID graphics.AssetID
}

Child describes a session-local image child and its graphics asset. Child IDs are never sent to the terminal; they make the protocol mapping explicit and stable for consumers.

type Command

type Command struct {
	Controls Controls
	Payload  []byte
}

Command is one complete APC graphics command. Payload is the encoded command payload and is copied from the parser input.

func ParseAPC

func ParseAPC(apc []byte, config ...Limits) (Command, error)

ParseAPC parses a complete ESC _ G ... ST sequence.

func ParseCommand

func ParseCommand(body []byte, config ...Limits) (Command, error)

ParseCommand parses the bytes between APC's G and its ST terminator. It is exported separately so adapters can validate commands without maintaining a stream parser.

type Compression added in v0.4.1

type Compression byte

Compression is the optional compression applied to raw image data.

const CompressionZlib Compression = 'z'

type Config

type Config = Limits

Config is an alias retained for callers that use constructor terminology.

type ControlKey

type ControlKey byte

ControlKey identifies a recognized Kitty control field.

const (
	ControlAction       ControlKey = 'a'
	ControlCompression  ControlKey = 'o'
	ControlFormat       ControlKey = 'f'
	ControlImageID      ControlKey = 'i'
	ControlImageNumber  ControlKey = 'I'
	ControlMore         ControlKey = 'm'
	ControlQuiet        ControlKey = 'q'
	ControlWidth        ControlKey = 's'
	ControlHeight       ControlKey = 'v'
	ControlColumns      ControlKey = 'c'
	ControlRows         ControlKey = 'r'
	ControlX            ControlKey = 'x'
	ControlY            ControlKey = 'y'
	ControlSourceWidth  ControlKey = 'w'
	ControlSourceHeight ControlKey = 'h'
	ControlLayer        ControlKey = 'z'
	ControlPlacementID  ControlKey = 'p'
	ControlDelete       ControlKey = 'd'
	ControlTransmission ControlKey = 't'
	ControlCursor       ControlKey = 'C'
	ControlSourceX      ControlKey = 'X'
	ControlSourceY      ControlKey = 'Y'
	ControlCellOffsetX  ControlKey = 'H'
	ControlCellOffsetY  ControlKey = 'V'
	ControlParent       ControlKey = 'P'
)

type Controls

type Controls struct {
	Action          Action
	HasAction       bool
	Compression     Compression
	HasCompression  bool
	Format          Format
	HasFormat       bool
	ImageID         uint64
	HasImageID      bool
	ImageNumber     uint64
	HasImageNumber  bool
	More            uint64
	HasMore         bool
	Quiet           Quiet
	HasQuiet        bool
	Width           uint64
	HasWidth        bool
	Height          uint64
	HasHeight       bool
	Columns         uint64
	HasColumns      bool
	Rows            uint64
	HasRows         bool
	X               uint64
	HasX            bool
	Y               uint64
	HasY            bool
	SourceWidth     uint64
	HasSourceWidth  bool
	SourceHeight    uint64
	HasSourceHeight bool
	Layer           int64
	HasLayer        bool
	PlacementID     uint64
	HasPlacementID  bool
	Delete          DeleteTarget
	HasDelete       bool
	Transmission    Transmission
	HasTransmission bool
	Cursor          uint64
	HasCursor       bool
	SourceX         uint64
	HasSourceX      bool
	SourceY         uint64
	HasSourceY      bool
	CellOffsetX     int64
	HasCellOffsetX  bool
	CellOffsetY     int64
	HasCellOffsetY  bool
	Parent          uint64
	HasParent       bool
}

Controls is the typed, closed representation of a Kitty control header. Has* fields preserve the distinction between an omitted field and zero.

func ParseControls

func ParseControls(header []byte) (Controls, error)

ParseControls parses the comma-separated control header of an APC.

func ParseHeader

func ParseHeader(header []byte) (Controls, error)

ParseHeader is an alias for ParseControls.

type DeleteTarget

type DeleteTarget byte

DeleteTarget is the closed set of targets accepted by a delete action.

const (
	DeleteImage       DeleteTarget = 'i'
	DeleteImageNumber DeleteTarget = 'I'
	DeleteCell        DeleteTarget = 'p'
	DeleteAll         DeleteTarget = 'a'
	DeleteAllImages   DeleteTarget = 'A'
	DeleteCellAll     DeleteTarget = 'P'
)

type Event

type Event struct {
	Kind    EventKind
	Text    []byte
	Command Command
	Err     error
}

Event is emitted by Parser. Text and command payloads are owned by the event and remain valid after the next Feed call.

type EventKind

type EventKind uint8

EventKind identifies parser output. Text events contain bytes which are not Kitty graphics APCs; command events contain complete commands.

const (
	EventText EventKind = iota + 1
	EventCommand
	EventError
)

type Format

type Format uint64

Format is the closed set of Kitty image formats supported by this adapter.

const (
	FormatRGB  Format = 24
	FormatRGBA Format = 32
	FormatPNG  Format = 100

	FormatRGB24  = FormatRGB
	FormatRGBA32 = FormatRGBA
)

func (Format) Valid

func (f Format) Valid() bool

type Limits

type Limits struct {
	MaxAPCBytes      uint64
	MaxPayloadBytes  uint64
	MaxUploadBytes   uint64
	MaxChunks        uint64
	MaxDecodedPixels uint64
	MaxDecodedBytes  uint64
	MaxDimension     uint64
	MaxResponseBytes uint64
	MaxImages        uint64
	MaxPlacements    uint64
}

Limits bounds parser and adapter resource use. Zero values select bounded defaults. The limits are independent from the graphics scene limits: both layers enforce their budgets.

type Mutation

type Mutation struct {
	Kind             MutationKind
	ImageID          uint64
	ChildID          uint64
	AssetID          graphics.AssetID
	PlacementID      uint64
	ScenePlacementID graphics.PlacementID
}

Mutation records the stable protocol and opaque scene IDs involved in one accepted command.

type MutationKind

type MutationKind uint8

MutationKind describes a scene mutation performed by a session.

const (
	MutationUpload MutationKind = iota + 1
	MutationPlacement
	MutationDeleteImage
	MutationDeletePlacement
	MutationClear
	MutationDeletePlacements
)

type Parser

type Parser struct {
	// contains filtered or unexported fields
}

Parser incrementally recognizes ESC _ G APCs. It never interprets ordinary text or other escape sequences and can be fed arbitrary byte-sized chunks.

func NewParser

func NewParser(config ...Limits) *Parser

NewParser creates an incremental bounded parser.

func (*Parser) Feed

func (p *Parser) Feed(data []byte) []Event

Feed consumes data and returns text and complete graphics events. The parser retains only an incomplete APC or a possible split prefix between calls. A malformed APC is reported as an EventError and discarded through its string terminator, allowing following text and APCs to be processed.

func (*Parser) FeedWithErrors

func (p *Parser) FeedWithErrors(data []byte) ([]Event, error)

FeedWithErrors is a conventional error-returning facade over Feed. Parser errors are also retained in the returned Event values.

func (*Parser) Finish

func (p *Parser) Finish() []Event

Finish reports an unterminated APC and resets the parser. Text which is a partial ordinary escape sequence is returned as text. Finish is useful at a stream boundary; a caller that will feed more data must not call it.

func (*Parser) Flush

func (p *Parser) Flush() []Event

Flush is an alias for Finish.

func (*Parser) Limits

func (p *Parser) Limits() Limits

Limits reports the parser limits.

func (*Parser) Parse

func (p *Parser) Parse(data []byte) []Event

Parse is an alias for Feed.

type ParserConfig

type ParserConfig = Limits

ParserConfig is a descriptive alias for Limits.

type Quiet

type Quiet uint8

Quiet controls protocol response emission. Kitty uses q=1 for successful operations only and q=2 for all responses.

type Response

type Response struct {
	ImageID uint64
	OK      bool
	Code    string
	Bytes   []byte
}

Response is the wire representation of a stable Kitty response.

type Result

type Result struct {
	Events    []Event
	Responses [][]byte
	Mutations []Mutation
}

Result contains all output from one or more commands in a Feed call.

func (Result) Bytes

func (r Result) Bytes() []byte

Bytes returns response bytes in stable command order. The returned slice is newly allocated and may be modified by the caller.

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session owns protocol-to-scene mappings. It is safe for one owner to call Feed and query methods serially; the mutex also makes read-only mapping access safe while a caller publishes a snapshot.

func New

func New(scene *graphics.Scene, config ...Limits) *Session

New is a concise constructor alias for NewSession.

func NewAdapter

func NewAdapter(scene *graphics.Scene, config ...Limits) *Session

NewAdapter is an adapter-named constructor alias.

func NewSession

func NewSession(scene *graphics.Scene, config ...Limits) *Session

NewSession constructs an adapter over scene. A nil scene is allowed so the parser can still be used for validation, but commands which mutate a scene return ErrNoScene.

func (*Session) AbortPendingUpload

func (s *Session) AbortPendingUpload()

AbortPendingUpload discards an in-flight chunked upload without changing committed images or placements. Screen-level full clears use it to ensure a continuation arriving after the clear cannot publish stale graphics.

func (*Session) Asset

func (s *Session) Asset(imageID uint64) (graphics.AssetID, bool)

Asset is an alias for Image.

func (*Session) Child

func (s *Session) Child(imageID uint64) (Child, bool)

Child returns the oldest session child associated with an image ID.

func (*Session) ChildByID

func (s *Session) ChildByID(childID uint64) (Child, bool)

ChildByID returns a session child by its adapter-local ID.

func (*Session) ChildID

func (s *Session) ChildID(imageID uint64) (uint64, bool)

ChildID returns the adapter-local child ID associated with an image ID.

func (*Session) Children

func (s *Session) Children() []Child

Children returns a stable copy of all current session children in child-ID order.

func (*Session) Feed

func (s *Session) Feed(data []byte) (Result, error)

Feed parses and applies arbitrary bytes. Ordinary text is returned as EventText; it is never interpreted, discarded, or passed through graphics scene mutation. A malformed command is reported after all complete events in the same input have been handled.

func (*Session) Finish

func (s *Session) Finish() (Result, error)

Finish flushes an incomplete parser sequence. It never mutates the scene.

func (*Session) Handle

func (s *Session) Handle(data []byte) (Result, error)

Handle is an adapter-oriented alias for Feed.

func (*Session) Image

func (s *Session) Image(imageID uint64) (graphics.AssetID, bool)

Image returns the graphics asset mapped from a Kitty image ID.

func (*Session) Placement

func (s *Session) Placement(imageID, placementID uint64) (graphics.PlacementID, bool)

Placement returns the graphics placement mapped from one Kitty image and placement-ID pair. Kitty placement IDs are scoped to their image ID.

func (*Session) PlacementID

func (s *Session) PlacementID(imageID, placementID uint64) (graphics.PlacementID, bool)

PlacementID is an alias for Placement.

func (*Session) Process

func (s *Session) Process(command Command) (Result, error)

Process applies one already parsed command. It is useful for callers that have their own stream framing but want this package's strict adapter.

func (*Session) SetPendingPlacement

func (s *Session) SetPendingPlacement(x, y uint64)

SetPendingPlacement supplies the cursor-relative pixel origin for the next placement. The origin is adapter context, not a Kitty control field: Kitty X/Y remain pixel offsets within the cursor cell.

func (*Session) Write

func (s *Session) Write(data []byte) (Result, error)

Write is an adapter-oriented alias for Feed.

type Transmission

type Transmission byte

Transmission is the direct transmission mode. File, temporary-file and shared-memory transmissions are intentionally not accepted by this adapter.

const TransmissionDirect Transmission = 'd'

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL