qafterm

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 16 Imported by: ? modules, 0 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

qafterm

A small, opinionated Go library for embedding a real terminal in a GUI application.

import "github.com/nhrbuilds/qafterm"

qafterm does not implement terminal emulation. That part is done by battle-tested libraries:

Concern Library
VT/xterm emulation (parser, screen, scrollback, alt screen, mouse, truecolor) charmbracelet/x/vt
Pseudo-terminal handling creack/pty

What qafterm adds is the layer a GUI host needs and no library provides:

  • a Session that owns a shell in a PTY and pumps bytes in both directions;
  • a renderer-facing snapshot (rows of styled cells) that never exposes upstream types, so the emulator can be swapped without breaking users;
  • damage reporting — which rows changed since the last snapshot, so a host repaints only what it must;
  • scrollback-aware viewport rendering (scroll up into history);
  • key and mouse encoding that respects the terminal's own modes (for example application cursor keys).

Everything is pure Go and CGO-free.

Install

go get github.com/nhrbuilds/qafterm

Usage

ses, err := qafterm.Start(qafterm.Config{
    Shell: "zsh",   // empty: $SHELL, then the user's login shell, then /bin/sh
    Dir:   "/path/to/project",
    Cols:  120,
    Rows:  30,
})
if err != nil {
    return err
}
defer ses.Close()

for {
    rows := ses.View(0)          // viewport rows (scroll up with View(n))
    changed := ses.Damage()      // row indices that changed since last call
    render(rows, changed)
    time.Sleep(16 * time.Millisecond)
}

Sending input:

_ = ses.Key(qafterm.Rune('a'))              // printable
_ = ses.Key(qafterm.SpecialMod(qafterm.KeyUp, qafterm.ModCtrl)) // ctrl+up
_ = ses.Text("hello")                       // literal text
_ = ses.Paste("pasted")                     // bracketed paste when enabled
_ = ses.Mouse(qafterm.MouseEvent{
    Kind: qafterm.MousePress, Button: qafterm.MouseLeft, X: 3, Y: 4,
})

API

Symbol Purpose
Start(Config) (*Session, error) Launch a shell in a PTY.
Session.Write/Key/Text/Paste/Mouse Send input to the shell.
Session.Snapshot() []Row The visible screen as styled cells.
Session.View(scroll int) []Row The viewport, scrolled up into history.
Session.Damage() []int Screen rows changed since the last call.
Session.Resize(cols, rows int) error Resize the terminal and inform the shell.
Session.Title() string The last window title the program set.
Session.AltScreen() bool Whether the program uses the alternate screen.
Session.ScrollbackLen() int Number of buffered history lines.
Session.Focus() / Blur() Focus events (mode 1004).
Session.Done() <-chan struct{} Closed when the shell exits.
Types

Cell carries the grapheme cluster, its width, the foreground and background Color, the SGR attributes (Bold, Faint, Italic, Blink, Reverse, Conceal, Strike) and the Underline style.

Color is one of:

  • ColorDefault — the terminal's own default color;
  • ColorIndexed — one of the 256 palette colors;
  • ColorRGB — a direct 24-bit color.

Design notes

  • No upstream types leak. The public API is defined here, so the emulator can be replaced later without a breaking change for users.
  • Damage is computed by the host layer. Row fingerprints make it a single comparison per row; a host repaints only the rows that changed.
  • Keys go through the emulator. The emulator owns the terminal's modes (application cursor keys, keypad mode, mouse reporting), so key encoding stays correct without duplicating that logic.

Roadmap

  • Reflow on resize (wrapping preserved lines) — currently the screen is padded/truncated like xterm without reflow.
  • A ready-to-use renderer for common toolkits (GTK, Gio).
  • Optional shell integration helpers (command marks, OSC 133).

License

MIT — see LICENSE.

Documentation

Overview

Package qafterm provides a small, opinionated host layer for embedding a real terminal in a GUI application.

It deliberately does not implement terminal emulation itself: the emulator is github.com/charmbracelet/x/vt, a battle-tested xterm/VT emulator, and the pseudo-terminal handling is github.com/creack/pty. qafterm wires them together and adds the pieces a GUI host needs but no library provides:

  • A session that owns a shell in a PTY and pumps bytes in both directions.
  • A renderer-facing snapshot (rows of styled cells) that never exposes upstream types, so the emulator can be swapped without breaking users.
  • Damage reporting: which rows changed since the last snapshot, so a host repaints only what it must.
  • Scrollback-aware viewport rendering (scroll up into history).
  • Key and mouse encoding that respects the terminal's own modes (for example application cursor keys).

Everything is pure Go and CGO-free.

Basic use:

ses, err := qafterm.Start(qafterm.Config{Cols: 120, Rows: 30})
if err != nil {
	return err
}
defer ses.Close()

go func() {
	for {
		rows := ses.View(0) // viewport rows
		changed := ses.Damage()
		render(rows, changed)
		time.Sleep(16 * time.Millisecond)
	}
}()

