termimg

package module
v0.1.24 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2025 License: MIT Imports: 26 Imported by: 5

README

Fallback logo

Modern terminal image library for Go

Features

Universal Protocol Support

  • 🐱 Kitty - Fast graphics with virtual images, z-index, compression
  • 🎨 Sixel - High-quality with palette optimization and dithering
  • 🍎 iTerm2 - Native inline images with ECH clearing
  • 🧱 Halfblocks - Unicode fallback (works everywhere)

Rich Image Processing

  • Smart scaling (fit, fill, stretch, none)
  • Advanced dithering (Stucki, Floyd-Steinberg)
  • Quality vs speed control
  • TUI framework integration (Bubbletea)

Advanced Features

  • Automatic protocol detection with fallbacks
  • Terminal font size detection via CSI queries
  • Tmux passthrough support
  • Optimized font size caching

[!WARNING] Kitty Unicode placeholder/relative placement features are currently under construction and not recommended for production use.

Supported Formats

  • PNG, JPEG, GIF
  • Any format supported by Go's image package
  • WebP support planned

Installation

go get github.com/blacktop/go-termimg

Getting Started

Basic Usage

package main

import "github.com/blacktop/go-termimg"

func main() {
    // Simple one-liner
    termimg.PrintFile("image.png")

    // Or with control
    img, _ := termimg.Open("image.png")
    img.Width(50).Height(25).Print()
}

API

// Auto-detect best protocol and render
rendered, err := termimg.Open("image.png").
    Width(80).
    Height(40).
    Scale(termimg.ScaleFit).
    Render()

Protocol-Specific Features

// Kitty with virtual images and z-index (experimental)
termimg.Open("overlay.png").
    Protocol(termimg.Kitty).
    Virtual(true).
    ZIndex(5).
    Print()

// Sixel with dithering
termimg.Open("photo.jpg").
    Protocol(termimg.Sixel).
    Dither(true).
    DitherMode(termimg.DitherStucki).
    Print()

TUI Integration

import tea "github.com/charmbracelet/bubbletea"

type model struct {
    widget *termimg.ImageWidget
}

func (m model) View() string {
    rendered, _ := m.widget.Render()
    return rendered
}

func main() {
    img := termimg.NewImageWidgetFromFile("image.png")
    img.SetSize(50, 25).SetProtocol(termimg.Auto)

    p := tea.NewProgram(model{widget: img})
    p.Run()
}

Command Line Tools

imgcat - Terminal Image Viewer

Install:

go install github.com/blacktop/go-termimg/cmd/imgcat@latest

Basic usage:

# Display an image
imgcat image.png

# With specific protocol and size
imgcat -W 100 -H 50 --protocol kitty image.png

# Virtual placement with positioning (Kitty only)
imgcat --virtual --x 10 --y 5 --z-index 3 image.png

# Test terminal capabilities
imgcat --detect

# Show Unicode test grid
imgcat --test-grid

Advanced options:

# Compression and PNG mode (Kitty)
imgcat --compression --png image.png

# Dithering
imgcat --dither photo.jpg

# Scale modes
imgcat --scale fit image.png    # Fit within terminal
imgcat --scale fill image.png   # Fill terminal, crop if needed
imgcat --scale none image.png   # No scaling

Install and run:

go install github.com/blacktop/go-termimg/cmd/gallery@latest
gallery

Interactive features:

  • File navigation (↑/↓ or k/j keys, page up/down, home/end)
  • Virtual mode toggle (v key - Kitty only)
  • Grid view toggle (g key)
  • Auto-detection of best terminal protocol

Protocol Detection

// Auto-detect best available protocol
protocol := termimg.DetectProtocol()

// Check specific protocol support
if termimg.KittySupported() {
    // Use Kitty features
}

// Get detailed terminal features
features := termimg.QueryTerminalFeatures()
fmt.Printf("Font size: %dx%d\n", features.FontWidth, features.FontHeight)

Performance

Performance benchmarks for different protocols:

  • Halfblocks: ~800µs (fastest, works everywhere)
  • Kitty: ~2.5ms (efficient, modern terminals)
  • iTerm2: ~2.5ms (fast, macOS)
  • Sixel: ~90ms (high quality, slower)

Font size detection is cached to avoid repeated terminal queries.

Running Examples

The cmd/ directory contains several example programs:

# Image viewer
cd cmd/imgcat/
go run main.go ../../test/image.png --id 123 --place --x 5 --y 10

# Interactive gallery
cd cmd/gallery/
go run main.go

# Terminal info
cd cmd/terminfo/
go run main.go

License

MIT Copyright (c) 2024-2025 blacktop

Documentation

Overview

Package termimg provides functionality to render images in terminal emulators that support various image protocols including Kitty, Sixel, iTerm2, and fallback Unicode halfblocks.

This package automatically detects which protocol is supported by the current terminal and renders images accordingly. It supports all image formats that Go's standard image package supports (PNG, JPEG, GIF, etc.).

