diff --git a/README.md b/README.md index cadc708..f26b3b8 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ What there is: - [chat](https://github.com/Neo-Desktop/bbs-sec/wiki/Chat-and-Paging): rooms, messages to a node, paging the sysop - [finger and gopher](https://github.com/Neo-Desktop/bbs-sec/wiki/Finger-and-Gopher): who is on, and chosen areas in gopherspace - [a web forum](https://github.com/Neo-Desktop/bbs-sec/wiki/Web-Forum): the message areas as a bulletin board in the browser, in the manner of Invision Power Board 3, or of IPB 5, 4, 2 or 1, Ikonboard, vBulletin 6 back to 2 or Lite, XenForo 2.3 back to 1, MyBB 1.8 back to 1.2, PunBB 1.4 and 1.2, FluxBB 1.5, YaBB 2.5 back to 1, Simple Machines Forum 3.0 back to 1, or phpBB 3.3 back to 1 (themes) -- [image boards](https://github.com/Neo-Desktop/bbs-sec/wiki/Image-Boards): anonymous boards of images and replies at /chan/, in the manner of kusaba x and 4chan: bumping, sage, tripcodes (2channel's, and secure ones), greentext and >>quotes, a catalog, oekaki boards to draw on with stroke replay, staff's bans and reports, Yotsuba, Yotsuba B, Futaba, Burichan, Photon and Tomorrow styles, and 4chan's JSON; on the terminals too, with the pictures in sixel, kitty's or iTerm2's graphics, or coloured blocks +- [image boards](https://github.com/Neo-Desktop/bbs-sec/wiki/Image-Boards): anonymous boards of images and replies at /chan/, in the manner of kusaba x and 4chan: bumping, sage, tripcodes (2channel's, and secure ones), greentext and >>quotes, a catalog, oekaki boards to draw on with stroke replay, staff's bans and reports, Yotsuba, Yotsuba B, Futaba, Burichan, Photon and Tomorrow styles, and 4chan's JSON; on the terminals too, with the pictures in sixel, kitty's or iTerm2's graphics, or coloured blocks, and on 3270s in vector graphics (PCOMM, in its 16 colours) or graphic escape's blocks (x3270) - [a web terminal](https://github.com/Neo-Desktop/bbs-sec/wiki/HTTP-API#the-web-terminal): the BBS in a browser (xterm.js, built in) - [an HTTP API](https://github.com/Neo-Desktop/bbs-sec/wiki/HTTP-API): REST, server-sent events, and WebSockets (JSON or protobuf) where web clients chat with terminal callers; Prometheus metrics - [customization](https://github.com/Neo-Desktop/bbs-sec/wiki/Customization): ANSI art and 3270 screens, menus of the sysop's, @-codes, the prompts' words diff --git a/bbs.conf.sample b/bbs.conf.sample index c424df2..f8f3f89 100644 --- a/bbs.conf.sample +++ b/bbs.conf.sample @@ -63,10 +63,12 @@ goodbye = Thanks for calling. ; terminal has it. tn3270_symbols: the logo (the system's name, or ; 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 +; x3270 family). tn3270_vector: pictures (an image board's) drawn in the +; terminal's own colors, and the logo, with vector graphics on terminals +; that have them (PCOMM with host graphics on); without them, pictures +; are drawn in blocks (graphic escape, x3270) or said in words tn3270_symbols = yes -tn3270_vector = no +tn3270_vector = yes ;tn3270_logo = /etc/bbs/logo.png ; file areas: where the files are kept (by number, never by their names), ; the largest file, and what a user may upload a day (sysops: no limit) diff --git a/docs/wiki/Sixel-Graphics.md b/docs/wiki/Sixel-Graphics.md index 7b5f374..c8093b8 100644 --- a/docs/wiki/Sixel-Graphics.md +++ b/docs/wiki/Sixel-Graphics.md @@ -19,6 +19,7 @@ The [image boards](Image-Boards)' pictures are shown with sixel too, and on terminals without it as they can: kitty's graphics protocol on kitty and Ghostty, iTerm2's inline images on iTerm2 and mintty, and coloured half blocks on any other UTF-8 terminal with colour. *Pictures on/off* -(**M**) on the profile turns them off for a caller. +(**M**) on the profile turns them off for a caller. 3270s have pictures +of their own: vector graphics, or blocks (see [TN3270](TN3270#pictures)). **See also:** [TN3270 graphics](TN3270), [Configuration](Configuration), [Image boards](Image-Boards) diff --git a/docs/wiki/TN3270.md b/docs/wiki/TN3270.md index 4ab1956..431227f 100644 --- a/docs/wiki/TN3270.md +++ b/docs/wiki/TN3270.md @@ -35,9 +35,37 @@ query replies) and uses what it has: | | terminals | used for | |---|---|---| -| graphic escape (code page 310) | nearly all: x3270, c3270, wc3270, PCOMM, Vista | the box around the main menu, rules, bar charts in System info; ASCII otherwise | +| graphic escape (code page 310) | nearly all: x3270, c3270, wc3270, PCOMM, Vista | the box around the main menu, rules, bar charts in System info; ASCII otherwise; pictures in blocks where there are no vector graphics | | programmed symbols | IBM PCOMM, HostExplorer, Quick3270 | the logo on the logon screen: the system's name in a pixel font, or `tn3270_logo` (a PNG), cut into character cells and loaded as a symbol set | -| vector graphics | PCOMM (host graphics, native protocol), HostExplorer | the logo as a bitmap image instead, with `tn3270_vector = yes`; experimental | +| vector graphics | PCOMM (host graphics, native protocol), HostExplorer | pictures, in the terminal's own colours, and the logo as a bitmap image instead of symbols (`tn3270_vector`, on by default) | + +### Pictures + +An image board's pictures (a post's thumbnail, and the image whole) are +drawn the best way the terminal has: + +- **Vector graphics** (PCOMM): the picture as bitmaps, a pel for a pixel, + error-diffused to the terminal's own palette: PCOMM's 16 colours (its + Graphic Color reply), orange, purple, the dark shades and grey among + them. Each colour is overpainted: PCOMM's exclusive or does not combine + blue with the other colours. The cells under a picture are left empty, + and the cursor elsewhere: on PCOMM a character over a picture clears it + in its cell. +- **Blocks** (x3270, and any colour 3270 with graphic escape): ▀ ▄ ▌ ▐ █ + in the 3270's 7 colours, a cell two pixels by two, each cell the colour + and block nearest its four pixels. +- **Words** on the rest: `[cat.png, 640x480, 52 KB]`, which every + terminal shows under the picture too. + +A caller can turn pictures off (and on) on their profile (M, or PF11). +The profile's terminal line says which way they are drawn. + +PCOMM sends its graphics query replies (the Segment reply that says it +has vector graphics, its colours) only when asked for them by name: the +BBS asks with a Query List for whatever its Summary reply lists that did +not come with the first Query. `cmd/gfxtest` in +[go3270-sec](https://github.com/Neo-Desktop/go3270-sec) is a 3270 server +for trying vector graphics on an emulator, every record both ways logged. Option T of the 3270 main menu, *Your terminal*, shows what the terminal reported: code page, cell size, graphic escape, its symbol sets and Load PS diff --git a/go.mod b/go.mod index 855690e..90167ac 100644 --- a/go.mod +++ b/go.mod @@ -48,4 +48,4 @@ require ( modernc.org/token v1.1.0 // indirect ) -replace github.com/racingmars/go3270 => github.com/Neo-Desktop/go3270-sec v0.9.14-0.20261010180804-750b72ee6b2f +replace github.com/racingmars/go3270 => github.com/Neo-Desktop/go3270-sec v0.9.14-0.20261016021140-6c4a4ee0bbe9 diff --git a/go.sum b/go.sum index de2021e..b659746 100644 --- a/go.sum +++ b/go.sum @@ -2,8 +2,8 @@ filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= github.com/Masterminds/semver/v3 v3.2.1 h1:RN9w6+7QoMeJVGyfmbcgs28Br8cvmnucEXnY0rYXWg0= github.com/Masterminds/semver/v3 v3.2.1/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ= -github.com/Neo-Desktop/go3270-sec v0.9.14-0.20261010180804-750b72ee6b2f h1:Bt6G332gAcwKuDK+WBYMx6MgAsAbjEwBPb0fSxwQch8= -github.com/Neo-Desktop/go3270-sec v0.9.14-0.20261010180804-750b72ee6b2f/go.mod h1:JCzKbsCGdevsd+2iLMRw3Cd+Wk7vmBeGlnfHmeJEcsU= +github.com/Neo-Desktop/go3270-sec v0.9.14-0.20261016021140-6c4a4ee0bbe9 h1:psyndXf9Fv7MT7RzMK3HLcqQKgmejH6nu/9+vrQkIYE= +github.com/Neo-Desktop/go3270-sec v0.9.14-0.20261016021140-6c4a4ee0bbe9/go.mod h1:JCzKbsCGdevsd+2iLMRw3Cd+Wk7vmBeGlnfHmeJEcsU= github.com/coder/websocket v1.8.13 h1:f3QZdXy7uGVz+4uCJy2nTZyM0yTBj8yANEHhqlXZ9FE= github.com/coder/websocket v1.8.13/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= diff --git a/internal/confui/fields.go b/internal/confui/fields.go index cc23169..358808c 100644 --- a/internal/confui/fields.go +++ b/internal/confui/fields.go @@ -69,7 +69,7 @@ var labels = map[string]string{ "general.phone_country": "Caller ID country", "general.geoip": "GeoIP database", "general.geoip_credit": "GeoIP credit", "general.geoip_credit_url": "GeoIP credit link", "general.new_user_level": "New users' level", "general.validated_level": "Validated users' level", - "general.tn3270_symbols": "Logo as programmed symbols", "general.tn3270_vector": "Logo as vector graphics", + "general.tn3270_symbols": "Logo as programmed symbols", "general.tn3270_vector": "Vector graphics (pictures, logo)", "general.tn3270_logo": "3270 logo (PNG)", "general.page_command": "Page command", "security.deny_file": "Addresses refused (file)", "security.name_deny_file": "Names refused (file)", "security.hack_log": "Hack log", "security.ban_minutes": "Ban after a lock-out (min)", diff --git a/internal/server/config.go b/internal/server/config.go index fb828d4..b65cab5 100644 --- a/internal/server/config.go +++ b/internal/server/config.go @@ -274,7 +274,7 @@ func (c *Config) general(g *config.Section) error { if c.Graphics.Symbols, err = g.Bool("tn3270_symbols", true); err != nil { return err } - if c.Graphics.Vector, err = g.Bool("tn3270_vector", false); err != nil { + if c.Graphics.Vector, err = g.Bool("tn3270_vector", true); err != nil { return err } c.LogoFile = g.String("logo", "") diff --git a/internal/server/pictures_test.go b/internal/server/pictures_test.go new file mode 100644 index 0000000..7945c0c --- /dev/null +++ b/internal/server/pictures_test.go @@ -0,0 +1,106 @@ +package server + +import ( + "bytes" + "image" + "image/color" + "image/png" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/Neo-Desktop/bbs-sec/internal/bbs" + "github.com/Neo-Desktop/bbs-sec/internal/imageboard" + "github.com/Neo-Desktop/bbs-sec/internal/ui3270" +) + +// TestPictures3270: on x3270, which has no vector graphics, an image +// board post's picture is drawn in graphic escape's blocks above what it +// is; turned off on the profile, it is said in words alone. +func TestPictures3270(t *testing.T) { + if _, err := exec.LookPath("s3270"); err != nil { + t.Skip("no s3270") + } + addr := freeTCP(t) + e := startFull(t, ui3270.Graphics{Vector: true}, nil, func(b *bbs.BBS, dir string) { + set := imageboard.Defaults() + set.Dir, set.ThreadWait, set.ReplyWait = filepath.Join(dir, "chan"), 0, 0 + ib := &imageboard.Server{B: b, S: set} + b.ImageBoards = ib + bd, err := b.Store.CreateBoard(imageboard.NewBoard("b", "Random")) + if err != nil { + t.Fatal(err) + } + // red over green + img := image.NewRGBA(image.Rect(0, 0, 200, 100)) + for y := 0; y < 100; y++ { + for x := 0; x < 200; x++ { + c := color.RGBA{255, 0, 0, 255} + if y >= 50 { + c = color.RGBA{0, 255, 0, 255} + } + img.Set(x, y, c) + } + } + var data bytes.Buffer + png.Encode(&data, img) + if _, err := ib.Submit(&imageboard.Submission{Board: bd, Subject: "Flag", Comment: "red over green", + Image: data.Bytes(), FileName: "flag.png", IP: "test"}); err != nil { + t.Fatal(err) + } + }, &Listener{Name: "telnet", Kind: "telnet", Address: addr, TN3270: true}) + view := func() string { + script := strings.Join([]string{ + "Connect(" + addr + ")", "Wait(10,InputField)", + `String("alice")`, "Tab()", `String("alicepass1")`, "Enter()", "Wait(5,InputField)", + `String("b")`, "Enter()", "Wait(5,InputField)", // image boards + `String("s")`, "Enter()", "Wait(5,InputField)", // /b/ + `String("s")`, "Enter()", "Wait(5,InputField)", // the thread + "Ascii()", "ReadBuffer(Ascii)", "Quit()", ""}, "\n") + cmd := exec.Command("s3270", "-model", "3279-2") + cmd.Stdin = strings.NewReader(script) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("s3270: %v\n%s", err, out) + } + if os.Getenv("SHOW3270") != "" { + t.Logf("%s", out) + } + return string(out) + } + out := view() + // the buffer's rows: 5 to 10 red blocks, 11 to 16 green (a cell + // 9x12 on s3270: 32 cells by 12 rows is the image's 2:1) + var rows []string + for _, l := range strings.Split(out, "\n") { + if strings.HasPrefix(l, "data: ") { + rows = append(rows, l) + } + } + if len(rows) < 48 { + t.Fatalf("no buffer:\n%s", out) + } + rows = rows[len(rows)-24:] // ReadBuffer's, after Ascii's + blocks := strings.Repeat("3f ", 32) + "SA(42=00)" + for r := 5; r <= 16; r++ { + color := map[bool]string{true: "f2", false: "f4"}[r <= 10] + if !strings.Contains(rows[r], "SA(42="+color+") "+blocks) { + t.Errorf("row %d, not %s blocks: %s", r, color, rows[r]) + } + } + if !strings.Contains(out, "[flag.png, 200x100, 0 KB]") || !strings.Contains(out, "red over green") { + t.Errorf("no caption or body:\n%s", out) + } + + // pictures off: in words alone + u, _ := e.b.Store.UserByName("alice") + if err := e.b.Store.SetPrefs(u.ID, "pictures=off"); err != nil { + t.Fatal(err) + } + out = view() + if strings.Contains(out, "SA(42=f2)") || !strings.Contains(out, "data: [flag.png, 200x100, 0 KB]") { + t.Errorf("pictures off:\n%s", out) + } +} diff --git a/internal/ui3270/frontend.go b/internal/ui3270/frontend.go index 1a9255f..b07c9f9 100644 --- a/internal/ui3270/frontend.go +++ b/internal/ui3270/frontend.go @@ -58,12 +58,39 @@ func (u *ui) Terminal() string { if c := u.dev.Codepage(); c != nil { cp = c.ID() } - return fmt.Sprintf("%s, %dx%d, code page %s", strings.TrimSpace(u.dev.TerminalType()), cols, rows, cp) + pictures := map[string]string{picNone: "off", picVector: "vector graphics", picBlocks: "blocks"}[u.pictureMode()] + return fmt.Sprintf("%s, %dx%d, code page %s, pictures %s", strings.TrimSpace(u.dev.TerminalType()), cols, rows, + cp, pictures) } -func (u *ui) TerminalActions() []view.Action { return nil } -func (u *ui) TerminalAction(string) error { return nil } -func (u *ui) TerminalInfo() error { return u.terminal() } +// TerminalActions: pictures on and off, where the terminal can show them. +func (u *ui) TerminalActions() []view.Action { + off := u.noPictures + u.noPictures = false + can := u.pictureMode() != picNone + u.noPictures = off + if !can { + return nil + } + return []view.Action{{ID: "pictures", Label: "Pictures on/off", Key: 'M', PF: 11, Short: "Pictures"}} +} + +// TerminalAction switches pictures, and keeps it for next time. +func (u *ui) TerminalAction(id string) error { + if id != "pictures" { + return nil + } + u.noPictures = !u.noPictures + return u.n.SetPref("pictures", map[bool]string{true: "off", false: "on"}[u.noPictures]) +} + +// applyPrefs: pictures as the caller left them last time. +func (u *ui) applyPrefs() { + if on, ok := u.n.Prefs().On("pictures"); ok { + u.noPictures = !on + } +} +func (u *ui) TerminalInfo() error { return u.terminal() } // Watch: a 3270 shows a node's screen no more than it shows a door's. func (u *ui) Watch(int) error { diff --git a/internal/ui3270/pictures.go b/internal/ui3270/pictures.go new file mode 100644 index 0000000..d79d3a2 --- /dev/null +++ b/internal/ui3270/pictures.go @@ -0,0 +1,249 @@ +package ui3270 + +// Pictures (an image board's, view.Picture) on a 3270, the best way the +// terminal has: +// +// - vector graphics: the picture as bitmaps in the terminal's own +// colors (16 on IBM Personal Communications), drawn over cells kept +// empty for it: a character, or the cursor, over a picture clears it +// in its cell +// - graphic escape's blocks (▀ ▄ ▌ ▐ █) in the 3270's 7 colors, a cell +// two pixels by two: x3270 and nearly every color 3270 +// +// and in words on the rest. The caller can turn them off on the profile. + +import ( + "image" + "image/color" + "strings" + + "github.com/racingmars/go3270" + "golang.org/x/image/draw" + + "github.com/Neo-Desktop/bbs-sec/internal/view" +) + +// Ways of showing a picture. +const ( + picNone = "" + picVector = "vector" + picBlocks = "blocks" +) + +// placed is a vector picture to draw once its screen is on the terminal. +type placed struct { + sfs [][]byte // Object Pictures +} + +// laidOut is a picture as picture made it, kept for the screen's next +// showing (a message scrolled, say) rather than loaded and dithered again. +type laidOut struct { + p *view.Picture + row, col, rows, cols int + fields go3270.Screen + used int + sfs [][]byte + mode string +} + +// pictureMode is how pictures are shown on the terminal ("": they are not). +func (u *ui) pictureMode() string { + switch { + case u.noPictures: + return picNone + case u.o.Graphics.Vector && u.dev.SupportsVectorGraphics(): + return picVector + case u.dev.SupportsGE() && u.colorTerminal(): + return picBlocks + } + return picNone +} + +// colorTerminal: the terminal shows colors (a 3279, or a Color reply of +// more than the defaults). +func (u *ui) colorTerminal() bool { + if strings.Contains(u.dev.TerminalType(), "3279") { + return true + } + r := u.dev.QueryReply(0x86) + return len(r) >= 4 && r[3] >= 8 // QCODE, flags, NP: the pairs +} + +// cell is the character cell in pels, as the terminal said or a 3279's. +func (u *ui) cell() (int, int) { + if w, h := u.dev.CellSize(); w > 0 && h > 0 { + return w, h + } + return 9, 16 +} + +// picture lays p out with its top left at row, col, in at most rows rows +// and cols columns: the fields to add to the screen (blocks; vector +// pictures are drawn after it, by drawGraphics, over cells left empty) and +// the rows it takes; 0 rows: it is not shown, and its Alt is the caller's +// to say. +func (u *ui) picture(p *view.Picture, row, col, rows, cols int) (go3270.Screen, int) { + mode := u.pictureMode() + if mode == picNone || p == nil || p.Load == nil || rows < 1 || cols < 1 { + return nil, 0 + } + if c := u.laid; c != nil && c.p == p && c.row == row && c.col == col && c.rows == rows && c.cols == cols && c.mode == mode { + if c.sfs != nil { + u.pictures = append(u.pictures, placed{sfs: c.sfs}) + } + return c.fields, c.used + } + fields, used, sfs := u.layOut(mode, p, row, col, rows, cols) + u.laid = &laidOut{p: p, row: row, col: col, rows: rows, cols: cols, fields: fields, used: used, sfs: sfs, mode: mode} + if sfs != nil { + u.pictures = append(u.pictures, placed{sfs: sfs}) + } + return fields, used +} + +// layOut makes p into blocks' fields, or vector graphics' structured +// fields. +func (u *ui) layOut(mode string, p *view.Picture, row, col, rows, cols int) (go3270.Screen, int, [][]byte) { + cw, ch := u.cell() + maxW, maxH := cols*cw, rows*ch + img, err := p.Load(maxW, maxH) + if err != nil || img == nil { + return nil, 0, nil + } + if mode == picBlocks { + // a cell is two block pixels by two, each cw/2 by ch/2 pels: the + // image as many of them as fit, its shape kept + w, h := fitSize(img.Bounds().Dx(), img.Bounds().Dy()*cw/ch, 2*cols, 2*rows) + w, h = w+w%2, h+h%2 + return blockFields(scale(img, w, h), row, col), h / 2, nil + } + // fitted in pels, which are square: the shape it has + w, h := fitSize(img.Bounds().Dx(), img.Bounds().Dy(), maxW, maxH) + used := (h + ch - 1) / ch + bitmaps := go3270.DitherBitmaps(scale(img, w, h), go3270.GraphicColors(u.dev)) + // graphics coordinates: pels, 0,0 the middle of the screen, y upwards + x := col*cw - u.cols*cw/2 + y := u.rows*ch/2 - row*ch + // a screen has one picture: its segments are numbered from 1 + sfs, _, err := go3270.ImagePictures(x, y, go3270.PictureOptions{Mix: go3270.MixOverpaint}, bitmaps...) + if err != nil { + u.b.Log.Printf("node %d: picture: %v", u.n.Num, err) + return nil, 0, nil + } + return nil, used, sfs +} + +// fitSize is w by h made to fit maxW by maxH, its shape kept (never made +// larger). +func fitSize(w, h, maxW, maxH int) (int, int) { + if w <= maxW && h <= maxH { + return max(w, 1), max(h, 1) + } + if w*maxH > h*maxW { + return maxW, max(1, h*maxW/w) + } + return max(1, w*maxH/h), maxH +} + +// scale is img made w by h. +func scale(img image.Image, w, h int) *image.RGBA { + out := image.NewRGBA(image.Rect(0, 0, w, h)) + draw.Draw(out, out.Bounds(), image.Black, image.Point{}, draw.Src) + draw.CatmullRom.Scale(out, out.Bounds(), img, img.Bounds(), draw.Over, nil) + return out +} + +// blockColors are the 3270's colors for blocks. +var blockColors = []struct { + c go3270.Color + rgb color.RGBA +}{ + {go3270.Blue, color.RGBA{0, 0, 255, 255}}, {go3270.Red, color.RGBA{255, 0, 0, 255}}, + {go3270.Pink, color.RGBA{255, 0, 255, 255}}, {go3270.Green, color.RGBA{0, 255, 0, 255}}, + {go3270.Turquoise, color.RGBA{0, 255, 255, 255}}, {go3270.Yellow, color.RGBA{255, 255, 0, 255}}, + {go3270.White, color.RGBA{255, 255, 255, 255}}, +} + +// blocks are graphic escape's blocks by the quarters of the cell they +// fill: top left, top right, bottom left, bottom right. +var blocks = []struct { + ch string + on [4]bool +}{ + {"█", [4]bool{true, true, true, true}}, {"▀", [4]bool{true, true, false, false}}, + {"▄", [4]bool{false, false, true, true}}, {"▌", [4]bool{true, false, true, false}}, + {"▐", [4]bool{false, true, false, true}}, +} + +// blockFields draws img, two pixels a cell each way, in blocks from row, +// col: a cell is one color, or black, so each takes the color and the +// block nearest its four pixels. Runs of a color are one Set Attribute. +func blockFields(img *image.RGBA, row, col int) go3270.Screen { + dist := func(a color.RGBA, b color.RGBA) int { + dr, dg, db := int(a.R)-int(b.R), int(a.G)-int(b.G), int(a.B)-int(b.B) + return 2*dr*dr + 4*dg*dg + 3*db*db + } + black := color.RGBA{0, 0, 0, 255} + var scr go3270.Screen + cells := img.Bounds().Dx() / 2 + for r := 0; r < img.Bounds().Dy()/2; r++ { + var run strings.Builder + var runColor go3270.Color + runAt := 0 + flush := func(at int) { + if run.Len() > 0 { + scr = append(scr, go3270.Field{Row: row + r, Col: col + runAt, AttributeOnly: true, + Color: runColor, Content: run.String()}) + } + run.Reset() + runAt = at + } + for c := 0; c < cells; c++ { + q := [4]color.RGBA{img.RGBAAt(2*c, 2*r), img.RGBAAt(2*c+1, 2*r), img.RGBAAt(2*c, 2*r+1), img.RGBAAt(2*c+1, 2*r+1)} + best, bestColor, bestD := " ", runColor, 0 + for _, s := range q { + bestD += dist(s, black) + } + for _, bc := range blockColors { + for _, b := range blocks { + d := 0 + for i, s := range q { + if b.on[i] { + d += dist(s, bc.rgb) + } else { + d += dist(s, black) + } + } + if d < bestD { + best, bestColor, bestD = b.ch, bc.c, d + } + } + } + if best != " " && bestColor != runColor { + flush(c) + runColor = bestColor + } + if run.Len() == 0 { + runAt = c + } + run.WriteString(best) + } + flush(0) + } + return scr +} + +// drawGraphics draws the screen's vector graphics, the logo and pictures, +// once the screen is on the terminal. +func (u *ui) drawGraphics() error { + if err := u.drawLogo(); err != nil { + return err + } + for _, p := range u.pictures { + if err := go3270.WriteStructuredFields(u.g, p.sfs...); err != nil { + return err + } + u.drawn = true + } + return nil +} diff --git a/internal/ui3270/pictures_test.go b/internal/ui3270/pictures_test.go new file mode 100644 index 0000000..b777912 --- /dev/null +++ b/internal/ui3270/pictures_test.go @@ -0,0 +1,161 @@ +package ui3270 + +import ( + "bytes" + "encoding/hex" + "image" + "image/color" + "net" + "testing" + + "github.com/racingmars/go3270" + + "github.com/Neo-Desktop/bbs-sec/internal/view" +) + +// pcommReplies are IBM Personal Communications' query replies (from the +// QCODE on): those it sends for a Query, then those for the Query List +// asking for the rest of its Summary. +var pcommReplies = [][]string{{ + "810300005000180103a114000188087009100780", "a600000b01000050001800500018", + "86000800f4f1f1f2f2f3f3f4f4f5f5f6f6f7f7", "870400f0f1f1f2f2f4f4", "88000102", "990000", "8400078004", + "85f2400910700000000700000002b900250100f103c301360280ff000000000380ff00000000", "9500001f401f400101", + "80808184858687889599a6a8b0b1b2b3b4b6", +}, { + "a80200f0ffff", "b08002000000fc00", "b10001000000fc00064006400601fffffff0", + "b20009000701010202030304040505060607070808", "b300030290090100030280007fff", + "b4000400ffff00100010000000000000000100ff00000002ff0000000003ffff000000040000ff00000500ffff000006ff00ff000007ffffff00000800000000000900a00000000aff00a000000ba0a00000000c0000a000000d00a0a000000ea000a000000f60606000", + "b6000009100000010000000012010000f0c1c1000009100002b900250000", +}} + +// pcomm is a DevInfo as NegotiateTelnet makes it of PCOMM's answers. +func pcomm(t *testing.T) go3270.DevInfo { + t.Helper() + srv, cli := net.Pipe() + t.Cleanup(func() { srv.Close(); cli.Close() }) + go func() { + buf := make([]byte, 4096) + var got []byte + until := func(want []byte) { + for !bytes.Contains(got, want) { + n, err := cli.Read(buf) + if err != nil { + return + } + got = append(got, buf[:n]...) + } + got = got[bytes.Index(got, want)+len(want):] + } + rec := func(qs []string) []byte { + r := []byte{0x88} + for _, q := range qs { + d, _ := hex.DecodeString(q) + d = append([]byte{0x81}, d...) + r = append(r, byte((len(d)+2)>>8), byte(len(d)+2)) + r = append(r, d...) + } + return append(bytes.ReplaceAll(r, []byte{0xff}, []byte{0xff, 0xff}), 0xff, 0xef) + } + for _, step := range [][2]string{{"fffd18", "fffb18"}, {"fffa1801fff0", "fffa1800" + hex.EncodeToString([]byte("IBM-3278-2-E")) + "fff0"}, + {"fffd19", "fffb19"}, {"fffd00", "fffb00"}, {"fffb19", "fffd19"}, {"fffb00", "fffd00"}} { + w, _ := hex.DecodeString(step[0]) + a, _ := hex.DecodeString(step[1]) + until(w) + cli.Write(a) + } + until([]byte{0x01, 0xff, 0xff, 0x02, 0xff, 0xef}) + cli.Write(rec(pcommReplies[0])) + until([]byte{0x01, 0xff, 0xff, 0x03, 0x00}) + cli.Write(rec(pcommReplies[1])) + for { + if _, err := cli.Read(buf); err != nil { + return + } + } + }() + dev, err := go3270.NegotiateTelnet(srv) + if err != nil { + t.Fatal(err) + } + return dev +} + +// TestVectorPicture: on PCOMM a picture is laid out in pels (its shape +// kept), in PCOMM's own colors, overpainted, its top left at the cell +// asked for; no fields (text would clear it). +func TestVectorPicture(t *testing.T) { + dev := pcomm(t) + u := &ui{dev: dev, rows: 24, cols: 80, o: Options{Graphics: Graphics{Vector: true}}} + if m := u.pictureMode(); m != picVector { + t.Fatalf("mode %q", m) + } + // orange, 400x100: fitted to 78 cells (702 pels) by 4 rows (64): 256x64 + img := image.NewRGBA(image.Rect(0, 0, 400, 100)) + for y := 0; y < 100; y++ { + for x := 0; x < 400; x++ { + img.Set(x, y, color.RGBA{255, 160, 0, 255}) + } + } + p := &view.Picture{Load: func(w, h int) (image.Image, error) { return img, nil }} + fields, used := u.picture(p, 5, 1, 4, 78) + if fields != nil || used != 4 || len(u.pictures) != 1 { + t.Fatalf("fields %v, rows %d, pictures %d", fields, used, len(u.pictures)) + } + sf := u.pictures[0].sfs[0] + seg := sf[19:] + if seg[0] != 0x0c || seg[1] != 0x02 { // Set Mix: overpaint + t.Errorf("mix % x", seg[:2]) + } + // Set Current Position: col 1, 9 pels from the left (-360: -351), row 5 + // (80 pels) down from the top (192); Set Color 10 (orange); 256x64 + want := []byte{0x21, 4, 0xfe, 0xa1, 0x00, 0x70, 0x0a, 10, 0x91, 6, 0, 0, 1, 0, 0, 64} + if !bytes.Equal(seg[2:2+len(want)], want) { + t.Errorf("orders % x, want % x", seg[2:2+len(want)], want) + } + // laid out once: the screen shown again draws it again + u.pictures = nil + if _, used := u.picture(p, 5, 1, 4, 78); used != 4 || len(u.pictures) != 1 { + t.Errorf("again: %d rows, %d pictures", used, len(u.pictures)) + } + // off: none + u.noPictures, u.laid = true, nil + if _, used := u.picture(p, 5, 1, 4, 78); used != 0 { + t.Error("off, and shown") + } +} + +// TestBlockFields: a cell takes the color and the block nearest its four +// pixels; a run of a color is one field. +func TestBlockFields(t *testing.T) { + img := image.NewRGBA(image.Rect(0, 0, 8, 2)) + set := func(x, y int, c color.RGBA) { img.SetRGBA(x, y, c) } + red, blue := color.RGBA{255, 0, 0, 255}, color.RGBA{0, 0, 255, 255} + // cell 0: red top (▀); cell 1: red left (▌); cell 2: black; cell 3: blue full (█) + set(0, 0, red) + set(1, 0, red) + set(2, 0, red) + set(2, 1, red) + for x := 6; x < 8; x++ { + set(x, 0, blue) + set(x, 1, blue) + } + for _, x := range []int{4, 5} { + set(x, 0, color.RGBA{0, 0, 0, 255}) + set(x, 1, color.RGBA{0, 0, 0, 255}) + } + for _, x := range []int{0, 1} { + set(x, 1, color.RGBA{0, 0, 0, 255}) + } + set(3, 0, color.RGBA{0, 0, 0, 255}) + set(3, 1, color.RGBA{0, 0, 0, 255}) + scr := blockFields(img, 7, 2) + if len(scr) != 2 { + t.Fatalf("fields %+v", scr) + } + if f := scr[0]; f.Row != 7 || f.Col != 2 || f.Color != go3270.Red || f.Content != "▀▌ " || !f.AttributeOnly { + t.Errorf("first %+v", f) + } + if f := scr[1]; f.Col != 5 || f.Color != go3270.Blue || f.Content != "█" { + t.Errorf("second %+v", f) + } +} diff --git a/internal/ui3270/ui.go b/internal/ui3270/ui.go index d85151e..7c6065b 100644 --- a/internal/ui3270/ui.go +++ b/internal/ui3270/ui.go @@ -68,10 +68,14 @@ type ui struct { logo *logo // nil: no graphics logo logoAt [2]int // where the vector logo goes on this screen drawn bool // vector graphics are on the screen - chatting bool // in a chat room (its lines are its screen's) - backlog []string // other nodes' lines not shown yet - say string // for the next screen's message line - sayBad bool // and it is of something refused or failed + pictures []placed // vector pictures for this screen + laid *laidOut // the last picture laid out + // noPictures: the caller turned pictures off (pictureMode) + noPictures bool + chatting bool // in a chat room (its lines are its screen's) + backlog []string // other nodes' lines not shown yet + say string // for the next screen's message line + sayBad bool // and it is of something refused or failed } // Run is a caller's session on a 3270, from the logon screen to the @@ -97,6 +101,7 @@ func (u *ui) run() error { if err := u.logon(); err != nil { return err } + u.applyPrefs() err := app.Run(u.b, u.n, u) if errors.Is(err, app.ErrLogoff) { err = errLogoff @@ -114,19 +119,21 @@ func (u *ui) show(scr go3270.Screen, vals map[string]string) (go3270.Response, m break } } - if u.drawn { - // vector graphics stay until the terminal is reset: Erase/Reset, - // to the alternate screen size if that is what go3270 writes to - flag := byte(0) - if u.rows != 24 || u.cols != 80 { - flag = 0x80 - } - if err := go3270.WriteStructuredFields(u.g, []byte{0x03, flag}); err != nil { - return go3270.Response{}, nil, err - } - u.drawn = false - } + // the screen's vector pictures are its own + defer func() { u.pictures = nil }() for { + if u.drawn { + // vector graphics stay until the terminal is reset: Erase/Reset, + // to the alternate screen size if that is what go3270 writes to + flag := byte(0) + if u.rows != 24 || u.cols != 80 { + flag = 0x80 + } + if err := go3270.WriteStructuredFields(u.g, []byte{0x03, flag}); err != nil { + return go3270.Response{}, nil, err + } + u.drawn = false + } u.g.n = 0 d := time.Now().Add(u.b.Conf().IdleTimeout) if !u.deadline.IsZero() && u.deadline.Before(d) { @@ -136,7 +143,7 @@ func (u *ui) show(scr go3270.Screen, vals map[string]string) (go3270.Response, m resp, err := go3270.ShowScreenOpts(scr, vals, u.g, go3270.ScreenOpts{ AltScreen: u.dev, Codepage: u.dev.Codepage(), CursorRow: crow, CursorCol: ccol, - PostSendCallback: func(any) error { return u.drawLogo() }, + PostSendCallback: func(any) error { return u.drawGraphics() }, }) u.g.SetReadDeadline(time.Time{}) if err != nil { diff --git a/internal/ui3270/view.go b/internal/ui3270/view.go index 4558802..6b39668 100644 --- a/internal/ui3270/view.go +++ b/internal/ui3270/view.go @@ -350,17 +350,41 @@ func (u *ui) messageScreen(m *view.Message, keys, msg string, off int) (go3270.S // the body as written: lines of up to 79, the width of the text editor width := min(u.cols-1, bbs.MaxLineLen) lines := bbs.Wrap(m.Body, width) - if m.Picture != nil && m.Picture.Alt != "" { - // a 3270 shows no pictures: what it is, above the body - lines = append([]string{"[" + m.Picture.Alt + "]", ""}, lines...) - } room := u.rows - 7 + if m.Picture != nil { + // the picture, then what it is, above the body: the picture's + // rows are lines of their own, empty (text would clear it) + rows := m.Picture.Rows + if rows <= 0 { + rows = 12 + } + pic, used := u.picture(m.Picture, 5, 1, min(rows, max(room-5, 4)), u.cols-2) + if off == 0 { + scr = append(scr, pic...) + } else { + u.pictures = nil // scrolled past + } + head := make([]string, used) + for i := range head { + head[i] = pictureRow + } + if m.Picture.Alt != "" { + head = append(head, "["+m.Picture.Alt+"]") + } + lines = append(append(head, ""), lines...) + } for i := 0; i < room && off+i < len(lines); i++ { + if lines[off+i] == pictureRow { + continue + } scr = append(scr, u.text(5+i, 0, bbs.Clean(lines[off+i], width), go3270.Green, false)) } return scr, len(lines) } +// pictureRow is a line of a screen that a picture takes. +const pictureRow = "\x00picture" + // field is a field to type in at row, col, width wide: past the end of the // row it goes on in the rows below. The row after it. func (u *ui) field(row, col, width int, name string, hidden bool) ([]go3270.Field, int) { @@ -437,8 +461,17 @@ func (u *ui) Panel(p *view.Panel) (string, error) { scr := u.frame(p.Title, keys, "") row := 2 lines := p.Lines - if p.Picture != nil && p.Picture.Alt != "" { - lines = append([]view.Line{view.T(view.Dim, "["+p.Picture.Alt+"]")}, lines...) + if p.Picture != nil { + rows := p.Picture.Rows + if rows <= 0 { + rows = u.rows - len(p.Lines) - 6 + } + pic, used := u.picture(p.Picture, row, 1, min(max(rows, 4), u.rows-6), u.cols-2) + scr = append(scr, pic...) + row += used + if p.Picture.Alt != "" { + lines = append([]view.Line{view.T(view.Dim, "["+p.Picture.Alt+"]")}, lines...) + } } for _, l := range lines { if row >= u.rows-3 {