Index

Constants

View Source
const (
	KeyEnter     = vt.KeyEnter
	KeyTab       = vt.KeyTab
	KeyEsc       = vt.KeyEscape
	KeyBackspace = vt.KeyBackspace
	KeySpace     = vt.KeySpace
	KeyUp        = vt.KeyUp
	KeyDown      = vt.KeyDown
	KeyRight     = vt.KeyRight
	KeyLeft      = vt.KeyLeft
	KeyHome      = vt.KeyHome
	KeyEnd       = vt.KeyEnd
	KeyPgUp      = vt.KeyPgUp
	KeyPgDown    = vt.KeyPgDown
	KeyInsert    = vt.KeyInsert
	KeyDelete    = vt.KeyDelete
	KeyF1        = vt.KeyF1
	KeyF2        = vt.KeyF2
	KeyF3        = vt.KeyF3
	KeyF4        = vt.KeyF4
	KeyF5        = vt.KeyF5
	KeyF6        = vt.KeyF6
	KeyF7        = vt.KeyF7
	KeyF8        = vt.KeyF8
	KeyF9        = vt.KeyF9
	KeyF10       = vt.KeyF10
	KeyF11       = vt.KeyF11
	KeyF12       = vt.KeyF12
)

Special key codes. Printable keys use their rune directly.

Variables

View Source
var DefaultColor = Color{Kind: ColorDefault}

DefaultColor is the terminal's default color.

Functions

This section is empty.

Types

type Cell

type Cell struct {
	// Text is the grapheme cluster shown in the cell. It is empty for a
	// blank cell.
	Text string
	// Width is the number of columns the cell occupies (0, 1 or 2).
	Width int
	// FG and BG are the foreground and background colors.
	FG, BG Color
	// Bold, Faint, Italic, Blink, Reverse, Conceal and Strike mirror the
	// corresponding SGR attributes.
	Bold, Faint, Italic, Blink, Reverse, Conceal, Strike bool
	// Underline is the underline decoration.
	Underline UnderlineStyle
}

Cell is one character cell of the terminal screen.

type Color

type Color struct {
	Kind    ColorKind
	Index   uint8 // palette index for ColorIndexed
	R, G, B uint8
}

Color is a cell color in a form that does not depend on the emulator.

func IndexedColor

func IndexedColor(i int) Color

IndexedColor returns a palette color.

func RGBColor

func RGBColor(r, g, b uint8) Color

RGBColor returns a direct color.

type ColorKind

type ColorKind uint8

ColorKind describes how a cell color is defined.

const (
	// ColorDefault means the terminal's default foreground or background.
	ColorDefault ColorKind = iota
	// ColorIndexed means one of the 256 palette colors.
	ColorIndexed
	// ColorRGB means a direct 24-bit color.
	ColorRGB
)

type Config

type Config struct {
	// Shell is the program to run. Empty means $SHELL, then the current
	// user's login shell from the password database, then /bin/sh.
	Shell string
	// Args are the arguments passed to the shell. When empty the shell is
	// started as a login shell ("-l") if it supports it, otherwise bare.
	Args []string
	// Dir is the working directory of the shell. Empty means the current
	// working directory.
	Dir string
	// Env holds extra environment entries in "KEY=VALUE" form. They are
	// appended to the inherited environment; an entry with an existing key
	// replaces it.
	Env []string
	// Cols and Rows are the initial terminal size in cells.
	Cols int
	Rows int
	// Scrollback is the number of history lines kept. Zero means the
	// emulator default (10000); negative disables scrollback.
	Scrollback int
}

Config describes a terminal session to start.

type KeyEvent

type KeyEvent struct {
	// Code is the key: a printable rune, or one of the Key* constants.
	Code rune
	// Text is the literal text the key produced, when it differs from Code
	// (for example a dead key or an IME result).
	Text string
	// Mod holds the active modifiers.
	Mod Mod
}

KeyEvent is a key press delivered to a session.

func Rune

func Rune(r rune) KeyEvent

Rune builds a printable key event.

func RuneMod

func RuneMod(r rune, mod Mod) KeyEvent

RuneMod builds a printable key event with modifiers.

func Special

func Special(code rune) KeyEvent

Special builds a key event for a special key.

func SpecialMod

func SpecialMod(code rune, mod Mod) KeyEvent

SpecialMod builds a key event for a special key with modifiers.

type Mod

type Mod uint8

Mod is a set of keyboard modifiers.

const (
	ModShift Mod = 1 << iota
	ModAlt
	ModCtrl
	ModMeta
)

Modifier bits.

type MouseButton

type MouseButton uint8

MouseButton identifies a mouse button.

const (
	MouseNone MouseButton = iota
	MouseLeft
	MouseMiddle
	MouseRight
	MouseWheelUp
	MouseWheelDown
	MouseWheelLeft
	MouseWheelRight
	MouseButton8
	MouseButton9
	MouseButton10
	MouseButton11
)

Mouse buttons, matching the xterm numbering.