Main features:

  • Automatic detection of supported terminal image protocols
  • Support for Kitty, Sixel, iTerm2, and Unicode halfblock protocols
  • Tmux passthrough support for graphics protocols in terminal multiplexers
  • Fluent API for easy configuration
  • Advanced features like scaling, dithering, z-index, virtual images
  • TUI framework integration (Bubbletea)
  • High performance with protocol-specific optimizations

Basic Usage:

// Simple one-liner
termimg.PrintFile("image.png")

// With configuration
img, err := termimg.Open("image.png")
if err != nil {
    log.Fatal(err)
}

err = img.Width(80).Height(40).Print()
if err != nil {
    log.Fatal(err)
}

Fluent API:

// Chain configuration methods
rendered, err := termimg.Open("image.png").
    Width(100).
    Height(50).
    Scale(termimg.ScaleFit).
    Protocol(termimg.Kitty).
    Virtual(true).
    ZIndex(5).
    Render()

Protocol Detection:

// Detect the best available protocol
protocol := termimg.DetectProtocol()
switch protocol {
case termimg.Kitty:
    fmt.Println("Kitty graphics protocol supported")
case termimg.Sixel:
    fmt.Println("Sixel protocol supported")
case termimg.ITerm2:
    fmt.Println("iTerm2 protocol supported")
case termimg.Halfblocks:
    fmt.Println("Unicode halfblocks fallback")
default:
    fmt.Println("No supported protocol detected")
}

// Check specific protocol support
if termimg.KittySupported() {
    fmt.Println("Kitty protocol available")
}
if termimg.SixelSupported() {
    fmt.Println("Sixel protocol available")
}
if termimg.ITerm2Supported() {
    fmt.Println("iTerm2 protocol available")
}

// Get all supported protocols
protocols := termimg.DetermineProtocols()
fmt.Printf("Available protocols: %v\n", protocols)

Tmux Support:

// Force tmux mode for testing
termimg.ForceTmux(true)

// Graphics protocols automatically work in tmux via passthrough
img, _ := termimg.Open("image.png")
img.Print() // Automatically uses tmux passthrough when needed

TUI Integration:

widget := termimg.NewImageWidget(termimg.New(img))
widget.SetSize(50, 25).SetProtocol(termimg.Auto)
rendered, _ := widget.Render()

This package is designed to make it easy to add modern image rendering capabilities to terminal-based Go applications with support for the latest terminal features.

Index

Constants

View Source
const (
	// Query timeouts
	QueryTimeout = 100 * time.Millisecond

	// Buffer sizes
	QueryBufferSize = 256

	// Default font dimensions (fallback values)
	DefaultFontWidth    = 7
	DefaultFontHeight   = 14
	AppleTerminalWidth  = 7
	AppleTerminalHeight = 16
	ITermWidth          = 7
	ITermHeight         = 14
	GhosttyWidth        = 9
	GhosttyHeight       = 18
	WezTermWidth        = 8
	WezTermHeight       = 16
	MinttyWidth         = 7
	MinttyHeight        = 14
	RioWidth            = 8
	RioHeight           = 16
	XtermWidth          = 6
	XtermHeight         = 13
	MltermWidth         = 7
	MltermHeight        = 14
	FootWidth           = 8
	FootHeight          = 16
	VT340Width          = 9
	VT340Height         = 15
)

Constants for terminal detection

View Source
const (
	DATA_RGBA_32_BIT = "f=32" // default
	DATA_RGBA_24_BIT = "f=24"
	DATA_PNG         = "f=100"

	ACTION_TRANSFER  = "a=T"
	ACTION_DELETE    = "a=d"
	ACTION_QUERY     = "a=q"
	ACTION_ANIMATE   = "a=a"
	ACTION_PLACEMENT = "a=p"

	COMPRESS_ZLIB = "0=z"

	TRANSFER_DIRECT = "t=d"
	TRANSFER_FILE   = "t=f"
	TRANSFER_TEMP   = "t=t"
	TRANSFER_SHARED = "t=s"

	// More flags for continuation
	MORE_CHUNKS = "m=1" // More chunks follow
	FINAL_CHUNK = "m=0" // Final chunk (default)

	// Virtual placement
	VIRTUAL_PLACEMENT = "U=1" // Create virtual placement

	DELETE_WITH_ID          = "d=i"
	DELETE_NEWEST           = "d=n"
	DELETE_AT_CURSOR        = "d=c"
	DELETE_ANIMATION_FRAMES = "d=a"

	SUPPRESS_OK  = "q=1"
	SUPPRESS_ERR = "q=2"
)
View Source
const (
	CHUNK_SIZE        = 4096               // 4KB
	BASE64_CHUNK_SIZE = 3 * CHUNK_SIZE / 4 // Base64 encoding expands data size
)
View Source
const (
	DefaultCacheSize = 100 // Maximum number of cached resized images
)

Constants for image resizing

View Source
const (
	DefaultEncodingWorkers = 4 // Number of parallel workers for encoding
)

Constants for base64 encoding

View Source
const ITERM2_CHUNK_SIZE = 0x40000 // 256KB chunk size for iTerm2 multipart images
View Source
const PLACEHOLDER_CHAR = "\U0010EEEE"

