rasterm

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 27 Imported by: 10 modules, 13 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README


Unit Tests Go Reference Releases Discord Discussion

About

rasterm draws a Go image.Image in a terminal. It writes the image with the graphics protocol that the terminal supports:

  • The Kitty graphics protocol, which kitty, Ghostty, WezTerm and Konsole support.
  • The inline images of iTerm2, which iTerm2 and WezTerm support.
  • Sixel, which foot, xterm, mlterm, Windows Terminal and others support.

It can also draw an image as text, with half blocks and 24-bit color, in a terminal that has no graphics.

rasterm asks the terminal which protocols it supports, so detection works over SSH and in tmux. It sends the bytes of a PNG or a JPEG as they are when the terminal can read them, and builds each image in memory and writes it in one call.

Status

The API changed after v0.1.23. Protocol replaced TermType, and Detect and Terminal.Encoder replaced Available, Encode, DefaultEncoder and PendingInput (D26 and D27 in docs/PLAN.md). The change is not released yet.

Installing

go get github.com/kenshaw/rasterm@latest

Using

Call Detect once, when the program starts, and keep the Terminal that it returns. Then get an encoder for the terminal, and encode each image with it:

term, pending, err := rasterm.Detect(ctx)
if err != nil {
	return err
}
enc := term.Encoder()
if enc == nil {
	return rasterm.ErrTermGraphicsNotAvailable
}
f, err := os.Open("photo.jpg")
if err != nil {
	return err
}
defer f.Close()
img, _, err := image.Decode(f)
if err != nil {
	return err
}
return enc.Encode(os.Stdout, img)

Detect finds the protocol in this order:

  1. If TERM_GRAPHICS names a protocol, Detect uses it, and asks the terminal nothing. The values are kitty, iterm, sixel, halfblock and none. Case, hyphens and a final s do not matter, so half-blocks also selects half blocks.
  2. If the program runs in tmux, Detect asks tmux for the terminal of its client. See tmux.
  3. If standard input and standard output are terminals, Detect asks the terminal. It sends all its queries in one write, and waits for the answers up to the timeout, which is 250 ms by default.
  4. If the terminal cannot be asked, or does not answer, Detect reads the other variables of the environment, such as TERM and TERM_PROGRAM.

These options change what Detect reads:

Option Default
WithInput(f) os.Stdin
WithOutput(f) os.Stdout
WithTimeout(d) DefaultDetectTimeout, 250 ms
WithGetenv(getenv) os.Getenv. A program with its own value for TERM_GRAPHICS gives it here

The context stops the wait. A terminal that does not answer is not an error.

When the terminal supports more than one protocol, Detect selects Kitty, then iTerm, then Sixel. It selects half blocks only when TERM_GRAPHICS asks for them.

The Terminal also tells what Detect found: the name and the version of the terminal, the size of a cell in pixels, each protocol that the terminal supports, and whether it reported Kitty animation.

Keys typed during the query

While Detect waits for the answers, it reads standard input. A key that the user types in that time is not part of an answer, so Detect returns it in pending, in the order that the user typed it. A program that reads standard input, such as a line editor, must use pending as its first input. Call Detect before the line editor starts.

Writing to a file

A program that writes to a file, or that knows the protocol, does not need Detect. It sets the protocol itself:

enc := rasterm.Terminal{Protocol: rasterm.Kitty}.Encoder(rasterm.WithNoNewline())

WithNoNewline writes no newline after each image. WithZlib sets how Kitty compresses raw pixels.

Sending the bytes of an image as is

An encoder sends the bytes that an image already holds, without decoding and encoding it again, when the image has one of these methods:

Interface Method Wrapper Encoders that send it as is
PNGImage PNG() []byte rasterm.PNG, rasterm.DecodePNG Kitty, iTerm
JPEGImage JPEG() []byte rasterm.JPEG, rasterm.DecodeJPEG iTerm
RGBImage RGB() []byte rasterm.RGB Kitty
RGBAImage RGBA() []byte rasterm.RGBA Kitty
buf, err := os.ReadFile("diagram.png")
if err != nil {
	return err
}
img, err := rasterm.DecodePNG(buf)
if err != nil {
	return err
}
// Kitty and iTerm send buf, and Sixel encodes img.Image
return enc.Encode(os.Stdout, img)

RGB and RGBA are packed 8-bit pixels, row by row, with no padding. RGBA alpha is not premultiplied. If the program scales or crops the image, it must wrap the new image with no bytes, or with new ones.

