From 3538820c9edb6bcee85e9d7b309eba3d2f199d83 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 11 Nov 2026 11:56:30 +0000 Subject: [PATCH] confui: settings picked from what the file and the machine have Most free-text settings of the configuration screens are now lists to pick from, made from what there is: certificates ([acme]'s, and the files other servers use) and the key that goes with one; an address's every-address, this-machine and each-IP forms, marked when another server has it; [dns] answers from the services' IPs; levels by their names; a menu item's actions (the doors, menus, screens, scripts, areas), with Add a menu item; the screens, AKAs, feed groups and areas, the machine's users and groups; and the fixed values of ACME, TLS, outbound mail and the rest, with notes. A list may be open (a value of one's own typed too) or of some at once (by commas). The full-screen list shows notes and checkboxes; a 3270's S and a plain terminal's number open a numbered table; F1 lists the choices. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01B82eRRorB6EaJ9gFhio2Fa --- docs/wiki/Configuration.md | 28 +- internal/confedit/catalog.go | 6 + internal/confui/choices.go | 669 ++++++++++++++++++++++++++++++++ internal/confui/choices_test.go | 195 ++++++++++ internal/confui/confui.go | 18 + internal/confui/confui_test.go | 10 +- internal/confui/fields.go | 70 +++- internal/confui/users.go | 3 + internal/textui/desk_test.go | 7 + internal/textui/sheet.go | 152 ++++++-- internal/ui3270/sheet.go | 18 +- internal/view/sheet.go | 178 ++++++++- 12 files changed, 1308 insertions(+), 46 deletions(-) create mode 100644 internal/confui/choices.go create mode 100644 internal/confui/choices_test.go diff --git a/docs/wiki/Configuration.md b/docs/wiki/Configuration.md index a917555..26b6633 100644 --- a/docs/wiki/Configuration.md +++ b/docs/wiki/Configuration.md @@ -101,7 +101,7 @@ covered in [Running](Running#running-as-a-user-of-its-own). |---|---| | arrows, PgUp, PgDn, Home, End | move (a letter goes to the next line beginning with it) | | Enter | open a menu, change a value (typed in a box that pops up, or picked from a list of its choices), do an action | -| Space | turn a yes/no over, or go to the next choice | +| Space | turn a yes/no over, or go to the next choice (a list's: open it; in a list of some, turn one on or off) | | Esc, left arrow | back a window | | `/`, F12, Alt+letter | the menu bar's pull-down menus (arrows between them, Enter to go) | | F1 or `?` | the whole help for the line (from bbs.conf.sample) | @@ -110,6 +110,32 @@ covered in [Running](Running#running-as-a-user-of-its-own). | `A`, `D` | add one (a listener, a door, a user ...), delete it | | Ctrl-L | draw the screen again | +### Values picked from what there is + +Most settings are picked from a list (marked `↕`) rather than typed, the +list made from what the file and the machine have, a word beside each: + +| Setting | Offered | +|---|---| +| a certificate (`tls_cert`, `cert_file`) | `acme` and each `acme:NAME` (with its names), and the certificate files other servers use | +| its key (`tls_key`, `key_file`) | the key that goes with the certificate chosen (from another server, or beside it on disk), and the others the file names; not asked for with `acme` | +| an address a server listens on | every address, this machine only, and each of this machine's IPs, at the port it has (or the usual one); one another server is on is marked *taken by* | +| `[dns]` `answer` and `*_answer` | the IPs the services listen on, and this machine's | +| `[dns]` `primary`, `backup` | this host's servers, and the well-known public ones | +| `[dns]` `services`, `[feeds]` `catalog`, `[time]` `servers`, `[mx]` `dnsbl`, gopher's and Gemini's `areas` | some of them at once (Space on each) | +| levels (new users', validated users', a user's, `[mrc]` and `[menu]` `require`) | the `[level N]`s, with their names | +| a menu item (Add a menu item on a menu's page) | the BBS's own actions, each door, the other menus, the screens and scripts, the areas, each with a label to begin from | +| `[menu]` `screen` | the display files in `screens_dir` | +| `[link]` `aka` | `[fido]`'s addresses | +| `[feed]` `group`, `area` | the catalogue's groups and the other feeds'; the message areas | +| the user and groups it runs as | this machine's accounts and groups | +| ACME's CA, DNS provider, challenge and key type; the log; TLS modes; outbound mail; and the rest of the settings with a fixed set of values | those values, with what each one does | + +A list whose values are only suggestions ends with *Type another value*, +and on a 3270 the value can always be typed over; F1 lists the choices +with their notes. On a 3270, `S` beside such a line opens the list; on a +terminal without ANSI its number does, a number each to pick. + In a box where a value is typed, the arrows, Home and End move, Ctrl-U clears it, Enter keeps it and Esc leaves the value as it was. The screens are sent a changed cell at a time, so moving the bar costs a modem caller diff --git a/internal/confedit/catalog.go b/internal/confedit/catalog.go index 925c94a..853ff20 100644 --- a/internal/confedit/catalog.go +++ b/internal/confedit/catalog.go @@ -217,6 +217,12 @@ func (x *Key) example(v string) { } // free reports whether a key is one of the sysop's own (a menu item's). +// IsFree is whether key is one of the sysop's own keys of the kind (a +// menu's item, a QWK network's conference), not one the sample names. +func (k *Kind) IsFree(key string) bool { + return k != nil && k.byKey[key] == nil && k.free(key) +} + func (k *Kind) free(key string) bool { switch k.Name { case "menu": diff --git a/internal/confui/choices.go b/internal/confui/choices.go new file mode 100644 index 0000000..98e664f --- /dev/null +++ b/internal/confui/choices.go @@ -0,0 +1,669 @@ +package confui + +import ( + "bufio" + "net" + "os" + "path/filepath" + "slices" + "sort" + "strconv" + "strings" + + "github.com/D-Modem/bbs/internal/certs" + "github.com/D-Modem/bbs/internal/confedit" + "github.com/D-Modem/bbs/internal/dnsd" + "github.com/D-Modem/bbs/internal/feeds" + "github.com/D-Modem/bbs/internal/screens" +) + +// What a key may be, offered from what the file (and the machine) has, +// so that a sysop picks a value rather than typing it: the certificates +// [acme] gets and the files the other servers name, this machine's +// addresses, the access levels, the screens, the feeds' catalogue... + +// offer is the values a key is offered, a note beside each. +type offer struct { + values []string + notes []string + open bool // a value of one's own may be typed too + multi bool // some of them, by commas +} + +// add puts v (with its note) on the offer, once. +func (o *offer) add(v, note string) { + if slices.Contains(o.values, v) { + return + } + o.values = append(o.values, v) + o.notes = append(o.notes, note) +} + +// more are the closed lists (by "kind.key") beside choices: the values +// the BBS takes and no others. "" is the default. +var more = map[string][]string{ + "listen.frontend": {"", "bbs", "compuserve", "marvel"}, + "acme.challenge": {"", "http", "tls-alpn", "dns"}, + "acme.dns_check": {"", "authoritative", "resolvers", "no"}, + "acme.key_type": {"", "ec256", "ec384", "rsa2048", "rsa3072", "rsa4096"}, + "mail.outbound": {"", "direct", "smarthost", "none"}, + "smarthost.tls": {"", "starttls", "implicit", "no"}, + "pop3.tls": {"", "required", "implicit", "optional", "no"}, + "imap.tls": {"", "required", "implicit", "optional", "no"}, + "smtp.tls": {"", "required", "implicit", "optional", "no"}, + "mx.tls": {"", "optional", "required", "implicit", "no"}, + "lmtp.tls": {"", "no", "optional", "required", "implicit"}, + "door.door32_comm": {"", "serial", "telnet", "local"}, + "ircpeer.protocol": {"", "ts6", "hybrid", "p10"}, + "quotes.alpaca_feed": {"", "iex", "sip", "delayed_sip"}, + "ptp.timestamping": {"", "software", "hardware"}, +} + +// notes are words beside some of the closed lists' values. +var notes = map[string]map[string]string{ + "listen.frontend": {"bbs": "the BBS", "compuserve": "CompuServe (CIS)", "marvel": "MSN 1995, dial-in"}, + "acme.challenge": {"http": "a token on port 80", "tls-alpn": "a certificate on port 443", + "dns": "a TXT record (the only one for *.wildcards)"}, + "acme.dns_check": {"authoritative": "the zone's own servers", "resolvers": "dns_resolvers", "no": "just wait dns_wait"}, + "acme.key_type": {"rsa2048": "Windows XP's clients know only RSA"}, + "mail.outbound": {"direct": "to each domain's MX, port 25", "smarthost": "through [smarthost]", + "none": "local mail only"}, + "ptp.timestamping": {"software": "the kernel's stamps", "hardware": "the network card's"}, + "quotes.alpaca_feed": {"iex": "the free plan", "sip": "every exchange (paid)"}, + "ircpeer.protocol": {"ts6": "Solanum, charybdis, ratbox", "hybrid": "ircd-hybrid 8", "p10": "ircu"}, +} + +// suggested are open lists: values most use, others typed. +var suggested = map[string][][2]string{ + "general.log": {{"syslog", "the daemon facility"}, {"stderr", "systemd's journal"}, {"none", ""}, + {"/var/log/bbs/bbs.log", "a file"}}, + "acme.ca": {{"letsencrypt", "Let's Encrypt"}, {"letsencrypt-staging", "for trying it out"}, {"zerossl", "ZeroSSL"}, + {"buypass", "Buypass"}, {"google", "Google Trust Services (needs EAB)"}, {"sslcom", "SSL.com"}}, + "acme.dns": {{"cloudflare", ""}, {"route53", "Amazon"}, {"digitalocean", ""}, {"hetzner", ""}, {"gandiv5", ""}, + {"ovh", ""}, {"namecheap", ""}, {"porkbun", ""}, {"godaddy", ""}, {"desec", ""}, {"duckdns", ""}, + {"pdns", "PowerDNS"}, {"rfc2136", "nsupdate"}, {"acme-dns", ""}, {"httpreq", ""}, + {"exec:/usr/local/bin/dns-hook", "a program of your own"}, {"acmesh:dns_cf", "an acme.sh dnsapi script"}}, + "general.page_command": {{"curl -s -d \"{user} on node {node}: {reason}\" https://ntfy.sh/my-bbs-pages", "ntfy.sh"}}, + "dns.primary": {{"1.1.1.1", "Cloudflare"}, {"8.8.8.8", "Google"}, {"9.9.9.9", "Quad9"}, + {"208.67.222.222", "OpenDNS"}}, + "dns.backup": {{"8.8.8.8", "Google"}, {"1.1.1.1", "Cloudflare"}, {"9.9.9.9", "Quad9"}, + {"208.67.220.220", "OpenDNS"}}, + "listen.socket_mode": {{"0660", "its group"}, {"0666", "anyone on this machine"}, {"0600", "the BBS's user only"}}, + "general.phone_country": {{"US", "North America (+1)"}, {"GB", "the UK"}, {"IE", "Ireland"}, {"AU", "Australia"}, + {"NZ", "New Zealand"}, {"DE", "Germany"}, {"FR", "France"}, {"NL", "the Netherlands"}, {"SE", "Sweden"}, {"JP", "Japan"}}, + "general.geoip_credit_url": {{"https://db-ip.com", "DB-IP"}, {"https://www.maxmind.com", "MaxMind"}}, + "general.geoip_credit": {{"IP geolocation by DB-IP", ""}, {"This product includes GeoLite2 data created by MaxMind", ""}}, +} + +// multiples are lists of some at once. +var multiples = map[string][][2]string{ + "time.servers": {{"nts time.cloudflare.com", "Cloudflare, NTS"}, {"nts nts.netnod.se", "Netnod, NTS"}, + {"nts ptbtime1.ptb.de", "PTB, NTS"}, {"nts time.nist.gov", ""}, {"ntp pool.ntp.org", "the NTP pool"}, + {"ntp time.google.com", "Google (smeared leap seconds)"}}, + "mx.dnsbl": {{"zen.spamhaus.org", "Spamhaus"}, {"bl.spamcop.net", "SpamCop"}, {"b.barracudacentral.org", "Barracuda"}, + {"psbl.surriel.com", "PSBL"}}, +} + +// listening are the kinds whose address keys are where the BBS listens +// (others' are where it calls). +var listening = map[string]bool{ + "listen": true, "ftp": true, "nntp": true, "pop3": true, "imap": true, "smtp": true, "mx": true, "lmtp": true, + "binkp": true, "irc": true, "irclink": true, "oscar": true, "aol": true, "msn": true, "marvel": true, "ymsg": true, + "dns": true, "finger": true, "gopher": true, "gemini": true, "ntp": true, "nts": true, "ptp": true, "http": true, + "acme": true, +} + +// offerFor is what key of s is offered, if anything. +func (e *Editor) offerFor(s confedit.Section, key string) (offer, bool) { + kk := s.Kind + "." + key + var o offer + switch { + case more[kk] != nil: + for _, v := range more[kk] { + o.add(v, notes[kk][v]) + } + case suggested[kk] != nil: + o.open = true + o.add("", "") + for _, v := range suggested[kk] { + o.add(v[0], v[1]) + } + case multiples[kk] != nil: + o.multi, o.open = true, true + for _, v := range multiples[kk] { + o.add(v[0], v[1]) + } + case s.Kind == "menu" && e.cat.Kind("menu").IsFree(key): + o = e.menuItemOffer() + case s.Kind == "qwknet" && e.cat.Kind("qwknet").IsFree(key): + o = e.areaOffer(false) + o.values, o.notes = o.values[1:], o.notes[1:] + case isCertKey(key): + o = e.certOffer(s) + case isKeyKey(key): + o = e.keyOffer(s, key) + case listening[s.Kind] && isAddressKey(key): + o = e.addressOffer(s, key) + case kk == "dns.answer" || kk == "dns.answer6" || s.Kind == "dns" && strings.HasSuffix(key, "_answer"): + o = e.answerOffer(key == "answer6") + case kk == "dns.services": + o.multi, o.open = true, true + for _, n := range dnsd.ServiceNames() { + note := "not set up here" + if e.serviceOn(n) { + note = "set up here" + } + o.add(n, note) + } + case kk == "dns.primary" || kk == "dns.backup": + o.open = true + o.add("", "the host's own servers") + for _, ns := range resolvConf() { + o.add(ns, "this host's") + } + for _, v := range suggested[kk] { + o.add(v[0], v[1]) + } + case kk == "general.new_user_level" || kk == "general.validated_level" || kk == "mrc.require" || kk == "menu.require": + o = e.levelOffer() + case kk == "link.aka": + o.open = true + o.add("", "ours in its zone") + v, _ := e.doc.Get(sec("fido"), "address") + for _, a := range strings.FieldsFunc(v, func(r rune) bool { return r == ',' || r == ' ' }) { + o.add(a, "") + } + case kk == "feeds.catalog": + o.multi, o.open = true, true + o.add("all", "every feed of the catalogue") + for _, g := range catalogGroups() { + o.add(strings.ToLower(g), "the group") + } + for _, c := range feeds.Catalog { + o.add(c.Name, c.Area) + } + case kk == "feed.group": + o.open = true + o.add("", "") + for _, g := range catalogGroups() { + o.add(g, "") + } + for _, f := range e.instances("feed", nil) { + if g, _ := e.doc.Get(f, "group"); g != "" { + o.add(g, "") + } + } + case kk == "feed.area" || kk == "gopher.areas" || kk == "gemini.areas": + o = e.areaOffer(kk != "feed.area") + case kk == "menu.screen": + o = e.screenOffer() + case kk == "quotes.interface" || kk == "ptp.interface": + o.open = true + o.add("", "") + for _, a := range localAddrs() { + o.add(a.iface, "") + } + case kk == "general.user": + o = sysNames("/etc/passwd") + case kk == "general.group" || kk == "listen.socket_group": + o = sysNames("/etc/group") + case kk == "mail.postmaster": + o.open = true + o.add("", "the sysop") + if e.db != nil { + for _, u := range e.db.users { + if u.Sysop { + o.add(u.Name, "a sysop") + } + } + } + default: + return offer{}, false + } + if len(o.values) == 0 || len(o.values) == 1 && o.values[0] == "" { + return offer{}, false + } + return o, true +} + +// isCertKey is whether a key names a certificate. +func isCertKey(key string) bool { return key == "tls_cert" || key == "cert_file" } + +// isKeyKey is whether a key names a certificate's private key. +func isKeyKey(key string) bool { return key == "tls_key" || key == "key_file" } + +// keyOf is the key key of a certificate key ("tls_cert": "tls_key"). +func keyOf(certKey string) string { + if certKey == "tls_cert" { + return "tls_key" + } + return "key_file" +} + +// certOf is the certificate key of a key key. +func certOf(keyKey string) string { + if keyKey == "tls_key" { + return "tls_cert" + } + return "cert_file" +} + +// isAddressKey is whether a key is an address the BBS listens on. +func isAddressKey(key string) bool { + return key == "address" || key == "metrics" || strings.HasSuffix(key, "_address") +} + +// certOffer: the [acme] certificates, and the certificate files other +// sections name. +func (e *Editor) certOffer(s confedit.Section) offer { + o := offer{open: true} + acme := e.doc.Has(sec("acme")) + switch { + case acme && s.Kind != "gemini" && s.Kind != "ymsg": + o.add("", "the [acme] certificate for the name asked") + default: + o.add("", "none") + } + if acme { + d, _ := e.doc.Get(sec("acme"), "domains") + o.add(certs.ACME, noteOr(d, "[acme]'s own")) + } + for _, a := range e.instances("acme", func(x confedit.Section) bool { return x.Name != "" }) { + d, _ := e.doc.Get(a, "domains") + o.add(certs.ACME+":"+a.Name, noteOr(d, "[acme "+a.Name+"]")) + } + for _, f := range e.files(isCertKey) { + o.add(f.value, "as "+f.where) + } + return o +} + +// keyOffer: the key that goes with the certificate chosen (where another +// section has them together), then the other key files named. +func (e *Editor) keyOffer(s confedit.Section, key string) offer { + o := offer{open: true} + o.add("", "") + cert, _ := e.doc.Get(s, certOf(key)) + if cert != "" && !certs.IsACME(cert) { + for _, x := range e.doc.Sections() { + for _, ck := range []string{"tls_cert", "cert_file"} { + if c, _ := e.doc.Get(x, ck); c == cert { + if k, _ := e.doc.Get(x, keyOf(ck)); k != "" { + o.add(k, "goes with "+filepath.Base(cert)) + } + } + } + } + // beside it: name.crt, name.key; cert.pem, key.pem + dir, base := filepath.Dir(cert), filepath.Base(cert) + ext := filepath.Ext(base) + for _, guess := range []string{strings.TrimSuffix(base, ext) + ".key", + strings.Replace(base, "cert", "key", 1), strings.Replace(base, "crt", "key", 1)} { + if guess == base { + continue + } + p := filepath.Join(dir, guess) + if _, err := os.Stat(p); err == nil { + o.add(p, "beside the certificate") + } + } + } + for _, f := range e.files(isKeyKey) { + o.add(f.value, "as "+f.where) + } + return o +} + +// named is a value the file has, and where. +type named struct{ value, where string } + +// files are the values of the keys keep says, in every section, once +// each. +func (e *Editor) files(keep func(string) bool) []named { + var out []named + seen := map[string]bool{} + for _, x := range e.doc.Sections() { + for _, k := range e.doc.Keys(x) { + if !keep(k) { + continue + } + v, _ := e.doc.Get(x, k) + if v == "" || certs.IsACME(v) || seen[v] { + continue + } + seen[v] = true + out = append(out, named{v, x.String()}) + } + } + return out +} + +// noteOr is s, or else if s is "". +func noteOr(s, orElse string) string { + if s == "" { + return orElse + } + return s +} + +// ifAddr is an address of this machine's. +type ifAddr struct { + iface string + ip net.IP +} + +// localAddrs are this machine's interfaces' addresses (a var for the +// tests). +var localAddrs = func() []ifAddr { + var out []ifAddr + ifs, err := net.Interfaces() + if err != nil { + return nil + } + for _, i := range ifs { + if i.Flags&net.FlagUp == 0 { + continue + } + as, _ := i.Addrs() + for _, a := range as { + if n, ok := a.(*net.IPNet); ok && !n.IP.IsLinkLocalUnicast() { + out = append(out, ifAddr{i.Name, n.IP}) + } + } + if len(as) == 0 { + out = append(out, ifAddr{iface: i.Name}) + } + } + return out +} + +// addressOffer: every address, this machine only, each of its addresses +// (at the port it has, or the sample's), and which other section is on +// each already. +func (e *Editor) addressOffer(s confedit.Section, key string) offer { + o := offer{open: true} + cur, _ := e.doc.Get(s, key) + port := "" + if _, p, err := net.SplitHostPort(cur); err == nil { + port = p + } + help := "" + if x := e.cat.Key(s.Kind, key); x != nil { + help = x.Help + for _, ex := range x.Examples { + if port != "" { + break + } + if strings.HasPrefix(ex, "/") { + o.add("", "") + o.add(ex, "a unix socket") + continue + } + if _, p, err := net.SplitHostPort(ex); err == nil { + port = p + } + } + } + if port == "" { + return o + } + used := e.usedAddresses(s, key) + note := func(addr, n string) string { + if who, ok := used[addr]; ok { + return "taken by " + who + } + if _, p, _ := net.SplitHostPort(addr); used[":"+p] != "" && addr != ":"+p { + return "taken by " + used[":"+p] + " (every address)" + } + return n + } + o.add("", "") + o.add(":"+port, note(":"+port, "every address")) + o.add("127.0.0.1:"+port, note("127.0.0.1:"+port, "this machine only")) + for _, a := range localAddrs() { + if a.ip == nil || a.ip.IsLoopback() { + continue + } + addr := net.JoinHostPort(a.ip.String(), port) + o.add(addr, note(addr, a.iface)) + } + if strings.Contains(help, "= none") { + o.add("none", "not on") + } + return o +} + +// usedAddresses are the addresses other keys listen on: address, whose. +func (e *Editor) usedAddresses(s confedit.Section, key string) map[string]string { + out := map[string]string{} + for _, x := range e.doc.Sections() { + if !listening[x.Kind] { + continue + } + for _, k := range e.doc.Keys(x) { + if !isAddressKey(k) || x == s && k == key { + continue + } + if v, _ := e.doc.Get(x, k); v != "" && v != "none" { + if _, ok := out[v]; !ok { + out[v] = x.String() + " " + k + } + } + } + } + return out +} + +// answerOffer: this machine's addresses (IPv6 ones for answer6), and the +// IPs the file's services listen on. +func (e *Editor) answerOffer(v6 bool) offer { + o := offer{open: true} + o.add("", "as each caller reached the BBS") + fits := func(ip net.IP) bool { return ip != nil && (ip.To4() == nil) == v6 && !ip.IsUnspecified() } + for _, x := range e.doc.Sections() { + if !listening[x.Kind] || x.Kind == "dns" { + continue + } + for _, k := range e.doc.Keys(x) { + if !isAddressKey(k) { + continue + } + v, _ := e.doc.Get(x, k) + if h, _, err := net.SplitHostPort(v); err == nil { + if ip := net.ParseIP(h); fits(ip) && !ip.IsLoopback() { + o.add(ip.String(), "["+x.String()+"] "+k) + } + } + } + } + for _, a := range localAddrs() { + if fits(a.ip) && !a.ip.IsLoopback() { + o.add(a.ip.String(), a.iface) + } + } + return o +} + +// serviceOn is whether a service [dns] answers for is set up here. +func (e *Editor) serviceOn(name string) bool { + if name == "compuserve" { + return len(e.instances("listen", e.ofFrontEnd("compuserve"))) > 0 + } + return e.doc.Has(sec(name)) +} + +// resolvConf is the host's name servers (not a local stub's). +func resolvConf() []string { + f, err := os.Open("/etc/resolv.conf") + if err != nil { + return nil + } + defer f.Close() + var out []string + sc := bufio.NewScanner(f) + for sc.Scan() { + fs := strings.Fields(sc.Text()) + if len(fs) >= 2 && fs[0] == "nameserver" { + if ip := net.ParseIP(fs[1]); ip != nil && !ip.IsLoopback() { + out = append(out, fs[1]) + } + } + } + return out +} + +// levelOffer: the [level N]s, their names beside them. +func (e *Editor) levelOffer() offer { + o := offer{open: true} + type lv struct { + n int + name string + } + var ls []lv + for _, s := range e.instances("level", nil) { + n, err := strconv.Atoi(s.Name) + if err != nil { + continue + } + name, _ := e.doc.Get(s, "name") + ls = append(ls, lv{n, name}) + } + if len(ls) == 0 { + return o + } + sort.Slice(ls, func(i, j int) bool { return ls[i].n < ls[j].n }) + o.add("", "") + for _, l := range ls { + o.add(strconv.Itoa(l.n), noteOr(l.name, "[level "+strconv.Itoa(l.n)+"]")) + } + return o +} + +// catalogGroups are the feeds' catalogue's groups, in its order. +func catalogGroups() []string { + var out []string + for _, c := range feeds.Catalog { + if c.Group != "" && !slices.Contains(out, c.Group) { + out = append(out, c.Group) + } + } + return out +} + +// areaOffer: the message areas (when the database has been read); some +// of them at once, for a wildmat, if multi. +func (e *Editor) areaOffer(multi bool) offer { + o := offer{open: true, multi: multi} + if !multi { + o.add("", "its name") + } + if e.db == nil { + if e.dbErr != nil { + return o + } + if _, e.dbErr = e.data(); e.dbErr != nil { + return o + } + } + for _, a := range e.db.areas { + o.add(a.Name, a.Description) + } + return o +} + +// screenOffer: the display files in screens_dir, by name. +func (e *Editor) screenOffer() offer { + o := offer{open: true} + dir, _ := e.doc.Get(sec("general"), "screens_dir") + if dir == "" { + return o + } + ents, err := os.ReadDir(dir) + if err != nil { + return o + } + o.add("", "") + for _, d := range ents { + n := d.Name() + switch ext := filepath.Ext(n); ext { + case ".ans", ".asc", ".txt", ".rip", ".3270", ".seq": + o.add(strings.TrimSuffix(n, ext), "") + } + } + return o +} + +// sysNames are the accounts (or groups) of this machine a BBS would run +// as: the people's (1000 and up), and those named for it. +func sysNames(file string) offer { + o := offer{open: true} + f, err := os.Open(file) + if err != nil { + return o + } + defer f.Close() + o.add("", "") + sc := bufio.NewScanner(f) + for sc.Scan() { + fs := strings.Split(sc.Text(), ":") + if len(fs) < 3 { + continue + } + id, err := strconv.Atoi(fs[2]) + if err != nil { + continue + } + known := strings.Contains(fs[0], "bbs") || fs[0] == "dialout" || fs[0] == "asterisk" || fs[0] == "uucp" + if known || id >= 1000 && id < 65534 { + o.add(fs[0], "") + } + } + return o +} + +// builtins are a menu item's actions of the BBS's own, with a label each. +var builtins = [][2]string{ + {"areas", "Message areas"}, {"mail", "E-mail"}, {"files", "File areas"}, {"doors", "Doors"}, + {"chat", "Chat"}, {"page", "Page the sysop"}, {"who", "Who's online"}, {"users", "User list"}, + {"profile", "Your profile"}, {"info", "System info"}, {"callers", "Last callers"}, {"boards", "Image boards"}, + {"feedback", "Feedback to the sysop"}, {"qwk", "QWK offline mail"}, {"terminal", "Your terminal"}, + {"sysop", "Sysop's menu"}, {"back", "Back"}, {"logoff", "Goodbye"}, +} + +// menuItemOffer: a menu item's actions, each with a label to begin from: +// the BBS's own, then the doors, the other menus, the screens, the scripts +// and the areas the file and the database have. +func (e *Editor) menuItemOffer() offer { + o := offer{open: true} + for _, b := range builtins { + o.add(b[0]+" "+b[1], "") + } + for _, d := range e.instances("door", nil) { + desc, _ := e.doc.Get(d, "description") + o.add("door:"+d.Name+" "+noteOr(desc, d.Name), "a door") + } + for _, m := range e.instances("menu", func(s confedit.Section) bool { return s.Name != "main" }) { + t, _ := e.doc.Get(m, "title") + o.add("menu:"+m.Name+" "+noteOr(screens.StripTags(t), m.Name), "a menu") + } + for _, sc := range e.screenOffer().values { + if sc != "" { + o.add("screen:"+sc+" "+sc, "a screen") + } + } + if dir, _ := e.doc.Get(sec("general"), "scripts_dir"); dir != "" { + if ents, err := os.ReadDir(dir); err == nil { + for _, d := range ents { + if n, ok := strings.CutSuffix(d.Name(), ".js"); ok && n != "logon" { + o.add("script:"+n+" "+n, "a script") + } + } + } + } + if e.db != nil { + for _, a := range e.db.areas { + o.add("area:"+a.Name+" "+a.Name, "an area") + } + } + return o +} diff --git a/internal/confui/choices_test.go b/internal/confui/choices_test.go new file mode 100644 index 0000000..7389077 --- /dev/null +++ b/internal/confui/choices_test.go @@ -0,0 +1,195 @@ +package confui + +import ( + "net" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + bbssec "github.com/D-Modem/bbs" + "github.com/D-Modem/bbs/internal/bbs" + "github.com/D-Modem/bbs/internal/confedit" + "github.com/D-Modem/bbs/internal/view" +) + +// editorOf is an Editor of the file text, not run: its fields to look at. +func editorOf(t *testing.T, text string) *Editor { + t.Helper() + doc, err := confedit.Parse([]byte(text)) + if err != nil { + t.Fatal(err) + } + orig, _ := confedit.Parse([]byte(text)) + return &Editor{UI: &script{t: t}, cat: confedit.NewCatalog(bbssec.Sample), doc: doc, orig: orig} +} + +// fakeAddrs makes this machine's addresses eth0's 192.0.2.10 and loopback's. +func fakeAddrs(t *testing.T) { + was := localAddrs + localAddrs = func() []ifAddr { + return []ifAddr{{"lo", net.ParseIP("127.0.0.1")}, {"eth0", net.ParseIP("192.0.2.10")}} + } + t.Cleanup(func() { localAddrs = was }) +} + +// noteOf is the note beside choice v of it ("" for none; fails if v is no +// choice). +func noteOf(t *testing.T, it item, v string) string { + t.Helper() + i := slices.Index(it.Choices, v) + if i < 0 { + t.Fatalf("%s: no %q in %q", it.Label, v, it.Choices) + } + return it.ChoiceNote(i) +} + +// TestCertificateChoices: a certificate is picked from [acme]'s and the +// files other servers name; its key from the one that goes with it. +func TestCertificateChoices(t *testing.T) { + e := editorOf(t, "[acme]\ndomains = bbs.example.org\n\n[acme mail]\ndomains = mail.example.org\n\n"+ + "[listen telnets]\ntype = telnet\naddress = :992\ntls_cert = /etc/bbs/tn.crt\ntls_key = /etc/bbs/tn.key\n\n"+ + "[irc]\naddress = :6667\ntls_cert = /etc/bbs/tn.crt\n\n[msn]\ntls_cert = acme:mail\n") + cert := e.field(sec("irc"), "tls_cert") + if cert.Kind != view.EntryChoice || !cert.Open { + t.Fatalf("irc tls_cert: kind %v open %v", cert.Kind, cert.Open) + } + if n := noteOf(t, cert, "acme:mail"); n != "mail.example.org" { + t.Errorf("acme:mail's note %q", n) + } + if n := noteOf(t, cert, "/etc/bbs/tn.crt"); !strings.Contains(n, "[listen telnets]") { + t.Errorf("tn.crt's note %q", n) + } + noteOf(t, cert, "acme") + key := e.field(sec("irc"), "tls_key") + if len(key.Choices) < 2 || key.Choices[1] != "/etc/bbs/tn.key" || !strings.Contains(key.ChoiceNote(1), "goes with tn.crt") { + t.Errorf("irc tls_key: %q %q", key.Choices, key.ChoiceNotes) + } + if k := e.field(sec("msn"), "tls_key"); k.Default != "not needed with acme" { + t.Errorf("msn tls_key's default %q", k.Default) + } + // a file of one's own may still be typed + if err := cert.set("/etc/bbs/irc.crt"); err != nil { + t.Error(err) + } +} + +// TestAddressChoices: an address is offered on every address, this +// machine's, and each of its IPs, those other services have marked. +func TestAddressChoices(t *testing.T) { + fakeAddrs(t) + e := editorOf(t, "[ymsg]\nhttps_address = 192.0.2.10:443\n\n[msn]\nhttps_address = :443\n\n[oscar]\naddress = :5190\n") + it := e.field(sec("oscar"), "tls_address") + for _, v := range []string{":443", "127.0.0.1:443", "192.0.2.10:443"} { + noteOf(t, it, v) + } + if n := noteOf(t, it, "192.0.2.10:443"); !strings.Contains(n, "[ymsg] https_address") { + t.Errorf("192.0.2.10:443's note %q", n) + } + if n := noteOf(t, it, ":443"); !strings.Contains(n, "[msn] https_address") { + t.Errorf(":443's note %q", n) + } + // the port it has is kept + it = e.field(sec("oscar"), "address") + noteOf(t, it, "192.0.2.10:5190") + // [dns]'s answers: the services' own IPs, and this machine's + a := e.field(sec("dns"), "msn_answer") + if n := noteOf(t, a, "192.0.2.10"); !strings.Contains(n, "ymsg") { + t.Errorf("answer 192.0.2.10's note %q", n) + } +} + +// TestClosedAndMultiChoices: a closed list takes its values only; a list +// of some takes several, by commas. +func TestClosedAndMultiChoices(t *testing.T) { + e := editorOf(t, "[mail]\ndomain = example.org\n\n[msn]\naddress = :1863\n\n[dns]\naddress = :53\n") + out := e.field(sec("mail"), "outbound") + if out.Kind != view.EntryChoice || out.Open { + t.Fatalf("outbound: kind %v open %v", out.Kind, out.Open) + } + if err := out.set("carrier pigeon"); err == nil { + t.Error("outbound took carrier pigeon") + } + if err := out.set("smarthost"); err != nil { + t.Error(err) + } + svc := e.field(sec("dns"), "services") + if !svc.Multi || noteOf(t, svc, "msn") != "set up here" || noteOf(t, svc, "ymsg") != "not set up here" { + t.Errorf("services: %q %q", svc.Choices, svc.ChoiceNotes) + } + if err := svc.set("msn, oscar"); err != nil { + t.Error(err) + } + if v, _ := e.doc.Get(sec("dns"), "services"); v != "msn, oscar" { + t.Errorf("services = %q", v) + } +} + +// TestLevelChoices: levels are picked from the [level]s, by name. +func TestLevelChoices(t *testing.T) { + e := editorOf(t, "[level 20]\nname = Member\n\n[level 10]\nname = New user\n") + it := e.field(sec("general"), "new_user_level") + if want := []string{"", "10", "20"}; !slices.Equal(it.Choices, want) { + t.Errorf("choices %q, want %q", it.Choices, want) + } + if n := noteOf(t, it, "20"); n != "Member" { + t.Errorf("20's note %q", n) + } + if err := it.set("30"); err != nil { // a level of no [level] of its own + t.Error(err) + } +} + +// TestMenuItems: a menu's item is added by its key, its action picked +// from the BBS's own, the doors and the other menus. +func TestMenuItems(t *testing.T) { + p := filepath.Join(t.TempDir(), "bbs.conf") + os.WriteFile(p, []byte("[general]\nname = Test\n\n[door lord]\ndescription = Legend of the Red Dragon\n\n"+ + "[menu main]\nm = areas Message areas\n\n[menu extras]\ntitle = {cyan}Extras{reset}\n"), 0o600) + ui := &script{t: t, forms: []map[string]string{{"key": "L"}}, steps: []step{ + open("Board configuration"), open("Menus"), open("main"), open("Add a menu item"), + func(t *testing.T, sh *view.Sheet) view.SheetResult { + e := sh.Entries[entry(t, sh, "l")] + if e.Value != "door:lord Legend of the Red Dragon" { + t.Errorf("l = %q", e.Value) + } + if !slices.Contains(e.Choices, "menu:extras Extras") { + t.Errorf("no menu:extras in %q", e.Choices) + } + return save(t, sh) + }, + }} + ui.tables = []func(*view.Table) view.Choice{func(tb *view.Table) view.Choice { + for i, r := range tb.Rows { + if strings.HasPrefix(r.Cells[1], "door:lord") { + return view.Choice{Action: view.Pick, Row: i} + } + } + t.Fatalf("no door:lord in the table") + return view.Choice{} + }} + if err := (&Editor{UI: ui, Tools: bbs.ConfigTools{Path: p}}).Run(); err != nil { + t.Fatal(err) + } + if data, _ := os.ReadFile(p); !strings.Contains(string(data), "l = door:lord Legend of the Red Dragon\n") { + t.Errorf("written:\n%s", data) + } +} + +// TestPickChoice: a list of some is turned on and off by number, Done +// taking it. +func TestPickChoice(t *testing.T) { + ui := &script{t: t} + e := view.Entry{Label: "Servers", Kind: view.EntryChoice, Multi: true, Value: "b, own", + Choices: []string{"a", "b", "c"}} + ui.tables = []func(*view.Table) view.Choice{ + func(*view.Table) view.Choice { return view.Choice{Action: view.Pick, Row: 2} }, // c on + func(*view.Table) view.Choice { return view.Choice{Action: view.Pick, Row: 1} }, // b off + func(*view.Table) view.Choice { return view.Choice{Action: "done"} }, + } + v, ok, err := view.PickChoice(ui, e) + if err != nil || !ok || v != "c, own" { + t.Errorf("%q %v %v", v, ok, err) + } +} diff --git a/internal/confui/confui.go b/internal/confui/confui.go index 58f34d9..13ca0a4 100644 --- a/internal/confui/confui.go +++ b/internal/confui/confui.go @@ -40,6 +40,7 @@ type Editor struct { doc *confedit.Doc db *data // the accounts and areas, as read and as changed (nil: not read yet) + dbErr error // why they could not be read, for the offers not to try again crumbs []string trail []string // the label of the item each page in crumbs was opened by ("": the first, or not by one) via string // the label of the item opening a page now @@ -292,6 +293,23 @@ func (e *Editor) helpOf(it item) error { help = "No help for this." } lines := wrap(help, e.width()) + if it.Kind == view.EntryChoice && len(it.Choices) > 0 { + head := "One of:" + switch { + case it.Multi: + head = "Any of (by commas):" + case it.Open: + head = "For instance (or a value of your own):" + } + lines = append(lines, view.L(""), view.T(view.Bright, head)) + for i, c := range it.Choices { + l := " " + view.ChoiceLabel(c) + if n := it.ChoiceNote(i); n != "" { + l += " " + n + } + lines = append(lines, view.L(l)) + } + } if it.Note != "" { lines = append(lines, view.L(""), view.T(view.Dim, "Takes effect: "+it.Note)) } diff --git a/internal/confui/confui_test.go b/internal/confui/confui_test.go index c9adf3a..dc71cdf 100644 --- a/internal/confui/confui_test.go +++ b/internal/confui/confui_test.go @@ -29,7 +29,8 @@ type script struct { confirms []bool forms []map[string]string said []string - sheets []string // the crumbs of each sheet drawn + sheets []string // the crumbs of each sheet drawn + tables []func(*view.Table) view.Choice // the answers to tables (none left: back) } // Sheet keeps the sheet's crumbs and status and answers with the next step; @@ -57,8 +58,13 @@ func (s *script) Narrow() bool { return false } // Menu goes back. func (s *script) Menu(m *view.Menu) (string, error) { return view.Back, nil } -// Table goes back. +// Table answers with the next of tables, or goes back. func (s *script) Table(t *view.Table) (view.Choice, error) { + if len(s.tables) > 0 { + f := s.tables[0] + s.tables = s.tables[1:] + return f(t), nil + } return view.Choice{Action: view.Back}, nil } diff --git a/internal/confui/fields.go b/internal/confui/fields.go index 38bed42..7a6922d 100644 --- a/internal/confui/fields.go +++ b/internal/confui/fields.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/D-Modem/bbs/internal/bbs" + "github.com/D-Modem/bbs/internal/certs" "github.com/D-Modem/bbs/internal/confedit" "github.com/D-Modem/bbs/internal/forum" "github.com/D-Modem/bbs/internal/vhost" @@ -131,6 +132,13 @@ func (e *Editor) field(s confedit.Section, key string, label ...string) item { } if cs, ok := choices[s.Kind+"."+key]; ok { it.Kind, it.Choices = view.EntryChoice, cs + } else if o, ok := e.offerFor(s, key); ok && it.Kind != view.EntryBool { + it.Kind, it.Choices, it.ChoiceNotes, it.Open, it.Multi = view.EntryChoice, o.values, o.notes, o.open, o.multi + } + if isKeyKey(key) { + if c, _ := e.doc.Get(s, certOf(key)); certs.IsACME(c) { + it.Default = "not needed with acme" + } } if !confedit.Live(s.Kind, key) { it.Note = "restart" @@ -140,8 +148,16 @@ func (e *Editor) field(s confedit.Section, key string, label ...string) item { if it.Kind == view.EntryBool && nv != "" && nv != "yes" && nv != "no" { return fmt.Errorf("%s: yes or no", it.Label) } - if it.Kind == view.EntryChoice && nv != "" && !contains(it.Choices, nv) { - return fmt.Errorf("%s: one of %s", it.Label, strings.Join(it.Choices, ", ")) + if it.Kind == view.EntryChoice && !it.Open && nv != "" { + vals := []string{nv} + if it.Multi { + vals = strings.Split(nv, ",") + } + for _, v := range vals { + if !contains(it.Choices, strings.TrimSpace(v)) { + return fmt.Errorf("%s: one of %s", it.Label, strings.Join(nonEmpty(it.Choices), ", ")) + } + } } old, had := e.doc.Get(s, key) wasMixed := e.refuseMixed() != nil @@ -196,6 +212,17 @@ func isBool(x *confedit.Key) bool { return n > 0 } +// nonEmpty is ss without "". +func nonEmpty(ss []string) []string { + var out []string + for _, s := range ss { + if s != "" { + out = append(out, s) + } + } + return out +} + // contains is whether s is one of ss. func contains(ss []string, s string) bool { for _, x := range ss { @@ -401,6 +428,9 @@ func (e *Editor) instancePage(s confedit.Section, noun string) page { } out := []item{name} out = append(out, e.sectionFields(cur)...) + if k := e.cat.Kind(cur.Kind); k != nil && k.Free != "" { + out = append(out, action(freeNoun[cur.Kind], func() error { return e.addFree(cur) })) + } out = append(out, action("Delete this "+noun, func() error { return e.deleteSection(cur) })) return out }, @@ -412,6 +442,42 @@ func (e *Editor) instancePage(s confedit.Section, noun string) page { }} } +// freeNoun is the Add item for the keys of the sysop's own of a kind. +var freeNoun = map[string]string{"menu": "Add a menu item", "qwknet": "Carry a conference"} + +// addFree adds a key of the sysop's own to s (a menu's item, a QWK +// network's conference): its key asked, then its value picked from what +// there is (or typed). +func (e *Editor) addFree(s confedit.Section) error { + intro, label := "The key callers press: one letter or digit.", "Key" + if s.Kind == "qwknet" { + intro, label = "The hub's conference number.", "Conference" + } + v, ok, err := e.UI.Form(&view.Form{Title: freeNoun[s.Kind], Intro: []view.Line{view.L(intro)}, + Fields: []view.Field{{Name: "key", Label: label, Width: 8}}, Submit: "Next"}) + if err != nil || !ok { + return err + } + key := strings.ToLower(strings.TrimSpace(v["key"])) + if key == "" { + return nil + } + if !e.cat.Kind(s.Kind).IsFree(key) { + e.say(view.Bad, key+": not a "+strings.ToLower(label)+".") + return nil + } + if had, _ := e.doc.Get(s, key); had != "" { + e.say(view.Bad, key+" is there already: "+had+".") + return nil + } + it := e.field(s, key) + val, ok, err := view.PickChoice(e.UI, it.Entry) + if err != nil || !ok || strings.TrimSpace(val) == "" { + return err + } + return it.set(val) +} + // deleteSection takes s out of the file if the sysop says yes, and is then // errClose: its page is gone. func (e *Editor) deleteSection(s confedit.Section) error { diff --git a/internal/confui/users.go b/internal/confui/users.go index a995ae3..587f158 100644 --- a/internal/confui/users.go +++ b/internal/confui/users.go @@ -305,6 +305,9 @@ func (e *Editor) userPage(u *store.User) page { self := e.Who != "" && strings.EqualFold(e.Who, u.Name) level := item{Entry: view.Entry{ID: "level", Kind: view.EntryText, Label: "Level", Value: strconv.Itoa(u.Level), Changed: u.Level != w.Level, Help: "0 to 255: what the [level] at or below it allows."}} + if o := e.levelOffer(); len(o.values) > 1 { + level.Kind, level.Choices, level.ChoiceNotes, level.Open = view.EntryChoice, o.values[1:], o.notes[1:], true + } level.set = func(v string) error { n, err := strconv.Atoi(strings.TrimSpace(v)) if err != nil || n < 0 || n > bbs.MaxLevel { diff --git a/internal/textui/desk_test.go b/internal/textui/desk_test.go index 07ec2bb..9059872 100644 --- a/internal/textui/desk_test.go +++ b/internal/textui/desk_test.go @@ -34,6 +34,10 @@ func sample() *view.Sheet { {ID: "on", Kind: view.EntryBool, Label: "Enabled", Value: "no"}, {ID: "tls", Kind: view.EntryChoice, Label: "TLS", Choices: []string{"no", "optional", "required"}, Value: "no"}, {ID: "aol", Kind: view.EntryMenu, Label: "AOL"}, + {ID: "cert", Kind: view.EntryChoice, Label: "Certificate", Open: true, Choices: []string{"", "acme", "acme:mail"}, + ChoiceNotes: []string{"", "bbs.example.org", "mail.example.org"}}, + {ID: "dnsbl", Kind: view.EntryChoice, Label: "Blocklists", Multi: true, Value: "a.example", + Choices: []string{"a.example", "b.example", "c.example"}}, }, Menus: []view.PullDown{{Label: "File", Items: []view.PullItem{{Label: "Save", Action: view.SheetSave}}}, {Label: "Online", Items: []view.PullItem{{Label: "Online services", Heading: true}, @@ -52,6 +56,9 @@ func TestDeskSheet(t *testing.T) { {"bool", "\x1b[B\r", view.SheetResult{Action: view.SheetSet, Entry: 2, Values: map[string]string{"on": "yes"}}}, {"choice", "\x1b[B\x1b[B\r\x1b[B\x1b[B\r", view.SheetResult{Action: view.SheetSet, Entry: 3, Values: map[string]string{"tls": "required"}}}, {"menu", "A\r", view.SheetResult{Action: view.Pick, Entry: 4}}, + {"open choice", "C\r\x1b[B\x1b[B\r", view.SheetResult{Action: view.SheetSet, Entry: 5, Values: map[string]string{"cert": "acme:mail"}}}, + {"own value", "C\r\x1b[F\r/etc/x.crt\r", view.SheetResult{Action: view.SheetSet, Entry: 5, Values: map[string]string{"cert": "/etc/x.crt"}}}, + {"some of", "Bl\r \x1b[B\x1b[B \r", view.SheetResult{Action: view.SheetSet, Entry: 6, Values: map[string]string{"dnsbl": "c.example"}}}, {"save", "\x1b[21~", view.SheetResult{Action: view.SheetSave, Entry: 1}}, {"pull-down", "/\x1b[C\x1b[B\r", view.SheetResult{Action: view.SheetJump, Entry: 1, Jump: []string{"Online services", "CompuServe"}}}, {"pull-down action", "/\r", view.SheetResult{Action: view.SheetSave, Entry: 1}}, diff --git a/internal/textui/sheet.go b/internal/textui/sheet.go index 0733a4b..06a1206 100644 --- a/internal/textui/sheet.go +++ b/internal/textui/sheet.go @@ -1,6 +1,8 @@ package textui import ( + "slices" + "strconv" "strings" "unicode" @@ -217,7 +219,16 @@ func (s *session) Sheet(sh *view.Sheet) (view.SheetResult, error) { case view.EntryChoice: switch k { case ' ': - return set(e.ID, e.Next()) + if !e.Listed() { + return set(e.ID, e.Next()) + } + v, ok, err := s.choiceBox(w.frame(), e) + if err != nil { + return view.SheetResult{}, err + } + if ok && v != e.Value { + return set(e.ID, v) + } case KeyRight: default: v, ok, err := s.choiceBox(w.frame(), e) @@ -706,6 +717,10 @@ func (s *session) helpBox(scr *screen, e *view.Entry, status, flash string) bool lines := wrapText(capFirst(help), cols-4) more := "" switch { + case e.Kind == view.EntryChoice && e.Multi && len(e.Choices) > 0: + more = "Any of: " + strings.Join(choiceLabels(e.Choices), ", ") + case e.Kind == view.EntryChoice && e.Open && len(e.Choices) > 0: + more = "Enter: pick one of " + strconv.Itoa(len(e.Choices)) + ", or type your own" case e.Kind == view.EntryChoice && len(e.Choices) > 0: more = "One of: " + strings.Join(choiceLabels(e.Choices), ", ") case e.Default != "" && e.Default != "default" && e.Value == "": @@ -1234,27 +1249,64 @@ func (s *session) inputBox(base *screen, e view.Entry) (string, bool, error) { return v, true, nil } -// choiceBox picks one of a choice entry's values from a list over base: -// false if it was given up. +// choiceBox picks an EntryChoice's value from a list over base: its +// choices (with their notes), * by what it is now. A Multi entry's are +// turned on and off with space, Enter taking them; an Open entry's last +// line types a value of its own. func (s *session) choiceBox(base *screen, e view.Entry) (string, bool, error) { - labels := choiceLabels(e.Choices) - cur := 0 + type line struct { + value, label, note string + other bool // the line to type one's own + } + var lines []line now := e.Value - if now == "" { + if now == "" && !e.Multi && !slices.Contains(e.Choices, "") { now = e.Default } - iw := len([]rune(e.Label)) + 6 + picked := map[string]bool{} + for _, p := range e.Picked() { + picked[p] = true + } + if e.Open && !e.Multi && e.Value != "" && !slices.Contains(e.Choices, e.Value) { + lines = append(lines, line{value: e.Value, label: e.Value, note: "as it is now"}) + } for i, c := range e.Choices { - iw = max(iw, len([]rune(labels[i]))+6) - if c == now || c == "" && e.Value == "" { + label := view.ChoiceLabel(c) + if c == "" && e.Default != "" && e.Default != "default" { + label = "(default: " + e.Default + ")" + } + lines = append(lines, line{value: c, label: label, note: e.ChoiceNote(i)}) + } + if e.Open { + lines = append(lines, line{label: "Type another value...", other: true}) + } + cur := 0 + lw0, nw0 := len([]rune(e.Label))+2, 0 + for i, l := range lines { + lw0 = max(lw0, len([]rune(l.label))) + nw0 = max(nw0, len([]rune(l.note))) + if !e.Multi && !l.other && l.value == now { cur = i } } - iw = min(max(iw, 24), s.t.Cols-8) - n := min(len(labels), s.t.Rows-10) + iw := lw0 + 6 + if e.Multi { + iw += 4 + } + if nw0 > 0 { + iw += nw0 + 2 + } + iw = min(max(iw, 28), s.t.Cols-8) + n := min(len(lines), s.t.Rows-10) row, col, bw, bh := s.dlgBox(iw, n+4) n = min(n, bh-6) top := 0 + on := func(l line) bool { + if e.Multi { + return picked[l.value] + } + return !l.other && l.value == now + } for { if cur < top { top = cur @@ -1266,51 +1318,97 @@ func (s *session) choiceBox(base *screen, e view.Entry) (string, bool, error) { scr.box(row, col, bh, bw, boxDouble, dlgFrame, dlgText) scr.shadow(row, col, bh, bw) scr.title(row, col, bw, e.Label, dlgTitle) - scr.put(row+1, col+2, "Values", attr{cYellow, cLightGray}) + head := "Values" + if e.Multi { + head = "Values (any of them)" + } + scr.put(row+1, col+2, head, attr{cYellow, cLightGray}) lw := bw - 4 for r := 0; r < n; r++ { j := top + r - a := attr{cBlack, cCyan} + a, na := attr{cBlack, cCyan}, attr{cBlue, cCyan} if j == cur { - a = attr{cWhite, cGreen} + a, na = attr{cWhite, cGreen}, attr{cLightGray, cGreen} } - l := " " + labels[j] - if e.Choices[j] == now || e.Choices[j] == "" && e.Value == "" { - l += " *" + l := lines[j] + text := " " + switch { + case e.Multi && !l.other && picked[l.value]: + text += "[x] " + case e.Multi && !l.other: + text += "[ ] " + } + text += l.label + if !e.Multi && on(l) { + text += " *" + } + scr.putw(row+2+r, col+2, lw, text, a) + if l.note != "" { + x := len([]rune(text)) + 2 + if col := 1 + lw0 + 4 + map[bool]int{true: 4}[e.Multi]; col+10 < lw { + x = max(x, col) // the notes in a column + } + if x < lw-2 { + scr.put(row+2+r, col+2+x, trunc(l.note, lw-x-1), na) + } } - scr.putw(row+2+r, col+2, lw, l, a) } if top > 0 { scr.put(row+2, col+2+lw-1, "▲", attr{cBlue, cCyan}) } - if top+n < len(labels) { + if top+n < len(lines) { scr.put(row+1+n, col+2+lw-1, "▼", attr{cBlue, cCyan}) } - scr.put(row+bh-2, col+2, trunc("* as it is now", lw), dlgDim) - s.keyBar(scr, [][2]string{{"Enter", "OK"}, {"Esc", "Cancel"}, {"↑↓", "Choose"}}, "") + foot := "* as it is now" + keys := [][2]string{{"Enter", "OK"}, {"Esc", "Cancel"}, {"↑↓", "Choose"}} + if e.Multi { + foot = "Space turns one on or off" + keys = [][2]string{{"Space", "On/off"}, {"Enter", "OK"}, {"Esc", "Cancel"}} + } + scr.put(row+bh-2, col+2, trunc(foot, lw), dlgDim) + s.keyBar(scr, keys, "") s.show(scr) k, _, err := s.key() if err != nil { return "", false, err } switch { + case lines[cur].other && (isEnter(k) || k == ' '): + typed := e + typed.Kind = view.EntryText + v, ok, err := s.inputBox(base, typed) + if err != nil || !ok { + if err != nil { + return "", false, err + } + continue + } + return strings.TrimSpace(v), true, nil + case e.Multi && k == ' ': + if v := lines[cur].value; v == "" { + picked = map[string]bool{} + } else { + picked[v] = !picked[v] + } + case e.Multi && isEnter(k): + return view.JoinPicked(e, picked), true, nil case isEnter(k) || k == ' ': - return e.Choices[cur], true, nil + return lines[cur].value, true, nil case k == 0x1b: return "", false, nil case k == KeyUp: cur = max(cur-1, 0) case k == KeyDown || k == '\t': - cur = min(cur+1, len(labels)-1) + cur = min(cur+1, len(lines)-1) case k == KeyHome || k == KeyPgUp: cur = 0 case k == KeyEnd || k == KeyPgDn: - cur = len(labels) - 1 + cur = len(lines) - 1 default: u := unicode.ToUpper(k) - for d := 1; d <= len(labels); d++ { - j := (cur + d) % len(labels) - if strings.HasPrefix(strings.ToUpper(labels[j]), string(u)) { + for d := 1; d <= len(lines); d++ { + j := (cur + d) % len(lines) + if strings.HasPrefix(strings.ToUpper(lines[j].label), string(u)) { cur = j break } diff --git a/internal/ui3270/sheet.go b/internal/ui3270/sheet.go index d6dda5a..a680c9e 100644 --- a/internal/ui3270/sheet.go +++ b/internal/ui3270/sheet.go @@ -25,7 +25,7 @@ func (u *ui) Sheet(sh *view.Sheet) (view.SheetResult, error) { nw = max(nw, len(e.Note)) } nw = min(nw, u.cols/5) - keys := "S+Enter=Open PF1=Help PF3=Back PF7/8=Page PF9=Quit PF10=Save+exit" + keys := "S+Enter=Open/pick PF1=Help PF3=Back PF7/8=Page PF9=Quit PF10=Save+exit" if k := pfKeys(sh.Keys, " "); k != "" { keys = k + " " + keys } @@ -88,6 +88,12 @@ func (u *ui) Sheet(sh *view.Sheet) (view.SheetResult, error) { scr = append(scr, go3270.Field{Row: row, Col: 2, Autoskip: true}) scr = append(scr, u.text(row, vcol, bbs.Trunc(e.Value, vw-4)+" ...", go3270.White, false)) default: + if e.Listed() { + // S by it: its choices to pick from (or type over the value) + scr = append(scr, go3270.Field{Row: row, Col: 0, Write: true, Name: "s" + id, + Color: go3270.Green, Highlighting: go3270.Underscore}) + scr = append(scr, go3270.Field{Row: row, Col: 2, Autoskip: true}) + } scr = append(scr, go3270.Field{Row: row, Col: vcol, Write: true, Name: "v" + id, Hidden: e.Secret, Color: go3270.Turquoise, Highlighting: go3270.Underscore}) if !e.Secret { @@ -135,6 +141,16 @@ func (u *ui) Sheet(sh *view.Sheet) (view.SheetResult, error) { continue } e := sh.Entries[i] + if e.Listed() { + nv, ok, err := view.PickChoice(u, e) + if err != nil { + return view.SheetResult{}, err + } + if ok && nv != e.Value { + return view.SheetResult{Action: view.SheetSet, Entry: i, Values: map[string]string{e.ID: nv}}, nil + } + break + } if !long[i] { return view.SheetResult{Action: view.Pick, Entry: i}, nil } diff --git a/internal/view/sheet.go b/internal/view/sheet.go index 4a07ce1..1d2f6d0 100644 --- a/internal/view/sheet.go +++ b/internal/view/sheet.go @@ -52,18 +52,27 @@ const ( // Entry is a sheet's line. type Entry struct { - ID string - Kind EntryKind - Label string - Value string // as it is now ("": not set) - Default string // shown, dim, when Value is "" - Choices []string // EntryChoice's - Secret bool // shown as stars, typed unseen - Changed bool // not saved yet: marked - Note string // at the line's end: "restart", "not available yet" - Help string // at the foot while the cursor is on it - Disabled bool // shown, not chosen - Width int // the most a value may be (0: 255) + ID string + Kind EntryKind + Label string + Value string // as it is now ("": not set) + Default string // shown, dim, when Value is "" + Choices []string // EntryChoice's + // ChoiceNotes are a word beside each of Choices, where it helps ("the + // [acme] certificate", "level 20: Member"); shorter than Choices: none + // for the rest + ChoiceNotes []string + // Open is an EntryChoice whose Choices are what the file has to offer, + // a value of one's own typed as well + Open bool + // Multi is an EntryChoice of some of Choices at once, by commas + Multi bool + Secret bool // shown as stars, typed unseen + Changed bool // not saved yet: marked + Note string // at the line's end: "restart", "not available yet" + Help string // at the foot while the cursor is on it + Disabled bool // shown, not chosen + Width int // the most a value may be (0: 255) } // Sheet results' actions beyond Pick and Back, and the keys' own IDs. @@ -130,6 +139,33 @@ func (e Entry) Shown() string { return e.Value } +// ChoiceNote is the word beside the choice i ("" for none). +func (e Entry) ChoiceNote(i int) string { + if i < len(e.ChoiceNotes) { + return e.ChoiceNotes[i] + } + return "" +} + +// Picked is the choices a Multi entry's value has: its comma-separated +// parts, trimmed. +func (e Entry) Picked() []string { + var out []string + for _, p := range strings.Split(e.Value, ",") { + if p = strings.TrimSpace(p); p != "" { + out = append(out, p) + } + } + return out +} + +// Listed is whether an EntryChoice's choices are better picked from a +// list than turned over one at a time: Open or Multi ones, or more than +// four. +func (e Entry) Listed() bool { + return e.Kind == EntryChoice && (e.Open || e.Multi || len(e.Choices) > 4) +} + // Next is the value an EntryBool or EntryChoice turns to. func (e Entry) Next() string { cur := e.Value @@ -230,7 +266,18 @@ func LineSheet(ui UI, s *Sheet) (SheetResult, error) { switch e.Kind { case EntryMenu, EntryAction: return SheetResult{Action: Pick, Entry: i}, nil - case EntryBool, EntryChoice: + case EntryChoice: + if !e.Listed() { + return SheetResult{Action: SheetSet, Entry: i, Values: map[string]string{e.ID: e.Next()}}, nil + } + v, ok, err := PickChoice(ui, e) + if err != nil { + return SheetResult{}, err + } + if ok && v != e.Value { + return SheetResult{Action: SheetSet, Entry: i, Values: map[string]string{e.ID: v}}, nil + } + case EntryBool: return SheetResult{Action: SheetSet, Entry: i, Values: map[string]string{e.ID: e.Next()}}, nil case EntryText: if e.Help != "" { @@ -250,3 +297,108 @@ func LineSheet(ui UI, s *Sheet) (SheetResult, error) { } } } + +// ChoiceLabel is how a choice reads: "" as "(default)". +func ChoiceLabel(c string) string { + if c == "" { + return "(default)" + } + return c +} + +// PickChoice is an EntryChoice's value picked from a table of its choices +// (a number each, its note beside it, * by those it has now): for Multi +// ones a number turns one on or off until Done; for Open ones O types a +// value of one's own. ok false: left as it was. +func PickChoice(ui UI, e Entry) (string, bool, error) { + picked := map[string]bool{} + if e.Multi { + for _, p := range e.Picked() { + picked[p] = true + } + } + for { + t := &Table{Title: e.Label, Pick: "Number", + Columns: []Column{{Title: "", Width: 2}, {Title: "Value", Width: 28}, {Title: "", Width: 0, Wide: true}}} + if e.Help != "" { + t.Note = []Line{T(Dim, e.Help)} + } + if e.Value != "" && (e.Multi || !contains(e.Choices, e.Value)) { + t.Note = append(t.Note, L("Now: "+e.Value)) + } + for i, c := range e.Choices { + on := c == e.Value || c == "" && e.Value == "" + if e.Multi { + on = picked[c] + } + mark := "" + if on { + mark = "*" + } + t.Rows = append(t.Rows, Row{Num: strconv.Itoa(i + 1), Cells: []string{mark, ChoiceLabel(c), e.ChoiceNote(i)}, Hot: on}) + } + if e.Multi { + t.Actions = append(t.Actions, Action{ID: "done", Label: "Done", Key: 'D', PF: 5}) + } + if e.Open { + t.Actions = append(t.Actions, Action{ID: "other", Label: "Other value", Key: 'O', PF: 4}) + } + c, err := ui.Table(t) + if err != nil { + return "", false, err + } + switch c.Action { + case Pick: + if c.Row < 0 || c.Row >= len(e.Choices) { + continue + } + v := e.Choices[c.Row] + if !e.Multi { + return v, true, nil + } + if v == "" { + picked = map[string]bool{} + continue + } + picked[v] = !picked[v] + case "done": + return JoinPicked(e, picked), true, nil + case "other": + f, ok, err := ui.Form(&Form{Title: e.Label, Fields: []Field{{Name: "v", Label: e.Label, + Width: e.Width, Value: e.Value, Edit: true}}, Submit: "Set"}) + if err != nil || !ok { + return "", false, err + } + return strings.TrimSpace(f["v"]), true, nil + default: + return "", false, nil + } + } +} + +// JoinPicked is a Multi entry's value of the choices picked: in the order +// of its Choices, then any of its own it had, by commas. +func JoinPicked(e Entry, picked map[string]bool) string { + var out []string + for _, c := range e.Choices { + if c != "" && picked[c] { + out = append(out, c) + } + } + for _, p := range e.Picked() { + if picked[p] && !contains(e.Choices, p) { + out = append(out, p) + } + } + return strings.Join(out, ", ") +} + +// contains is whether s is one of ss. +func contains(ss []string, s string) bool { + for _, x := range ss { + if x == s { + return true + } + } + return false +}