Unicode placeholder character - using U+10EEEE as suggested by Kitty maintainer

Variables

View Source
var ErrEmptyResponse = fmt.Errorf("empty response")

Functions

func Base64Encode added in v0.1.20

func Base64Encode(src []byte) string

Base64Encode provides faster base64 encoding with buffer reuse

func ChunkedBase64Encode added in v0.1.20

func ChunkedBase64Encode(data []byte, chunkSize int) []string

ChunkedBase64Encode processes data in chunks with optimized encoding

func ClearAll added in v0.1.20

func ClearAll() error

ClearAll sends a command to clear all images drawn by the Kitty protocol. This is a no-op for other protocols.

func ClearAllString added in v0.1.22

func ClearAllString() string

ClearAllString returns a command to clear all images drawn by the Kitty protocol as a string.

func ClearDetectionLog added in v0.1.20

func ClearDetectionLog()

ClearDetectionLog clears the detection log

func ClearEnvironmentCache added in v0.1.20

func ClearEnvironmentCache()

ClearEnvironmentCache clears cached environment checks (for testing)

func ClearFeatureCache added in v0.1.20

func ClearFeatureCache()

ClearFeatureCache clears the cached terminal features (mainly for testing)

func ClearResizeCache added in v0.1.20

func ClearResizeCache()

ClearResizeCache clears the resize cache to free memory

func CreatePlaceholder added in v0.1.20

func CreatePlaceholder(row, column uint16, id_extra byte) string

CreatePlaceholder generates a Unicode placeholder for the given image position placeholder_char + row_diacritic + column_diacritic + id_extra_diacritic

func CreatePlaceholderArea added in v0.1.20

func CreatePlaceholderArea(imageID uint32, rows, columns uint16) [][]string

CreatePlaceholderArea generates a grid of placeholders for an image

func CropImageCenter added in v0.1.20

func CropImageCenter(img image.Image, targetWidth, targetHeight int) image.Image

CropImageCenter crops an image to target dimensions from the center

func DetectITerm2FromEnvironment added in v0.1.20

func DetectITerm2FromEnvironment() bool

DetectITerm2FromEnvironment checks environment variables for iTerm2 indicators

func DetectKittyFromEnvironment added in v0.1.20

func DetectKittyFromEnvironment() bool

DetectKittyFromEnvironment checks environment variables for Kitty indicators

func DetectSixelFromEnvironment added in v0.1.20

func DetectSixelFromEnvironment() bool

DetectSixelFromEnvironment checks environment variables for Sixel indicators

func DitherImage added in v0.1.20

func DitherImage(img image.Image, palette color.Palette) image.Image

DitherImage dithers an image using the given palette.

func FastResize added in v0.1.20

func FastResize(img image.Image, width, height uint) image.Image

FastResize skips quality for speed - use for previews/thumbnails

func ForceTmux added in v0.1.20

func ForceTmux(force bool)

ForceTmux sets the global flag to force tmux passthrough mode

func GetITerm2CellSize added in v0.1.20

func GetITerm2CellSize() (float64, float64, float64, bool)

GetITerm2CellSize uses OSC 1337 ReportCellSize to get font dimensions Returns width, height, scale, and whether the query succeeded

func GetITerm2Variable added in v0.1.20

func GetITerm2Variable(variable string) (string, bool)

func HalfblocksSupported added in v0.1.20

func HalfblocksSupported() bool

HalfblocksSupported checks if halfblocks rendering is supported (always true as fallback)

func ITerm2Supported added in v0.1.20

func ITerm2Supported() bool

ITerm2Supported checks if iTerm2 inline images protocol are supported in the current environment

func IsTmuxForced added in v0.1.20

func IsTmuxForced() bool

IsTmuxForced returns whether tmux mode is being forced

func IsTmuxPassthroughEnabled added in v0.1.20

func IsTmuxPassthroughEnabled() bool

IsTmuxPassthroughEnabled returns whether tmux passthrough was successfully enabled

func KittySupported added in v0.1.20

func KittySupported() bool

KittySupported checks if the current terminal supports Kitty graphics protocol

func MoveCursorUpAndToBeginning added in v0.1.20

func MoveCursorUpAndToBeginning(n int) string

MoveCursorUpAndToBeginning moves the cursor up n lines and to the beginning of the line.

func ParallelBase64Encode added in v0.1.20

func ParallelBase64Encode(data []byte, chunkSize int) []string

ParallelBase64Encode processes large data with multiple goroutines

func ParallelProtocolDetection added in v0.1.20

func ParallelProtocolDetection() (kitty, sixel, iterm2 bool)

ParallelProtocolDetection performs all protocol detections concurrently

func Print added in v0.1.20

func Print(img image.Image) error

Print prints an image with default settings

func PrintFile added in v0.1.20

func PrintFile(path string) error

PrintFile prints an image file with default settings

func Render added in v0.1.20

func Render(img image.Image) (string, error)

Render renders an image with default settings

func RenderFile added in v0.1.20

func RenderFile(path string) (string, error)