Raw pixels take less time to encode than a PNG, and the terminal must read more bytes. Kitty compresses raw pixels of 64 KiB or more with zlib while they compress to less than a quarter of their size. It checks after each 64 KiB, and sends the pixels raw at the first check that fails. So a flat image, such as a chart, sends few bytes, and a photo stays raw. Set WithZlib(rasterm.ZlibAlways) or WithZlib(rasterm.ZlibNever) to force the choice.

Kitty animation

A terminal with the Kitty protocol can play an animation. The program sends each frame once, as it decodes it, and the terminal keeps the time and loops:

k, ok := term.Encoder().(rasterm.KittyEncoder)
if !ok {
	return rasterm.ErrTermGraphicsNotAvailable
}
anim, err := k.Animate(os.Stdout, frames[0], delays[0])
if err != nil {
	return err
}
for i := 1; i < len(frames); i++ {
	if _, err := anim.Frame(frames[i], rasterm.KittyFrame{Delay: delays[i]}); err != nil {
		return err
	}
}
// 0 loops forever
return anim.End(0)

The terminal plays each frame as it arrives, and waits at the last frame for the next one, until End. A KittyFrame can also cover a part of the root frame, at At, over a base frame or a background color. Stop holds the frame that shows, and Delete removes the image and its frames.

Use it for a finite animation, such as a GIF. The terminal keeps every frame, so draw a stream with no end, such as video, as one image for each frame. kitty 0.20.0 and later and Ghostty 1.4.0 play animations. Terminal.KittyAnimation is true when the terminal reports it, which kitty 0.50.0 and later do, so the program decides.

Kitty stream

A stream shows pictures of one size as one Kitty image, at the times that the program chooses. The terminal stores two frames however many pictures come, so a stream suits an animation of any length, such as video:

s, err := k.Stream(os.Stdout, frames[0])
if err != nil {
	return err
}
for _, frame := range frames[1:] {
	// wait until the frame is due, then draw it
	if err := s.Draw(frame); err != nil {
		return err
	}
}

Draw writes the picture into the frame that is not shown, and then shows that frame, so the picture changes at once. Each picture must have the size of the first one. Delete removes the image.

Half blocks

The half-block encoder draws an image as text, with the ▀ character and 24-bit color. Each cell shows two pixels, one above the other. It does not scale the image, so scale it to the size of the terminal first: one column for each pixel across, and one row for each two pixels down. Detect selects it only when TERM_GRAPHICS=halfblock is set.

tmux

In a tmux pane, the Kitty and iTerm encoders wrap each escape sequence in the DCS passthrough of tmux, so that tmux sends it to the terminal. tmux sends it only when its allow-passthrough option is on:

set -g allow-passthrough on

In tmux, Detect does not ask the terminal, because tmux answers the questions itself. It asks tmux for the terminal of its client, and finds kitty, Ghostty, iTerm2 and WezTerm by name. tmux learns that name from the terminal when the client attaches, over SSH too. When allow-passthrough is off, Detect selects no protocol.

tmux does not know about an image that goes through it, so it can draw over the image. In tmux, Kitty draws each image with Unicode placeholder cells, which kitty 0.28 and later and Ghostty read. tmux keeps the cells as text, so each image keeps its rows, and the terminal draws it again when tmux draws the pane again. An iTerm image in tmux does not keep its rows.

tmux drops a sequence over its input-buffer-size, which is 1 MiB by default, so an iTerm image file over about 786 KB does not show. Kitty sends each chunk in a sequence of its own, so it has no such limit. tmux built with image support draws Sixel itself, and half blocks are text, so neither is wrapped.

Ghostty 1.3.1 can close after a clear of the terminal in tmux, when it shows images that use placeholder cells. This is a fault in Ghostty, related to Ghostty discussion 5453.

Performance

The values below were measured on 2026-11-14, with Go 1.27.4 and go-sixel v0.0.14, on an AMD Ryzen 9 9950X. Each value is the median of 6 runs. The time is the time to encode in memory. It does not include the time that the terminal takes to show the image. testdata/README.md describes each image.

An image that holds its own bytes skips the encoding:

Image Encoder Encoded Sent as is Output
flag.png as a PNG Kitty 5.82 ms 0.013 ms 63 KB, then 45 KB
flag.png as a PNG iTerm 14.0 ms 0.014 ms 137 KB, then 45 KB
photo.jpg as a JPEG iTerm 14.6 ms 0.082 ms 376 KB, then 274 KB
photo.jpg as an RGB Kitty 44.0 ms 1.84 ms 1860 KB, then 4900 KB
photo.jpg as an RGBA Kitty 44.0 ms 2.29 ms 1860 KB, then 6534 KB

