91 lines
1.9 KiB
Go
91 lines
1.9 KiB
Go
package server
|
|
|
|
import (
|
|
"strings"
|
|
"unicode/utf8"
|
|
|
|
"git.a-wan.net/alan/pipelines/internal/protocol"
|
|
)
|
|
|
|
// terminalTitles follows a terminal stream across reads and reports the
|
|
// window title the program sets (OSC 0 or OSC 2, ended by BEL or ST), so a
|
|
// listed terminal keeps a name before any client draws it.
|
|
type terminalTitles struct {
|
|
state int
|
|
osc []byte
|
|
}
|
|
|
|
const (
|
|
titleText = iota
|
|
titleEscape
|
|
titleOSC
|
|
titleOSCEscape
|
|
)
|
|
|
|
// feed scans data and returns the last title it completed, if any.
|
|
func (t *terminalTitles) feed(data []byte) (string, bool) {
|
|
title, found := "", false
|
|
for _, b := range data {
|
|
switch t.state {
|
|
case titleText:
|
|
if b == 0x1b {
|
|
t.state = titleEscape
|
|
}
|
|
case titleEscape:
|
|
if b == ']' {
|
|
t.state, t.osc = titleOSC, t.osc[:0]
|
|
} else if b != 0x1b {
|
|
t.state = titleText
|
|
}
|
|
case titleOSC:
|
|
switch {
|
|
case b == 0x07:
|
|
if s, ok := t.finish(); ok {
|
|
title, found = s, true
|
|
}
|
|
case b == 0x1b:
|
|
t.state = titleOSCEscape
|
|
case len(t.osc) < 4*protocol.TerminalTitleLimit:
|
|
t.osc = append(t.osc, b)
|
|
}
|
|
case titleOSCEscape:
|
|
if b == '\\' {
|
|
if s, ok := t.finish(); ok {
|
|
title, found = s, true
|
|
}
|
|
} else {
|
|
t.state = titleEscape
|
|
}
|
|
}
|
|
}
|
|
return title, found
|
|
}
|
|
|
|
func (t *terminalTitles) finish() (string, bool) {
|
|
t.state = titleText
|
|
body := string(t.osc)
|
|
for _, prefix := range []string{"0;", "2;"} {
|
|
if strings.HasPrefix(body, prefix) {
|
|
return cleanTerminalTitle(body[len(prefix):]), true
|
|
}
|
|
}
|
|
return "", false
|
|
}
|
|
|
|
// cleanTerminalTitle keeps printable text within the title bound.
|
|
func cleanTerminalTitle(title string) string {
|
|
title = strings.ToValidUTF8(title, "")
|
|
title = strings.Map(func(r rune) rune {
|
|
if r < 0x20 || r == 0x7f {
|
|
return -1
|
|
}
|
|
return r
|
|
}, title)
|
|
title = strings.TrimSpace(title)
|
|
for len(title) > protocol.TerminalTitleLimit {
|
|
_, size := utf8.DecodeLastRuneInString(title)
|
|
title = title[:len(title)-size]
|
|
}
|
|
return title
|
|
}
|