RenderFile renders an image file with default settings

func RenderPlaceholderAreaWithImageID added in v0.1.20

func RenderPlaceholderAreaWithImageID(area [][]string, imageID uint32) string

RenderPlaceholderAreaWithImageID converts a placeholder area to a string with proper positioning Each placeholder is positioned at the current cursor location plus row/column offsets

func ResizeImage added in v0.1.20

func ResizeImage(img image.Image, width, height uint, path string) image.Image

ResizeImage provides faster image resizing with caching and optimizations

func SixelSupported added in v0.1.20

func SixelSupported() bool

SixelSupported checks if Sixel protocol is supported in the current environment

func SupportedProtocols added in v0.1.18

func SupportedProtocols() string

Types

type AnimationOptions added in v0.1.20

type AnimationOptions struct {
	DelayMs  int      // Delay between frames in milliseconds
	Loops    int      // Number of animation loops (0 = infinite)
	ImageIDs []string // List of image IDs to animate between
}

AnimationOptions contains parameters for Kitty image animation

type AsyncRenderWorker added in v0.1.22

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

AsyncRenderWorker renders images on background goroutines so callers can keep UI loops responsive. When the queue is full, newer requests replace older ones to always prioritise the latest viewport.

func NewAsyncRenderWorker added in v0.1.22

func NewAsyncRenderWorker(img *Image, opts AsyncWorkerOptions) *AsyncRenderWorker

NewAsyncRenderWorker starts a worker for the provided image.

func (*AsyncRenderWorker) Close added in v0.1.22

func (w *AsyncRenderWorker) Close()

Close stops all worker goroutines.

func (*AsyncRenderWorker) Schedule added in v0.1.22

func (w *AsyncRenderWorker) Schedule(req renderRequest)

Schedule enqueues a render request. If an identical request is already the most recent, it is skipped. When the queue is full the oldest pending request is dropped to keep the pipeline current.

func (*AsyncRenderWorker) TryLatest added in v0.1.22

func (w *AsyncRenderWorker) TryLatest() (RenderOutcome, bool)

TryLatest returns the newest completed render, if any. It drains the result buffer to always surface the most recent output.

type AsyncWorkerOptions added in v0.1.22

type AsyncWorkerOptions struct {
	Workers int // number of goroutines to use; defaults to 1
	Queue   int // size of the request/result buffers; defaults to 1 (latest wins)
}

AsyncWorkerOptions configures the render worker.

type ClearOptions added in v0.1.20

type ClearOptions struct {
	ImageID string
	All     bool
}

ClearOptions contains options for clearing an image

type DetectionResult added in v0.1.20

type DetectionResult struct {
	Protocol string
	Success  bool
	Error    error
	Fallback bool
}

DetectionResult contains the result of protocol detection with error info

func GetDetectionLog added in v0.1.20

func GetDetectionLog() []DetectionResult

GetDetectionLog returns the detection log for debugging

type DitherMode added in v0.1.20

type DitherMode int

DitherMode defines dithering algorithms for color reduction

const (
	// DitherNone performs no dithering
	DitherNone DitherMode = iota
	// DitherFloydSteinberg uses Floyd-Steinberg dithering
	DitherFloydSteinberg
)

type HalfblocksRenderer added in v0.1.20

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

HalfblocksRenderer implements the Renderer interface using mosaic

func (*HalfblocksRenderer) Clear added in v0.1.20

func (r *HalfblocksRenderer) Clear(opts ClearOptions) error

Clear removes the image from the terminal

func (*HalfblocksRenderer) Print added in v0.1.20

func (r *HalfblocksRenderer) Print(img image.Image, opts RenderOptions) error

Print outputs the image directly to stdout

func (*HalfblocksRenderer) Protocol added in v0.1.20

func (r *HalfblocksRenderer) Protocol() Protocol

Protocol returns the protocol type

func (*HalfblocksRenderer) Render added in v0.1.20

func (r *HalfblocksRenderer) Render(img image.Image, opts RenderOptions) (string, error)

Render generates the escape sequence for displaying the image

type ITerm2Options added in v0.1.20

type ITerm2Options struct {
	PreserveAspectRatio bool
	Inline              bool
}

ITerm2Options contains iTerm2-specific rendering options

type ITerm2Renderer added in v0.1.20

type ITerm2Renderer struct{}

ITerm2Renderer implements the Renderer interface for iTerm2 inline images protocol

func (*ITerm2Renderer) Clear added in v0.1.20

func (r *ITerm2Renderer) Clear(opts ClearOptions) error

Clear removes the image from the terminal

func (*ITerm2Renderer) Print added in v0.1.20

func (r *ITerm2Renderer) Print(img image.Image, opts RenderOptions) error

Print outputs the image directly to stdout

func (*ITerm2Renderer) Protocol added in v0.1.20

func (r *ITerm2Renderer) Protocol() Protocol

Protocol returns the protocol type

func (*ITerm2Renderer) Render added in v0.1.20

func (r *ITerm2Renderer) Render(img image.Image, opts RenderOptions) (string, error)

