diff --git a/.github/config-screens.png b/.github/config-screens.png new file mode 100644 index 0000000..c347df2 Binary files /dev/null and b/.github/config-screens.png differ diff --git a/docs/wiki/Configuration.md b/docs/wiki/Configuration.md index 43a303d..2042c6c 100644 --- a/docs/wiki/Configuration.md +++ b/docs/wiki/Configuration.md @@ -62,21 +62,36 @@ password. ## Editing it: the configuration screens -`bbs -config /etc/bbs/bbs.conf config` opens full-screen menus on your +`bbs -config /etc/bbs/bbs.conf config` opens the setup screens on your terminal for editing the file and the accounts, whether or not the BBS is -running. The same menus are in the [sysop tools](Sysop-Tools) (`F`, -Configuration). They are full screen on ANSI terminals, use PF keys on a -3270, and become numbered lines on a terminal with neither. +running. The same screens are in the [sysop tools](Sysop-Tools) (`F`, +Configuration). On an ANSI terminal they look like the BBS setup programs +of the 1990s: a menu bar of pull-down menus, a shaded blue desk, each menu +a window over the one it was opened from, the line's help in a box below, +and values changed in boxes that pop up. They use PF keys on a 3270, and +become numbered lines on a terminal with neither. + +The setup screens: the Online pull-down menu over the main menu | Menu | What is in it | |---|---| | Board configuration | the BBS's name, the sysop's, the location, postal address, dial-in numbers and internet addresses; the banner, message of the day, goodbye, logo; menus and prompts | | System configuration | the user and group it runs as; the database and log; where files are kept and how large they may be; deny lists, the hack log, bans; scheduled events; every section of the file as it is | | Connections and modems | modem lines and every listener; callers at once, logins, time-outs, lock-outs; passwords by modemmenu's auth socket ([Modem callers](Modem-Callers#the-same-password-for-telnet-ssh-and-the-web)); the caller ID country and GeoIP | -| Services | telnet, TN3270, SSH and RLogin listeners; finger, gopher, Gemini, FTP, IRC, news, the web (API, forum, image boards); MRC, FidoNet, QWK networks, doors | +| Internet services | telnet, TN3270, SSH and RLogin listeners; finger, gopher, Gemini, FTP, news, the web (API, forum, image boards) | +| Online services | [AOL](AOL), [CompuServe](CompuServe) (its listeners) and [The Microsoft Network](MSN-Classic) (its TCP host and dial-in listeners) | +| Messengers and chat | [AIM and ICQ](AIM-and-ICQ), [MSN Messenger](MSN-Messenger), [Yahoo! Messenger](Yahoo-Messenger), the [IRC](IRC) server, [IRC network links](IRC-Linking) and their peers, [MRC](MRC) | +| E-mail | [`[mail]`](E-mail), the smarthost, POP3, IMAP, SMTP submission, MX and LMTP | +| Networks and doors | [FidoNet](FidoNet) and binkp, QWK networks, doors | +| Time | the clock and its sources, and the NTP, NTS-KE and PTP servers ([Time](Time)) | | Users and groups | the accounts (level, flags, sysop, locked, a new password; new ones; deleted ones) and the access levels | | Maintenance | disk space; what message areas keep, old messages taken out; the image boards' archive; backups: one now, those made, `[backup]` ([Backups](Backups)) | +The menu bar's pull-down menus (`/`, F12, or Alt and the menu's red +letter) go straight to any of these from anywhere: File (review, check, +save, quit), Setup, Lines, Internet, Online (the online services and the +messengers), Mail, Networks, Time and Help. + System passwords (PAM, LDAP) are checked by modemmenu, which logs callers in and hands them to the BBS (see [Modem callers](Modem-Callers)). Running the BBS as a user of its own (System configuration's Run as user) is @@ -85,13 +100,21 @@ covered in [Running](Running#running-as-a-user-of-its-own). | Key | What it does | |---|---| | arrows, PgUp, PgDn, Home, End | move (a letter goes to the next line beginning with it) | -| Enter | open a menu, change a value (typed on the foot line, Enter to keep it), do an action | +| 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 | -| Esc, left arrow | back | +| 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) | | F9 | quit without saving (after a yes, if anything changed) | | F10 | save and exit | | `A`, `D` | add one (a listener, a door, a user ...), delete it | +| Ctrl-L | draw the screen again | + +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 +a few bytes, and a terminal without UTF-8 gets code page 437's lines and +shading. On a 3270, type `S` beside a menu to open it, type over values and send them with Enter; PF1 is help, PF3 goes back, and PF9 and PF10 work like F9 @@ -99,7 +122,7 @@ and F10. On a terminal without ANSI, type a line's number to open or change it, `S` to save and exit, or `X` to leave without saving. Nothing changes until you save. A changed line is marked `*`, and the -bottom line counts the unsaved changes. The main menu's Review changes +help box counts the unsaved changes. The main menu's Review changes lists them all, and Check the configuration reads the file as the BBS would. diff --git a/docs/wiki/Sysop-Tools.md b/docs/wiki/Sysop-Tools.md index 4b7e0ff..3322d22 100644 --- a/docs/wiki/Sysop-Tools.md +++ b/docs/wiki/Sysop-Tools.md @@ -11,7 +11,7 @@ any terminal, although watching a node needs a text terminal. | statistics | `S` | totals (users, messages, mail, files; logins, posts, pages and failed logins since the start), and calls, new users, posts and uploads for each of the last 14 days, as bars | | hack log and bans | `H` | the addresses banned now (a number lifts its ban), and `L` the [hack log](Security#keeping-callers-out)'s last 100 lines | | scheduled events | `E` | the events, when they run next and how their last run went; one's command and output, and `R` runs it now | -| configuration | `F` | the configuration menus: the board, the system, connections, services, users and groups, maintenance; nothing changes until F10 saves (F9 quits), and then what may change while callers are on is put in force at once ([Configuration](Configuration#editing-it-the-configuration-screens)). Shown when the BBS runs with `-config` | +| configuration | `F` | the setup screens (blue windows and pull-down menus on ANSI terminals): the board, the system, connections, internet and online services, messengers, e-mail, networks, time, users and groups, maintenance; nothing changes until F10 saves (F9 quits), and then what may change while callers are on is put in force at once ([Configuration](Configuration#editing-it-the-configuration-screens)). Shown when the BBS runs with `-config` | | available | `A` | whether pages reach you; when not, a caller who pages is told you are not available and may leave you a message | Validating new users stays on the main menu (`V`, when some wait). diff --git a/internal/confui/confui.go b/internal/confui/confui.go index 7ac4aa3..2fe2fa8 100644 --- a/internal/confui/confui.go +++ b/internal/confui/confui.go @@ -41,7 +41,10 @@ type Editor struct { db *data // the accounts and areas, as read and as changed (nil: not read yet) crumbs []string - flash string // a word for the next screen's foot + 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 + jump []string // where a pull-down menu's item goes: labels of items to open from the first page + flash string // a word for the next screen's foot } var ( @@ -53,11 +56,14 @@ var ( // Run shows the screens until the sysop saves or leaves. func (e *Editor) Run() error { e.cat = confedit.NewCatalog(bbssec.Sample) + if se, ok := e.UI.(view.SheetEnder); ok { + defer se.EndSheets() + } if ok, err := e.load(); err != nil || !ok { return err } for { - e.crumbs = nil + e.crumbs, e.trail, e.jump = nil, nil, nil err := e.show(e.mainMenu()) switch { case err == nil || errors.Is(err, errQuit): @@ -121,6 +127,7 @@ func (e *Editor) load() (bool, error) { type item struct { view.Entry open func() error // EntryMenu: another page + sub func() page // and that page, where it is known (for the pull-down menus) set func(v string) error // a value's do func() error // EntryAction help string // the whole help, for F1 (Entry.Help: its first line) @@ -141,12 +148,61 @@ type page struct { // back a page (nil). func (e *Editor) show(p page) error { e.crumbs = append(e.crumbs, p.title) - defer func() { e.crumbs = e.crumbs[:len(e.crumbs)-1] }() + e.trail = append(e.trail, e.via) + e.via = "" + defer func() { + e.crumbs = e.crumbs[:len(e.crumbs)-1] + e.trail = e.trail[:len(e.trail)-1] + }() cursor := 0 for { its := p.items() + if e.jump != nil { + // a pull-down's item: back to where its path and this page's + // meet, then on down it + at := e.trail[1:] + if len(at) > len(e.jump) || !prefix(at, e.jump) { + return nil + } + if len(at) == len(e.jump) { + e.jump = nil + } else { + next, last := e.jump[len(at)], len(at) == len(e.jump)-1 + i := -1 + for j, it := range its { + if it.Label == next && it.Choosable() { + i = j + break + } + } + if i < 0 { + e.jump = nil + } else { + cursor = i + var err error + switch it := its[i]; { + case it.open != nil: + e.via = it.Label + err = it.open() + e.via = "" + case it.do != nil && last: + e.jump = nil + err = it.do() + default: + e.jump = nil + } + if errors.Is(err, errClose) { + return nil + } + if err != nil { + return err + } + continue + } + } + } sh := &view.Sheet{Title: p.title, Crumbs: strings.Join(e.crumbs, " > "), Note: p.note, - Cursor: cursor, Keys: p.keys, Status: e.status()} + Cursor: cursor, Keys: p.keys, Status: e.status(), Menus: e.pullDowns()} for _, it := range its { sh.Entries = append(sh.Entries, it.Entry) } @@ -164,6 +220,11 @@ func (e *Editor) show(p page) error { return errSave case view.SheetQuit: return errQuit + case view.SheetJump: + e.jump = r.Jump + if len(e.jump) == 0 { + e.jump = nil + } case view.SheetHelp: if r.Entry >= 0 && r.Entry < len(its) { err = e.helpOf(its[r.Entry]) @@ -174,7 +235,9 @@ func (e *Editor) show(p page) error { } switch it := its[r.Entry]; { case it.open != nil: + e.via = it.Label err = it.open() + e.via = "" case it.do != nil: err = it.do() } @@ -202,6 +265,19 @@ func (e *Editor) show(p page) error { } } +// prefix is whether a begins b. +func prefix(a, b []string) bool { + if len(a) > len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + // helpOf shows an item's whole help (F1), wrapped to the screen, and when a // change to it takes effect. func (e *Editor) helpOf(it item) error { @@ -358,8 +434,8 @@ func (e *Editor) save() (bool, error) { if len(ch) > 0 { if e.Tools.Reload == nil { lines = append(lines, view.L(""), - view.L("A BBS running puts the green changes in force at a reload (systemctl reload"), - view.L("bbs, or SIGHUP); the yellow ones when it starts again."), view.L("")) + view.L("A BBS running puts the green changes in force at a reload (systemctl reload bbs, or SIGHUP); the yellow ones when it starts again."), + view.L("")) lines = append(lines, e.diffLines(ch)...) } else { applied, restart, err := e.Tools.Reload() diff --git a/internal/confui/confui_test.go b/internal/confui/confui_test.go index 73a15b1..c9adf3a 100644 --- a/internal/confui/confui_test.go +++ b/internal/confui/confui_test.go @@ -13,6 +13,7 @@ import ( bbssec "github.com/D-Modem/bbs" "github.com/D-Modem/bbs/internal/backup" "github.com/D-Modem/bbs/internal/bbs" + "github.com/D-Modem/bbs/internal/confedit" "github.com/D-Modem/bbs/internal/store" "github.com/D-Modem/bbs/internal/view" ) @@ -291,7 +292,7 @@ func TestServices(t *testing.T) { p := writeConf(t) os.WriteFile(p, []byte(file+"\n; finger\n;[finger]\n;address = :79\n"), 0o600) ui := &script{t: t, forms: []map[string]string{{"name": "ssh"}}, steps: []step{ - open("Services"), + open("Internet services"), open("Finger"), expect("Enabled", "no", false, set("Enabled", "yes")), set("online", "no"), back, open("SSH"), key("add"), expect("type", "ssh", true, set("address", ":2222")), back, back, @@ -451,3 +452,87 @@ func TestBackUpNow(t *testing.T) { t.Errorf("written:\n%s", data) } } + +// jump is a step that picks a pull-down menu's item (by the menu's label +// and the item's), checking the sheet has it. +func jump(menu, item string) step { + return func(t *testing.T, sh *view.Sheet) view.SheetResult { + t.Helper() + for _, m := range sh.Menus { + if m.Label != menu { + continue + } + for _, it := range m.Items { + if it.Label == item && !it.Heading { + if it.Action != "" { + return view.SheetResult{Action: it.Action} + } + return view.SheetResult{Action: view.SheetJump, Jump: it.Path} + } + } + } + t.Fatalf("%s: no %s > %s in the menus", sh.Crumbs, menu, item) + return view.SheetResult{} + } +} + +// at is a step that checks the sheet is the one crumbs names, then does +// then. +func at(crumbs string, then step) step { + return func(t *testing.T, sh *view.Sheet) view.SheetResult { + t.Helper() + if sh.Crumbs != crumbs { + t.Fatalf("at %q, not %q", sh.Crumbs, crumbs) + } + return then(t, sh) + } +} + +// TestPullDowns: a pull-down menu's item goes from deep in one menu to a +// page of another, by the pages between; every front end is on a menu. +func TestPullDowns(t *testing.T) { + p := writeConf(t) + ui := &script{t: t, steps: []step{ + open("Internet services"), open("Finger"), + jump("Online", "America Online (AOL)"), + at("Configuration > Online services > America Online (AOL)", set("Enabled", "yes")), + jump("Online", "Yahoo! Messenger"), + at("Configuration > Messengers and chat > Yahoo! Messenger", set("Enabled", "yes")), + jump("Time", "NTP server"), + at("Configuration > Time > NTP server", back), + at("Configuration > Time", back), + at("Configuration", jump("File", "Save and exit F10")), + }} + if err := (&Editor{UI: ui, Tools: bbs.ConfigTools{Path: p}}).Run(); err != nil { + t.Fatal(err) + } + data, _ := os.ReadFile(p) + for _, want := range []string{"[aol]", "[ymsg]"} { + if !strings.Contains(string(data), want) { + t.Errorf("no %q in:\n%s", want, data) + } + } + // every kind of section the sample has is on a menu's page + e := &Editor{UI: ui} + e.cat = confeditCatalog() + e.doc, _ = confeditParse(nil) + e.orig, _ = confeditParse(nil) + var labels []string + for _, m := range e.pullDowns() { + for _, it := range m.Items { + labels = append(labels, it.Label) + } + } + all := strings.Join(labels, "|") + for _, want := range []string{"America Online (AOL)", "CompuServe (CIS)", "The Microsoft Network (MSN 1995)", + "AIM and ICQ (OSCAR)", "MSN Messenger", "Yahoo! Messenger", "IRC server", "IRC network links", "Multi Relay Chat", + "POP3", "IMAP", "Smarthost (send through)", "Gopher", "Gemini", "Finger", "NTP server", "PTP grandmaster", "FidoNet", "Doors"} { + if !strings.Contains("|"+all+"|", "|"+want+"|") { + t.Errorf("no %q in the pull-down menus: %s", want, all) + } + } +} + +func confeditCatalog() *confedit.Catalog { return confedit.NewCatalog(bbssec.Sample) } + +func confeditParse(b []byte) (*confedit.Doc, error) { return confedit.Parse(b) } diff --git a/internal/confui/menus.go b/internal/confui/menus.go index 45315a3..1253ba9 100644 --- a/internal/confui/menus.go +++ b/internal/confui/menus.go @@ -10,31 +10,139 @@ import ( // The menus, by what a sysop looks for. +// The first page's menus, by their labels (the pull-down menus' paths +// name them). +const ( + mBoard = "Board configuration" + mSystem = "System configuration" + mLines = "Connections and modems" + mInternet = "Internet services" + mOnline = "Online services" + mChat = "Messengers and chat" + mMail = "E-mail" + mNetworks = "Networks and doors" + mTime = "Time" + mUsers = "Users and groups" + mMaint = "Maintenance" + mReview = "Review changes" + mCheck = "Check the configuration" +) + // mainMenu is the first page: the menus, then review, check, save and quit. func (e *Editor) mainMenu() page { return page{title: "Configuration", items: func() []item { g := sec("general") name, _ := e.doc.Get(g, "name") n := e.changes() - review := menu("Review changes", fmt.Sprintf("%d not saved", n), e.review) - review.Kind = view.EntryAction - review.do, review.open = e.review, nil + review := action(mReview, e.review) + review.Value = fmt.Sprintf("%d not saved", n) return []item{ - menu("Board configuration", name, func() error { return e.show(e.boardMenu()) }), - menu("System configuration", "", func() error { return e.show(e.systemMenu()) }), - menu("Connections and modems", e.count("listen", nil, "listener"), func() error { return e.show(e.connectionsMenu()) }), - menu("Services", "", func() error { return e.show(e.servicesMenu()) }), - menu("Users and groups", "", func() error { return e.show(e.usersMenu()) }), - menu("Maintenance", "", func() error { return e.show(e.maintenanceMenu()) }), + withHelp(e.submenu(mBoard, name, e.boardMenu), "The BBS's name, sysop and where it is; what callers see; the menus and prompts."), + withHelp(e.submenu(mSystem, "", e.systemMenu), "The database and log, where files are kept, security, the user it runs as, scheduled events, and every section of the file."), + withHelp(e.submenu(mLines, e.count("listen", nil, "listener"), e.connectionsMenu), "Modem lines and listeners (the ports callers come in by), callers' limits, modemmenu's passwords, caller ID."), + heading("What callers reach"), + withHelp(e.submenu(mInternet, "", e.servicesMenu), "Telnet, TN3270, SSH and RLogin for terminals; finger, gopher, Gemini, FTP, news and the web."), + withHelp(e.submenu(mOnline, e.onCount("aol", "marvel"), e.onlineMenu), "The BBS as America Online, CompuServe and The Microsoft Network, for their own 1990s client programs."), + withHelp(e.submenu(mChat, e.onCount("oscar", "msn", "ymsg", "irc", "irclink", "mrc"), e.chatMenu), "AIM and ICQ, MSN Messenger, Yahoo! Messenger, the IRC server and its network links, Multi Relay Chat."), + withHelp(e.submenu(mMail, e.onOff(sec("mail")), e.mailMenu), "Each user's e-mail: the domain, sending (direct or by a smarthost), POP3, IMAP, SMTP, MX and LMTP."), + withHelp(e.submenu(mNetworks, "", e.networksMenu), "FidoNet and binkp, QWK networks, and the doors."), + withHelp(e.submenu(mTime, e.onCount("time", "ntp", "nts", "ptp"), e.timeMenu), "The clock the BBS follows (NTP, NTS, PTP servers) and the time servers it can be."), + heading("Accounts and upkeep"), + withHelp(e.submenu(mUsers, "", e.usersMenu), "User accounts, access levels and flags."), + withHelp(e.submenu(mMaint, "", e.maintenanceMenu), "Disk space, what the message areas keep, backups."), heading(""), review, - action("Check the configuration", e.check), + action(mCheck, e.check), action("Save and exit (F10)", func() error { return errSave }), action("Quit without saving (F9)", func() error { return errQuit }), } }} } +// withHelp is it with its help. +func withHelp(it item, help string) item { + it.Help = help + return it +} + +// submenu is an item that opens the page p makes. +func (e *Editor) submenu(label, value string, p func() page) item { + it := menu(label, value, func() error { return e.show(p()) }) + it.sub = p + return it +} + +// onCount is how many of the sections of kinds the file has, in words. +func (e *Editor) onCount(kinds ...string) string { + n := 0 + for _, k := range kinds { + if e.doc.Has(sec(k)) { + n++ + } + } + if n == 0 { + return "off" + } + return fmt.Sprintf("%d on", n) +} + +// pullDowns are the menu bar's menus: File, then the first page's menus +// gathered under short names, each item a jump to its page. +func (e *Editor) pullDowns() []view.PullDown { + tops := map[string]item{} + for _, it := range e.mainMenu().items() { + tops[it.Label] = it + } + // expand is a first-page menu's own menus, under a heading of it + expand := func(label string, head bool) []view.PullItem { + var out []view.PullItem + top, ok := tops[label] + if !ok || top.sub == nil { + return nil + } + if head { + out = append(out, view.PullItem{Label: label, Heading: true}) + } + for _, it := range top.sub().items() { + switch { + case it.Kind == view.EntryHeading: + if len(out) > 0 && !out[len(out)-1].Heading { + out = append(out, view.PullItem{Label: it.Label, Heading: true}) + } + case it.Kind == view.EntryMenu && !it.Disabled: + out = append(out, view.PullItem{Label: it.Label, Path: []string{label, it.Label}}) + } + } + for len(out) > 0 && out[len(out)-1].Heading { + out = out[:len(out)-1] + } + return out + } + page := func(label string) view.PullItem { return view.PullItem{Label: label, Path: []string{label}} } + pd := func(label string, items ...[]view.PullItem) view.PullDown { + m := view.PullDown{Label: label} + for _, its := range items { + m.Items = append(m.Items, its...) + } + return m + } + one := func(its ...view.PullItem) []view.PullItem { return its } + rule := view.PullItem{Heading: true} + return []view.PullDown{ + pd("File", one(page(mReview), page(mCheck), rule, + view.PullItem{Label: "Save and exit F10", Action: view.SheetSave}, + view.PullItem{Label: "Quit without saving F9", Action: view.SheetQuit})), + pd("Setup", one(page(mBoard), page(mSystem), page(mUsers), page(mMaint), rule, + view.PullItem{Label: "All settings, by section", Path: []string{mSystem, "All settings, by section"}})), + pd("Lines", one(page(mLines), rule), expand(mLines, false)), + pd("Internet", one(page(mInternet), rule), expand(mInternet, false)), + pd("Online", expand(mOnline, true), expand(mChat, true)), + pd("Mail", one(page(mMail), rule), expand(mMail, false)), + pd("Networks", one(page(mNetworks), rule), expand(mNetworks, false)), + pd("Time", one(page(mTime), rule), expand(mTime, false)), + } +} + // count is how many sections of a kind there are, in words. func (e *Editor) count(kind string, keep func(confedit.Section) bool, noun string) string { n := len(e.instances(kind, keep)) @@ -163,21 +271,40 @@ func (e *Editor) onOff(s confedit.Section) string { return "off" } -// servicesMenu is Services: listeners by type, the servers whose section -// turns them on, and the networks and doors. -func (e *Editor) servicesMenu() page { - ofType := func(t string) func(confedit.Section) bool { - return func(s confedit.Section) bool { return listenType(e, s) == t } +// ofType keeps the listeners of a type. +func (e *Editor) ofType(t string) func(confedit.Section) bool { + return func(s confedit.Section) bool { return listenType(e, s) == t } +} + +// ofFrontEnd keeps the listeners that answer as a front end (compuserve, +// marvel). +func (e *Editor) ofFrontEnd(f string) func(confedit.Section) bool { + return func(s confedit.Section) bool { + v, _ := e.doc.Get(s, "frontend") + return v == f } +} + +// single is an item for a section whose being there turns a server on: +// its page has Enabled and its keys. +func (e *Editor) single(label, kind string) item { + it := menu(label, e.onOff(sec(kind)), func() error { return e.show(e.sectionPage(sec(kind), label, true)) }) + if k := e.cat.Kind(kind); k != nil { + it.Help = firstSentence(k.Help) + it.help = k.Help + } + return it +} + +// servicesMenu is Internet services: the terminals' listeners by type, and +// the servers whose section turns them on. +func (e *Editor) servicesMenu() page { listeners := func(label, t, addr string) item { - return menu(label, e.count("listen", ofType(t), "listener"), func() error { - return e.show(e.listeners(ofType(t), label, map[string]string{"type": t, "address": addr})) + return menu(label, e.count("listen", e.ofType(t), "listener"), func() error { + return e.show(e.listeners(e.ofType(t), label, map[string]string{"type": t, "address": addr})) }) } - single := func(label, kind string) item { - return menu(label, e.onOff(sec(kind)), func() error { return e.show(e.sectionPage(sec(kind), label, true)) }) - } - return page{title: "Services", items: func() []item { + return page{title: mInternet, items: func() []item { return []item{ heading("Callers' terminals"), listeners("Telnet", "telnet", ":23"), @@ -185,15 +312,112 @@ func (e *Editor) servicesMenu() page { listeners("SSH", "ssh", ":22"), listeners("RLogin", "rlogin", "127.0.0.1:513"), heading("Servers"), - single("Finger", "finger"), - single("Gopher", "gopher"), - single("Gemini", "gemini"), - single("FTP", "ftp"), - single("IRC (ircd)", "irc"), + e.single("Finger", "finger"), + e.single("Gopher", "gopher"), + e.single("Gemini", "gemini"), + e.single("FTP", "ftp"), menu("News (NNTP)", e.onOff(sec("nntp")), func() error { return e.show(e.newsPage()) }), menu("Web: API, forum, image boards", e.onOff(sec("http")), func() error { return e.show(e.webPage()) }), - heading("Networks and doors"), - single("Multi Relay Chat", "mrc"), + } + }} +} + +// onlineMenu is Online services: the dial-up services of the 1990s the BBS +// answers as, for their own client programs. +func (e *Editor) onlineMenu() page { + return page{title: mOnline, + note: []view.Line{view.T(view.Dim, "The BBS as the online services, for their own client programs.")}, + items: func() []item { + return []item{ + e.single("America Online (AOL)", "aol"), + menu("CompuServe (CIS)", e.count("listen", e.ofFrontEnd("compuserve"), "listener"), func() error { + return e.show(e.frontEndListeners("CompuServe (CIS)", "compuserve", + "Listeners with frontend = compuserve answer as CompuServe.", + map[string]string{"type": "telnet", "address": ":2324", "frontend": "compuserve"})) + }), + menu("The Microsoft Network (MSN 1995)", e.onOff(sec("marvel")), func() error { return e.show(e.marvelPage()) }), + } + }} +} + +// frontEndListeners is the listeners that answer as a front end, with a +// word on it; added ones get the keys of with. +func (e *Editor) frontEndListeners(title, frontend, note string, with map[string]string) page { + p := e.listeners(e.ofFrontEnd(frontend), title, with) + p.note = []view.Line{view.T(view.Dim, note)} + return p +} + +// marvelPage is MSN Classic: its TCP host, and its dial-in listeners. +func (e *Editor) marvelPage() page { + return page{title: "The Microsoft Network (MSN 1995)", items: func() []item { + out := []item{e.enabled(sec("marvel"), "Over TCP (port 569)")} + out = append(out, e.sectionFields(sec("marvel"))...) + out = append(out, heading("Modem callers"), + menu("Listeners with frontend = marvel", e.count("listen", e.ofFrontEnd("marvel"), "listener"), func() error { + return e.show(e.frontEndListeners("MSN dial-in listeners", "marvel", + "Windows 95's MSN client dialing in comes through these.", + map[string]string{"type": "raw", "address": "127.0.0.1:2325", "frontend": "marvel"})) + })) + return out + }} +} + +// chatMenu is Messengers and chat: the instant messengers, IRC and its +// links, Multi Relay Chat. +func (e *Editor) chatMenu() page { + return page{title: mChat, items: func() []item { + return []item{ + heading("Instant messengers"), + e.single("AIM and ICQ (OSCAR)", "oscar"), + e.single("MSN Messenger", "msn"), + e.single("Yahoo! Messenger", "ymsg"), + heading("IRC"), + e.single("IRC server", "irc"), + menu("IRC network links", e.onOff(sec("irclink")), func() error { return e.show(e.ircLinkPage()) }), + heading("Between BBSes"), + e.single("Multi Relay Chat", "mrc"), + } + }} +} + +// ircLinkPage is IRC server linking: [irclink] and the [ircpeer]s. +func (e *Editor) ircLinkPage() page { + return page{title: "IRC network links", items: func() []item { + out := []item{e.enabled(sec("irclink"), "Linked to a network")} + out = append(out, e.sectionFields(sec("irclink"))...) + out = append(out, heading("Servers linked with"), menu("Peer servers", e.count("ircpeer", nil, "server"), func() error { + return e.show(e.listPage("Peer servers", "ircpeer", "server", nil, func(s confedit.Section) string { + a, _ := e.doc.Get(s, "address") + return a + }, nil)) + })) + return out + }} +} + +// mailMenu is E-mail: [mail], the smarthost, and each mail server. +func (e *Editor) mailMenu() page { + return page{title: mMail, items: func() []item { + out := []item{e.enabled(sec("mail"), "E-mail")} + out = append(out, e.sectionFields(sec("mail"))...) + out = append(out, + heading("Sending"), + e.single("Smarthost (send through)", "smarthost"), + heading("Servers"), + e.single("POP3", "pop3"), + e.single("IMAP", "imap"), + e.single("SMTP submission", "smtp"), + e.single("MX (mail from the internet)", "mx"), + e.single("LMTP (from a mail server)", "lmtp")) + return out + }} +} + +// networksMenu is Networks and doors: FidoNet, QWK, the doors. +func (e *Editor) networksMenu() page { + return page{title: mNetworks, items: func() []item { + return []item{ menu("FidoNet", e.onOff(sec("fido")), func() error { return e.show(e.fidoPage()) }), menu("QWK networks", e.count("qwknet", nil, "network"), func() error { return e.show(e.listPage("QWK networks", "qwknet", "network", nil, func(s confedit.Section) string { @@ -211,6 +435,19 @@ func (e *Editor) servicesMenu() page { }} } +// timeMenu is Time: the clock the BBS follows, and its time servers. +func (e *Editor) timeMenu() page { + return page{title: mTime, items: func() []item { + return []item{ + e.single("Clock and time sources", "time"), + heading("Time servers"), + e.single("NTP server", "ntp"), + e.single("NTS-KE server (secure NTP)", "nts"), + e.single("PTP grandmaster", "ptp"), + } + }} +} + // tn3270Page is TN3270: the 3270 pictures and logo, and the tn3270 key of // each telnet listener. func (e *Editor) tn3270Page() page { diff --git a/internal/server/reload_test.go b/internal/server/reload_test.go index f7e9c31..a29376d 100644 --- a/internal/server/reload_test.go +++ b/internal/server/reload_test.go @@ -133,19 +133,19 @@ func TestConfigScreens(t *testing.T) { saved(t, e, p) } -// TestConfigScreensANSI: on an ANSI terminal, the full screen: the arrow -// keys, Enter to change a value, F10 to save and leave. +// TestConfigScreensANSI: on an ANSI terminal, the setup screens: the arrow +// keys, Enter to change a value in its box, F10 to save and leave. func TestConfigScreensANSI(t *testing.T) { e, p := configEnv(t, "yes") s := ansiLogin(e) s.send("*") s.expect("Configuration") s.send("F") - s.expect("F10 save+exit") + s.expect("Messengers and chat") s.send("\x1b[B\x1b[A\r") // down, up: Board configuration - s.expect("Configuration > Board configuration") + s.expect("Sysop's name") s.send("\r") - s.expect("BBS name: ") + s.expect("Clear") // the box the name is typed in s.send("\x15Renamed BBS\r") s.expect("1 change not saved") s.send("\x1b[21~") // F10 @@ -158,9 +158,9 @@ func TestConfigQuit(t *testing.T) { e, p := configEnv(t, "yes") s := ansiLogin(e) s.send("*F") - s.expect("F10 save+exit") + s.expect("Messengers and chat") s.send("\r\r") - s.expect("BBS name: ") + s.expect("Clear") s.send("\x15Not Saved\r") s.expect("1 change not saved") s.send("\x1b[20~") // F9 diff --git a/internal/textui/desk.go b/internal/textui/desk.go new file mode 100644 index 0000000..f1c0eae --- /dev/null +++ b/internal/textui/desk.go @@ -0,0 +1,297 @@ +package textui + +import ( + "strconv" + "strings" + "unicode/utf8" +) + +// The desk: a full screen drawn in character cells, as the setup programs +// of the 1990s drew theirs (blue windows over a shaded desktop, a menu bar, +// a bar of keys). What is drawn is kept, and only the cells that changed +// are sent, so that a caller at 2400 bit/s is not sent the whole screen for +// a moved bar. + +// The sixteen colors of a PC's text mode: 0-7 as backgrounds too. +const ( + cBlack = iota + cBlue + cGreen + cCyan + cRed + cMagenta + cBrown + cLightGray + cDarkGray + cLightBlue + cLightGreen + cLightCyan + cLightRed + cLightMagenta + cYellow + cWhite +) + +// attr is a cell's colors: foreground (0-15) and background (0-7). +type attr struct{ fg, bg uint8 } + +// cell is a character cell. +type cell struct { + r rune + a attr +} + +// screen is a screen's cells. +type screen struct { + cols, rows int + c []cell +} + +func newScreen(cols, rows int) *screen { + s := &screen{cols: cols, rows: rows, c: make([]cell, cols*rows)} + for i := range s.c { + s.c[i] = cell{' ', attr{cLightGray, cBlack}} + } + return s +} + +// clone is a copy of s. +func (s *screen) clone() *screen { + n := &screen{cols: s.cols, rows: s.rows, c: make([]cell, len(s.c))} + copy(n.c, s.c) + return n +} + +// at is the cell at row and column (from 0), nil off the screen. +func (s *screen) at(row, col int) *cell { + if row < 0 || col < 0 || row >= s.rows || col >= s.cols { + return nil + } + return &s.c[row*s.cols+col] +} + +// put writes str from row, col in a, cut at the screen's edge; how many +// cells it took. +func (s *screen) put(row, col int, str string, a attr) int { + n := 0 + for _, r := range str { + if c := s.at(row, col+n); c != nil { + *c = cell{r, a} + } + n++ + } + return n +} + +// putw writes str in exactly w cells: cut, or padded with spaces. +func (s *screen) putw(row, col, w int, str string, a attr) { + s.put(row, col, fit(str, w), a) +} + +// fill fills a rectangle with r in a. +func (s *screen) fill(row, col, h, w int, r rune, a attr) { + for y := row; y < row+h; y++ { + for x := col; x < col+w; x++ { + if c := s.at(y, x); c != nil { + *c = cell{r, a} + } + } + } +} + +// paint sets the colors of a rectangle, keeping its characters. +func (s *screen) paint(row, col, h, w int, a attr) { + for y := row; y < row+h; y++ { + for x := col; x < col+w; x++ { + if c := s.at(y, x); c != nil { + c.a = a + } + } + } +} + +// boxStyle is a box's lines: corners, sides and the joins of a line +// across it. +type boxStyle struct{ tl, tr, bl, br, h, v, lj, rj rune } + +var ( + boxDouble = boxStyle{'╔', '╗', '╚', '╝', '═', '║', '╟', '╢'} + boxSingle = boxStyle{'┌', '┐', '└', '┘', '─', '│', '├', '┤'} +) + +// box draws a box's frame and fills its inside. +func (s *screen) box(row, col, h, w int, st boxStyle, frame, inside attr) { + s.fill(row+1, col+1, h-2, w-2, ' ', inside) + for x := col + 1; x < col+w-1; x++ { + s.put(row, x, string(st.h), frame) + s.put(row+h-1, x, string(st.h), frame) + } + for y := row + 1; y < row+h-1; y++ { + s.put(y, col, string(st.v), frame) + s.put(y, col+w-1, string(st.v), frame) + } + s.put(row, col, string(st.tl), frame) + s.put(row, col+w-1, string(st.tr), frame) + s.put(row+h-1, col, string(st.bl), frame) + s.put(row+h-1, col+w-1, string(st.br), frame) +} + +// rule draws a line across a box at row, joined to its sides. +func (s *screen) rule(row, col, w int, st boxStyle, a attr) { + s.put(row, col, string(st.lj), a) + for x := col + 1; x < col+w-1; x++ { + s.put(row, x, "─", a) + } + s.put(row, col+w-1, string(st.rj), a) +} + +// title puts a title in a box's top line, centered: "[ Title ]". +func (s *screen) title(row, col, w int, t string, a attr) { + t = " " + trunc(t, w-6) + " " + s.put(row, col+(w-len([]rune(t)))/2, t, a) +} + +// shadow darkens the cells to the right of and below a rectangle, as a +// window's shadow on the desk. +func (s *screen) shadow(row, col, h, w int) { + dark := attr{cDarkGray, cBlack} + s.paint(row+1, col+w, h, 2, dark) + s.paint(row+h, col+2, 1, w, dark) +} + +// render is what turns the terminal's screen, old (nil: unknown), into s: +// each changed run of cells, with its colors. The last cell of the last +// line is left alone (writing it scrolls some terminals). +func (s *screen) render(old *screen, mono bool) string { + var b strings.Builder + if old == nil || old.cols != s.cols || old.rows != s.rows { + b.WriteString("\x1b[0m\x1b[2J") + old = nil + } + cur := attr{255, 255} + for y := 0; y < s.rows; y++ { + last := s.cols + if y == s.rows-1 { + last-- + } + at := -1 // where the cursor is after the last cell written (-1: unknown) + for x := 0; x < last; x++ { + c := s.c[y*s.cols+x] + if old != nil && old.c[y*s.cols+x] == c { + // unchanged: skipped, unless a change follows so near + // that writing the cells costs less than moving + if at != x || !s.changedWithin(old, y, x, last, 8) { + continue + } + } + if at != x { + b.WriteString("\x1b[" + strconv.Itoa(y+1) + ";" + strconv.Itoa(x+1) + "H") + } + if c.a != cur { + b.WriteString(sgr(c.a, mono)) + cur = c.a + } + r := c.r + if r < ' ' || r == 0x7f || !utf8.ValidRune(r) { + r = ' ' + } + b.WriteRune(r) + at = x + 1 + } + } + return b.String() +} + +// changedWithin is whether a cell of row y from x, before last, within n +// of x, differs from old's. +func (s *screen) changedWithin(old *screen, y, x, last, n int) bool { + for i := x; i < min(x+n, last); i++ { + if old.c[y*s.cols+i] != s.c[y*s.cols+i] { + return true + } + } + return false +} + +// sgr is the escape that gives a's colors (in mono: bright as bold, a light +// background as reverse). +func sgr(a attr, mono bool) string { + if mono { + s := "\x1b[0" + if a.fg >= 8 { + s += ";1" + } + if a.bg == cLightGray || a.bg == cCyan || a.bg == cGreen { + s += ";7" + } + return s + "m" + } + ansi := []int{0, 4, 2, 6, 1, 5, 3, 7} // the PC's order to ANSI's + s := "\x1b[0" + if a.fg >= 8 { + s += ";1" + } + return s + ";" + strconv.Itoa(30+ansi[a.fg%8]) + ";" + strconv.Itoa(40+ansi[a.bg%8]) + "m" +} + +// fit is s cut or padded with spaces to exactly w runes. +func fit(s string, w int) string { + if w <= 0 { + return "" + } + r := []rune(s) + if len(r) > w { + return string(r[:w]) + } + return s + strings.Repeat(" ", w-len(r)) +} + +// trunc is s cut to w runes, with "…" where it was cut. +func trunc(s string, w int) string { + r := []rune(s) + if w <= 0 { + return "" + } + if len(r) <= w { + return s + } + if w == 1 { + return string(r[:1]) + } + return string(r[:w-1]) + "…" +} + +// wrapText breaks s into lines of at most w runes, at spaces where it can. +func wrapText(s string, w int) []string { + var out []string + for _, para := range strings.Split(s, "\n") { + words := strings.Fields(para) + if len(words) == 0 { + out = append(out, "") + continue + } + line := "" + for _, wd := range words { + for len([]rune(wd)) > w { + if line != "" { + out = append(out, line) + line = "" + } + r := []rune(wd) + out = append(out, string(r[:w])) + wd = string(r[w:]) + } + switch { + case line == "": + line = wd + case len([]rune(line))+1+len([]rune(wd)) <= w: + line += " " + wd + default: + out = append(out, line) + line = wd + } + } + out = append(out, line) + } + return out +} diff --git a/internal/textui/desk_test.go b/internal/textui/desk_test.go new file mode 100644 index 0000000..07ec2bb --- /dev/null +++ b/internal/textui/desk_test.go @@ -0,0 +1,143 @@ +package textui + +import ( + "bytes" + "strings" + "testing" + "time" + + "github.com/D-Modem/bbs/internal/view" +) + +// keyConn is a terminal whose keys are given and whose output is kept. +type keyConn struct { + in *bytes.Reader + out bytes.Buffer +} + +func (c *keyConn) Read(p []byte) (int, error) { return c.in.Read(p) } +func (c *keyConn) Write(p []byte) (int, error) { return c.out.Write(p) } +func (c *keyConn) SetReadDeadline(time.Time) error { return nil } +func deskTerm(keys string, utf8 bool) (*session, *keyConn) { + c := &keyConn{in: bytes.NewReader([]byte(keys))} + t := NewTerm(c) + t.ANSI, t.UTF8, t.Cols, t.Rows = true, utf8, 80, 25 + return &session{t: t}, c +} + +// sample is a sheet of each kind of entry, with a pull-down menu. +func sample() *view.Sheet { + return &view.Sheet{Title: "Services", Crumbs: "Configuration > Services", + Entries: []view.Entry{ + {ID: "h", Kind: view.EntryHeading, Label: "Servers"}, + {ID: "name", Kind: view.EntryText, Label: "BBS name", Value: "Old", Help: "the name"}, + {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"}, + }, + Menus: []view.PullDown{{Label: "File", Items: []view.PullItem{{Label: "Save", Action: view.SheetSave}}}, + {Label: "Online", Items: []view.PullItem{{Label: "Online services", Heading: true}, + {Label: "America Online", Path: []string{"Online services", "America Online"}}, + {Label: "CompuServe", Path: []string{"Online services", "CompuServe"}}}}}} +} + +// TestDeskSheet: a value typed in its box, a yes/no turned over, a choice +// picked from its list, a menu opened, a pull-down's item. +func TestDeskSheet(t *testing.T) { + for _, c := range []struct { + name, keys string + want view.SheetResult + }{ + {"text", "\r\x15New\r", view.SheetResult{Action: view.SheetSet, Entry: 1, Values: map[string]string{"name": "New"}}}, + {"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}}, + {"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}}, + } { + s, conn := deskTerm(c.keys, true) + r, err := s.Sheet(sample()) + if err != nil { + t.Errorf("%s: %v", c.name, err) + continue + } + if r.Action != c.want.Action || r.Entry != c.want.Entry || len(r.Values) != len(c.want.Values) || + strings.Join(r.Jump, ">") != strings.Join(c.want.Jump, ">") { + t.Errorf("%s: %+v, not %+v", c.name, r, c.want) + } + for k, v := range c.want.Values { + if r.Values[k] != v { + t.Errorf("%s: %s = %q, not %q", c.name, k, r.Values[k], v) + } + } + out := conn.out.String() + for _, want := range []string{"╔", "Services", "░", "nline"} { + if !strings.Contains(out, want) { + t.Errorf("%s: no %q drawn", c.name, want) + } + } + } +} + +// TestDeskCP437: a terminal without UTF-8 gets the lines and shading in +// code page 437, not question marks. +func TestDeskCP437(t *testing.T) { + s, conn := deskTerm("\x1b[21~", false) + if _, err := s.Sheet(sample()); err != nil { + t.Fatal(err) + } + out := conn.out.Bytes() + for _, b := range []byte{0xC9, 0xBB, 0xB0, 0xCD} { // ╔ ╗ ░ ═ + if !bytes.Contains(out, []byte{b}) { + t.Errorf("no %#x", b) + } + } + if !bytes.Contains(out, []byte{0x10}) { // ► + t.Errorf("no ►") + } + if bytes.Contains(bytes.ReplaceAll(out, []byte("\x1b[?25l"), nil), []byte("?")) { + t.Errorf("a ? in %q", out) + } +} + +// TestDeskDialogs: with the desk up, a question and help come up as +// dialogs over it; EndSheets clears it. +func TestDeskDialogs(t *testing.T) { + s, conn := deskTerm("\x1b[21~"+"y"+"\r", true) + if _, err := s.Sheet(sample()); err != nil { + t.Fatal(err) + } + yes, err := s.Confirm("Leave without saving 3 changes?", false) + if err != nil || !yes { + t.Fatalf("confirm: %v %v", yes, err) + } + if err := s.Show("Check", []view.Line{view.T(view.Good, "As the BBS would take it.")}); err != nil { + t.Fatal(err) + } + if !strings.Contains(conn.out.String(), "Confirm") || !strings.Contains(conn.out.String(), "As the BBS would take it.") { + t.Errorf("no dialogs in %q", conn.out.String()) + } + s.EndSheets() + if s.desk != nil || !strings.HasSuffix(conn.out.String(), "\x1b[0m\x1b[2J\x1b[H\x1b[?25h") { + t.Errorf("desk not ended") + } +} + +// TestRender: only what changed is sent again. +func TestRender(t *testing.T) { + a := newScreen(20, 5) + a.put(1, 1, "hello", attr{cYellow, cBlue}) + first := a.render(nil, false) + if !strings.Contains(first, "\x1b[2J") || !strings.Contains(first, "hello") { + t.Errorf("first %q", first) + } + b := a.clone() + b.put(1, 1, "j", attr{cYellow, cBlue}) + if got := b.render(a, false); got != "\x1b[2;2H\x1b[0;1;33;44mj" { + t.Errorf("diff %q", got) + } + if got := b.render(b, false); got != "" { + t.Errorf("no change %q", got) + } +} diff --git a/internal/textui/sheet.go b/internal/textui/sheet.go index 261af87..0733a4b 100644 --- a/internal/textui/sheet.go +++ b/internal/textui/sheet.go @@ -4,148 +4,325 @@ import ( "strings" "unicode" - "github.com/D-Modem/bbs/internal/bbs" + "github.com/D-Modem/bbs/internal/screens" "github.com/D-Modem/bbs/internal/view" ) -// Sheets on ANSI terminals: the whole screen, a bar of where it is at the -// top, the entries in a window the cursor keys move through, the entry's -// help and the keys at the foot. Elsewhere a sheet is view.LineSheet's -// table. +// Sheets on ANSI terminals, as the BBS setup programs of the 1990s drew +// them: a menu bar of pull-down menus at the top, a shaded blue desk, each +// sheet a window over the one it was opened from, the entry's help in a box +// below and the keys on a bar at the foot. Values are changed in boxes +// that pop up over it (a line to type in, a list of choices), and questions +// and help come up in dialogs. The desk stays up between sheets until +// EndSheets. Elsewhere a sheet is view.LineSheet's table. -// Sheet draws a sheet and waits for the caller to do something on it. -func (s *session) Sheet(sh *view.Sheet) (view.SheetResult, error) { +// desk is the full screen kept up between sheets. +type desk struct { + on *screen // what the terminal shows (nil: not known) + stack []under // the sheets under the one up, outermost first + depth int // the one up's: how many sheets it was opened through + last *view.Sheet // the sheet up last, and its cursor + lastAt int // + notify func() []string // the terminal's Notify, put back at the end + flash string // a word for the next foot (Say) +} + +// under is a sheet under the one up: its cursor, and its depth. +type under struct { + sh *view.Sheet + cur int + depth int +} + +// deskOK is whether the terminal can have the desk. +func (s *session) deskOK() bool { t := s.t - if !t.ANSI || t.VT52 || t.PETSCII || t.Rows < 12 || t.Cols < 40 { + return t.ANSI && !t.VT52 && !t.PETSCII && t.Rows >= 14 && t.Cols >= 40 +} + +// startDesk puts the desk up, if it is not. +func (s *session) startDesk() *desk { + if s.desk == nil { + s.desk = &desk{notify: s.t.Notify} + s.t.Notify = nil // what other nodes send waits: it would draw over the desk + } + return s.desk +} + +// EndSheets takes the desk down: the screen cleared, the cursor shown. +func (s *session) EndSheets() { + d := s.desk + if d == nil { + return + } + s.desk = nil + s.t.Notify = d.notify + s.t.Print("\x1b[0m\x1b[2J\x1b[H\x1b[?25h") + s.t.Flush() +} + +// deskBase is what a dialog goes over: the screen as it is. +func (s *session) deskBase() *screen { + if s.desk.on != nil && s.desk.on.cols == s.t.Cols && s.desk.on.rows == s.t.Rows { + return s.desk.on + } + return s.deskScreen(nil, -1) +} + +// show sends what changed between the screen and scr. +func (s *session) show(scr *screen) { + d := s.desk + out := scr.render(d.on, s.t.Mono) + "\x1b[?25l" + t := s.t + switch { + case t.UTF8: + t.Print(out) + case t.xl != nil: // a VT's: the arrows as letters + t.Print(asciiGlyphs.Replace(out)) + default: // code page 437, the arrows its own + t.w.Write(encode437(out)) + } + d.on = scr.clone() + s.t.Flush() +} + +// glyphs code page 437 has in its control range, and an ellipsis for it +var cp437Glyphs = map[rune]byte{'►': 0x10, '◄': 0x11, '↕': 0x12, '↑': 0x18, '↓': 0x19, '→': 0x1a, '←': 0x1b, + '▲': 0x1e, '▼': 0x1f, '…': 0xaf} + +// asciiGlyphs are those for a terminal with neither +var asciiGlyphs = strings.NewReplacer("►", ">", "◄", "<", "↕", "|", "↑", "^", "↓", "v", "→", ">", "←", "<", + "▲", "^", "▼", "v", "…", "~") + +// encode437 is s in code page 437. +func encode437(s string) []byte { + out := make([]byte, 0, len(s)) + for _, r := range s { + if b, ok := cp437Glyphs[r]; ok { + out = append(out, b) + continue + } + out = append(out, screens.EncodeCP437(string(r))...) + } + return out +} + +// key reads a key; alt is true for a letter typed with Alt (Esc and the +// letter at once). +func (s *session) key() (k rune, alt bool, err error) { + t := s.t + k, err = t.EditKey() + if err != nil || k != 0x1b || t.r.Buffered() == 0 { + return k, false, err + } + n, err := t.EditKey() + if err != nil { + return 0, false, err + } + if n < 0x80 && unicode.IsLetter(n) { + return unicode.ToUpper(n), true, nil + } + return 0x1b, false, nil +} + +func isEnter(k rune) bool { return k == '\r' || k == '\n' } + +// Sheet draws a sheet in its window on the desk and waits for the caller to +// do something on it. +func (s *session) Sheet(sh *view.Sheet) (view.SheetResult, error) { + if !s.deskOK() { + s.EndSheets() return view.LineSheet(s, sh) } - notify := t.Notify - t.Notify = nil // what other nodes send waits: it would draw over the sheet - defer func() { - t.Notify = notify - t.Print("\x1b[?25h\x1b[0m\x1b[2J\x1b[H") - t.Flush() - }() - d := &sheetDraw{t: t, sh: sh, cur: -1} - d.cur = d.step(sh.Cursor-1, 1) - if d.cur < 0 { - d.cur = max(sh.Cursor, 0) + d := s.startDesk() + d.place(sh) + w := &sheetWin{s: s, sh: sh, cur: -1} + w.cur = w.step(sh.Cursor-1, 1) + if w.cur < 0 { + w.cur = max(sh.Cursor, 0) + } + res := func(action string) (view.SheetResult, error) { + d.last, d.lastAt = sh, w.cur + return view.SheetResult{Action: action, Entry: w.cur}, nil + } + set := func(id, v string) (view.SheetResult, error) { + r, _ := res(view.SheetSet) + r.Values = map[string]string{id: v} + return r, nil } - d.drawAll() for { - t.Print("\x1b[?25l") // no cursor while moving: the bar shows where - k, err := t.EditKey() + s.show(w.frame()) + k, alt, err := s.key() if err != nil { return view.SheetResult{}, err } - res := func(action string) view.SheetResult { return view.SheetResult{Action: action, Entry: d.cur} } + if alt || k == '/' || k == KeyF1+11 { + i := 0 + if alt { + if i = w.barKey(k); i < 0 { + continue + } + } + r, ok, err := s.pullDown(w, i) + if err != nil { + return view.SheetResult{}, err + } + if ok { + d.last, d.lastAt = sh, w.cur + r.Entry = w.cur + return r, nil + } + continue + } switch { case k == KeyF1 || k == '?': - return res(view.SheetHelp), nil + return res(view.SheetHelp) case k == KeyF1+9: - return res(view.SheetSave), nil + return res(view.SheetSave) case k == KeyF1+8: - return res(view.SheetQuit), nil + return res(view.SheetQuit) case k == 0x1b || k == KeyLeft: - return res(view.Back), nil + return res(view.Back) case k == KeyUp: - d.move(d.step(d.cur, -1)) + w.move(w.step(w.cur, -1)) case k == KeyDown || k == '\t': - d.move(d.step(d.cur, 1)) + w.move(w.step(w.cur, 1)) case k == KeyPgUp: - d.move(d.page(-1)) + w.move(w.page(-1)) case k == KeyPgDn: - d.move(d.page(1)) + w.move(w.page(1)) case k == KeyHome: - d.move(d.step(-1, 1)) + w.move(w.step(-1, 1)) case k == KeyEnd: - d.move(d.step(len(sh.Entries), -1)) - case k == 0x0c: // ^L - d.drawAll() - case k == '\r' || k == ' ' || k == KeyRight: - if d.cur < 0 || d.cur >= len(sh.Entries) { + w.move(w.step(len(sh.Entries), -1)) + case k == 0x0c: // ^L: all of it again + d.on = nil + case isEnter(k) || k == ' ' || k == KeyRight: + if w.cur < 0 || w.cur >= len(sh.Entries) { + continue + } + e := sh.Entries[w.cur] + if e.Disabled { continue } - e := sh.Entries[d.cur] switch e.Kind { case view.EntryMenu, view.EntryAction: if k != ' ' { - return res(view.Pick), nil + return res(view.Pick) } - case view.EntryBool, view.EntryChoice: + case view.EntryBool: if k != KeyRight { - r := res(view.SheetSet) - r.Values = map[string]string{e.ID: e.Next()} - return r, nil + return set(e.ID, e.Next()) + } + case view.EntryChoice: + switch k { + case ' ': + return set(e.ID, e.Next()) + case KeyRight: + default: + 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 view.EntryText: if k == ' ' { continue } - v, ok, err := d.edit(e) + v, ok, err := s.inputBox(w.frame(), e) if err != nil { return view.SheetResult{}, err } - if ok { - r := res(view.SheetSet) - r.Values = map[string]string{e.ID: v} - return r, nil + if ok && v != e.Value { + return set(e.ID, v) } - d.drawAll() } default: if id := action(sh.Keys, k); id != "" { - return res(id), nil + return res(id) } // a letter: the next entry beginning with it - d.move(d.letter(unicode.ToUpper(k))) + w.move(w.letter(unicode.ToUpper(k))) } } } -type sheetDraw struct { - t *Term +// place puts the sheets this one was opened from under it: those its +// crumbs name, as they were last drawn (one jumped through, never drawn, +// leaves a gap). +func (d *desk) place(sh *view.Sheet) { + parts := []string{sh.Title} + if sh.Crumbs != "" { + parts = strings.Split(sh.Crumbs, " > ") + } + names := parts[:len(parts)-1] + var keep []under + for _, u := range d.stack { + if u.depth < len(names) && names[u.depth] == u.sh.Title { + keep = append(keep, u) + } + } + if l := d.last; l != nil && l != sh { + for i := len(names) - 1; i >= 0; i-- { + if names[i] != l.Title { + continue + } + j := 0 + for j < len(keep) && keep[j].depth < i { + j++ + } + if j == len(keep) || keep[j].depth != i { + keep = append(keep[:j], append([]under{{l, d.lastAt, i}}, keep[j:]...)...) + } + break + } + } + d.stack, d.depth = keep, len(names) + d.last = sh +} + +// --- the sheet's window + +type sheetWin struct { + s *session sh *view.Sheet cur int // the entry the cursor is on top int // the first entry shown } -// first is the row where the entries' window begins, below the notes. -func (d *sheetDraw) first() int { return 3 + min(len(d.sh.Note), 3) } - -// height is how many rows the entries' window has, at least 3. -func (d *sheetDraw) height() int { return max(d.t.Rows-3-d.first()+1, 3) } - // step is the next entry the cursor may rest on from i, by dir (-1 if none). -func (d *sheetDraw) step(i, dir int) int { - for j := i + dir; j >= 0 && j < len(d.sh.Entries); j += dir { - if d.sh.Entries[j].Choosable() { +func (w *sheetWin) step(i, dir int) int { + for j := i + dir; j >= 0 && j < len(w.sh.Entries); j += dir { + if w.sh.Entries[j].Choosable() { return j } } - if i >= 0 && i < len(d.sh.Entries) && d.sh.Entries[i].Choosable() { + if i >= 0 && i < len(w.sh.Entries) && w.sh.Entries[i].Choosable() { return i } return -1 } -// page is the entry the cursor goes to a page up (dir -1) or down (1): -// the nearest that may be chosen, -1 if none. -func (d *sheetDraw) page(dir int) int { - j := min(max(d.cur+dir*(d.height()-1), 0), len(d.sh.Entries)-1) - if n := d.step(j-dir, dir); n >= 0 { +// page is the entry the cursor goes to a page up (dir -1) or down (1). +func (w *sheetWin) page(dir int) int { + g := w.s.geom(w.sh, w.s.desk.depth) + j := min(max(w.cur+dir*(g.list-1), 0), len(w.sh.Entries)-1) + if n := w.step(j-dir, dir); n >= 0 { return n } - return d.step(j, -dir) + return w.step(j, -dir) } // letter is the next entry after the cursor, going round, that may be // chosen and begins with r; -1 if none. -func (d *sheetDraw) letter(r rune) int { - n := len(d.sh.Entries) +func (w *sheetWin) letter(r rune) int { + n := len(w.sh.Entries) for k := 1; k <= n; k++ { - j := (d.cur + k) % n - e := d.sh.Entries[j] + j := (w.cur + k) % n + e := w.sh.Entries[j] if e.Choosable() && strings.HasPrefix(strings.ToUpper(e.Label), string(r)) { return j } @@ -153,208 +330,1095 @@ func (d *sheetDraw) letter(r rune) int { return -1 } -// move puts the cursor on entry j, drawing what changed. -func (d *sheetDraw) move(j int) { - if j < 0 || j == d.cur { - return +// move puts the cursor on entry j (none if j < 0). +func (w *sheetWin) move(j int) { + if j >= 0 { + w.cur = j } - old := d.cur - d.cur = j - if d.scroll() { - d.drawEntries() - } else { - d.drawEntry(old) - d.drawEntry(j) - } - d.drawFoot() } -// scroll keeps the cursor's entry in the window; true if the window moved. -func (d *sheetDraw) scroll() bool { - top := d.top - if d.cur < d.top { - d.top = d.cur - // a heading just above comes too - if d.top > 0 && d.sh.Entries[d.top-1].Kind == view.EntryHeading { - d.top-- +// geometry is a window's place: its top row and left column, its height +// and width (from 0, frame and all), the rows of notes and of entries. +type geometry struct{ row, col, h, w, notes, list int } + +// layout is the desk's rows: the first and last a window may use, and +// whether there is a help box. +func (s *session) layout() (first, last int, help bool) { + rows := s.t.Rows + help = rows >= 20 + last = rows - 3 // above the key bar and the window's shadow + if help { + last = rows - 6 // the shadow under the help box + } + return 2, last, help +} + +// geom is where a sheet's window goes at a depth (0: the first sheet). +func (s *session) geom(sh *view.Sheet, depth int) geometry { + cols := s.t.Cols + first, last, _ := s.layout() + lw, vw := 0, 0 + for _, e := range sh.Entries { + if e.Kind == view.EntryHeading { + lw = max(lw, len([]rune(e.Label))+4-12) + continue + } + lw = max(lw, len([]rune(e.Label))) + v := e.Shown() + if e.Note != "" { + v += " " + e.Note + } + vw = max(vw, len([]rune(v))) + } + for _, n := range sh.Note { + vw = max(vw, len([]rune(n.Label+n.Text))-lw-4) + } + maxW := cols - 4 + width := 2 + 2 + lw + 2 + min(max(vw, 12), 40) + 3 + width = max(width, len([]rune(sh.Title))+10, min(46, maxW)) + width = min(width, maxW) + off := min(depth, 5) + g := geometry{w: width, col: 2 + 3*off, row: first + off} + if g.col+g.w+2 > cols { + g.col = max(cols-2-g.w, 0) + } + g.notes = min(len(sh.Note), 3) + if g.notes > 0 { + g.notes++ // the rule under them + } + g.list = max(len(sh.Entries), 1) + room := last - g.row + 1 + if g.h = 2 + g.notes + g.list; g.h > room { + if room < 2+g.notes+5 { // too far down: up as far as needed + g.row = max(first, last+1-(2+g.notes+5)) + room = last - g.row + 1 + } + g.h = min(g.h, room) + g.list = max(g.h-2-g.notes, 1) + } + return g +} + +// colors of a window, as it is up or under another +type winColors struct { + frame, title, label, value, unset, note, mark, info, off, head attr + bar, barValue attr + box boxStyle +} + +var ( + activeWin = winColors{ + frame: attr{cWhite, cBlue}, title: attr{cYellow, cBlue}, label: attr{cWhite, cBlue}, + value: attr{cYellow, cBlue}, unset: attr{cLightGray, cBlue}, note: attr{cCyan, cBlue}, + mark: attr{cLightRed, cBlue}, info: attr{cLightGray, cBlue}, off: attr{cDarkGray, cBlue}, + head: attr{cLightCyan, cBlue}, bar: attr{cWhite, cCyan}, barValue: attr{cYellow, cCyan}, box: boxDouble, + } + inactiveWin = winColors{ + frame: attr{cLightGray, cBlue}, title: attr{cLightGray, cBlue}, label: attr{cLightGray, cBlue}, + value: attr{cLightGray, cBlue}, unset: attr{cLightGray, cBlue}, note: attr{cLightGray, cBlue}, + mark: attr{cLightGray, cBlue}, info: attr{cLightGray, cBlue}, off: attr{cDarkGray, cBlue}, + head: attr{cLightGray, cBlue}, bar: attr{cBlack, cLightGray}, barValue: attr{cBlack, cLightGray}, box: boxSingle, + } +) + +// frame is the whole screen with the sheet up: the desk, the menu bar, +// the windows under it, its own, the help box and the keys. +func (w *sheetWin) frame() *screen { + s, d, sh := w.s, w.s.desk, w.sh + scr := s.deskScreen(sh.Menus, -1) + for _, u := range d.stack { + s.drawWin(scr, u.sh, u.depth, u.cur, nil, inactiveWin) + } + s.drawWin(scr, sh, d.depth, w.cur, &w.top, activeWin) + var e *view.Entry + if w.cur >= 0 && w.cur < len(sh.Entries) { + e = &sh.Entries[w.cur] + } + status, flash := sh.Status, d.flash + d.flash = "" + if s.helpBox(scr, e, status, flash) { + status = "" // on the help box + } else if flash != "" { + status = flash + } + keys := [][2]string{{"F1", "Help"}} + if e != nil { + switch e.Kind { + case view.EntryText, view.EntryChoice, view.EntryBool: + keys = append(keys, [2]string{"Enter", "Change"}) + default: + keys = append(keys, [2]string{"Enter", "Select"}) } } - if d.cur >= d.top+d.height() { - d.top = d.cur - d.height() + 1 + keys = append(keys, [2]string{"Esc", "Back"}) + if len(sh.Menus) > 0 { + keys = append(keys, [2]string{"/", "Menu"}) } - return top != d.top + for _, a := range sh.Keys { + if a.Key != 0 { // a 3270's PF key alone: nothing to press here + keys = append(keys, [2]string{string(a.Key), a.Label}) + } + } + keys = append(keys, [2]string{"F9", "Quit"}, [2]string{"F10", "Save"}) + s.keyBar(scr, keys, status) + return scr } -// drawAll draws the whole sheet: the title bar (the crumbs, if any), up to -// three lines of note, the entries, the foot. -func (d *sheetDraw) drawAll() { - t := d.t - d.scroll() - var w strings.Builder - w.WriteString("\x1b[0m\x1b[2J") - bar := " " + d.sh.Title - if d.sh.Crumbs != "" { - bar = " " + d.sh.Crumbs +// deskScreen is the bare desk: the shading, and the menu bar (open: the +// menu shown pulled down, -1 none). +func (s *session) deskScreen(menus []view.PullDown, open int) *screen { + t := s.t + scr := newScreen(t.Cols, t.Rows) + scr.fill(1, 0, t.Rows-2, t.Cols, '░', attr{cLightGray, cBlue}) + bar := attr{cBlack, cLightGray} + scr.fill(0, 0, 1, t.Cols, ' ', bar) + for i, m := range barMenus(menus) { + a, hot := bar, attr{cRed, cLightGray} + if i == open { + a, hot = attr{cBlack, cGreen}, attr{cRed, cGreen} + } + scr.put(0, m.col-1, " "+m.label+" ", a) + if m.hot >= 0 { + scr.put(0, m.col+m.hot, string([]rune(m.label)[m.hot]), hot) + } } - w.WriteString(at(1, 1) + "\x1b[0;1;37;44m" + bbs.Fit(bbs.Trunc(bar, t.Cols-1), t.Cols-1) + "\x1b[0m") - for i, l := range d.sh.Note { - if i == 3 { + name := " BBS Setup " + if b := s.b; b != nil { + if n := b.Conf().Name; n != "" { + name = " " + n + " Setup " + } + } + if menuEnd(menus)+len([]rune(name))+2 < t.Cols { + scr.put(0, t.Cols-len([]rune(name))-1, name, bar) + } + return scr +} + +// barMenu is a menu's place on the bar. +type barMenu struct { + label string + col int // where its label begins + hot int // its hot key's rune in label (-1: none) + key rune +} + +// helpMenu is the menu bar's last: what the keys do, and what this is. +var helpMenu = view.PullDown{Label: "Help", Items: []view.PullItem{ + {Label: "Keys", Action: "keys"}, {Label: "About", Action: "about"}}} + +// barMenus are the bar's menus (with Help after them, if there are any), +// placed, each with a hot key no other has. +func barMenus(menus []view.PullDown) []barMenu { + if len(menus) == 0 { + return nil + } + menus = append(menus[:len(menus):len(menus)], helpMenu) + var out []barMenu + used := map[rune]bool{} + col := 3 + for _, m := range menus { + b := barMenu{label: m.Label, col: col, hot: -1} + for i, r := range []rune(m.Label) { + u := unicode.ToUpper(r) + if unicode.IsLetter(r) && !used[u] { + b.hot, b.key, used[u] = i, u, true + break + } + } + out = append(out, b) + col += len([]rune(m.Label)) + 2 + } + return out +} + +// menuEnd is the column after the bar's last menu. +func menuEnd(menus []view.PullDown) int { + bm := barMenus(menus) + if len(bm) == 0 { + return 0 + } + l := bm[len(bm)-1] + return l.col + len([]rune(l.label)) + 1 +} + +// barKey is the menu whose hot key k is (-1: none). +func (w *sheetWin) barKey(k rune) int { + for i, m := range barMenus(w.sh.Menus) { + if m.key == k { + return i + } + } + return -1 +} + +// drawWin draws a sheet's window at a depth, its cursor's entry barred; +// top (if not nil) is scrolled to keep the cursor in it. +func (s *session) drawWin(scr *screen, sh *view.Sheet, depth, cur int, top *int, c winColors) { + g := s.geom(sh, depth) + scr.box(g.row, g.col, g.h, g.w, c.box, c.frame, c.label) + scr.shadow(g.row, g.col, g.h, g.w) + scr.title(g.row, g.col, g.w, sh.Title, c.title) + inner := g.w - 2 + for i := 0; i < min(len(sh.Note), 3); i++ { + l := sh.Note[i] + scr.putw(g.row+1+i, g.col+1, inner, " "+trunc(l.Label+l.Text, inner-2), toneAttr(l.Tone, c)) + } + if g.notes > 0 { + scr.rule(g.row+g.notes, g.col, g.w, c.box, c.frame) + } + t := 0 + if top != nil { + t = *top + } + if cur >= 0 && cur < t { + t = cur + if t > 0 && sh.Entries[t-1].Kind == view.EntryHeading { + t-- // a heading just above comes too + } + } + if cur >= t+g.list { + t = cur - g.list + 1 + } + t = max(min(t, len(sh.Entries)-g.list), 0) + if top != nil { + *top = t + } + lw, vmax := 0, 0 + for _, e := range sh.Entries { + if e.Kind != view.EntryHeading { + lw = max(lw, len([]rune(e.Label))) + vmax = max(vmax, len([]rune(e.Shown()))) + } + } + lw = min(lw, max(inner*11/20, inner-6-max(vmax, 8))) + vw := inner - 2 - lw - 2 - 2 + first := g.row + 1 + g.notes + for r := 0; r < g.list; r++ { + i := t + r + row := first + r + if i >= len(sh.Entries) { break } - w.WriteString(at(2+i, 1) + d.tone(l)) - } - t.Print(w.String()) - d.drawEntries() - d.drawFoot() -} - -// tone is a note's line, fitted to the screen, in its tone's color. -func (d *sheetDraw) tone(l view.Line) string { - t := d.t - s := bbs.Trunc(" "+l.Label+l.Text, t.Cols-1) - switch l.Tone { - case view.Bad: - return t.C(Red, s) - case view.Warn: - return t.C(Yellow, s) - case view.Good: - return t.C(Green, s) - case view.Dim: - return t.C(Dim, s) - case view.Bright: - return t.C(White, s) - } - return s -} - -// drawEntries draws every row of the entries' window. -func (d *sheetDraw) drawEntries() { - for r := 0; r < d.height(); r++ { - d.drawEntry(d.top + r) - } -} - -// columns: the label's, the note's -func (d *sheetDraw) widths() (label, note int) { - note = 0 - for _, e := range d.sh.Entries { - note = max(note, len(e.Note)) - if e.Kind != view.EntryHeading { - label = max(label, len([]rune(e.Label))+2) + e := sh.Entries[i] + if e.Kind == view.EntryHeading { + line := strings.Repeat("─", inner) + scr.put(row, g.col+1, line, c.off) + if e.Label != "" { + scr.put(row, g.col+2, " "+trunc(e.Label, inner-4)+" ", c.head) + } + continue } - } - label = min(max(label, 16), d.t.Cols/2) - return label, min(note, d.t.Cols/4) -} - -// drawEntry draws entry i on its row, if it is in the window (a row past -// the entries is cleared): a heading, or its changed mark, label, value -// and note in columns, in reverse under the cursor. -func (d *sheetDraw) drawEntry(i int) { - t := d.t - row := d.first() + i - d.top - if i < d.top || row >= d.first()+d.height() { - return - } - if i < 0 || i >= len(d.sh.Entries) { - t.Print(at(row, 1) + "\x1b[0m\x1b[K") - return - } - e := d.sh.Entries[i] - if e.Kind == view.EntryHeading { - t.Print(at(row, 1) + "\x1b[0m\x1b[K" + t.C(Cyan, bbs.Trunc(" "+e.Label, t.Cols-1))) - return - } - lw, nw := d.widths() - room := t.Cols - 1 - mark := " " - if e.Changed { - mark = " *" - } - label := e.Label - val := e.Shown() - switch e.Kind { - case view.EntryMenu: - label += " >" - } - vw := max(room-2-lw-1-nw-1, 4) - cells := mark + bbs.Fit(bbs.Trunc(label, lw), lw) + " " + bbs.Fit(bbs.Trunc(val, vw), vw) + " " + - bbs.Fit(bbs.Trunc(e.Note, nw), nw) - cells = bbs.Fit(bbs.Trunc(cells, room), room) - var out string - switch { - case i == d.cur: - out = "\x1b[0;7m" + cells + "\x1b[0m" - case e.Disabled: - out = t.C(Dim, cells) - default: - // the parts in their colors - vc := val + label, value, unset, note, mark := c.label, c.value, c.unset, c.note, c.mark switch { - case e.Changed: - vc = t.C(Yellow, bbs.Fit(bbs.Trunc(val, vw), vw)) - case e.Value == "": - vc = t.C(Dim, bbs.Fit(bbs.Trunc(val, vw), vw)) - default: - vc = t.C(White, bbs.Fit(bbs.Trunc(val, vw), vw)) + case e.Disabled: + label, value, unset, note = c.off, c.off, c.off, c.off + case e.Kind == view.EntryInfo: + value = c.info + case e.Kind == view.EntryMenu: + value = c.note + } + if i == cur { + scr.fill(row, g.col+1, 1, inner, ' ', c.bar) + label, unset, note, mark = c.bar, c.bar, c.bar, c.barValue + value = c.barValue + if e.Disabled { + label, value = attr{cDarkGray, c.bar.bg}, attr{cDarkGray, c.bar.bg} + } } - m := mark if e.Changed { - m = t.C(Yellow, mark) + scr.put(row, g.col+1, "*", mark) + } + scr.putw(row, g.col+2, lw, trunc(e.Label, lw), label) + v := e.Shown() + va := value + if e.Value == "" && e.Kind != view.EntryMenu { + va = unset + } + x := g.col + 2 + lw + 2 + n := scr.put(row, x, trunc(v, vw), va) + if e.Note != "" && n+3 < vw && vw >= 20 { + scr.put(row, x+n+2, trunc(e.Note, vw-n-2), note) + } + switch e.Kind { + case view.EntryMenu: + scr.put(row, g.col+g.w-3, "►", value) + case view.EntryChoice: + scr.put(row, g.col+g.w-3, "↕", note) } - out = m + bbs.Fit(bbs.Trunc(label, lw), lw) + " " + vc + " " + t.C(Dim, bbs.Fit(bbs.Trunc(e.Note, nw), nw)) } - t.Print(at(row, 1) + "\x1b[0m\x1b[K" + out) + if t > 0 { + scr.put(first, g.col+g.w-1, "▲", c.frame) + } + if t+g.list < len(sh.Entries) { + scr.put(first+g.list-1, g.col+g.w-1, "▼", c.frame) + } } -// drawFoot draws the entry's help, the status and the keys. -func (d *sheetDraw) drawFoot() { - t := d.t - help := "" - if d.cur >= 0 && d.cur < len(d.sh.Entries) { - e := d.sh.Entries[d.cur] - help = e.Help - if help == "" && e.Kind == view.EntryText && len(e.Value) > t.Cols/2 { - help = e.Value // a long value: whole here - } +// toneAttr is a note line's colors in a window. +func toneAttr(tn view.Tone, c winColors) attr { + bg := c.label.bg + switch tn { + case view.Bad: + return attr{cLightRed, bg} + case view.Warn: + return attr{cYellow, bg} + case view.Good: + return attr{cLightGreen, bg} + case view.Dim: + return attr{cLightGray, bg} + case view.Bright: + return attr{cWhite, bg} } - keys := "Enter change Esc back F1 help F9 quit F10 save+exit" - for _, a := range d.sh.Keys { - if a.Key != 0 { // a 3270's PF key alone: nothing to press here - keys = string(a.Key) + " " + a.Label + " " + keys - } - } - w := t.Cols - 1 - var b strings.Builder - b.WriteString(at(t.Rows-2, 1) + "\x1b[0m\x1b[K" + t.C(Dim, bbs.Trunc(" "+help, w))) - b.WriteString(at(t.Rows-1, 1) + "\x1b[0m\x1b[K" + t.C(Yellow, bbs.Trunc(" "+d.sh.Status, w))) - b.WriteString(at(t.Rows, 1) + "\x1b[0;30;46m" + bbs.Fit(bbs.Trunc(" "+keys, w), w) + "\x1b[0m") - t.Print(b.String()) + return c.label } -// edit reads a text entry's new value on the help row: false if it was -// left as it was. -func (d *sheetDraw) edit(e view.Entry) (string, bool, error) { - t := d.t - prompt := " " + e.Label + ": " - t.Print(at(t.Rows-2, 1) + "\x1b[0m\x1b[K" + t.C(Cyan, prompt) + "\x1b[?25h") - max := e.Width - if max <= 0 { - max = 255 +// helpBox draws the box of the cursor's entry's help above the key bar +// (where the screen has the rows). +func (s *session) helpBox(scr *screen, e *view.Entry, status, flash string) bool { + _, last, ok := s.layout() + if !ok { + return false } - var l Line - var err error - if e.Secret { - l, err = t.ReadLine(LineOpts{Max: max, Mask: true}) - if err == nil && l.Text == "" { - return "", false, nil // nothing typed: kept + cols := s.t.Cols + row := last + 1 + scr.box(row, 0, 4, cols, boxSingle, attr{cLightCyan, cBlue}, attr{cWhite, cBlue}) + if status != "" { + st := " " + trunc(status, cols/2) + " " + scr.put(row+3, cols-len([]rune(st))-2, st, attr{cYellow, cBlue}) + } + if flash != "" { // what was just said, in place of the help + scr.title(row, 0, cols, "Note", attr{cYellow, cBlue}) + for i, l := range wrapText(flash, cols-4) { + if i < 2 { + scr.put(row+1+i, 2, l, attr{cLightRed, cBlue}) + } } + return true + } + if e == nil { + return true + } + scr.title(row, 0, cols, e.Label, attr{cYellow, cBlue}) + help := e.Help + if help == "" && e.Kind == view.EntryText && len([]rune(e.Value)) > cols/2 { + help = e.Value // a long value: whole here + } + lines := wrapText(capFirst(help), cols-4) + more := "" + switch { + 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 == "": + more = "Default: " + e.Default + } + if len(lines) > 2 || len(lines) == 2 && more != "" { + lines[1] = trunc(lines[1], cols-14) + " (F1: more)" + lines = lines[:2] + } else if more != "" && len(lines) < 2 { + if len(lines) == 1 && lines[0] == "" { + lines = lines[:0] + } + lines = append(lines, more) + } + for i, l := range lines { + a := attr{cWhite, cBlue} + if l == more { + a = attr{cLightGray, cBlue} + } + scr.put(row+1+i, 2, trunc(l, cols-4), a) + } + return true +} + +// capFirst is s with its first letter a capital. +func capFirst(s string) string { + r := []rune(s) + if len(r) > 0 { + r[0] = unicode.ToUpper(r[0]) + } + return string(r) +} + +// choiceLabels are choices as they read: "" as "(default)". +func choiceLabels(cs []string) []string { + out := make([]string, len(cs)) + for i, c := range cs { + out[i] = c + if c == "" { + out[i] = "(default)" + } + } + return out +} + +// keyBar draws the bar of keys at the foot, and status at its right. +func (s *session) keyBar(scr *screen, keys [][2]string, status string) { + cols, row := s.t.Cols, s.t.Rows-1 + bar, hot := attr{cBlack, cLightGray}, attr{cRed, cLightGray} + scr.fill(row, 0, 1, cols, ' ', bar) + room := cols - 1 + if status != "" { + room -= min(len([]rune(status))+3, cols/2) + } + x := 1 + for _, k := range keys { + n := len([]rune(k[0])) + 1 + len([]rune(k[1])) + if x+n > room { + break + } + scr.put(row, x, k[0], hot) + scr.put(row, x+len([]rune(k[0]))+1, k[1], bar) + x += n + 2 + } + if status != "" { + st := trunc(status, cols/2-2) + scr.put(row, cols-len([]rune(st))-2, st, attr{cBlue, cLightGray}) + } +} + +// --- pull-down menus + +// pullDown shows the menu bar's menus, menu i pulled down, until one of +// their items is picked (true) or the caller leaves them. +func (s *session) pullDown(w *sheetWin, i int) (view.SheetResult, bool, error) { + menus := append(w.sh.Menus[:len(w.sh.Menus):len(w.sh.Menus)], helpMenu) + bm := barMenus(w.sh.Menus) + if len(bm) == 0 { + return view.SheetResult{}, false, nil + } + cur := -1 + first := func(m view.PullDown) int { + for j, it := range m.Items { + if !it.Heading { + return j + } + } + return -1 + } + cur = first(menus[i]) + top := 0 + for { + base := w.frame() + scr := s.deskScreen(w.sh.Menus, i) + // the bar as pulled down, over the sheet's frame + for x := 0; x < scr.cols; x++ { + *base.at(0, x) = *scr.at(0, x) + } + m := menus[i] + width := 12 + for _, it := range m.Items { + width = max(width, len([]rune(it.Label))+4) + } + width = min(width, s.t.Cols-2) + col := min(bm[i].col-2, s.t.Cols-width-2) + col = max(col, 0) + room := s.t.Rows - 4 + n := min(len(m.Items), room-2) + if cur >= 0 { + if cur < top { + top = cur + } + if cur >= top+n { + top = cur - n + 1 + } + } + box := attr{cBlack, cLightGray} + base.box(1, col, n+2, width, boxSingle, box, box) + base.shadow(1, col, n+2, width) + for r := 0; r < n; r++ { + j := top + r + it := m.Items[j] + row := 2 + r + if it.Heading { + base.rule(row, col, width, boxSingle, box) + if it.Label != "" { + base.put(row, col+2, " "+trunc(it.Label, width-6)+" ", attr{cDarkGray, cLightGray}) + } + continue + } + a := box + if j == cur { + a = attr{cBlack, cGreen} + } + base.putw(row, col+1, width-2, " "+trunc(it.Label, width-3), a) + } + if top > 0 { + base.put(2, col+width-1, "▲", box) + } + if top+n < len(m.Items) { + base.put(1+n, col+width-1, "▼", box) + } + s.keyBar(base, [][2]string{{"Enter", "Select"}, {"Esc", "Close"}, {"←→", "Menus"}, {"↑↓", "Items"}}, "") + s.show(base) + k, alt, err := s.key() + if err != nil { + return view.SheetResult{}, false, err + } + move := func(dir int) { + for j := cur + dir; j >= 0 && j < len(m.Items); j += dir { + if !m.Items[j].Heading { + cur = j + return + } + } + } + switch { + case alt: + if j := w.barKey(k); j >= 0 { + i, cur, top = j, first(menus[j]), 0 + } + case k == 0x1b || k == '/' || k == KeyF1+11: + return view.SheetResult{}, false, nil + case k == KeyLeft: + i = (i + len(menus) - 1) % len(menus) + cur, top = first(menus[i]), 0 + case k == KeyRight: + i = (i + 1) % len(menus) + cur, top = first(menus[i]), 0 + case k == KeyUp: + move(-1) + case k == KeyDown || k == '\t': + move(1) + case k == KeyHome: + cur = -1 + move(1) + case k == KeyEnd: + cur = len(m.Items) + move(-1) + case k == KeyPgUp: + for r := 0; r < n-1; r++ { + move(-1) + } + case k == KeyPgDn: + for r := 0; r < n-1; r++ { + move(1) + } + case isEnter(k) || k == ' ': + if cur < 0 { + continue + } + it := m.Items[cur] + switch { + case it.Action == "keys": + if err := s.messageBox(w.frame(), "Keys", keyHelp(len(w.sh.Menus) > 0)); err != nil { + return view.SheetResult{}, false, err + } + return view.SheetResult{}, false, nil + case it.Action == "about": + if err := s.messageBox(w.frame(), "About", aboutHelp()); err != nil { + return view.SheetResult{}, false, err + } + return view.SheetResult{}, false, nil + case it.Action != "": + return view.SheetResult{Action: it.Action}, true, nil + case len(it.Path) > 0: + return view.SheetResult{Action: view.SheetJump, Jump: it.Path}, true, nil + } + default: + // a letter: the next item beginning with it + u := unicode.ToUpper(k) + for d := 1; d <= len(m.Items); d++ { + j := (cur + d + len(m.Items)) % len(m.Items) + it := m.Items[j] + if !it.Heading && strings.HasPrefix(strings.ToUpper(it.Label), string(u)) { + cur = j + break + } + } + } + } +} + +// keyHelp is the Keys dialog's lines. +func keyHelp(menus bool) []view.Line { + ls := []view.Line{ + view.V("↑ ↓ PgUp PgDn ", "move the bar"), + view.V("Home End ", "the first, the last"), + view.V("A letter ", "the next entry beginning with it"), + view.V("Enter ", "open a menu, change a value, do it"), + view.V("Space ", "turn a yes/no over, the next choice"), + view.V("Esc ← ", "back a window"), + view.V("F1 ? ", "the entry's whole help"), + } + if menus { + ls = append(ls, view.V("/ F12 Alt+key ", "the menu bar's pull-down menus")) + } + return append(ls, + view.V("F9 ", "quit without saving"), + view.V("F10 ", "save it all and leave"), + view.V("Ctrl-L ", "draw the screen again"), + view.L(""), + view.T(view.Dim, "A * marks a change not saved yet.")) +} + +// aboutHelp is the About dialog's lines. +func aboutHelp() []view.Line { + return []view.Line{ + view.T(view.Bright, "D-Modem BBS Setup"), + view.L(""), + view.L("The board, its lines and modems, and every front end the BBS answers as: AOL, CompuServe, MSN, AIM and ICQ, Yahoo!, IRC, mail, news, the web, gopher, finger, Gemini, time servers and more."), + view.L(""), + view.T(view.Dim, "Nothing is written until you save (F10). bbs.conf keeps its comments."), + } +} + +// --- dialogs over the desk + +// dialog colors: a light gray box with a white frame +var ( + dlgFrame = attr{cWhite, cLightGray} + dlgText = attr{cBlack, cLightGray} + dlgTitle = attr{cWhite, cLightGray} + dlgField = attr{cYellow, cBlue} + dlgBtn = attr{cBlack, cGreen} + dlgBtnOn = attr{cWhite, cGreen} + dlgDim = attr{cDarkGray, cLightGray} +) + +// dlgTone is a line's color in a dialog. +func dlgTone(tn view.Tone) attr { + switch tn { + case view.Bad: + return attr{cRed, cLightGray} + case view.Warn: + return attr{cBrown, cLightGray} + case view.Good: + return attr{cGreen, cLightGray} + case view.Dim: + return dlgDim + case view.Bright: + return attr{cBlue, cLightGray} + } + return dlgText +} + +// dlgBox is where a dialog of inner width iw and h rows inside goes: +// centered on the desk. +func (s *session) dlgBox(iw, h int) (row, col, bw, bh int) { + bw = min(iw+4, s.t.Cols-2) + bh = min(h+2, s.t.Rows-3) + row = max((s.t.Rows-bh)/2, 1) + col = max((s.t.Cols-bw)/2, 0) + return +} + +// button draws a button, lit if on. +func button(scr *screen, row, col int, label string, on bool) int { + a := dlgBtn + if on { + a = dlgBtnOn + label = "►" + label + "◄" } else { - l, err = t.ReadLine(LineOpts{Max: max, Initial: e.Value}) + label = " " + label + " " } - t.Print("\x1b[?25l") - if err != nil { + n := scr.put(row, col, label, a) + scr.put(row, col+n, "▄", attr{cBlack, cLightGray}) + scr.put(row+1, col+1, strings.Repeat("▀", n), attr{cBlack, cLightGray}) + return n +} + +// messageBox shows lines in a dialog over base, scrolled with the cursor +// keys, until Enter or Esc. +func (s *session) messageBox(base *screen, title string, ls []view.Line) error { + type tl struct { + text string + a attr + } + iw := min(max(40, len([]rune(title))+6), s.t.Cols-6) + for _, l := range ls { + iw = max(iw, min(len([]rune(l.Label+l.Text)), s.t.Cols-6)) + } + var lines []tl + for _, l := range ls { + for _, w := range wrapText(l.Label+l.Text, iw) { + lines = append(lines, tl{w, dlgTone(l.Tone)}) + } + } + row, col, bw, bh := s.dlgBox(iw, len(lines)+3) + body := bh - 5 // frame, a blank, the button and its shadow + top := 0 + for { + scr := base.clone() + scr.box(row, col, bh, bw, boxDouble, dlgFrame, dlgText) + scr.shadow(row, col, bh, bw) + scr.title(row, col, bw, title, dlgTitle) + for r := 0; r < body && top+r < len(lines); r++ { + l := lines[top+r] + scr.put(row+1+r, col+2, trunc(l.text, bw-4), l.a) + } + if top > 0 { + scr.put(row+1, col+bw-1, "▲", dlgFrame) + } + if top+body < len(lines) { + scr.put(row+body, col+bw-1, "▼", dlgFrame) + } + button(scr, row+bh-3, col+(bw-6)/2, "OK", true) + keys := [][2]string{{"Enter", "OK"}} + if len(lines) > body { + keys = append(keys, [2]string{"↑↓ PgUp PgDn", "Scroll"}) + } + s.keyBar(scr, keys, "") + s.show(scr) + k, _, err := s.key() + if err != nil { + return err + } + switch k { + case KeyUp: + top = max(top-1, 0) + case KeyDown: + top = max(min(top+1, len(lines)-body), 0) + case KeyPgUp: + top = max(top-body, 0) + case KeyPgDn: + top = max(min(top+body, len(lines)-body), 0) + case KeyHome: + top = 0 + case KeyEnd: + top = max(len(lines)-body, 0) + case '\r', '\n', 0x1b, ' ', 'O', 'o', 'Q', 'q': + return nil + } + } +} + +// confirmBox asks a yes or no question in a dialog over base, def lit. +func (s *session) confirmBox(base *screen, question string, def bool) (bool, error) { + iw := min(max(36, len([]rune(question))), min(60, s.t.Cols-6)) + lines := wrapText(question, iw) + row, col, bw, bh := s.dlgBox(iw, len(lines)+4) + yes := def + for { + scr := base.clone() + scr.box(row, col, bh, bw, boxDouble, dlgFrame, dlgText) + scr.shadow(row, col, bh, bw) + scr.title(row, col, bw, "Confirm", dlgTitle) + for i, l := range lines { + if 1+i < bh-4 { + scr.put(row+1+i, col+2, l, dlgText) + } + } + bx := col + bw/2 - 10 + button(scr, row+bh-3, bx, "Yes", yes) + button(scr, row+bh-3, bx+12, "No", !yes) + s.keyBar(scr, [][2]string{{"Y", "Yes"}, {"N", "No"}, {"←→", "Choose"}, {"Enter", "OK"}, {"Esc", "Cancel"}}, "") + s.show(scr) + k, _, err := s.key() + if err != nil { + return false, err + } + switch k { + case 'y', 'Y': + return true, nil + case 'n', 'N', 0x1b: + return false, nil + case '\r', '\n', ' ': + return yes, nil + case KeyLeft, KeyRight, '\t': + yes = !yes + } + } +} + +// lineEdit edits a value in a field of w cells at row, col over base: the +// value and the key that ended it (Enter, Tab, Esc, Up or Down). +func (s *session) lineEdit(base *screen, row, col, w int, value string, maxLen int, secret bool) (string, rune, error) { + if maxLen <= 0 { + maxLen = 255 + } + buf := []rune(value) + pos, off := len(buf), 0 + for { + if pos < off { + off = pos + } + if pos >= off+w { + off = pos - w + 1 + } + shown := buf[off:min(len(buf), off+w)] + str := string(shown) + if secret { + str = strings.Repeat("*", len(shown)) + } + scr := base.clone() + scr.putw(row, col, w, str, dlgField) + if off > 0 { + scr.put(row, col, "◄", attr{cLightCyan, cBlue}) + } + if off+w < len(buf) { + scr.put(row, col+w-1, "►", attr{cLightCyan, cBlue}) + } + s.show(scr) + s.t.Print(at(row+1, col+1+pos-off) + "\x1b[?25h") + k, _, err := s.key() + s.t.Print("\x1b[?25l") + if err != nil { + return "", 0, err + } + switch { + case isEnter(k): + return string(buf), '\r', nil + case k == '\t' || k == 0x1b || k == KeyUp || k == KeyDown: + return string(buf), k, nil + case k == KeyLeft: + pos = max(pos-1, 0) + case k == KeyRight: + pos = min(pos+1, len(buf)) + case k == KeyHome || k == 0x01: + pos = 0 + case k == KeyEnd || k == 0x05: + pos = len(buf) + case k == 0x08 || k == 0x7f: + if pos > 0 { + buf = append(buf[:pos-1], buf[pos:]...) + pos-- + } + case k == KeyDelete || k == 0x04: + if pos < len(buf) { + buf = append(buf[:pos], buf[pos+1:]...) + } + case k == 0x15 || k == 0x19: // ^U ^Y: all of it + buf, pos, off = buf[:0], 0, 0 + case k == 0x0b: // ^K: to the end + buf = buf[:pos] + case k >= ' ' && k < KeyUp && k != 0x7f && len(buf) < maxLen: + buf = append(buf[:pos], append([]rune{k}, buf[pos:]...)...) + pos++ + } + } +} + +// inputBox changes a text entry's value in a dialog over base: false if +// it was given up (Esc). +func (s *session) inputBox(base *screen, e view.Entry) (string, bool, error) { + iw := min(64, s.t.Cols-8) + help := wrapText(capFirst(e.Help), iw) + if len(help) == 1 && help[0] == "" { + help = nil + } + help = help[:min(len(help), 4)] + var foot []string + if e.Default != "" && e.Default != "default" { + foot = append(foot, "Default: "+e.Default+" (left empty)") + } + if e.Secret { + foot = append(foot, "Leave it empty to keep the one there is.") + } + row, col, bw, bh := s.dlgBox(iw, 2+len(help)+len(foot)+1) + scr := base.clone() + scr.box(row, col, bh, bw, boxDouble, dlgFrame, dlgText) + scr.shadow(row, col, bh, bw) + scr.title(row, col, bw, e.Label, dlgTitle) + r := row + 1 + for _, h := range help { + scr.put(r, col+2, h, dlgText) + r++ + } + r++ + field := r + for i, f := range foot { + scr.put(field+2+i, col+2, trunc(f, bw-4), dlgDim) + } + s.keyBar(scr, [][2]string{{"Enter", "OK"}, {"Esc", "Cancel"}, {"Ctrl-U", "Clear"}}, "") + initial := e.Value + if e.Secret { + initial = "" + } + v, k, err := s.lineEdit(scr, field, col+2, bw-4, initial, e.Width, e.Secret) + if err != nil || k == 0x1b { return "", false, err } - return l.Text, l.Text != e.Value, nil + if e.Secret && v == "" { + return "", false, nil // nothing typed: kept + } + return v, true, nil +} + +// choiceBox picks one of a choice entry's values from a list over base: +// false if it was given up. +func (s *session) choiceBox(base *screen, e view.Entry) (string, bool, error) { + labels := choiceLabels(e.Choices) + cur := 0 + now := e.Value + if now == "" { + now = e.Default + } + iw := len([]rune(e.Label)) + 6 + for i, c := range e.Choices { + iw = max(iw, len([]rune(labels[i]))+6) + if c == now || c == "" && e.Value == "" { + cur = i + } + } + iw = min(max(iw, 24), s.t.Cols-8) + n := min(len(labels), s.t.Rows-10) + row, col, bw, bh := s.dlgBox(iw, n+4) + n = min(n, bh-6) + top := 0 + for { + if cur < top { + top = cur + } + if cur >= top+n { + top = cur - n + 1 + } + scr := base.clone() + 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}) + lw := bw - 4 + for r := 0; r < n; r++ { + j := top + r + a := attr{cBlack, cCyan} + if j == cur { + a = attr{cWhite, cGreen} + } + l := " " + labels[j] + if e.Choices[j] == now || e.Choices[j] == "" && e.Value == "" { + l += " *" + } + 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) { + 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"}}, "") + s.show(scr) + k, _, err := s.key() + if err != nil { + return "", false, err + } + switch { + case isEnter(k) || k == ' ': + return e.Choices[cur], 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) + case k == KeyHome || k == KeyPgUp: + cur = 0 + case k == KeyEnd || k == KeyPgDn: + cur = len(labels) - 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)) { + cur = j + break + } + } + } + } +} + +// formBox fills a form's fields in a dialog over base: Tab and the cursor +// keys between them, Enter on the last (or anywhere, with ^S) to finish; +// false if it was given up. +func (s *session) formBox(base *screen, f *view.Form) (map[string]string, bool, error) { + iw := min(64, s.t.Cols-8) + var intro []view.Line + for _, l := range f.Intro { + for _, w := range wrapText(l.Label+l.Text, iw) { + intro = append(intro, view.Line{Text: w, Tone: l.Tone}) + } + } + lw := 0 + for _, fd := range f.Fields { + lw = max(lw, len([]rune(fieldLabel(fd)))) + } + lw = min(lw, iw/2) + h := len(intro) + len(f.Fields) + if len(intro) > 0 { + h++ + } + row, col, bw, bh := s.dlgBox(iw, h+3) + vals := make([]string, len(f.Fields)) + for i, fd := range f.Fields { + if fd.Edit && !fd.Secret { + vals[i] = fd.Value + } + } + cur := 0 + for { + scr := base.clone() + scr.box(row, col, bh, bw, boxDouble, dlgFrame, dlgText) + scr.shadow(row, col, bh, bw) + scr.title(row, col, bw, f.Title, dlgTitle) + r := row + 1 + for _, l := range intro { + scr.put(r, col+2, trunc(l.Text, bw-4), dlgTone(l.Tone)) + r++ + } + if len(intro) > 0 { + r++ + } + fw := bw - 4 - lw - 1 + rows := make([]int, len(f.Fields)) + for i, fd := range f.Fields { + rows[i] = r + scr.putw(r, col+2, lw, trunc(fieldLabel(fd), lw), dlgText) + v := vals[i] + if fd.Secret { + v = strings.Repeat("*", len([]rune(v))) + } + a := attr{cLightGray, cBlue} + if v == "" && fd.Value != "" && !fd.Edit { + v = fd.Value + } + if vals[i] != "" { + a = dlgField + } + scr.putw(r, col+2+lw+1, fw, trunc(v, fw), a) + r++ + } + s.keyBar(scr, [][2]string{{"Enter", "Next/OK"}, {"Tab", "Next"}, {"Esc", "Cancel"}}, "") + width := f.Fields[cur].Width + v, k, err := s.lineEdit(scr, rows[cur], col+2+lw+1, fw, vals[cur], width, f.Fields[cur].Secret) + if err != nil { + return nil, false, err + } + vals[cur] = v + switch { + case k == 0x1b: + return map[string]string{}, false, nil + case k == KeyUp: + cur = max(cur-1, 0) + case k == KeyDown || k == '\t': + cur = (cur + 1) % len(f.Fields) + case k == '\r': + if cur < len(f.Fields)-1 { + cur++ + continue + } + out := map[string]string{} + for i, fd := range f.Fields { + v := vals[i] + if v == "" && !fd.Edit { + if fd.Value == "" && i == 0 { + return out, false, nil + } + v = fd.Value + } + out[fd.Name] = v + } + return out, true, nil + } + } +} + +// fieldLabel is a form field's label on a dialog. +func fieldLabel(fd view.Field) string { + l := fd.Label + if l == "" { + l = strings.TrimRight(fd.Prompt, ": ?") + } + return l } diff --git a/internal/textui/ui.go b/internal/textui/ui.go index 0f5c870..03c7c6a 100644 --- a/internal/textui/ui.go +++ b/internal/textui/ui.go @@ -28,7 +28,8 @@ type session struct { o Options user *store.User - chatting bool // in a chat room: its lines shown as such + chatting bool // in a chat room: its lines shown as such + desk *desk // the full screen kept up between sheets (sheet.go), if it is up } // errHangup: the caller logged off. diff --git a/internal/textui/view.go b/internal/textui/view.go index a7e3b95..d86ad99 100644 --- a/internal/textui/view.go +++ b/internal/textui/view.go @@ -111,6 +111,7 @@ func (s *session) Narrow() bool { return s.t.Narrow() } // a key until it is an item's. It is that item's key; "" for Enter (none // chosen: the caller shows its menu again, or goes back if it will). func (s *session) Menu(m *view.Menu) (string, error) { + s.EndSheets() t := s.t if len(m.Intro) > 0 { t.Println("") @@ -164,6 +165,7 @@ func (s *session) Menu(m *view.Menu) (string, error) { // action's key, More at Enter if there is more, or Back. With nothing to // pick or do it pauses at the end and is Back. func (s *session) Table(tb *view.Table) (view.Choice, error) { + s.EndSheets() t := s.t t.Println("") t.Println(t.C(Cyan, tb.Title)) @@ -272,6 +274,7 @@ func (s *session) Table(tb *view.Table) (view.Choice, error) { // picture, its body a page at a time; then waits for an action's key (Q: // Quit, Enter or space: Default, each Back if unset). func (s *session) Message(m *view.Message) (string, error) { + s.EndSheets() t := s.t t.Clear() t.Println(t.C(Dim, m.Where)) @@ -319,6 +322,9 @@ func (s *session) Message(m *view.Message) (string, error) { // Form asks for each field in turn, Enter keeping its value; nothing typed // for a first field with no value is giving up (false). func (s *session) Form(f *view.Form) (map[string]string, bool, error) { + if s.desk != nil && len(f.Fields) > 0 { + return s.formBox(s.deskBase(), f) + } t := s.t for _, l := range f.Intro { t.Println(s.line(l)) @@ -365,6 +371,7 @@ func (s *session) Form(f *view.Form) (map[string]string, bool, error) { // Panel shows a panel's title, picture and lines, and reads a key: an // action's ID, Back for Q or Enter, "" for any other. func (s *session) Panel(p *view.Panel) (string, error) { + s.EndSheets() t := s.t t.Println("") t.Println(t.C(Cyan, p.Title)) @@ -399,6 +406,7 @@ func (s *session) Panel(p *view.Panel) (string, error) { // line editor; true if it was sent. An error sending is told the caller, // and is false. func (s *session) Edit(d *view.Draft) (bool, error) { + s.EndSheets() t := s.t t.Println("") to := d.To @@ -466,12 +474,19 @@ func (s *session) Edit(d *view.Draft) (bool, error) { // Confirm asks a yes or no question, def at Enter. func (s *session) Confirm(question string, def bool) (bool, error) { + if s.desk != nil { + return s.confirmBox(s.deskBase(), question, def) + } return s.t.YesNo(question, def) } // Say prints msg in its tone; a Bright one as a heading, after a blank // line. func (s *session) Say(tn view.Tone, msg string) { + if s.desk != nil { + s.desk.flash = msg // at the foot of the next screen + return + } if tn == view.Bright { s.t.Println("") s.t.Println(s.t.C(Cyan, msg)) @@ -483,6 +498,9 @@ func (s *session) Say(tn view.Tone, msg string) { // Show shows a title and lines a page at a time, and waits for a key at // the end (not if the caller quit before it). func (s *session) Show(title string, ls []view.Line) error { + if s.desk != nil { + return s.messageBox(s.deskBase(), title, ls) + } t := s.t t.Println("") t.Println(t.C(Cyan, title)) diff --git a/internal/textui/view_test.go b/internal/textui/view_test.go index c9ab96d..46a7239 100644 --- a/internal/textui/view_test.go +++ b/internal/textui/view_test.go @@ -25,15 +25,24 @@ func TestKeyLabel(t *testing.T) { } } -// TestSheetFoot: the key line names a sheet's keys, leaving out those with +// TestSheetFoot: the key bar names a sheet's keys, leaving out those with // a 3270 PF key alone (no NUL for them). func TestSheetFoot(t *testing.T) { - term, c := ansiTerm() - d := &sheetDraw{t: term, sh: &view.Sheet{Keys: []view.Action{{Key: 'A', Label: "Add"}, {PF: 5, Label: "PFonly"}}}, cur: -1} - d.drawFoot() - term.Flush() - out := c.String() - if strings.Contains(out, "\x00") || strings.Contains(out, "PFonly") || !strings.Contains(out, "A Add Enter change") { - t.Errorf("foot %q", out) + term, _ := ansiTerm() + s := &session{t: term} + s.startDesk() + w := &sheetWin{s: s, sh: &view.Sheet{Title: "T", Keys: []view.Action{{Key: 'A', Label: "Add"}, {PF: 5, Label: "PFonly"}}}, cur: -1} + bar := screenRow(w.frame(), term.Rows-1) + if strings.Contains(bar, "\x00") || strings.Contains(bar, "PFonly") || !strings.Contains(bar, "A Add F9 Quit") { + t.Errorf("key bar %q", bar) } } + +// screenRow is a screen's row as text. +func screenRow(scr *screen, row int) string { + var b strings.Builder + for x := 0; x < scr.cols; x++ { + b.WriteRune(scr.at(row, x).r) + } + return b.String() +} diff --git a/internal/view/sheet.go b/internal/view/sheet.go index da90916..6c02999 100644 --- a/internal/view/sheet.go +++ b/internal/view/sheet.go @@ -16,6 +16,24 @@ type Sheet struct { Cursor int // the entry the cursor begins on Keys []Action // more keys (A Add, D Delete ...), with PF keys on a 3270 Status string // the foot's left: "3 changes not saved" + // Menus are the pull-down menus of a menu bar, where the front end + // draws one (a text terminal's full screen): picking an item jumps + // to its Path, or does its Action + Menus []PullDown +} + +// PullDown is a pull-down menu of a menu bar. +type PullDown struct { + Label string + Items []PullItem +} + +// PullItem is a pull-down menu's line. +type PullItem struct { + Label string + Path []string // where it jumps: the labels of the entries to open, from the first sheet + Action string // or what it does (SheetSave, SheetQuit), as a sheet's result + Heading bool // a line between groups (Label: its words, if any) } // EntryKind is what an entry is. @@ -61,6 +79,18 @@ type SheetResult struct { Action string // Pick (a Menu or Action entry chosen), SheetSet, SheetSave, SheetQuit, Back, a Keys ID Entry int // the entry the cursor was on Values map[string]string // SheetSet: entries' new values by ID (a 3270 sends all it changed at once) + Jump []string // SheetJump: a pull-down item's Path +} + +// SheetJump is a sheet's result when a pull-down item was picked: go to +// its Path. +const SheetJump = "jump" + +// SheetEnder is a front end that keeps its full screen up between sheets +// (to put questions and help over it): EndSheets puts it away when they +// are done. +type SheetEnder interface { + EndSheets() } // SheetUI is a front end that draws sheets full-screen.