feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

@@ -0,0 +1,185 @@
package vt
import (
"bytes"
"encoding/base64"
)
// ClipboardAnswer is how the ClipboardRead effect answers a program's
// read of the clipboard.
type ClipboardAnswer int
const (
// ClipboardRefused has the library refuse the read itself: an empty
// OSC 52 reply, an EPERM status for the Kitty protocol's OSC 5522,
// which the binding drops, as the read of a terminal that is not the
// one to answer. It is the zero value.
ClipboardRefused ClipboardAnswer = iota
// ClipboardAnswered answers the read with ClipboardReply.Contents
// now, which the library encodes as it returns.
ClipboardAnswered
// ClipboardDeferred holds the library's refusal back and answers the
// read later with Terminal.AnswerClipboard, which needs a
// ClipboardReply carrying a DeferredClipboardRead.
ClipboardDeferred
)
// DeferredClipboardRead is a read the embedder answers after its effect
// returned (ClipboardDeferred). The binding fills it as the library
// writes the refusal it holds back: kitty tells that the read came by
// the Kitty clipboard protocol (OSC 5522) rather than OSC 52; for OSC
// 52, prefix is the reply's beginning ("\x1b]52;" with the selector and
// its ";") and terminator how the request ended; refusal is what the
// library wrote to refuse the read (the empty OSC 52 reply, or the EPERM
// packet), which a denial writes again; mimes, list and primary are what
// the program asked for, and id is the id of a Kitty protocol read,
// echoed in its answer. Pass it to Terminal.AnswerClipboard.
type DeferredClipboardRead struct {
kitty bool
prefix, terminator, refusal []byte
mimes []string
list, primary bool
id string
}
// readChunkSize is how many raw bytes of one MIME type a Kitty protocol
// DATA packet carries.
const readChunkSize = 4096
// AnswerClipboard answers a read that the ClipboardRead effect deferred
// (ClipboardDeferred): allowed serves contents by MIME type, and
// available for the types listing (OSC 5522's "."), while denied writes
// the refusal the library wrote for the read and the binding held back.
// It is safe from any goroutine, and contents and available are not
// retained after it returns.
func (t *Terminal) AnswerClipboard(d *DeferredClipboardRead, allowed bool, contents map[string][]byte, available []string) {
if d == nil || t.effects.WritePTY == nil {
return
}
if !allowed {
t.effects.WritePTY(d.refusal)
return
}
if d.kitty {
t.effects.WritePTY(d.kittyAnswer(contents, available))
return
}
out := make([]byte, 0, len(d.prefix)+len(d.terminator)+16)
out = append(out, d.prefix...)
out = base64.StdEncoding.AppendEncode(out, contents["text/plain"])
out = append(out, d.terminator...)
t.effects.WritePTY(out)
}
// kittyAnswer encodes the read's answer as the library encodes one
// (ReadSuccess.encode in Ghostty's response.zig): an OK packet, the
// targets listing when asked for, the requested representations in
// request order as DATA packets, and DONE. The loc metadata is only on
// the OK packet, and no packet carries a password, as for a reply to a
// read.
func (d *DeferredClipboardRead) kittyAnswer(contents map[string][]byte, available []string) []byte {
out := make([]byte, 0, 64)
packet := func(out []byte, status string, loc bool) []byte {
out = append(out, "\x1b]5522;type=read:status="...)
out = append(out, status...)
if loc && d.primary {
out = append(out, ":loc=primary"...)
}
if d.id != "" {
out = append(out, ":id="...)
out = append(out, d.id...)
}
return out
}
out = packet(out, "OK", true)
out = append(out, d.terminator...)
if d.list {
out = packet(out, "DATA", false)
out = append(out, ":mime="...)
out = base64.StdEncoding.AppendEncode(out, []byte("."))
if len(available) > 0 {
// The types joined by spaces with a trailing newline, whole
// types only, as the library writes them.
var raw []byte
for i, mime := range available {
sep := 0
if i > 0 {
sep = 1
}
if len(raw)+sep+len(mime)+1 > readChunkSize {
break
}
if i > 0 {
raw = append(raw, ' ')
}
raw = append(raw, mime...)
}
raw = append(raw, '\n')
out = append(out, ';')
out = base64.StdEncoding.AppendEncode(out, raw)
}
out = append(out, d.terminator...)
}
for _, mime := range d.mimes {
data := contents[mime]
for i := 0; i < len(data); i += readChunkSize {
n := min(len(data)-i, readChunkSize)
out = packet(out, "DATA", false)
out = append(out, ":mime="...)
out = base64.StdEncoding.AppendEncode(out, []byte(mime))
out = append(out, ';')
out = base64.StdEncoding.AppendEncode(out, data[i:i+n])
out = append(out, d.terminator...)
}
}
out = packet(out, "DONE", false)
out = append(out, d.terminator...)
return out
}
// setRefusal parses the bytes the library wrote to refuse a deferred read
// and keeps them for a denial.
func (d *DeferredClipboardRead) setRefusal(p []byte) bool {
switch {
case bytes.HasPrefix(p, []byte("\x1b]52;")):
// p is "\x1b]52;<selector>;<terminator>": the payload is empty.
first := bytes.IndexByte(p, ';')
if first < 0 {
return false
}
second := bytes.IndexByte(p[first+1:], ';')
if second < 0 {
return false
}
second += first + 1
d.kitty = false
d.prefix = append([]byte(nil), p[:second+1]...)
d.terminator = append([]byte(nil), p[second+1:]...)
d.refusal = append([]byte(nil), p...)
return true
case bytes.HasPrefix(p, []byte("\x1b]5522;type=read:status=")):
d.kitty = true
d.refusal = append([]byte(nil), p...)
switch {
case bytes.HasSuffix(p, []byte("\x1b\\")):
d.terminator = append([]byte(nil), p[len(p)-2:]...)
case len(p) > 0 && p[len(p)-1] == '\x07':
d.terminator = append([]byte(nil), p[len(p)-1:]...)
default:
d.terminator = append([]byte(nil), "\x1b\\"...)
}
d.id = ""
if i := bytes.Index(p, []byte(":id=")); i >= 0 {
rest := p[i+len(":id="):]
if j := bytes.IndexAny(rest, ":\x1b\x07"); j >= 0 {
rest = rest[:j]
}
d.id = string(rest)
}
if bytes.Contains(p, []byte(":loc=primary")) {
d.primary = true
}
return true
}
return false
}
+369
View File
@@ -0,0 +1,369 @@
package vt
import (
"runtime"
"unsafe"
)
// Key is a GhosttyKey: a key by its place on the keyboard, as the W3C's
// KeyboardEvent.code names them.
type Key int32
// Keys, in the order of GhosttyKey.
const (
KeyUnidentified Key = iota
KeyBackquote
KeyBackslash
KeyBracketLeft
KeyBracketRight
KeyComma
KeyDigit0
KeyDigit1
KeyDigit2
KeyDigit3
KeyDigit4
KeyDigit5
KeyDigit6
KeyDigit7
KeyDigit8
KeyDigit9
KeyEqual
KeyIntlBackslash
KeyIntlRo
KeyIntlYen
KeyA
KeyB
KeyC
KeyD
KeyE
KeyF
KeyG
KeyH
KeyI
KeyJ
KeyK
KeyL
KeyM
KeyN
KeyO
KeyP
KeyQ
KeyR
KeyS
KeyT
KeyU
KeyV
KeyW
KeyX
KeyY
KeyZ
KeyMinus
KeyPeriod
KeyQuote
KeySemicolon
KeySlash
KeyAltLeft
KeyAltRight
KeyBackspace
KeyCapsLock
KeyContextMenu
KeyControlLeft
KeyControlRight
KeyEnter
KeyMetaLeft
KeyMetaRight
KeyShiftLeft
KeyShiftRight
KeySpace
KeyTab
KeyConvert
KeyKanaMode
KeyNonConvert
KeyDelete
KeyEnd
KeyHelp
KeyHome
KeyInsert
KeyPageDown
KeyPageUp
KeyArrowDown
KeyArrowLeft
KeyArrowRight
KeyArrowUp
)
// KeyEscape and the function keys follow the 41 keys of the numpad.
const (
KeyEscape Key = KeyArrowUp + 1 + 41 + iota
KeyF1
)
// Mods are modifier keys (GhosttyMods): Shift, Ctrl, Alt and Super, the
// same bits as MyGo's.
type Mods uint16
const (
ModShift Mods = 1 << iota
ModCtrl
ModAlt
ModSuper
)
// KeyAction is what happened to a key.
type KeyAction int32
const (
KeyRelease KeyAction = iota
KeyPress
KeyRepeat
)
// KeyEvent is a key to encode for the program.
type KeyEvent struct {
Action KeyAction
Key Key
Mods Mods
// Consumed are the modifiers that made Text, as Shift an "A".
Consumed Mods
// Text is what the key types, without what Ctrl or Alt change; empty
// for keys that type nothing.
Text string
// Unshifted is the character the key types without modifiers.
Unshifted rune
// Composing tells that an input method is composing.
Composing bool
}
// KeyEncoder encodes keys as the terminal's modes ask: legacy sequences,
// xterm's modifyOtherKeys or the Kitty keyboard protocol.
type KeyEncoder struct {
h, ev uintptr
buf [128]byte
}
// NewKeyEncoder makes a key encoder.
func NewKeyEncoder() (*KeyEncoder, error) {
e := &KeyEncoder{}
if err := result(call(fnKeyEncoderNew, 0, uintptr(unsafe.Pointer(&e.h)))); err != nil {
return nil, err
}
if err := result(call(fnKeyEventNew, 0, uintptr(unsafe.Pointer(&e.ev)))); err != nil {
e.Free()
return nil, err
}
return e, nil
}
// Free frees the encoder.
func (e *KeyEncoder) Free() {
if e.ev != 0 {
call(fnKeyEventFree, e.ev)
}
if e.h != 0 {
call(fnKeyEncoderFree, e.h)
}
*e = KeyEncoder{}
}
// Sync takes the terminal's modes, and whether Option is Alt on macOS.
func (e *KeyEncoder) Sync(t *Terminal, optionAsAlt bool) {
call(fnKeyEncoderSetoptFromTerminal, e.h, t.h)
v := int32(b2u(optionAsAlt))
call(fnKeyEncoderSetopt, e.h, 6, uintptr(unsafe.Pointer(&v)))
}
// Encode returns the bytes the program reads for k, valid until the next
// call; nil for keys that send nothing.
func (e *KeyEncoder) Encode(k KeyEvent) []byte {
call(fnKeyEventSetAction, e.ev, uintptr(k.Action))
call(fnKeyEventSetKey, e.ev, uintptr(k.Key))
call(fnKeyEventSetMods, e.ev, uintptr(k.Mods))
call(fnKeyEventSetConsumedMods, e.ev, uintptr(k.Consumed))
call(fnKeyEventSetComposing, e.ev, b2u(k.Composing))
call(fnKeyEventSetUnshifted, e.ev, uintptr(k.Unshifted))
// The event keeps the text's address until it is encoded.
var pin runtime.Pinner
defer pin.Unpin()
text := []byte(k.Text)
if len(text) > 0 {
pin.Pin(&text[0])
call(fnKeyEventSetUTF8, e.ev, uintptr(unsafe.Pointer(&text[0])), uintptr(len(text)))
} else {
call(fnKeyEventSetUTF8, e.ev, 0, 0)
}
var n uintptr
r := call(fnKeyEncoderEncode, e.h, e.ev, uintptr(unsafe.Pointer(&e.buf[0])), uintptr(len(e.buf)), uintptr(unsafe.Pointer(&n)))
if Result(int32(r)) == OutOfSpace && n > 0 {
big := make([]byte, n)
r = call(fnKeyEncoderEncode, e.h, e.ev, uintptr(unsafe.Pointer(&big[0])), n, uintptr(unsafe.Pointer(&n)))
call(fnKeyEventSetUTF8, e.ev, 0, 0)
if !ok(r) {
return nil
}
return big[:n]
}
call(fnKeyEventSetUTF8, e.ev, 0, 0)
if !ok(r) || n == 0 {
return nil
}
return e.buf[:n]
}
// MouseAction is what the pointer did.
type MouseAction int32
const (
MousePress MouseAction = iota
MouseRelease
MouseMotion
)
// Mouse buttons: 1 left, 2 right, 3 middle, 4 and 5 the wheel up and down,
// 6 and 7 left and right.
const (
ButtonNone = 0
ButtonLeft = 1
ButtonRight = 2
ButtonMiddle = 3
WheelUp = 4
WheelDown = 5
WheelLeft = 6
WheelRight = 7
)
// MouseEncoder encodes pointer events in the format and for the events
// the program asked for.
type MouseEncoder struct {
h, ev uintptr
buf [64]byte
}
// NewMouseEncoder makes a mouse encoder.
func NewMouseEncoder() (*MouseEncoder, error) {
m := &MouseEncoder{}
if err := result(call(fnMouseEncoderNew, 0, uintptr(unsafe.Pointer(&m.h)))); err != nil {
return nil, err
}
if err := result(call(fnMouseEventNew, 0, uintptr(unsafe.Pointer(&m.ev)))); err != nil {
m.Free()
return nil, err
}
// Motion is reported once per cell, as xterm does.
v := true
call(fnMouseEncoderSetopt, m.h, 4, uintptr(unsafe.Pointer(&v)))
return m, nil
}
// Free frees the encoder.
func (m *MouseEncoder) Free() {
if m.ev != 0 {
call(fnMouseEventFree, m.ev)
}
if m.h != 0 {
call(fnMouseEncoderFree, m.h)
}
*m = MouseEncoder{}
}
// Sync takes the terminal's mouse modes, the geometry of the screen in
// pixels, and whether a button is held.
func (m *MouseEncoder) Sync(t *Terminal, width, height, cellWidth, cellHeight, padLeft, padTop int, pressed bool) {
call(fnMouseEncoderSetoptFromTerminal, m.h, t.h)
s := mouseEncoderSize{
size: unsafe.Sizeof(mouseEncoderSize{}), screenWidth: uint32(max(width, 1)), screenHeight: uint32(max(height, 1)),
cellWidth: uint32(max(cellWidth, 1)), cellHeight: uint32(max(cellHeight, 1)),
paddingTop: uint32(max(padTop, 0)), paddingLeft: uint32(max(padLeft, 0)),
}
call(fnMouseEncoderSetopt, m.h, 2, uintptr(unsafe.Pointer(&s)))
call(fnMouseEncoderSetopt, m.h, 3, uintptr(unsafe.Pointer(&pressed)))
}
// Encode returns the bytes the program reads for a pointer event at x, y
// pixels, valid until the next call; nil when it asked for no such event.
func (m *MouseEncoder) Encode(action MouseAction, button int, mods Mods, x, y float32) []byte {
call(fnMouseEventSetAction, m.ev, uintptr(action))
if button == ButtonNone {
call(fnMouseEventClearButton, m.ev)
} else {
call(fnMouseEventSetButton, m.ev, uintptr(button))
}
call(fnMouseEventSetMods, m.ev, uintptr(mods))
mouseEventSetPosition(m.ev, mousePosition{x, y})
var n uintptr
if !ok(call(fnMouseEncoderEncode, m.h, m.ev, uintptr(unsafe.Pointer(&m.buf[0])), uintptr(len(m.buf)), uintptr(unsafe.Pointer(&n)))) || n == 0 {
return nil
}
return m.buf[:n]
}
// EncodeFocus returns the report of the terminal gaining or losing the
// focus (mode 1004).
func EncodeFocus(gained bool) []byte {
var buf [8]byte
var n uintptr
if !ok(call(fnFocusEncode, b2u(!gained), uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)), uintptr(unsafe.Pointer(&n)))) {
return nil
}
return buf[:n]
}
// EncodePaste returns text as the program reads a paste: bracketed (mode
// 2004), or with newlines as carriage returns, and without the control
// characters that could run commands.
func EncodePaste(text string, bracketed bool) []byte {
data := []byte(text)
if len(data) == 0 {
return nil
}
out := make([]byte, len(data)+16)
var n uintptr
r := call(fnPasteEncode, uintptr(unsafe.Pointer(&data[0])), uintptr(len(data)), b2u(bracketed), uintptr(unsafe.Pointer(&out[0])), uintptr(len(out)), uintptr(unsafe.Pointer(&n)))
if Result(int32(r)) == OutOfSpace && n > 0 {
data = []byte(text) // encoding may have changed it in place
out = make([]byte, n)
r = call(fnPasteEncode, uintptr(unsafe.Pointer(&data[0])), uintptr(len(data)), b2u(bracketed), uintptr(unsafe.Pointer(&out[0])), n, uintptr(unsafe.Pointer(&n)))
}
if !ok(r) {
return nil
}
return out[:n]
}
// PasteEvent tells the program what the clipboard offers a paste, by the
// MIME types, for it to read what it wants (mode 5522, the Kitty
// clipboard protocol); the program's reads come to Effects.ClipboardRead,
// granted. The event goes to the program through Effects.WritePTY. It
// reports whether the event was sent: it is not when the mode is not set
// or the terminal has no ClipboardRead, when the paste is the embedder's
// to encode (EncodePaste).
func (t *Terminal) PasteEvent(mimes []string) bool {
if !t.Mode(ModePasteEvents) || t.effects.ClipboardRead == nil {
return false
}
var keep [][]byte
cs := make([]cString, 0, len(mimes))
for _, m := range mimes {
cs = append(cs, cStringOf(m, &keep))
}
p := paste{size: unsafe.Sizeof(paste{}), source: 0 /* the clipboard */, mimesLen: uintptr(len(cs))}
if len(cs) > 0 {
p.mimes = uintptr(unsafe.Pointer(&cs[0]))
// The library asks a reader for data only when it pastes text
// itself, which it does not for an event; one is still required.
p.reader = mimeReader{read: cbNoRead}
}
var written bool
r := call(fnTerminalPaste, t.h, uintptr(unsafe.Pointer(&p)), uintptr(unsafe.Pointer(&written)))
runtime.KeepAlive(keep)
runtime.KeepAlive(cs)
return ok(r) && written
}
// PasteIsSafe reports whether pasting text cannot run a command by itself.
func PasteIsSafe(text string) bool {
if text == "" {
return true
}
b := []byte(text)
return cbool(call(fnPasteIsSafe, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b))))
}
+23
View File
@@ -0,0 +1,23 @@
//go:build (darwin && !ios) || (linux && !android && (amd64 || arm64)) || (windows && (amd64 || arm64))
package vt
import "github.com/ebitengine/purego"
// Supported reports whether the platform can load the library.
const Supported = true
// call calls a C function whose arguments are integers or pointers. Go
// pointers converted in the call, as in uintptr(unsafe.Pointer(&x)), are
// moved to the heap and kept alive until it returns (go:uintptrescapes):
// otherwise stack growth could move x while the library uses it.
//
//go:uintptrescapes
func call(fn uintptr, args ...uintptr) uintptr {
r, _, _ := purego.SyscallN(fn, args...)
return r
}
func registerFunc(fptr any, addr uintptr) { purego.RegisterFunc(fptr, addr) }
func newCallback(fn any) uintptr { return purego.NewCallback(fn) }
@@ -0,0 +1,18 @@
//go:build !(darwin && !ios) && !(linux && !android && (amd64 || arm64)) && !(windows && (amd64 || arm64))
package vt
import "errors"
// Supported reports whether the platform can load the library.
const Supported = false
func open(string) (uintptr, error) { return 0, errors.ErrUnsupported }
func sym(uintptr, string) (uintptr, error) { return 0, errors.ErrUnsupported }
func call(uintptr, ...uintptr) uintptr { panic("vt: libghostty-vt is not supported on this platform") }
func registerFunc(any, uintptr) {}
func newCallback(any) uintptr { return 0 }
+266
View File
@@ -0,0 +1,266 @@
package vt
import (
"bytes"
"image"
"image/draw"
"image/png"
"unsafe"
)
// Data of the Kitty graphics protocol's images (GhosttyKittyGraphicsData,
// GhosttyKittyGraphicsImageData, GhosttyKittyGraphicsPlacementData).
const (
dataKittyGraphics = 30
kittyPlacementIterator = 1
imageWidth = 3
imageHeight = 4
imageFormat = 5
imageData = 7
imageDataLen = 8
imageGeneration = 9
placementImageID = 1
placementID = 2
placementVirtual = 3
placementXOffset = 4
placementYOffset = 5
placementColumns = 10
placementRows = 11
placementZ = 12
placementSourceX = 6
placementSourceY = 7
placementSourceW = 8
placementSourceH = 9
)
// ImageFormat is how an image's pixels are laid out (GhosttyKittyImageFormat).
type ImageFormat int32
// Image formats: PNG is decoded to RGBA as an image arrives.
const (
ImageRGB ImageFormat = 0
ImageRGBA ImageFormat = 1
ImageGrayAlpha ImageFormat = 3
ImageGray ImageFormat = 4
)
// SetImageLimit sets how many bytes the images of the Kitty graphics
// protocol may take, zero refusing them (and deleting those there are).
func (t *Terminal) SetImageLimit(bytes uint64) {
t.set(optKittyImageLimit, unsafe.Pointer(&bytes))
}
// Image is an image of the Kitty graphics protocol.
type Image struct {
ID uint32
Width, Height int
Format ImageFormat
// Pixels are the image's, decoded; Generation changes when they do.
Pixels []byte
Generation uint64
}
// Placement is where a program placed an image (Kitty graphics), as the
// screen shows it now.
type Placement struct {
ImageID, ID uint32
// Virtual tells that the placement shows through the cells of Unicode
// placeholders rather than where it is placed.
Virtual bool
// Col and Row are its top left cell on the screen, Row negative when
// its top scrolled off; Visible tells that some of it shows.
Col, Row int
Visible bool
// XOffset and YOffset place it within its first cell, in pixels;
// Width and Height are the pixels it takes on the screen, Cols and Rows
// the cells.
XOffset, YOffset int
Width, Height int
Cols, Rows int
// SrcX, SrcY, SrcW and SrcH are the part of the image it shows, in the
// image's pixels.
SrcX, SrcY, SrcW, SrcH int
// Z orders it: below the cells' backgrounds when below -1<<30, below
// the text when negative, above it otherwise.
Z int32
// Params are the placement as a program asked for it: offsets, the
// part of the image and the cells, 0 for what the image gives.
ParamCols, ParamRows int
ParamSrcX, ParamSrcY, ParamSrcW, ParamSrcH int
}
// renderInfo is a GhosttyKittyGraphicsPlacementRenderInfo.
type renderInfo struct {
size uintptr
pixelWidth, pixelHeight, gridCols, gridRows uint32
viewportCol, viewportRow int32
viewportVisible bool
sourceX, sourceY, sourceW, sourceH uint32
}
// graphics returns the image storage of the screen that shows, 0 without
// one.
func (t *Terminal) graphics() uintptr {
var g uintptr
if t.get(dataKittyGraphics, unsafe.Pointer(&g)) != nil {
return 0
}
return g
}
// Placements calls fn with each placement of the screen that shows.
func (t *Terminal) Placements(fn func(Placement)) {
g := t.graphics()
if g == 0 {
return
}
var it uintptr
if !ok(call(fnPlacementIteratorNew, 0, uintptr(unsafe.Pointer(&it)))) || it == 0 {
return
}
defer call(fnPlacementIteratorFree, it)
if !ok(call(fnKittyGet, g, kittyPlacementIterator, uintptr(unsafe.Pointer(&it)))) {
return
}
u32 := func(data int) int {
var v uint32
call(fnPlacementGet, it, uintptr(data), uintptr(unsafe.Pointer(&v)))
return int(v)
}
for cbool(call(fnPlacementNext, it)) {
var p Placement
p.ImageID, p.ID = uint32(u32(placementImageID)), uint32(u32(placementID))
call(fnPlacementGet, it, placementVirtual, uintptr(unsafe.Pointer(&p.Virtual)))
call(fnPlacementGet, it, placementZ, uintptr(unsafe.Pointer(&p.Z)))
p.XOffset, p.YOffset = u32(placementXOffset), u32(placementYOffset)
p.ParamCols, p.ParamRows = u32(placementColumns), u32(placementRows)
p.ParamSrcX, p.ParamSrcY = u32(placementSourceX), u32(placementSourceY)
p.ParamSrcW, p.ParamSrcH = u32(placementSourceW), u32(placementSourceH)
img := call(fnKittyImage, g, uintptr(p.ImageID))
if img != 0 {
ri := renderInfo{size: unsafe.Sizeof(renderInfo{})}
if ok(call(fnPlacementRenderInfo, it, img, t.h, uintptr(unsafe.Pointer(&ri)))) {
p.Col, p.Row, p.Visible = int(ri.viewportCol), int(ri.viewportRow), ri.viewportVisible
p.Width, p.Height = int(ri.pixelWidth), int(ri.pixelHeight)
p.Cols, p.Rows = int(ri.gridCols), int(ri.gridRows)
p.SrcX, p.SrcY, p.SrcW, p.SrcH = int(ri.sourceX), int(ri.sourceY), int(ri.sourceW), int(ri.sourceH)
}
}
fn(p)
}
}
// ImageGeneration returns the generation of an image, 0 when there is no
// such image or its pixels have yet to arrive.
func (t *Terminal) ImageGeneration(id uint32) uint64 {
img := t.image(id)
if img == 0 {
return 0
}
var gen uint64
var p uintptr
if !ok(call(fnKittyImageGet, img, imageData, uintptr(unsafe.Pointer(&p)))) || p == 0 {
return 0
}
call(fnKittyImageGet, img, imageGeneration, uintptr(unsafe.Pointer(&gen)))
return gen
}
func (t *Terminal) image(id uint32) uintptr {
g := t.graphics()
if g == 0 {
return 0
}
return call(fnKittyImage, g, uintptr(id))
}
// Image returns an image, its pixels copied; false when there is no such
// image or its pixels have yet to arrive.
func (t *Terminal) Image(id uint32) (Image, bool) {
img := t.image(id)
if img == 0 {
return Image{}, false
}
var w, h uint32
var format int32
var p, n uintptr
var gen uint64
call(fnKittyImageGet, img, imageWidth, uintptr(unsafe.Pointer(&w)))
call(fnKittyImageGet, img, imageHeight, uintptr(unsafe.Pointer(&h)))
call(fnKittyImageGet, img, imageFormat, uintptr(unsafe.Pointer(&format)))
call(fnKittyImageGet, img, imageGeneration, uintptr(unsafe.Pointer(&gen)))
if !ok(call(fnKittyImageGet, img, imageData, uintptr(unsafe.Pointer(&p)))) || p == 0 {
return Image{}, false
}
call(fnKittyImageGet, img, imageDataLen, uintptr(unsafe.Pointer(&n)))
pixels := make([]byte, n)
copy(pixels, unsafe.Slice((*byte)(mem(p)), n))
return Image{ID: id, Width: int(w), Height: int(h), Format: ImageFormat(format), Pixels: pixels, Generation: gen}, true
}
// sysDecodePNG is GHOSTTY_SYS_OPT_DECODE_PNG.
const sysDecodePNG = 1
// sysImage is a GhosttySysImage: a PNG decoded, its pixels RGBA in memory
// of the library's allocator.
type sysImage struct {
width, height uint32
data, dataLen uintptr
}
// Ghostty's limits on an image, as Kitty's: no side longer than
// maxImageSide pixels, and no more than maxImageBytes of pixels.
const (
maxImageSide = 10000
maxImageBytes = 400 << 20
)
// imageFits reports whether an image of w×h RGBA pixels is within
// Ghostty's limits.
func imageFits(w, h int) bool {
return w > 0 && h > 0 && w <= maxImageSide && h <= maxImageSide && 4*w*h <= maxImageBytes
}
// decodePNG gives the library a PNG decoder, without which it refuses
// images sent as PNG (Kitty graphics, f=100), as grok sends them. A PNG
// whose header gives it more pixels than Ghostty's limits take is refused
// before it is decoded, as its size is the program's to claim; the pixels
// are converted into the library's memory, with no copy of them between.
func decodePNG() {
cb := newCallback(func(_, alloc, data, n, out uintptr) uintptr {
if data == 0 || n == 0 {
return 0
}
src := unsafe.Slice((*byte)(mem(data)), n)
cfg, err := png.DecodeConfig(bytes.NewReader(src))
if err != nil || !imageFits(cfg.Width, cfg.Height) {
return 0
}
img, err := png.Decode(bytes.NewReader(src))
if err != nil {
return 0
}
b := img.Bounds()
w, h := b.Dx(), b.Dy()
if !imageFits(w, h) {
return 0
}
size := uintptr(4 * w * h)
p := call(fnAlloc, alloc, size)
if p == 0 {
return 0
}
dst := &image.NRGBA{Pix: unsafe.Slice((*byte)(mem(p)), size), Stride: 4 * w, Rect: image.Rect(0, 0, w, h)}
if nrgba, ok := img.(*image.NRGBA); ok && nrgba.Stride == 4*w && b.Min == (image.Point{}) {
copy(dst.Pix, nrgba.Pix)
} else {
draw.Draw(dst, dst.Rect, img, b.Min, draw.Src)
}
*(*sysImage)(mem(out)) = sysImage{width: uint32(w), height: uint32(h), data: p, dataLen: size}
return 1
})
call(fnSysSet, sysDecodePNG, cb)
}
@@ -0,0 +1,133 @@
package vt
import (
"bytes"
"compress/zlib"
"encoding/base64"
"encoding/binary"
"fmt"
"hash/crc32"
"image"
"image/color"
"image/draw"
"image/png"
"runtime"
"testing"
)
// sendPNG transmits a PNG as an image of the Kitty graphics protocol
// (f=100), in chunks.
func sendPNG(term *Terminal, id int, data []byte) {
enc := base64.StdEncoding.EncodeToString(data)
var b bytes.Buffer
for i := 0; i == 0 || i < len(enc); i += 4096 {
more := 0
if i+4096 < len(enc) {
more = 1
}
part := enc[i:min(i+4096, len(enc))]
if i == 0 {
fmt.Fprintf(&b, "\x1b_Ga=t,f=100,i=%d,q=2,m=%d;%s\x1b\\", id, more, part)
} else {
fmt.Fprintf(&b, "\x1b_Gm=%d;%s\x1b\\", more, part)
}
}
term.Write(b.Bytes())
}
// pngClaiming returns a PNG whose header claims w×h gray pixels, with
// almost none of them.
func pngClaiming(w, h int) []byte {
var b bytes.Buffer
b.WriteString("\x89PNG\r\n\x1a\n")
chunk := func(typ string, data []byte) {
binary.Write(&b, binary.BigEndian, uint32(len(data)))
b.WriteString(typ)
b.Write(data)
binary.Write(&b, binary.BigEndian, crc32.ChecksumIEEE(append([]byte(typ), data...)))
}
ihdr := binary.BigEndian.AppendUint32(nil, uint32(w))
ihdr = binary.BigEndian.AppendUint32(ihdr, uint32(h))
chunk("IHDR", append(ihdr, 8, 0, 0, 0, 0)) // 8-bit gray
var z bytes.Buffer
zw := zlib.NewWriter(&z)
zw.Write(make([]byte, 64))
zw.Close()
chunk("IDAT", z.Bytes())
chunk("IEND", nil)
return b.Bytes()
}
// PNGs of every kind decode to RGBA, and one that claims more pixels than
// Ghostty takes is refused before it is decoded.
func TestPNGLimits(t *testing.T) {
loadLib(t)
term, err := NewTerminal(20, 5, Effects{})
if err != nil {
t.Fatal(err)
}
defer term.Free()
term.SetImageLimit(320 << 20)
r := image.Rect(0, 0, 3, 2)
nrgba := image.NewNRGBA(r)
rgb := image.NewRGBA(r)
gray := image.NewGray(r)
pal := image.NewPaletted(r, color.Palette{color.NRGBA{1, 2, 3, 255}, color.NRGBA{200, 100, 50, 128}})
deep := image.NewNRGBA64(r)
for y := range 2 {
for x := range 3 {
c := color.NRGBA{uint8(40 * x), uint8(90 * y), 77, uint8(100 + 50*x)}
nrgba.SetNRGBA(x, y, c)
rgb.Set(x, y, color.NRGBA{c.R, c.G, c.B, 255})
gray.SetGray(x, y, color.Gray{uint8(60*x + 30*y)})
pal.SetColorIndex(x, y, uint8((x+y)%2))
deep.Set(x, y, c)
}
}
for i, img := range []image.Image{nrgba, rgb, gray, pal, deep} {
var b bytes.Buffer
if err := png.Encode(&b, img); err != nil {
t.Fatal(err)
}
id := i + 1
sendPNG(term, id, b.Bytes())
got, ok := term.Image(uint32(id))
if !ok {
t.Errorf("image %d (%T) refused", id, img)
continue
}
want := image.NewNRGBA(r)
draw.Draw(want, r, img, image.Point{}, draw.Src)
if got.Format != ImageRGBA || got.Width != 3 || got.Height != 2 || !bytes.Equal(got.Pixels, want.Pix) {
t.Errorf("image %d (%T): format %d, %d×%d, pixels %v, want %v", id, img, got.Format, got.Width, got.Height, got.Pixels, want.Pix)
}
}
// Ghostty's limits: no side over 10000 pixels.
var b bytes.Buffer
png.Encode(&b, image.NewGray(image.Rect(0, 0, maxImageSide+1, 1)))
sendPNG(term, 10, b.Bytes())
if _, ok := term.Image(10); ok {
t.Error("an image 10001 pixels wide was taken")
}
b.Reset()
png.Encode(&b, image.NewGray(image.Rect(0, 0, maxImageSide, 1)))
sendPNG(term, 11, b.Bytes())
if _, ok := term.Image(11); !ok {
t.Error("an image 10000 pixels wide was refused")
}
// A header that claims 20000×20000 pixels, which decoding would
// allocate before reading them: refused with next to no memory.
var before, after runtime.MemStats
runtime.ReadMemStats(&before)
sendPNG(term, 12, pngClaiming(20000, 20000))
runtime.ReadMemStats(&after)
if _, ok := term.Image(12); ok {
t.Error("an image of 20000×20000 pixels was taken")
}
if n := after.TotalAlloc - before.TotalAlloc; n > 16<<20 {
t.Errorf("refusing it allocated %d MB", n>>20)
}
}
+456
View File
@@ -0,0 +1,456 @@
// Package vt binds libghostty-vt, the terminal emulator of Ghostty, which
// it loads at run time through purego: no cgo. It mirrors the structs of
// the C API it passes, checks them against the layouts the library
// describes (ghostty_type_json) as it loads, and reads packed cells by the
// bit positions the library reports, so that a library of another version
// fails to load instead of corrupting memory.
//
// Nothing here is safe for concurrent use: callers serialize the calls on a
// Terminal and on what is made from it.
package vt
import (
"encoding/json/v2"
"errors"
"fmt"
"sync"
"unsafe"
)
var lib struct {
mu sync.Mutex
loaded bool
err error
}
// Symbols called with integer and pointer arguments only, through call.
var (
fnTerminalNew, fnTerminalFree, fnTerminalReset, fnTerminalResize, fnTerminalSet, fnTerminalGet,
fnTerminalVTWrite, fnTerminalCompress, fnTerminalCompressionActivity uintptr
fnRenderStateNew, fnRenderStateFree, fnRenderStateBeginUpdate, fnRenderStateEndUpdate, fnRenderStateClean,
fnRenderStateGet, fnRowIteratorNew, fnRowIteratorFree, fnRowIteratorNext, fnRowGet,
fnRowCellsNew, fnRowCellsFree, fnRowCellsSelect, fnRowCellsGet uintptr
fnKeyEncoderNew, fnKeyEncoderFree, fnKeyEncoderSetopt, fnKeyEncoderSetoptFromTerminal, fnKeyEncoderEncode,
fnKeyEventNew, fnKeyEventFree, fnKeyEventSetAction, fnKeyEventSetKey, fnKeyEventSetMods,
fnKeyEventSetConsumedMods, fnKeyEventSetComposing, fnKeyEventSetUTF8, fnKeyEventSetUnshifted uintptr
fnMouseEncoderNew, fnMouseEncoderFree, fnMouseEncoderSetopt, fnMouseEncoderSetoptFromTerminal,
fnMouseEncoderReset, fnMouseEncoderEncode, fnMouseEventNew, fnMouseEventFree, fnMouseEventSetAction,
fnMouseEventSetButton, fnMouseEventClearButton, fnMouseEventSetMods uintptr
fnFocusEncode, fnPasteEncode, fnPasteIsSafe, fnTerminalPaste, fnFree uintptr
fnGestureNew, fnGestureFree, fnGestureReset, fnGestureGet, fnGestureEventNew, fnGestureEventFree,
fnGestureEventSet, fnGestureEvent, fnSelectAll uintptr
fnGridRefHyperlinkURI, fnGridRefGraphemes, fnGridRefCell, fnGridRefRow, fnRowData, fnTypeJSON, fnFormatterFormatAlloc, fnFormatterFree uintptr
fnSearchNew, fnSearchFree, fnSearchSet, fnSearchGet, fnSearchFeed, fnSearchTick, fnPointFromGridRef uintptr
fnKittyGet, fnKittyImage, fnKittyImageGet, fnPlacementIteratorNew, fnPlacementIteratorFree,
fnPlacementNext, fnPlacementGet, fnPlacementRenderInfo, fnSysSet, fnAlloc uintptr
// Bound with registerFunc below: they take structs or floats.
fnTerminalScrollViewport, fnTerminalGridRef, fnMouseEventSetPosition, fnSelectionFormatAlloc, fnFormatterTerminalNew uintptr
)
// Functions taking structs or floats by value, which purego passes as the
// platform's C ABI does.
var (
terminalScrollViewport func(t uintptr, v scrollViewport)
terminalGridRef func(t uintptr, p point, out *GridRef) int32
mouseEventSetPosition func(ev uintptr, pos mousePosition)
selectionFormatAlloc func(t uintptr, alloc uintptr, opts selectionFormatOptions, out *uintptr, n *uintptr) int32
formatterTerminalNew func(alloc uintptr, out *uintptr, t uintptr, opts formatterOptions) int32
)
var symbols = []struct {
name string
addr *uintptr
}{
{"ghostty_terminal_new", &fnTerminalNew},
{"ghostty_terminal_free", &fnTerminalFree},
{"ghostty_terminal_reset", &fnTerminalReset},
{"ghostty_terminal_resize", &fnTerminalResize},
{"ghostty_terminal_set", &fnTerminalSet},
{"ghostty_terminal_get", &fnTerminalGet},
{"ghostty_terminal_vt_write", &fnTerminalVTWrite},
{"ghostty_terminal_compress", &fnTerminalCompress},
{"ghostty_terminal_compression_activity", &fnTerminalCompressionActivity},
{"ghostty_terminal_scroll_viewport", &fnTerminalScrollViewport},
{"ghostty_terminal_grid_ref", &fnTerminalGridRef},
{"ghostty_render_state_new", &fnRenderStateNew},
{"ghostty_render_state_free", &fnRenderStateFree},
{"ghostty_render_state_begin_update", &fnRenderStateBeginUpdate},
{"ghostty_render_state_end_update", &fnRenderStateEndUpdate},
{"ghostty_render_state_clean", &fnRenderStateClean},
{"ghostty_render_state_get", &fnRenderStateGet},
{"ghostty_render_state_row_iterator_new", &fnRowIteratorNew},
{"ghostty_render_state_row_iterator_free", &fnRowIteratorFree},
{"ghostty_render_state_row_iterator_next", &fnRowIteratorNext},
{"ghostty_render_state_row_get", &fnRowGet},
{"ghostty_render_state_row_cells_new", &fnRowCellsNew},
{"ghostty_render_state_row_cells_free", &fnRowCellsFree},
{"ghostty_render_state_row_cells_select", &fnRowCellsSelect},
{"ghostty_render_state_row_cells_get", &fnRowCellsGet},
{"ghostty_key_encoder_new", &fnKeyEncoderNew},
{"ghostty_key_encoder_free", &fnKeyEncoderFree},
{"ghostty_key_encoder_setopt", &fnKeyEncoderSetopt},
{"ghostty_key_encoder_setopt_from_terminal", &fnKeyEncoderSetoptFromTerminal},
{"ghostty_key_encoder_encode", &fnKeyEncoderEncode},
{"ghostty_key_event_new", &fnKeyEventNew},
{"ghostty_key_event_free", &fnKeyEventFree},
{"ghostty_key_event_set_action", &fnKeyEventSetAction},
{"ghostty_key_event_set_key", &fnKeyEventSetKey},
{"ghostty_key_event_set_mods", &fnKeyEventSetMods},
{"ghostty_key_event_set_consumed_mods", &fnKeyEventSetConsumedMods},
{"ghostty_key_event_set_composing", &fnKeyEventSetComposing},
{"ghostty_key_event_set_utf8", &fnKeyEventSetUTF8},
{"ghostty_key_event_set_unshifted_codepoint", &fnKeyEventSetUnshifted},
{"ghostty_mouse_encoder_new", &fnMouseEncoderNew},
{"ghostty_mouse_encoder_free", &fnMouseEncoderFree},
{"ghostty_mouse_encoder_setopt", &fnMouseEncoderSetopt},
{"ghostty_mouse_encoder_setopt_from_terminal", &fnMouseEncoderSetoptFromTerminal},
{"ghostty_mouse_encoder_reset", &fnMouseEncoderReset},
{"ghostty_mouse_encoder_encode", &fnMouseEncoderEncode},
{"ghostty_mouse_event_new", &fnMouseEventNew},
{"ghostty_mouse_event_free", &fnMouseEventFree},
{"ghostty_mouse_event_set_action", &fnMouseEventSetAction},
{"ghostty_mouse_event_set_button", &fnMouseEventSetButton},
{"ghostty_mouse_event_clear_button", &fnMouseEventClearButton},
{"ghostty_mouse_event_set_mods", &fnMouseEventSetMods},
{"ghostty_mouse_event_set_position", &fnMouseEventSetPosition},
{"ghostty_focus_encode", &fnFocusEncode},
{"ghostty_paste_encode", &fnPasteEncode},
{"ghostty_terminal_paste", &fnTerminalPaste},
{"ghostty_paste_is_safe", &fnPasteIsSafe},
{"ghostty_free", &fnFree},
{"ghostty_selection_gesture_new", &fnGestureNew},
{"ghostty_selection_gesture_free", &fnGestureFree},
{"ghostty_selection_gesture_reset", &fnGestureReset},
{"ghostty_selection_gesture_get", &fnGestureGet},
{"ghostty_kitty_graphics_get", &fnKittyGet},
{"ghostty_kitty_graphics_image", &fnKittyImage},
{"ghostty_kitty_graphics_image_get", &fnKittyImageGet},
{"ghostty_kitty_graphics_placement_iterator_new", &fnPlacementIteratorNew},
{"ghostty_kitty_graphics_placement_iterator_free", &fnPlacementIteratorFree},
{"ghostty_kitty_graphics_placement_next", &fnPlacementNext},
{"ghostty_kitty_graphics_placement_get", &fnPlacementGet},
{"ghostty_kitty_graphics_placement_render_info", &fnPlacementRenderInfo},
{"ghostty_sys_set", &fnSysSet},
{"ghostty_alloc", &fnAlloc},
{"ghostty_selection_gesture_event_new", &fnGestureEventNew},
{"ghostty_selection_gesture_event_free", &fnGestureEventFree},
{"ghostty_selection_gesture_event_set", &fnGestureEventSet},
{"ghostty_selection_gesture_event", &fnGestureEvent},
{"ghostty_terminal_select_all", &fnSelectAll},
{"ghostty_terminal_selection_format_alloc", &fnSelectionFormatAlloc},
{"ghostty_grid_ref_hyperlink_uri", &fnGridRefHyperlinkURI},
{"ghostty_grid_ref_graphemes", &fnGridRefGraphemes},
{"ghostty_grid_ref_cell", &fnGridRefCell},
{"ghostty_grid_ref_row", &fnGridRefRow},
{"ghostty_row_get", &fnRowData},
{"ghostty_type_json", &fnTypeJSON},
{"ghostty_formatter_terminal_new", &fnFormatterTerminalNew},
{"ghostty_formatter_format_alloc", &fnFormatterFormatAlloc},
{"ghostty_formatter_free", &fnFormatterFree},
{"ghostty_search_new", &fnSearchNew},
{"ghostty_search_free", &fnSearchFree},
{"ghostty_search_set", &fnSearchSet},
{"ghostty_search_get", &fnSearchGet},
{"ghostty_search_feed", &fnSearchFeed},
{"ghostty_search_tick", &fnSearchTick},
{"ghostty_terminal_point_from_grid_ref", &fnPointFromGridRef},
}
// Load loads the library at path. Only the first call loads one: later
// calls report how it went, whatever their path.
func Load(path string) error {
lib.mu.Lock()
defer lib.mu.Unlock()
if lib.loaded || lib.err != nil {
return lib.err
}
lib.err = load(path)
lib.loaded = lib.err == nil
return lib.err
}
func load(path string) error {
h, err := open(path)
if err != nil {
return fmt.Errorf("loading %s: %w", path, err)
}
for _, s := range symbols {
if *s.addr, err = sym(h, s.name); err != nil {
return fmt.Errorf("%s is not a libghostty-vt this package binds: %w", path, err)
}
}
if err := checkLayouts(); err != nil {
return fmt.Errorf("%s is not a libghostty-vt this package binds: %w", path, err)
}
registerFunc(&terminalScrollViewport, fnTerminalScrollViewport)
registerFunc(&terminalGridRef, fnTerminalGridRef)
registerFunc(&mouseEventSetPosition, fnMouseEventSetPosition)
registerFunc(&selectionFormatAlloc, fnSelectionFormatAlloc)
registerFunc(&formatterTerminalNew, fnFormatterTerminalNew)
makeCallbacks()
decodePNG()
return nil
}
// Loaded reports whether Load succeeded.
func Loaded() bool {
lib.mu.Lock()
defer lib.mu.Unlock()
return lib.loaded
}
// Result is a GhosttyResult other than GHOSTTY_SUCCESS.
type Result int32
const (
success Result = 0
OutOfMemory Result = -1
Invalid Result = -2
OutOfSpace Result = -3
NoValue Result = -4
IOError Result = -5
Exceeded Result = -6
Rejected Result = -7
)
func (r Result) Error() string {
switch r {
case OutOfMemory:
return "libghostty-vt: out of memory"
case Invalid:
return "libghostty-vt: invalid value"
case OutOfSpace:
return "libghostty-vt: out of space"
case NoValue:
return "libghostty-vt: no value"
case IOError:
return "libghostty-vt: I/O error"
case Exceeded:
return "libghostty-vt: limit exceeded"
case Rejected:
return "libghostty-vt: rejected"
}
return fmt.Sprintf("libghostty-vt: error %d", int32(r))
}
// result converts what a function returning GhosttyResult returned.
func result(r uintptr) error {
if v := Result(int32(r)); v != success {
return v
}
return nil
}
// ok reports whether a function returning GhosttyResult succeeded.
func ok(r uintptr) bool { return int32(r) == 0 }
// cbool reads a C bool returned in a register, whose upper bits are
// undefined.
func cbool(r uintptr) bool { return byte(r) != 0 }
func b2u(b bool) uintptr {
if b {
return 1
}
return 0
}
// mem converts an address the library gave into a pointer.
func mem(p uintptr) unsafe.Pointer { return *(*unsafe.Pointer)(unsafe.Pointer(&p)) }
// goString copies a string the library owns.
func goString(p, n uintptr) string {
if p == 0 || n == 0 {
return ""
}
return string(unsafe.Slice((*byte)(mem(p)), n))
}
// cStringAt copies a NUL-terminated string the library owns.
func cStringAt(p uintptr) string {
n := uintptr(0)
for *(*byte)(unsafe.Add(mem(p), n)) != 0 {
n++
}
return goString(p, n)
}
// cell is the layout of the packed GhosttyCell, from the manifest.
var cell struct {
tag, codepoint, styleID, wide, hyperlink bitField
// paletteIndex, r, g and b are the content of cells holding only a
// background color.
paletteIndex, r, g, b bitField
}
type bitField struct{ lsb, width uint }
func (f bitField) of(v uint64) uint64 { return v >> f.lsb & (1<<f.width - 1) }
// manifest is what ghostty_type_json describes.
type manifest struct {
ABI struct {
PointerSize int `json:"pointer_size"`
} `json:"abi"`
Types map[string]typeInfo `json:"types"`
}
type typeInfo struct {
Kind string `json:"kind"`
Size uintptr `json:"size"`
Fields map[string]fieldInfo `json:"fields"`
Bits map[string]bitInfo `json:"bits"`
Values map[string]int64 `json:"values"`
}
// enums are values of enums this package hardcodes, which the manifest
// must agree with.
var enums = []struct {
typ, name string
value int64
}{
{"GhosttyKey", "A", int64(KeyA)},
{"GhosttyKey", "ARROW_UP", int64(KeyArrowUp)},
{"GhosttyKey", "ESCAPE", int64(KeyEscape)},
{"GhosttyKey", "F1", int64(KeyF1)},
{"GhosttyKeyAction", "REPEAT", int64(KeyRepeat)},
{"GhosttyMouseAction", "MOTION", int64(MouseMotion)},
{"GhosttyMouseButton", "FIVE", WheelDown},
{"GhosttyRenderStateCursorVisualStyle", "BLOCK_HOLLOW", int64(CursorBlockHollow)},
{"GhosttyRenderStateDirty", "FULL", int64(Full)},
{"GhosttyTerminalData", "KITTY_GRAPHICS", dataKittyGraphics},
{"GhosttyTerminalData", "COLOR_FOREGROUND", dataColorFg},
{"GhosttyTerminalData", "COLOR_FOREGROUND_DEFAULT", dataColorFgDefault},
{"GhosttyTerminalData", "KITTY_KEYBOARD_FLAGS", dataKittyKeyboardFlags},
{"GhosttyTerminalData", "SCROLLBACK_ROWS", dataScrollbackRows},
{"GhosttyTerminalData", "MOUSE_TRACKING", dataMouseTracking},
{"GhosttyTerminalData", "MOUSE_SHAPE", dataMouseShape},
{"GhosttyRowData", "WRAP", rowDataWrap},
{"GhosttyRowData", "SEMANTIC_PROMPT", rowDataSemanticPrompt},
{"GhosttyRowSemanticPrompt", "PROMPT_CONTINUATION", int64(PromptContinuation)},
{"GhosttyRenderStateRowData", "RAW", rowDataRaw},
{"GhosttyKittyGraphicsPlacementData", "Z", placementZ},
{"GhosttyKittyGraphicsImageData", "GENERATION", imageGeneration},
{"GhosttyKittyImageFormat", "GRAY", int64(ImageGray)},
{"GhosttySysOption", "DECODE_PNG", sysDecodePNG},
{"GhosttyCellWide", "SPACER_HEAD", int64(SpacerHead)},
{"GhosttyStyleColorTag", "RGB", colorRGB},
{"GhosttySgrUnderline", "DASHED", UnderlineDashed},
{"GhosttyTerminalScrollViewportTag", "ROW", 3},
{"GhosttyPointTag", "VIEWPORT", 1},
{"GhosttyClipboardWriteResult", "UNSUPPORTED", 2},
{"GhosttySelectionGestureEventType", "DRAG", gestureDrag},
{"GhosttySearchStatus", "COMPLETE", int64(SearchComplete)},
{"GhosttySearchOption", "SELECT_PREV", searchOptSelectPrev},
{"GhosttySearchData", "VIEWPORT_MATCHES", searchDataViewportMatches},
{"GhosttySearchScroll", "NONE", searchScrollNone},
{"GhosttyPointTag", "SCREEN", pointScreen},
}
type fieldInfo struct {
Offset uintptr `json:"offset"`
}
type bitInfo struct {
LSB uint `json:"lsb"`
Width uint `json:"width"`
Arms map[string]*bitArms `json:"arms"`
}
type bitArms struct {
Bits map[string]bitInfo `json:"bits"`
}
// layout is a struct this package mirrors: its size and the offsets of
// its fields as Go lays them out.
type layout struct {
size uintptr
fields map[string]uintptr
}
// checkLayouts compares the structs of this package with the layouts the
// library reports, and reads the bit positions of packed cells.
func checkLayouts() error {
p := call(fnTypeJSON)
if p == 0 {
return errors.New("no type manifest")
}
var m manifest
if err := json.Unmarshal([]byte(cStringAt(p)), &m); err != nil {
return fmt.Errorf("type manifest: %w", err)
}
return m.check()
}
func (m *manifest) check() error {
if m.ABI.PointerSize != int(unsafe.Sizeof(uintptr(0))) {
return fmt.Errorf("built for %d-byte pointers", m.ABI.PointerSize)
}
for name, want := range layouts() {
t, ok := m.Types[name]
if !ok {
return fmt.Errorf("no type %s", name)
}
if t.Size != want.size {
return fmt.Errorf("%s is %d bytes, not %d", name, t.Size, want.size)
}
for field, off := range want.fields {
f, ok := t.Fields[field]
if !ok {
return fmt.Errorf("%s has no field %s", name, field)
}
if f.Offset != off {
return fmt.Errorf("%s.%s is at %d, not %d", name, field, f.Offset, off)
}
}
}
for _, e := range enums {
if v, ok := m.Types[e.typ].Values[e.name]; !ok || v != e.value {
return fmt.Errorf("%s %s is not %d", e.typ, e.name, e.value)
}
}
c, ok := m.Types["GhosttyCell"]
if !ok || c.Kind != "packed" || c.Size != 8 {
return errors.New("GhosttyCell is not a packed 64-bit value")
}
var errs []error
field := func(dst *bitField, name string) {
b, ok := c.Bits[name]
if !ok {
errs = append(errs, fmt.Errorf("GhosttyCell has no %s", name))
}
*dst = bitField{b.LSB, b.Width}
}
arm := func(dst *bitField, tag, name string) {
content := c.Bits["content"]
a := content.Arms[tag]
if a == nil {
errs = append(errs, fmt.Errorf("GhosttyCell content has no %s", tag))
return
}
b, ok := a.Bits[name]
if !ok {
errs = append(errs, fmt.Errorf("GhosttyCell content has no %s.%s", tag, name))
}
*dst = bitField{content.LSB + b.LSB, b.Width}
}
field(&cell.tag, "content_tag")
field(&cell.styleID, "style_id")
field(&cell.wide, "wide")
field(&cell.hyperlink, "hyperlink")
arm(&cell.codepoint, "CODEPOINT", "codepoint")
arm(&cell.paletteIndex, "BG_COLOR_PALETTE", "index")
arm(&cell.r, "BG_COLOR_RGB", "r")
arm(&cell.g, "BG_COLOR_RGB", "g")
arm(&cell.b, "BG_COLOR_RGB", "b")
return errors.Join(errs...)
}
@@ -0,0 +1,11 @@
//go:build (darwin && !ios) || (linux && !android && (amd64 || arm64))
package vt
import "github.com/ebitengine/purego"
func open(path string) (uintptr, error) {
return purego.Dlopen(path, purego.RTLD_NOW|purego.RTLD_LOCAL)
}
func sym(h uintptr, name string) (uintptr, error) { return purego.Dlsym(h, name) }
@@ -0,0 +1,14 @@
//go:build windows && (amd64 || arm64)
package vt
import "syscall"
func open(path string) (uintptr, error) {
h, err := syscall.LoadLibrary(path)
return uintptr(h), err
}
func sym(h uintptr, name string) (uintptr, error) {
return syscall.GetProcAddress(syscall.Handle(h), name)
}
+384
View File
@@ -0,0 +1,384 @@
package vt
import (
"fmt"
"strconv"
"strings"
"unsafe"
)
// RenderState is a GhosttyRenderState: what a frame draws of a terminal,
// copied from it by an update, with the rows that changed since the last
// frame marked dirty.
type RenderState struct {
h uintptr
rows uintptr // the row iterator
cells uintptr // the cells of the iterator's row
// raw holds the cells of the row read last.
raw []Cell
}
// Render state data (GhosttyRenderStateData and its row and cell kinds).
const (
rsDataCols = 1
rsDataRows = 2
rsDataDirty = 3
rsDataRowIterator = 4
rsDataCursor = 18
rsDataColors = 19
rowDataDirty = 1
rowDataRaw = 2
rowDataCells = 3
rowDataSelection = 4
rowDataCellsRaw = 5
rowDataID = 7
cellDataStyle = 2
cellDataGraphemesLen = 3
cellDataGraphemesBuf = 4
)
// NewRenderState makes an empty render state.
func NewRenderState() (*RenderState, error) {
r := &RenderState{}
if err := result(call(fnRenderStateNew, 0, uintptr(unsafe.Pointer(&r.h)))); err != nil {
return nil, err
}
if err := result(call(fnRowIteratorNew, 0, uintptr(unsafe.Pointer(&r.rows)))); err != nil {
r.Free()
return nil, err
}
if err := result(call(fnRowCellsNew, 0, uintptr(unsafe.Pointer(&r.cells)))); err != nil {
r.Free()
return nil, err
}
return r, nil
}
// Free frees the render state.
func (r *RenderState) Free() {
if r.cells != 0 {
call(fnRowCellsFree, r.cells)
}
if r.rows != 0 {
call(fnRowIteratorFree, r.rows)
}
if r.h != 0 {
call(fnRenderStateFree, r.h)
}
*r = RenderState{}
}
// BeginUpdate copies the terminal's state, the only step that needs the
// terminal; EndUpdate finishes the update without it.
func (r *RenderState) BeginUpdate(t *Terminal) error {
return result(call(fnRenderStateBeginUpdate, r.h, t.h))
}
// EndUpdate finishes the update BeginUpdate started.
func (r *RenderState) EndUpdate() { call(fnRenderStateEndUpdate, r.h) }
// Update updates the render state from the terminal in one step.
func (r *RenderState) Update(t *Terminal) error {
if err := r.BeginUpdate(t); err != nil {
return err
}
r.EndUpdate()
return nil
}
// Clean marks everything drawn.
func (r *RenderState) Clean() { call(fnRenderStateClean, r.h) }
func (r *RenderState) get(data int, out unsafe.Pointer) error {
return result(call(fnRenderStateGet, r.h, uintptr(data), uintptr(out)))
}
// Dirty is how much of a frame changed.
type Dirty int32
const (
Clean Dirty = iota
Partial
Full
)
// Dirty reports how much changed since the last Clean.
func (r *RenderState) Dirty() Dirty {
var d Dirty
r.get(rsDataDirty, unsafe.Pointer(&d))
return d
}
// Size returns the size of the viewport in cells.
func (r *RenderState) Size() (cols, rows int) {
var c, rr uint16
r.get(rsDataCols, unsafe.Pointer(&c))
r.get(rsDataRows, unsafe.Pointer(&rr))
return int(c), int(rr)
}
// Colors are the colors of a frame: those programs set, else the defaults.
type Colors struct {
Background, Foreground RGB
// Cursor is the cursor's color when HasCursor is set; it takes the
// text's otherwise.
Cursor RGB
HasCursor bool
Palette [256]RGB
}
// Colors returns the colors of the frame.
func (r *RenderState) Colors() Colors {
c := renderColors{size: unsafe.Sizeof(renderColors{})}
r.get(rsDataColors, unsafe.Pointer(&c))
return Colors{Background: c.background, Foreground: c.foreground, Cursor: c.cursor, HasCursor: c.cursorHasValue, Palette: c.palette}
}
// Cursor is the cursor of a frame.
type Cursor struct {
// InView reports that the cursor is in the viewport, at column X of
// row Y; WideTail that it is on the second half of a wide character.
InView bool
X, Y int
WideTail bool
// Visible reports that programs show the cursor, Blinking that it
// blinks, Password that the program reads a password.
Visible, Blinking, Password bool
Style CursorStyle
}
// Cursor returns the cursor of the frame.
func (r *RenderState) Cursor() Cursor {
c := renderCursor{size: unsafe.Sizeof(renderCursor{})}
r.get(rsDataCursor, unsafe.Pointer(&c))
return Cursor{
InView: c.viewportHasValue, X: int(c.viewportX), Y: int(c.viewportY), WideTail: c.wideTail,
Visible: c.visible, Blinking: c.blinking, Password: c.passwordInput, Style: CursorStyle(c.visualStyle),
}
}
// Rows starts going through the rows of the frame, top to bottom, with
// NextRow.
func (r *RenderState) Rows() { r.get(rsDataRowIterator, unsafe.Pointer(&r.rows)) }
// NextRow moves to the next row, and reports whether there is one.
func (r *RenderState) NextRow() bool { return cbool(call(fnRowIteratorNext, r.rows)) }
func (r *RenderState) rowGet(data int, out unsafe.Pointer) bool {
return ok(call(fnRowGet, r.rows, uintptr(data), uintptr(out)))
}
// RowDirty reports whether the row changed since the last Clean.
func (r *RenderState) RowDirty() bool {
var v bool
return r.rowGet(rowDataDirty, unsafe.Pointer(&v)) && v
}
// RowWrapped reports whether the row soft-wraps into the next.
func (r *RenderState) RowWrapped() bool {
var raw uint64
if !r.rowGet(rowDataRaw, unsafe.Pointer(&raw)) {
return false
}
var v bool
return ok(call(fnRowData, uintptr(raw), rowDataWrap, uintptr(unsafe.Pointer(&v)))) && v
}
// RowPrompt returns how the row belongs to a shell's prompt.
func (r *RenderState) RowPrompt() RowPrompt {
var raw uint64
if !r.rowGet(rowDataRaw, unsafe.Pointer(&raw)) {
return NoPrompt
}
v := NoPrompt
if !ok(call(fnRowData, uintptr(raw), rowDataSemanticPrompt, uintptr(unsafe.Pointer(&v)))) {
return NoPrompt
}
return v
}
// RowID returns the identity of the row, which it keeps as it scrolls.
func (r *RenderState) RowID() RowID {
var id RowID
r.rowGet(rowDataID, unsafe.Pointer(&id))
return id
}
// RowSelection returns the selected columns of the row, from start to end
// inclusive.
func (r *RenderState) RowSelection() (start, end int, ok bool) {
s := rowSelection{size: unsafe.Sizeof(rowSelection{})}
if !r.rowGet(rowDataSelection, unsafe.Pointer(&s)) {
return 0, 0, false
}
return int(s.startX), int(s.endX), true
}
// Wide is how wide a cell's character is.
type Wide uint8
const (
Narrow Wide = iota
// WideChar takes this cell and the next, a SpacerTail.
WideChar
SpacerTail
// SpacerHead ends a soft-wrapped row before a wide character that did
// not fit.
SpacerHead
)
// Cell is a cell of a row.
type Cell struct {
// Codepoint is the character, 0 for none; Grapheme reports more
// codepoints after it (CellGraphemes).
Codepoint rune
Grapheme bool
// Style identifies the cell's style (CellStyle) among the row's
// cells: 0 is the default.
Style uint16
Wide Wide
Hyperlink bool
// Background is the color of a cell without text whose background
// a program filled, when HasBackground; Palette tells that it is
// the palette's color of index Background.R.
Background RGB
HasBackground bool
Palette bool
}
// RowCells returns the cells of the row, valid until the next update.
func (r *RenderState) RowCells() []Cell {
var v cellsView
if !r.rowGet(rowDataCellsRaw, unsafe.Pointer(&v)) || v.ptr == 0 {
return nil
}
raw := unsafe.Slice((*uint64)(mem(v.ptr)), v.len)
r.raw = r.raw[:0]
for _, c := range raw {
var out Cell
switch cell.tag.of(c) {
case 0, 1: // a codepoint, of a grapheme cluster for 1
out.Codepoint = rune(cell.codepoint.of(c))
out.Grapheme = cell.tag.of(c) == 1
case 2:
out.HasBackground, out.Palette = true, true
out.Background.R = uint8(cell.paletteIndex.of(c))
case 3:
out.HasBackground = true
out.Background = RGB{uint8(cell.r.of(c)), uint8(cell.g.of(c)), uint8(cell.b.of(c))}
}
out.Style = uint16(cell.styleID.of(c))
out.Wide = Wide(cell.wide.of(c))
out.Hyperlink = cell.hyperlink.of(c) != 0
r.raw = append(r.raw, out)
}
// The cells of the row for the style and grapheme lookups.
r.rowGet(rowDataCells, unsafe.Pointer(&r.cells))
return r.raw
}
// Color is the color of a style: none (the default), an index of the
// palette, or an RGB color.
type Color struct {
Kind uint8 // 0 none, 1 palette, 2 RGB
Index uint8
RGB RGB
}
func (c styleColor) color() Color {
switch c.tag {
case colorPalette:
return Color{Kind: 1, Index: c.value[0]}
case colorRGB:
return Color{Kind: 2, RGB: RGB{c.value[0], c.value[1], c.value[2]}}
}
return Color{}
}
// Underline styles.
const (
UnderlineNone = iota
UnderlineSingle
UnderlineDouble
UnderlineCurly
UnderlineDotted
UnderlineDashed
)
// Style is how a cell's text shows.
type Style struct {
FG, BG, UnderlineColor Color
Bold, Italic, Faint, Blink, Inverse, Invisible, Strikethrough, Overline bool
Underline int
}
// SGR returns the SGR sequence that sets the style from none.
func (s Style) SGR() string {
p := []string{"0"}
add := func(on bool, code string) {
if on {
p = append(p, code)
}
}
add(s.Bold, "1")
add(s.Faint, "2")
add(s.Italic, "3")
switch s.Underline {
case UnderlineNone:
case UnderlineSingle:
p = append(p, "4")
default:
p = append(p, "4:"+strconv.Itoa(s.Underline))
}
add(s.Blink, "5")
add(s.Inverse, "7")
add(s.Invisible, "8")
add(s.Strikethrough, "9")
add(s.Overline, "53")
for _, c := range []struct {
c Color
base string
}{{s.FG, "38"}, {s.BG, "48"}, {s.UnderlineColor, "58"}} {
switch c.c.Kind {
case 1:
p = append(p, c.base+":5:"+strconv.Itoa(int(c.c.Index)))
case 2:
p = append(p, fmt.Sprintf("%s:2::%d:%d:%d", c.base, c.c.RGB.R, c.c.RGB.G, c.c.RGB.B))
}
}
return "\x1b[" + strings.Join(p, ";") + "m"
}
// CellStyle returns the style of cell x of the row RowCells read.
func (r *RenderState) CellStyle(x int) Style {
s := style{size: unsafe.Sizeof(style{})}
if ok(call(fnRowCellsSelect, r.cells, uintptr(x))) {
call(fnRowCellsGet, r.cells, cellDataStyle, uintptr(unsafe.Pointer(&s)))
}
return Style{
FG: s.fg.color(), BG: s.bg.color(), UnderlineColor: s.underlineColor.color(),
Bold: s.bold, Italic: s.italic, Faint: s.faint, Blink: s.blink, Inverse: s.inverse,
Invisible: s.invisible, Strikethrough: s.strikethrough, Overline: s.overline, Underline: int(s.underline),
}
}
// CellGraphemes appends the codepoints of cell x of the row RowCells read
// to buf.
func (r *RenderState) CellGraphemes(x int, buf []rune) []rune {
if !ok(call(fnRowCellsSelect, r.cells, uintptr(x))) {
return buf
}
var n uint32
call(fnRowCellsGet, r.cells, cellDataGraphemesLen, uintptr(unsafe.Pointer(&n)))
if n == 0 {
return buf
}
cps := make([]uint32, n)
call(fnRowCellsGet, r.cells, cellDataGraphemesBuf, uintptr(unsafe.Pointer(&cps[0])))
for _, c := range cps {
buf = append(buf, rune(c))
}
return buf
}
+50
View File
@@ -0,0 +1,50 @@
package vt
import (
"bytes"
"unsafe"
)
// What a Mirror reads of a terminal besides its rows, which a render state
// reads.
const (
rowDataWrap = 1
rowDataSemanticPrompt = 6
dataKittyKeyboardFlags = 8
dataScrollbackRows = 15
)
// ScrollbackRows returns how many rows the scrollback holds.
func (t *Terminal) ScrollbackRows() int {
var n uintptr
t.get(dataScrollbackRows, unsafe.Pointer(&n))
return int(n)
}
// KittyKeyboardFlags returns the flags of the kitty keyboard protocol
// programs set.
func (t *Terminal) KittyKeyboardFlags() int {
var f uint8
t.get(dataKittyKeyboardFlags, unsafe.Pointer(&f))
return int(f)
}
// ModifyOtherKeys reports whether xterm's modifyOtherKeys mode 2 is on
// (CSI > 4 ; 2 m). The library tells it in no GhosttyTerminalData, but a
// key encoder takes it from the terminal with the other modes: without the
// Kitty keyboard protocol, Ctrl+P is CSI 27 ; 5 ; 112 ~ in mode 2, and ^P
// otherwise.
func (t *Terminal) ModifyOtherKeys() bool {
e, err := NewKeyEncoder()
if err != nil {
return false
}
defer e.Free()
call(fnKeyEncoderSetoptFromTerminal, e.h, t.h)
var kitty uint8
call(fnKeyEncoderSetopt, e.h, 5, uintptr(unsafe.Pointer(&kitty)))
b := e.Encode(KeyEvent{Action: KeyPress, Key: KeyP, Mods: ModCtrl, Text: "p", Unshifted: 'p'})
return bytes.HasPrefix(b, []byte("\x1b[27;"))
}
+183
View File
@@ -0,0 +1,183 @@
package vt
import (
"runtime"
"unsafe"
)
// Search options and data (GhosttySearchOption, GhosttySearchData).
const (
searchOptNeedle = 0
searchOptSelectNext = 1
searchOptSelectPrev = 2
searchOptSelectScroll = 3
searchScrollNone = 1
searchDataStatus = 0
searchDataTotal = 2
searchDataSelectedIndex = 3
searchDataSelectedMatch = 4
searchDataViewportMatches = 6
)
// SearchStatus is how far a search went (GhosttySearchStatus).
type SearchStatus int32
const (
// SearchRunning: Tick makes progress.
SearchRunning SearchStatus = iota
// SearchFeedRequired: Feed must read the terminal first.
SearchFeedRequired
// SearchComplete: the search caught up with the terminal as of the
// last Feed.
SearchComplete
)
// Search searches a terminal, its scrollback included, for text, as
// Ghostty's find does: matches follow the screen as it changes, and the
// screens as programs switch them. Matching is exact but for ASCII letters,
// whose case it ignores.
type Search struct {
h uintptr
}
// selectionBuffer is a GhosttySelectionBuffer.
type selectionBuffer struct {
ptr *Selection
cap, len uintptr
}
// NewSearch makes a search of t, which looks for nothing until SetText.
// Selecting a match scrolls nothing: the caller shows it where it likes.
func NewSearch(t *Terminal) (*Search, error) {
s := &Search{}
if err := result(call(fnSearchNew, 0, uintptr(unsafe.Pointer(&s.h)), t.h)); err != nil {
return nil, err
}
none := int32(searchScrollNone)
call(fnSearchSet, s.h, searchOptSelectScroll, uintptr(unsafe.Pointer(&none)))
return s, nil
}
// Free frees the search, before or after its terminal.
func (s *Search) Free() {
if s.h != 0 {
call(fnSearchFree, s.h)
s.h = 0
}
}
// SetText searches for text from scratch, or keeps the matches when it is
// the text searched already; "" searches for nothing.
func (s *Search) SetText(text string) {
b := []byte(text)
cs := cBytes(b)
call(fnSearchSet, s.h, searchOptNeedle, uintptr(unsafe.Pointer(&cs)))
runtime.KeepAlive(b)
}
// Feed reads what changed of the terminal, a bounded amount at a time.
func (s *Search) Feed() { call(fnSearchFeed, s.h) }
// Tick makes a bounded amount of progress, without the terminal.
func (s *Search) Tick() SearchStatus {
st := SearchComplete
call(fnSearchTick, s.h, uintptr(unsafe.Pointer(&st)))
return st
}
// Status returns how far the search went.
func (s *Search) Status() SearchStatus {
st := SearchComplete
call(fnSearchGet, s.h, searchDataStatus, uintptr(unsafe.Pointer(&st)))
return st
}
// Total returns how many matches the search found so far.
func (s *Search) Total() int {
var n uintptr
call(fnSearchGet, s.h, searchDataTotal, uintptr(unsafe.Pointer(&n)))
return int(n)
}
// Selected returns the index of the selected match, 0 the newest, and
// reports whether one is.
func (s *Search) Selected() (int, bool) {
var i uintptr
return int(i), ok(call(fnSearchGet, s.h, searchDataSelectedIndex, uintptr(unsafe.Pointer(&i))))
}
// SelectedMatch returns the selected match.
func (s *Search) SelectedMatch() (Selection, bool) {
m := Selection{size: unsafe.Sizeof(Selection{})}
return m, ok(call(fnSearchGet, s.h, searchDataSelectedMatch, uintptr(unsafe.Pointer(&m))))
}
// Select selects the next match toward older output, or toward newer
// output when back, wrapping around. It reports whether there was a match.
func (s *Search) Select(back bool) bool {
opt := uintptr(searchOptSelectNext)
if back {
opt = searchOptSelectPrev
}
return ok(call(fnSearchSet, s.h, opt, 0))
}
// ViewportMatches returns the matches on the pages the viewport shows, as
// of the last Feed, in buf's memory when it has room.
func (s *Search) ViewportMatches(buf []Selection) []Selection {
for {
buf = buf[:cap(buf)]
for i := range buf {
buf[i].size = unsafe.Sizeof(Selection{})
}
b := selectionBuffer{cap: uintptr(len(buf))}
if len(buf) > 0 {
b.ptr = &buf[0]
}
r := Result(int32(call(fnSearchGet, s.h, searchDataViewportMatches, uintptr(unsafe.Pointer(&b)))))
switch {
case r == success:
return buf[:b.len]
case r == OutOfSpace && int(b.len) > len(buf):
buf = make([]Selection, b.len)
default:
return buf[:0]
}
}
}
// ViewportPoint returns the column and the row of the viewport of a cell,
// and reports whether the viewport shows it.
func (t *Terminal) ViewportPoint(ref *GridRef) (x, y int, shown bool) {
return t.pointOf(ref, pointViewport)
}
// ScreenRow returns the row of a cell among those of the screen and its
// scrollback, 0 the oldest, as ScrollToRow takes it.
func (t *Terminal) ScreenRow(ref *GridRef) (int, bool) {
_, y, found := t.pointOf(ref, pointScreen)
return y, found
}
// GhosttyPointTag's coordinate systems.
const (
pointViewport = 1
pointScreen = 2
)
func (t *Terminal) pointOf(ref *GridRef, tag uintptr) (x, y int, found bool) {
var p struct {
x uint16
_ uint16
y uint32
}
if !ok(call(fnPointFromGridRef, t.h, uintptr(unsafe.Pointer(ref)), tag, uintptr(unsafe.Pointer(&p)))) {
return 0, 0, false
}
return int(p.x), int(p.y), true
}
// Ends returns the cells a selection starts and ends at.
func (s *Selection) Ends() (start, end *GridRef) { return &s.start, &s.end }
@@ -0,0 +1,150 @@
package vt
import "unsafe"
// Selection gesture events, options and data (GhosttySelectionGesture*).
const (
gesturePress = 0
gestureRelease = 1
gestureDrag = 2
gestureAutoTick = 3
gestureOptRef = 0
gestureOptPosition = 1
gestureOptRepeatDistance = 2
gestureOptTime = 3
gestureOptRepeatInterval = 4
gestureOptRectangle = 7
gestureOptGeometry = 8
gestureOptViewport = 9
gestureDataDragged = 1
gestureDataAutoscroll = 2
)
// Gesture turns presses and drags of the pointer into selections as
// Ghostty does: a click and a drag select cells, a double click words and
// a triple click lines, and dragging past the top or the bottom asks to
// scroll.
type Gesture struct {
h uintptr
press, release, drag, tick uintptr
}
// Geometry is the grid in pixels, for drags.
type Geometry struct {
Columns, CellWidth, PadLeft, Height int
}
// NewGesture makes a gesture: repeated clicks count within interval
// nanoseconds of each other and distance pixels.
func NewGesture(interval uint64, distance float64) (*Gesture, error) {
g := &Gesture{}
if err := result(call(fnGestureNew, 0, uintptr(unsafe.Pointer(&g.h)))); err != nil {
return nil, err
}
for _, e := range []struct {
h *uintptr
typ int
}{{&g.press, gesturePress}, {&g.release, gestureRelease}, {&g.drag, gestureDrag}, {&g.tick, gestureAutoTick}} {
if err := result(call(fnGestureEventNew, 0, uintptr(unsafe.Pointer(e.h)), uintptr(e.typ))); err != nil {
g.Free(nil)
return nil, err
}
}
call(fnGestureEventSet, g.press, gestureOptRepeatInterval, uintptr(unsafe.Pointer(&interval)))
call(fnGestureEventSet, g.press, gestureOptRepeatDistance, uintptr(unsafe.Pointer(&distance)))
return g, nil
}
// Free frees the gesture, which belongs to t (nil if it was never used).
func (g *Gesture) Free(t *Terminal) {
for _, e := range []uintptr{g.press, g.release, g.drag, g.tick} {
if e != 0 {
call(fnGestureEventFree, e)
}
}
if g.h != 0 {
th := uintptr(0)
if t != nil {
th = t.h
}
call(fnGestureFree, g.h, th)
}
*g = Gesture{}
}
func (g *Gesture) apply(t *Terminal, ev uintptr) (Selection, bool) {
s := Selection{size: unsafe.Sizeof(Selection{})}
return s, ok(call(fnGestureEvent, g.h, t.h, ev, uintptr(unsafe.Pointer(&s))))
}
// Press presses the pointer on cell ref at x, y pixels, at time ns of a
// monotonic clock. A double or triple click selects at once.
func (g *Gesture) Press(t *Terminal, ref GridRef, x, y float64, ns uint64) (Selection, bool) {
pos := surfacePosition{x, y}
call(fnGestureEventSet, g.press, gestureOptRef, uintptr(unsafe.Pointer(&ref)))
call(fnGestureEventSet, g.press, gestureOptPosition, uintptr(unsafe.Pointer(&pos)))
call(fnGestureEventSet, g.press, gestureOptTime, uintptr(unsafe.Pointer(&ns)))
return g.apply(t, g.press)
}
// Drag moves the pressed pointer to cell ref at x, y pixels, selecting a
// rectangle when rect is set.
func (g *Gesture) Drag(t *Terminal, ref GridRef, x, y float64, geo Geometry, rect bool) (Selection, bool) {
pos := surfacePosition{x, y}
gg := gestureGeometry{uint32(max(geo.Columns, 1)), uint32(max(geo.CellWidth, 1)), uint32(max(geo.PadLeft, 0)), uint32(max(geo.Height, 1))}
call(fnGestureEventSet, g.drag, gestureOptRef, uintptr(unsafe.Pointer(&ref)))
call(fnGestureEventSet, g.drag, gestureOptPosition, uintptr(unsafe.Pointer(&pos)))
call(fnGestureEventSet, g.drag, gestureOptGeometry, uintptr(unsafe.Pointer(&gg)))
call(fnGestureEventSet, g.drag, gestureOptRectangle, uintptr(unsafe.Pointer(&rect)))
return g.apply(t, g.drag)
}
// Tick continues a drag past an edge after the viewport scrolled, with the
// pointer at x, y pixels over column col of row row of the viewport.
func (g *Gesture) Tick(t *Terminal, col, row int, x, y float64, geo Geometry, rect bool) (Selection, bool) {
pos := surfacePosition{x, y}
gg := gestureGeometry{uint32(max(geo.Columns, 1)), uint32(max(geo.CellWidth, 1)), uint32(max(geo.PadLeft, 0)), uint32(max(geo.Height, 1))}
vp := struct {
x uint16
_ uint16
y uint32
}{x: uint16(max(col, 0)), y: uint32(max(row, 0))}
call(fnGestureEventSet, g.tick, gestureOptPosition, uintptr(unsafe.Pointer(&pos)))
call(fnGestureEventSet, g.tick, gestureOptGeometry, uintptr(unsafe.Pointer(&gg)))
call(fnGestureEventSet, g.tick, gestureOptViewport, uintptr(unsafe.Pointer(&vp)))
call(fnGestureEventSet, g.tick, gestureOptRectangle, uintptr(unsafe.Pointer(&rect)))
return g.apply(t, g.tick)
}
// Release releases the pointer over cell ref, or outside the grid when ref
// is nil.
func (g *Gesture) Release(t *Terminal, ref *GridRef) {
call(fnGestureEventSet, g.release, gestureOptRef, uintptr(unsafe.Pointer(ref)))
g.apply(t, g.release)
}
// Dragged reports whether the pointer moved to another cell since it was
// pressed.
func (g *Gesture) Dragged(t *Terminal) bool {
var v bool
return ok(call(fnGestureGet, g.h, t.h, gestureDataDragged, uintptr(unsafe.Pointer(&v)))) && v
}
// Autoscroll reports whether a drag past an edge asks to scroll up (-1) or
// down (1).
func (g *Gesture) Autoscroll(t *Terminal) int {
var v int32
call(fnGestureGet, g.h, t.h, gestureDataAutoscroll, uintptr(unsafe.Pointer(&v)))
switch v {
case 1:
return -1
case 2:
return 1
}
return 0
}
// Reset forgets the gesture's clicks.
func (g *Gesture) Reset(t *Terminal) { call(fnGestureReset, g.h, t.h) }
@@ -0,0 +1,869 @@
package vt
import (
"bytes"
"errors"
"fmt"
"runtime"
"slices"
"strings"
"sync"
"unsafe"
)
// Terminal is a GhosttyTerminal: the screen, its scrollback, the cursor
// and the modes, which the output of programs changes.
type Terminal struct {
h uintptr
id uintptr
// Effects are called during Write, on its goroutine; they must not
// call Write.
effects Effects
// silent is set while a clipboard read is refused: the refusal the
// library writes for it, a Kitty protocol EPERM, is dropped, as the
// read of a terminal that is not the one to answer.
silent bool
// deferred is the clipboard read the embedder answers later: the
// library's refusal, which follows the read's effect, is held back
// and captured in it.
deferred *DeferredClipboardRead
// reply gathers what the library writes while it answers a clipboard
// read, which WritePTY then gets at once.
reply *[]byte
}
// ClipboardRead is a program's request to read the clipboard.
type ClipboardRead struct {
// Mimes are the types asked for, in order of preference; List asks
// for the types available.
Mimes []string
List bool
// Primary is the selection clipboard of X11.
Primary bool
// Granted tells that the program holds the terminal's permission, as
// when it reads what a paste offered it.
Granted bool
// CanRemember tells that the program asked with a password (the one
// a paste event gave it, with its name): a terminal that pasted
// knows it — Granted says so — and one that does not never can, and
// leaves the read to the one it is for.
CanRemember bool
}
// ClipboardReply answers a ClipboardRead: Contents by MIME type, of the
// types asked for, and Available when the list was asked for. Without
// contents the read is refused. A deferred read carries Deferred instead.
type ClipboardReply struct {
Contents map[string][]byte
Available []string
// Deferred is the read to answer later, with ClipboardDeferred.
Deferred *DeferredClipboardRead
}
// Effects are what a terminal asks of its embedder while it processes
// output, all optional. They run during Terminal.Write, which they must
// not call.
type Effects struct {
// WritePTY answers the program, as to a query of the cursor's
// position. p is only valid during the call.
WritePTY func(p []byte)
Bell func()
// TitleChanged and PwdChanged tell that Title or Pwd changed.
TitleChanged func()
PwdChanged func()
// RenderHold tells that the program started or ended a synchronized
// update (mode 2026), during which the screen should not show.
RenderHold func(held bool)
// Clipboard writes text to the clipboard (OSC 52), and reports
// whether it did. primary is the selection clipboard of X11.
Clipboard func(text string, primary bool) bool
// ClipboardRead answers a program's read of the clipboard (OSC 52
// with "?", the Kitty clipboard protocol's OSC 5522): the contents of
// the MIME types asked for, and the types available when the program
// asks for the list. ClipboardAnswered writes the reply, encoded, to
// WritePTY in one call as ClipboardRead returns; ClipboardRefused
// refuses it (an empty OSC 52 reply, EPERM for OSC 5522), and the
// EPERM is dropped, so that a terminal that is not the one to answer
// stays silent; ClipboardDeferred holds the refusal back and answers
// later through Terminal.AnswerClipboard, for a terminal that must
// ask the user first.
ClipboardRead func(req ClipboardRead) (reply ClipboardReply, answer ClipboardAnswer)
// Size reports the size of the screen in cells and of a cell in
// pixels, for size reports.
Size func() (cols, rows, cellWidth, cellHeight int)
// Dark reports whether the colors are dark, for color scheme reports.
Dark func() bool
// Notify shows a desktop notification (OSC 9, OSC 777).
Notify func(title, body string)
// Progress reports the progress of the program (OSC 9;4): state is
// 0 to remove it, 1 to set it to progress (0 to 100), 2 for an error,
// 3 for indeterminate progress and 4 paused.
Progress func(state, progress int)
}
// terminals finds the terminal of a callback by its userdata.
var terminals struct {
sync.Mutex
next uintptr
m map[uintptr]*Terminal
}
func terminalOf(id uintptr) *Terminal {
terminals.Lock()
defer terminals.Unlock()
return terminals.m[id]
}
// Terminal options and data (GhosttyTerminalOption, GhosttyTerminalData).
const (
optUserdata = 0
optWritePTY = 1
optBell = 2
optTitleChanged = 5
optSize = 6
optColorScheme = 7
optDeviceAttributes = 8
optColorForeground = 11
optColorBackground = 12
optColorCursor = 13
optColorPalette = 14
optKittyImageLimit = 15
optDefaultCursorStyle = 22
optDefaultCursorBlink = 23
optPwdChanged = 25
optClipboardWrite = 26
optClipboardRead = 38
optScrollbackMaxBytes = 27
optDesktopNotification = 29
optProgressReport = 30
optModeDefault = 33
optMode = 34
optTerminfoName = 37
optResizePullBack = 40
optRenderHold = 41
dataCols = 1
dataRows = 2
dataCursorX = 3
dataCursorY = 4
dataActiveScreen = 6
dataScrollbar = 9
dataMouseTracking = 11
dataTitle = 12
dataPwd = 13
dataColorFg = 18 // then the background, the cursor and the palette
dataColorFgDefault = 22 // the same, defaults alone
dataViewportActive = 32
dataMode = 37
dataMouseShape = 41
)
// NewTerminal makes a terminal of cols columns and rows rows.
func NewTerminal(cols, rows int, effects Effects) (*Terminal, error) {
if !Loaded() {
return nil, errors.New("libghostty-vt is not loaded")
}
t := &Terminal{effects: effects}
if err := result(call(fnTerminalNew, 0, uintptr(unsafe.Pointer(&t.h)), uintptr(clamp16(cols)), uintptr(clamp16(rows)))); err != nil {
return nil, err
}
terminals.Lock()
if terminals.m == nil {
terminals.m = map[uintptr]*Terminal{}
}
terminals.next++
t.id = terminals.next
terminals.m[t.id] = t
terminals.Unlock()
t.setValue(optUserdata, t.id)
t.setValue(optWritePTY, cbWritePTY)
t.setValue(optBell, cbBell)
t.setValue(optTitleChanged, cbTitleChanged)
t.setValue(optPwdChanged, cbPwdChanged)
t.setValue(optRenderHold, cbRenderHold)
t.setValue(optClipboardWrite, cbClipboardWrite)
t.setValue(optClipboardRead, cbClipboardRead)
t.setValue(optSize, cbSize)
t.setValue(optColorScheme, cbColorScheme)
t.setValue(optDeviceAttributes, cbDeviceAttributes)
t.setValue(optDesktopNotification, cbDesktopNotification)
t.setValue(optProgressReport, cbProgressReport)
// Images of the Kitty graphics protocol are refused until SetImageLimit
// takes them, so that programs fall back to something else.
t.SetImageLimit(0)
return t, nil
}
// set sets an option to a pointer to its value. The pointer is converted
// in the call, so that the value stays put while the library reads it
// (see call).
func (t *Terminal) set(opt int, value unsafe.Pointer) error {
return result(call(fnTerminalSet, t.h, uintptr(opt), uintptr(value)))
}
// setValue sets an option that is a value itself: a callback, or the
// userdata.
func (t *Terminal) setValue(opt int, value uintptr) error {
return result(call(fnTerminalSet, t.h, uintptr(opt), value))
}
func (t *Terminal) get(data int, out unsafe.Pointer) error {
return result(call(fnTerminalGet, t.h, uintptr(data), uintptr(out)))
}
// Free frees the terminal.
func (t *Terminal) Free() {
if t.h == 0 {
return
}
call(fnTerminalFree, t.h)
t.h = 0
terminals.Lock()
delete(terminals.m, t.id)
terminals.Unlock()
}
// Write processes output of the program.
func (t *Terminal) Write(p []byte) {
if len(p) > 0 {
// A read that was deferred but whose refusal never came, as of a
// library of another version, is stale.
t.deferred = nil
call(fnTerminalVTWrite, t.h, uintptr(unsafe.Pointer(&p[0])), uintptr(len(p)))
t.deferred = nil
// A read that writes no refusal, as OSC 52's, leaves silent set;
// it is for that read alone.
t.silent = false
}
}
// Resize sets the size of the screen in cells, and of a cell in pixels.
func (t *Terminal) Resize(cols, rows, cellWidth, cellHeight int) error {
return result(call(fnTerminalResize, t.h, uintptr(clamp16(cols)), uintptr(clamp16(rows)), uintptr(max(cellWidth, 1)), uintptr(max(cellHeight, 1))))
}
// Size returns the size of the screen in cells.
func (t *Terminal) Size() (cols, rows int) {
var c, r uint16
t.get(dataCols, unsafe.Pointer(&c))
t.get(dataRows, unsafe.Pointer(&r))
return int(c), int(r)
}
// Cursor returns the cursor's column and row in the active screen, the
// bottom of the scrollback.
func (t *Terminal) Cursor() (x, y int) {
var cx, cy uint16
t.get(dataCursorX, unsafe.Pointer(&cx))
t.get(dataCursorY, unsafe.Pointer(&cy))
return int(cx), int(cy)
}
// Reset resets the terminal fully (RIS).
func (t *Terminal) Reset() { call(fnTerminalReset, t.h) }
// SetColors sets the default colors, which programs may change: the
// foreground, the background, the cursor's (nil for the text's) and the
// palette of 256 colors (nil for Ghostty's).
func (t *Terminal) SetColors(fg, bg RGB, cursor *RGB, palette *[256]RGB) {
t.set(optColorForeground, unsafe.Pointer(&fg))
t.set(optColorBackground, unsafe.Pointer(&bg))
t.set(optColorCursor, unsafe.Pointer(cursor))
t.set(optColorPalette, unsafe.Pointer(palette))
}
// SetScrollback limits the scrollback to about n bytes.
func (t *Terminal) SetScrollback(n int) {
v := uintptr(max(n, 0))
t.set(optScrollbackMaxBytes, unsafe.Pointer(&v))
}
// SetTerminfoName sets the name of the terminfo entry the terminal reports
// (XTGETTCAP TN).
func (t *Terminal) SetTerminfoName(name string) {
b := []byte(name)
s := cString{len: uintptr(len(b))}
// The string holds the address of b, which the call does not see.
var pin runtime.Pinner
defer pin.Unpin()
if len(b) > 0 {
pin.Pin(&b[0])
s.ptr = uintptr(unsafe.Pointer(&b[0]))
}
t.set(optTerminfoName, unsafe.Pointer(&s))
}
// CursorStyle is the shape of the cursor.
type CursorStyle int32
const (
CursorBar CursorStyle = iota
CursorBlock
CursorUnderline
CursorBlockHollow
)
// SetDefaultCursor sets the cursor that programs reset to (DECSCUSR 0).
func (t *Terminal) SetDefaultCursor(s CursorStyle, blink bool) {
t.set(optDefaultCursorStyle, unsafe.Pointer(&s))
t.set(optDefaultCursorBlink, unsafe.Pointer(&blink))
}
func (t *Terminal) str(data int) string {
var s cString
if t.get(data, unsafe.Pointer(&s)) != nil {
return ""
}
return goString(s.ptr, s.len)
}
// Title returns the title programs set (OSC 0, OSC 2).
func (t *Terminal) Title() string { return t.str(dataTitle) }
// Pwd returns the working directory the shell reported (OSC 7), as it
// reported it: a file URL, or a path.
func (t *Terminal) Pwd() string { return t.str(dataPwd) }
// Mode is a GhosttyMode: a DEC private mode, or an ANSI one with bit 15.
type Mode uint16
// Modes.
const (
ModeCursorKeys Mode = 1
ModeCursorVisible Mode = 25
ModeFocusEvent Mode = 1004
ModeAltScroll Mode = 1007
ModeBracketedPaste Mode = 2004
// ModePasteEvents has a paste tell the program what the clipboard
// holds, which it reads itself (the Kitty clipboard protocol).
ModePasteEvents Mode = 5522
ModeSyncOutput Mode = 2026
ModeGraphemes Mode = 2027
// ModeColorScheme has the terminal tell the program when its colors
// go from light to dark or back (CSI ? 997 ; 1 n for dark, 2 light).
ModeColorScheme Mode = 2031
)
// Mode reports whether a mode is set.
func (t *Terminal) Mode(m Mode) bool {
c := modeConfig{mode: uint16(m)}
return t.get(dataMode, unsafe.Pointer(&c)) == nil && c.value
}
// SetMode sets a mode.
func (t *Terminal) SetMode(m Mode, v bool) {
c := modeConfig{mode: uint16(m), value: v}
t.set(optMode, unsafe.Pointer(&c))
}
// SetModeDefault sets a mode, and the value a reset restores.
func (t *Terminal) SetModeDefault(m Mode, v bool) {
c := modeConfig{mode: uint16(m), value: v}
t.set(optModeDefault, unsafe.Pointer(&c))
}
// MouseTracking reports whether a program asked for mouse events.
func (t *Terminal) MouseTracking() bool {
var v bool
return t.get(dataMouseTracking, unsafe.Pointer(&v)) == nil && v
}
// MouseShape returns the pointer shape a program asked for (OSC 22), a
// GhosttyMouseShape.
func (t *Terminal) MouseShape() int {
var v int32
t.get(dataMouseShape, unsafe.Pointer(&v))
return int(v)
}
// TermColors are a terminal's colors; a color neither a program set nor a
// default gave is not Has.
type TermColors struct {
Foreground, Background, Cursor RGB
HasForeground, HasBackground, HasCursor bool
Palette [256]RGB
}
// Colors returns the colors programs see: those they set (OSC 4, 10, 11,
// 12) over the defaults, or with defaults the defaults alone.
func (t *Terminal) Colors(defaults bool) TermColors {
base := dataColorFg
if defaults {
base = dataColorFgDefault
}
var c TermColors
c.HasForeground = t.get(base, unsafe.Pointer(&c.Foreground)) == nil
c.HasBackground = t.get(base+1, unsafe.Pointer(&c.Background)) == nil
c.HasCursor = t.get(base+2, unsafe.Pointer(&c.Cursor)) == nil
t.get(base+3, unsafe.Pointer(&c.Palette))
return c
}
// AltScreen reports whether the alternate screen shows, as in full-screen
// programs.
func (t *Terminal) AltScreen() bool {
var v int32
return t.get(dataActiveScreen, unsafe.Pointer(&v)) == nil && v == 1
}
// Scrollbar returns where the viewport is in the scrollback.
func (t *Terminal) Scrollbar() Scrollbar {
var s Scrollbar
t.get(dataScrollbar, unsafe.Pointer(&s))
return s
}
// AtBottom reports whether the viewport follows the active screen, rather
// than showing the scrollback.
func (t *Terminal) AtBottom() bool {
var v bool
return t.get(dataViewportActive, unsafe.Pointer(&v)) != nil || v
}
// ScrollToTop, ScrollToBottom, ScrollBy and ScrollToRow move the viewport:
// to the top of the scrollback, to the active screen, by rows (negative
// up), or to show row first.
func (t *Terminal) ScrollToTop() { terminalScrollViewport(t.h, scrollViewport{tag: 0}) }
func (t *Terminal) ScrollToBottom() { terminalScrollViewport(t.h, scrollViewport{tag: 1}) }
func (t *Terminal) ScrollBy(rows int) {
terminalScrollViewport(t.h, scrollViewport{tag: 2, value: [2]uint64{uint64(int64(rows))}})
}
func (t *Terminal) ScrollToRow(row int) {
terminalScrollViewport(t.h, scrollViewport{tag: 3, value: [2]uint64{uint64(max(row, 0))}})
}
// CellAt returns the cell at column x of row y of the viewport.
func (t *Terminal) CellAt(x, y int) (GridRef, bool) {
ref := GridRef{size: unsafe.Sizeof(GridRef{})}
p := point{tag: 1, x: uint16(max(0, min(x, 0xFFFF))), y: uint32(max(y, 0))}
return ref, terminalGridRef(t.h, p, &ref) == 0
}
// SetResizePullBack sets whether growing the screen pulls rows back from
// the scrollback, which a pseudo-terminal keeping its own screen, as
// Windows' ConPTY, cannot follow.
func (t *Terminal) SetResizePullBack(v bool) {
t.set(optResizePullBack, unsafe.Pointer(&v))
}
// RowText returns the text of row y of the viewport, and the column of
// each of its runes.
func (t *Terminal) RowText(y int) (text []rune, cols []int) {
c, _ := t.Size()
var buf [16]uint32
for x := range c {
ref, found := t.CellAt(x, y)
if !found {
break
}
var raw uint64
if ok(call(fnGridRefCell, uintptr(unsafe.Pointer(&ref)), uintptr(unsafe.Pointer(&raw)))) {
if w := Wide(cell.wide.of(raw)); w == SpacerTail || w == SpacerHead {
continue
}
}
var n uintptr
if !ok(call(fnGridRefGraphemes, uintptr(unsafe.Pointer(&ref)), uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)), uintptr(unsafe.Pointer(&n)))) || n == 0 {
text, cols = append(text, ' '), append(cols, x)
continue
}
for _, r := range buf[:n] {
text, cols = append(text, rune(r)), append(cols, x)
}
}
return text, cols
}
// RowPrompt is how a row belongs to a shell's prompt, which the shell
// marks with OSC 133 (shell integration).
type RowPrompt int32
const (
NoPrompt RowPrompt = iota
// PromptStart is the row a prompt starts on (OSC 133;A).
PromptStart
// PromptContinuation is a row the prompt or its input goes on over:
// one a long command wraps onto, or a prompt's next line.
PromptContinuation
)
// Row returns how row y of the viewport belongs to a shell's prompt, and
// whether it soft-wraps into the next.
func (t *Terminal) Row(y int) (prompt RowPrompt, wrap bool) {
ref, found := t.CellAt(0, y)
if !found {
return NoPrompt, false
}
var row uint64
if !ok(call(fnGridRefRow, uintptr(unsafe.Pointer(&ref)), uintptr(unsafe.Pointer(&row)))) {
return NoPrompt, false
}
if !ok(call(fnRowData, uintptr(row), rowDataSemanticPrompt, uintptr(unsafe.Pointer(&prompt)))) {
prompt = NoPrompt
}
return prompt, ok(call(fnRowData, uintptr(row), rowDataWrap, uintptr(unsafe.Pointer(&wrap)))) && wrap
}
// Hyperlink returns the URI of the hyperlink (OSC 8) of a cell, or "".
func (t *Terminal) Hyperlink(ref GridRef) string {
var buf [512]byte
var n uintptr
r := call(fnGridRefHyperlinkURI, uintptr(unsafe.Pointer(&ref)), uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)), uintptr(unsafe.Pointer(&n)))
if Result(int32(r)) == OutOfSpace && n > 0 {
big := make([]byte, n)
r = call(fnGridRefHyperlinkURI, uintptr(unsafe.Pointer(&ref)), uintptr(unsafe.Pointer(&big[0])), n, uintptr(unsafe.Pointer(&n)))
if !ok(r) {
return ""
}
return string(big[:n])
}
if !ok(r) {
return ""
}
return string(buf[:n])
}
// SetSelection selects s, or nothing when s is nil.
func (t *Terminal) SetSelection(s *Selection) {
t.set(21, unsafe.Pointer(s))
}
// ExtendSelection moves the selection's logical end to ref, keeping its
// original anchor even for a reversed selection. Read a fresh snapshot:
// grid references cannot be kept across output, scrolling or resizing.
func (t *Terminal) ExtendSelection(ref GridRef) bool {
s := Selection{size: unsafe.Sizeof(Selection{})}
if t.get(31, unsafe.Pointer(&s)) != nil {
return false
}
s.end, s.rectangle = ref, false
return t.set(21, unsafe.Pointer(&s)) == nil
}
// SelectAll returns a selection of everything, scrollback included.
func (t *Terminal) SelectAll() (Selection, bool) {
s := Selection{size: unsafe.Sizeof(Selection{})}
return s, ok(call(fnSelectAll, t.h, uintptr(unsafe.Pointer(&s))))
}
// SelectionText returns the text of the selection, with soft-wrapped lines
// joined and trailing spaces trimmed, as Ghostty copies it.
func (t *Terminal) SelectionText() (string, bool) {
var p, n uintptr
opts := selectionFormatOptions{size: unsafe.Sizeof(selectionFormatOptions{}), unwrap: true, trim: true}
if selectionFormatAlloc(t.h, 0, opts, &p, &n) != 0 {
return "", false
}
s := goString(p, n)
if p != 0 {
call(fnFree, 0, p, n)
}
return s, true
}
// Text returns the text of the screen and its scrollback, with
// soft-wrapped lines joined and trailing spaces trimmed.
func (t *Terminal) Text() string {
opts := formatterOptions{size: unsafe.Sizeof(formatterOptions{}), unwrap: true, trim: true}
opts.extra.size = unsafe.Sizeof(opts.extra)
opts.extra.screen.size = unsafe.Sizeof(opts.extra.screen)
var f uintptr
if formatterTerminalNew(0, &f, t.h, opts) != 0 {
return ""
}
defer call(fnFormatterFree, f)
var p, n uintptr
if !ok(call(fnFormatterFormatAlloc, f, 0, uintptr(unsafe.Pointer(&p)), uintptr(unsafe.Pointer(&n)))) {
return ""
}
s := goString(p, n)
if p != 0 {
call(fnFree, 0, p, n)
}
return s
}
// formatVT is GHOSTTY_FORMATTER_FORMAT_VT: text with escape sequences.
const formatVT = 1
// VT returns the terminal's state as escape sequences, which restore it in
// a terminal of the same size: the scrollback and the screen with their
// styles and hyperlinks, then the modes, the scrolling region, the tab
// stops, the working directory, the keyboard's flags and the cursor. The
// palette is left out, as the terminal it restores in has colors of its
// own.
func (t *Terminal) VT() []byte {
opts := formatterOptions{size: unsafe.Sizeof(formatterOptions{}), emit: formatVT}
x := &opts.extra
x.size = unsafe.Sizeof(opts.extra)
x.modes, x.scrollingRegion, x.tabstops, x.pwd, x.keyboard = true, true, true, true, true
x.screen.size = unsafe.Sizeof(opts.extra.screen)
x.screen.cursor, x.screen.style, x.screen.hyperlink, x.screen.protection, x.screen.kittyKeyboard, x.screen.charsets = true, true, true, true, true, true
var f uintptr
if formatterTerminalNew(0, &f, t.h, opts) != 0 {
return nil
}
defer call(fnFormatterFree, f)
var p, n uintptr
if !ok(call(fnFormatterFormatAlloc, f, 0, uintptr(unsafe.Pointer(&p)), uintptr(unsafe.Pointer(&n)))) {
return nil
}
b := []byte(goString(p, n))
if p != 0 {
call(fnFree, 0, p, n)
}
return t.padRows(b)
}
// padRows adds the blank rows at the end of the screen, which the
// formatter leaves out, to the rows of a VT snapshot. Without them, the
// rows written scroll fewer into the scrollback of the terminal they are
// replayed in: what was scrollback shows on the screen, as after clear,
// and the cursor, on a blank row under the last one written, lands on
// that row, whose text what is written next overwrites. The rows end
// where the snapshot places the cursor, one "\r\n" after the other.
func (t *Terminal) padRows(b []byte) []byte {
_, rows := t.Size()
total := int(t.Scrollbar().Total)
if total <= rows || t.AltScreen() {
// No scrollback, or a full-screen program's screen, which has
// none: the cursor's position alone places it.
return b
}
x, y := t.Cursor()
end := bytes.LastIndex(b, fmt.Appendf(nil, "\x1b[%d;%dH", y+1, x+1))
if end < 0 {
return b
}
pad := total - (bytes.Count(b[:end], []byte("\r\n")) + 1)
if pad <= 0 {
return b
}
return slices.Concat(b[:end], bytes.Repeat([]byte("\r\n"), pad), b[end:])
}
// Compress compresses some of the scrollback, as when the terminal is
// idle, and reports whether more is left to compress.
func (t *Terminal) Compress() bool {
var r int32
if !ok(call(fnTerminalCompress, t.h, 0, uintptr(unsafe.Pointer(&r)))) {
return false
}
return r == 1
}
// Activity returns a token that changes when the scrollback may compress.
func (t *Terminal) Activity() uint64 {
var v uint64
call(fnTerminalCompressionActivity, t.h, uintptr(unsafe.Pointer(&v)))
return v
}
func clamp16(v int) int { return max(1, min(v, 0xFFFF)) }
// The callbacks of every terminal, made once: purego's are never freed.
var (
cbWritePTY, cbBell, cbTitleChanged, cbPwdChanged, cbRenderHold, cbClipboardWrite, cbClipboardRead, cbSize,
cbColorScheme, cbDeviceAttributes, cbDesktopNotification, cbProgressReport, cbNoRead uintptr
)
func makeCallbacks() {
// A GhosttyMimeReader for PasteEvent, which the library never calls
// (it reads nothing for an event); it gives no data if it did.
cbNoRead = newCallback(func(_, _, _, _, _ uintptr) uintptr { return 0 })
cbWritePTY = newCallback(func(_, id, data, n uintptr) uintptr {
if t := terminalOf(id); t != nil && t.effects.WritePTY != nil && n > 0 {
p := unsafe.Slice((*byte)(mem(data)), n)
if d := t.deferred; d != nil {
// A deferred read: what the library writes now is its
// refusal, which the read's answer replaces.
t.deferred = nil
if d.setRefusal(p) {
return 0
}
}
if t.silent && bytes.HasPrefix(p, []byte("\x1b]5522;type=read:status=EPERM")) {
// The refusal of a read that goes unanswered: the library
// writes it as the read's callback returns without a reply.
t.silent = false
return 0
}
if t.reply != nil {
*t.reply = append(*t.reply, p...)
return 0
}
t.effects.WritePTY(p)
}
return 0
})
cbClipboardRead = newCallback(func(_, id, req uintptr) uintptr {
r := (*clipboardRead)(mem(req))
t := terminalOf(id)
if t == nil || t.effects.ClipboardRead == nil {
return 0 // refused by the library
}
var in ClipboardRead
in.List, in.Primary, in.Granted, in.CanRemember = r.list, r.location != 0, r.granted, r.canRemember
for _, m := range unsafe.Slice((*cString)(mem(r.mimes)), r.mimesLen) {
in.Mimes = append(in.Mimes, goString(m.ptr, m.len))
}
out, answer := t.effects.ClipboardRead(in)
switch answer {
case ClipboardAnswered:
reply := clipboardReadReply{size: unsafe.Sizeof(clipboardReadReply{}), result: 1} // denied
var contents []clipboardContent
var available []cString
var keep [][]byte
for _, m := range in.Mimes {
if data, ok := out.Contents[m]; ok && len(data) > 0 {
contents = append(contents, clipboardContent{mime: cStringOf(m, &keep), data: cBytes(data)})
}
}
for _, m := range out.Available {
available = append(available, cStringOf(m, &keep))
}
if len(contents) > 0 || in.List && len(available) > 0 {
reply.result = 0
if len(contents) > 0 {
reply.contents, reply.contentsLen = uintptr(unsafe.Pointer(&contents[0])), uintptr(len(contents))
}
if len(available) > 0 {
reply.available, reply.availableLen = uintptr(unsafe.Pointer(&available[0])), uintptr(len(available))
}
}
var written []byte
t.reply = &written
call(r.reply, req, uintptr(unsafe.Pointer(&reply)))
t.reply = nil
if len(written) > 0 && t.effects.WritePTY != nil {
t.effects.WritePTY(written)
}
runtime.KeepAlive(keep)
runtime.KeepAlive(out)
runtime.KeepAlive(contents)
runtime.KeepAlive(available)
case ClipboardDeferred:
d := out.Deferred
if d != nil {
d.mimes, d.list, d.primary = in.Mimes, in.List, in.Primary
t.deferred = d
return 0
}
fallthrough
default: // ClipboardRefused: the library writes the refusal itself.
t.silent = true
}
return 0
})
cbBell = newCallback(func(_, id uintptr) uintptr {
if t := terminalOf(id); t != nil && t.effects.Bell != nil {
t.effects.Bell()
}
return 0
})
cbTitleChanged = newCallback(func(_, id uintptr) uintptr {
if t := terminalOf(id); t != nil && t.effects.TitleChanged != nil {
t.effects.TitleChanged()
}
return 0
})
cbPwdChanged = newCallback(func(_, id uintptr) uintptr {
if t := terminalOf(id); t != nil && t.effects.PwdChanged != nil {
t.effects.PwdChanged()
}
return 0
})
cbRenderHold = newCallback(func(_, id, held uintptr) uintptr {
if t := terminalOf(id); t != nil && t.effects.RenderHold != nil {
t.effects.RenderHold(cbool(held))
}
return 0
})
cbClipboardWrite = newCallback(func(_, id, req uintptr) uintptr {
w := (*clipboardWrite)(mem(req))
reply := clipboardWriteReply{size: unsafe.Sizeof(clipboardWriteReply{}), result: 1} // denied
t := terminalOf(id)
if t != nil && t.effects.Clipboard != nil {
// No contents clears the clipboard; otherwise the first plain
// text, else the first text of another kind, is written.
text, found := "", w.contentsLen == 0
for _, c := range unsafe.Slice((*clipboardContent)(mem(w.contents)), w.contentsLen) {
mime := goString(c.mime.ptr, c.mime.len)
if strings.HasPrefix(mime, "text/plain") || strings.HasPrefix(mime, "text/") && !found {
text, found = goString(c.data.ptr, c.data.len), true
}
}
switch {
case !found:
reply.result = 2 // unsupported
case t.effects.Clipboard(text, w.location != 0):
reply.result = 0
}
}
call(w.reply, req, uintptr(unsafe.Pointer(&reply)))
return 0
})
cbSize = newCallback(func(_, id, out uintptr) uintptr {
t := terminalOf(id)
if t == nil || t.effects.Size == nil {
return 0
}
cols, rows, cw, ch := t.effects.Size()
*(*sizeReport)(mem(out)) = sizeReport{rows: uint16(clamp16(rows)), columns: uint16(clamp16(cols)), cellWidth: uint32(max(cw, 1)), cellHeight: uint32(max(ch, 1))}
return 1
})
cbColorScheme = newCallback(func(_, id, out uintptr) uintptr {
t := terminalOf(id)
if t == nil || t.effects.Dark == nil {
return 0
}
v := int32(0)
if t.effects.Dark() {
v = 1
}
*(*int32)(mem(out)) = v
return 1
})
cbDeviceAttributes = newCallback(func(_, id, out uintptr) uintptr {
// As Ghostty answers: a VT220 with ANSI colors (DA1), of type 1
// and version 10 (DA2).
da := (*deviceAttributes)(mem(out))
*da = deviceAttributes{conformance: 62, numFeatures: 1, deviceType: 1, firmware: 10}
da.features[0] = 22
return 1
})
cbDesktopNotification = newCallback(func(_, id, req uintptr) uintptr {
if t := terminalOf(id); t != nil && t.effects.Notify != nil {
n := (*desktopNotification)(mem(req))
t.effects.Notify(goString(n.title.ptr, n.title.len), goString(n.body.ptr, n.body.len))
}
return 0
})
cbProgressReport = newCallback(func(_, id, req uintptr) uintptr {
if t := terminalOf(id); t != nil && t.effects.Progress != nil {
p := (*progressReport)(mem(req))
t.effects.Progress(int(p.state), int(p.progress))
}
return 0
})
}
// cStringOf points a GhosttyString at a copy of s, kept in keep for as
// long as the library may read it.
func cStringOf(s string, keep *[][]byte) cString {
if s == "" {
return cString{}
}
b := []byte(s)
*keep = append(*keep, b)
return cBytes(b)
}
// cBytes points a GhosttyString at b, which must stay alive and unchanged
// while the library reads it.
func cBytes(b []byte) cString {
if len(b) == 0 {
return cString{}
}
return cString{ptr: uintptr(unsafe.Pointer(&b[0])), len: uintptr(len(b))}
}
+357
View File
@@ -0,0 +1,357 @@
package vt
import "unsafe"
// RGB is a GhosttyColorRgb.
type RGB struct{ R, G, B uint8 }
// styleColor is a GhosttyStyleColor: a tag and, after padding, a union of a
// palette index and an RGB color.
type styleColor struct {
tag int32
_ int32
value [8]byte
}
const (
colorNone = 0
colorPalette = 1
colorRGB = 2
)
// style is a GhosttyStyle.
type style struct {
size uintptr
fg, bg, underlineColor styleColor
bold, italic, faint, blink, inverse, invisible, strikethrough, overline bool
underline int32
}
// renderCursor is a GhosttyRenderStateCursor.
type renderCursor struct {
size uintptr
viewportHasValue bool
viewportX, viewportY uint16
wideTail, visible, blinking, passwordInput bool
visualStyle int32
}
// renderColors is a GhosttyRenderStateColors.
type renderColors struct {
size uintptr
background, foreground, cursor RGB
cursorHasValue bool
palette [256]RGB
}
// rowSelection is a GhosttyRenderStateRowSelection.
type rowSelection struct {
size uintptr
startX, endX uint16
}
// cellsView is a GhosttyCellsView.
type cellsView struct {
ptr, len uintptr
}
// cString is a GhosttyString.
type cString struct {
ptr, len uintptr
}
// Scrollbar is a GhosttyTerminalScrollbar: the rows of the screen and its
// scrollback, the first row of the viewport and how many rows it shows.
type Scrollbar struct {
Total, Offset, Len uint64
}
// scrollViewport is a GhosttyTerminalScrollViewport.
type scrollViewport struct {
tag int32
_ int32
value [2]uint64
}
// modeConfig is a GhosttyTerminalModeConfig.
type modeConfig struct {
mode uint16
value bool
}
// GridRef is a GhosttyGridRef: a cell of the terminal, valid until the
// terminal next changes.
type GridRef struct {
size uintptr
node uintptr
x, y uint16
}
// point is a GhosttyPoint whose value is a coordinate.
type point struct {
tag int32
_ int32
x uint16
_ uint16
y uint32
_ uint64
}
// Selection is a GhosttySelection: two cells of the terminal, inclusive,
// valid until the terminal next changes.
type Selection struct {
size uintptr
start, end GridRef
rectangle bool
}
// selectionFormatOptions is a GhosttyTerminalSelectionFormatOptions.
type selectionFormatOptions struct {
size uintptr
emit int32
unwrap bool
trim bool
selection uintptr
}
// formatterOptions is a GhosttyFormatterTerminalOptions, with its extras
// (GhosttyFormatterTerminalExtra and GhosttyFormatterScreenExtra).
type formatterOptions struct {
size uintptr
emit int32
unwrap bool
trim bool
extra formatterExtra
selection uintptr
}
type formatterExtra struct {
size uintptr
palette, modes, scrollingRegion, tabstops, pwd, keyboard bool
screen struct {
size uintptr
cursor, style, hyperlink, protection, kittyKeyboard, charsets bool
}
}
// mouseEncoderSize is a GhosttyMouseEncoderSize.
type mouseEncoderSize struct {
size uintptr
screenWidth, screenHeight, cellWidth, cellHeight uint32
paddingTop, paddingBottom, paddingRight, paddingLeft uint32
}
// mousePosition is a GhosttyMousePosition.
type mousePosition struct{ x, y float32 }
// gestureGeometry is a GhosttySelectionGestureGeometry.
type gestureGeometry struct {
columns, cellWidth, paddingLeft, screenHeight uint32
}
// surfacePosition is a GhosttySurfacePosition.
type surfacePosition struct{ x, y float64 }
// sizeReport is a GhosttySizeReportSize.
type sizeReport struct {
rows, columns uint16
cellWidth, cellHeight uint32
}
// clipboardWrite is a GhosttyClipboardWrite.
type clipboardWrite struct {
size uintptr
location int32
contents uintptr
contentsLen uintptr
name cString
granted, canRemember bool
ctx, reply uintptr
}
// clipboardContent is a GhosttyClipboardContent.
type clipboardContent struct {
mime, data cString
}
// clipboardWriteReply is a GhosttyClipboardWriteReply.
type clipboardWriteReply struct {
size uintptr
result int32
remember bool
}
// clipboardRead is a GhosttyClipboardRead.
type clipboardRead struct {
size uintptr
location int32
mimes uintptr
mimesLen uintptr
list bool
name cString
granted, canRemember bool
ctx, reply uintptr
}
// clipboardReadReply is a GhosttyClipboardReadReply.
type clipboardReadReply struct {
size uintptr
result int32
contents uintptr
contentsLen uintptr
available uintptr
availableLen uintptr
remember bool
}
// paste is a GhosttyPaste: what a paste offers the program.
type paste struct {
size uintptr
location int32
source int32
mimes uintptr
mimesLen uintptr
reader mimeReader
allowUnsafe bool
}
// mimeReader is a GhosttyMimeReader.
type mimeReader struct {
read, userdata uintptr
}
// desktopNotification is a GhosttyTerminalDesktopNotification.
type desktopNotification struct {
size uintptr
title, body cString
}
// progressReport is a GhosttyTerminalProgressReport.
type progressReport struct {
size uintptr
state int32
progress int8
}
// deviceAttributes is a GhosttyDeviceAttributes.
type deviceAttributes struct {
conformance uint16
features [64]uint16
numFeatures uintptr
deviceType, firmware, romCartridge uint16
unitID uint32
}
// RowID identifies a row across render state updates (a
// GhosttyRenderStateRowId).
type RowID struct{ bits [2]uint64 }
func layouts() map[string]layout {
var (
ri renderInfo
si sysImage
sc styleColor
s style
c renderCursor
rc renderColors
rs rowSelection
cv cellsView
sb Scrollbar
sv scrollViewport
mc modeConfig
gr GridRef
pt point
sel Selection
sbu selectionBuffer
sfo selectionFormatOptions
mes mouseEncoderSize
cw clipboardWrite
cc clipboardContent
cwr clipboardWriteReply
cr clipboardRead
crr clipboardReadReply
pa paste
dn desktopNotification
pr progressReport
da deviceAttributes
fo formatterOptions
)
return map[string]layout{
"GhosttyColorRgb": {unsafe.Sizeof(RGB{}), map[string]uintptr{"r": 0, "g": 1, "b": 2}},
"GhosttyStyleColor": {unsafe.Sizeof(sc), map[string]uintptr{"tag": 0, "value": unsafe.Offsetof(sc.value)}},
"GhosttyStyle": {unsafe.Sizeof(s), map[string]uintptr{
"fg_color": unsafe.Offsetof(s.fg), "bg_color": unsafe.Offsetof(s.bg), "underline_color": unsafe.Offsetof(s.underlineColor),
"bold": unsafe.Offsetof(s.bold), "italic": unsafe.Offsetof(s.italic), "faint": unsafe.Offsetof(s.faint),
"blink": unsafe.Offsetof(s.blink), "inverse": unsafe.Offsetof(s.inverse), "invisible": unsafe.Offsetof(s.invisible),
"strikethrough": unsafe.Offsetof(s.strikethrough), "overline": unsafe.Offsetof(s.overline), "underline": unsafe.Offsetof(s.underline),
}},
"GhosttyRenderStateCursor": {unsafe.Sizeof(c), map[string]uintptr{
"viewport_has_value": unsafe.Offsetof(c.viewportHasValue), "viewport_x": unsafe.Offsetof(c.viewportX),
"viewport_y": unsafe.Offsetof(c.viewportY), "wide_tail": unsafe.Offsetof(c.wideTail), "visible": unsafe.Offsetof(c.visible),
"blinking": unsafe.Offsetof(c.blinking), "password_input": unsafe.Offsetof(c.passwordInput), "visual_style": unsafe.Offsetof(c.visualStyle),
}},
"GhosttyRenderStateColors": {unsafe.Sizeof(rc), map[string]uintptr{
"background": unsafe.Offsetof(rc.background), "foreground": unsafe.Offsetof(rc.foreground), "cursor": unsafe.Offsetof(rc.cursor),
"cursor_has_value": unsafe.Offsetof(rc.cursorHasValue), "palette": unsafe.Offsetof(rc.palette),
}},
"GhosttyRenderStateRowSelection": {unsafe.Sizeof(rs), map[string]uintptr{"start_x": unsafe.Offsetof(rs.startX), "end_x": unsafe.Offsetof(rs.endX)}},
"GhosttyCellsView": {unsafe.Sizeof(cv), map[string]uintptr{"ptr": 0, "len": unsafe.Offsetof(cv.len)}},
"GhosttyString": {unsafe.Sizeof(cString{}), map[string]uintptr{"ptr": 0, "len": unsafe.Offsetof(cString{}.len)}},
"GhosttyTerminalScrollbar": {unsafe.Sizeof(sb), map[string]uintptr{"total": 0, "offset": unsafe.Offsetof(sb.Offset), "len": unsafe.Offsetof(sb.Len)}},
"GhosttyTerminalScrollViewport": {unsafe.Sizeof(sv), map[string]uintptr{"tag": 0, "value": unsafe.Offsetof(sv.value)}},
"GhosttyTerminalModeConfig": {unsafe.Sizeof(mc), map[string]uintptr{"mode": 0, "value": unsafe.Offsetof(mc.value)}},
"GhosttyGridRef": {unsafe.Sizeof(gr), map[string]uintptr{"node": unsafe.Offsetof(gr.node), "x": unsafe.Offsetof(gr.x), "y": unsafe.Offsetof(gr.y)}},
"GhosttyPoint": {unsafe.Sizeof(pt), map[string]uintptr{"tag": 0, "value": unsafe.Offsetof(pt.x)}},
"GhosttyPointCoordinate": {8, map[string]uintptr{"x": unsafe.Offsetof(pt.x) - unsafe.Offsetof(pt.x), "y": unsafe.Offsetof(pt.y) - unsafe.Offsetof(pt.x)}},
"GhosttySelection": {unsafe.Sizeof(sel), map[string]uintptr{"start": unsafe.Offsetof(sel.start), "end": unsafe.Offsetof(sel.end), "rectangle": unsafe.Offsetof(sel.rectangle)}},
"GhosttySelectionBuffer": {unsafe.Sizeof(sbu), map[string]uintptr{"ptr": 0, "cap": unsafe.Offsetof(sbu.cap), "len": unsafe.Offsetof(sbu.len)}},
"GhosttyTerminalSelectionFormatOptions": {unsafe.Sizeof(sfo), map[string]uintptr{
"emit": unsafe.Offsetof(sfo.emit), "unwrap": unsafe.Offsetof(sfo.unwrap), "trim": unsafe.Offsetof(sfo.trim), "selection": unsafe.Offsetof(sfo.selection),
}},
"GhosttyMouseEncoderSize": {unsafe.Sizeof(mes), map[string]uintptr{
"screen_width": unsafe.Offsetof(mes.screenWidth), "screen_height": unsafe.Offsetof(mes.screenHeight),
"cell_width": unsafe.Offsetof(mes.cellWidth), "cell_height": unsafe.Offsetof(mes.cellHeight),
"padding_top": unsafe.Offsetof(mes.paddingTop), "padding_left": unsafe.Offsetof(mes.paddingLeft),
}},
"GhosttyMousePosition": {unsafe.Sizeof(mousePosition{}), map[string]uintptr{"x": 0, "y": 4}},
"GhosttyKittyGraphicsPlacementRenderInfo": {unsafe.Sizeof(ri), map[string]uintptr{
"pixel_width": unsafe.Offsetof(ri.pixelWidth), "grid_rows": unsafe.Offsetof(ri.gridRows),
"viewport_col": unsafe.Offsetof(ri.viewportCol), "viewport_visible": unsafe.Offsetof(ri.viewportVisible),
"source_x": unsafe.Offsetof(ri.sourceX), "source_height": unsafe.Offsetof(ri.sourceH),
}},
"GhosttySysImage": {unsafe.Sizeof(si), map[string]uintptr{"width": 0, "height": 4, "data": unsafe.Offsetof(si.data), "data_len": unsafe.Offsetof(si.dataLen)}},
"GhosttySelectionGestureGeometry": {unsafe.Sizeof(gestureGeometry{}), map[string]uintptr{"columns": 0, "cell_width": 4, "padding_left": 8, "screen_height": 12}},
"GhosttySurfacePosition": {unsafe.Sizeof(surfacePosition{}), map[string]uintptr{"x": 0, "y": 8}},
"GhosttySizeReportSize": {unsafe.Sizeof(sizeReport{}), map[string]uintptr{"rows": 0, "columns": 2, "cell_width": 4, "cell_height": 8}},
"GhosttyClipboardWrite": {unsafe.Sizeof(cw), map[string]uintptr{
"location": unsafe.Offsetof(cw.location), "contents": unsafe.Offsetof(cw.contents), "contents_len": unsafe.Offsetof(cw.contentsLen),
"name": unsafe.Offsetof(cw.name), "granted": unsafe.Offsetof(cw.granted), "ctx": unsafe.Offsetof(cw.ctx), "reply": unsafe.Offsetof(cw.reply),
}},
"GhosttyClipboardContent": {unsafe.Sizeof(cc), map[string]uintptr{"mime": 0, "data": unsafe.Offsetof(cc.data)}},
"GhosttyClipboardWriteReply": {unsafe.Sizeof(cwr), map[string]uintptr{"result": unsafe.Offsetof(cwr.result), "remember": unsafe.Offsetof(cwr.remember)}},
"GhosttyClipboardRead": {unsafe.Sizeof(cr), map[string]uintptr{
"location": unsafe.Offsetof(cr.location), "mimes": unsafe.Offsetof(cr.mimes), "mimes_len": unsafe.Offsetof(cr.mimesLen),
"list": unsafe.Offsetof(cr.list), "name": unsafe.Offsetof(cr.name), "granted": unsafe.Offsetof(cr.granted),
"can_remember": unsafe.Offsetof(cr.canRemember), "ctx": unsafe.Offsetof(cr.ctx), "reply": unsafe.Offsetof(cr.reply),
}},
"GhosttyClipboardReadReply": {unsafe.Sizeof(crr), map[string]uintptr{
"result": unsafe.Offsetof(crr.result), "contents": unsafe.Offsetof(crr.contents), "contents_len": unsafe.Offsetof(crr.contentsLen),
"available": unsafe.Offsetof(crr.available), "available_len": unsafe.Offsetof(crr.availableLen), "remember": unsafe.Offsetof(crr.remember),
}},
"GhosttyPaste": {unsafe.Sizeof(pa), map[string]uintptr{
"location": unsafe.Offsetof(pa.location), "source": unsafe.Offsetof(pa.source), "mimes": unsafe.Offsetof(pa.mimes),
"mimes_len": unsafe.Offsetof(pa.mimesLen), "reader": unsafe.Offsetof(pa.reader), "allow_unsafe": unsafe.Offsetof(pa.allowUnsafe),
}},
"GhosttyMimeReader": {unsafe.Sizeof(mimeReader{}), map[string]uintptr{"read": 0, "userdata": unsafe.Offsetof(mimeReader{}.userdata)}},
"GhosttyTerminalDesktopNotification": {unsafe.Sizeof(dn), map[string]uintptr{"title": unsafe.Offsetof(dn.title), "body": unsafe.Offsetof(dn.body)}},
"GhosttyTerminalProgressReport": {unsafe.Sizeof(pr), map[string]uintptr{"state": unsafe.Offsetof(pr.state), "progress": unsafe.Offsetof(pr.progress)}},
"GhosttyDeviceAttributes": {unsafe.Sizeof(da), map[string]uintptr{"primary": 0, "secondary": unsafe.Offsetof(da.deviceType), "tertiary": unsafe.Offsetof(da.unitID)}},
"GhosttyRenderStateRowId": {unsafe.Sizeof(RowID{}), map[string]uintptr{"bits": 0}},
"GhosttyFormatterTerminalOptions": {unsafe.Sizeof(fo), map[string]uintptr{
"emit": unsafe.Offsetof(fo.emit), "unwrap": unsafe.Offsetof(fo.unwrap), "trim": unsafe.Offsetof(fo.trim),
"extra": unsafe.Offsetof(fo.extra), "selection": unsafe.Offsetof(fo.selection),
}},
"GhosttyFormatterTerminalExtra": {unsafe.Sizeof(fo.extra), map[string]uintptr{"keyboard": unsafe.Offsetof(fo.extra.keyboard), "screen": unsafe.Offsetof(fo.extra.screen)}},
"GhosttyFormatterScreenExtra": {unsafe.Sizeof(fo.extra.screen), map[string]uintptr{"charsets": unsafe.Offsetof(fo.extra.screen.charsets)}},
}
}
+662
View File
@@ -0,0 +1,662 @@
package vt
import (
"bytes"
"encoding/base64"
"os"
"strings"
"testing"
"github.com/egoist/mygo/plugins/terminal/internal/library"
)
// loadLib loads the libghostty-vt of the terminal plugin, which it
// downloads into the user's cache when missing, or the one
// $MYGO_GHOSTTY_VT names; -short skips the tests then.
func loadLib(t *testing.T) {
t.Helper()
if testing.Short() && os.Getenv("MYGO_GHOSTTY_VT") == "" {
t.Skip("downloads libghostty-vt")
}
manifest, err := os.ReadFile("../../mygo-plugin.json")
if err != nil {
t.Fatal(err)
}
path, err := library.Find(manifest)
if err != nil {
t.Fatal(err)
}
if err := Load(path); err != nil {
t.Fatal(err)
}
}
func rowText(r *RenderState) []string {
var rows []string
r.Rows()
for r.NextRow() {
var b strings.Builder
for _, c := range r.RowCells() {
if c.Codepoint == 0 {
b.WriteByte(' ')
} else if c.Wide != SpacerTail {
b.WriteRune(c.Codepoint)
}
}
rows = append(rows, strings.TrimRight(b.String(), " "))
}
return rows
}
func TestTerminal(t *testing.T) {
loadLib(t)
var replies []string
var titled bool
term, err := NewTerminal(20, 5, Effects{
WritePTY: func(p []byte) { replies = append(replies, string(p)) },
TitleChanged: func() { titled = true },
})
if err != nil {
t.Fatal(err)
}
defer term.Free()
term.Write([]byte("Hello, \x1b[1;32mworld\x1b[0m!\r\nsecond line\x1b]2;the title\x07\x1b[6n"))
if want := []string{"\x1b[2;12R"}; strings.Join(replies, "") != want[0] {
t.Errorf("replies = %q, want %q", replies, want)
}
if !titled || term.Title() != "the title" {
t.Errorf("title = %q (changed %v)", term.Title(), titled)
}
r, err := NewRenderState()
if err != nil {
t.Fatal(err)
}
defer r.Free()
if err := r.Update(term); err != nil {
t.Fatal(err)
}
if cols, rows := r.Size(); cols != 20 || rows != 5 {
t.Errorf("size = %d×%d", cols, rows)
}
if got := rowText(r); got[0] != "Hello, world!" || got[1] != "second line" {
t.Errorf("rows = %q", got)
}
r.Rows()
r.NextRow()
cells := r.RowCells()
if cells[7].Style == 0 {
t.Fatal("w has the default style")
}
s := r.CellStyle(7)
if !s.Bold || s.FG != (Color{Kind: 1, Index: 2}) {
t.Errorf("style of w = %+v", s)
}
if got := term.Text(); got != "Hello, world!\nsecond line" {
t.Errorf("text = %q", got)
}
if c := r.Cursor(); !c.InView || c.X != 11 || c.Y != 1 {
t.Errorf("cursor = %+v", c)
}
}
func TestWideAndGraphemes(t *testing.T) {
loadLib(t)
term, _ := NewTerminal(10, 2, Effects{})
defer term.Free()
term.Write([]byte("\x1b[?2027h世👍🏽"))
r, _ := NewRenderState()
defer r.Free()
r.Update(term)
r.Rows()
r.NextRow()
cells := r.RowCells()
if cells[0].Codepoint != '世' || cells[0].Wide != WideChar || cells[1].Wide != SpacerTail {
t.Errorf("cells = %+v", cells[:2])
}
if !cells[2].Grapheme {
t.Fatalf("cell 2 = %+v", cells[2])
}
if got := string(r.CellGraphemes(2, nil)); got != "👍🏽" {
t.Errorf("graphemes = %q", got)
}
}
// The rows of a shell's prompt (OSC 133): where it starts, and those its
// input wraps onto, which the terminal and a render state tell alike.
func TestRowPrompt(t *testing.T) {
loadLib(t)
term, _ := NewTerminal(10, 5, Effects{})
defer term.Free()
term.Write([]byte("out\r\n\x1b]133;A\a$ \x1b]133;B\aecho hello world"))
want := []struct {
prompt RowPrompt
wrap bool
}{{NoPrompt, false}, {PromptStart, true}, {PromptContinuation, false}, {NoPrompt, false}}
r, _ := NewRenderState()
defer r.Free()
r.Update(term)
r.Rows()
for y, w := range want {
r.NextRow()
if p, wrap := term.Row(y); p != w.prompt || wrap != w.wrap {
t.Errorf("row %d is %d, wrapping %v; want %d, %v", y, p, wrap, w.prompt, w.wrap)
}
if p := r.RowPrompt(); p != w.prompt {
t.Errorf("render state's row %d is %d, want %d", y, p, w.prompt)
}
}
if p, _ := term.Row(99); p != NoPrompt {
t.Errorf("row 99 is %d", p)
}
}
func TestEncoders(t *testing.T) {
loadLib(t)
term, _ := NewTerminal(80, 24, Effects{})
defer term.Free()
k, err := NewKeyEncoder()
if err != nil {
t.Fatal(err)
}
defer k.Free()
k.Sync(term, false)
for _, c := range []struct {
ev KeyEvent
want string
}{
{KeyEvent{Action: KeyPress, Key: KeyEnter}, "\r"},
{KeyEvent{Action: KeyPress, Key: KeyC, Mods: ModCtrl, Unshifted: 'c'}, "\x03"},
{KeyEvent{Action: KeyPress, Key: KeyArrowUp}, "\x1b[A"},
{KeyEvent{Action: KeyPress, Key: KeyA, Text: "a", Unshifted: 'a'}, "a"},
{KeyEvent{Action: KeyPress, Key: KeyA, Mods: ModShift, Consumed: ModShift, Text: "A", Unshifted: 'a'}, "A"},
{KeyEvent{Action: KeyRelease, Key: KeyA, Unshifted: 'a'}, ""},
{KeyEvent{Action: KeyPress, Key: KeyEscape}, "\x1b"},
{KeyEvent{Action: KeyPress, Key: KeyF1}, "\x1bOP"},
} {
if got := string(k.Encode(c.ev)); got != c.want {
t.Errorf("Encode(%+v) = %q, want %q", c.ev, got, c.want)
}
}
term.Write([]byte("\x1b[?1h"))
k.Sync(term, false)
if got := string(k.Encode(KeyEvent{Action: KeyPress, Key: KeyArrowUp})); got != "\x1bOA" {
t.Errorf("up in cursor key mode = %q", got)
}
m, err := NewMouseEncoder()
if err != nil {
t.Fatal(err)
}
defer m.Free()
m.Sync(term, 800, 480, 10, 20, 0, 0, false)
if got := m.Encode(MousePress, ButtonLeft, 0, 5, 5); got != nil {
t.Errorf("press without tracking = %q", got)
}
term.Write([]byte("\x1b[?1000h\x1b[?1006h"))
m.Sync(term, 800, 480, 10, 20, 0, 0, false)
if got := string(m.Encode(MousePress, ButtonLeft, 0, 25, 45)); got != "\x1b[<0;3;3M" {
t.Errorf("press = %q", got)
}
if got := string(m.Encode(MouseRelease, ButtonLeft, 0, 25, 45)); got != "\x1b[<0;3;3m" {
t.Errorf("release = %q", got)
}
if got := string(EncodeFocus(true)); got != "\x1b[I" {
t.Errorf("focus = %q", got)
}
if got := string(EncodePaste("a\nb", false)); got != "a\rb" {
t.Errorf("paste = %q", got)
}
if got := string(EncodePaste("a\nb", true)); got != "\x1b[200~a\nb\x1b[201~" {
t.Errorf("bracketed paste = %q", got)
}
if PasteIsSafe("rm -rf /\n") || !PasteIsSafe("ls") {
t.Error("PasteIsSafe")
}
}
func TestSelection(t *testing.T) {
loadLib(t)
term, _ := NewTerminal(20, 3, Effects{})
defer term.Free()
term.Write([]byte("hello world\r\nsecond"))
g, err := NewGesture(500e6, 5)
if err != nil {
t.Fatal(err)
}
defer g.Free(term)
geo := Geometry{Columns: 20, CellWidth: 10, Height: 60}
a, _ := term.CellAt(0, 0)
g.Press(term, a, 2, 5, 1)
b, _ := term.CellAt(4, 0)
s, ok := g.Drag(term, b, 46, 5, geo, false)
if !ok {
t.Fatal("no selection")
}
term.SetSelection(&s)
g.Release(term, &b)
if text, ok := term.SelectionText(); !ok || text != "hello" {
t.Errorf("selection = %q, %v", text, ok)
}
// A double click selects the word.
c, _ := term.CellAt(7, 0)
g.Press(term, c, 72, 5, 600e6)
g.Release(term, &c)
s, ok = g.Press(term, c, 72, 5, 700e6)
if !ok {
t.Fatal("double click selected nothing")
}
term.SetSelection(&s)
if text, _ := term.SelectionText(); text != "world" {
t.Errorf("word = %q", text)
}
all, _ := term.SelectAll()
term.SetSelection(&all)
if text, _ := term.SelectionText(); text != "hello world\nsecond" {
t.Errorf("all = %q", text)
}
term.SetSelection(nil)
if _, ok := term.SelectionText(); ok {
t.Error("selection after clearing it")
}
}
func TestScrollback(t *testing.T) {
loadLib(t)
term, _ := NewTerminal(10, 3, Effects{})
defer term.Free()
for i := range 10 {
term.Write([]byte(strings.Repeat(string(rune('0'+i)), 3) + "\r\n"))
}
sb := term.Scrollbar()
if sb.Total != 11 || sb.Len != 3 || sb.Offset != 8 || !term.AtBottom() {
t.Errorf("scrollbar = %+v", sb)
}
term.ScrollBy(-2)
if term.AtBottom() || term.Scrollbar().Offset != 6 {
t.Errorf("after scrolling up: %+v", term.Scrollbar())
}
r, _ := NewRenderState()
defer r.Free()
r.Update(term)
if got := rowText(r); got[0] != "666" {
t.Errorf("rows = %q", got)
}
term.ScrollToBottom()
if !term.AtBottom() {
t.Error("not at the bottom")
}
term.Resize(5, 3, 10, 20)
if cols, rows := term.Size(); cols != 5 || rows != 3 {
t.Errorf("size = %d×%d", cols, rows)
}
}
// The keyboard's modes a Mirror passes on: modifyOtherKeys follows CSI > 4
// alone, not the pointer shape (OSC 22), and the Kitty keyboard flags
// their own sequences.
func TestKeyboardModes(t *testing.T) {
loadLib(t)
term, _ := NewTerminal(20, 3, Effects{})
defer term.Free()
if term.ModifyOtherKeys() {
t.Error("modifyOtherKeys on in a new terminal")
}
term.Write([]byte("\x1b]22;pointer\x1b\\"))
if term.MouseShape() != 3 || term.ModifyOtherKeys() {
t.Errorf("after OSC 22: shape %d, modifyOtherKeys %v", term.MouseShape(), term.ModifyOtherKeys())
}
term.Write([]byte("text\x1b[>4;2m"))
if !term.ModifyOtherKeys() {
t.Error("modifyOtherKeys off after CSI > 4 ; 2 m")
}
term.Write([]byte("\x1b[>4;1m"))
if term.ModifyOtherKeys() {
t.Error("modifyOtherKeys on after CSI > 4 ; 1 m")
}
term.Write([]byte("\x1b[>5u"))
if f := term.KittyKeyboardFlags(); f != 5 {
t.Errorf("kitty keyboard flags %d, want 5", f)
}
// A sequence split across writes sets it, with the Kitty protocol on
// as well; a reset of the key formats, and of the terminal, clears it.
term.Write([]byte("\x1b[>4"))
term.Write([]byte(";2m"))
if !term.ModifyOtherKeys() {
t.Error("modifyOtherKeys off after a split CSI > 4 ; 2 m")
}
for _, reset := range []string{"\x1b[>m", "\x1b[>4n", "\x1bc"} {
term.Write([]byte("\x1b[>4;2m" + reset))
if term.ModifyOtherKeys() {
t.Errorf("modifyOtherKeys on after %q", reset)
}
}
term.Write([]byte("\x1b[>4;2m"))
term.Reset()
if term.ModifyOtherKeys() {
t.Error("modifyOtherKeys on after Reset")
}
}
// A search finds text in the scrollback and on the screen, ignoring the
// case of ASCII letters; selecting goes from the newest match to older
// ones, scrolling to them, and the viewport's matches are where it shows.
func TestSearch(t *testing.T) {
loadLib(t)
term, _ := NewTerminal(20, 3, Effects{})
defer term.Free()
for i := range 10 {
line := "line"
if i%3 == 0 {
line = "an Error here"
}
term.Write([]byte(line + "\r\n"))
}
s, err := NewSearch(term)
if err != nil {
t.Fatal(err)
}
defer s.Free()
run := func() {
for range 1000 {
switch s.Tick() {
case SearchComplete:
return
case SearchFeedRequired:
s.Feed()
}
}
t.Fatal("the search never completed")
}
s.SetText("error")
run()
if n := s.Total(); n != 4 {
t.Fatalf("total = %d, want 4", n)
}
if _, ok := s.Selected(); ok {
t.Error("a match is selected before any was")
}
text := func() string {
m, ok := s.SelectedMatch()
if !ok {
return ""
}
term.SetSelection(&m)
got, _ := term.SelectionText()
term.SetSelection(nil)
return got
}
if !s.Select(false) {
t.Fatal("nothing to select")
}
if i, _ := s.Selected(); i != 0 || text() != "Error" {
t.Errorf("selected %d %q", i, text())
}
// The next, row 6, is above the screen: selecting it scrolls nothing,
// and its row is where to scroll.
s.Select(false)
m, _ := s.SelectedMatch()
a, _ := m.Ends()
row, ok := term.ScreenRow(a)
if i, _ := s.Selected(); i != 1 || !term.AtBottom() || !ok || row != 6 {
t.Errorf("selected %d at row %d (%v), at the bottom: %v", i, row, ok, term.AtBottom())
}
if _, _, shown := term.ViewportPoint(a); shown {
t.Error("a match above the viewport shows")
}
term.ScrollToRow(row)
s.Feed()
var shown int
for _, m := range s.ViewportMatches(nil) {
a, b := m.Ends()
x0, y0, ok0 := term.ViewportPoint(a)
x1, y1, ok1 := term.ViewportPoint(b)
if ok0 && ok1 && y0 < 3 {
shown++
if x0 != 3 || x1 != 7 || y0 != y1 {
t.Errorf("match at %d,%d–%d,%d", x0, y0, x1, y1)
}
}
}
if shown != 1 {
t.Errorf("%d matches show, want 1", shown)
}
s.Select(true)
s.Select(true)
if i, _ := s.Selected(); i != 3 {
t.Errorf("selected %d after wrapping back, want 3", i)
}
s.SetText("")
run()
if s.Total() != 0 {
t.Errorf("total = %d with no text", s.Total())
}
}
// A paste with mode 5522 set tells the program what the clipboard holds;
// the program's read with the event's password is granted and served in
// chunks; a terminal that does not answer a read stays silent.
func TestPasteEvent(t *testing.T) {
loadLib(t)
png := bytes.Repeat([]byte("\x89PNG\r\n\x1a\n0123456789"), 500) // over two chunks
var out bytes.Buffer
term, err := NewTerminal(80, 24, Effects{
WritePTY: func(p []byte) { out.Write(p) },
ClipboardRead: func(req ClipboardRead) (ClipboardReply, ClipboardAnswer) {
if !req.Granted {
return ClipboardReply{}, ClipboardRefused
}
return ClipboardReply{Contents: map[string][]byte{"image/png": png, "text/plain": []byte("hi")}}, ClipboardAnswered
},
})
if err != nil {
t.Fatal(err)
}
defer term.Free()
if term.PasteEvent([]string{"text/plain", "image/png"}) {
t.Fatal("an event without the mode")
}
term.Write([]byte("\x1b[?5522h"))
if !term.PasteEvent([]string{"text/plain", "image/png"}) {
t.Fatal("no event with the mode")
}
event := out.String()
out.Reset()
// ESC]5522;type=read:status=OK:pw=<b64>ESC\ ... DATA ... DONE
_, after, ok := strings.Cut(event, ":pw=")
if !ok || !strings.Contains(event, "status=DATA:mime=Lg==") || !strings.HasSuffix(event, "status=DONE:pw="+after[:strings.Index(after, "\x1b")]+"\x1b\\") {
t.Fatalf("event = %q", event)
}
pw := after[:strings.Index(after, "\x1b")]
listing, _ := base64.StdEncoding.DecodeString(event[strings.Index(event, "Lg==:pw="+pw+";")+len("Lg==:pw="+pw+";") : strings.Index(event, "\x1b\\\x1b]5522;type=read:status=DONE")])
if string(listing) != "text/plain image/png\n" {
t.Errorf("listing = %q", listing)
}
// The program reads the PNG with the password.
name := base64.StdEncoding.EncodeToString([]byte("Paste event"))
mime := base64.StdEncoding.EncodeToString([]byte("image/png"))
term.Write([]byte("\x1b]5522;type=read:pw=" + pw + ":name=" + name + ";" + mime + "\x1b\\"))
reply := out.String()
out.Reset()
if !strings.HasPrefix(reply, "\x1b]5522;type=read:status=OK\x1b\\") || !strings.HasSuffix(reply, "\x1b]5522;type=read:status=DONE\x1b\\") {
t.Fatalf("reply = %.80q…", reply)
}
var got []byte
for _, pkt := range strings.Split(reply, "\x1b\\") {
if _, data, ok := strings.Cut(pkt, "status=DATA:mime="+mime+";"); ok {
b, err := base64.StdEncoding.DecodeString(data)
if err != nil {
t.Fatal(err)
}
got = append(got, b...)
}
}
if !bytes.Equal(got, png) {
t.Errorf("read %d bytes, want %d", len(got), len(png))
}
// The password is used up: the same read again is not granted, and
// unanswered, which leaves the program nothing at all.
term.Write([]byte("\x1b]5522;type=read:pw=" + pw + ":name=" + name + ";" + mime + "\x1b\\"))
if out.Len() != 0 {
t.Errorf("an unanswered read wrote %q", out.String())
}
// A later query is answered as usual.
term.Write([]byte("\x1b[6n"))
if out.String() != "\x1b[1;1R" {
t.Errorf("after silence, the cursor report = %q", out.String())
}
// A read that writes no refusal (OSC 52's) does not silence the next.
term.Write([]byte("\x1b]52;c;?\x1b\\"))
if term.silent {
t.Error("an OSC 52 read left the terminal silent")
}
}
// A deferred read (ClipboardDeferred) holds the library's refusal back,
// and AnswerClipboard answers it, allowed or denied, with the selector,
// terminator and refusal the library wrote.
func TestDeferredClipboardRead(t *testing.T) {
loadLib(t)
var out bytes.Buffer
var deferred *DeferredClipboardRead
term, err := NewTerminal(80, 24, Effects{
WritePTY: func(p []byte) { out.Write(p) },
ClipboardRead: func(req ClipboardRead) (ClipboardReply, ClipboardAnswer) {
deferred = &DeferredClipboardRead{}
return ClipboardReply{Deferred: deferred}, ClipboardDeferred
},
})
if err != nil {
t.Fatal(err)
}
defer term.Free()
text := map[string][]byte{"text/plain": []byte("hello")}
for _, c := range []struct {
name string
read string
allow bool
contents map[string][]byte
want string
}{
{"allow c", "\x1b]52;c;?\x1b\\", true, text, "\x1b]52;c;aGVsbG8=\x1b\\"},
{"deny c", "\x1b]52;c;?\x1b\\", false, nil, "\x1b]52;c;\x1b\\"},
{"deny s bel", "\x1b]52;s;?\x07", false, nil, "\x1b]52;s;\x07"},
{"allow p", "\x1b]52;p;?\x1b\\", true, text, "\x1b]52;p;aGVsbG8=\x1b\\"},
{"allow empty", "\x1b]52;c;?\x1b\\", true, nil, "\x1b]52;c;\x1b\\"},
} {
out.Reset()
deferred = nil
term.Write([]byte(c.read))
if out.Len() != 0 {
t.Fatalf("%s: a deferred read wrote %q before it was answered", c.name, out.String())
}
if deferred == nil {
t.Fatalf("%s: the read was not deferred", c.name)
}
term.AnswerClipboard(deferred, c.allow, c.contents, nil)
if got := out.String(); got != c.want {
t.Errorf("%s: answered %q, want %q", c.name, got, c.want)
}
}
// A nil handle answers nothing.
out.Reset()
term.AnswerClipboard(nil, true, text, nil)
if out.Len() != 0 {
t.Errorf("a nil deferred read wrote %q", out.String())
}
}
// A deferred Kitty protocol read is answered exactly as the library would
// answer a reply: compare a read answered synchronously with the same read
// deferred and answered through AnswerClipboard, for an id, a listing,
// chunks, and a denial.
func TestDeferredClipboardReadKitty(t *testing.T) {
loadLib(t)
png := bytes.Repeat([]byte("\x89PNG\r\n\x1a\n0123456789"), 300) // over one 4096-byte chunk
contents := map[string][]byte{"image/png": png, "text/plain": []byte("hi")}
available := []string{"text/plain", "image/png"}
b64 := func(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) }
want := func(t *testing.T, read string, req func(ClipboardRead) (ClipboardReply, ClipboardAnswer)) string {
t.Helper()
var out bytes.Buffer
term, err := NewTerminal(80, 24, Effects{
WritePTY: func(p []byte) { out.Write(p) },
ClipboardRead: req,
})
if err != nil {
t.Fatal(err)
}
defer term.Free()
term.Write([]byte(read))
return out.String()
}
for _, c := range []struct {
name string
read string
reply ClipboardReply
deny bool
}{
{"plain", "\x1b]5522;type=read;" + b64("text/plain") + "\x1b\\", ClipboardReply{Contents: contents}, false},
{"id", "\x1b]5522;type=read:id=abc.123;" + b64("text/plain") + "\x1b\\", ClipboardReply{Contents: contents}, false},
{"listing", "\x1b]5522;type=read:id=9;" + b64("text/plain image/png .") + "\x1b\\", ClipboardReply{Contents: contents, Available: available}, false},
{"listing only", "\x1b]5522;type=read;Lg==\x1b\\", ClipboardReply{Available: available}, false},
{"primary", "\x1b]5522;type=read:loc=primary:id=x;dGV4dC9wbGFpbg==\x1b\\", ClipboardReply{Contents: contents}, false},
{"bel", "\x1b]5522;type=read:id=7;" + b64("text/plain") + "\x07", ClipboardReply{Contents: contents}, false},
{"deny", "\x1b]5522;type=read:id=d;" + b64("text/plain") + "\x1b\\", ClipboardReply{}, true},
} {
sync := want(t, c.read, func(req ClipboardRead) (ClipboardReply, ClipboardAnswer) {
return c.reply, ClipboardAnswered
})
var deferred *DeferredClipboardRead
out := &bytes.Buffer{}
term, err := NewTerminal(80, 24, Effects{
WritePTY: func(p []byte) { out.Write(p) },
ClipboardRead: func(req ClipboardRead) (ClipboardReply, ClipboardAnswer) {
deferred = &DeferredClipboardRead{}
return ClipboardReply{Deferred: deferred}, ClipboardDeferred
},
})
if err != nil {
t.Fatal(err)
}
term.Write([]byte(c.read))
if out.Len() != 0 {
t.Fatalf("%s: a deferred read wrote %q before it was answered", c.name, out.String())
}
term.AnswerClipboard(deferred, !c.deny, c.reply.Contents, c.reply.Available)
term.Free()
if got := out.String(); got != sync {
t.Errorf("%s: deferred %q, synchronous %q", c.name, got, sync)
}
if sync == "" {
t.Errorf("%s: the library answered nothing", c.name)
}
}
// A listing the clipboard has nothing for is still sent, as the
// library's own encoder writes it.
var listing *DeferredClipboardRead
out := &bytes.Buffer{}
term, err := NewTerminal(80, 24, Effects{
WritePTY: func(p []byte) { out.Write(p) },
ClipboardRead: func(req ClipboardRead) (ClipboardReply, ClipboardAnswer) {
listing = &DeferredClipboardRead{}
return ClipboardReply{Deferred: listing}, ClipboardDeferred
},
})
if err != nil {
t.Fatal(err)
}
term.Write([]byte("\x1b]5522;type=read;Lg==\x1b\\"))
term.AnswerClipboard(listing, true, nil, nil)
term.Free()
wantEmpty := "\x1b]5522;type=read:status=OK\x1b\\" +
"\x1b]5522;type=read:status=DATA:mime=Lg==\x1b\\" +
"\x1b]5522;type=read:status=DONE\x1b\\"
if got := out.String(); got != wantEmpty {
t.Errorf("an empty listing: %q, want %q", got, wantEmpty)
}
}