Render generates the escape sequence for displaying the image

type Image added in v0.1.20

type Image struct {
	Source image.Image
	Bounds image.Rectangle
	// contains filtered or unexported fields
}

Image represents a terminal image with a fluent API for configuration

func From added in v0.1.20

func From(r io.Reader) (*Image, error)

From creates a new Image from an io.Reader

func New added in v0.1.20

func New(img image.Image) *Image

New creates a new Image from an image.Image

func Open

func Open(path string) (*Image, error)

Open creates a new Image from a file path

func (*Image) Clear added in v0.1.20

func (i *Image) Clear(opts ClearOptions) error

Clear removes the image from the terminal

func (*Image) Compression added in v0.1.20

func (i *Image) Compression(c bool) *Image

Compression enables zlib compression for protocols that support it

func (*Image) Dither added in v0.1.20

func (i *Image) Dither(d bool) *Image

Dither enables dithering with the default algorithm

func (*Image) DitherMode added in v0.1.20

func (i *Image) DitherMode(mode DitherMode) *Image

DitherMode sets the dithering algorithm

func (*Image) GetRenderer added in v0.1.20

func (i *Image) GetRenderer() (Renderer, error)

GetRenderer returns the renderer associated with this image

func (*Image) GetSource added in v0.1.20

func (i *Image) GetSource() (image.Image, error)

GetSource returns the underlying image.Image

func (*Image) Height added in v0.1.20

func (i *Image) Height(h int) *Image

Height sets the target height in character cells

func (*Image) HeightPixels added in v0.1.20

func (i *Image) HeightPixels(h int) *Image

HeightPixels sets the target height in pixels

func (*Image) ImageNum added in v0.1.20

func (i *Image) ImageNum(num int) *Image

ImageNum sets the image number for Kitty protocol

func (*Image) PNG added in v0.1.20

func (i *Image) PNG(p bool) *Image

PNG enables PNG data transfer for protocols that support it

func (*Image) Print added in v0.1.20

func (i *Image) Print() error

Print outputs the image to stdout

func (*Image) Protocol added in v0.1.20

func (i *Image) Protocol(p Protocol) *Image

Protocol sets the rendering protocol to use

func (*Image) Render added in v0.1.20

func (i *Image) Render() (string, error)

Render generates the escape sequence string for the image

func (*Image) Scale added in v0.1.20

func (i *Image) Scale(mode ScaleMode) *Image

Scale sets the scaling mode

func (*Image) Size added in v0.1.20

func (i *Image) Size(w, h int) *Image

Size sets both width and height in character cells

func (*Image) SizePixels added in v0.1.20

func (i *Image) SizePixels(w, h int) *Image

SizePixels sets both width and height in pixels

func (*Image) TempFile added in v0.1.20

func (i *Image) TempFile(t bool) *Image

TempFile enables temporary file transfer for protocols that support it

func (*Image) Virtual added in v0.1.20

func (i *Image) Virtual(v bool) *Image

Virtual enables virtual image mode (for Kitty protocol)

func (*Image) Width added in v0.1.20

func (i *Image) Width(w int) *Image

Width sets the target width in character cells

func (*Image) WidthPixels added in v0.1.20

func (i *Image) WidthPixels(w int) *Image

WidthPixels sets the target width in pixels

func (*Image) ZIndex added in v0.1.20

func (i *Image) ZIndex(z int) *Image

ZIndex sets the z-index for protocols that support layering

type ImageGallery added in v0.1.20

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

ImageGallery represents a collection of images for gallery display

func NewImageGallery added in v0.1.20

func NewImageGallery(columns int) *ImageGallery

NewImageGallery creates a new image gallery

func (*ImageGallery) AddImage added in v0.1.20

func (g *ImageGallery) AddImage(img *Image) *ImageGallery

AddImage adds an image to the gallery

func (*ImageGallery) AddImageFromFile added in v0.1.20

func (g *ImageGallery) AddImageFromFile(path string) error

AddImageFromFile adds an image from a file path to the gallery

func (*ImageGallery) Render added in v0.1.20

func (g *ImageGallery) Render() (string, error)

Render renders the entire gallery as a grid

func (*ImageGallery) SetImageSize added in v0.1.20

func (g *ImageGallery) SetImageSize(width, height int) *ImageGallery

SetImageSize sets the size for all images in the gallery

func (*ImageGallery) SetProtocol added in v0.1.20

func (g *ImageGallery) SetProtocol(protocol Protocol) *ImageGallery

SetProtocol sets the protocol for all images in the gallery

func (*ImageGallery) SetSpacing added in v0.1.20

func (g *ImageGallery) SetSpacing(spacing int) *ImageGallery

SetSpacing sets the spacing between images in character cells

func (*ImageGallery) UpdateAllImages added in v0.1.20

func (g *ImageGallery) UpdateAllImages()

UpdateAllImages forces all image widgets in the gallery to update

type ImageWidget added in v0.1.20

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

ImageWidget represents an image widget for TUI frameworks

func NewImageWidget added in v0.1.20

func NewImageWidget(img *Image) *ImageWidget