type MouseEvent

type MouseEvent struct {
	Kind   MouseKind
	Button MouseButton
	// X and Y are the zero-based cell coordinates.
	X, Y int
	// Mod holds the active modifiers.
	Mod Mod
}

MouseEvent is a mouse event delivered to a session.

type MouseKind

type MouseKind uint8

MouseKind describes the type of a mouse event.

const (
	// MousePress is a button press.
	MousePress MouseKind = iota
	// MouseRelease is a button release.
	MouseRelease
	// MouseMotion is a pointer move.
	MouseMotion
	// MouseWheel is a wheel movement.
	MouseWheel
)

type Row

type Row []Cell

Row is one line of the terminal screen.

type Session

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

Session is a running shell attached to a pseudo-terminal.

func Start

func Start(cfg Config) (*Session, error)

Start launches a shell in a pseudo-terminal and returns a session for it.

func (*Session) AltScreen

func (s *Session) AltScreen() bool

AltScreen reports whether the program is using the alternate screen (full screen applications such as vim or htop).

func (*Session) Bell

func (s *Session) Bell() bool

Bell reports whether the terminal bell rang since the last call.

func (*Session) Blur

func (s *Session) Blur()

Blur tells the shell the terminal lost focus (mode 1004).

func (*Session) BracketedPaste

func (s *Session) BracketedPaste() bool

BracketedPaste reports whether the program enabled bracketed paste.

func (*Session) Close

func (s *Session) Close() error

Close terminates the session and releases the pseudo-terminal. The emulator itself is shut down by the input pump (see pumpInput); Close kills the shell, closes the PTY, waits for the output pump, and then wakes the input pump so nothing stays parked.

func (*Session) Cols

func (s *Session) Cols() int

Cols and Rows report the current terminal size.

func (*Session) Cursor

func (s *Session) Cursor() (x, y int, hidden bool)

Cursor returns the cursor position in cells and whether the cursor is hidden (the program asked for it to be invisible).

func (*Session) Damage

func (s *Session) Damage() []int

Damage reports which screen rows changed since the previous call to Snapshot or View. The returned indices are relative to the visible screen; a scrolled viewport should be repainted in full.

func (*Session) Done

func (s *Session) Done() <-chan struct{}

Done is closed when the shell exits.

func (*Session) Focus

func (s *Session) Focus()

Focus tells the shell the terminal gained focus (mode 1004).

func (*Session) Key

func (s *Session) Key(k KeyEvent) error

Key sends a key press to the shell. Special keys use the Key* constants; printable keys use their rune.

func (*Session) MaxScrollback

func (s *Session) MaxScrollback() int

MaxScrollback reports the scrollback limit.

func (*Session) Mouse

func (s *Session) Mouse(ev MouseEvent) error

Mouse sends a mouse event to the shell. It is ignored unless the program enabled mouse reporting.

func (*Session) MouseEnabled

func (s *Session) MouseEnabled() bool

MouseEnabled reports whether the program asked for mouse reports. Hosts must not forward mouse events while this is false: the program would receive reports it never asked for.

func (*Session) Paste

func (s *Session) Paste(text string) error

Paste sends text to the shell using bracketed paste when the program enabled the mode.

func (*Session) Resize

func (s *Session) Resize(cols, rows int) error

Resize changes the terminal size, informing the shell through the PTY.

func (*Session) Rows

func (s *Session) Rows() int

Rows reports the current terminal height.

func (*Session) ScrollbackLen

func (s *Session) ScrollbackLen() int

ScrollbackLen reports how many history lines are buffered.

func (*Session) ShellName

func (s *Session) ShellName() string

ShellName returns a short display name for the shell (for example "zsh"), suitable for a tab title.

func (*Session) Snapshot

func (s *Session) Snapshot() []Row

Snapshot returns the current viewport: the visible screen rows.

The walk holds emuMu for its whole duration: CellAt and Scrollback hand out pointers into the emulator's live buffer memory, so reading their fields must exclude the output pump's Write (which mutates those cells). emuMu is always taken before s.mu — the same order the pump uses.

func (*Session) Text

func (s *Session) Text(text string) error

Text sends literal text to the shell (typing, pasting).

func (*Session) Title

func (s *Session) Title() string

Title reports the last window title set by the program.

func (*Session) View

func (s *Session) View(scroll int) []Row

View returns the viewport rows scrolled up by the given number of lines. A scroll of zero shows the live screen; larger values replace the top of the screen with history lines. The result always has the terminal's height.

func (*Session) WorkingDir

func (s *Session) WorkingDir() string

WorkingDir reports the last working directory reported by the shell, when the program supports that reporting.

type UnderlineStyle

type UnderlineStyle uint8

UnderlineStyle is the underline decoration of a cell.

const (
	UnderlineNone UnderlineStyle = iota
	UnderlineSingle
	UnderlineDouble
	UnderlineCurly
	UnderlineDotted
	UnderlineDashed
)

Jump to

Keyboard shortcuts

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