From 27377f2a4930cf1b2e6c91cc99f4d5cf20314efb Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 10 Oct 2026 17:35:12 +0000 Subject: [PATCH] Sixel graphics for telnet callers Every ANSI terminal is asked for its device attributes (CSI c) and its cell size in pixels (CSI 16 t); one that has sixel (attribute 4) sees the logo as a picture above the system's name: [general] logo, a PNG, or the name drawn in a pixel font, fitted to the window. Callers turn it off or on in their profile. Listeners have sixel = auto (telnet's default) or no (raw and rlogin: modem lines are slow). The encoder (internal/sixel) keeps a picture's own colors up to 255 and dithers to the web-safe palette beyond, leaves transparent pixels as the background, run-length codes, and keeps register 0 black for decoders that fill unset pixels with it; a test decodes its output with ImageMagick. The logo's PNG and pixel font move to internal/logo, shared with the 3270 logo; the PNG's size is checked before it is decoded. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01AFQhReUqUc7F5srk2hViqr --- README.md | 20 ++++- bbs.conf.sample | 9 +- cmd/bbs/main.go | 1 + internal/logo/logo.go | 82 +++++++++++++++++ internal/server/config.go | 20 ++++- internal/server/server.go | 12 ++- internal/server/server_test.go | 58 +++++++++++- internal/sixel/sixel.go | 158 +++++++++++++++++++++++++++++++++ internal/sixel/sixel_test.go | 112 +++++++++++++++++++++++ internal/textui/logo.go | 72 +++++++++++++++ internal/textui/term.go | 75 ++++++++++++++-- internal/textui/ui.go | 24 ++++- internal/ui3270/graphics.go | 45 ++-------- 13 files changed, 628 insertions(+), 60 deletions(-) create mode 100644 internal/logo/logo.go create mode 100644 internal/sixel/sixel.go create mode 100644 internal/sixel/sixel_test.go create mode 100644 internal/textui/logo.go diff --git a/README.md b/README.md index 2eb6e68..2939d4f 100644 --- a/README.md +++ b/README.md @@ -242,6 +242,20 @@ x3270 -model 3279-4 localhost:2300 `tn3270 = no` on a listener sends 3270s the text BBS (which they cannot show). +### Sixel graphics + +Telnet callers whose terminal has sixel graphics (xterm `-ti vt340`, +mlterm, foot, WezTerm, Windows Terminal, iTerm2, SyncTERM, ...) see the +logo as a picture above the system's name: `logo = /etc/bbs/logo.png`, or +without one the name drawn in a pixel font. The BBS asks every ANSI +terminal for its device attributes (`CSI c`; sixel is attribute 4) and its +character cell in pixels (`CSI 16 t`, to fit the logo to the window), so +nothing changes for terminals without sixel. A caller turns it off (or on, +if their terminal has it) in their profile. + +`sixel = auto` is the default for telnet listeners and `no` for raw and +rlogin ones: a picture is slow over a modem. + ### 3270 graphics The BBS reads everything the terminal says of itself when it connects (its @@ -302,6 +316,8 @@ and Greg Price's [3270 Graphics](https://www.prycroft6.com.au/misc/3270grfx.html | `internal/telnet` | the server side of telnet: options, terminal type, window size, the handoff to go3270 | | `internal/textui` | the text BBS: line editing, ANSI detection, paging, the menus | | `internal/ui3270` | the 3270 BBS: screens and PF keys on go3270, and its graphics | +| `internal/sixel` | the sixel encoder | +| `internal/logo` | the logo: a PNG, or the name in a pixel font | | `internal/bbs` | the BBS itself: nodes, logins, new users, posting, cleaning text | | `internal/store` | the SQLite database | | `internal/config` | the configuration file | @@ -315,5 +331,7 @@ modemmenu header, one whose header is not trusted, a login and a post, a new user, rlogin with a right and a wrong password and trusted, throttling by caller ID, all lines busy, a telnet ANSI client, a TN3270 client taken through go3270's negotiation to the logon screen and out with PF3, -and TN3270 clients that report programmed symbols (the logo is loaded and +telnet terminals with and without sixel, the sixel encoder checked by +decoding its output with ImageMagick (when installed), and TN3270 +clients that report programmed symbols (the logo is loaded and shown), vector graphics (the logo is drawn) or neither (nothing is sent). diff --git a/bbs.conf.sample b/bbs.conf.sample index a82e0d8..07daed1 100644 --- a/bbs.conf.sample +++ b/bbs.conf.sample @@ -23,9 +23,13 @@ log = syslog ;motd = "The line is down for maintenance on Sunday." ;motd_file = /etc/bbs/motd.txt goodbye = Thanks for calling. +; the logo: a PNG (at most 1000x400), shown as sixel graphics on telnet +; terminals that have them, and on 3270s (below). Without one, the +; system's name is drawn in a pixel font +;logo = /etc/bbs/logo.png ; 3270 graphics. Box drawing (graphic escape) is used wherever the ; terminal has it. tn3270_symbols: the logo (the system's name, or -; tn3270_logo, a PNG: dark or opaque pixels are drawn) loaded as programmed +; tn3270_logo, a PNG, or logo: one color, dark or opaque pixels drawn) loaded as programmed ; symbols on terminals that take them (IBM PCOMM, HostExplorer; not the ; x3270 family). tn3270_vector: the logo drawn with vector graphics instead ; on terminals that have them (PCOMM with host graphics on); experimental @@ -63,6 +67,9 @@ throttle_time = 600 ; (or believes its terminal type), yes, no ; utf8 = auto UTF-8 both ways: auto by the terminal type (xterm ; and friends yes; "ansi" BBS terminals no), yes, no +; sixel = auto the logo as sixel graphics on terminals that say +; they have them (device attributes); no. auto for +; telnet, no for raw and rlogin (slow modem lines) ; max_per_ip = 4 connections at once from one address (loopback ; and unix sockets: no limit, they are modem servers) ; header = no yes: a session header comes first, NAME=value lines diff --git a/cmd/bbs/main.go b/cmd/bbs/main.go index e083b0d..328e329 100644 --- a/cmd/bbs/main.go +++ b/cmd/bbs/main.go @@ -155,6 +155,7 @@ func serve(cfg *server.Config) int { defer stop() srv := server.New(b, cfg.Listeners) srv.Graphics = cfg.Graphics + srv.LogoFile = cfg.LogoFile if err := srv.Run(ctx); err != nil { lg.Printf("%v", err) return 1 diff --git a/internal/logo/logo.go b/internal/logo/logo.go new file mode 100644 index 0000000..58d3734 --- /dev/null +++ b/internal/logo/logo.go @@ -0,0 +1,82 @@ +// Package logo is the BBS's logo as a picture: a PNG the sysop gives, or +// the system's name drawn in a pixel font. The 3270 and sixel front ends +// each show it their own way. +package logo + +import ( + "errors" + "image" + "image/color" + "image/png" + "os" + + "golang.org/x/image/font" + "golang.org/x/image/font/basicfont" + "golang.org/x/image/math/fixed" +) + +// Largest picture taken from a file. +const ( + MaxWidth = 1000 + MaxHeight = 400 +) + +// Load reads a PNG logo. +func Load(path string) (image.Image, error) { + f, err := os.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + cfg, err := png.DecodeConfig(f) + if err != nil { + return nil, err + } + // look at the size before decoding: a small file can claim a huge one + if cfg.Width > MaxWidth || cfg.Height > MaxHeight { + return nil, errors.New("logo: larger than 1000x400") + } + if _, err := f.Seek(0, 0); err != nil { + return nil, err + } + return png.Decode(f) +} + +// On reports whether a pel of a picture is drawn: opaque and not near +// white (dark on white, or anything on transparent). +func On(c color.Color) bool { + n := color.NRGBAModel.Convert(c).(color.NRGBA) + lum := (299*int(n.R) + 587*int(n.G) + 114*int(n.B)) / 1000 + return n.A >= 128 && lum < 200 +} + +// Mono is a picture as on (255) and off (0) pels. +func Mono(src image.Image) *image.Gray { + b := src.Bounds() + img := image.NewGray(image.Rect(0, 0, b.Dx(), b.Dy())) + for y := 0; y < b.Dy(); y++ { + for x := 0; x < b.Dx(); x++ { + if On(src.At(b.Min.X+x, b.Min.Y+y)) { + img.SetGray(x, y, color.Gray{255}) + } + } + } + return img +} + +// Name draws text in a 7x13 pixel font, scaled by a whole factor to be +// about height pels high (at least 13): on pels 255, off 0. +func Name(text string, height int) *image.Gray { + n := len([]rune(text)) + small := image.NewGray(image.Rect(0, 0, 7*n, 13)) + d := font.Drawer{Dst: small, Src: image.White, Face: basicfont.Face7x13, Dot: fixed.P(0, 11)} + d.DrawString(text) + scale := max(1, height/13) + img := image.NewGray(image.Rect(0, 0, 7*n*scale, 13*scale)) + for y := 0; y < img.Bounds().Dy(); y++ { + for x := 0; x < img.Bounds().Dx(); x++ { + img.SetGray(x, y, small.GrayAt(x/scale, y/scale)) + } + } + return img +} diff --git a/internal/server/config.go b/internal/server/config.go index 65b1141..f2ef915 100644 --- a/internal/server/config.go +++ b/internal/server/config.go @@ -11,6 +11,7 @@ import ( "github.com/Neo-Desktop/bbs-sec/internal/bbs" "github.com/Neo-Desktop/bbs-sec/internal/config" + "github.com/Neo-Desktop/bbs-sec/internal/logo" "github.com/Neo-Desktop/bbs-sec/internal/ui3270" ) @@ -18,6 +19,7 @@ import ( type Config struct { Settings bbs.Settings Graphics ui3270.Graphics + LogoFile string // [general] logo: a PNG, for sixel terminals and 3270s Database string Log string // syslog, stderr, none, or a file Listeners []*Listener @@ -30,9 +32,9 @@ type Config struct { func DefaultListeners() []*Listener { return []*Listener{ {Name: "telnet", Kind: "telnet", Address: ":2300", Via: "telnet", TN3270: true, - ANSI: "auto", UTF8: "auto", MaxPerIP: 4}, + ANSI: "auto", UTF8: "auto", Sixel: "auto", MaxPerIP: 4}, {Name: "modem", Kind: "raw", Address: "127.0.0.1:2323", Via: "modem", - ANSI: "auto", UTF8: "no", HeaderTimeout: 10 * time.Second}, + ANSI: "auto", UTF8: "no", Sixel: "no", HeaderTimeout: 10 * time.Second}, } } @@ -107,7 +109,16 @@ func (c *Config) general(g *config.Section) error { if c.Graphics.Vector, err = g.Bool("tn3270_vector", false); err != nil { return err } - c.Graphics.LogoFile = g.String("tn3270_logo", "") + c.LogoFile = g.String("logo", "") + // 3270s may have a logo of their own (one-color, cut into cells) + c.Graphics.LogoFile = g.String("tn3270_logo", c.LogoFile) + for _, f := range []string{c.LogoFile, c.Graphics.LogoFile} { + if f != "" { + if _, err := logo.Load(f); err != nil { + return fmt.Errorf("logo %s: %w", f, err) + } + } + } ints := []struct { key string p *int @@ -172,7 +183,8 @@ func listener(sec *config.Section) (*Listener, error) { key string p *string def string - }{{"ansi", &l.ANSI, "auto"}, {"utf8", &l.UTF8, map[bool]string{true: "auto", false: "no"}[l.Kind == "telnet"]}} { + }{{"ansi", &l.ANSI, "auto"}, {"utf8", &l.UTF8, map[bool]string{true: "auto", false: "no"}[l.Kind == "telnet"]}, + {"sixel", &l.Sixel, map[bool]string{true: "auto", false: "no"}[l.Kind == "telnet"]}} { *o.p = strings.ToLower(sec.String(o.key, o.def)) switch *o.p { case "auto", "yes", "no": diff --git a/internal/server/server.go b/internal/server/server.go index c759978..da67783 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -50,6 +50,7 @@ type Listener struct { TN3270 bool // telnet: take 3270 clients ANSI string // auto, yes, no: the terminal's ANSI, if not told UTF8 string // auto, yes, no + Sixel string // auto or yes (ask the terminal), no Header bool // read a session header first HeaderTimeout time.Duration TrustUser bool // the header's MODEM_USER (rlogin's server user) is logged in @@ -71,6 +72,7 @@ type Server struct { B *bbs.BBS Listeners []*Listener Graphics ui3270.Graphics // for 3270s + LogoFile string // the logo for sixel terminals ("": the name) mu sync.Mutex perIP map[string]int @@ -432,7 +434,15 @@ func (s *Server) text(rw io.ReadWriter, c net.Conn, l *Listener, node *bbs.Node, default: t.UTF8 = utf8Term(tt) } - return textui.Run(s.B, node, t, textui.Options{CreateTrusted: l.CreateUsers}) + if t.ANSI && (l.Sixel == "auto" || l.Sixel == "yes") { + on, err := t.DetectSixel(1500 * time.Millisecond) + if err != nil { + return err + } + t.Sixel = on + } + return textui.Run(s.B, node, t, textui.Options{CreateTrusted: l.CreateUsers, + LogoFile: s.LogoFile}) } type deadliner interface{ SetReadDeadline(time.Time) error } diff --git a/internal/server/server_test.go b/internal/server/server_test.go index 6074428..f5c29f7 100644 --- a/internal/server/server_test.go +++ b/internal/server/server_test.go @@ -301,9 +301,13 @@ func TestTelnetANSI(t *testing.T) { type tnClient struct { c net.Conn ttype string - got []byte - recs [][]byte // 3270 records, split at IAC EOR - cur []byte + // answers to the BBS's terminal queries: device attributes (CSI c) + // and the cell size (CSI 16 t), "" for none + da, cell string + asked int + got []byte + recs [][]byte // 3270 records, split at IAC EOR + cur []byte } const ( @@ -381,10 +385,23 @@ func (tc *tnClient) read(t *testing.T) { } } +// answer answers the terminal queries that have come. +func (tc *tnClient) answer() { + for n := bytes.Count(tc.got, []byte("\x1b[c")); tc.asked < n; tc.asked++ { + if tc.cell != "" { + tc.c.Write([]byte(tc.cell)) + } + if tc.da != "" { + tc.c.Write([]byte(tc.da)) + } + } +} + func (tc *tnClient) expect(t *testing.T, want string) { t.Helper() for !bytes.Contains(tc.got, []byte(want)) { tc.read(t) + tc.answer() } } @@ -564,3 +581,38 @@ func TestVectorLogo(t *testing.T) { t.Fatalf("no Object Picture after the logon screen: % x", after[:min(len(after), 16)]) } } + +func TestSixelLogo(t *testing.T) { + e := start(t, nil, &Listener{Name: "telnet", Kind: "telnet", Address: "telnet.sock", + TN3270: true, ANSI: "auto", UTF8: "auto", Sixel: "auto"}) + c, err := net.Dial("unix", filepath.Join(e.dir, "telnet.sock")) + if err != nil { + t.Fatal(err) + } + defer c.Close() + tc := &tnClient{c: c, ttype: "xterm-256color", da: "\x1b[?63;1;4;22c", cell: "\x1b[6;20;10t"} + tc.expect(t, "\x1bP0;1;0q") + tc.expect(t, "\x1b\\") + tc.expect(t, "Test BBS") + // the name, two rows of 20 pels high: 13 pels of font scaled by 3 + if !bytes.Contains(tc.got, []byte("\"1;1;")) { + t.Error("no raster attributes") + } + tc.expect(t, "Name") +} + +func TestNoSixel(t *testing.T) { + e := start(t, nil, &Listener{Name: "telnet", Kind: "telnet", Address: "telnet.sock", + TN3270: true, ANSI: "auto", UTF8: "auto", Sixel: "auto"}) + c, err := net.Dial("unix", filepath.Join(e.dir, "telnet.sock")) + if err != nil { + t.Fatal(err) + } + defer c.Close() + // a VT220-like terminal: attributes without 4 + tc := &tnClient{c: c, ttype: "xterm", da: "\x1b[?62;1;6;22c"} + tc.expect(t, "Name") + if bytes.Contains(tc.got, []byte("\x1bP")) { + t.Error("sixel sent to a terminal without it") + } +} diff --git a/internal/sixel/sixel.go b/internal/sixel/sixel.go new file mode 100644 index 0000000..7d14947 --- /dev/null +++ b/internal/sixel/sixel.go @@ -0,0 +1,158 @@ +// Package sixel encodes pictures as DEC sixel graphics, which xterm +// (-ti vt340), mlterm, foot, WezTerm, Windows Terminal, iTerm2, SyncTERM +// and others show inline. +// +// A sixel picture is a DCS string: ESC P 0;1;0 q, the raster attributes, +// the palette, then bands six pels high, each a run of characters per color +// whose six low bits are that color's pels in the column, and ESC \. +package sixel + +import ( + "bytes" + "errors" + "fmt" + "image" + "image/color" + "image/color/palette" + "image/draw" +) + +// MaxColors is the most colors a picture is given, register 0 aside: a +// VT340 had 16 registers; terminals today have 256. +const MaxColors = 255 + +// Encode encodes img. Transparent pels (alpha < 128) are left as the +// terminal's background. A picture with more than MaxColors colors is +// dithered to the web-safe palette. +func Encode(img image.Image) ([]byte, error) { + b := img.Bounds() + w, h := b.Dx(), b.Dy() + if w <= 0 || h <= 0 { + return nil, errors.New("sixel: empty picture") + } + if w > 4096 || h > 4096 { + return nil, errors.New("sixel: picture too large") + } + pal, idx := quantize(img) + + var out bytes.Buffer + // P2 = 1: pels with no sixel keep the background + out.WriteString("\x1bP0;1;0q") + fmt.Fprintf(&out, "\"1;1;%d;%d", w, h) + // register 0 is black and unused: decoders that fill the pels no + // sixel sets (rather than leave them, as P2 = 1 asks) fill them with + // register 0. The picture's colors are 1 on. + out.WriteString("#0;2;0;0;0") + for i, c := range pal { + r, g, bl, _ := c.RGBA() + fmt.Fprintf(&out, "#%d;2;%d;%d;%d", i+1, pct(r), pct(g), pct(bl)) + } + for band := 0; band < h; band += 6 { + // the colors in this band + used := make([]bool, len(pal)) + for y := band; y < band+6 && y < h; y++ { + for x := 0; x < w; x++ { + if c := idx[y*w+x]; c >= 0 { + used[c] = true + } + } + } + first := true + for c := range pal { + if !used[c] { + continue + } + if !first { + out.WriteByte('$') // back to the band's start for the next color + } + first = false + fmt.Fprintf(&out, "#%d", c+1) + run, last := 0, byte(0) + flush := func() { + switch { + case run == 0: + case run > 3: + fmt.Fprintf(&out, "!%d%c", run, last) + default: + for i := 0; i < run; i++ { + out.WriteByte(last) + } + } + } + for x := 0; x < w; x++ { + var bits byte + for i := 0; i < 6 && band+i < h; i++ { + if idx[(band+i)*w+x] == c { + bits |= 1 << i + } + } + ch := 63 + bits + if ch == last && run > 0 { + run++ + continue + } + flush() + run, last = 1, ch + } + // trailing empty columns need not be sent + if last != 63 { + flush() + } + } + out.WriteByte('-') // next band + } + out.WriteString("\x1b\\") + return out.Bytes(), nil +} + +func pct(v uint32) int { return int((v*100 + 0x7fff) / 0xffff) } + +// quantize gives the picture's palette and each pel's index in it (-1 for +// transparent). +func quantize(img image.Image) ([]color.Color, []int) { + b := img.Bounds() + w, h := b.Dx(), b.Dy() + idx := make([]int, w*h) + seen := map[color.NRGBA]int{} + var pal []color.Color + exact := true + for y := 0; y < h && exact; y++ { + for x := 0; x < w; x++ { + c := color.NRGBAModel.Convert(img.At(b.Min.X+x, b.Min.Y+y)).(color.NRGBA) + if c.A < 128 { + idx[y*w+x] = -1 + continue + } + c.A = 255 + i, ok := seen[c] + if !ok { + if len(pal) == MaxColors { + exact = false + break + } + i = len(pal) + seen[c] = i + pal = append(pal, c) + } + idx[y*w+x] = i + } + } + if exact { + return pal, idx + } + // too many colors: dither to the web-safe palette (216) + dst := image.NewPaletted(image.Rect(0, 0, w, h), palette.WebSafe) + draw.FloydSteinberg.Draw(dst, dst.Bounds(), img, b.Min) + pal = palette.WebSafe + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + _, _, _, a := img.At(b.Min.X+x, b.Min.Y+y).RGBA() + if a < 0x8000 { + idx[y*w+x] = -1 + } else { + idx[y*w+x] = int(dst.ColorIndexAt(x, y)) + } + } + } + return pal, idx +} diff --git a/internal/sixel/sixel_test.go b/internal/sixel/sixel_test.go new file mode 100644 index 0000000..6fa74e5 --- /dev/null +++ b/internal/sixel/sixel_test.go @@ -0,0 +1,112 @@ +package sixel + +import ( + "bytes" + "image" + "image/color" + "image/png" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +func picture() *image.NRGBA { + img := image.NewNRGBA(image.Rect(0, 0, 20, 9)) + red := color.NRGBA{255, 0, 0, 255} + blue := color.NRGBA{0, 0, 255, 255} + for x := 0; x < 20; x++ { + img.Set(x, 0, red) // a red line + img.Set(x, 8, blue) + } + for y := 0; y < 9; y++ { + img.Set(3, y, blue) // a blue column through both bands + } + return img +} + +func TestEncodeShape(t *testing.T) { + data, err := Encode(picture()) + if err != nil { + t.Fatal(err) + } + s := string(data) + if !strings.HasPrefix(s, "\x1bP0;1;0q\"1;1;20;9") || !strings.HasSuffix(s, "\x1b\\") { + t.Errorf("framing: %q", s) + } + if strings.Count(s, "-") != 2 { + t.Errorf("want 2 bands: %q", s) + } + if !strings.Contains(s, "!") { + t.Errorf("no run-length: %q", s) + } + // nothing but sixel characters, digits and the controls of the format + // between the introducer and the terminator + for _, c := range s[len("\x1bP0;1;0q") : len(s)-2] { + if c < 0x20 || c > 0x7e { + t.Fatalf("byte %#x in the picture", c) + } + } + if _, err := Encode(image.NewNRGBA(image.Rect(0, 0, 0, 0))); err == nil { + t.Error("encoded an empty picture") + } +} + +func TestManyColors(t *testing.T) { + img := image.NewNRGBA(image.Rect(0, 0, 64, 64)) + for y := 0; y < 64; y++ { + for x := 0; x < 64; x++ { + img.Set(x, y, color.NRGBA{uint8(x * 4), uint8(y * 4), 128, 255}) + } + } + data, err := Encode(img) + if err != nil { + t.Fatal(err) + } + if n := strings.Count(string(data), ";2;"); n > MaxColors+1 { + t.Errorf("%d colors", n) + } +} + +// ImageMagick reads sixel: the picture it gets back must be ours +func TestDecodeWithImageMagick(t *testing.T) { + convert, err := exec.LookPath("convert") + if err != nil { + t.Skip("no ImageMagick") + } + data, err := Encode(picture()) + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + in, out := filepath.Join(dir, "p.six"), filepath.Join(dir, "p.png") + os.WriteFile(in, data, 0600) + if msg, err := exec.Command(convert, "sixel:"+in, out).CombinedOutput(); err != nil { + t.Skipf("convert: %v %s", err, msg) + } + f, err := os.ReadFile(out) + if err != nil { + t.Fatal(err) + } + got, err := png.Decode(bytes.NewReader(f)) + if err != nil { + t.Fatal(err) + } + want := picture() + if got.Bounds().Dx() != 20 || got.Bounds().Dy() < 9 { + t.Fatalf("size %v", got.Bounds()) + } + for y := 0; y < 9; y++ { + for x := 0; x < 20; x++ { + wr, wg, wb, wa := want.At(x, y).RGBA() + gr, gg, gb, _ := got.At(x, y).RGBA() + if wa == 0 { + continue // background: whatever the decoder makes of it + } + if wr>>8 != gr>>8 || wg>>8 != gg>>8 || wb>>8 != gb>>8 { + t.Errorf("(%d,%d) = %d,%d,%d, want %d,%d,%d", x, y, gr>>8, gg>>8, gb>>8, wr>>8, wg>>8, wb>>8) + } + } + } +} diff --git a/internal/textui/logo.go b/internal/textui/logo.go new file mode 100644 index 0000000..2b3395d --- /dev/null +++ b/internal/textui/logo.go @@ -0,0 +1,72 @@ +package textui + +import ( + "image" + "image/color" + + "github.com/Neo-Desktop/bbs-sec/internal/logo" + "github.com/Neo-Desktop/bbs-sec/internal/sixel" +) + +// the cell assumed when the terminal does not say +const ( + defaultCellW = 10 + defaultCellH = 20 + logoRows = 6 // the most text rows the logo takes +) + +// cyan is the name logo's color +var cyan = color.NRGBA{0x00, 0xb4, 0xff, 0xff} + +// sixelLogo is the logo as sixel graphics for t: the PNG in file, or name +// in a pixel font two text rows high; nil if there is none to show. +func sixelLogo(t *Term, name, file string) []byte { + cw, ch := t.CellW, t.CellH + if cw == 0 || ch == 0 { + cw, ch = defaultCellW, defaultCellH + } + var img image.Image + if file != "" { + src, err := logo.Load(file) + if err != nil { + return nil + } + img = src + } else { + mono := logo.Name(name, 2*ch) + col := image.NewNRGBA(mono.Bounds()) + for y := 0; y < mono.Bounds().Dy(); y++ { + for x := 0; x < mono.Bounds().Dx(); x++ { + if mono.GrayAt(x, y).Y >= 128 { + col.SetNRGBA(x, y, cyan) + } + } + } + img = col + } + img = shrink(img, (t.Cols-1)*cw, logoRows*ch) + data, err := sixel.Encode(img) + if err != nil { + return nil + } + return data +} + +// shrink scales img down by a whole factor to fit maxW by maxH. +func shrink(img image.Image, maxW, maxH int) image.Image { + b := img.Bounds() + f := 1 + for b.Dx()/f > maxW || b.Dy()/f > maxH { + f++ + } + if f == 1 { + return img + } + out := image.NewNRGBA(image.Rect(0, 0, b.Dx()/f, b.Dy()/f)) + for y := 0; y < out.Bounds().Dy(); y++ { + for x := 0; x < out.Bounds().Dx(); x++ { + out.Set(x, y, img.At(b.Min.X+x*f, b.Min.Y+y*f)) + } + } + return out +} diff --git a/internal/textui/term.go b/internal/textui/term.go index e1412b8..90cf4ee 100644 --- a/internal/textui/term.go +++ b/internal/textui/term.go @@ -29,14 +29,17 @@ type Conn interface { // Term is the caller's terminal. type Term struct { - c Conn - r *bufio.Reader - w *bufio.Writer - ANSI bool // color and cursor movement - UTF8 bool // UTF-8 both ways; otherwise 7-bit ASCII - Cols int - Rows int - Idle time.Duration // for each key + c Conn + r *bufio.Reader + w *bufio.Writer + ANSI bool // color and cursor movement + UTF8 bool // UTF-8 both ways; otherwise 7-bit ASCII + Sixel bool // sixel graphics + // a character cell in pixels, if the terminal said (for sixel) + CellW, CellH int + Cols int + Rows int + Idle time.Duration // for each key deadline time.Time // a hard limit for keys (the login's) lastCR bool @@ -414,3 +417,59 @@ func (t *Term) DetectANSI(timeout time.Duration) (bool, error) { t.w.WriteString("\r" + strings.Repeat(" ", 20) + "\r") return false, nil } + +var ( + daPattern = regexp.MustCompile(`\x1b\[\?([0-9;]*)c`) + cellPattern = regexp.MustCompile(`\x1b\[6;(\d+);(\d+)t`) +) + +// DetectSixel asks the terminal for its device attributes (DA1), and its +// character cell's size in pixels (xterm's CSI 16 t, which not every +// terminal answers): a terminal whose attributes include 4 has sixel +// graphics. Only for ANSI terminals; one that does not answer within +// timeout has none. +func (t *Term) DetectSixel(timeout time.Duration) (bool, error) { + t.w.WriteString("\x1b[16t\x1b[c") + if err := t.Flush(); err != nil { + return false, err + } + var got []byte + end := time.Now().Add(timeout) + for time.Now().Before(end) && len(got) < 256 { + t.c.SetReadDeadline(end) + b, err := t.r.ReadByte() + t.c.SetReadDeadline(time.Time{}) + if err != nil { + if errors.Is(err, os.ErrDeadlineExceeded) { + break + } + return false, err + } + got = append(got, b) + if m := daPattern.FindSubmatch(got); m != nil { + if c := cellPattern.FindSubmatch(got); c != nil { + h, _ := strconv.Atoi(string(c[1])) + w, _ := strconv.Atoi(string(c[2])) + if w >= 4 && w <= 64 && h >= 4 && h <= 128 { + t.CellW, t.CellH = w, h + } + } + for _, a := range strings.Split(string(m[1]), ";") { + if a == "4" { + return true, nil + } + } + return false, nil + } + } + return false, nil +} + +// Picture shows a sixel picture (sixel.Encode's) on its own lines. +func (t *Term) Picture(data []byte) { + if !t.Sixel || len(data) == 0 { + return + } + t.w.Write(data) + t.w.WriteString("\r\n") +} diff --git a/internal/textui/ui.go b/internal/textui/ui.go index e45f191..08012c9 100644 --- a/internal/textui/ui.go +++ b/internal/textui/ui.go @@ -15,6 +15,8 @@ import ( type Options struct { // a trusted user unknown here gets an account of its own CreateTrusted bool + // the logo (a PNG; "": the system's name), on sixel terminals + LogoFile string } type session struct { @@ -48,6 +50,9 @@ func Run(b *bbs.BBS, n *bbs.Node, t *Term, o Options) error { func (s *session) run() error { t := s.t t.Clear() + if t.Sixel { + t.Picture(sixelLogo(t, s.b.Name, s.o.LogoFile)) + } t.Println(t.C(Cyan, s.b.Name)) if s.b.Banner != "" { t.Println(s.b.Banner) @@ -854,8 +859,9 @@ func (s *session) profile() error { t.Printf(" From: %s\n", u.Location) t.Printf(" Member: since %s, %d calls, %d posts\n", u.Created.Format("2006-01-02"), u.Logins, u.Posts) onOff := map[bool]string{true: "on", false: "off"} - t.Printf(" Terminal: %dx%d, ANSI %s, UTF-8 %s\n", t.Cols, t.Rows, onOff[t.ANSI], onOff[t.UTF8]) - menu := "\n[L]ocation, [A]NSI on/off, [8]-bit UTF-8 on/off, " + t.Printf(" Terminal: %dx%d, ANSI %s, UTF-8 %s, sixel %s\n", t.Cols, t.Rows, + onOff[t.ANSI], onOff[t.UTF8], onOff[t.Sixel]) + menu := "\n[L]ocation, [A]NSI on/off, [8]-bit UTF-8 on/off, [S]ixel on/off, " if !u.External { menu += "[P]assword, " } @@ -878,6 +884,20 @@ func (s *session) profile() error { t.ANSI = !t.ANSI case '8': t.UTF8 = !t.UTF8 + case 'S': + // on only where the terminal can: sixel bytes are noise elsewhere + if t.Sixel { + t.Sixel = false + } else if t.ANSI { + on, err := t.DetectSixel(2 * time.Second) + if err != nil { + return err + } + t.Sixel = on + if !on { + t.Println(t.C(Red, "Your terminal does not say it has sixel graphics.")) + } + } case 'P': if u.External { continue diff --git a/internal/ui3270/graphics.go b/internal/ui3270/graphics.go index 1255bf4..3bcde33 100644 --- a/internal/ui3270/graphics.go +++ b/internal/ui3270/graphics.go @@ -15,14 +15,11 @@ import ( "image" "image/color" "image/draw" - "image/png" - "os" "strings" "github.com/racingmars/go3270" - "golang.org/x/image/font" - "golang.org/x/image/font/basicfont" - "golang.org/x/image/math/fixed" + + logopkg "github.com/Neo-Desktop/bbs-sec/internal/logo" ) // Graphics are the 3270 graphics settings ([general] tn3270_*). @@ -133,45 +130,13 @@ func symbolCell(dev interface { // tall enough to fill rows character rows of cellH pels. func logoImage(g Graphics, name string, rows, cellH int) (*image.Gray, error) { if g.LogoFile != "" { - f, err := os.Open(g.LogoFile) + src, err := logopkg.Load(g.LogoFile) if err != nil { return nil, err } - defer f.Close() - src, err := png.Decode(f) - if err != nil { - return nil, err - } - b := src.Bounds() - if b.Dx() > 1000 || b.Dy() > 400 { - return nil, errors.New("logo: larger than 1000x400") - } - img := image.NewGray(image.Rect(0, 0, b.Dx(), b.Dy())) - for y := 0; y < b.Dy(); y++ { - for x := 0; x < b.Dx(); x++ { - // on: opaque and not near white (dark on white, or - // anything on transparent) - c := color.NRGBAModel.Convert(src.At(b.Min.X+x, b.Min.Y+y)).(color.NRGBA) - lum := (299*int(c.R) + 587*int(c.G) + 114*int(c.B)) / 1000 - if c.A >= 128 && lum < 200 { - img.SetGray(x, y, color.Gray{255}) - } - } - } - return img, nil + return logopkg.Mono(src), nil } - face := basicfont.Face7x13 - small := image.NewGray(image.Rect(0, 0, 7*len([]rune(name)), 13)) - d := font.Drawer{Dst: small, Src: image.White, Face: face, Dot: fixed.P(0, 11)} - d.DrawString(name) - scale := max(1, rows*cellH/13) - img := image.NewGray(image.Rect(0, 0, small.Bounds().Dx()*scale, 13*scale)) - for y := 0; y < img.Bounds().Dy(); y++ { - for x := 0; x < img.Bounds().Dx(); x++ { - img.SetGray(x, y, small.GrayAt(x/scale, y/scale)) - } - } - return img, nil + return logopkg.Name(name, rows*cellH), nil } // cut cuts img into cells: the distinct cells' symbols (an empty cell is the