NewImageWidget creates a new image widget from an Image

func NewImageWidgetFromFile added in v0.1.20

func NewImageWidgetFromFile(path string) (*ImageWidget, error)

NewImageWidgetFromFile creates a new image widget from a file path

func NewImageWidgetFromImage added in v0.1.20

func NewImageWidgetFromImage(img image.Image) *ImageWidget

NewImageWidgetFromImage creates a new image widget from an image.Image

func (*ImageWidget) Clear added in v0.1.20

func (w *ImageWidget) Clear() error

Clear clears the image from the terminal

func (*ImageWidget) GetPosition added in v0.1.20

func (w *ImageWidget) GetPosition() (x, y int)

GetPosition returns the current widget position

func (*ImageWidget) GetSize added in v0.1.20

func (w *ImageWidget) GetSize() (width, height int)

GetSize returns the current widget dimensions

func (*ImageWidget) PlaceAt added in v0.1.20

func (w *ImageWidget) PlaceAt(x, y int) (string, error)

PlaceAt places a virtual image at the specified position

func (*ImageWidget) Render added in v0.1.20

func (w *ImageWidget) Render() (string, error)

Render returns the string representation of the image for the TUI

func (*ImageWidget) RenderVirtual added in v0.1.20

func (w *ImageWidget) RenderVirtual() (string, error)

RenderVirtual renders the image with virtual placement and returns the placement string

func (*ImageWidget) SetPosition added in v0.1.20

func (w *ImageWidget) SetPosition(x, y int) *ImageWidget

SetPosition sets the widget position in the TUI grid

func (*ImageWidget) SetProtocol added in v0.1.20

func (w *ImageWidget) SetProtocol(protocol Protocol) *ImageWidget

SetProtocol sets the rendering protocol to use

func (*ImageWidget) SetSize added in v0.1.20

func (w *ImageWidget) SetSize(width, height int) *ImageWidget

SetSize sets the widget dimensions in character cells

func (*ImageWidget) SetSizeWithCorrection added in v0.1.20

func (w *ImageWidget) SetSizeWithCorrection(width, height int) *ImageWidget

SetSizeWithCorrection sets the widget dimensions and corrects for aspect ratio

func (*ImageWidget) SetVirtual added in v0.1.20

func (w *ImageWidget) SetVirtual(virtual bool) *ImageWidget

SetVirtual enables virtual placement mode (Kitty only)

func (*ImageWidget) SetZIndex added in v0.1.20

func (w *ImageWidget) SetZIndex(zIndex int) *ImageWidget

SetZIndex sets the z-index for layering (Kitty only)

func (*ImageWidget) Update added in v0.1.20

func (w *ImageWidget) Update()

Update forces the widget to re-render on next Render() call

type KittyOptions added in v0.1.20

type KittyOptions struct {
	ImageID      string
	Placement    string
	UseUnicode   bool
	Animation    *AnimationOptions
	Position     *PositionOptions
	FileTransfer bool
	Compression  bool
	PNG          bool
	TempFile     bool
	ImageNum     int
}

KittyOptions contains Kitty-specific rendering options

type KittyRenderer added in v0.1.20

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

KittyRenderer implements the Renderer interface for Kitty graphics protocol

func (*KittyRenderer) AnimateImages added in v0.1.20

func (r *KittyRenderer) AnimateImages(imageIDs []string, delayMs int, loops int) error

AnimateImages creates an animation sequence from a list of image IDs

func (*KittyRenderer) Clear added in v0.1.20

func (r *KittyRenderer) Clear(opts ClearOptions) error

Clear removes the image from the terminal

func (*KittyRenderer) ClearVirtualImage added in v0.1.20

func (r *KittyRenderer) ClearVirtualImage(imageID string) error

ClearVirtualImage explicitly deletes a virtual image by ID

func (*KittyRenderer) GetLastImageID added in v0.1.20

func (r *KittyRenderer) GetLastImageID() uint32

GetLastImageID returns the image ID that was assigned during the last render

func (*KittyRenderer) PlaceImage added in v0.1.20

func (r *KittyRenderer) PlaceImage(imageID string, xCells, yCells, zIndex int) error

PlaceImage positions a previously transferred virtual image at specific coordinates using Unicode placeholders

func (*KittyRenderer) PlaceImageWithSize added in v0.1.20

func (r *KittyRenderer) PlaceImageWithSize(imageID string, xCells, yCells, zIndex, widthCells, heightCells int) error

PlaceImageWithSize positions a virtual image with specific dimensions in character cells

func (*KittyRenderer) Print added in v0.1.20

func (r *KittyRenderer) Print(img image.Image, opts RenderOptions) error

Print outputs the image directly to stdout

func (*KittyRenderer) Protocol added in v0.1.20

func (r *KittyRenderer) Protocol() Protocol

Protocol returns the protocol type

func (*KittyRenderer) Render added in v0.1.20

func (r *KittyRenderer) Render(img image.Image, opts RenderOptions) (string, error)

Render generates the escape sequence for displaying the image

func (*KittyRenderer) SendFile added in v0.1.20