A PNG or a JPEG that is sent as is takes 170 to 1000 times less time. Raw pixels take 19 to 24 times less time, and the terminal must read 3 to 4 times the bytes. iTerm sends a JPEG for an image that is not paletted (D5), so it encodes flag.png as a JPEG.

Kitty compresses raw RGBA pixels with zlib when they compress well. The size is what the terminal reads, after base64:

Image Raw Always zlib Automatic
a flat 1024 x 1024 image 5474 KiB, 1.74 ms 44 KiB, 1.40 ms 44 KiB, 1.45 ms
flag.png 4503 KiB, 1.54 ms 51 KiB, 1.77 ms 51 KiB, 1.78 ms
alpha-gradient.png 342 KiB, 0.10 ms 146 KiB, 0.99 ms 342 KiB, 0.35 ms
random noise, 1024 x 1024 5474 KiB, 1.71 ms 5474 KiB, 2.72 ms 5474 KiB, 1.76 ms
photo.jpg 6381 KiB, 2.00 ms 2890 KiB, 19.3 ms 6381 KiB, 2.29 ms
earth.jpg 8559 KiB, 2.64 ms 5029 KiB, 30.0 ms 8559 KiB, 3.51 ms

The black border at the top of earth.jpg compresses well, so the automatic choice compresses the first rows before it finds that the photo does not, and then sends it raw.

When each encoder started to write the image in one call, on 2026-10-15, it changed as follows. The values are geometric means over the test images of that time, which are no longer in the repository.

Encoder Time Memory allocated Allocations Calls to Write
Kitty 53% less 91% less 98% less about 16 to 1
iTerm 26% less 92% less 57% less 2 to 1
Sixel no change no change no change 2 to 1

To measure on your own machine, run the benchmarks:

go test -run '^$' -bench . -benchtime 10x -count 6 . > new.txt
go run golang.org/x/perf/cmd/benchstat@latest new.txt
Project About
iv Releases A command line image viewer. It draws each image and each frame of an animation with rasterm.
usql Releases A universal command line client for SQL databases. It draws charts and images in the terminal with rasterm.
zuzu Releases Charts and diagrams in pure Go, from a Vega spec, DOT or Mermaid.
okage Releases A pure Go port of resvg, which renders SVG to an image.

Documents

Document About
docs/PLAN.md Each decision, and the open questions
docs/BACKLOG.md Work that is known and not done
docs/DETECTION.md The design of detection by query, and of the API that replaced Available
docs/KITTY_ANIMATION.md The design of Kitty animation
testdata/README.md Where each test image comes from, and its license
CONTRIBUTING.md How to change rasterm

History

rasterm began as a fork of BourgeoisBear/rasterm, by Jason Stewart, which was rewritten in 2023 (D1) and has changed much since. The copyright notice of that project stays in LICENSE.

Documentation

Overview

Package rasterm draws images in a terminal, with the Kitty graphics protocol, the inline images of iTerm2, Sixel, or half blocks of text.

Detect asks the terminal which protocols it supports. Terminal.Encoder returns the encoder for the protocol that Detect selected.

Example
package main

import (
	"context"
	"image"
	"os"

	"github.com/kenshaw/rasterm"
	_ "image/png"
)

