MIT-Lizenz, weniger Speicher pro Tab, schnellere Ausgabe und Manager (#47)

* MIT-Lizenz; Terminal-Verlauf kompakt, schnellerer Bildlauf, Manager mit vielen Verbindungen schneller

- LICENSE (MIT), winget/Homebrew/apt-Metadaten, README, Webseite, --version
- termemu: Verlauf mit 8 statt 112 Byte pro Zeichen, Ringpuffer
- third_party/vt: angepasste Kopie (rotateLines, SetScrollbackHook)
- Store: Connections() zwischengespeichert; Manager: buildRows ohne Teillisten,
  Fußzeile misst Breiten einmal
- Benchmarks: make bench

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018i4GUjBAAPCAZVnGzCZxdS

* Testprogramm aus dem Commit entfernt

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018i4GUjBAAPCAZVnGzCZxdS

* Testprogramm entfernt, *.test ignorieren

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018i4GUjBAAPCAZVnGzCZxdS

* TestSerialSession: auf stehenden Prompt warten statt auf das erste #

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018i4GUjBAAPCAZVnGzCZxdS

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
db9979andClaude Opus 5.5 authored and GitHub committed 2026-11-06 10:02:26 +01:00
1 parent e5dc9158c5
commit 2513a7818d
61 files changed
+7312 -68

No files matched your search

+2
View File
@@ -13,6 +13,8 @@ jobs:
with:
go-version-file: go.mod
- run: go vet ./... && go test ./...
- name: Terminal-Emulator (eigene Kopie in third_party/vt)
run: cd third_party/vt && go test ./...
- name: Cross-Compile
run: |
for t in windows/arm64 windows/386 windows/amd64 darwin/arm64 darwin/amd64 linux/amd64; do
+2
View File
@@ -5,3 +5,5 @@
*.new
.DS_Store
tools/dev/gifs/out/
*.test
*.out
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Dominik Bornhäußer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+6 -1
View File
@@ -6,12 +6,17 @@ PKG := github.com/db9979/sshtermy/internal/version
LDFLAGS := -s -w -X $(PKG).Version=$(VERSION) -X $(PKG).Commit=$(COMMIT) -X $(PKG).Date=$(DATE) -X $(PKG).UpdatePubKey=$(UPDATE_PUBKEY)
TARGETS := windows/arm64 windows/386 windows/amd64 darwin/arm64 darwin/amd64 linux/amd64 linux/arm64
.PHONY: build test dist clean run
.PHONY: build test bench dist clean run
build:
CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o bin/sshtermy ./cmd/sshtermy
test:
go vet ./... && go test ./...
cd third_party/vt && go test ./...
# Leistung: Terminal-Durchsatz, Speicher pro Tab, Manager mit 500 Verbindungen
bench:
go test -run '^$$' -bench . -benchtime 2s ./internal/termemu ./internal/ui ./internal/store
dist: test
@mkdir -p dist
+9
View File
@@ -373,6 +373,7 @@ Windows-Anmeldung ──DPAPI CryptProtectData───────────
```
make test # go vet + Tests
make bench # Leistung: Terminal-Durchsatz, Speicher pro Tab, Manager mit 500 Verbindungen
make build # bin/sshtermy
make dist # alle Plattformen nach dist/ + checksums.txt
```
@@ -389,6 +390,9 @@ python3 tools/dev/fakellm.py # Test-LLM auf 127.0.0.1:11434 (/v1/ch
SSHTERMY_HOME=/tmp/sth go run ./cmd/sshtermy
```
Der Terminal-Emulator liegt als angepasste Kopie in `third_party/vt` (schnellerer Bildlauf, kompakter Verlauf),
siehe `third_party/vt/README.sshtermy.md`.
## Nächste Schritte (Vorschläge)
1. Windows-Ressourcen (Icon, Versionsinfo) und Code-Signing der `.exe`, macOS Notarisierung.
@@ -448,3 +452,8 @@ betreffen. Abgeglichen wird beim Start, wenige Sekunden nach jeder Änderung und
Zum Ausprobieren ohne NAS: `go run ./tools/dev/devdav` (http auf Port 5005) oder `go run ./tools/dev/devdav -tls -addr 127.0.0.1:5006`
(selbstsigniert), Benutzer `dominik`, Passwort `nas-pw`.
## Lizenz
sshTermy steht unter der [MIT-Lizenz](LICENSE): Du darfst es benutzen, kopieren, ändern und weitergeben, auch
kommerziell, solange der Urheberhinweis und der Lizenztext dabei bleiben. Idee: Dominik Bornhäußer.
+9
View File
@@ -376,6 +376,7 @@ Windows login ──DPAPI CryptProtectData────────────
```
make test # go vet + tests
make bench # performance: terminal throughput, memory per tab, manager with 500 connections
make build # bin/sshtermy
make dist # all platforms to dist/ + checksums.txt
```
@@ -392,6 +393,9 @@ python3 tools/dev/fakellm.py # test LLM on 127.0.0.1:11434 (/v1/cha
SSHTERMY_HOME=/tmp/sth go run ./cmd/sshtermy
```
The terminal emulator is a patched copy in `third_party/vt` (faster scrolling, compact scrollback),
see `third_party/vt/README.sshtermy.md`.
## Next steps (suggestions)
1. Windows resources (icon, version info) and code signing of the `.exe`, macOS notarization.
@@ -451,3 +455,8 @@ Syncing happens at start, a few seconds after every change and every 5 minutes;
To try it without a NAS: `go run ./tools/dev/devdav` (http on port 5005) or `go run ./tools/dev/devdav -tls -addr 127.0.0.1:5006`
(self-signed), user `dominik`, password `nas-pw`.
## License
sshTermy is released under the [MIT License](LICENSE): you may use, copy, change and pass it on, also commercially,
as long as the copyright notice and the license text stay included. Idea: Dominik Bornhäußer.
+2
View File
@@ -34,3 +34,5 @@ require (
github.com/xo/terminfo v1.0.0 // indirect
golang.org/x/sync v0.24.0 // indirect
)
replace github.com/charmbracelet/x/vt => ./third_party/vt
-2
View File
@@ -26,8 +26,6 @@ github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSg
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=
github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo=
github.com/charmbracelet/x/vt v0.1.0 h1:oVueL3dwH/DlY/z6R6XHA9PQ/w3LdCCq99600Vs48vA=
github.com/charmbracelet/x/vt v0.1.0/go.mod h1:u1LOIABor9JqY54oZdktK3TCRrgzP6tzHrDYx1nd3wY=
github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM=
github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k=
github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8=
+68
View File
@@ -0,0 +1,68 @@
package store
import (
"fmt"
"testing"
"github.com/db9979/sshtermy/internal/domain"
)
// Connections() wird zwischengespeichert: jede Änderung muss trotzdem
// sofort sichtbar sein, und Aufrufer dürfen ihre Kopie verändern.
func TestConnectionsCacheFollowsChanges(t *testing.T) {
t.Setenv("SSHTERMY_HOME", t.TempDir())
s, err := Open()
if err != nil {
t.Fatal(err)
}
if err := s.Init([]byte("correct horse"), false); err != nil {
t.Fatal(err)
}
c, _ := s.UpsertConnection(domain.Connection{Alias: "b", Host: "h", Username: "u", Auth: domain.AuthAgent})
cs := s.Connections()
cs[0].Alias = "verändert"
if s.Connections()[0].Alias != "b" {
t.Fatal("Aufrufer hat den Zwischenspeicher verändert")
}
s.UpsertConnection(domain.Connection{Alias: "a", Host: "h2", Username: "u", Auth: domain.AuthAgent})
if cs := s.Connections(); len(cs) != 2 || cs[0].Alias != "a" {
t.Fatalf("neue Verbindung fehlt oder falsch sortiert: %v", cs)
}
s.Touch(c.ID)
if got, _ := s.Connection(c.ID); s.Connections()[1].LastUsed != got.LastUsed {
t.Fatal("Touch nicht sichtbar")
}
if _, err := s.ApplySync(0, func(d *domain.Data) { d.Connections[0].Host = "neu" }); err != nil {
t.Fatal(err)
}
found := false
for _, x := range s.Connections() {
found = found || x.Host == "neu"
}
if !found {
t.Fatal("Sync-Stand nicht sichtbar")
}
s.DeleteConnection(c.ID)
if len(s.Connections()) != 1 {
t.Fatal("Löschen nicht sichtbar")
}
s.Lock()
if s.Connections() != nil {
t.Fatal("nach Sperren noch Verbindungen")
}
}
func BenchmarkConnections500(b *testing.B) {
b.Setenv("SSHTERMY_HOME", b.TempDir())
s, _ := Open()
s.Init([]byte("correct horse"), false)
cs := make([]domain.Connection, 500)
for i := range cs {
cs[i] = domain.Connection{Alias: fmt.Sprintf("srv-%03d", i), Host: "h", Username: "u", Auth: domain.AuthAgent, Group: fmt.Sprintf("G%d", i%10)}
}
s.AddConnections(cs)
b.ReportAllocs()
for b.Loop() {
_ = s.Connections()
}
}
+43 -1
View File
@@ -15,6 +15,7 @@ import (
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/db9979/sshtermy/internal/domain"
@@ -57,9 +58,26 @@ type Store struct {
OnChange func()
rev uint64 // zählt lokale Änderungen
// Zwischenspeicher für Connections(): bei 500 Verbindungen kostet das
// Sortieren pro Bild mehrere Millisekunden, und der Manager fragt pro
// Bild mehrmals. gen zählt jede Änderung (persist, Laden, Sperren); ein
// Eintrag gilt nur, solange seine gen aktuell ist.
gen atomic.Uint64
cmu sync.Mutex
conns connCache
stats cmdStats // Befehlsstatistik (cmdstats.go), nur lokal
}
type connCache struct {
gen uint64
ok bool
cs []domain.Connection
}
// changed macht den Zwischenspeicher ungültig.
func (s *Store) changed() { s.gen.Add(1) }
// Open öffnet (oder bereitet vor) den Store im Standardordner.
func Open() (*Store, error) {
dir, err := Dir()
@@ -88,6 +106,7 @@ func (s *Store) Init(password []byte, useDPAPI bool) error {
s.data = domain.NewData()
s.data.Settings.UseDPAPI = s.V.HasDPAPI()
s.mu.Unlock()
s.changed()
return s.save()
}
@@ -100,6 +119,7 @@ func (s *Store) AfterUnlock() error {
s.mu.Lock()
s.data = d
s.mu.Unlock()
s.changed()
return nil
}
@@ -108,6 +128,7 @@ func (s *Store) Lock() {
s.mu.Lock()
s.data = nil
s.mu.Unlock()
s.changed()
s.forgetStats()
s.V.Lock()
}
@@ -126,6 +147,7 @@ func (s *Store) save() error {
}
func (s *Store) persist() error {
s.changed()
s.mu.RLock()
defer s.mu.RUnlock()
if s.data == nil {
@@ -149,12 +171,32 @@ func newID() string {
}
// Connections: sortiert nach Ordner, dann Reihenfolge im Ordner, dann Alias.
// Der Aufrufer bekommt eine eigene Kopie und darf sie verändern.
func (s *Store) Connections() []domain.Connection {
g := s.gen.Load()
s.cmu.Lock()
if c := s.conns; c.ok && c.gen == g {
s.cmu.Unlock()
return append([]domain.Connection(nil), c.cs...)
}
s.cmu.Unlock()
s.mu.RLock()
defer s.mu.RUnlock()
if s.data == nil {
s.mu.RUnlock()
return nil
}
out := s.sortedConns()
s.mu.RUnlock()
s.cmu.Lock()
s.conns = connCache{gen: g, ok: true, cs: out}
s.cmu.Unlock()
return append([]domain.Connection(nil), out...)
}
// sortedConns (Aufrufer hält s.mu).
func (s *Store) sortedConns() []domain.Connection {
out := append([]domain.Connection(nil), s.data.Connections...)
for i := range out {
out[i] = s.withLocalKey(out[i])
+18 -15
View File
@@ -96,15 +96,19 @@ func (t *Term) ScrollbackLen() int {
if t.AltScreen() {
return 0
}
return t.emu.ScrollbackLen()
return t.sb.Len()
}
// cellAt liefert die Zelle im Gesamtpuffer.
func (t *Term) cellAt(sb int, p Pos) *uv.Cell {
// cellAt liefert die Zelle im Gesamtpuffer; ok = false, wenn dort keine
// ist (hinter dem Zeilenende im Verlauf, außerhalb des Bildschirms).
func (t *Term) cellAt(sb int, p Pos) (uv.Cell, bool) {
if p.Line < sb {
return t.emu.ScrollbackCellAt(p.Col, p.Line)
return t.sb.cell(p.Col, p.Line)
}
return t.emu.CellAt(p.Col, p.Line-sb)
if c := t.emu.CellAt(p.Col, p.Line-sb); c != nil {
return *c, true
}
return uv.Cell{}, false
}
// Render zeichnet den Bildschirm, um offset Zeilen in den Scrollback
@@ -122,11 +126,10 @@ func (t *Term) render(offset int, sel *Sel, hook func(line, x int, c *uv.Cell))
for y := 0; y < h; y++ {
abs := first + y
for x := 0; x < w; x++ {
c := t.cellAt(sb, Pos{abs, x})
if c == nil {
line[x] = uv.EmptyCell
if c, ok := t.cellAt(sb, Pos{abs, x}); ok {
line[x] = c
} else {
line[x] = *c
line[x] = uv.EmptyCell
}
if sel != nil && !line[x].IsZero() && sel.Contains(Pos{abs, x}) {
if line[x].Content == "" {
@@ -172,9 +175,9 @@ func (t *Term) Text(s Sel) string {
}
var sbuf strings.Builder
for x := from; x <= to; x++ {
c := t.cellAt(sb, Pos{l, x})
c, ok := t.cellAt(sb, Pos{l, x})
switch {
case c == nil:
case !ok:
sbuf.WriteByte(' ')
case c.IsZero():
// zweite Hälfte eines breiten Zeichens
@@ -196,8 +199,8 @@ func (t *Term) WordAt(p Pos) Sel {
w, _ := t.Size()
sb := t.ScrollbackLen()
isWord := func(x int) bool {
c := t.cellAt(sb, Pos{p.Line, x})
if c == nil {
c, ok := t.cellAt(sb, Pos{p.Line, x})
if !ok {
return false
}
if c.IsZero() {
@@ -235,9 +238,9 @@ func (t *Term) LineText(line int) (text string, cols []int) {
cols = make([]int, w+1)
last := 0
for x := 0; x < w; x++ {
c := t.cellAt(sb, Pos{line, x})
c, ok := t.cellAt(sb, Pos{line, x})
switch {
case c == nil, c.Content == "" && !c.IsZero():
case !ok, c.Content == "" && !c.IsZero():
cols[x] = b.Len()
b.WriteByte(' ')
case c.IsZero():
+221
View File
@@ -0,0 +1,221 @@
package termemu
import (
"sync"
"unicode/utf8"
uv "github.com/charmbracelet/ultraviolet"
)
// Platzsparender Verlauf (Scrollback)
//
// Der Emulator (charmbracelet/x/vt) hebt jede Zeile, die oben aus dem Bild
// läuft, als volle Zellen auf: 112 Byte pro Zeichen (Text, Stil mit drei
// Farben, Link, Breite). Bei 5000 Zeilen à 150 Zeichen sind das rund 80 MB
// pro Tab, mit 8 Tabs also mehrere hundert MB. Hier liegt jede Zeile
// kompakt: 8 Byte pro Zeichen, Stile und Links nur einmal pro Zeile. Nach
// jedem Write zieht Term die neuen Zeilen aus dem Emulator ab (drain) und
// leert dessen Puffer wieder. Der Ringpuffer verwirft die älteste Zeile in
// O(1) statt das ganze Feld umzukopieren.
// sbCell: Zeichen (rune, < 0 = Index in extra), Stil- und Linknummer der
// Zeile (0 = keiner) und Breite.
type sbCell struct {
r int32
st, ln uint8
w uint8
}
type sbLine struct {
cells []sbCell
styles []uv.Style // styles[0] = kein Stil
links []uv.Link // links[0] = kein Link
extra []string // Grapheme aus mehreren Runen (Emoji, Akzente)
raw uv.Line // Ausweichweg für Zeilen mit über 255 Stilen
}
type scrollback struct {
mu sync.Mutex
lines []sbLine // Ring, head = älteste Zeile
head int
n int
max int
}
func newScrollback(max int) *scrollback { return &scrollback{max: max} }
func (s *scrollback) Len() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.n
}
func (s *scrollback) clear() {
s.mu.Lock()
s.lines, s.head, s.n = nil, 0, 0
s.mu.Unlock()
}
// push hängt eine Zeile an (die Zellen werden kopiert, line darf danach
// wiederverwendet werden).
func (s *scrollback) push(line uv.Line) {
l := encodeLine(line)
s.mu.Lock()
defer s.mu.Unlock()
if s.max <= 0 {
return
}
if s.n < s.max {
if len(s.lines) < s.max {
s.lines = append(s.lines, l)
} else {
s.lines[(s.head+s.n)%s.max] = l
}
s.n++
return
}
s.lines[s.head] = l
s.head = (s.head + 1) % s.max
}
func (s *scrollback) at(y int) *sbLine {
if y < 0 || y >= s.n {
return nil
}
return &s.lines[(s.head+y)%len(s.lines)]
}
// cell liefert Zelle x der Zeile y (0 = älteste). ok = false hinter dem
// Zeilenende oder außerhalb des Verlaufs.
func (s *scrollback) cell(x, y int) (uv.Cell, bool) {
s.mu.Lock()
defer s.mu.Unlock()
l := s.at(y)
if l == nil {
return uv.Cell{}, false
}
return l.cell(x)
}
// line liefert die ganze Zeile y als Zellen (für Klartext).
func (s *scrollback) line(y int) uv.Line {
s.mu.Lock()
defer s.mu.Unlock()
l := s.at(y)
if l == nil {
return nil
}
if l.raw != nil {
return l.raw
}
out := make(uv.Line, len(l.cells))
for x := range out {
out[x], _ = l.cell(x)
}
return out
}
func (l *sbLine) cell(x int) (uv.Cell, bool) {
if l.raw != nil {
if x < 0 || x >= len(l.raw) {
return uv.Cell{}, false
}
return l.raw[x], true
}
if x < 0 || x >= len(l.cells) {
return uv.Cell{}, false
}
c := l.cells[x]
out := uv.Cell{Width: int(c.w)}
switch {
case c.r < 0:
out.Content = l.extra[-c.r-1]
case c.r == 0:
case c.r < utf8.RuneSelf:
out.Content = asciiStr[c.r]
default:
out.Content = string(rune(c.r))
}
if c.st > 0 {
out.Style = l.styles[c.st]
}
if c.ln > 0 {
out.Link = l.links[c.ln]
}
return out, true
}
var asciiStr = func() (t [utf8.RuneSelf]string) {
for i := range t {
t[i] = string(rune(i))
}
return t
}()
func encodeLine(line uv.Line) sbLine {
var l sbLine
l.cells = make([]sbCell, len(line))
for i := range line {
c := &line[i]
var sc sbCell
if c.Width >= 0 && c.Width < 256 {
sc.w = uint8(c.Width)
} else {
return rawLine(line)
}
switch r, size := utf8.DecodeRuneInString(c.Content); {
case c.Content == "":
case size == len(c.Content) && r != utf8.RuneError && r != 0:
sc.r = r
default:
l.extra = append(l.extra, c.Content)
sc.r = -int32(len(l.extra))
}
if !c.Style.IsZero() {
k := -1
for j := 1; j < len(l.styles); j++ {
if l.styles[j] == c.Style {
k = j
break
}
}
if k < 0 {
if len(l.styles) == 0 {
l.styles = append(l.styles, uv.Style{})
}
if len(l.styles) > 255 {
return rawLine(line)
}
l.styles = append(l.styles, c.Style)
k = len(l.styles) - 1
}
sc.st = uint8(k)
}
if c.Link != (uv.Link{}) {
k := -1
for j := 1; j < len(l.links); j++ {
if l.links[j] == c.Link {
k = j
break
}
}
if k < 0 {
if len(l.links) == 0 {
l.links = append(l.links, uv.Link{})
}
if len(l.links) > 255 {
return rawLine(line)
}
l.links = append(l.links, c.Link)
k = len(l.links) - 1
}
sc.ln = uint8(k)
}
l.cells[i] = sc
}
return l
}
func rawLine(line uv.Line) sbLine {
return sbLine{raw: append(uv.Line(nil), line...)}
}
+172
View File
@@ -0,0 +1,172 @@
package termemu
import (
"fmt"
"io"
"runtime"
"strings"
"testing"
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/x/ansi"
)
// Kompakter Verlauf: jede Zelle kommt so zurück, wie sie hineinging.
func TestScrollbackRoundTrip(t *testing.T) {
red := uv.Style{Fg: ansi.Red, Attrs: uv.AttrBold}
rgb := uv.Style{Fg: ansi.IndexedColor(208), Bg: ansi.Black, Underline: uv.UnderlineCurly}
link := uv.Link{URL: "https://example.org", Params: "id=1"}
line := uv.Line{
{Content: "a", Width: 1},
{Content: "ä", Width: 1, Style: red},
{Content: "漢", Width: 2, Style: rgb}, {},
{Content: "👍🏽", Width: 2, Link: link}, {},
{Content: " ", Width: 1, Style: red},
{Content: "é", Width: 1},
{Content: "\x00", Width: 1},
}
sb := newScrollback(10)
sb.push(line)
for x, want := range line {
got, ok := sb.cell(x, 0)
if !ok || got != want {
t.Fatalf("Spalte %d: %+v statt %+v", x, got, want)
}
}
if _, ok := sb.cell(len(line), 0); ok {
t.Fatal("hinter dem Zeilenende darf keine Zelle sein")
}
if got := sb.line(0).String(); got != line.String() {
t.Fatalf("Text %q statt %q", got, line.String())
}
}
// Mehr als 255 Stile in einer Zeile: Ausweichweg mit vollen Zellen.
func TestScrollbackManyStyles(t *testing.T) {
var line uv.Line
for i := 0; i < 300; i++ {
line = append(line, uv.Cell{Content: "x", Width: 1, Style: uv.Style{Fg: ansi.RGBColor{R: uint8(i), G: uint8(i >> 8)}}})
}
sb := newScrollback(10)
sb.push(line)
for x := range line {
if got, _ := sb.cell(x, 0); got != line[x] {
t.Fatalf("Spalte %d: %+v", x, got)
}
}
}
// Ringpuffer: die ältesten Zeilen fallen heraus, Reihenfolge bleibt.
func TestScrollbackRingAndTerm(t *testing.T) {
tm := New(40, 5, io.Discard)
defer tm.Close()
var b strings.Builder
for i := 0; i < ScrollbackLines+1000; i++ {
fmt.Fprintf(&b, "\x1b[3%dmzeile %d\x1b[0m\r\n", i%8, i)
}
tm.Write([]byte(b.String()))
if n := tm.ScrollbackLen(); n != ScrollbackLines {
t.Fatalf("Verlauf %d Zeilen, erwartet %d", n, ScrollbackLines)
}
// 5 Bildschirmzeilen: die letzte ist leer (Cursor), davor stehen 4
first := ScrollbackLines + 1000 - 4 - ScrollbackLines
if got := tm.PlainLine(0); got != fmt.Sprintf("zeile %d", first) {
t.Fatalf("älteste Zeile %q, erwartet zeile %d", got, first)
}
if got := tm.PlainLine(ScrollbackLines - 1); got != fmt.Sprintf("zeile %d", first+ScrollbackLines-1) {
t.Fatalf("jüngste Verlaufszeile %q", got)
}
if c, ok := tm.cellAt(tm.ScrollbackLen(), Pos{0, 0}); !ok || c.Style.Fg != ansi.BasicColor((first)%8) {
t.Fatalf("Farbe im Verlauf verloren: %+v", c)
}
if ms := tm.Search(fmt.Sprintf("zeile %d", first+10), false); len(ms) != 1 || ms[0].Line != 10 {
t.Fatalf("Suche im Verlauf: %+v", ms)
}
if v := tm.Render(ScrollbackLines, nil); !strings.Contains(v, fmt.Sprintf("zeile %d", first)) {
t.Fatalf("Zurückblättern zeigt nicht die älteste Zeile: %q", strings.Split(ansi.Strip(v), "\n")[0])
}
if !strings.Contains(tm.PlainLines(3), fmt.Sprintf("zeile %d", ScrollbackLines+999)) {
t.Fatal("PlainLines ohne letzte Zeile")
}
// ESC[3J (z. B. „clear“ in neueren Shells) leert auch den Verlauf
tm.Write([]byte("\x1b[H\x1b[2J\x1b[3J"))
if n := tm.ScrollbackLen(); n != 0 {
t.Fatalf("nach ESC[3J noch %d Zeilen", n)
}
// ESC[2J allein schiebt den Bildschirm in den Verlauf (wie xterm)
tm.Write([]byte("eins\r\nzwei\x1b[2J"))
if n := tm.ScrollbackLen(); n == 0 {
t.Fatal("ESC[2J soll den Bildschirm in den Verlauf schieben")
}
}
// Speicher: ein voller Verlauf (5000 Zeilen à ~150 Zeichen, farbig) darf
// nur wenige MB kosten. Vorher waren es rund 59 MB pro Tab.
func TestScrollbackMemory(t *testing.T) {
if testing.Short() {
t.Skip("misst Speicher")
}
mb := sessionHeapMB(t, 2)
t.Logf("%.1f MB pro Tab mit vollem Verlauf", mb)
if mb > 20 {
t.Fatalf("%.1f MB pro Tab, erwartet unter 20", mb)
}
}
// sessionHeapMB: Heap pro Terminal mit vollem Verlauf.
func sessionHeapMB(tb testing.TB, n int) float64 {
var m0, m1 runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&m0)
big := []byte(strings.Repeat(benchLine, ScrollbackLines+100))
terms := make([]*Term, n)
for i := range terms {
terms[i] = New(160, 42, io.Discard)
terms[i].Write(big)
}
runtime.GC()
runtime.ReadMemStats(&m1)
for _, tm := range terms {
if tm.ScrollbackLen() != ScrollbackLines {
tb.Fatalf("Verlauf %d", tm.ScrollbackLen())
}
tm.Close()
}
return float64(m1.HeapAlloc-m0.HeapAlloc) / 1e6 / float64(n)
}
// typische farbige Ausgabezeile (ls --color, Logs): ~150 Zeichen
var benchLine = strings.Repeat("\x1b[32mhello\x1b[0m world \x1b[1;34m12345\x1b[0m ", 6) + "\r\n"
// BenchmarkWrite: Durchsatz bei durchlaufender Ausgabe (cat großer Datei).
func BenchmarkWrite(b *testing.B) {
big := []byte(strings.Repeat(benchLine, 1000))
tm := New(160, 42, io.Discard)
defer tm.Close()
b.SetBytes(int64(len(big)))
b.ReportAllocs()
for b.Loop() {
tm.Write(big)
}
}
// BenchmarkSessionMemory: MB pro Tab mit vollem Verlauf (Metrik MB/tab).
func BenchmarkSessionMemory(b *testing.B) {
var mb float64
for b.Loop() {
mb = sessionHeapMB(b, 4)
}
b.ReportMetric(mb, "MB/tab")
}
// BenchmarkRenderScrolled: ein Bild beim Zurückblättern im Verlauf.
func BenchmarkRenderScrolled(b *testing.B) {
tm := New(160, 42, io.Discard)
defer tm.Close()
tm.Write([]byte(strings.Repeat(benchLine, ScrollbackLines)))
b.ReportAllocs()
for b.Loop() {
_ = tm.Render(2000, nil)
}
}
+3 -3
View File
@@ -32,10 +32,10 @@ func (t *Term) lineText(sb, w, l int) (string, []int) {
var b strings.Builder
cols := make([]int, 0, w)
for x := 0; x < w; x++ {
c := t.cellAt(sb, Pos{l, x})
c, ok := t.cellAt(sb, Pos{l, x})
s := " "
switch {
case c == nil:
case !ok:
case c.IsZero():
continue // zweite Hälfte eines breiten Zeichens
case c.Content != "":
@@ -105,7 +105,7 @@ func (t *Term) Search(q string, errorsOnly bool) []Match {
// cellWidthAt: Breite des Zeichens in Spalte x (1 oder 2).
func cellWidthAt(sb int, t *Term, l, x int) int {
if c := t.cellAt(sb, Pos{l, x}); c != nil && c.Width > 1 {
if c, ok := t.cellAt(sb, Pos{l, x}); ok && c.Width > 1 {
return c.Width
}
return 1
+20 -10
View File
@@ -26,6 +26,7 @@ type Term struct {
bell bool
mouse map[ansi.DECMode]bool // vom Programm angeforderte Maus-Modi
sb *scrollback // Verlauf, kompakt statt im Emulator (scrollback.go)
host io.Writer
muted atomic.Bool // Antworten auf Abfragen verwerfen (MuteReplies)
@@ -37,8 +38,19 @@ type Term struct {
// New erzeugt das Terminal. toHost bekommt alle Bytes, die zum Server sollen
// (kodierte Tasten, Paste, Antworten auf Abfragen).
func New(cols, rows int, toHost io.Writer) *Term {
t := &Term{emu: vt.NewSafeEmulator(cols, rows), host: toHost}
t.emu.SetScrollbackSize(5000)
t := &Term{emu: vt.NewSafeEmulator(cols, rows), host: toHost, sb: newScrollback(ScrollbackLines)}
// Zeilen, die oben hinauslaufen, landen direkt im kompakten Verlauf
// (läuft innerhalb von Write, push kopiert die Zellen).
t.emu.SetScrollbackHook(t.sb.push)
// ESC[3J löscht den Verlauf: auch unseren. Läuft innerhalb von Write
// (Emulator gesperrt), daher das ungesperrte IsAltScreen. false = der
// eingebaute Handler macht danach den Rest.
t.emu.RegisterCsiHandler('J', func(p ansi.Params) bool {
if n, _, _ := p.Param(0, 0); n == 3 && !t.emu.Emulator.IsAltScreen() {
t.sb.clear()
}
return false
})
t.emu.SetCallbacks(vt.Callbacks{
Title: func(s string) { t.mu.Lock(); t.title = s; t.mu.Unlock() },
Bell: func() { t.mu.Lock(); t.bell = true; t.mu.Unlock() },
@@ -116,6 +128,9 @@ func (t *Term) LastExit() (seq, code int) {
return t.exitSeq, t.exitCode
}
// ScrollbackLines: so viele Zeilen behält der Verlauf eines Tabs.
const ScrollbackLines = 5000
// Write füttert Ausgabe des Servers in den Emulator.
func (t *Term) Write(p []byte) (int, error) { return t.emu.Write(p) }
@@ -210,14 +225,9 @@ func (t *Term) View(ghost string, ghostStyle func(string) string) string {
func (t *Term) PlainLines(n int) string {
var all []string
if !t.AltScreen() {
if sb := t.emu.Scrollback(); sb != nil {
ls := sb.Lines()
if len(ls) > n {
ls = ls[len(ls)-n:]
}
for _, l := range ls {
all = append(all, strings.TrimRight(l.String(), " "))
}
sb := t.sb.Len()
for y := max(0, sb-n); y < sb; y++ {
all = append(all, strings.TrimRight(t.sb.line(y).String(), " "))
}
}
for _, l := range strings.Split(t.emu.String(), "\n") {
+29 -16
View File
@@ -647,39 +647,52 @@ func (a *App) fitFooter(keys [][2]string) [][2]string {
out[i] = [2]string{strings.ReplaceAll(k[0], "Shift+", "⇧"), k[1]} // kürzer: ⇧F9
}
keep := func(k [2]string) bool { return k[0] == help || k[0] == explain }
width := func(ks [][2]string) int {
w := 0
for _, k := range ks {
w += lipgloss.Width(a.s.Key.Render(k[0]))
if k[1] != "" {
w += lipgloss.Width(a.s.KeyDesc.Render(k[1]))
}
// Breiten einmal messen und die Summe mitführen: lipgloss.Width über
// gerenderte Stile ist teuer, und die Schleifen unten fragten früher
// bei jedem Schritt die ganze Zeile neu ab (pro Bild Hunderte Mal).
kw, dw := make([]int, len(out)), make([]int, len(out))
total := 0
for i, k := range out {
kw[i] = lipgloss.Width(a.s.Key.Render(k[0]))
if k[1] != "" {
dw[i] = lipgloss.Width(a.s.KeyDesc.Render(k[1]))
}
return w
total += kw[i] + dw[i]
}
drop := func(i int) {
total -= kw[i] + dw[i]
out = append(out[:i], out[i+1:]...)
kw = append(kw[:i], kw[i+1:]...)
dw = append(dw[:i], dw[i+1:]...)
}
noDesc := func(i int) {
total -= dw[i]
dw[i] = 0
out[i][1] = ""
}
const minKeys = 4 // so viele beschriftete Tasten bleiben mindestens
// 1. ganze Tasten von hinten weglassen, Beschriftungen bleiben
for i := len(out) - 1; i >= 0 && width(out) > a.w && len(out) > minKeys; i-- {
for i := len(out) - 1; i >= 0 && total > a.w && len(out) > minKeys; i-- {
if !keep(out[i]) {
out = append(out[:i], out[i+1:]...)
drop(i)
}
}
// 2. Beschreibungen von hinten weglassen (nicht die der Hilfe)
for i := len(out) - 1; i >= 0 && width(out) > a.w; i-- {
for i := len(out) - 1; i >= 0 && total > a.w; i-- {
if out[i][0] != help {
out[i][1] = ""
noDesc(i)
}
}
// 3. weitere Tasten von hinten weglassen, nie die Hilfe
for i := len(out) - 1; i >= 0 && width(out) > a.w; i-- {
for i := len(out) - 1; i >= 0 && total > a.w; i-- {
if out[i][0] != help {
out = append(out[:i], out[i+1:]...)
drop(i)
}
}
// 4. zur Not auch „Hilfe“ nur als Taste
for i := range out {
if width(out) > a.w && out[i][0] == help {
out[i][1] = ""
if total > a.w && out[i][0] == help {
noDesc(i)
}
}
return out
+17 -16
View File
@@ -100,22 +100,23 @@ func connMatches(c domain.Connection, words, tags []string) bool {
// Ordner mit Treffern aufgeklappt, leere fallen weg.
func buildRows(tree *domain.TreeNode, words, tags []string) []mgrRow {
filtering := len(words) > 0 || len(tags) > 0
var walk func(n *domain.TreeNode, depth int) []mgrRow
walk = func(n *domain.TreeNode, depth int) []mgrRow {
var out []mgrRow
// alles in ein Feld anhängen: mgrRow trägt die ganze Verbindung, und bei
// Hunderten Einträgen kostete das Zusammenkopieren der Teillisten pro
// Ebene spürbar Zeit in jedem Bild
var out []mgrRow
var walk func(n *domain.TreeNode, depth int)
walk = func(n *domain.TreeNode, depth int) {
for _, f := range n.Folders {
inner := walk(f, depth+1)
if filtering {
if len(inner) == 0 && (len(tags) > 0 || !allIn(strings.ToLower(f.Path), words)) {
continue
}
out = append(out, mgrRow{node: f, depth: depth})
out = append(out, inner...)
continue
}
at := len(out)
out = append(out, mgrRow{node: f, depth: depth})
if !f.Collapsed {
out = append(out, inner...)
switch {
case filtering:
walk(f, depth+1)
if len(out) == at+1 && (len(tags) > 0 || !allIn(strings.ToLower(f.Path), words)) {
out = out[:at] // Ordner ohne Treffer weglassen
}
case !f.Collapsed:
walk(f, depth+1)
}
}
for _, c := range n.Conns {
@@ -123,9 +124,9 @@ func buildRows(tree *domain.TreeNode, words, tags []string) []mgrRow {
out = append(out, mgrRow{conn: c, depth: depth})
}
}
return out
}
return walk(tree, 0)
walk(tree, 0)
return out
}
func allIn(hay string, words []string) bool {
+98
View File
@@ -0,0 +1,98 @@
package ui
import (
"fmt"
"testing"
"github.com/db9979/sshtermy/internal/domain"
"github.com/db9979/sshtermy/internal/store"
)
// Leistung mit vielen Verbindungen: go test -run '^$' -bench . ./internal/ui
// manyConnsApp: App mit n Verbindungen in 30 Ordnern, Manager offen.
func manyConnsApp(tb testing.TB, n int) *App {
tb.Setenv("SSHTERMY_HOME", tb.TempDir())
st, err := store.Open()
if err != nil {
tb.Fatal(err)
}
if err := st.Init([]byte("correct horse"), false); err != nil {
tb.Fatal(err)
}
cs := make([]domain.Connection, n)
for i := range cs {
cs[i] = domain.Connection{
Alias: fmt.Sprintf("srv-%03d", i), Host: fmt.Sprintf("10.%d.%d.%d", i/65536, i/256%256, i%256), Port: 22,
Username: "admin", Auth: domain.AuthPassword, Group: fmt.Sprintf("Kunde %d / Standort %d", i%10, i%3),
Tags: []string{"linux", fmt.Sprintf("rack%d", i%7)},
}
}
if _, err := st.AddConnections(cs); err != nil {
tb.Fatal(err)
}
a, err := New(st)
if err != nil {
tb.Fatal(err)
}
a.intro = nil
a.w, a.h, a.scr = 160, 45, scrManager
return a
}
// Ein Bild des Managers mit 500 Verbindungen (läuft bei jeder Taste).
func BenchmarkManagerView500(b *testing.B) {
a := manyConnsApp(b, 500)
a.View()
b.ReportAllocs()
for b.Loop() {
a.View()
}
}
// Manager mit Suchtext: jede Taste filtert alle Verbindungen neu.
func BenchmarkManagerSearch500(b *testing.B) {
a := manyConnsApp(b, 500)
a.mgr.search.SetValue("srv-4")
a.View()
b.ReportAllocs()
for b.Loop() {
a.View()
}
}
// Die Zeilen müssen auch mit vielen Ordnern stimmen: Suche zeigt nur
// Ordner mit Treffern, zugeklappte Ordner verstecken ihre Einträge.
func TestManagerRowsMany(t *testing.T) {
a := manyConnsApp(t, 500)
all := a.mgrRows()
conns := 0
for _, r := range all {
if !r.isFolder() {
conns++
}
}
if conns != 500 {
t.Fatalf("%d Verbindungen sichtbar, erwartet 500", conns)
}
a.mgr.search.SetValue("srv-123")
rows := a.mgrRows()
var names []string
for _, r := range rows {
if r.isFolder() {
names = append(names, "/"+r.node.Path)
} else {
names = append(names, r.conn.Alias)
}
}
if len(rows) != 3 || rows[2].conn.Alias != "srv-123" {
t.Fatalf("Suche: %v", names)
}
a.mgr.search.SetValue("")
if err := a.st.SetCollapsed(true, "Kunde 3"); err != nil {
t.Fatal(err)
}
if got := len(a.mgrRows()); got >= len(all) {
t.Fatalf("zugeklappt: %d Zeilen, vorher %d", got, len(all))
}
}
+12 -1
View File
@@ -13,6 +13,7 @@ import (
"github.com/db9979/sshtermy/internal/devfake"
"github.com/db9979/sshtermy/internal/domain"
"github.com/db9979/sshtermy/internal/hostinfo"
)
// openPTY: Pseudo-Terminal als virtuelle serielle Leitung.
@@ -69,7 +70,17 @@ func TestSerialSession(t *testing.T) {
if s.state != stConnected || !s.netDev() {
t.Fatal("nicht verbunden")
}
waitFor(t, func() bool { return strings.HasSuffix(strings.TrimSpace(s.term.CursorLine()), "#") })
// Der Prompt muss stehen bleiben: nach „Press any key“ kann ein zweiter
// Weck-Tastendruck noch eine Leerzeile und einen neuen Prompt auslösen,
// dazwischen ist die Cursorzeile kurz leer.
atPrompt := func() bool { return hostinfo.IsPrompt(s.term.CursorLine()) }
waitFor(t, func() bool {
if !atPrompt() {
return false
}
time.Sleep(150 * time.Millisecond)
return atPrompt()
})
cmd := a.hostNetCmd(s, true, false)
if cmd == nil {
t.Fatalf("keine Abfrage: %s", s.host.err)
+1 -1
View File
@@ -36,6 +36,6 @@ func Short() string { return fmt.Sprintf("%s v%s", Name, Version) }
// Long: für "sshtermy --version" und den Über-Dialog.
func Long() string {
return fmt.Sprintf("%s v%s (%s, %s) %s/%s\n%s\n%s · https://github.com/%s",
return fmt.Sprintf("%s v%s (%s, %s) %s/%s\n%s\n%s · MIT · https://github.com/%s",
Name, Version, Commit, Date, runtime.GOOS, runtime.GOARCH, i18n.T(Slogan), i18n.T(Idea), Repo)
}
+3
View File
@@ -14,7 +14,10 @@ cat >"$root/usr/share/doc/sshtermy/copyright" <<'TXT'
sshTermy – SSH terminal with an AI copilot
Idea: Dominik Bornhäußer
Source: https://github.com/db9979/sshtermy
License: MIT
TXT
cat "$(dirname "$0")/../LICENSE" >>"$root/usr/share/doc/sshtermy/copyright"
size="$(du -sk "$root/usr" | cut -f1)"
cat >"$root/DEBIAN/control" <<TXT
Package: sshtermy
+1
View File
@@ -16,6 +16,7 @@ cat <<RB
class Sshtermy < Formula
desc "SSH terminal with an AI copilot"
homepage "https://db9979.github.io/sshtermy/"
license "MIT"
version "$ver"
on_macos do
+4 -2
View File
@@ -57,7 +57,8 @@ Publisher: Dominik Bornhäußer
PublisherUrl: https://github.com/db9979
PackageName: sshTermy
PackageUrl: https://db9979.github.io/sshtermy/
License: Freeware
License: MIT
LicenseUrl: https://github.com/db9979/sshtermy/blob/main/LICENSE
ShortDescription: SSH terminal with an AI copilot
Description: Terminal application with connection manager, encrypted store, SFTP, tunnels, broadcast and an AI copilot for any OpenAI-compatible endpoint.
Moniker: sshtermy
@@ -80,7 +81,8 @@ PackageLocale: de-DE
Publisher: Dominik Bornhäußer
PackageName: sshTermy
PackageUrl: https://db9979.github.io/sshtermy/de/
License: Freeware
License: MIT
LicenseUrl: https://github.com/db9979/sshtermy/blob/main/LICENSE
ShortDescription: SSH-Terminal mit KI-Copilot
ManifestType: locale
ManifestVersion: $mv_
+1
View File
@@ -177,6 +177,7 @@ sudo apt update && sudo apt install sshtermy</pre></div>
<span><b>sshTermy</b> · Idee: Dominik Bornhäußer</span>
<a href="https://github.com/db9979/sshtermy">GitHub</a>
<a href="https://github.com/db9979/sshtermy/releases">Releases</a>
<a href="https://github.com/db9979/sshtermy/blob/main/LICENSE">MIT-Lizenz</a>
<a href="https://buymeacoffee.com/zquu1xu570">☕ Kaffee spendieren</a>
<a href="../">English</a>
</div>
+1
View File
@@ -180,6 +180,7 @@ sudo apt update && sudo apt install sshtermy</pre></div>
<span><b>sshTermy</b> · Idea: Dominik Bornhäußer</span>
<a href="https://github.com/db9979/sshtermy">GitHub</a>
<a href="https://github.com/db9979/sshtermy/releases">Releases</a>
<a href="https://github.com/db9979/sshtermy/blob/main/LICENSE">MIT License</a>
<a href="https://buymeacoffee.com/zquu1xu570">☕ Buy me a coffee</a>
<a href="de/">Deutsch</a>
</div>
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Charmbracelet, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+16
View File
@@ -0,0 +1,16 @@
# charmbracelet/x/vt v0.1.0 mit Anpassungen für sshTermy
Kopie von github.com/charmbracelet/x/vt v0.1.0 (MIT, siehe LICENSE), eingebunden
über `replace` in der go.mod von sshTermy. Geändert ist nur, was mit `sshTermy:`
markiert ist:
- `screen.go`: `rotateLines` – Zeilen löschen/einfügen bei voller Breite (jeder
Zeilenvorschub in der letzten Zeile) verschiebt nur die Zeilen statt jede Zelle
des Bildschirms einzeln zu kopieren. Durchlaufende Ausgabe wird so rund 3× schneller.
Test: `rotate_test.go` vergleicht mit dem zellweisen Weg.
- `scrollback.go`, `emulator.go`: `SetScrollbackHook` – Zeilen, die oben aus dem
Bild laufen, gehen an sshTermy (`internal/termemu/scrollback.go`), das sie kompakt
speichert (8 statt 112 Byte pro Zeichen).
Beim Wechsel auf eine neuere vt-Version: Dateien ersetzen, die markierten Stellen
wieder einbauen, `go test ./...` hier und im Hauptmodul laufen lassen.
+162
View File
@@ -0,0 +1,162 @@
package vt
import uv "github.com/charmbracelet/ultraviolet"
// Buffer is a terminal cell buffer.
type Buffer struct {
uv.Buffer
}
// InsertLine inserts n lines at the given line position, with the given
// optional cell, within the specified rectangles. If no rectangles are
// specified, it inserts lines in the entire buffer. Only cells within the
// rectangle's horizontal bounds are affected. Lines are pushed out of the
// rectangle bounds and lost. This follows terminal [ansi.IL] behavior.
// It returns the pushed out lines.
func (b *Buffer) InsertLine(y, n int, c *uv.Cell) {
b.InsertLineRect(y, n, c, b.Bounds())
}
// InsertLineRect inserts new lines at the given line position, with the
// given optional cell, within the rectangle bounds. Only cells within the
// rectangle's horizontal bounds are affected. Lines are pushed out of the
// rectangle bounds and lost. This follows terminal [ansi.IL] behavior.
func (b *Buffer) InsertLineRect(y, n int, c *uv.Cell, rect uv.Rectangle) {
if n <= 0 || y < rect.Min.Y || y >= rect.Max.Y || y >= b.Height() {
return
}
// Limit number of lines to insert to available space
if y+n > rect.Max.Y {
n = rect.Max.Y - y
}
// Move existing lines down within the bounds
for i := rect.Max.Y - 1; i >= y+n; i-- {
for x := rect.Min.X; x < rect.Max.X; x++ {
// We don't need to clone c here because we're just moving lines down.
b.Lines[i][x] = b.Lines[i-n][x]
}
}
// Clear the newly inserted lines within bounds
for i := y; i < y+n; i++ {
for x := rect.Min.X; x < rect.Max.X; x++ {
b.SetCell(x, i, c)
}
}
}
// DeleteLineRect deletes lines at the given line position, with the given
// optional cell, within the rectangle bounds. Only cells within the
// rectangle's bounds are affected. Lines are shifted up within the bounds and
// new blank lines are created at the bottom. This follows terminal [ansi.DL]
// behavior.
func (b *Buffer) DeleteLineRect(y, n int, c *uv.Cell, rect uv.Rectangle) {
if n <= 0 || y < rect.Min.Y || y >= rect.Max.Y || y >= b.Height() {
return
}
// Limit deletion count to available space in scroll region
if n > rect.Max.Y-y {
n = rect.Max.Y - y
}
// Shift cells up within the bounds
for dst := y; dst < rect.Max.Y-n; dst++ {
src := dst + n
for x := rect.Min.X; x < rect.Max.X; x++ {
// We don't need to clone c here because we're just moving cells up.
b.Lines[dst][x] = b.Lines[src][x]
}
}
// Fill the bottom n lines with blank cells
for i := rect.Max.Y - n; i < rect.Max.Y; i++ {
for x := rect.Min.X; x < rect.Max.X; x++ {
b.SetCell(x, i, c)
}
}
}
// DeleteLine deletes n lines at the given line position, with the given
// optional cell, within the specified rectangles. If no rectangles are
// specified, it deletes lines in the entire buffer.
func (b *Buffer) DeleteLine(y, n int, c *uv.Cell) {
b.DeleteLineRect(y, n, c, b.Bounds())
}
// InsertCell inserts new cells at the given position, with the given optional
// cell, within the specified rectangles. If no rectangles are specified, it
// inserts cells in the entire buffer. This follows terminal [ansi.ICH]
// behavior.
func (b *Buffer) InsertCell(x, y, n int, c *uv.Cell) {
b.InsertCellRect(x, y, n, c, b.Bounds())
}
// InsertCellRect inserts new cells at the given position, with the given
// optional cell, within the rectangle bounds. Only cells within the
// rectangle's bounds are affected, following terminal [ansi.ICH] behavior.
func (b *Buffer) InsertCellRect(x, y, n int, c *uv.Cell, rect uv.Rectangle) {
if n <= 0 || y < rect.Min.Y || y >= rect.Max.Y || y >= b.Height() ||
x < rect.Min.X || x >= rect.Max.X || x >= b.Width() {
return
}
// Limit number of cells to insert to available space
if x+n > rect.Max.X {
n = rect.Max.X - x
}
// Move existing cells within rectangle bounds to the right
for i := rect.Max.X - 1; i >= x+n && i-n >= rect.Min.X; i-- {
// We don't need to clone c here because we're just moving cells to the
// right.
// b.lines[y][i] = b.lines[y][i-n]
b.Lines[y][i] = b.Lines[y][i-n]
}
// Clear the newly inserted cells within rectangle bounds
for i := x; i < x+n && i < rect.Max.X; i++ {
b.SetCell(i, y, c)
}
}
// DeleteCell deletes cells at the given position, with the given optional
// cell, within the specified rectangles. If no rectangles are specified, it
// deletes cells in the entire buffer. This follows terminal [ansi.DCH]
// behavior.
func (b *Buffer) DeleteCell(x, y, n int, c *uv.Cell) {
b.DeleteCellRect(x, y, n, c, b.Bounds())
}
// DeleteCellRect deletes cells at the given position, with the given
// optional cell, within the rectangle bounds. Only cells within the
// rectangle's bounds are affected, following terminal [ansi.DCH] behavior.
func (b *Buffer) DeleteCellRect(x, y, n int, c *uv.Cell, rect uv.Rectangle) {
if n <= 0 || y < rect.Min.Y || y >= rect.Max.Y || y >= b.Height() ||
x < rect.Min.X || x >= rect.Max.X || x >= b.Width() {
return
}
// Calculate how many positions we can actually delete
remainingCells := rect.Max.X - x
if n > remainingCells {
n = remainingCells
}
// Shift the remaining cells to the left
for i := x; i < rect.Max.X-n; i++ {
if i+n < rect.Max.X {
// We don't need to clone c here because we're just moving cells to
// the left.
// b.lines[y][i] = b.lines[y][i+n]
b.Lines[y][i] = b.Lines[y][i+n]
}
}
// Fill the vacated positions with the given cell
for i := rect.Max.X - n; i < rect.Max.X; i++ {
b.SetCell(i, y, c)
}
}
+63
View File
@@ -0,0 +1,63 @@
package vt
import (
"image/color"
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/x/ansi"
)
// Callbacks represents a set of callbacks for a terminal.
type Callbacks struct {
// Bell callback. When set, this function is called when a bell character is
// received.
Bell func()
// Title callback. When set, this function is called when the terminal title
// changes.
Title func(string)
// IconName callback. When set, this function is called when the terminal
// icon name changes.
IconName func(string)
// AltScreen callback. When set, this function is called when the alternate
// screen is activated or deactivated.
AltScreen func(bool)
// CursorPosition callback. When set, this function is called when the cursor
// position changes.
CursorPosition func(old, new uv.Position) //nolint:predeclared,revive
// CursorVisibility callback. When set, this function is called when the
// cursor visibility changes.
CursorVisibility func(visible bool)
// CursorStyle callback. When set, this function is called when the cursor
// style changes.
CursorStyle func(style CursorStyle, blink bool)
// CursorColor callback. When set, this function is called when the cursor
// color changes. Nil indicates the default terminal color.
CursorColor func(color color.Color)
// BackgroundColor callback. When set, this function is called when the
// background color changes. Nil indicates the default terminal color.
BackgroundColor func(color color.Color)
// ForegroundColor callback. When set, this function is called when the
// foreground color changes. Nil indicates the default terminal color.
ForegroundColor func(color color.Color)
// WorkingDirectory callback. When set, this function is called when the
// current working directory changes.
WorkingDirectory func(string)
// EnableMode callback. When set, this function is called when a mode is
// enabled.
EnableMode func(mode ansi.Mode)
// DisableMode callback. When set, this function is called when a mode is
// disabled.
DisableMode func(mode ansi.Mode)
}
+60
View File
@@ -0,0 +1,60 @@
package vt
import (
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/x/ansi"
)
// handleControl handles a control character.
func (e *Emulator) handleControl(r byte) {
e.flushGrapheme() // Flush any pending grapheme before handling control codes.
if !e.handleCc(r) {
e.logf("unhandled sequence: ControlCode %q", r)
}
}
// linefeed is the same as [index], except that it respects [ansi.LNM] mode.
func (e *Emulator) linefeed() {
e.index()
if e.isModeSet(ansi.ModeLineFeedNewLine) {
e.carriageReturn()
}
}
// index moves the cursor down one line, scrolling up if necessary. This
// always resets the phantom state i.e. pending wrap state.
func (e *Emulator) index() {
x, y := e.scr.CursorPosition()
scroll := e.scr.ScrollRegion()
// XXX: Handle scrollback whenever we add it.
if y == scroll.Max.Y-1 && x >= scroll.Min.X && x < scroll.Max.X {
e.scr.ScrollUp(1)
} else if y < scroll.Max.Y-1 || !uv.Pos(x, y).In(scroll) {
e.scr.moveCursor(0, 1)
}
e.atPhantom = false
}
// horizontalTabSet sets a horizontal tab stop at the current cursor position.
func (e *Emulator) horizontalTabSet() {
x, _ := e.scr.CursorPosition()
e.tabstops.Set(x)
}
// reverseIndex moves the cursor up one line, or scrolling down. This does not
// reset the phantom state i.e. pending wrap state.
func (e *Emulator) reverseIndex() {
x, y := e.scr.CursorPosition()
scroll := e.scr.ScrollRegion()
if y == scroll.Min.Y && x >= scroll.Min.X && x < scroll.Max.X {
e.scr.ScrollDown(1)
} else {
e.scr.moveCursor(0, -1)
}
}
// backspace moves the cursor back one cell, if possible.
func (e *Emulator) backspace() {
// This acts like [ansi.CUB]
e.moveCursor(-1, 0)
}
+45
View File
@@ -0,0 +1,45 @@
package vt
// CharSet represents a character set designator.
// This can be used to select a character set for G0 or G1 and others.
type CharSet map[byte]string
// Character sets.
var (
UK = CharSet{
'$': "£", // U+00A3
}
SpecialDrawing = CharSet{
'`': "◆", // U+25C6
'a': "▒", // U+2592
'b': "␉", // U+2409
'c': "␌", // U+240C
'd': "␍", // U+240D
'e': "␊", // U+240A
'f': "°", // U+00B0
'g': "±", // U+00B1
'h': "␤", // U+2424
'i': "␋", // U+240B
'j': "┘", // U+2518
'k': "┐", // U+2510
'l': "┌", // U+250C
'm': "└", // U+2514
'n': "┼", // U+253C
'o': "⎺", // U+23BA
'p': "⎻", // U+23BB
'q': "─", // U+2500
'r': "⎼", // U+23BC
's': "⎽", // U+23BD
't': "├", // U+251C
'u': "┤", // U+2524
'v': "┴", // U+2534
'w': "┬", // U+252C
'x': "│", // U+2502
'y': "⩽", // U+2A7D
'z': "⩾", // U+2A7E
'{': "π", // U+03C0
'|': "≠", // U+2260
'}': "£", // U+00A3
'~': "·", // U+00B7
}
)
+55
View File
@@ -0,0 +1,55 @@
package vt
import (
"fmt"
"io"
"strings"
"github.com/charmbracelet/x/ansi"
)
func (e *Emulator) handleCsi(cmd ansi.Cmd, params ansi.Params) {
e.flushGrapheme() // Flush any pending grapheme before handling CSI sequences.
if !e.handlers.handleCsi(cmd, params) {
e.logf("unhandled sequence: CSI %q", paramsString(cmd, params))
}
}
func (e *Emulator) handleRequestMode(params ansi.Params, isAnsi bool) {
n, _, ok := params.Param(0, 0)
if !ok || n == 0 {
return
}
var mode ansi.Mode = ansi.DECMode(n)
if isAnsi {
mode = ansi.ANSIMode(n)
}
setting := e.modes[mode]
_, _ = io.WriteString(e.pw, ansi.ReportMode(mode, setting))
}
func paramsString(cmd ansi.Cmd, params ansi.Params) string {
var s strings.Builder
if mark := cmd.Prefix(); mark != 0 {
s.WriteByte(mark)
}
params.ForEach(-1, func(i, p int, more bool) {
fmt.Fprintf(&s, "%d", p)
if i < len(params)-1 {
if more {
s.WriteByte(':')
} else {
s.WriteByte(';')
}
}
})
if inter := cmd.Intermediate(); inter != 0 {
s.WriteByte(inter)
}
if final := cmd.Final(); final != 0 {
s.WriteByte(final)
}
return s.String()
}
+110
View File
@@ -0,0 +1,110 @@
package vt
import (
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/x/ansi"
)
// nextTab moves the cursor to the next tab stop n times. This respects the
// horizontal scrolling region. This performs the same function as [ansi.CHT].
func (e *Emulator) nextTab(n int) {
x, y := e.scr.CursorPosition()
scroll := e.scr.ScrollRegion()
for range n {
ts := e.tabstops.Next(x)
if ts < x {
break
}
x = ts
}
if x >= scroll.Max.X {
x = min(scroll.Max.X-1, e.Width()-1)
}
// NOTE: We use t.scr.setCursor here because we don't want to reset the
// phantom state.
e.scr.setCursor(x, y, false)
}
// prevTab moves the cursor to the previous tab stop n times. This respects the
// horizontal scrolling region when origin mode is set. If the cursor would
// move past the leftmost valid column, the cursor remains at the leftmost
// valid column and the operation completes.
func (e *Emulator) prevTab(n int) {
x, _ := e.scr.CursorPosition()
leftmargin := 0
scroll := e.scr.ScrollRegion()
if e.isModeSet(ansi.DECOM) {
leftmargin = scroll.Min.X
}
for range n {
ts := e.tabstops.Prev(x)
if ts > x {
break
}
x = ts
}
if x < leftmargin {
x = leftmargin
}
// NOTE: We use t.scr.setCursorX here because we don't want to reset the
// phantom state.
e.scr.setCursorX(x, false)
}
// moveCursor moves the cursor by the given x and y deltas. If the cursor
// is at phantom, the state will reset and the cursor is back in the screen.
func (e *Emulator) moveCursor(dx, dy int) {
e.scr.moveCursor(dx, dy)
e.atPhantom = false
}
// setCursor sets the cursor position. This resets the phantom state.
func (e *Emulator) setCursor(x, y int) {
e.scr.setCursor(x, y, false)
e.atPhantom = false
}
// setCursorPosition sets the cursor position. This respects [ansi.DECOM],
// Origin Mode. This performs the same function as [ansi.CUP].
func (e *Emulator) setCursorPosition(x, y int) {
mode, ok := e.modes[ansi.DECOM]
margins := ok && mode.IsSet()
e.scr.setCursor(x, y, margins)
e.atPhantom = false
}
// carriageReturn moves the cursor to the leftmost column. If [ansi.DECOM] is
// set, the cursor is set to the left margin. If not, and the cursor is on or
// to the right of the left margin, the cursor is set to the left margin.
// Otherwise, the cursor is set to the leftmost column of the screen.
// This performs the same function as [ansi.CR].
func (e *Emulator) carriageReturn() {
mode, ok := e.modes[ansi.DECOM]
margins := ok && mode.IsSet()
x, y := e.scr.CursorPosition()
if margins {
e.scr.setCursor(0, y, true)
} else if region := e.scr.ScrollRegion(); uv.Pos(x, y).In(region) {
e.scr.setCursor(region.Min.X, y, false)
} else {
e.scr.setCursor(0, y, false)
}
e.atPhantom = false
}
// repeatPreviousCharacter repeats the previous character n times. This is
// equivalent to typing the same character n times. This performs the same as
// [ansi.REP].
func (e *Emulator) repeatPreviousCharacter(n int) {
if e.lastChar == 0 {
return
}
for range n {
e.handlePrint(e.lastChar)
}
}
+113
View File
@@ -0,0 +1,113 @@
package vt
import (
"io"
"github.com/charmbracelet/x/ansi"
)
func (e *Emulator) handleMode(params ansi.Params, set, isAnsi bool) {
for _, p := range params {
param := p.Param(-1)
if param == -1 {
// Missing parameter, ignore
continue
}
var mode ansi.Mode = ansi.DECMode(param)
if isAnsi {
mode = ansi.ANSIMode(param)
}
setting := e.modes[mode]
if setting == ansi.ModePermanentlyReset || setting == ansi.ModePermanentlySet {
// Permanently set modes are ignored.
continue
}
setting = ansi.ModeReset
if set {
setting = ansi.ModeSet
}
e.setMode(mode, setting)
}
}
// setAltScreenMode sets the alternate screen mode.
func (e *Emulator) setAltScreenMode(on bool) {
if (on && e.scr == &e.scrs[1]) || (!on && e.scr == &e.scrs[0]) {
// Already in alternate screen mode, or normal screen, do nothing.
return
}
if on {
e.scr = &e.scrs[1]
e.scrs[1].cur = e.scrs[0].cur
e.scr.Clear()
e.scr.ClearTouched()
e.setCursor(0, 0)
} else {
e.scr = &e.scrs[0]
}
if e.cb.AltScreen != nil {
e.cb.AltScreen(on)
}
if e.cb.CursorVisibility != nil {
e.cb.CursorVisibility(!e.scr.cur.Hidden)
}
}
// saveCursor saves the cursor position.
func (e *Emulator) saveCursor() {
e.scr.SaveCursor()
}
// restoreCursor restores the cursor position.
func (e *Emulator) restoreCursor() {
e.scr.RestoreCursor()
}
// setMode sets the mode to the given value.
func (e *Emulator) setMode(mode ansi.Mode, setting ansi.ModeSetting) {
e.logf("setting mode %T(%v) to %v", mode, mode, setting)
e.modes[mode] = setting
switch mode {
case ansi.ModeTextCursorEnable:
e.scr.setCursorHidden(!setting.IsSet())
case ansi.ModeAltScreen:
e.setAltScreenMode(setting.IsSet())
case ansi.ModeSaveCursor:
if setting.IsSet() {
e.saveCursor()
} else {
e.restoreCursor()
}
case ansi.ModeAltScreenSaveCursor: // Alternate Screen Save Cursor (1047 & 1048)
// Save primary screen cursor position
// Switch to alternate screen
// Doesn't support scrollback
if setting.IsSet() {
e.saveCursor()
}
e.setAltScreenMode(setting.IsSet())
case ansi.ModeInBandResize:
if setting.IsSet() {
_, _ = io.WriteString(e.pw, ansi.InBandResize(e.Height(), e.Width(), 0, 0))
}
}
if setting.IsSet() {
if e.cb.EnableMode != nil {
e.cb.EnableMode(mode)
}
} else if setting.IsReset() {
if e.cb.DisableMode != nil {
e.cb.DisableMode(mode)
}
}
}
// isModeSet returns true if the mode is set.
func (e *Emulator) isModeSet(mode ansi.Mode) bool {
m, ok := e.modes[mode]
return ok && m.IsSet()
}
+18
View File
@@ -0,0 +1,18 @@
package vt
import (
uv "github.com/charmbracelet/ultraviolet"
)
// eraseCharacter erases n characters starting from the cursor position. It
// does not move the cursor. This is equivalent to [ansi.ECH].
func (e *Emulator) eraseCharacter(n int) {
if n <= 0 {
n = 1
}
x, y := e.scr.CursorPosition()
rect := uv.Rect(x, y, n, 1)
e.scr.FillArea(e.scr.blankCell(), rect)
e.atPhantom = false
// ECH does not move the cursor.
}
+12
View File
@@ -0,0 +1,12 @@
package vt
import (
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/x/ansi"
)
// handleSgr handles SGR escape sequences.
// handleSgr handles Select Graphic Rendition (SGR) escape sequences.
func (e *Emulator) handleSgr(params ansi.Params) {
uv.ReadStyle(params, &e.scr.cur.Pen)
}
+25
View File
@@ -0,0 +1,25 @@
package vt
import uv "github.com/charmbracelet/ultraviolet"
// CursorStyle represents a cursor style.
type CursorStyle int
// Cursor styles.
const (
CursorBlock CursorStyle = iota
CursorUnderline
CursorBar
)
// Cursor represents a cursor in a terminal.
type Cursor struct {
Pen uv.Style
Link uv.Link
uv.Position
Style CursorStyle
Steady bool // Not blinking
Hidden bool
}
+71
View File
@@ -0,0 +1,71 @@
package vt
import uv "github.com/charmbracelet/ultraviolet"
// Damage represents a damaged area.
type Damage interface {
// Bounds returns the bounds of the damaged area.
Bounds() uv.Rectangle
}
// CellDamage represents a damaged cell.
type CellDamage struct {
X, Y int
Width int
}
// Bounds returns the bounds of the damaged area.
func (d CellDamage) Bounds() uv.Rectangle {
return uv.Rect(d.X, d.Y, d.Width, 1)
}
// RectDamage represents a damaged rectangle.
type RectDamage uv.Rectangle
// Bounds returns the bounds of the damaged area.
func (d RectDamage) Bounds() uv.Rectangle {
return uv.Rectangle(d)
}
// X returns the x-coordinate of the damaged area.
func (d RectDamage) X() int {
return uv.Rectangle(d).Min.X
}
// Y returns the y-coordinate of the damaged area.
func (d RectDamage) Y() int {
return uv.Rectangle(d).Min.Y
}
// Width returns the width of the damaged area.
func (d RectDamage) Width() int {
return uv.Rectangle(d).Dx()
}
// Height returns the height of the damaged area.
func (d RectDamage) Height() int {
return uv.Rectangle(d).Dy()
}
// ScreenDamage represents a damaged screen.
type ScreenDamage struct {
Width, Height int
}
// Bounds returns the bounds of the damaged area.
func (d ScreenDamage) Bounds() uv.Rectangle {
return uv.Rect(0, 0, d.Width, d.Height)
}
// MoveDamage represents a moved area.
// The area is moved from the source to the destination.
type MoveDamage struct {
Src, Dst uv.Rectangle
}
// ScrollDamage represents a scrolled area.
// The area is scrolled by the given deltas.
type ScrollDamage struct {
uv.Rectangle
Dx, Dy int
}
+35
View File
@@ -0,0 +1,35 @@
package vt
import "github.com/charmbracelet/x/ansi"
// handleDcs handles a DCS escape sequence.
func (e *Emulator) handleDcs(cmd ansi.Cmd, params ansi.Params, data []byte) {
e.flushGrapheme() // Flush any pending grapheme before handling DCS sequences.
if !e.handlers.handleDcs(cmd, params, data) {
e.logf("unhandled sequence: DCS %q %q", paramsString(cmd, params), data)
}
}
// handleApc handles an APC escape sequence.
func (e *Emulator) handleApc(data []byte) {
e.flushGrapheme() // Flush any pending grapheme before handling APC sequences.
if !e.handlers.handleApc(data) {
e.logf("unhandled sequence: APC %q", data)
}
}
// handleSos handles an SOS escape sequence.
func (e *Emulator) handleSos(data []byte) {
e.flushGrapheme() // Flush any pending grapheme before handling SOS sequences.
if !e.handlers.handleSos(data) {
e.logf("unhandled sequence: SOS %q", data)
}
}
// handlePm handles a PM escape sequence.
func (e *Emulator) handlePm(data []byte) {
e.flushGrapheme() // Flush any pending grapheme before handling PM sequences.
if !e.handlers.handlePm(data) {
e.logf("unhandled sequence: PM %q", data)
}
}
+179
View File
@@ -0,0 +1,179 @@
package vt
import (
"strings"
"testing"
"time"
uv "github.com/charmbracelet/ultraviolet"
)
// TestDrawFullFrame verifies that Draw repaints the entire screen every
// time, not just lines written since the last draw. Hosts that rebuild the
// frame on each render pass (like Bubble Tea) lose content otherwise.
func TestDrawFullFrame(t *testing.T) {
e := newTestTerminal(t, 20, 5)
if _, err := e.WriteString("hello"); err != nil {
t.Fatal(err)
}
render := func() string {
scr := uv.NewScreenBuffer(20, 5)
e.Draw(scr, scr.Bounds())
return scr.Render()
}
first := render()
if !strings.Contains(first, "hello") {
t.Fatalf("first draw missing content:\n%q", first)
}
// A second draw of the same emulator must contain the same content,
// even though nothing was written in between.
second := render()
if !strings.Contains(second, "hello") {
t.Fatalf("second draw lost content:\n%q", second)
}
}
// TestCursorHidden verifies the cursor visibility state tracks DECSCUSR /
// DECTCEM sequences so hosts can hide the cursor when the child does.
func TestCursorHidden(t *testing.T) {
e := newTestTerminal(t, 20, 5)
if e.CursorHidden() {
t.Fatal("cursor should be visible by default")
}
if _, err := e.WriteString("\x1b[?25l"); err != nil { // hide cursor
t.Fatal(err)
}
if !e.CursorHidden() {
t.Fatal("cursor should be hidden after DECTCEM reset")
}
if _, err := e.WriteString("\x1b[?25h"); err != nil { // show cursor
t.Fatal(err)
}
if e.CursorHidden() {
t.Fatal("cursor should be visible after DECTCEM set")
}
}
// TestCursorStyle verifies the cursor style and blink state track DECSCUSR
// sequences.
func TestCursorStyle(t *testing.T) {
e := newTestTerminal(t, 20, 5)
style, blink := e.CursorStyle()
if style != CursorBlock || !blink {
t.Fatalf("default cursor should be a blinking block, got style=%v blink=%v", style, blink)
}
// Set cursor style: steady bar.
if _, err := e.WriteString("\x1b[6 q"); err != nil {
t.Fatal(err)
}
style, blink = e.CursorStyle()
if style != CursorBar || blink {
t.Fatalf("expected steady bar, got style=%v blink=%v", style, blink)
}
}
// readInputs reads n bytes the emulator produced on its input pipe.
func readInputs(t *testing.T, e *Emulator, n int) string {
t.Helper()
type result struct {
data string
err error
}
done := make(chan result, 1)
go func() {
buf := make([]byte, 64)
var out []byte
for len(out) < n {
read, err := e.Read(buf)
if err != nil {
done <- result{string(out), err}
return
}
out = append(out, buf[:read]...)
}
done <- result{string(out), nil}
}()
select {
case r := <-done:
if r.err != nil {
t.Fatalf("read input: %v", r.err)
}
return r.data
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for terminal input")
return ""
}
}
// TestSendKeyPrintableText verifies printable keys send their resolved
// text rather than the unshifted key code.
func TestSendKeyPrintableText(t *testing.T) {
e := newTestTerminal(t, 20, 5)
done := make(chan string, 1)
go func() { done <- readInputs(t, e, 3) }()
e.SendKey(uv.KeyPressEvent{Code: 'a', Text: "A"})
e.SendKey(uv.KeyPressEvent{Code: '1', Text: "!"})
e.SendKey(uv.KeyPressEvent{Code: 'z'})
select {
case got := <-done:
if got != "A!z" {
t.Fatalf("expected %q, got %q", "A!z", got)
}
case <-time.After(2 * time.Second):
t.Fatal("timed out")
}
}
// TestSendKeyApplicationCursorKeys verifies arrow keys are encoded for the
// cursor key mode the child enabled: a full-screen program that turns on
// application cursor keys expects SS3 sequences, and one that does not
// expects CSI ones.
func TestSendKeyApplicationCursorKeys(t *testing.T) {
e := newTestTerminal(t, 20, 5)
if _, err := e.WriteString("\x1b[?1h"); err != nil { // application cursor keys
t.Fatal(err)
}
done := make(chan string, 1)
go func() { done <- readInputs(t, e, 3) }()
e.SendKey(uv.KeyPressEvent{Code: KeyUp})
select {
case got := <-done:
if got != "\x1bOA" {
t.Fatalf("expected application cursor encoding %q, got %q", "\x1bOA", got)
}
case <-time.After(2 * time.Second):
t.Fatal("timed out")
}
// Without the mode, the same key must use the CSI form.
e2 := newTestTerminal(t, 20, 5)
done2 := make(chan string, 1)
go func() { done2 <- readInputs(t, e2, 3) }()
e2.SendKey(uv.KeyPressEvent{Code: KeyUp})
select {
case got := <-done2:
if got != "\x1b[A" {
t.Fatalf("expected normal cursor encoding %q, got %q", "\x1b[A", got)
}
case <-time.After(2 * time.Second):
t.Fatal("timed out")
}
}
+509
View File
@@ -0,0 +1,509 @@
package vt
import (
"image/color"
"io"
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/ultraviolet/screen"
"github.com/charmbracelet/x/ansi"
"github.com/charmbracelet/x/ansi/parser"
)
// Logger represents a logger interface.
type Logger interface {
Printf(format string, v ...any)
}
// Emulator represents a virtual terminal emulator.
type Emulator struct {
handlers
// The terminal's indexed 256 colors.
colors [256]color.Color
// Both main and alt screens and a pointer to the currently active screen.
scrs [2]Screen
scr *Screen
// Character sets
charsets [4]CharSet
// log is the logger to use.
logger Logger
// terminal default colors.
defaultFg, defaultBg, defaultCur color.Color
fgColor, bgColor, curColor color.Color
// Terminal modes.
modes ansi.Modes
// The last written character.
lastChar rune // either ansi.Rune or ansi.Grapheme
// The bytes of a grapheme cluster still being composed. Bytes rather than
// runes, so the segmenter can read the buffer without a conversion on
// every character.
grapheme []byte
// The ANSI parser to use.
parser *ansi.Parser
cb Callbacks
// The terminal's icon name and title.
iconName, title string
// The current reported working directory. This is not validated.
cwd string
// tabstop is the list of tab stops.
tabstops *uv.TabStops
// I/O pipes.
pr *io.PipeReader
pw *io.PipeWriter
// The GL and GR character set identifiers.
gl, gr int
gsingle int // temporarily select GL or GR
// Indicates if the terminal is closed.
closed bool
// atPhantom indicates if the cursor is out of bounds.
// When true, and a character is written, the cursor is moved to the next line.
atPhantom bool
}
var _ Terminal = (*Emulator)(nil)
// NewEmulator creates a new virtual terminal emulator.
func NewEmulator(w, h int) *Emulator {
t := new(Emulator)
t.scrs[0] = *NewScreen(w, h)
t.scrs[1] = *NewScreen(w, h)
t.scr = &t.scrs[0]
t.scrs[0].cb = &t.cb
t.scrs[1].cb = &t.cb
t.parser = ansi.NewParser()
t.parser.SetParamsSize(parser.MaxParamsSize)
t.parser.SetDataSize(1024 * 1024 * 4) // 4MB data buffer
t.parser.SetHandler(ansi.Handler{
Print: t.handlePrint,
Execute: t.handleControl,
HandleCsi: t.handleCsi,
HandleEsc: t.handleEsc,
HandleDcs: t.handleDcs,
HandleOsc: t.handleOsc,
HandleApc: t.handleApc,
HandlePm: t.handlePm,
HandleSos: t.handleSos,
})
t.pr, t.pw = io.Pipe()
t.resetModes()
t.tabstops = uv.DefaultTabStops(w)
t.registerDefaultHandlers()
// Default colors
t.defaultFg = color.White
t.defaultBg = color.Black
t.defaultCur = color.White
return t
}
// SetLogger sets the terminal's logger.
func (e *Emulator) SetLogger(l Logger) {
e.logger = l
}
// SetCallbacks sets the terminal's callbacks.
func (e *Emulator) SetCallbacks(cb Callbacks) {
e.cb = cb
e.scrs[0].cb = &e.cb
e.scrs[1].cb = &e.cb
}
// Touched returns the touched lines in the current screen buffer.
func (e *Emulator) Touched() []*uv.LineData {
return e.scr.Touched()
}
// String returns a string representation of the underlying screen buffer.
func (e *Emulator) String() string {
s := e.scr.buf.String()
return uv.TrimSpace(s)
}
// Render renders a snapshot of the terminal screen as a string with styles and
// links encoded as ANSI escape codes.
func (e *Emulator) Render() string {
return e.scr.buf.Render()
}
var _ uv.Screen = (*Emulator)(nil)
// Bounds returns the bounds of the terminal.
func (e *Emulator) Bounds() uv.Rectangle {
return e.scr.Bounds()
}
// CellAt returns the current focused screen cell at the given x, y position.
// It returns nil if the cell is out of bounds.
func (e *Emulator) CellAt(x, y int) *uv.Cell {
return e.scr.CellAt(x, y)
}
// SetCell sets the current focused screen cell at the given x, y position.
func (e *Emulator) SetCell(x, y int, c *uv.Cell) {
e.scr.SetCell(x, y, c)
}
// WidthMethod returns the width method used by the terminal.
func (e *Emulator) WidthMethod() uv.WidthMethod {
if e.isModeSet(ansi.ModeUnicodeCore) {
return ansi.GraphemeWidth
}
return ansi.WcWidth
}
// Draw implements the [uv.Drawable] interface.
//
// It paints the entire visible screen, not just the lines that changed
// since the last write: most hosts (including Bubble Tea) rebuild the frame
// every render pass and diff it themselves, so an incremental paint here
// would make content vanish between writes.
func (e *Emulator) Draw(scr uv.Screen, area uv.Rectangle) {
bg := uv.EmptyCell
bg.Style.Bg = e.BackgroundColor()
screen.FillArea(scr, &bg, area)
for y := 0; y < e.Height(); y++ {
for x := 0; x < e.Width(); {
w := 1
cell := e.CellAt(x, y)
if cell != nil {
cell = cell.Clone()
if cell.Width > 1 {
w = cell.Width
}
if cell.Style.Bg == nil && e.bgColor != nil {
cell.Style.Bg = e.bgColor
}
if cell.Style.Fg == nil && e.fgColor != nil {
cell.Style.Fg = e.fgColor
}
scr.SetCell(x+area.Min.X, y+area.Min.Y, cell)
}
x += w
}
}
}
// Height returns the height of the terminal.
func (e *Emulator) Height() int {
return e.scr.Height()
}
// Width returns the width of the terminal.
func (e *Emulator) Width() int {
return e.scr.Width()
}
// CursorPosition returns the terminal's cursor position.
func (e *Emulator) CursorPosition() uv.Position {
x, y := e.scr.CursorPosition()
return uv.Pos(x, y)
}
// CursorHidden reports whether the cursor is currently hidden. Full-screen
// TUIs hide the cursor constantly, and a host that renders the cursor on
// top of this emulator must respect that or it will show a phantom cursor.
func (e *Emulator) CursorHidden() bool {
return e.scr.cur.Hidden
}
// CursorStyle returns the current cursor style and whether it is blinking.
func (e *Emulator) CursorStyle() (style CursorStyle, blink bool) {
return e.scr.cur.Style, !e.scr.cur.Steady
}
// Resize resizes the terminal.
func (e *Emulator) Resize(width int, height int) {
x, y := e.scr.CursorPosition()
if e.atPhantom {
if x < width-1 {
e.atPhantom = false
x++
}
}
if y < 0 {
y = 0
}
if y >= height {
y = height - 1
}
if x < 0 {
x = 0
}
if x >= width {
x = width - 1
}
e.scrs[0].Resize(width, height)
e.scrs[1].Resize(width, height)
e.tabstops = uv.DefaultTabStops(width)
e.setCursor(x, y)
if e.isModeSet(ansi.ModeInBandResize) {
_, _ = io.WriteString(e.pw, ansi.InBandResize(e.Height(), e.Width(), 0, 0))
}
}
// Read reads data from the terminal input buffer.
func (e *Emulator) Read(p []byte) (n int, err error) {
if e.closed {
return 0, io.EOF
}
return e.pr.Read(p) //nolint:wrapcheck
}
// Close closes the terminal.
func (e *Emulator) Close() error {
if e.closed {
return nil
}
e.closed = true
return e.pw.CloseWithError(io.EOF) //nolint:wrapcheck
}
// Write writes data to the terminal output buffer.
func (e *Emulator) Write(p []byte) (n int, err error) {
if e.closed {
return 0, io.ErrClosedPipe
}
for i := range p {
e.parser.Advance(p[i])
// Flush the last cluster once the whole slice is written. Every
// sequence handler flushes on its own way in, so a cluster only has to
// survive until either the next printable character extends it or the
// write ends.
if len(e.grapheme) > 0 && i == len(p)-1 {
e.flushGrapheme()
}
}
return len(p), nil
}
// WriteString writes a string to the terminal output buffer.
func (e *Emulator) WriteString(s string) (n int, err error) {
return e.Write([]byte(s))
}
// InputPipe returns the terminal's input pipe.
// This can be used to send input to the terminal.
func (e *Emulator) InputPipe() io.Writer {
return e.pw
}
// Paste pastes text into the terminal.
// If bracketed paste mode is enabled, the text is bracketed with the
// appropriate escape sequences.
func (e *Emulator) Paste(text string) {
if e.isModeSet(ansi.ModeBracketedPaste) {
_, _ = io.WriteString(e.pw, ansi.BracketedPasteStart)
defer io.WriteString(e.pw, ansi.BracketedPasteEnd) //nolint:errcheck
}
_, _ = io.WriteString(e.pw, text)
}
// SendText sends arbitrary text to the terminal.
func (e *Emulator) SendText(text string) {
_, _ = io.WriteString(e.pw, text)
}
// SendKeys sends multiple keys to the terminal.
func (e *Emulator) SendKeys(keys ...uv.KeyEvent) {
for _, k := range keys {
e.SendKey(k)
}
}
// ForegroundColor returns the terminal's foreground color. This returns nil if
// the foreground color is not set which means the outer terminal color is
// used.
func (e *Emulator) ForegroundColor() color.Color {
if e.fgColor == nil {
return e.defaultFg
}
return e.fgColor
}
// SetForegroundColor sets the terminal's foreground color.
func (e *Emulator) SetForegroundColor(c color.Color) {
if c == nil {
c = e.defaultFg
}
e.fgColor = c
if e.cb.ForegroundColor != nil {
e.cb.ForegroundColor(c)
}
}
// SetDefaultForegroundColor sets the terminal's default foreground color.
func (e *Emulator) SetDefaultForegroundColor(c color.Color) {
if c == nil {
c = color.White
}
e.defaultFg = c
}
// BackgroundColor returns the terminal's background color. This returns nil if
// the background color is not set which means the outer terminal color is
// used.
func (e *Emulator) BackgroundColor() color.Color {
if e.bgColor == nil {
return e.defaultBg
}
return e.bgColor
}
// SetBackgroundColor sets the terminal's background color.
func (e *Emulator) SetBackgroundColor(c color.Color) {
if c == nil {
c = e.defaultBg
}
e.bgColor = c
if e.cb.BackgroundColor != nil {
e.cb.BackgroundColor(c)
}
}
// SetDefaultBackgroundColor sets the terminal's default background color.
func (e *Emulator) SetDefaultBackgroundColor(c color.Color) {
if c == nil {
c = color.Black
}
e.defaultBg = c
}
// CursorColor returns the terminal's cursor color. This returns nil if the
// cursor color is not set which means the outer terminal color is used.
func (e *Emulator) CursorColor() color.Color {
if e.curColor == nil {
return e.defaultCur
}
return e.curColor
}
// SetCursorColor sets the terminal's cursor color.
func (e *Emulator) SetCursorColor(c color.Color) {
if c == nil {
c = e.defaultCur
}
e.curColor = c
if e.cb.CursorColor != nil {
e.cb.CursorColor(c)
}
}
// SetDefaultCursorColor sets the terminal's default cursor color.
func (e *Emulator) SetDefaultCursorColor(c color.Color) {
if c == nil {
c = color.White
}
e.defaultCur = c
}
// IndexedColor returns a terminal's indexed color. An indexed color is a color
// between 0 and 255.
func (e *Emulator) IndexedColor(i int) color.Color {
if i < 0 || i > 255 {
return nil
}
c := e.colors[i]
if c == nil {
// Return the default color.
return ansi.IndexedColor(i)
}
return c
}
// SetIndexedColor sets a terminal's indexed color.
// The index must be between 0 and 255.
func (e *Emulator) SetIndexedColor(i int, c color.Color) {
if i < 0 || i > 255 {
return
}
e.colors[i] = c
}
// resetTabStops resets the terminal tab stops to the default set.
func (e *Emulator) resetTabStops() {
e.tabstops = uv.DefaultTabStops(e.Width())
}
func (e *Emulator) logf(format string, v ...any) {
if e.logger != nil {
e.logger.Printf(format, v...)
}
}
// Scrollback returns the scrollback buffer for the main screen.
// Returns nil if the terminal is in alternate screen mode, as the alternate
// screen typically doesn't use scrollback.
func (e *Emulator) Scrollback() *Scrollback {
// Return main screen's scrollback only
return e.scrs[0].Scrollback()
}
// ScrollbackLen returns the number of lines in the scrollback buffer.
func (e *Emulator) ScrollbackLen() int {
sb := e.Scrollback()
if sb == nil {
return 0
}
return sb.Len()
}
// ScrollbackCellAt returns the cell at the given position in the scrollback buffer.
// x is the column, y is the line index (0 = oldest line in scrollback).
// Returns nil if position is out of bounds.
func (e *Emulator) ScrollbackCellAt(x, y int) *uv.Cell {
sb := e.Scrollback()
if sb == nil {
return nil
}
return sb.CellAt(x, y)
}
// SetScrollbackSize sets the maximum number of lines in the scrollback buffer.
func (e *Emulator) SetScrollbackSize(maxLines int) {
e.scrs[0].SetScrollbackSize(maxLines)
}
// SetScrollbackHook (sshTermy): siehe Scrollback.SetHook. Vor dem ersten
// Write aufrufen.
func (e *Emulator) SetScrollbackHook(f func(uv.Line)) {
e.scrs[0].Scrollback().SetHook(f)
}
// ClearScrollback clears the scrollback buffer.
func (e *Emulator) ClearScrollback() {
sb := e.Scrollback()
if sb != nil {
sb.Clear()
}
}
// IsAltScreen returns whether the terminal is in alternate screen mode.
func (e *Emulator) IsAltScreen() bool {
return e.scr == &e.scrs[1]
}
+1828
View File
File diff suppressed because it is too large. Load diff
+37
View File
@@ -0,0 +1,37 @@
package vt
import (
"github.com/charmbracelet/x/ansi"
)
// handleEsc handles an escape sequence.
func (e *Emulator) handleEsc(cmd ansi.Cmd) {
e.flushGrapheme() // Flush any pending grapheme before handling ESC sequences.
if !e.handlers.handleEsc(int(cmd)) {
var str string
if inter := cmd.Intermediate(); inter != 0 {
str += string(inter) + " "
}
if final := cmd.Final(); final != 0 {
str += string(final)
}
e.logf("unhandled sequence: ESC %q", str)
}
}
// fullReset performs a full terminal reset as in [ansi.RIS].
func (e *Emulator) fullReset() {
e.scrs[0].Reset()
e.scrs[1].Reset()
e.resetTabStops()
// XXX: Do we reset all modes here? Investigate.
e.resetModes()
e.gl, e.gr = 0, 1
e.gsingle = 0
e.charsets = [4]CharSet{}
e.atPhantom = false
e.grapheme = e.grapheme[:0]
e.lastChar = 0
}
+29
View File
@@ -0,0 +1,29 @@
package vt
import (
"io"
"github.com/charmbracelet/x/ansi"
)
// Focus sends the terminal a focus event if focus events mode is enabled.
// This is the opposite of [Blur].
func (e *Emulator) Focus() {
e.focus(true)
}
// Blur sends the terminal a blur event if focus events mode is enabled.
// This is the opposite of [Focus].
func (e *Emulator) Blur() {
e.focus(false)
}
func (e *Emulator) focus(focus bool) {
if mode, ok := e.modes[ansi.ModeFocusEvent]; ok && mode.IsSet() {
if focus {
_, _ = io.WriteString(e.pw, ansi.Focus)
} else {
_, _ = io.WriteString(e.pw, ansi.Blur)
}
}
}
+26
View File
@@ -0,0 +1,26 @@
module github.com/charmbracelet/x/vt
go 1.24.2
require (
github.com/charmbracelet/ultraviolet v0.0.0-20260303162955-0b88c25f3fff
github.com/charmbracelet/x/ansi v0.11.7
github.com/charmbracelet/x/exp/ordered v0.1.0
)
require (
github.com/charmbracelet/colorprofile v0.4.2 // indirect
github.com/charmbracelet/x/term v0.2.2 // indirect
github.com/charmbracelet/x/termios v0.1.1 // indirect
github.com/charmbracelet/x/windows v0.2.2 // indirect
github.com/clipperhouse/displaywidth v0.11.0 // indirect
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/lucasb-eyer/go-colorful v1.4.0 // indirect
github.com/mattn/go-runewidth v0.0.23 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/exp v0.0.0-20231006140011-7918f672742d // indirect
golang.org/x/sync v0.19.0 // indirect
golang.org/x/sys v0.41.0 // indirect
)
+34
View File
@@ -0,0 +1,34 @@
github.com/charmbracelet/colorprofile v0.4.2 h1:BdSNuMjRbotnxHSfxy+PCSa4xAmz7szw70ktAtWRYrY=
github.com/charmbracelet/colorprofile v0.4.2/go.mod h1:0rTi81QpwDElInthtrQ6Ni7cG0sDtwAd4C4le060fT8=
github.com/charmbracelet/ultraviolet v0.0.0-20260303162955-0b88c25f3fff h1:uY7A6hTokHPJBHfq7rj9Y/wm+IAjOghZTxKfVW6QLvw=
github.com/charmbracelet/ultraviolet v0.0.0-20260303162955-0b88c25f3fff/go.mod h1:E6/0abq9uG2SnM8IbLB9Y5SW09uIgfaFETk8aRzgXUQ=
github.com/charmbracelet/x/ansi v0.11.7 h1:kzv1kJvjg2S3r9KHo8hDdHFQLEqn4RBCb39dAYC84jI=
github.com/charmbracelet/x/ansi v0.11.7/go.mod h1:9qGpnAVYz+8ACONkZBUWPtL7lulP9No6p1epAihUZwQ=
github.com/charmbracelet/x/exp/ordered v0.1.0 h1:55/qLwjIh0gL0Vni+QAWk7T/qRVP6sBf+2agPBgnOFE=
github.com/charmbracelet/x/exp/ordered v0.1.0/go.mod h1:5UHwmG+is5THxMyCJHNPCn2/ecI07aKNrW+LcResjJ8=
github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=
github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo=
github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM=
github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k=
github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8=
github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0=
github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk=
github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
github.com/lucasb-eyer/go-colorful v1.4.0 h1:UtrWVfLdarDgc44HcS7pYloGHJUjHV/4FwW4TvVgFr4=
github.com/lucasb-eyer/go-colorful v1.4.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw=
github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
+923
View File
@@ -0,0 +1,923 @@
package vt
import (
"io"
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/x/ansi"
)
// DcsHandler is a function that handles a DCS escape sequence.
type DcsHandler func(params ansi.Params, data []byte) bool
// CsiHandler is a function that handles a CSI escape sequence.
type CsiHandler func(params ansi.Params) bool
// OscHandler is a function that handles an OSC escape sequence.
type OscHandler func(data []byte) bool
// ApcHandler is a function that handles an APC escape sequence.
type ApcHandler func(data []byte) bool
// SosHandler is a function that handles an SOS escape sequence.
type SosHandler func(data []byte) bool
// PmHandler is a function that handles a PM escape sequence.
type PmHandler func(data []byte) bool
// EscHandler is a function that handles an ESC escape sequence.
type EscHandler func() bool
// CcHandler is a function that handles a control character.
type CcHandler func() bool
// handlers contains the terminal's escape sequence handlers.
type handlers struct {
ccHandlers map[byte][]CcHandler
dcsHandlers map[int][]DcsHandler
csiHandlers map[int][]CsiHandler
oscHandlers map[int][]OscHandler
escHandler map[int][]EscHandler
apcHandlers []ApcHandler
sosHandlers []SosHandler
pmHandlers []PmHandler
}
// RegisterDcsHandler registers a DCS escape sequence handler.
func (h *handlers) RegisterDcsHandler(cmd int, handler DcsHandler) {
if h.dcsHandlers == nil {
h.dcsHandlers = make(map[int][]DcsHandler)
}
h.dcsHandlers[cmd] = append(h.dcsHandlers[cmd], handler)
}
// RegisterCsiHandler registers a CSI escape sequence handler.
func (h *handlers) RegisterCsiHandler(cmd int, handler CsiHandler) {
if h.csiHandlers == nil {
h.csiHandlers = make(map[int][]CsiHandler)
}
h.csiHandlers[cmd] = append(h.csiHandlers[cmd], handler)
}
// RegisterOscHandler registers an OSC escape sequence handler.
func (h *handlers) RegisterOscHandler(cmd int, handler OscHandler) {
if h.oscHandlers == nil {
h.oscHandlers = make(map[int][]OscHandler)
}
h.oscHandlers[cmd] = append(h.oscHandlers[cmd], handler)
}
// RegisterApcHandler registers an APC escape sequence handler.
func (h *handlers) RegisterApcHandler(handler ApcHandler) {
h.apcHandlers = append(h.apcHandlers, handler)
}
// RegisterSosHandler registers an SOS escape sequence handler.
func (h *handlers) RegisterSosHandler(handler SosHandler) {
h.sosHandlers = append(h.sosHandlers, handler)
}
// RegisterPmHandler registers a PM escape sequence handler.
func (h *handlers) RegisterPmHandler(handler PmHandler) {
h.pmHandlers = append(h.pmHandlers, handler)
}
// RegisterEscHandler registers an ESC escape sequence handler.
func (h *handlers) RegisterEscHandler(cmd int, handler EscHandler) {
if h.escHandler == nil {
h.escHandler = make(map[int][]EscHandler)
}
h.escHandler[cmd] = append(h.escHandler[cmd], handler)
}
// registerCcHandler registers a control character handler.
func (h *handlers) registerCcHandler(r byte, handler CcHandler) {
if h.ccHandlers == nil {
h.ccHandlers = make(map[byte][]CcHandler)
}
h.ccHandlers[r] = append(h.ccHandlers[r], handler)
}
// handleCc handles a control character.
// It returns true if the control character was handled.
func (h *handlers) handleCc(r byte) bool {
// Reverse iterate over the handlers so that the last registered handler
// is the first to be called.
for i := len(h.ccHandlers[r]) - 1; i >= 0; i-- {
if h.ccHandlers[r][i]() {
return true
}
}
return false
}
// handleDcs handles a DCS escape sequence.
// It returns true if the sequence was handled.
func (h *handlers) handleDcs(cmd ansi.Cmd, params ansi.Params, data []byte) bool {
// Reverse iterate over the handlers so that the last registered handler
// is the first to be called.
if handlers, ok := h.dcsHandlers[int(cmd)]; ok {
for i := len(handlers) - 1; i >= 0; i-- {
if handlers[i](params, data) {
return true
}
}
}
return false
}
// handleCsi handles a CSI escape sequence.
// It returns true if the sequence was handled.
func (h *handlers) handleCsi(cmd ansi.Cmd, params ansi.Params) bool {
// Reverse iterate over the handlers so that the last registered handler
// is the first to be called.
if handlers, ok := h.csiHandlers[int(cmd)]; ok {
for i := len(handlers) - 1; i >= 0; i-- {
if handlers[i](params) {
return true
}
}
}
return false
}
// handleOsc handles an OSC escape sequence.
// It returns true if the sequence was handled.
func (h *handlers) handleOsc(cmd int, data []byte) bool {
// Reverse iterate over the handlers so that the last registered handler
// is the first to be called.
if handlers, ok := h.oscHandlers[cmd]; ok {
for i := len(handlers) - 1; i >= 0; i-- {
if handlers[i](data) {
return true
}
}
}
return false
}
// handleApc handles an APC escape sequence.
// It returns true if the sequence was handled.
func (h *handlers) handleApc(data []byte) bool {
// Reverse iterate over the handlers so that the last registered handler
// is the first to be called.
for i := len(h.apcHandlers) - 1; i >= 0; i-- {
if h.apcHandlers[i](data) {
return true
}
}
return false
}
// handleSos handles an SOS escape sequence.
// It returns true if the sequence was handled.
func (h *handlers) handleSos(data []byte) bool {
// Reverse iterate over the handlers so that the last registered handler
// is the first to be called.
for i := len(h.sosHandlers) - 1; i >= 0; i-- {
if h.sosHandlers[i](data) {
return true
}
}
return false
}
// handlePm handles a PM escape sequence.
// It returns true if the sequence was handled.
func (h *handlers) handlePm(data []byte) bool {
// Reverse iterate over the handlers so that the last registered handler
// is the first to be called.
for i := len(h.pmHandlers) - 1; i >= 0; i-- {
if h.pmHandlers[i](data) {
return true
}
}
return false
}
// handleEsc handles an ESC escape sequence.
// It returns true if the sequence was handled.
func (h *handlers) handleEsc(cmd int) bool {
// Reverse iterate over the handlers so that the last registered handler
// is the first to be called.
if handlers, ok := h.escHandler[cmd]; ok {
for i := len(handlers) - 1; i >= 0; i-- {
if handlers[i]() {
return true
}
}
}
return false
}
// registerDefaultHandlers registers the default escape sequence handlers.
func (e *Emulator) registerDefaultHandlers() {
e.registerDefaultCcHandlers()
e.registerDefaultCsiHandlers()
e.registerDefaultEscHandlers()
e.registerDefaultOscHandlers()
}
// registerDefaultCcHandlers registers the default control character handlers.
func (e *Emulator) registerDefaultCcHandlers() {
for i := byte(ansi.NUL); i <= ansi.US; i++ {
switch i {
case ansi.NUL: // Null [ansi.NUL]
// Ignored
e.registerCcHandler(i, func() bool {
return true
})
case ansi.BEL: // Bell [ansi.BEL]
e.registerCcHandler(i, func() bool {
if e.cb.Bell != nil {
e.cb.Bell()
}
return true
})
case ansi.BS: // Backspace [ansi.BS]
e.registerCcHandler(i, func() bool {
e.backspace()
return true
})
case ansi.HT: // Horizontal Tab [ansi.HT]
e.registerCcHandler(i, func() bool {
e.nextTab(1)
return true
})
case ansi.LF, ansi.VT, ansi.FF:
// Line Feed [ansi.LF]
// Vertical Tab [ansi.VT]
// Form Feed [ansi.FF]
e.registerCcHandler(i, func() bool {
e.linefeed()
return true
})
case ansi.CR: // Carriage Return [ansi.CR]
e.registerCcHandler(i, func() bool {
e.carriageReturn()
return true
})
}
}
for i := byte(ansi.PAD); i <= byte(ansi.APC); i++ {
switch i {
case ansi.HTS: // Horizontal Tab Set [ansi.HTS]
e.registerCcHandler(i, func() bool {
e.horizontalTabSet()
return true
})
case ansi.RI: // Reverse Index [ansi.RI]
e.registerCcHandler(i, func() bool {
e.reverseIndex()
return true
})
case ansi.SO: // Shift Out [ansi.SO]
e.registerCcHandler(i, func() bool {
e.gl = 1
return true
})
case ansi.SI: // Shift In [ansi.SI]
e.registerCcHandler(i, func() bool {
e.gl = 0
return true
})
case ansi.IND: // Index [ansi.IND]
e.registerCcHandler(i, func() bool {
e.index()
return true
})
case ansi.SS2: // Single Shift 2 [ansi.SS2]
e.registerCcHandler(i, func() bool {
e.gsingle = 2
return true
})
case ansi.SS3: // Single Shift 3 [ansi.SS3]
e.registerCcHandler(i, func() bool {
e.gsingle = 3
return true
})
}
}
}
// registerDefaultOscHandlers registers the default OSC escape sequence handlers.
func (e *Emulator) registerDefaultOscHandlers() {
for _, cmd := range []int{
0, // Set window title and icon name
1, // Set icon name
2, // Set window title
} {
e.RegisterOscHandler(cmd, func(data []byte) bool {
e.handleTitle(cmd, data)
return true
})
}
e.RegisterOscHandler(7, func(data []byte) bool {
// Report the shell current working directory
// [ansi.NotifyWorkingDirectory].
e.handleWorkingDirectory(7, data)
return true
})
e.RegisterOscHandler(8, func(data []byte) bool {
// Set/Query Hyperlink [ansi.SetHyperlink]
e.handleHyperlink(8, data)
return true
})
for _, cmd := range []int{
10, // Set/Query foreground color
11, // Set/Query background color
12, // Set/Query cursor color
110, // Reset foreground color
111, // Reset background color
112, // Reset cursor color
} {
e.RegisterOscHandler(cmd, func(data []byte) bool {
e.handleDefaultColor(cmd, data)
return true
})
}
}
// registerDefaultEscHandlers registers the default ESC escape sequence handlers.
func (e *Emulator) registerDefaultEscHandlers() {
e.RegisterEscHandler('=', func() bool {
// Keypad Application Mode [ansi.DECKPAM]
e.setMode(ansi.ModeNumericKeypad, ansi.ModeSet)
return true
})
e.RegisterEscHandler('>', func() bool {
// Keypad Numeric Mode [ansi.DECKPNM]
e.setMode(ansi.ModeNumericKeypad, ansi.ModeReset)
return true
})
e.RegisterEscHandler('7', func() bool {
// Save Cursor [ansi.DECSC]
e.scr.SaveCursor()
return true
})
e.RegisterEscHandler('8', func() bool {
// Restore Cursor [ansi.DECRC]
e.scr.RestoreCursor()
return true
})
for _, cmd := range []int{
ansi.Command(0, '(', 'A'), // UK G0
ansi.Command(0, ')', 'A'), // UK G1
ansi.Command(0, '*', 'A'), // UK G2
ansi.Command(0, '+', 'A'), // UK G3
ansi.Command(0, '(', 'B'), // USASCII G0
ansi.Command(0, ')', 'B'), // USASCII G1
ansi.Command(0, '*', 'B'), // USASCII G2
ansi.Command(0, '+', 'B'), // USASCII G3
ansi.Command(0, '(', '0'), // Special G0
ansi.Command(0, ')', '0'), // Special G1
ansi.Command(0, '*', '0'), // Special G2
ansi.Command(0, '+', '0'), // Special G3
} {
e.RegisterEscHandler(cmd, func() bool {
// Select Character Set [ansi.SCS]
c := ansi.Cmd(cmd)
set := c.Intermediate() - '('
switch c.Final() {
case 'A': // UK Character Set
e.charsets[set] = UK
case 'B': // USASCII Character Set
e.charsets[set] = nil // USASCII is the default
case '0': // Special Drawing Character Set
e.charsets[set] = SpecialDrawing
default:
return false
}
return true
})
}
e.RegisterEscHandler('D', func() bool {
// Index [ansi.IND]
e.index()
return true
})
e.RegisterEscHandler('H', func() bool {
// Horizontal Tab Set [ansi.HTS]
e.horizontalTabSet()
return true
})
e.RegisterEscHandler('M', func() bool {
// Reverse Index [ansi.RI]
e.reverseIndex()
return true
})
e.RegisterEscHandler('c', func() bool {
// Reset Initial State [ansi.RIS]
e.fullReset()
return true
})
e.RegisterEscHandler('n', func() bool {
// Locking Shift G2 [ansi.LS2]
e.gl = 2
return true
})
e.RegisterEscHandler('o', func() bool {
// Locking Shift G3 [ansi.LS3]
e.gl = 3
return true
})
e.RegisterEscHandler('|', func() bool {
// Locking Shift 3 Right [ansi.LS3R]
e.gr = 3
return true
})
e.RegisterEscHandler('}', func() bool {
// Locking Shift 2 Right [ansi.LS2R]
e.gr = 2
return true
})
e.RegisterEscHandler('~', func() bool {
// Locking Shift 1 Right [ansi.LS1R]
e.gr = 1
return true
})
}
// registerDefaultCsiHandlers registers the default CSI escape sequence handlers.
func (e *Emulator) registerDefaultCsiHandlers() {
e.RegisterCsiHandler('@', func(params ansi.Params) bool {
// Insert Character [ansi.ICH]
n, _, _ := params.Param(0, 1)
e.scr.InsertCell(n)
return true
})
e.RegisterCsiHandler('A', func(params ansi.Params) bool {
// Cursor Up [ansi.CUU]
n, _, _ := params.Param(0, 1)
e.moveCursor(0, -n)
return true
})
e.RegisterCsiHandler('B', func(params ansi.Params) bool {
// Cursor Down [ansi.CUD]
n, _, _ := params.Param(0, 1)
e.moveCursor(0, n)
return true
})
e.RegisterCsiHandler('C', func(params ansi.Params) bool {
// Cursor Forward [ansi.CUF]
n, _, _ := params.Param(0, 1)
e.moveCursor(n, 0)
return true
})
e.RegisterCsiHandler('D', func(params ansi.Params) bool {
// Cursor Backward [ansi.CUB]
n, _, _ := params.Param(0, 1)
e.moveCursor(-n, 0)
return true
})
e.RegisterCsiHandler('E', func(params ansi.Params) bool {
// Cursor Next Line [ansi.CNL]
n, _, _ := params.Param(0, 1)
e.moveCursor(0, n)
e.carriageReturn()
return true
})
e.RegisterCsiHandler('F', func(params ansi.Params) bool {
// Cursor Previous Line [ansi.CPL]
n, _, _ := params.Param(0, 1)
e.moveCursor(0, -n)
e.carriageReturn()
return true
})
e.RegisterCsiHandler('G', func(params ansi.Params) bool {
// Cursor Horizontal Absolute [ansi.CHA]
n, _, _ := params.Param(0, 1)
_, y := e.scr.CursorPosition()
e.setCursor(n-1, y)
return true
})
e.RegisterCsiHandler('H', func(params ansi.Params) bool {
// Cursor Position [ansi.CUP]
width, height := e.Width(), e.Height()
row, _, _ := params.Param(0, 1)
col, _, _ := params.Param(1, 1)
if row < 1 {
row = 1
}
if col < 1 {
col = 1
}
y := min(height-1, row-1)
x := min(width-1, col-1)
e.setCursorPosition(x, y)
return true
})
e.RegisterCsiHandler('I', func(params ansi.Params) bool {
// Cursor Horizontal Tabulation [ansi.CHT]
n, _, _ := params.Param(0, 1)
e.nextTab(n)
return true
})
e.RegisterCsiHandler('J', func(params ansi.Params) bool {
// Erase in Display [ansi.ED]
n, _, _ := params.Param(0, 0)
width, height := e.Width(), e.Height()
x, y := e.scr.CursorPosition()
switch n {
case 0: // Erase screen below (from after cursor position)
rect1 := uv.Rect(x, y, width, 1) // cursor to end of line
rect2 := uv.Rect(0, y+1, width, height-y-1) // next line onwards
e.scr.FillArea(e.scr.blankCell(), rect1)
e.scr.FillArea(e.scr.blankCell(), rect2)
case 1: // Erase screen above (including cursor)
rect := uv.Rect(0, 0, width, y+1)
e.scr.FillArea(e.scr.blankCell(), rect)
case 2: // erase screen
// Save screen content to scrollback before clearing
e.scr.ClearWithScrollback()
case 3: // erase display (including scrollback in some terminals)
// For ED 3, we clear the screen but also clear scrollback
// This matches xterm behavior where ESC[3J clears scrollback
e.scr.Clear()
if sb := e.scr.Scrollback(); sb != nil {
sb.Clear()
}
default:
return false
}
return true
})
e.RegisterCsiHandler('K', func(params ansi.Params) bool {
// Erase in Line [ansi.EL]
n, _, _ := params.Param(0, 0)
// NOTE: Erase Line (EL) erases all character attributes but not cell
// bg color.
x, y := e.scr.CursorPosition()
w := e.scr.Width()
switch n {
case 0: // Erase from cursor to end of line
e.eraseCharacter(w - x)
case 1: // Erase from start of line to cursor
rect := uv.Rect(0, y, x+1, 1)
e.scr.FillArea(e.scr.blankCell(), rect)
case 2: // Erase entire line
rect := uv.Rect(0, y, w, 1)
e.scr.FillArea(e.scr.blankCell(), rect)
default:
return false
}
return true
})
e.RegisterCsiHandler('L', func(params ansi.Params) bool {
// Insert Line [ansi.IL]
n, _, _ := params.Param(0, 1)
if e.scr.InsertLine(n) {
// Move the cursor to the left margin.
e.scr.setCursorX(0, true)
}
return true
})
e.RegisterCsiHandler('M', func(params ansi.Params) bool {
// Delete Line [ansi.DL]
n, _, _ := params.Param(0, 1)
if e.scr.DeleteLine(n) {
// If the line was deleted successfully, move the cursor to the
// left.
// Move the cursor to the left margin.
e.scr.setCursorX(0, true)
}
return true
})
e.RegisterCsiHandler('P', func(params ansi.Params) bool {
// Delete Character [ansi.DCH]
n, _, _ := params.Param(0, 1)
e.scr.DeleteCell(n)
return true
})
e.RegisterCsiHandler('S', func(params ansi.Params) bool {
// Scroll Up [ansi.SU]
n, _, _ := params.Param(0, 1)
e.scr.ScrollUp(n)
return true
})
e.RegisterCsiHandler('T', func(params ansi.Params) bool {
// Scroll Down [ansi.SD]
n, _, _ := params.Param(0, 1)
e.scr.ScrollDown(n)
return true
})
e.RegisterCsiHandler(ansi.Command('?', 0, 'W'), func(params ansi.Params) bool {
// Set Tab at Every 8 Columns [ansi.DECST8C]
if len(params) == 1 && params[0] == 5 {
e.resetTabStops()
return true
}
return false
})
e.RegisterCsiHandler('X', func(params ansi.Params) bool {
// Erase Character [ansi.ECH]
n, _, _ := params.Param(0, 1)
e.eraseCharacter(n)
return true
})
e.RegisterCsiHandler('Z', func(params ansi.Params) bool {
// Cursor Backward Tabulation [ansi.CBT]
n, _, _ := params.Param(0, 1)
e.prevTab(n)
return true
})
e.RegisterCsiHandler('`', func(params ansi.Params) bool {
// Horizontal Position Absolute [ansi.HPA]
n, _, _ := params.Param(0, 1)
width := e.Width()
_, y := e.scr.CursorPosition()
e.setCursorPosition(min(width-1, n-1), y)
return true
})
e.RegisterCsiHandler('a', func(params ansi.Params) bool {
// Horizontal Position Relative [ansi.HPR]
n, _, _ := params.Param(0, 1)
width := e.Width()
x, y := e.scr.CursorPosition()
e.setCursorPosition(min(width-1, x+n), y)
return true
})
e.RegisterCsiHandler('b', func(params ansi.Params) bool {
// Repeat Previous Character [ansi.REP]
n, _, _ := params.Param(0, 1)
e.repeatPreviousCharacter(n)
return true
})
e.RegisterCsiHandler('c', func(params ansi.Params) bool {
// Primary Device Attributes [ansi.DA1]
n, _, _ := params.Param(0, 0)
if n != 0 {
return false
}
// Do we fully support VT220?
_, _ = io.WriteString(e.pw, ansi.PrimaryDeviceAttributes(
62, // VT220
1, // 132 columns
6, // Selective Erase
22, // ANSI color
))
return true
})
e.RegisterCsiHandler(ansi.Command('>', 0, 'c'), func(params ansi.Params) bool {
// Secondary Device Attributes [ansi.DA2]
n, _, _ := params.Param(0, 0)
if n != 0 {
return false
}
// Do we fully support VT220?
_, _ = io.WriteString(e.pw, ansi.SecondaryDeviceAttributes(
1, // VT220
10, // Version 1.0
0, // ROM Cartridge is always zero
))
return true
})
e.RegisterCsiHandler('d', func(params ansi.Params) bool {
// Vertical Position Absolute [ansi.VPA]
n, _, _ := params.Param(0, 1)
height := e.Height()
x, _ := e.scr.CursorPosition()
e.setCursorPosition(x, min(height-1, n-1))
return true
})
e.RegisterCsiHandler('e', func(params ansi.Params) bool {
// Vertical Position Relative [ansi.VPR]
n, _, _ := params.Param(0, 1)
height := e.Height()
x, y := e.scr.CursorPosition()
e.setCursorPosition(x, min(height-1, y+n))
return true
})
e.RegisterCsiHandler('f', func(params ansi.Params) bool {
// Horizontal and Vertical Position [ansi.HVP]
width, height := e.Width(), e.Height()
row, _, _ := params.Param(0, 1)
col, _, _ := params.Param(1, 1)
y := min(height-1, row-1)
x := min(width-1, col-1)
e.setCursor(x, y)
return true
})
e.RegisterCsiHandler('g', func(params ansi.Params) bool {
// Tab Clear [ansi.TBC]
value, _, _ := params.Param(0, 0)
switch value {
case 0:
x, _ := e.scr.CursorPosition()
e.tabstops.Reset(x)
case 3:
e.tabstops.Clear()
default:
return false
}
return true
})
e.RegisterCsiHandler('h', func(params ansi.Params) bool {
// Set Mode [ansi.SM] - ANSI
e.handleMode(params, true, true)
return true
})
e.RegisterCsiHandler(ansi.Command('?', 0, 'h'), func(params ansi.Params) bool {
// Set Mode [ansi.SM] - DEC
e.handleMode(params, true, false)
return true
})
e.RegisterCsiHandler('l', func(params ansi.Params) bool {
// Reset Mode [ansi.RM] - ANSI
e.handleMode(params, false, true)
return true
})
e.RegisterCsiHandler(ansi.Command('?', 0, 'l'), func(params ansi.Params) bool {
// Reset Mode [ansi.RM] - DEC
e.handleMode(params, false, false)
return true
})
e.RegisterCsiHandler('m', func(params ansi.Params) bool {
// Select Graphic Rendition [ansi.SGR]
e.handleSgr(params)
return true
})
e.RegisterCsiHandler('n', func(params ansi.Params) bool {
// Device Status Report [ansi.DSR]
n, _, ok := params.Param(0, 1)
if !ok || n == 0 {
return false
}
switch n {
case 5: // Operating Status
// We're always ready ;)
// See: https://vt100.net/docs/vt510-rm/DSR-OS.html
_, _ = io.WriteString(e.pw, ansi.DeviceStatusReport(ansi.DECStatusReport(0)))
case 6: // Cursor Position Report [ansi.CPR]
x, y := e.scr.CursorPosition()
_, _ = io.WriteString(e.pw, ansi.CursorPositionReport(y+1, x+1))
default:
return false
}
return true
})
e.RegisterCsiHandler(ansi.Command('?', 0, 'n'), func(params ansi.Params) bool {
n, _, ok := params.Param(0, 1)
if !ok || n == 0 {
return false
}
switch n {
case 6: // Extended Cursor Position Report [ansi.DECXCPR]
x, y := e.scr.CursorPosition()
_, _ = io.WriteString(e.pw, ansi.ExtendedCursorPositionReport(y+1, x+1, 0)) // We don't support page numbers //nolint:errcheck
default:
return false
}
return true
})
e.RegisterCsiHandler(ansi.Command(0, '$', 'p'), func(params ansi.Params) bool {
// Request Mode [ansi.DECRQM] - ANSI
e.handleRequestMode(params, true)
return true
})
e.RegisterCsiHandler(ansi.Command('?', '$', 'p'), func(params ansi.Params) bool {
// Request Mode [ansi.DECRQM] - DEC
e.handleRequestMode(params, false)
return true
})
e.RegisterCsiHandler(ansi.Command(0, ' ', 'q'), func(params ansi.Params) bool {
// Set Cursor Style [ansi.DECSCUSR]
n := 1
if param, _, ok := params.Param(0, 0); ok && param > n {
n = param
}
blink := n == 0 || n%2 == 1
style := n / 2
if !blink {
style--
}
e.scr.setCursorStyle(CursorStyle(style), blink)
return true
})
e.RegisterCsiHandler('r', func(params ansi.Params) bool {
// Set Top and Bottom Margins [ansi.DECSTBM]
top, _, _ := params.Param(0, 1)
if top < 1 {
top = 1
}
height := e.Height()
bottom, _ := e.parser.Param(1, height)
if bottom < 1 {
bottom = height
}
if top >= bottom {
return false
}
// Rect is [x, y) which means y is exclusive. So the top margin
// is the top of the screen minus one.
e.scr.setVerticalMargins(top-1, bottom)
// Move the cursor to the top-left of the screen or scroll region
// depending on [ansi.DECOM].
e.setCursorPosition(0, 0)
return true
})
e.RegisterCsiHandler('s', func(params ansi.Params) bool {
// Set Left and Right Margins [ansi.DECSLRM]
// These conflict with each other. When [ansi.DECSLRM] is set, the we
// set the left and right margins. Otherwise, we save the cursor
// position.
if e.isModeSet(ansi.ModeLeftRightMargin) {
// Set Left Right Margins [ansi.DECSLRM]
left, _, _ := params.Param(0, 1)
if left < 1 {
left = 1
}
width := e.Width()
right, _, _ := params.Param(1, width)
if right < 1 {
right = width
}
if left >= right {
return false
}
e.scr.setHorizontalMargins(left-1, right)
// Move the cursor to the top-left of the screen or scroll region
// depending on [ansi.DECOM].
e.setCursorPosition(0, 0)
} else {
// Save Current Cursor Position [ansi.SCOSC]
e.scr.SaveCursor()
}
return true
})
}
+459
View File
@@ -0,0 +1,459 @@
package vt
import (
"io"
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/x/ansi"
)
// KeyMod represents a key modifier.
type KeyMod = uv.KeyMod
// Modifier keys.
const (
ModShift = uv.ModShift
ModAlt = uv.ModAlt
ModCtrl = uv.ModCtrl
ModMeta = uv.ModMeta
)
// KeyPressEvent represents a key press event.
type KeyPressEvent = uv.KeyPressEvent
// SendKey returns the default key map.
func (e *Emulator) SendKey(k uv.KeyEvent) {
var seq string
ack := e.isModeSet(ansi.ModeCursorKeys) // Application cursor keys mode
akk := e.isModeSet(ansi.ModeNumericKeypad) // Application keypad keys mode
//nolint:godox
// TODO: Support Kitty, CSI u, and XTerm modifyOtherKeys.
switch key := k.(type) {
case KeyPressEvent:
if key.Mod&ModAlt != 0 {
// Handle alt-modified keys
seq = "\x1b" + seq
key.Mod &^= ModAlt // Remove the Alt modifier for easier matching
}
//nolint:godox
// FIXME: We remove any Base and Shifted codes to properly handle
// comparison. This is a workaround for the fact that we don't support
// extended keys yet.
key.BaseCode = 0
key.ShiftedCode = 0
switch key {
// Control keys
case KeyPressEvent{Code: KeySpace, Mod: ModCtrl}:
seq += "\x00"
case KeyPressEvent{Code: 'a', Mod: ModCtrl}:
seq += "\x01"
case KeyPressEvent{Code: 'b', Mod: ModCtrl}:
seq += "\x02"
case KeyPressEvent{Code: 'c', Mod: ModCtrl}:
seq += "\x03"
case KeyPressEvent{Code: 'd', Mod: ModCtrl}:
seq += "\x04"
case KeyPressEvent{Code: 'e', Mod: ModCtrl}:
seq += "\x05"
case KeyPressEvent{Code: 'f', Mod: ModCtrl}:
seq += "\x06"
case KeyPressEvent{Code: 'g', Mod: ModCtrl}:
seq += "\x07"
case KeyPressEvent{Code: 'h', Mod: ModCtrl}:
seq += "\x08"
case KeyPressEvent{Code: 'i', Mod: ModCtrl}:
seq += "\x09"
case KeyPressEvent{Code: 'j', Mod: ModCtrl}:
seq += "\x0a"
case KeyPressEvent{Code: 'k', Mod: ModCtrl}:
seq += "\x0b"
case KeyPressEvent{Code: 'l', Mod: ModCtrl}:
seq += "\x0c"
case KeyPressEvent{Code: 'm', Mod: ModCtrl}:
seq += "\x0d"
case KeyPressEvent{Code: 'n', Mod: ModCtrl}:
seq += "\x0e"
case KeyPressEvent{Code: 'o', Mod: ModCtrl}:
seq += "\x0f"
case KeyPressEvent{Code: 'p', Mod: ModCtrl}:
seq += "\x10"
case KeyPressEvent{Code: 'q', Mod: ModCtrl}:
seq += "\x11"
case KeyPressEvent{Code: 'r', Mod: ModCtrl}:
seq += "\x12"
case KeyPressEvent{Code: 's', Mod: ModCtrl}:
seq += "\x13"
case KeyPressEvent{Code: 't', Mod: ModCtrl}:
seq += "\x14"
case KeyPressEvent{Code: 'u', Mod: ModCtrl}:
seq += "\x15"
case KeyPressEvent{Code: 'v', Mod: ModCtrl}:
seq += "\x16"
case KeyPressEvent{Code: 'w', Mod: ModCtrl}:
seq += "\x17"
case KeyPressEvent{Code: 'x', Mod: ModCtrl}:
seq += "\x18"
case KeyPressEvent{Code: 'y', Mod: ModCtrl}:
seq += "\x19"
case KeyPressEvent{Code: 'z', Mod: ModCtrl}:
seq += "\x1a"
case KeyPressEvent{Code: '[', Mod: ModCtrl}:
seq += "\x1b"
case KeyPressEvent{Code: '\\', Mod: ModCtrl}:
seq += "\x1c"
case KeyPressEvent{Code: ']', Mod: ModCtrl}:
seq += "\x1d"
case KeyPressEvent{Code: '^', Mod: ModCtrl}:
seq += "\x1e"
case KeyPressEvent{Code: '_', Mod: ModCtrl}:
seq += "\x1f"
case KeyPressEvent{Code: KeyEnter}:
seq += "\r"
case KeyPressEvent{Code: KeyTab}:
seq += "\t"
case KeyPressEvent{Code: KeyBackspace}:
seq += "\x7f"
case KeyPressEvent{Code: KeyEscape}:
seq += "\x1b"
case KeyPressEvent{Code: KeyUp}:
if ack {
seq += "\x1bOA"
} else {
seq += "\x1b[A"
}
case KeyPressEvent{Code: KeyDown}:
if ack {
seq += "\x1bOB"
} else {
seq += "\x1b[B"
}
case KeyPressEvent{Code: KeyRight}:
if ack {
seq += "\x1bOC"
} else {
seq += "\x1b[C"
}
case KeyPressEvent{Code: KeyLeft}:
if ack {
seq += "\x1bOD"
} else {
seq += "\x1b[D"
}
case KeyPressEvent{Code: KeyInsert}:
seq += "\x1b[2~"
case KeyPressEvent{Code: KeyDelete}:
seq += "\x1b[3~"
case KeyPressEvent{Code: KeyHome}:
seq += "\x1b[H"
case KeyPressEvent{Code: KeyEnd}:
seq += "\x1b[F"
case KeyPressEvent{Code: KeyPgUp}:
seq += "\x1b[5~"
case KeyPressEvent{Code: KeyPgDown}:
seq += "\x1b[6~"
case KeyPressEvent{Code: KeyF1}:
seq += "\x1bOP"
case KeyPressEvent{Code: KeyF2}:
seq += "\x1bOQ"
case KeyPressEvent{Code: KeyF3}:
seq += "\x1bOR"
case KeyPressEvent{Code: KeyF4}:
seq += "\x1bOS"
case KeyPressEvent{Code: KeyF5}:
seq += "\x1b[15~"
case KeyPressEvent{Code: KeyF6}:
seq += "\x1b[17~"
case KeyPressEvent{Code: KeyF7}:
seq += "\x1b[18~"
case KeyPressEvent{Code: KeyF8}:
seq += "\x1b[19~"
case KeyPressEvent{Code: KeyF9}:
seq += "\x1b[20~"
case KeyPressEvent{Code: KeyF10}:
seq += "\x1b[21~"
case KeyPressEvent{Code: KeyF11}:
seq += "\x1b[23~"
case KeyPressEvent{Code: KeyF12}:
seq += "\x1b[24~"
case KeyPressEvent{Code: KeyKp0}:
if akk {
seq += "\x1bOp"
} else {
seq += "0"
}
case KeyPressEvent{Code: KeyKp1}:
if akk {
seq += "\x1bOq"
} else {
seq += "1"
}
case KeyPressEvent{Code: KeyKp2}:
if akk {
seq += "\x1bOr"
} else {
seq += "2"
}
case KeyPressEvent{Code: KeyKp3}:
if akk {
seq += "\x1bOs"
} else {
seq += "3"
}
case KeyPressEvent{Code: KeyKp4}:
if akk {
seq += "\x1bOt"
} else {
seq += "4"
}
case KeyPressEvent{Code: KeyKp5}:
if akk {
seq += "\x1bOu"
} else {
seq += "5"
}
case KeyPressEvent{Code: KeyKp6}:
if akk {
seq += "\x1bOv"
} else {
seq += "6"
}
case KeyPressEvent{Code: KeyKp7}:
if akk {
seq += "\x1bOw"
} else {
seq += "7"
}
case KeyPressEvent{Code: KeyKp8}:
if akk {
seq += "\x1bOx"
} else {
seq = "8"
}
case KeyPressEvent{Code: KeyKp9}:
if akk {
seq += "\x1bOy"
} else {
seq += "9"
}
case KeyPressEvent{Code: KeyKpEnter}:
if akk {
seq += "\x1bOM"
} else {
seq += "\r"
}
case KeyPressEvent{Code: KeyKpEqual}:
if akk {
seq += "\x1bOX"
} else {
seq += "="
}
case KeyPressEvent{Code: KeyKpMultiply}:
if akk {
seq += "\x1bOj"
} else {
seq += "*"
}
case KeyPressEvent{Code: KeyKpPlus}:
if akk {
seq += "\x1bOk"
} else {
seq += "+"
}
case KeyPressEvent{Code: KeyKpComma}:
if akk {
seq += "\x1bOl"
} else {
seq += ","
}
case KeyPressEvent{Code: KeyKpMinus}:
if akk {
seq += "\x1bOm"
} else {
seq += "-"
}
case KeyPressEvent{Code: KeyKpDecimal}:
if akk {
seq += "\x1bOn"
} else {
seq += "."
}
case KeyPressEvent{Code: KeyTab, Mod: ModShift}:
seq += "\x1b[Z"
default:
// Handle the rest of the keys. Printable keys carry their
// resolved text, which is what the user actually typed:
// [Key.Code] is the unshifted base key, so sending it would
// turn "!" into "1" and "A" into "a".
switch {
case key.Text != "" && key.Mod&ModCtrl == 0:
seq += key.Text
case key.Text == "" && key.Mod == 0:
seq += string(key.Code)
}
}
io.WriteString(e.pw, seq) //nolint:errcheck,gosec
}
}
// Key codes.
const (
KeyExtended = uv.KeyExtended
KeyUp = uv.KeyUp
KeyDown = uv.KeyDown
KeyRight = uv.KeyRight
KeyLeft = uv.KeyLeft
KeyBegin = uv.KeyBegin
KeyFind = uv.KeyFind
KeyInsert = uv.KeyInsert
KeyDelete = uv.KeyDelete
KeySelect = uv.KeySelect
KeyPgUp = uv.KeyPgUp
KeyPgDown = uv.KeyPgDown
KeyHome = uv.KeyHome
KeyEnd = uv.KeyEnd
KeyKpEnter = uv.KeyKpEnter
KeyKpEqual = uv.KeyKpEqual
KeyKpMultiply = uv.KeyKpMultiply
KeyKpPlus = uv.KeyKpPlus
KeyKpComma = uv.KeyKpComma
KeyKpMinus = uv.KeyKpMinus
KeyKpDecimal = uv.KeyKpDecimal
KeyKpDivide = uv.KeyKpDivide
KeyKp0 = uv.KeyKp0
KeyKp1 = uv.KeyKp1
KeyKp2 = uv.KeyKp2
KeyKp3 = uv.KeyKp3
KeyKp4 = uv.KeyKp4
KeyKp5 = uv.KeyKp5
KeyKp6 = uv.KeyKp6
KeyKp7 = uv.KeyKp7
KeyKp8 = uv.KeyKp8
KeyKp9 = uv.KeyKp9
KeyKpSep = uv.KeyKpSep
KeyKpUp = uv.KeyKpUp
KeyKpDown = uv.KeyKpDown
KeyKpLeft = uv.KeyKpLeft
KeyKpRight = uv.KeyKpRight
KeyKpPgUp = uv.KeyKpPgUp
KeyKpPgDown = uv.KeyKpPgDown
KeyKpHome = uv.KeyKpHome
KeyKpEnd = uv.KeyKpEnd
KeyKpInsert = uv.KeyKpInsert
KeyKpDelete = uv.KeyKpDelete
KeyKpBegin = uv.KeyKpBegin
KeyF1 = uv.KeyF1
KeyF2 = uv.KeyF2
KeyF3 = uv.KeyF3
KeyF4 = uv.KeyF4
KeyF5 = uv.KeyF5
KeyF6 = uv.KeyF6
KeyF7 = uv.KeyF7
KeyF8 = uv.KeyF8
KeyF9 = uv.KeyF9
KeyF10 = uv.KeyF10
KeyF11 = uv.KeyF11
KeyF12 = uv.KeyF12
KeyF13 = uv.KeyF13
KeyF14 = uv.KeyF14
KeyF15 = uv.KeyF15
KeyF16 = uv.KeyF16
KeyF17 = uv.KeyF17
KeyF18 = uv.KeyF18
KeyF19 = uv.KeyF19
KeyF20 = uv.KeyF20
KeyF21 = uv.KeyF21
KeyF22 = uv.KeyF22
KeyF23 = uv.KeyF23
KeyF24 = uv.KeyF24
KeyF25 = uv.KeyF25
KeyF26 = uv.KeyF26
KeyF27 = uv.KeyF27
KeyF28 = uv.KeyF28
KeyF29 = uv.KeyF29
KeyF30 = uv.KeyF30
KeyF31 = uv.KeyF31
KeyF32 = uv.KeyF32
KeyF33 = uv.KeyF33
KeyF34 = uv.KeyF34
KeyF35 = uv.KeyF35
KeyF36 = uv.KeyF36
KeyF37 = uv.KeyF37
KeyF38 = uv.KeyF38
KeyF39 = uv.KeyF39
KeyF40 = uv.KeyF40
KeyF41 = uv.KeyF41
KeyF42 = uv.KeyF42
KeyF43 = uv.KeyF43
KeyF44 = uv.KeyF44
KeyF45 = uv.KeyF45
KeyF46 = uv.KeyF46
KeyF47 = uv.KeyF47
KeyF48 = uv.KeyF48
KeyF49 = uv.KeyF49
KeyF50 = uv.KeyF50
KeyF51 = uv.KeyF51
KeyF52 = uv.KeyF52
KeyF53 = uv.KeyF53
KeyF54 = uv.KeyF54
KeyF55 = uv.KeyF55
KeyF56 = uv.KeyF56
KeyF57 = uv.KeyF57
KeyF58 = uv.KeyF58
KeyF59 = uv.KeyF59
KeyF60 = uv.KeyF60
KeyF61 = uv.KeyF61
KeyF62 = uv.KeyF62
KeyF63 = uv.KeyF63
KeyCapsLock = uv.KeyCapsLock
KeyScrollLock = uv.KeyScrollLock
KeyNumLock = uv.KeyNumLock
KeyPrintScreen = uv.KeyPrintScreen
KeyPause = uv.KeyPause
KeyMenu = uv.KeyMenu
KeyMediaPlay = uv.KeyMediaPlay
KeyMediaPause = uv.KeyMediaPause
KeyMediaPlayPause = uv.KeyMediaPlayPause
KeyMediaReverse = uv.KeyMediaReverse
KeyMediaStop = uv.KeyMediaStop
KeyMediaFastForward = uv.KeyMediaFastForward
KeyMediaRewind = uv.KeyMediaRewind
KeyMediaNext = uv.KeyMediaNext
KeyMediaPrev = uv.KeyMediaPrev
KeyMediaRecord = uv.KeyMediaRecord
KeyLowerVol = uv.KeyLowerVol
KeyRaiseVol = uv.KeyRaiseVol
KeyMute = uv.KeyMute
KeyLeftShift = uv.KeyLeftShift
KeyLeftAlt = uv.KeyLeftAlt
KeyLeftCtrl = uv.KeyLeftCtrl
KeyLeftSuper = uv.KeyLeftSuper
KeyLeftHyper = uv.KeyLeftHyper
KeyLeftMeta = uv.KeyLeftMeta
KeyRightShift = uv.KeyRightShift
KeyRightAlt = uv.KeyRightAlt
KeyRightCtrl = uv.KeyRightCtrl
KeyRightSuper = uv.KeyRightSuper
KeyRightHyper = uv.KeyRightHyper
KeyRightMeta = uv.KeyRightMeta
KeyIsoLevel3Shift = uv.KeyIsoLevel3Shift
KeyIsoLevel5Shift = uv.KeyIsoLevel5Shift
KeyBackspace = uv.KeyBackspace
KeyTab = uv.KeyTab
KeyEnter = uv.KeyEnter
KeyReturn = uv.KeyReturn
KeyEscape = uv.KeyEscape
KeyEsc = uv.KeyEsc
KeySpace = uv.KeySpace
)
+33
View File
@@ -0,0 +1,33 @@
package vt
import "github.com/charmbracelet/x/ansi"
// resetModes resets all modes to their default values.
func (e *Emulator) resetModes() {
e.modes = ansi.Modes{
// Recognized modes and their default values.
ansi.ModeCursorKeys: ansi.ModeReset, // ?1
ansi.ModeOrigin: ansi.ModeReset, // ?6
ansi.ModeAutoWrap: ansi.ModeSet, // ?7
ansi.ModeMouseX10: ansi.ModeReset, // ?9
ansi.ModeLineFeedNewLine: ansi.ModeReset, // ?20
ansi.ModeTextCursorEnable: ansi.ModeSet, // ?25
ansi.ModeNumericKeypad: ansi.ModeReset, // ?66
ansi.ModeLeftRightMargin: ansi.ModeReset, // ?69
ansi.ModeMouseNormal: ansi.ModeReset, // ?1000
ansi.ModeMouseHighlight: ansi.ModeReset, // ?1001
ansi.ModeMouseButtonEvent: ansi.ModeReset, // ?1002
ansi.ModeMouseAnyEvent: ansi.ModeReset, // ?1003
ansi.ModeFocusEvent: ansi.ModeReset, // ?1004
ansi.ModeMouseExtSgr: ansi.ModeReset, // ?1006
ansi.ModeAltScreen: ansi.ModeReset, // ?1047
ansi.ModeSaveCursor: ansi.ModeReset, // ?1048
ansi.ModeAltScreenSaveCursor: ansi.ModeReset, // ?1049
ansi.ModeBracketedPaste: ansi.ModeReset, // ?2004
}
// Set mode effects.
for mode, setting := range e.modes {
e.setMode(mode, setting)
}
}
+115
View File
@@ -0,0 +1,115 @@
package vt
import (
"io"
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/x/ansi"
)
// MouseButton represents the button that was pressed during a mouse message.
type MouseButton = uv.MouseButton
// Mouse event buttons
//
// This is based on X11 mouse button codes.
//
// 1 = left button
// 2 = middle button (pressing the scroll wheel)
// 3 = right button
// 4 = turn scroll wheel up
// 5 = turn scroll wheel down
// 6 = push scroll wheel left
// 7 = push scroll wheel right
// 8 = 4th button (aka browser backward button)
// 9 = 5th button (aka browser forward button)
// 10
// 11
//
// Other buttons are not supported.
const (
MouseNone = uv.MouseNone
MouseLeft = uv.MouseLeft
MouseMiddle = uv.MouseMiddle
MouseRight = uv.MouseRight
MouseWheelUp = uv.MouseWheelUp
MouseWheelDown = uv.MouseWheelDown
MouseWheelLeft = uv.MouseWheelLeft
MouseWheelRight = uv.MouseWheelRight
MouseBackward = uv.MouseBackward
MouseForward = uv.MouseForward
MouseButton10 = uv.MouseButton10
MouseButton11 = uv.MouseButton11
)
// Mouse represents a mouse event.
type Mouse = uv.MouseEvent
// MouseClick represents a mouse click event.
type MouseClick = uv.MouseClickEvent
// MouseRelease represents a mouse release event.
type MouseRelease = uv.MouseReleaseEvent
// MouseWheel represents a mouse wheel event.
type MouseWheel = uv.MouseWheelEvent
// MouseMotion represents a mouse motion event.
type MouseMotion = uv.MouseMotionEvent
// SendMouse sends a mouse event to the terminal. This can be any kind of mouse
// events such as [MouseClick], [MouseRelease], [MouseWheel], or [MouseMotion].
func (e *Emulator) SendMouse(m Mouse) {
// XXX: Support [Utf8ExtMouseMode], [UrxvtExtMouseMode], and
// [SgrPixelExtMouseMode].
var (
enc ansi.Mode
mode ansi.Mode
)
for _, m := range []ansi.DECMode{
ansi.ModeMouseX10, // Button press
ansi.ModeMouseNormal, // Button press/release
ansi.ModeMouseHighlight, // Button press/release/hilight
ansi.ModeMouseButtonEvent, // Button press/release/cell motion
ansi.ModeMouseAnyEvent, // Button press/release/all motion
} {
if e.isModeSet(m) {
mode = m
}
}
if mode == nil {
return
}
for _, mm := range []ansi.DECMode{
// ansi.Utf8ExtMouseMode,
ansi.ModeMouseExtSgr,
// ansi.UrxvtExtMouseMode,
// ansi.SgrPixelExtMouseMode,
} {
if e.isModeSet(mm) {
enc = mm
}
}
// Encode button
mouse := m.Mouse()
_, isMotion := m.(MouseMotion)
_, isRelease := m.(MouseRelease)
b := ansi.EncodeMouseButton(mouse.Button, isMotion,
mouse.Mod.Contains(ModShift),
mouse.Mod.Contains(ModAlt),
mouse.Mod.Contains(ModCtrl))
switch enc {
// XXX: Support [ansi.HighlightMouseMode].
// XXX: Support [ansi.Utf8ExtMouseMode], [ansi.UrxvtExtMouseMode], and
// [ansi.SgrPixelExtMouseMode].
case nil: // X10 mouse encoding
_, _ = io.WriteString(e.pw, ansi.MouseX10(b, mouse.X, mouse.Y))
case ansi.ModeMouseExtSgr: // SGR mouse encoding
_, _ = io.WriteString(e.pw, ansi.MouseSgr(b, mouse.X, mouse.Y, isRelease))
}
}
+136
View File
@@ -0,0 +1,136 @@
// Package vt provides a virtual terminal implementation.
// SKIP: Fix typecheck errors - function signature mismatches and undefined types
package vt
import (
"bytes"
"image/color"
"io"
"github.com/charmbracelet/x/ansi"
)
// handleOsc handles an OSC escape sequence.
func (e *Emulator) handleOsc(cmd int, data []byte) {
e.flushGrapheme() // Flush any pending grapheme before handling OSC sequences.
if !e.handlers.handleOsc(cmd, data) {
e.logf("unhandled sequence: OSC %q", data)
}
}
func (e *Emulator) handleTitle(cmd int, data []byte) {
parts := bytes.Split(data, []byte{';'})
if len(parts) != 2 {
// Invalid, ignore
return
}
switch cmd {
case 0: // Set window title and icon name
name := string(parts[1])
e.iconName, e.title = name, name
if e.cb.Title != nil {
e.cb.Title(name)
}
if e.cb.IconName != nil {
e.cb.IconName(name)
}
case 1: // Set icon name
name := string(parts[1])
e.iconName = name
if e.cb.IconName != nil {
e.cb.IconName(name)
}
case 2: // Set window title
name := string(parts[1])
e.title = name
if e.cb.Title != nil {
e.cb.Title(name)
}
}
}
func (e *Emulator) handleDefaultColor(cmd int, data []byte) {
if cmd != 10 && cmd != 11 && cmd != 12 &&
cmd != 110 && cmd != 111 && cmd != 112 {
// Invalid, ignore
return
}
parts := bytes.Split(data, []byte{';'})
if len(parts) == 0 {
// Invalid, ignore
return
}
cb := func(c color.Color) {
switch cmd {
case 10, 110: // Foreground color
e.SetForegroundColor(c)
case 11, 111: // Background color
e.SetBackgroundColor(c)
case 12, 112: // Cursor color
e.SetCursorColor(c)
}
}
switch len(parts) {
case 1: // Reset color
cb(nil)
case 2: // Set/Query color
arg := string(parts[1])
if arg == "?" {
var xrgb ansi.XRGBColor
switch cmd {
case 10: // Query foreground color
xrgb.Color = e.ForegroundColor()
if xrgb.Color != nil {
io.WriteString(e.pw, ansi.SetForegroundColor(xrgb.String())) //nolint:errcheck,gosec
}
case 11: // Query background color
xrgb.Color = e.BackgroundColor()
if xrgb.Color != nil {
io.WriteString(e.pw, ansi.SetBackgroundColor(xrgb.String())) //nolint:errcheck,gosec
}
case 12: // Query cursor color
xrgb.Color = e.CursorColor()
if xrgb.Color != nil {
io.WriteString(e.pw, ansi.SetCursorColor(xrgb.String())) //nolint:errcheck,gosec
}
}
} else if c := ansi.XParseColor(arg); c != nil {
cb(c)
}
}
}
func (e *Emulator) handleWorkingDirectory(cmd int, data []byte) {
if cmd != 7 {
// Invalid, ignore
return
}
// The data is the working directory path.
parts := bytes.Split(data, []byte{';'})
if len(parts) != 2 {
// Invalid, ignore
return
}
path := string(parts[1])
e.cwd = path
if e.cb.WorkingDirectory != nil {
e.cb.WorkingDirectory(path)
}
}
func (e *Emulator) handleHyperlink(cmd int, data []byte) {
parts := bytes.Split(data, []byte{';'})
if len(parts) != 3 || cmd != 8 {
// Invalid, ignore
return
}
e.scr.cur.Link.Params = string(parts[1])
e.scr.cur.Link.URL = string(parts[2])
}
+48
View File
@@ -0,0 +1,48 @@
package vt
import "testing"
// OSC 8 wire format per https://gist.github.com/egmontkov/eb6100b9 is
// ESC ] 8 ; <params> ; <uri> ST. handleHyperlink must store the
// <params> segment in Link.Params and the <uri> segment in Link.URL.
// Prior to the fix in this commit the two were swapped: Link.URL
// received parts[1] (params) and Link.Params received parts[2] (uri),
// which produced visible-but-unclickable links once Buffer.Render()
// emitted them back out via ansi.SetHyperlink(URL, Params).
func TestHandleHyperlink_StoresURLAndParamsInCorrectFields(t *testing.T) {
t.Parallel()
t.Run("empty params, populated uri (common case)", func(t *testing.T) {
t.Parallel()
term := newTestTerminal(t, 80, 24)
// Feed an OSC 8 open + a single character + OSC 8 close so the
// open's Link metadata sticks on the cell.
_, _ = term.Write([]byte("\x1b]8;;https://example.com/\x1b\\X\x1b]8;;\x1b\\"))
cell := term.CellAt(0, 0)
if cell == nil {
t.Fatal("cell at (0,0) is nil")
}
if got, want := cell.Link.URL, "https://example.com/"; got != want {
t.Errorf("Link.URL = %q, want %q", got, want)
}
if got, want := cell.Link.Params, ""; got != want {
t.Errorf("Link.Params = %q, want %q", got, want)
}
})
t.Run("populated params and uri", func(t *testing.T) {
t.Parallel()
term := newTestTerminal(t, 80, 24)
_, _ = term.Write([]byte("\x1b]8;id=42:tag=demo;https://example.com/path?x=1\x1b\\X\x1b]8;;\x1b\\"))
cell := term.CellAt(0, 0)
if cell == nil {
t.Fatal("cell at (0,0) is nil")
}
if got, want := cell.Link.URL, "https://example.com/path?x=1"; got != want {
t.Errorf("Link.URL = %q, want %q", got, want)
}
if got, want := cell.Link.Params, "id=42:tag=demo"; got != want {
t.Errorf("Link.Params = %q, want %q", got, want)
}
})
}
+53
View File
@@ -0,0 +1,53 @@
package vt
import (
"math/rand"
"testing"
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/x/ansi"
)
// sshTermy: rotateLines muss genau dasselbe Ergebnis liefern wie das
// zellweise Umkopieren in Buffer.DeleteLineArea/InsertLineArea.
func TestRotateLinesMatchesCellCopy(t *testing.T) {
rng := rand.New(rand.NewSource(1))
for round := 0; round < 500; round++ {
w, h := 3+rng.Intn(10), 3+rng.Intn(10)
fast, slow := NewScreen(w, h), NewScreen(w, h)
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
c := uv.Cell{Content: string(rune('a' + rng.Intn(26))), Width: 1}
fast.buf.SetCell(x, y, &c)
slow.buf.SetCell(x, y, &c)
}
}
top := rng.Intn(h)
bottom := top + 1 + rng.Intn(h-top)
area := uv.Rect(0, top, w, bottom-top)
fast.scroll, slow.scroll = area, area
if rng.Intn(2) == 0 {
bg := ansi.IndexedColor(rng.Intn(16))
fast.cur.Pen.Bg, slow.cur.Pen.Bg = bg, bg
}
y := top + rng.Intn(bottom-top)
n := 1 + rng.Intn(h+2)
if rng.Intn(2) == 0 {
if !fast.rotateLines(y, bottom, n) {
t.Fatal("voller Bereich: schneller Weg erwartet")
}
slow.buf.DeleteLineArea(y, n, slow.blankCell(), area)
} else {
fast.rotateLines(y, bottom, -n)
slow.buf.InsertLineArea(y, n, slow.blankCell(), area)
}
for yy := 0; yy < h; yy++ {
for x := 0; x < w; x++ {
a, b := fast.buf.CellAt(x, yy), slow.buf.CellAt(x, yy)
if !a.Equal(b) || a.Style.Bg != b.Style.Bg {
t.Fatalf("Runde %d: Zelle %d,%d: %+v statt %+v", round, x, yy, a, b)
}
}
}
}
}
+240
View File
@@ -0,0 +1,240 @@
package vt
import (
"image/color"
"sync"
uv "github.com/charmbracelet/ultraviolet"
)
// SafeEmulator is a wrapper around an Emulator that adds concurrency safety.
type SafeEmulator struct {
*Emulator
mu sync.RWMutex
}
var _ Terminal = (*SafeEmulator)(nil)
// NewSafeEmulator creates a new SafeEmulator instance.
func NewSafeEmulator(w, h int) *SafeEmulator {
return &SafeEmulator{
Emulator: NewEmulator(w, h),
}
}
// Write writes data to the emulator in a concurrency-safe manner.
func (se *SafeEmulator) Write(data []byte) (int, error) {
se.mu.Lock()
defer se.mu.Unlock()
return se.Emulator.Write(data)
}
// Read reads data from the emulator in a concurrency-safe manner.
func (se *SafeEmulator) Read(p []byte) (int, error) {
return se.Emulator.Read(p)
}
// Resize resizes the emulator in a concurrency-safe manner.
func (se *SafeEmulator) Resize(w, h int) {
se.mu.Lock()
defer se.mu.Unlock()
se.Emulator.Resize(w, h)
}
// Render renders the emulator's current state in a concurrency-safe manner.
func (se *SafeEmulator) Render() string {
se.mu.RLock()
defer se.mu.RUnlock()
return se.Emulator.Render()
}
// SetCell sets a cell in the emulator in a concurrency-safe manner.
func (se *SafeEmulator) SetCell(x, y int, cell *uv.Cell) {
se.mu.Lock()
defer se.mu.Unlock()
se.Emulator.SetCell(x, y, cell)
}
// CellAt retrieves a cell from the emulator in a concurrency-safe manner.
func (se *SafeEmulator) CellAt(x, y int) *uv.Cell {
se.mu.RLock()
defer se.mu.RUnlock()
return se.Emulator.CellAt(x, y)
}
// SendKey sends a key event to the emulator in a concurrency-safe manner.
func (se *SafeEmulator) SendKey(key uv.KeyEvent) {
se.mu.Lock()
defer se.mu.Unlock()
se.Emulator.SendKey(key)
}
// SendMouse sends a mouse event to the emulator in a concurrency-safe manner.
func (se *SafeEmulator) SendMouse(mouse uv.MouseEvent) {
se.mu.Lock()
defer se.mu.Unlock()
se.Emulator.SendMouse(mouse)
}
// SendText sends text input to the emulator in a concurrency-safe manner.
func (se *SafeEmulator) SendText(text string) {
se.mu.Lock()
defer se.mu.Unlock()
se.Emulator.SendText(text)
}
// Paste pastes text into the emulator in a concurrency-safe manner.
func (se *SafeEmulator) Paste(text string) {
se.mu.Lock()
defer se.mu.Unlock()
se.Emulator.Paste(text)
}
// SetForegroundColor sets the foreground color in a concurrency-safe manner.
func (se *SafeEmulator) SetForegroundColor(color color.Color) {
se.mu.Lock()
defer se.mu.Unlock()
se.Emulator.SetForegroundColor(color)
}
// SetBackgroundColor sets the background color in a concurrency-safe manner.
func (se *SafeEmulator) SetBackgroundColor(color color.Color) {
se.mu.Lock()
defer se.mu.Unlock()
se.Emulator.SetBackgroundColor(color)
}
// SetCursorColor sets the cursor color in a concurrency-safe manner.
func (se *SafeEmulator) SetCursorColor(color color.Color) {
se.mu.Lock()
defer se.mu.Unlock()
se.Emulator.SetCursorColor(color)
}
// SetIndexedColor sets an indexed color in a concurrency-safe manner.
func (se *SafeEmulator) SetIndexedColor(index int, color color.Color) {
se.mu.Lock()
defer se.mu.Unlock()
se.Emulator.SetIndexedColor(index, color)
}
// IndexedColor retrieves an indexed color in a concurrency-safe manner.
func (se *SafeEmulator) IndexedColor(index int) color.Color {
se.mu.RLock()
defer se.mu.RUnlock()
return se.Emulator.IndexedColor(index)
}
// Touched returns the touched lines in a concurrency-safe manner.
func (se *SafeEmulator) Touched() []*uv.LineData {
se.mu.RLock()
defer se.mu.RUnlock()
return se.Emulator.Touched()
}
// Height returns the height of the emulator in a concurrency-safe manner.
func (se *SafeEmulator) Height() int {
se.mu.RLock()
defer se.mu.RUnlock()
return se.Emulator.Height()
}
// Width returns the width of the emulator in a concurrency-safe manner.
func (se *SafeEmulator) Width() int {
se.mu.RLock()
defer se.mu.RUnlock()
return se.Emulator.Width()
}
// ForegroundColor returns the foreground color in a concurrency-safe manner.
func (se *SafeEmulator) ForegroundColor() color.Color {
se.mu.RLock()
defer se.mu.RUnlock()
return se.Emulator.ForegroundColor()
}
// BackgroundColor returns the background color in a concurrency-safe manner.
func (se *SafeEmulator) BackgroundColor() color.Color {
se.mu.RLock()
defer se.mu.RUnlock()
return se.Emulator.BackgroundColor()
}
// CursorColor returns the cursor color in a concurrency-safe manner.
func (se *SafeEmulator) CursorColor() color.Color {
se.mu.RLock()
defer se.mu.RUnlock()
return se.Emulator.CursorColor()
}
// CursorPosition returns the cursor position in a concurrency-safe manner.
func (se *SafeEmulator) CursorPosition() uv.Position {
se.mu.RLock()
defer se.mu.RUnlock()
return se.Emulator.CursorPosition()
}
// CursorHidden returns whether the cursor is hidden in a concurrency-safe
// manner.
func (se *SafeEmulator) CursorHidden() bool {
se.mu.RLock()
defer se.mu.RUnlock()
return se.Emulator.CursorHidden()
}
// CursorStyle returns the cursor style and blink state in a concurrency-safe
// manner.
func (se *SafeEmulator) CursorStyle() (style CursorStyle, blink bool) {
se.mu.RLock()
defer se.mu.RUnlock()
return se.Emulator.CursorStyle()
}
// Draw draws the emulator's content onto a given surface in a concurrency-safe manner.
func (se *SafeEmulator) Draw(s uv.Screen, a uv.Rectangle) {
se.mu.RLock()
defer se.mu.RUnlock()
se.Emulator.Draw(s, a)
}
// Scrollback returns the scrollback buffer in a concurrency-safe manner.
func (se *SafeEmulator) Scrollback() *Scrollback {
se.mu.RLock()
defer se.mu.RUnlock()
return se.Emulator.Scrollback()
}
// ScrollbackLen returns the number of lines in the scrollback buffer in a concurrency-safe manner.
func (se *SafeEmulator) ScrollbackLen() int {
se.mu.RLock()
defer se.mu.RUnlock()
return se.Emulator.ScrollbackLen()
}
// ScrollbackCellAt returns a cell from the scrollback buffer in a concurrency-safe manner.
func (se *SafeEmulator) ScrollbackCellAt(x, y int) *uv.Cell {
se.mu.RLock()
defer se.mu.RUnlock()
return se.Emulator.ScrollbackCellAt(x, y)
}
// SetScrollbackSize sets the scrollback buffer size in a concurrency-safe manner.
func (se *SafeEmulator) SetScrollbackSize(maxLines int) {
se.mu.Lock()
defer se.mu.Unlock()
se.Emulator.SetScrollbackSize(maxLines)
}
// ClearScrollback clears the scrollback buffer in a concurrency-safe manner.
func (se *SafeEmulator) ClearScrollback() {
se.mu.Lock()
defer se.mu.Unlock()
se.Emulator.ClearScrollback()
}
// IsAltScreen returns whether in alternate screen mode in a concurrency-safe manner.
func (se *SafeEmulator) IsAltScreen() bool {
se.mu.RLock()
defer se.mu.RUnlock()
return se.Emulator.IsAltScreen()
}
+466
View File
@@ -0,0 +1,466 @@
package vt
import (
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/x/exp/ordered"
)
// Screen represents a virtual terminal screen.
type Screen struct {
// cb is the callbacks struct to use.
cb *Callbacks
// The buffer of the screen.
buf *uv.RenderBuffer
// The cur of the screen.
cur, saved Cursor
// scroll is the scroll region.
scroll uv.Rectangle
// scrollback is the scrollback buffer for lines scrolled off the top.
scrollback *Scrollback
}
// NewScreen creates a new screen.
func NewScreen(w, h int) *Screen {
s := Screen{
buf: uv.NewRenderBuffer(w, h),
scrollback: NewScrollback(DefaultScrollbackSize),
}
s.scroll = s.buf.Bounds()
return &s
}
// Reset resets the screen.
// It clears the screen, sets the cursor to the top left corner, reset the
// cursor styles, and resets the scroll region.
func (s *Screen) Reset() {
s.buf.Clear()
s.cur = Cursor{}
s.saved = Cursor{}
s.scroll = s.buf.Bounds()
s.buf.Touched = nil
}
// Bounds returns the bounds of the screen.
func (s *Screen) Bounds() uv.Rectangle {
return s.buf.Bounds()
}
// Touched returns touched lines in the screen buffer.
func (s *Screen) Touched() []*uv.LineData {
return s.buf.Touched
}
// ClearTouched clears the touched state.
func (s *Screen) ClearTouched() {
s.buf.Touched = nil
}
// CellAt returns the cell at the given x, y position.
func (s *Screen) CellAt(x int, y int) *uv.Cell {
return s.buf.CellAt(x, y)
}
// SetCell sets the cell at the given x, y position.
func (s *Screen) SetCell(x, y int, c *uv.Cell) {
s.buf.SetCell(x, y, c)
}
// Height returns the height of the screen.
func (s *Screen) Height() int {
return s.buf.Height()
}
// Resize resizes the screen.
func (s *Screen) Resize(width int, height int) {
if s.buf == nil {
s.buf = uv.NewRenderBuffer(width, height)
} else {
s.buf.Resize(width, height)
s.buf.Touched = nil
}
s.scroll = s.buf.Bounds()
}
// Width returns the width of the screen.
func (s *Screen) Width() int {
return s.buf.Width()
}
// Clear clears the screen with blank cells.
func (s *Screen) Clear() {
s.ClearArea(s.Bounds())
}
// ClearWithScrollback saves all non-empty lines to scrollback before clearing.
// This is used for operations like ED 2 (erase screen) where content should
// be preserved in history.
func (s *Screen) ClearWithScrollback() {
if s.scrollback != nil {
// Save all lines that have content before clearing
for y := 0; y < s.buf.Height(); y++ {
line := s.buf.Line(y)
if line != nil && !s.isLineEmpty(line) {
s.scrollback.Push(line)
}
}
}
s.Clear()
}
// isLineEmpty returns true if the line contains only empty/space cells.
func (s *Screen) isLineEmpty(line uv.Line) bool {
for _, cell := range line {
if cell.Content != "" && cell.Content != " " {
return false
}
}
return true
}
// ClearArea clears the given area.
func (s *Screen) ClearArea(area uv.Rectangle) {
s.buf.ClearArea(area)
s.touchArea(area)
}
// Fill fills the screen or part of it.
func (s *Screen) Fill(c *uv.Cell) {
s.FillArea(c, s.Bounds())
}
// FillArea fills the given area with the given cell.
func (s *Screen) FillArea(c *uv.Cell, area uv.Rectangle) {
s.buf.FillArea(c, area)
s.touchArea(area)
}
// setHorizontalMargins sets the horizontal margins.
func (s *Screen) setHorizontalMargins(left, right int) {
s.scroll.Min.X = left
s.scroll.Max.X = right
}
// setVerticalMargins sets the vertical margins.
func (s *Screen) setVerticalMargins(top, bottom int) {
s.scroll.Min.Y = top
s.scroll.Max.Y = bottom
}
// setCursorX sets the cursor X position. If margins is true, the cursor is
// only set if it is within the scroll margins.
func (s *Screen) setCursorX(x int, margins bool) {
s.setCursor(x, s.cur.Y, margins)
}
// setCursor sets the cursor position. If margins is true, the cursor is only
// set if it is within the scroll margins. This follows how [ansi.CUP] works.
func (s *Screen) setCursor(x, y int, margins bool) {
old := s.cur.Position
if !margins {
y = ordered.Clamp(y, 0, s.buf.Height()-1)
x = ordered.Clamp(x, 0, s.buf.Width()-1)
} else {
y = ordered.Clamp(s.scroll.Min.Y+y, s.scroll.Min.Y, s.scroll.Max.Y-1)
x = ordered.Clamp(s.scroll.Min.X+x, s.scroll.Min.X, s.scroll.Max.X-1)
}
s.cur.X, s.cur.Y = x, y
if s.cb.CursorPosition != nil && (old.X != x || old.Y != y) {
s.cb.CursorPosition(old, uv.Pos(x, y))
}
}
// moveCursor moves the cursor by the given x and y deltas. If the cursor
// position is inside the scroll region, it is bounded by the scroll region.
// Otherwise, it is bounded by the screen bounds.
// This follows how [ansi.CUU], [ansi.CUD], [ansi.CUF], [ansi.CUB], [ansi.CNL],
// [ansi.CPL].
func (s *Screen) moveCursor(dx, dy int) {
scroll := s.scroll
old := s.cur.Position
if old.X < scroll.Min.X {
scroll.Min.X = 0
}
if old.X >= scroll.Max.X {
scroll.Max.X = s.buf.Width()
}
pt := uv.Pos(s.cur.X+dx, s.cur.Y+dy)
var x, y int
if old.In(scroll) {
y = ordered.Clamp(pt.Y, scroll.Min.Y, scroll.Max.Y-1)
x = ordered.Clamp(pt.X, scroll.Min.X, scroll.Max.X-1)
} else {
y = ordered.Clamp(pt.Y, 0, s.buf.Height()-1)
x = ordered.Clamp(pt.X, 0, s.buf.Width()-1)
}
s.cur.X, s.cur.Y = x, y
if s.cb.CursorPosition != nil && (old.X != x || old.Y != y) {
s.cb.CursorPosition(old, uv.Pos(x, y))
}
}
// Cursor returns the cursor.
func (s *Screen) Cursor() Cursor {
return s.cur
}
// CursorPosition returns the cursor position.
func (s *Screen) CursorPosition() (x, y int) {
return s.cur.X, s.cur.Y
}
// ScrollRegion returns the scroll region.
func (s *Screen) ScrollRegion() uv.Rectangle {
return s.scroll
}
// SaveCursor saves the cursor.
func (s *Screen) SaveCursor() {
s.saved = s.cur
}
// RestoreCursor restores the cursor.
func (s *Screen) RestoreCursor() {
old := s.cur.Position
s.cur = s.saved
if s.cb.CursorPosition != nil && (old.X != s.cur.X || old.Y != s.cur.Y) {
s.cb.CursorPosition(old, s.cur.Position)
}
}
// setCursorHidden sets the cursor hidden.
func (s *Screen) setCursorHidden(hidden bool) {
changed := s.cur.Hidden != hidden
s.cur.Hidden = hidden
if changed && s.cb.CursorVisibility != nil {
s.cb.CursorVisibility(!hidden)
}
}
// setCursorStyle sets the cursor style.
func (s *Screen) setCursorStyle(style CursorStyle, blink bool) {
changed := s.cur.Style != style || s.cur.Steady != !blink
s.cur.Style = style
s.cur.Steady = !blink
if changed && s.cb.CursorStyle != nil {
s.cb.CursorStyle(style, !blink)
}
}
// cursorPen returns the cursor pen.
func (s *Screen) cursorPen() uv.Style {
return s.cur.Pen
}
// cursorLink returns the cursor link.
func (s *Screen) cursorLink() uv.Link {
return s.cur.Link
}
// ShowCursor shows the cursor.
func (s *Screen) ShowCursor() {
s.setCursorHidden(false)
}
// HideCursor hides the cursor.
func (s *Screen) HideCursor() {
s.setCursorHidden(true)
}
// InsertCell inserts n blank characters at the cursor position pushing out
// cells to the right and out of the screen.
func (s *Screen) InsertCell(n int) {
if n <= 0 {
return
}
x, y := s.cur.X, s.cur.Y
s.buf.InsertCellArea(x, y, n, s.blankCell(), s.scroll)
}
// DeleteCell deletes n cells at the cursor position moving cells to the left.
// This has no effect if the cursor is outside the scroll region.
func (s *Screen) DeleteCell(n int) {
if n <= 0 {
return
}
x, y := s.cur.X, s.cur.Y
s.buf.DeleteCellArea(x, y, n, s.blankCell(), s.scroll)
}
// ScrollUp scrolls the content up n lines within the given region. Lines
// scrolled past the top margin are lost. This is equivalent to [ansi.SU] which
// moves the cursor to the top margin and performs a [ansi.DL] operation.
func (s *Screen) ScrollUp(n int) {
x, y := s.CursorPosition()
s.setCursor(s.cur.X, 0, true)
s.DeleteLine(n)
s.setCursor(x, y, false)
}
// ScrollDown scrolls the content down n lines within the given region. Lines
// scrolled past the bottom margin are lost. This is equivalent to [ansi.SD]
// which moves the cursor to top margin and performs a [ansi.IL] operation.
func (s *Screen) ScrollDown(n int) {
x, y := s.CursorPosition()
s.setCursor(s.cur.X, 0, true)
s.InsertLine(n)
s.setCursor(x, y, false)
}
// InsertLine inserts n blank lines at the cursor position Y coordinate.
// Only operates if cursor is within scroll region. Lines below cursor Y
// are moved down, with those past bottom margin being discarded.
// It returns true if the operation was successful.
func (s *Screen) InsertLine(n int) bool {
if n <= 0 {
return false
}
x, y := s.cur.X, s.cur.Y
// Only operate if cursor Y is within scroll region
if y < s.scroll.Min.Y || y >= s.scroll.Max.Y ||
x < s.scroll.Min.X || x >= s.scroll.Max.X {
return false
}
if !s.rotateLines(y, s.scroll.Max.Y, -n) {
s.buf.InsertLineArea(y, n, s.blankCell(), s.scroll)
}
return true
}
// DeleteLine deletes n lines at the cursor position Y coordinate.
// Only operates if cursor is within scroll region. Lines below cursor Y
// are moved up, with blank lines inserted at the bottom of scroll region.
// If scrollback is enabled and cursor is at top of scroll region, lines
// are saved to the scrollback buffer before deletion.
// It returns true if the operation was successful.
func (s *Screen) DeleteLine(n int) bool {
if n <= 0 {
return false
}
scroll := s.scroll
x, y := s.cur.X, s.cur.Y
// Only operate if cursor Y is within scroll region
if y < scroll.Min.Y || y >= scroll.Max.Y ||
x < scroll.Min.X || x >= scroll.Max.X {
return false
}
// Save lines to scrollback if we're at the top of the scroll region
// and the scroll region uses the full width (typical terminal scroll).
// This captures lines that would be lost during scroll up operations.
if s.scrollback != nil && y == scroll.Min.Y &&
scroll.Min.X == 0 && scroll.Max.X == s.buf.Width() {
// Save lines that will be deleted
linesToSave := min(n, scroll.Max.Y-y)
s.scrollback.PushN(s.buf, y, linesToSave)
}
if !s.rotateLines(y, scroll.Max.Y, n) {
s.buf.DeleteLineArea(y, n, s.blankCell(), scroll)
}
return true
}
// rotateLines (sshTermy): schneller Weg für Zeilen löschen/einfügen, wenn
// der Scrollbereich die volle Breite hat (der Normalfall bei jedem
// Zeilenvorschub in der letzten Zeile). Statt jede Zelle des Bildschirms
// einzeln umzukopieren, werden nur die Zeilen-Slices verschoben und die frei
// gewordenen Zeilen geleert. n > 0 schiebt nach oben (DL), n < 0 nach unten
// (IL). Ergebnis wie bei Buffer.DeleteLineArea/InsertLineArea.
func (s *Screen) rotateLines(top, bottom, n int) bool {
w := s.buf.Width()
if s.scroll.Min.X != 0 || s.scroll.Max.X != w || n == 0 ||
top < 0 || bottom > s.buf.Height() || top >= bottom {
return false
}
seg := s.buf.Lines[top:bottom]
k := n
if k < 0 {
k = -k
}
k = min(k, len(seg))
if n > 0 {
// die obersten k Zeilen wandern nach unten und werden geleert
tmp := append([]uv.Line(nil), seg[:k]...)
copy(seg, seg[k:])
copy(seg[len(seg)-k:], tmp)
s.blankLines(seg[len(seg)-k:])
} else {
tmp := append([]uv.Line(nil), seg[len(seg)-k:]...)
copy(seg[k:], seg[:len(seg)-k])
copy(seg, tmp)
s.blankLines(seg[:k])
}
for y := top; y < bottom; y++ {
s.buf.TouchLine(0, y, w)
}
return true
}
func (s *Screen) blankLines(ls []uv.Line) {
// ganze Zeilen: kein angeschnittenes breites Zeichen möglich, daher
// direkt füllen (wie Line.Set mit einer Leerzelle der Breite 1)
c := uv.EmptyCell
if b := s.blankCell(); b != nil {
c = *b
}
for _, l := range ls {
for x := range l {
l[x] = c
}
}
}
// blankCell returns the cursor blank cell with the background color set to the
// current pen background color. If the pen background color is nil, the return
// value is nil.
func (s *Screen) blankCell() *uv.Cell {
if s.cur.Pen.Bg == nil {
return nil
}
c := uv.EmptyCell
c.Style.Bg = s.cur.Pen.Bg
return &c
}
// touchArea marks all lines in the given area as touched.
func (s *Screen) touchArea(area uv.Rectangle) {
for y := area.Min.Y; y < area.Max.Y; y++ {
s.buf.TouchLine(area.Min.X, y, area.Max.X-area.Min.X)
}
}
// Scrollback returns the screen's scrollback buffer.
func (s *Screen) Scrollback() *Scrollback {
return s.scrollback
}
// SetScrollback sets the screen's scrollback buffer.
// Pass nil to disable scrollback.
func (s *Screen) SetScrollback(sb *Scrollback) {
s.scrollback = sb
}
// SetScrollbackSize sets the maximum number of lines in the scrollback buffer.
func (s *Screen) SetScrollbackSize(maxLines int) {
if s.scrollback == nil {
s.scrollback = NewScrollback(maxLines)
} else {
s.scrollback.SetMaxLines(maxLines)
}
}
+154
View File
@@ -0,0 +1,154 @@
package vt
import (
"slices"
uv "github.com/charmbracelet/ultraviolet"
)
// DefaultScrollbackSize is the default maximum number of lines in the scrollback buffer.
const DefaultScrollbackSize = 10000
// Scrollback represents a scrollback buffer that stores lines scrolled off the screen.
type Scrollback struct {
lines []uv.Line
maxLines int
hook func(uv.Line) // sshTermy: übernimmt die Zeile statt sie hier abzulegen
}
// NewScrollback creates a new scrollback buffer with the given maximum number of lines.
func NewScrollback(maxLines int) *Scrollback {
if maxLines <= 0 {
maxLines = DefaultScrollbackSize
}
return &Scrollback{
lines: make([]uv.Line, 0, min(maxLines, 1000)), // Pre-allocate reasonable capacity
maxLines: maxLines,
}
}
// Push adds a line to the scrollback buffer.
// If the buffer is full, the oldest line is removed.
func (s *Scrollback) Push(line uv.Line) {
if s == nil || s.maxLines <= 0 {
return
}
// Find last non-empty cell to trim trailing empty cells.
// This helps with wrapping and window resizing.
lastNonEmpty := -1
for i := len(line) - 1; i >= 0; i-- {
c := &line[i]
if !c.IsZero() && !c.Equal(&uv.EmptyCell) {
lastNonEmpty = i
break
}
}
// sshTermy: eigener, kompakter Verlauf. Die Zeile gehört weiter dem
// Bildschirm, der Empfänger muss sie kopieren.
if s.hook != nil {
s.hook(line[:lastNonEmpty+1])
return
}
// Clone the line content up to and including the last non-empty cell
cloned := slices.Clone(line[:lastNonEmpty+1])
if len(s.lines) >= s.maxLines {
// Remove oldest line and append new one
s.lines = slices.Delete(s.lines, 0, 1)
}
s.lines = append(s.lines, cloned)
}
// PushN adds n lines from the buffer starting at line y to the scrollback.
func (s *Scrollback) PushN(buf *uv.RenderBuffer, y, n int) {
if s == nil || buf == nil || n <= 0 {
return
}
for i := range min(n, buf.Height()-y) {
if line := buf.Line(y + i); line != nil {
s.Push(line)
}
}
}
// Len returns the number of lines in the scrollback buffer.
func (s *Scrollback) Len() int {
if s == nil {
return 0
}
return len(s.lines)
}
// MaxLines returns the maximum number of lines the scrollback buffer can hold.
func (s *Scrollback) MaxLines() int {
if s == nil {
return 0
}
return s.maxLines
}
// SetMaxLines sets the maximum number of lines in the scrollback buffer.
// If the current number of lines exceeds the new maximum, oldest lines are removed.
func (s *Scrollback) SetMaxLines(maxLines int) {
if s == nil || maxLines <= 0 {
return
}
s.maxLines = maxLines
if len(s.lines) > maxLines {
// Remove oldest lines
s.lines = s.lines[len(s.lines)-maxLines:]
}
}
// Line returns the line at the given index.
// Index 0 is the oldest line, Len()-1 is the most recent.
// Returns nil if index is out of bounds.
func (s *Scrollback) Line(index int) uv.Line {
if s == nil || index < 0 || index >= len(s.lines) {
return nil
}
return s.lines[index]
}
// Lines returns all lines in the scrollback buffer.
// Index 0 is the oldest line.
func (s *Scrollback) Lines() []uv.Line {
if s == nil {
return nil
}
return s.lines
}
// Clear removes all lines from the scrollback buffer.
func (s *Scrollback) Clear() {
if s == nil {
return
}
s.lines = s.lines[:0]
}
// CellAt returns the cell at the given position in the scrollback buffer.
// x is the column, y is the line index (0 = oldest).
// Returns nil if position is out of bounds.
func (s *Scrollback) CellAt(x, y int) *uv.Cell {
line := s.Line(y)
if line == nil || x < 0 || x >= len(line) {
return nil
}
return &line[x]
}
// SetHook (sshTermy): f bekommt jede Zeile, die oben aus dem Bild läuft,
// und speichert sie selbst. Der Puffer hier bleibt dann leer.
func (s *Scrollback) SetHook(f func(uv.Line)) {
if s == nil {
return
}
s.hook = f
s.lines = nil
}
+166
View File
@@ -0,0 +1,166 @@
package vt
import (
"testing"
)
func TestScrollback(t *testing.T) {
t.Run("basic push and len", func(t *testing.T) {
sb := NewScrollback(100)
if sb.Len() != 0 {
t.Errorf("expected len 0, got %d", sb.Len())
}
if sb.MaxLines() != 100 {
t.Errorf("expected max 100, got %d", sb.MaxLines())
}
})
t.Run("scrollback in emulator", func(t *testing.T) {
// Create a small terminal
e := NewEmulator(10, 5)
// Fill the screen with numbered lines and force scrolling
for i := 0; i < 10; i++ {
e.WriteString("\r\n") // Scroll up
}
// Check scrollback has captured some lines
sbLen := e.ScrollbackLen()
t.Logf("scrollback length after 10 newlines: %d", sbLen)
if sbLen == 0 {
t.Error("expected scrollback to have captured lines, got 0")
}
})
t.Run("scrollback with content", func(t *testing.T) {
e := NewEmulator(20, 5)
// Write content that will scroll
for i := 0; i < 10; i++ {
e.WriteString("line\r\n")
}
// Verify scrollback captured the scrolled content
sb := e.Scrollback()
if sb == nil {
t.Fatal("scrollback is nil")
}
// Should have captured lines (at least 5, since screen is 5 tall and we wrote 10 lines)
if sb.Len() < 5 {
t.Errorf("expected at least 5 lines in scrollback, got %d", sb.Len())
}
})
t.Run("scrollback max lines", func(t *testing.T) {
sb := NewScrollback(5)
// Push more lines than max
for i := 0; i < 10; i++ {
sb.Push(nil)
}
if sb.Len() != 5 {
t.Errorf("expected len 5 after overflow, got %d", sb.Len())
}
})
t.Run("clear scrollback", func(t *testing.T) {
e := NewEmulator(20, 5)
// Write content that will scroll
for i := 0; i < 10; i++ {
e.WriteString("line\r\n")
}
// Verify we have scrollback
if e.ScrollbackLen() == 0 {
t.Error("expected scrollback before clear")
}
// Clear it
e.ClearScrollback()
if e.ScrollbackLen() != 0 {
t.Errorf("expected empty scrollback after clear, got %d", e.ScrollbackLen())
}
})
t.Run("alt screen does not have scrollback", func(t *testing.T) {
e := NewEmulator(20, 5)
// Write some content to main screen
for i := 0; i < 10; i++ {
e.WriteString("line\r\n")
}
mainScrollbackLen := e.ScrollbackLen()
if mainScrollbackLen == 0 {
t.Error("expected scrollback on main screen")
}
// Enter alt screen
e.WriteString("\x1b[?1049h") // DECSET alt screen
// Scrollback should still be from main screen
if e.ScrollbackLen() != mainScrollbackLen {
t.Errorf("expected scrollback len %d in alt screen, got %d",
mainScrollbackLen, e.ScrollbackLen())
}
// Write to alt screen - should not affect main scrollback
for i := 0; i < 10; i++ {
e.WriteString("alt\r\n")
}
// Main screen scrollback should be unchanged
if e.ScrollbackLen() != mainScrollbackLen {
t.Errorf("expected scrollback len %d after alt screen writes, got %d",
mainScrollbackLen, e.ScrollbackLen())
}
})
t.Run("ED 2 saves to scrollback", func(t *testing.T) {
e := NewEmulator(20, 5)
// Write some content (not enough to scroll)
e.WriteString("line 1\r\n")
e.WriteString("line 2\r\n")
e.WriteString("line 3\r\n")
// Should have no scrollback yet (didn't scroll)
initialLen := e.ScrollbackLen()
// Clear screen with ED 2 (ESC[2J)
e.WriteString("\x1b[2J")
// Should have saved lines to scrollback
newLen := e.ScrollbackLen()
if newLen <= initialLen {
t.Errorf("expected scrollback to grow after ED 2, was %d now %d", initialLen, newLen)
}
t.Logf("scrollback after ED 2: %d lines", newLen)
})
t.Run("ED 3 clears scrollback", func(t *testing.T) {
e := NewEmulator(20, 5)
// Write content that will scroll
for i := 0; i < 10; i++ {
e.WriteString("line\r\n")
}
// Verify we have scrollback
if e.ScrollbackLen() == 0 {
t.Error("expected scrollback before ED 3")
}
// ED 3 (ESC[3J) should clear scrollback
e.WriteString("\x1b[3J")
if e.ScrollbackLen() != 0 {
t.Errorf("expected empty scrollback after ED 3, got %d", e.ScrollbackLen())
}
})
}
+66
View File
@@ -0,0 +1,66 @@
package vt
import (
"image/color"
"io"
uv "github.com/charmbracelet/ultraviolet"
)
// Terminal represents a virtual terminal interface.
type Terminal interface {
BackgroundColor() color.Color
Blur()
Bounds() uv.Rectangle
CellAt(x int, y int) *uv.Cell
ClearScrollback()
Close() error
CursorColor() color.Color
CursorPosition() uv.Position
// CursorHidden reports whether the cursor is currently hidden.
CursorHidden() bool
// CursorStyle returns the current cursor style and whether it blinks.
CursorStyle() (style CursorStyle, blink bool)
Draw(scr uv.Screen, area uv.Rectangle)
Focus()
ForegroundColor() color.Color
Height() int
IndexedColor(i int) color.Color
InputPipe() io.Writer
IsAltScreen() bool
Paste(text string)
Read(p []byte) (n int, err error)
RegisterApcHandler(handler ApcHandler)
RegisterCsiHandler(cmd int, handler CsiHandler)
RegisterDcsHandler(cmd int, handler DcsHandler)
RegisterEscHandler(cmd int, handler EscHandler)
RegisterOscHandler(cmd int, handler OscHandler)
RegisterPmHandler(handler PmHandler)
RegisterSosHandler(handler SosHandler)
Render() string
Resize(width int, height int)
Scrollback() *Scrollback
ScrollbackCellAt(x, y int) *uv.Cell
ScrollbackLen() int
SendKey(k uv.KeyEvent)
SendKeys(keys ...uv.KeyEvent)
SendMouse(m Mouse)
SendText(text string)
SetBackgroundColor(c color.Color)
SetCallbacks(cb Callbacks)
SetCell(x int, y int, c *uv.Cell)
SetCursorColor(c color.Color)
SetDefaultBackgroundColor(c color.Color)
SetDefaultCursorColor(c color.Color)
SetDefaultForegroundColor(c color.Color)
SetForegroundColor(c color.Color)
SetIndexedColor(i int, c color.Color)
SetLogger(l Logger)
SetScrollbackSize(maxLines int)
String() string
Touched() []*uv.LineData
Width() int
WidthMethod() uv.WidthMethod
Write(p []byte) (n int, err error)
WriteString(s string) (n int, err error)
}
+133
View File
@@ -0,0 +1,133 @@
package vt
import (
"unicode/utf8"
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/x/ansi"
)
// printableASCII reports whether r is a character that can never join the
// grapheme cluster beside it. No ASCII character is a combining mark, a ZWJ, a
// spacing mark or a regional indicator, and CR and LF are not printable, so a
// cluster boundary between two of these is certain without asking the
// segmenter.
func printableASCII(r rune) bool {
return r >= ansi.SP && r < ansi.DEL
}
// handlePrint handles printable characters.
//
// A character is held back rather than printed straight away, because the one
// after it may be a combining mark that belongs to the same cluster. Printing
// "e" from "e\u0301" before the mark arrives puts the base in one cell and
// leaves the mark to become a zero-width cell of its own, which the next write
// or erase then destroys.
func (e *Emulator) handlePrint(r rune) {
// No ASCII character can extend the cluster before it: none of them is
// Extend, ZWJ, SpacingMark, Prepend, a regional indicator, or part of an
// Indic conjunct. So an ASCII character arriving is proof that whatever is
// buffered is finished, and the buffer can go out.
//
// This is also what keeps the buffer from being re-segmented as it grows.
// Asking where the clusters are on every character costs the length of the
// buffer each time, which is quadratic over a long run of combining marks
// that never resolves into more than one cluster.
if printableASCII(r) {
// Two printable ASCII characters in a row is the common case by a wide
// margin, and needs no segmenting at all.
if len(e.grapheme) == 1 && printableASCII(rune(e.grapheme[0])) {
e.handleGrapheme(string(e.grapheme[0]), 1)
e.grapheme = utf8.AppendRune(e.grapheme[:0], r)
return
}
e.flushGrapheme()
}
e.grapheme = utf8.AppendRune(e.grapheme, r)
}
// flushGrapheme flushes the current grapheme buffer, if any, and handles the
// grapheme as a single unit.
func (e *Emulator) flushGrapheme() {
if len(e.grapheme) == 0 {
return
}
// XXX: We always use [ansi.GraphemeWidth] here to report accurate widths
// and it's up to the caller to decide how to handle Unicode vs non-Unicode
// modes.
method := ansi.GraphemeWidth
graphemes := e.grapheme
for len(graphemes) > 0 {
cluster, width := ansi.FirstGraphemeCluster(graphemes, method)
if len(cluster) == 0 {
break
}
e.handleGrapheme(string(cluster), width)
graphemes = graphemes[len(cluster):]
}
e.grapheme = e.grapheme[:0] // Reset the grapheme buffer.
}
// handleGrapheme handles UTF-8 graphemes.
func (e *Emulator) handleGrapheme(content string, width int) {
awm := e.isModeSet(ansi.ModeAutoWrap)
cell := uv.Cell{
Content: content,
Width: width,
Style: e.scr.cursorPen(),
Link: e.scr.cursorLink(),
}
x, y := e.scr.CursorPosition()
if e.atPhantom && awm {
// moves cursor down similar to [Terminal.linefeed] except it doesn't
// respects [ansi.LNM] mode.
// This will reset the phantom state i.e. pending wrap state.
e.index()
_, y = e.scr.CursorPosition()
x = 0
}
// A single shift applies to the next character, whatever that character
// turns out to be. Take it now, so it cannot leak onto the one after this
// when this is a cluster no charset has a mapping for.
single := e.gsingle
e.gsingle = 0
// Handle character set mappings
if len(content) == 1 { //nolint:nestif
var charset CharSet
c := content[0]
if single > 1 && single < 4 {
charset = e.charsets[single]
} else if c < 128 {
charset = e.charsets[e.gl]
} else {
charset = e.charsets[e.gr]
}
if charset != nil {
if r, ok := charset[c]; ok {
cell.Content = r
cell.Width = 1
}
}
}
if cell.Width == 1 && len(content) == 1 {
e.lastChar, _ = utf8.DecodeRuneInString(content)
}
e.scr.SetCell(x, y, &cell)
// Handle phantom state at the end of the line
e.atPhantom = awm && x >= e.scr.Width()-1
if !e.atPhantom {
x += cell.Width
}
// NOTE: We don't reset the phantom state here, we handle it up above.
e.scr.setCursor(x, y, false)
}
+106
View File
@@ -0,0 +1,106 @@
package vt
import (
"strings"
"testing"
"time"
)
// A combining mark belongs to the character before it, however that character
// arrived. The printable-ASCII path used to write its cell immediately, which
// left a following mark with nowhere to go: it became a zero-width cell of its
// own, and the next write or erase destroyed it.
func TestCombiningMarkJoinsPrecedingASCII(t *testing.T) {
for _, tc := range []struct {
name string
input string
want []string
}{
{"bare", "bcé", []string{"b", "c", "é"}},
{"then erase", "bcé\x1b[K", []string{"b", "c", "é"}},
{"then another character", "bcéx", []string{"b", "c", "é", "x"}},
{"several in a row", "áb́c", []string{"á", "b́", "c"}},
{"mark on a wide character", "世́x", []string{"世́", "", "x"}},
{"emoji with a modifier", "\U0001f44b\U0001f3ffx", []string{"\U0001f44b\U0001f3ff", "", "x"}},
} {
t.Run(tc.name, func(t *testing.T) {
term := newTestTerminal(t, 10, 1)
term.WriteString(tc.input)
for x, want := range tc.want {
cell := term.CellAt(x, 0)
if cell == nil {
t.Fatalf("cell %d: nil", x)
}
if cell.Content != want {
t.Errorf("cell %d: got %q, want %q", x, cell.Content, want)
}
}
})
}
}
// A character is held back until the next one arrives, so it has to be flushed
// when the write ends or a caller reading the screen would not see it.
func TestLastCharacterIsFlushedWhenTheWriteEnds(t *testing.T) {
term := newTestTerminal(t, 10, 1)
term.WriteString("hi")
for x, want := range []string{"h", "i"} {
if cell := term.CellAt(x, 0); cell == nil || cell.Content != want {
t.Errorf("cell %d: got %v, want %q", x, cell, want)
}
}
}
// A single shift applies to one character, and the character it applies to may
// be a cluster no charset has a mapping for. Taking the shift only when the
// mapping happens left it set, and it landed on the character after.
func TestSingleShiftDoesNotLeakPastACluster(t *testing.T) {
for _, tc := range []struct {
name string
input string
want []string
}{
// SS2, then a cluster, then a plain character. The cluster has no
// mapping; the "b" must not be drawn from the shifted set.
{"cluster then plain", "\x1b*0\x8eáb", []string{"á", "b"}},
// The same shift with a mappable character, to show it still applies.
{"plain then plain", "\x1b*0\x8eab", []string{"▒", "b"}},
} {
t.Run(tc.name, func(t *testing.T) {
term := newTestTerminal(t, 10, 1)
term.WriteString(tc.input)
for x, want := range tc.want {
if cell := term.CellAt(x, 0); cell == nil || cell.Content != want {
t.Errorf("cell %d: got %v, want %q", x, cell, want)
}
}
})
}
}
// A run of combining marks is one cluster that keeps growing. Asking where its
// boundaries are on every character costs the length of the buffer each time,
// which is quadratic: 64KB of marks took six seconds before this was a single
// segmentation at the end of the run.
//
// The budget below is thousands of times the linear cost and a fraction of the
// quadratic one, so it says which of the two is in place without being a
// stopwatch on the machine it runs on.
func TestLongClusterRunStaysLinear(t *testing.T) {
input := "a" + strings.Repeat("́", 32*1024)
done := make(chan time.Duration, 1)
go func() {
term := NewEmulator(80, 24)
start := time.Now()
term.WriteString(input)
done <- time.Since(start)
}()
select {
case elapsed := <-done:
t.Logf("%d bytes in %v", len(input), elapsed)
case <-time.After(10 * time.Second):
t.Fatalf("writing %d bytes of one cluster did not finish in 10s", len(input))
}
}
+3
View File
@@ -0,0 +1,3 @@
// Package vt is a virtual terminal emulator that can be used to emulate a
// modern terminal application.
package vt