func (r *KittyRenderer) SendFile(filePath string, opts RenderOptions) error

SendFile optimizes transfer by sending file path instead of data when possible

type KittyResponse added in v0.1.14

type KittyResponse struct {
	ID      string
	Message string
}

type PositionOptions added in v0.1.20

type PositionOptions struct {
	X      int // X coordinate in character cells
	Y      int // Y coordinate in character cells
	ZIndex int // Z-index for layering
}

PositionOptions contains parameters for precise image positioning

type Protocol

type Protocol int
const (
	Unsupported Protocol = iota
	Auto                 // Auto-detect the best protocol
	ITerm2
	Kitty
	Sixel
	Halfblocks
)

func DetectProtocol

func DetectProtocol() Protocol

DetectProtocol returns the first supported protocol

func DetermineProtocols added in v0.1.20

func DetermineProtocols() []Protocol

DetermineProtocols returns a slice of supported protocols in the preferred order. We try Kitty first (richest feature-set), then iTerm2 (mac-only but common), then Sixel (legacy but widely available). Halfblocks is always available as the ultimate fallback.

func (Protocol) String

func (p Protocol) String() string

type RenderOptions added in v0.1.20

type RenderOptions struct {
	Path         string
	Width        int
	Height       int
	WidthPixels  int // Width in pixels instead of character cells
	HeightPixels int // Height in pixels instead of character cells
	ScaleMode    ScaleMode
	ZIndex       int
	Virtual      bool
	Dither       bool
	DitherMode   DitherMode

	// Protocol-specific options
	KittyOpts  *KittyOptions
	SixelOpts  *SixelOptions
	ITerm2Opts *ITerm2Options
	// contains filtered or unexported fields
}

RenderOptions contains all options for rendering an image

type RenderOutcome added in v0.1.22

type RenderOutcome struct {
	Output   string
	Width    int
	Height   int
	Duration time.Duration
	Err      error
	Pending  bool
	Skipped  bool
}

RenderOutcome describes the result of rendering a widget into a viewport. Pending is true when an async render is in-flight and the returned Output may still be from a previous size. Skipped indicates the viewport was too small to render anything safely.

type Renderer added in v0.1.20

type Renderer interface {
	// Render generates the escape sequence for displaying the image
	Render(img image.Image, opts RenderOptions) (string, error)

	// Print outputs the image directly to stdout
	Print(img image.Image, opts RenderOptions) error

	// Clear removes the image from the terminal
	Clear(opts ClearOptions) error

	// Protocol returns the protocol type
	Protocol() Protocol
}

Renderer is the interface that all protocol implementations must satisfy

func GetRenderer added in v0.1.20

func GetRenderer(protocol Protocol) (Renderer, error)

GetRenderer returns a renderer for the specified protocol

type ResizeCache added in v0.1.20

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

ResizeCache caches resized images to avoid repeated expensive operations

type ScaleMode added in v0.1.20

type ScaleMode int

ScaleMode defines how images should be scaled

const (
	// ScaleAuto intelligently scales: no resize if dimensions match, fit to terminal if too large
	ScaleAuto ScaleMode = iota
	// ScaleNone performs no scaling
	ScaleNone
	// ScaleFit fits the image within bounds while maintaining aspect ratio
	ScaleFit
	// ScaleFill fills the bounds, potentially cropping the image
	ScaleFill
	// ScaleStretch stretches the image to fill bounds exactly
	ScaleStretch
)

type SixelClearMode added in v0.1.20

type SixelClearMode int

SixelClearMode defines how sixel images should be cleared

const (
	// SixelClearScreen clears the entire screen
	SixelClearScreen SixelClearMode = iota
	// SixelClearPrecise clears only the exact image area
	SixelClearPrecise
)

type SixelOptions added in v0.1.20

type SixelOptions struct {
	Colors    int            // Number of colors in palette
	ClearMode SixelClearMode // How to clear images
}

SixelOptions contains Sixel-specific rendering options

type SixelRenderer added in v0.1.20

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

SixelRenderer implements the Renderer interface for Sixel protocol

func (*SixelRenderer) Clear added in v0.1.20

func (r *SixelRenderer) Clear(opts ClearOptions) error

Clear removes the image from the terminal

func (*SixelRenderer) Print added in v0.1.20

func (r *SixelRenderer) Print(img image.Image, opts RenderOptions) error

Print outputs the image directly to stdout

func (*SixelRenderer) Protocol added in v0.1.20

func (r *SixelRenderer) Protocol() Protocol

Protocol returns the protocol type

func (*SixelRenderer) Render added in v0.1.20

func (r *SixelRenderer) Render(img image.Image, opts RenderOptions) (string, error)

Render generates the escape sequence for displaying the image

type StatefulImageWidget added in v0.1.22

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

StatefulImageWidget tracks viewport size and re-renders only when needed. It can operate synchronously or with an AsyncRenderWorker for background rendering.

func NewStatefulImageWidget added in v0.1.22

func NewStatefulImageWidget(img *Image) *StatefulImageWidget

