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)
}
}
Output:
Index ¶
- Variables
- type DetectOption
- type Encoder
- type EncoderOption
- type Error
- type HalfblockEncoder
- type ITermEncoder
- type JPEG
- type JPEGImage
- type KittyAnimation
- type KittyEncoder
- type KittyFrame
- type KittyStream
- type PNG
- type PNGImage
- type Protocol
- type RGB
- type RGBA
- type RGBAImage
- type RGBImage
- type SixelEncoder
- type Source
- type Terminal
- type ZlibMode
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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).
var DefaultJPEGQuality = 93
DefaultJPEGQuality is the default JPEG encode quality.
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 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.
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.
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.
type JPEG ¶ added in v0.1.18
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
DecodeJPEG decodes buf as a JPEG, and keeps buf as the encoding of the image.
type JPEGImage ¶ added in v0.1.18
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 ¶
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
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.
type PNGImage ¶ added in v0.1.18
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
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
MarshalText satisfies the encoding.TextMarshaler interface.
func (Protocol) String ¶ added in v0.2.0
String satisfies the fmt.Stringer interface.
func (*Protocol) UnmarshalText ¶ added in v0.2.0
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.
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.
type RGBAImage ¶ added in v0.1.18
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
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.
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
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
Detect finds the terminal graphics protocol of the terminal, in this order (D26, D27):
- 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.
- 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).
- 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.
- 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.
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.