func main() {
	term, _, err := rasterm.Detect(context.Background())
	if err != nil {
		panic(err)
	}
	enc := term.Encoder()
	if enc == nil {
		panic(rasterm.ErrTermGraphicsNotAvailable)
	}
	f, err := os.Open("/path/to/image.png")
	if err != nil {
		panic(err)
	}
	defer f.Close()
	img, _, err := image.Decode(f)
	if err != nil {
		panic(err)
	}
	if err := enc.Encode(os.Stdout, img); err != nil {
		panic(err)
	}
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultDetectTimeout = 250 * time.Millisecond

DefaultDetectTimeout is how long Detect waits for the terminal to answer, unless WithTimeout sets it. A terminal on the same host answers in under a millisecond, and one over SSH in one round trip (D23).

View Source
var DefaultJPEGQuality = 93

DefaultJPEGQuality is the default JPEG encode quality.

View Source
var DefaultPNGCompression = png.BestSpeed

DefaultPNGCompression is the default PNG compression level.

png.BestSpeed encodes in less time than png.DefaultCompression, and gives a larger PNG. BenchmarkPNGCompression measures both.

Functions

This section is empty.

Types

type DetectOption added in v0.2.0

type DetectOption func(*detectOptions)

DetectOption is an option of Detect.

func WithGetenv added in v0.2.0

func WithGetenv(getenv func(string) string) DetectOption

WithGetenv is a detect option that reads the environment with getenv. The default is os.Getenv. A program that has its own value for TERM_GRAPHICS can give it here.

func WithInput added in v0.2.0

func WithInput(f *os.File) DetectOption

WithInput is a detect option that reads the answers of the terminal from f. The default is os.Stdin.

func WithOutput added in v0.2.0

func WithOutput(f *os.File) DetectOption

WithOutput is a detect option that writes the queries to f. The default is os.Stdout.

func WithTimeout added in v0.2.0

func WithTimeout(d time.Duration) DetectOption

WithTimeout is a detect option that sets how long Detect waits for the terminal to answer. The default is DefaultDetectTimeout.

type Encoder

type Encoder interface {
	Encode(w io.Writer, img image.Image) error
}

Encoder encodes an image for a terminal.

type EncoderOption added in v0.2.0

type EncoderOption func(*encoderOptions)

EncoderOption is an option of Terminal.Encoder.

func WithNoNewline added in v0.2.0

func WithNoNewline() EncoderOption

WithNoNewline is an encoder option that writes no newline after the image.

func WithZlib added in v0.2.0

func WithZlib(mode ZlibMode) EncoderOption

WithZlib is an encoder option that sets how Kitty compresses raw pixels. The default is ZlibAuto.

type Error

type Error string

Error is an error.

const (
	// ErrTermGraphicsNotAvailable is the error when the terminal has no
	// graphics.
	ErrTermGraphicsNotAvailable Error = "term graphics not available"
	// ErrNonTTY is the error when standard input or standard output is not a
	// terminal.
	ErrNonTTY Error = "non tty"
	// ErrTermResponseTimedOut is the error when the terminal does not answer
	// in time.
	ErrTermResponseTimedOut Error = "term response timed out"
	// ErrUnknownProtocol is the error when text names no protocol.
	ErrUnknownProtocol Error = "unknown protocol"
	// ErrFrameOutOfBounds is the error when a frame of a Kitty animation is
	// not inside the root frame.
	ErrFrameOutOfBounds Error = "frame out of bounds"
	// ErrUnknownFrame is the error when a frame of a Kitty animation names a
	// base frame that does not exist.
	ErrUnknownFrame Error = "unknown frame"
	// ErrInvalidLoops is the error when the number of loops of a Kitty
	// animation is negative or too large.
	ErrInvalidLoops Error = "invalid loops"
	// ErrAnimationEnded is the error when a frame is added to a Kitty
	// animation after End or Delete, or drawn in a Kitty stream after Delete.
	ErrAnimationEnded Error = "animation ended"
	// ErrFrameSize is the error when a picture of a Kitty stream does not
	// have the size of the first one.
	ErrFrameSize Error = "frame size does not match"
)

Errors.

func (Error) Error

func (err Error) Error() string

Error satisfies the [error] interface.

type HalfblockEncoder added in v0.1.18

type HalfblockEncoder struct {
	// NoNewline writes no newline after the image.
	NoNewline bool
}

HalfblockEncoder is a terminal graphics encoder that draws an image as text, with the Unicode half block characters and 24-bit color.

Each cell shows two pixels, one above the other. The character `▀` shows the upper pixel in the foreground color and the lower pixel in the background color. A pixel whose alpha is less than half is transparent, and shows the background of the terminal.

The encoder does not scale. Each column of pixels is one column of cells, and each two rows of pixels are one row of cells, so the caller scales the image to the size of the terminal first. Detect selects it only when TERM_GRAPHICS is halfblock, because the encoder needs nothing from the terminal except 24-bit color, which no query or variable reliably reports (D12). It satisfies the Encoder interface.

func (HalfblockEncoder) Encode added in v0.1.18

func (r HalfblockEncoder) Encode(w io.Writer, img image.Image) error

Encode satisfies the Encoder interface.

The output is built in memory and written to w in one call. A color sequence is written only when the color changes from the cell before it, and each row ends with a reset of the colors.

type ITermEncoder

type ITermEncoder struct {
	// NoNewline writes no newline after the image.
	NoNewline bool
	// Tmux wraps the escape sequence in the DCS passthrough of tmux (D20).
	Tmux bool
}

ITermEncoder encodes an image with the inline images protocol of iTerm2. It satisfies the Encoder interface.

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

func (ITermEncoder) Encode

func (r ITermEncoder) Encode(w io.Writer, img image.Image) error

Encode satisfies the Encoder interface.

If img is a PNGImage or a JPEGImage, its bytes are sent as they are. Otherwise a paletted image is sent as a PNG, and any other image as a JPEG (D5). The output is built in memory and written to w in one call (D9).

type JPEG added in v0.1.18

type JPEG struct {
	image.Image

	// Data is the encoding of Image as a JPEG.
	Data []byte
}

JPEG is an image and its encoding as a JPEG. It satisfies the JPEGImage interface.

Wrap an image only while it is not changed. A scaled or cropped image needs a new JPEG, or no wrapper at all.

func DecodeJPEG added in v0.1.18

func DecodeJPEG(buf []byte) (JPEG, error)

DecodeJPEG decodes buf as a JPEG, and keeps buf as the encoding of the image.

func (JPEG) JPEG added in v0.1.18

func (j JPEG) JPEG() []byte

JPEG satisfies the JPEGImage interface.

func (JPEG) Unwrap added in v0.1.18

func (j JPEG) Unwrap() image.Image

Unwrap returns the image that j wraps.

type JPEGImage added in v0.1.18

type JPEGImage interface {
	image.Image
	JPEG() []byte
}

JPEGImage is the interface for an image that holds its own encoding as a JPEG.

The iTerm encoder sends the bytes that JPEG returns, and does not encode the image again. It checks that the bytes start with the JPEG start of image marker, and that the width and height in the frame header match the bounds of the image. If either check fails, it encodes the image. Kitty and Sixel cannot send a JPEG, and encode the image.

type KittyAnimation added in v0.2.0

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

KittyAnimation streams the frames of one finite animation, such as a GIF, to a terminal with the Kitty graphics protocol. The terminal stores the frames under one image id, and plays them with the delay of each frame (D25).

It is not for a stream with no end, such as video, because the terminal keeps every frame, and nothing tells the program which frame it shows. Draw a stream as one image for each frame instead.

Each method writes its output with one call to Write (D9). A KittyAnimation is not safe for concurrent use.

func (*KittyAnimation) Delete added in v0.2.0

func (a *KittyAnimation) Delete() error

Delete deletes the image and all of its frames from the terminal. No frame can be added after it.

func (*KittyAnimation) End added in v0.2.0

func (a *KittyAnimation) End(loops int) error

End tells the terminal that no more frames come, and plays the frames loops times. 0 plays them forever.

func (*KittyAnimation) Frame added in v0.2.0

func (a *KittyAnimation) Frame(img image.Image, f KittyFrame) (int, error)

Frame adds img as the next frame, and returns its number. The root frame is 1.

If img is a PNGImage, an RGBImage or an RGBAImage, its bytes are sent as they are, as KittyEncoder.Encode does.

func (*KittyAnimation) Frames added in v0.2.0

func (a *KittyAnimation) Frames() int

Frames returns the number of frames, with the root frame.

func (*KittyAnimation) ID added in v0.2.0

func (a *KittyAnimation) ID() uint32

ID returns the image id of the animation.

func (*KittyAnimation) Stop added in v0.2.0

func (a *KittyAnimation) Stop() error

Stop stops the animation on the frame that it shows. Frames can still be added, and KittyAnimation.End plays the animation again.

type KittyEncoder

type KittyEncoder struct {
	// NoNewline writes no newline after the image.
	NoNewline bool
	// Zlib is how raw pixels are compressed. The zero value is [ZlibAuto].
	Zlib ZlibMode
	// Tmux wraps each escape sequence in the DCS passthrough of tmux (D20).
	Tmux bool
	// Cell is the size of a cell in pixels. In tmux, when it is known, the
	// image is drawn with Unicode placeholder cells (D22).
	Cell image.Point
}

KittyEncoder encodes an image with the Kitty graphics protocol. It satisfies the Encoder interface. Terminal.Encoder sets it up for the terminal.

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

func (KittyEncoder) Animate added in v0.2.0

func (r KittyEncoder) Animate(w io.Writer, first image.Image, delay time.Duration) (*KittyAnimation, error)

Animate sends first as the root frame of an animation, shown for delay, and places it at the cursor, or as placeholder cells in tmux. The terminal plays each frame as it arrives, and waits at the last frame for the next one, until KittyAnimation.End.

A terminal that does not support animation shows first, and ignores the frames. Terminal.KittyAnimation is true when the terminal reported that it supports animation, but kitty before 0.50.0 and Ghostty support it and do not report it, so the program decides.

func (KittyEncoder) Encode

func (r KittyEncoder) Encode(w io.Writer, img image.Image) error

Encode satisfies the Encoder interface.

If img is a PNGImage, an RGBImage or an RGBAImage, its bytes are sent as they are, in that order of preference. Otherwise the image is sent as a PNG. Raw pixels are compressed with zlib as KittyEncoder.Zlib says. The output is built in memory and written to w in one call (D9).

func (KittyEncoder) Stream added in v0.3.0

func (r KittyEncoder) Stream(w io.Writer, first image.Image) (*KittyStream, error)

Stream sends first as frame 1 of a Kitty image, and places it at the cursor, or as placeholder cells in tmux. It stops the animation of the image, so that the terminal does not play it.

The image of each later KittyStream.Draw must have the size of first. PNGImage, RGBImage and RGBAImage are sent as they are, as KittyEncoder.Encode does.

type KittyFrame added in v0.2.0

type KittyFrame struct {
	// Delay is how long the frame is shown. A Delay under 0 makes a frame
	// that is never shown, and that is a base for later frames. A Delay from
	// 0 to 1 ms is 1 ms, because the protocol reads 0 as its default of 40
	// ms.
	Delay time.Duration
	// At is where the top left of the image goes, relative to the top left
	// of the root frame. The image covers At to At plus its size, which
	// must be inside the root frame.
	At image.Point
	// Base is the frame that gives the pixels that the image does not cover,
	// numbered from 1, as [KittyAnimation.Frame] returns them. 0 is the frame
	// before. -1 is the Background color.
	Base int
	// Background is the color of the pixels that the image does not cover,
	// when Base is -1. nil is transparent.
	Background color.Color
	// Replace replaces the pixels under the image. By default, the image is
	// blended over them.
	Replace bool
}

KittyFrame describes how a frame of a KittyAnimation is drawn.

type KittyStream added in v0.3.0

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

KittyStream shows a sequence of pictures of one size as one Kitty image, with the terminal storing two frames however many pictures come. The program keeps the time, and calls KittyStream.Draw when the next picture is due. It suits an animation of any length, such as video (D29).

The animation of the image stays stopped, so the terminal never changes the picture by itself. Draw writes the picture into the frame that is not shown, and then shows that frame, so the picture changes at once and does not flicker.

Each method writes its output with one call to Write (D9). A KittyStream is not safe for concurrent use.

func (*KittyStream) Delete added in v0.3.0

func (s *KittyStream) Delete() error

Delete deletes the image and its frames from the terminal. No picture can be drawn after it.

func (*KittyStream) Draw added in v0.3.0

func (s *KittyStream) Draw(img image.Image) error

Draw shows img in place of the picture that shows. It writes img into the frame that is not shown, and then shows that frame, in one call to Write. It returns ErrFrameSize when img does not have the size of the first image.

func (*KittyStream) ID added in v0.3.0

func (s *KittyStream) ID() uint32

ID returns the image id of the stream.

type PNG added in v0.1.18

type PNG struct {
	image.Image

	// Data is the encoding of Image as a PNG.
	Data []byte
}

PNG is an image and its encoding as a PNG. It satisfies the PNGImage interface.

Wrap an image only while it is not changed. A scaled or cropped image needs a new PNG, or no wrapper at all.

func DecodePNG added in v0.1.18

func DecodePNG(buf []byte) (PNG, error)

DecodePNG decodes buf as a PNG, and keeps buf as the encoding of the image.

func (PNG) PNG added in v0.1.18

func (p PNG) PNG() []byte

PNG satisfies the PNGImage interface.

func (PNG) Unwrap added in v0.1.18

func (p PNG) Unwrap() image.Image

Unwrap returns the image that p wraps.

type PNGImage added in v0.1.18

type PNGImage interface {
	image.Image
	PNG() []byte
}

PNGImage is the interface for an image that holds its own encoding as a PNG.

The Kitty and iTerm encoders send the bytes that PNG returns, and do not encode the image again. They check that the bytes start with the PNG signature and that the width and height in the header match the bounds of the image. If either check fails, they encode the image. Sixel cannot send a PNG, and encodes the image.

type Protocol added in v0.2.0

type Protocol uint8

Protocol is a terminal graphics protocol.

const (
	// None is no graphics.
	None Protocol = iota
	// Kitty is the Kitty graphics protocol.
	Kitty
	// ITerm is the inline images protocol of iTerm2.
	ITerm
	// Sixel is the Sixel protocol.
	Sixel
	// Halfblock draws an image as text, with half blocks and 24-bit color. It
	// is not a protocol of the terminal, so [Detect] selects it only when
	// TERM_GRAPHICS asks for it (D12).
	Halfblock
)

Terminal graphics protocols.

func ParseProtocol added in v0.2.0

func ParseProtocol(s string) (p Protocol, ok bool)

ParseProtocol returns the protocol that s names, as Detect reads TERM_GRAPHICS. Case, the characters that are not letters, and a final s do not matter, so "Half-Blocks" is Halfblock and "iTerm2" is ITerm. ok is false when s names no protocol, as the empty string does.

func (Protocol) MarshalText added in v0.2.0

func (p Protocol) MarshalText() ([]byte, error)

MarshalText satisfies the encoding.TextMarshaler interface.

func (Protocol) String added in v0.2.0

func (p Protocol) String() string

String satisfies the fmt.Stringer interface.

func (*Protocol) UnmarshalText added in v0.2.0

func (p *Protocol) UnmarshalText(buf []byte) error

UnmarshalText satisfies the encoding.TextUnmarshaler interface. It reads the text as ParseProtocol does. Empty text is None.

type RGB added in v0.1.18

type RGB struct {
	image.Image

	// Data is the pixels of Image, as [RGBImage] describes them.
	Data []byte
}

RGB is an image and its pixels as packed red, green and blue. It satisfies the RGBImage interface.

Wrap an image only while it is not changed. A scaled or cropped image needs new pixels, or no wrapper at all.

func (RGB) RGB added in v0.1.18

func (r RGB) RGB() []byte

RGB satisfies the RGBImage interface.

func (RGB) Unwrap added in v0.1.18

func (r RGB) Unwrap() image.Image

Unwrap returns the image that r wraps.

type RGBA added in v0.1.18

type RGBA struct {
	image.Image

	// Data is the pixels of Image, as [RGBAImage] describes them.
	Data []byte
}

RGBA is an image and its pixels as packed red, green, blue and alpha. It satisfies the RGBAImage interface.

Wrap an image only while it is not changed. A scaled or cropped image needs new pixels, or no wrapper at all.

func (RGBA) RGBA added in v0.1.18

func (r RGBA) RGBA() []byte

RGBA satisfies the RGBAImage interface.

func (RGBA) Unwrap added in v0.1.18

func (r RGBA) Unwrap() image.Image

Unwrap returns the image that r wraps.

type RGBAImage added in v0.1.18

type RGBAImage interface {
	image.Image
	RGBA() []byte
}

RGBAImage is the interface for an image that holds its own pixels as packed 8-bit red, green, blue and alpha, 4 bytes for each pixel, row by row from the top left, with no padding at the end of a row. The alpha is not premultiplied, as in image.NRGBA.

The Kitty encoder sends the bytes that RGBA returns, and does not encode the image. It checks that their length is 4 times the number of pixels in the bounds of the image. If the check fails, it encodes the image. iTerm, Sixel and half blocks cannot send raw pixels, and encode the image.

type RGBImage added in v0.1.18

type RGBImage interface {
	image.Image
	RGB() []byte
}

RGBImage is the interface for an image that holds its own pixels as packed 8-bit red, green and blue, 3 bytes for each pixel, row by row from the top left, with no padding at the end of a row.

The Kitty encoder sends the bytes that RGB returns, and does not encode the image. It checks that their length is 3 times the number of pixels in the bounds of the image. If the check fails, it encodes the image. iTerm, Sixel and half blocks cannot send raw pixels, and encode the image.

type SixelEncoder

type SixelEncoder struct {
	// NoNewline writes no newline after the image.
	NoNewline bool
}

SixelEncoder encodes an image with Sixel. It satisfies the Encoder interface.

See: https://saitoha.github.io/libsixel/

func (SixelEncoder) Encode

func (r SixelEncoder) Encode(w io.Writer, img image.Image) error

Encode satisfies the Encoder interface.

The output and the newline are built in memory and written to w in one call (D9). go-sixel before v0.0.14 made a call to Write for each few bytes when w was not an os.File.

type Source added in v0.2.0

type Source uint8

Source is where the protocol of a Terminal comes from.

const (
	// SourceNone is no source. Nothing was found.
	SourceNone Source = iota
	// SourceForced is TERM_GRAPHICS.
	SourceForced
	// SourceTmux is the answer of tmux about the terminal of its client.
	SourceTmux
	// SourceQuery is the answers of the terminal to the queries of [Detect].
	SourceQuery
	// SourceEnv is the variables of the environment other than
	// TERM_GRAPHICS.
	SourceEnv
)

Sources.

func (Source) String added in v0.2.0

func (s Source) String() string

String satisfies the fmt.Stringer interface.

type Terminal added in v0.2.0

type Terminal struct {
	// Protocol is the protocol that the encoder uses. [None] is no graphics.
	Protocol Protocol
	// Source is where Protocol comes from.
	Source Source
	// Protocols is each protocol that the terminal reported, or that its name
	// tells, in the order of preference: Kitty, iTerm, Sixel. It is empty
	// when TERM_GRAPHICS selects the protocol.
	Protocols []Protocol
	// Name and Version are the name and the version that the terminal
	// reports, from XTVERSION, or from tmux.
	Name, Version string
	// Cell is the size of a cell in pixels. It is zero when it is not known.
	Cell image.Point
	// SixelColors is the number of color registers of Sixel, or 0 when it is
	// not known.
	SixelColors int
	// KittyAnimation is true when the terminal reported that it can play a
	// Kitty animation. False means that it did not report it: kitty before
	// 0.50.0 and Ghostty play animations and do not report it.
	KittyAnimation bool
	// Tmux is true when the program runs in tmux.
	Tmux bool
	// Passthrough is true when the allow-passthrough option of tmux is on.
	Passthrough bool
}

Terminal is what Detect found about a terminal. A Terminal with only Protocol set is valid, for a program that knows the protocol, as when it writes to a file.

func Detect added in v0.2.0

func Detect(ctx context.Context, opts ...DetectOption) (Terminal, []byte, error)

Detect finds the terminal graphics protocol of the terminal, in this order (D26, D27):

  1. If TERM_GRAPHICS names a protocol, or none, Detect uses it, and asks the terminal nothing. In tmux, it still asks tmux for the size of a cell, which reads no input.
  2. In tmux, Detect asks tmux for the terminal of its client, and finds the protocols by the name of the terminal. It does not read the other variables of the environment, because they can belong to another terminal (D21).
  3. If the input and the output are terminals, Detect sends its queries in one write, and reads the answers until the answer to DA1, which every terminal sends last. It waits up to the timeout.
  4. If the terminal cannot be asked, or does not answer, Detect reads the other variables of the environment, such as TERM and TERM_PROGRAM.

When the terminal has more than one protocol, Detect selects Kitty, then iTerm, then Sixel.

While Detect waits for the answers, it reads the input. It returns the keys that it read and that are not part of an answer, in the order that the user typed them. A program that reads the input after Detect must use them as its first input (D24).

A terminal that does not answer is not an error. The error is from ctx, or from a failure to read or to write.

func (Terminal) Encoder added in v0.2.0

func (t Terminal) Encoder(opts ...EncoderOption) Encoder

Encoder returns the encoder for t.Protocol, set up for t. In tmux, Kitty and iTerm wrap their output in the passthrough of tmux (D20), and Kitty draws placeholder cells when t.Cell is known (D22). It returns nil when t.Protocol is None.

func (Terminal) Has added in v0.2.0

func (t Terminal) Has(p Protocol) bool

Has returns true when p is in t.Protocols.

type ZlibMode added in v0.1.19

type ZlibMode uint8

ZlibMode is how the Kitty encoder compresses the raw pixels of an RGBImage or an RGBAImage. It never compresses a PNG, which is compressed already.

const (
	// ZlibAuto compresses raw pixels when they compress well. Pixels under
	// [zlibMin] bytes are sent raw. For more, the encoder starts one zlib
	// stream, and after each [zlibProbe] bytes of input, it compares all the
	// output so far with all the input so far. At the first check where the
	// output is not less than [zlibRatio] of the input, it drops the stream
	// and sends the pixels raw. The stream is never flushed, so a stream that
	// is sent is the same as one stream of all the pixels. Flat and rendered
	// images compress, and photos stay raw.
	ZlibAuto ZlibMode = iota
	// ZlibAlways compresses raw pixels of any size.
	ZlibAlways
	// ZlibNever sends raw pixels as they are.
	ZlibNever
)

Zlib modes.

Jump to

Keyboard shortcuts

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