NewStatefulImageWidget creates a widget that can adapt to changing viewports.

func (*StatefulImageWidget) Close added in v0.1.22

func (w *StatefulImageWidget) Close()

Close stops the attached worker, if any.

func (*StatefulImageWidget) EnableAsync added in v0.1.22

func (w *StatefulImageWidget) EnableAsync(workers int) *StatefulImageWidget

EnableAsync spins up a background worker. workers<=0 defaults to 1.

func (*StatefulImageWidget) RenderInto added in v0.1.22

func (w *StatefulImageWidget) RenderInto(width, height int) RenderOutcome

RenderInto renders the widget into a viewport of width x height cells. When async is enabled, Pending will be true until the worker finishes a render that matches the current target size.

func (*StatefulImageWidget) SetMinimumCells added in v0.1.22

func (w *StatefulImageWidget) SetMinimumCells(minWidth, minHeight int) *StatefulImageWidget

SetMinimumCells configures the minimum width/height (in cells) required before rendering. Calls with smaller viewports will be skipped.

func (*StatefulImageWidget) SetProtocol added in v0.1.22

func (w *StatefulImageWidget) SetProtocol(protocol Protocol) *StatefulImageWidget

SetProtocol overrides the protocol used for rendering.

func (*StatefulImageWidget) SetScaleMode added in v0.1.22

func (w *StatefulImageWidget) SetScaleMode(mode ScaleMode) *StatefulImageWidget

SetScaleMode controls how the image scales inside the viewport.

func (*StatefulImageWidget) SetVirtual added in v0.1.22

func (w *StatefulImageWidget) SetVirtual(virtual bool) *StatefulImageWidget

SetVirtual toggles Kitty virtual placement support.

func (*StatefulImageWidget) SetZIndex added in v0.1.22

func (w *StatefulImageWidget) SetZIndex(z int) *StatefulImageWidget

SetZIndex sets Kitty z-index ordering.

func (*StatefulImageWidget) WithWorker added in v0.1.22

WithWorker attaches a caller-supplied worker (useful for sharing across widgets).

type TUIHelper added in v0.1.20

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

TUIHelper provides utilities for TUI integration

func NewTUIHelper added in v0.1.20

func NewTUIHelper() *TUIHelper

NewTUIHelper creates a new TUI helper

func (*TUIHelper) CreateImageGallery added in v0.1.20

func (h *TUIHelper) CreateImageGallery(columns int, imageWidth, imageHeight int) *ImageGallery

CreateImageGallery creates a properly configured image gallery

func (*TUIHelper) CreateImageWidget added in v0.1.20

func (h *TUIHelper) CreateImageWidget(img *Image, width, height int) *ImageWidget

CreateImageWidget creates a properly configured image widget

func (*TUIHelper) GetBestProtocol added in v0.1.20

func (h *TUIHelper) GetBestProtocol() Protocol

GetBestProtocol returns the best available protocol

func (*TUIHelper) SetPreferredProtocol added in v0.1.20

func (h *TUIHelper) SetPreferredProtocol(protocol Protocol)

SetPreferredProtocol sets the preferred protocol for the TUI

func (*TUIHelper) ShowProtocolWarning added in v0.1.20

func (h *TUIHelper) ShowProtocolWarning(protocol Protocol) string

ShowProtocolWarning shows a warning if the protocol isn't optimal for TUI

type TerminalFeatures added in v0.1.20

type TerminalFeatures struct {
	TermName    string
	TermProgram string
	IsTmux      bool
	IsScreen    bool

	FontWidth  int
	FontHeight int

	WindowCols int
	WindowRows int

	KittyGraphics  bool
	SixelGraphics  bool
	ITerm2Graphics bool

	TrueColor bool
}

TerminalFeatures represents detected terminal capabilities (simplified from utils.go)

func QueryTerminalFeatures added in v0.1.20

func QueryTerminalFeatures() *TerminalFeatures

QueryTerminalFeatures performs unified terminal capability detection

func (*TerminalFeatures) GetTerminalFontSize added in v0.1.20

func (tf *TerminalFeatures) GetTerminalFontSize() (width, height int, err error)

GetTerminalFontSize query functions with short timeouts

type TerminalQuerier added in v0.1.20

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

TerminalQuerier handles batched terminal queries for improved performance

func NewTerminalQuerier added in v0.1.20

func NewTerminalQuerier() (*TerminalQuerier, error)

NewTerminalQuerier creates a new querier with terminal in raw mode

func (*TerminalQuerier) Close added in v0.1.20

func (tq *TerminalQuerier) Close()

Close restores terminal state and closes tty

func (*TerminalQuerier) Query added in v0.1.20

func (tq *TerminalQuerier) Query(query string, timeout time.Duration) (string, error)

Query sends a query and waits for response with timeout

Directories

Path Synopsis
cmd
demo command
gallery module
imgcat module
pkg
csi
Package csi provides CSI (Control Sequence Introducer) query functions for terminal capabilities
Package csi provides CSI (Control Sequence Introducer) query functions for terminal capabilities

Jump to

Keyboard shortcuts

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