diff --git a/.github/scripts/test-windows.ps1 b/.github/scripts/test-windows.ps1 index 74a51e0..3af846b 100644 --- a/.github/scripts/test-windows.ps1 +++ b/.github/scripts/test-windows.ps1 @@ -74,7 +74,8 @@ $required = @( 'TestAnalyzeTerminalAndUnsearchedResultsAreExplicit', 'TestAnalyzeRefusalsDoNotWriteState', 'TestAnalyzeDoesNotRedirectAnUnreadableExactGame', - 'TestPlayNowCutsAMaxSearchShort' + 'TestPlayNowCutsAMaxSearchShort', + 'TestStudyNoteSurvivesLeavingAndResizing' ) $missing = @($required | Where-Object { -not $passes.ContainsKey($_) }) $missingStorage = @() @@ -109,7 +110,9 @@ if ($Scope -eq 'all') { 'gamestore/TestOnlyOneFinishOfAGameIsStored', 'gamestore/TestReadingAStoreNothingMayWriteTo', 'gamestore/TestASaveThatCannotReplaceTheGameKeepsTheStoredOne', - 'gamestore/TestWindowsDeviceGameIDsAreRejected' + 'gamestore/TestWindowsDeviceGameIDsAreRejected', + 'study/TestTwoProcessesSavingOneStudyLoseNothing', + 'study/TestSaveWaitsForTheLockAndSeesTheSaveBeforeIt' ) $missingStorage = @($requiredStorage | Where-Object { -not $allPasses.ContainsKey('github.com/BAKocska/twixtui/internal/' + $_) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 180d2bc..d4041d7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -221,7 +221,7 @@ jobs: # job nobody reads. run: | go test -race -count=1 ./internal/netplay/ ./internal/app/ ./internal/cli/ \ - ./internal/leaderboard/ ./internal/profile/ + ./internal/leaderboard/ ./internal/profile/ ./internal/study/ go test -race -count=1 -run '^TestProgress' ./internal/bot/ # Native Windows executes the same product scenarios through ConPTY. The diff --git a/CHANGELOG.md b/CHANGELOG.md index bd6c6fa..81ce96d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,17 @@ project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). move: completed depth, nodes and time in all, and stop reason. A status line too narrow for all of them gives up whole items, the stop reason before the time and the nodes, and always keeps the move and its completed depth. +- Study notes and bookmarks in the replay viewer: `m` bookmarks the selected + entry and `e` writes a one-line note on it, shown in the panel and marked in + the entry list with `*` and `#`. They are kept per game, record digest and + entry in `study/.json` beside the saved game (study format 1); the + canonical record is never rewritten. Notes are bounded to 8 KiB of UTF-8 and + study files to 1 MiB, and stored text is drawn inert. +- Saves are checked against the revision the viewer loaded: a save another + window has overtaken is refused with the typed note kept, and it can replace + the stored note only once the viewer has shown that version whole. A changed + record, a newer or damaged study file and unfinished games refuse edits + visibly and leave the file as it was. ### Fixed diff --git a/docs/MANUAL.md b/docs/MANUAL.md index df2c2de..7893f10 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -347,6 +347,12 @@ Correspondence keeps `c` available to retrieve the final code, including after reopening the saved game. `ctrl+c` still ends the whole program, even when `enter` or `q` would return to the menu. +The replay viewer reuses the movement keys above for stepping through a record +and adds keys of its own, listed under [Reviewing saved games](#reviewing-saved-games): +`:` jumps to an entry, `m` bookmarks the selected entry and `e` writes a note on +it. While a note is being written every printable key is text, and the key +bound to `enter` above is the one that saves it. + ## Playing a bot ``` @@ -893,7 +899,9 @@ shows both the entry counter and the number of moves played. | `k` / `up`, `j` / `down` | Back or forward five entries. | | `g` / `G` | Initial position / final entry. | | `:` | Type an entry number; `enter` jumps and `esc` cancels the input. | -| `q` / `esc` | Leave the viewer when not editing the entry number. | +| `m` | Bookmark the selected entry, or take its bookmark off. Saved at once. | +| `e` | Write or edit the selected entry's note; `enter` saves and `esc` cancels without saving. | +| `q` / `esc` | Leave the viewer when not editing the entry number or a note. | | `ctrl+c` | End the program. | Numbers outside `0..last entry`, non-digits and oversized input are refused, @@ -910,10 +918,50 @@ remains the record's result while stepping through earlier positions. Replay validates the whole record before opening and retains one mutable board, not a board snapshot per entry. Small backward steps use undo; longer backward seeks rebuild the requested prefix to avoid repeatedly scanning draw-offer -history. Reviewing never changes the stored record or ratings. Notes and -variations are not part of this viewer; engine analysis is available through the +history. Reviewing never changes the stored record or ratings. Variations +are not part of this viewer; engine analysis is available through the separate `analyze` commands below, not as an interactive replay action. +#### Notes and bookmarks + +A finished game can carry a note and a bookmark on any entry, including `0`. +They are kept in `study/.json` in the configuration directory, beside +the saved game rather than in it: the canonical record is never rewritten, and +an exported record carries no notes. An imported game can have notes of its own +on this machine while its record stays exactly as it was imported. + +The panel shows the selected entry's bookmark and note. The entry list gives +marked entries a column of their own once any exist: `*` for a bookmark and `#` +for a note, as characters rather than colours. A note is one line of at most +8 KiB of UTF-8; a longer paste is refused whole rather than cut, and line +breaks in a paste become spaces. While the note input is open every printable +key is text, so `q`, `h` or `:` are typed rather than acted on. Text read from +the file is drawn inert: control characters and escape sequences are shown as +plain text or dropped, never obeyed, and a note written with line breaks by +another program keeps them unless you edit them away. + +Notes are attached to the record's digest as well as to the game ID, and the +file is limited to 1 MiB. If the record has changed since the notes were +written, or the file was written by a newer twixtui or is damaged, the viewer +says so and the notes are read-only; the file is left exactly as it was, never +moved onto the new record or rewritten. Notes can be saved on finished games +only, so an unfinished imported game can be watched but `m` and `e` explain why +they do nothing. In a terminal with no room for the panel, the status line +gives the reason for a refused `m`, `e` or save in a few words. + +Every save is checked against the revision the viewer last read, and a +successful save advances it. If another window saved first, the save is refused +instead of overwriting it: the input stays open with your text, the stored +note is shown beneath it, and saving again replaces it while `esc` keeps the +stored one. Saving again is taken only while the whole stored note is on +screen. In a terminal too small to show it — with no panel, or a panel too +short or narrow for all of it — the save is refused again and nothing is +written until the terminal is enlarged; `esc` still keeps the stored note. A +bookmark refused the same way shows what is stored, and pressing `m` again +decides. A file another program has left at the highest revision there is +still shows its notes but can take no further save: saving is refused as for a +damaged file, and the file is left as it was. + ## Position analysis Analyse a saved game, a record file (or standard input), or a position written in diff --git a/internal/app/app.go b/internal/app/app.go index c5050ea..85e6813 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -15,6 +15,7 @@ import ( "github.com/BAKocska/twixtui/internal/leaderboard" "github.com/BAKocska/twixtui/internal/netplay" "github.com/BAKocska/twixtui/internal/profile" + "github.com/BAKocska/twixtui/internal/study" "github.com/BAKocska/twixtui/internal/theme" "github.com/BAKocska/twixtui/internal/ui" ) @@ -28,6 +29,11 @@ type Deps struct { Profiles *profile.Store Board *leaderboard.Board Games *gamestore.Store + // Study keeps the notes and bookmarks a player writes on the entries of a + // replayed game, in a file beside the game rather than in its record. Nil + // means notes are not kept: the replay still opens, and says so when it + // is asked for one. + Study *study.Store Theme theme.Theme Styles *ui.Styles diff --git a/internal/app/replay.go b/internal/app/replay.go index bda5cd1..671a194 100644 --- a/internal/app/replay.go +++ b/internal/app/replay.go @@ -34,6 +34,9 @@ type ReplayScreen struct { stuck string // jump is the entry-number input, open only while a number is being typed. jump entryJump + // notes are the player's notes and bookmarks on this game's entries, and + // the note input while one is being written. See replay_study.go. + notes replayNotes // winning is the run of pegs that won the game, worked out once when the // screen opens: it cannot change, and it belongs to one position — the last // one, where the chain the record ends in is actually on the board. @@ -196,6 +199,8 @@ var replayKeys = []replayKey{ {ui.ActMoveUp, nil, "five", func(s *ReplayScreen) tea.Cmd { s.seek(s.step() - replayJump); return nil }}, {ui.ActEdgeTop, nil, "ends", func(s *ReplayScreen) tea.Cmd { s.seek(0); return nil }}, {ui.ActEdgeBottom, nil, "ends", func(s *ReplayScreen) tea.Cmd { s.seek(s.entries()); return nil }}, + {ui.ActNone, []string{"m"}, "mark", func(s *ReplayScreen) tea.Cmd { s.toggleBookmark(); return nil }}, + {ui.ActNone, []string{"e"}, "note", func(s *ReplayScreen) tea.Cmd { s.openNoteEditor(); return nil }}, {ui.ActQuit, []string{"esc"}, "leaves", func(*ReplayScreen) tea.Cmd { return Back() }}, } @@ -263,6 +268,7 @@ func NewReplayScreen(d Deps, saved gamestore.Saved) (Screen, error) { // reaches. A View that looked for it per frame would walk the link // graph of a 48-hole board on every keypress to draw the same holes. winning: winningChain(cursor.current()), + notes: openNotes(d.Study, saved, record, cursor.entries()), }, nil } @@ -277,10 +283,15 @@ func (s *ReplayScreen) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case tea.KeyPressMsg: return s, s.press(m) case tea.PasteMsg: - // The entry input is the only field on this screen, so a paste is a - // number for it or nothing at all. The spaces are what a paste out of a - // chat window brings with it; the digits are bounded and checked before - // any of them are kept. + // A paste goes to whichever field is open. The note input bounds and + // cleans what it is given itself. + if s.notes.editor.open { + s.notes.editor.insert(m.Content) + return s, nil + } + // The entry input takes a number or nothing at all. The spaces are + // what a paste out of a chat window brings with it; the digits are + // bounded and checked before any of them are kept. if s.jump.open { if len(m.Content) > entryPasteMax { s.jump.problem = fmt.Sprintf("max %d digits", s.jump.digits) @@ -305,6 +316,12 @@ func (s *ReplayScreen) press(m tea.KeyPressMsg) tea.Cmd { s.editEntry(m) return nil } + // The note input owns it for the same reason, and more of it: the letters + // of a note are every key this screen answers. + if s.notes.editor.open { + s.editNote(m) + return nil + } action := ui.ActNone // The control forms of a binding are the shell's: it answers them before // this screen is asked, so the footer does not name them and dispatch does @@ -439,30 +456,45 @@ func (s *ReplayScreen) focus() (game.Point, bool) { // keys do, dropped from the end when the terminal is too narrow for all of it. // // At the widths that have no room for a panel it is the whole of the interface, -// so the entry input is drawn here as well as there, and what is wrong with a -// number comes before the keys that would fix it. +// so an open input is drawn here as well as there, and what is wrong with a +// number, or what the notes refused, comes before the counter and the keys, +// which are what a narrow line gives up first. func (s *ReplayScreen) status(width int) string { // These are record entries rather than moves: a draw offer is an entry that // changes nothing on the board, so counting them as moves disagreed with // every other surface's move count. counter := fmt.Sprintf("step %d of %d", s.step(), s.entries()) - if s.jump.open { + parts := make([]string, 0, len(s.hints)+3) + hints := s.hints + switch { + case s.jump.open: note := s.jump.note() fieldWidth := max(3, width-ansi.StringWidth(note)-1) - input := note + " " + s.jump.edit.render(shellStyles(s.deps), fieldWidth) - return hintLine(width, input, counter, keyLabel(s.confirm...)+" jump", "esc cancel") + parts = append(parts, note+" "+s.jump.edit.render(shellStyles(s.deps), fieldWidth)) + hints = []string{keyLabel(s.confirm...) + " jump", "esc cancel"} + case s.notes.editor.open: + parts = append(parts, s.noteInput(width)) + hints = []string{keyLabel(s.confirm...) + " save", "esc cancel"} + } + // A part wider than the row is shortened here, with a mark, rather than + // clipped at the edge of the frame: the frame pulls a marked cut back to a + // whole word, and an unmarked one ends wherever the edge fell. + if note := s.studyStatus(); note != "" { + parts = append(parts, truncateText(note, width)) } - parts := make([]string, 0, len(s.hints)+1) parts = append(parts, counter) - return hintLine(width, append(parts, s.hints...)...) + return hintLine(width, append(parts, hints...)...) } // panel is the record beside the board: where in it the player is, what it came // to, and the entries themselves as a list to move through. // -// The list is promised its share of the rows before the prose is given any. The -// panel below a board is four rows at its smallest, and one that spent every row -// on titles and results would leave a review with nothing to review. +// The list is promised its share of the rows before anything else is given +// any. The panel below a board is four rows at its smallest, and one that spent +// every row on titles and results would leave a review with nothing to review. +// The study block comes next: it is built for every row the list leaves it and +// sets aside the rows it needs, so an open note input or a refusal is drawn +// whole wherever there is room for it, and the prose has what is left. func (s *ReplayScreen) panel(width, height int) []string { if width <= 0 || height <= 0 { return nil @@ -470,14 +502,22 @@ func (s *ReplayScreen) panel(width, height int) []string { out := make([]string, 0, height) // The input goes first because it is what the player is doing. out = append(out, clampLines(s.jump.lines(shellStyles(s.deps), width), height)...) - list := min(s.entries()+1, max(1, height/2)) - if room := height - len(out) - list; room > 1 { + list := s.listShare(height) + study := s.studyLines(width, s.studyRoom(width, height)) + if room := height - len(out) - list - s.studyReserve(width, study); room > 1 { out = append(out, clampLines(s.describe(width), room-1)...) out = append(out, "") } + if room := height - len(out) - list; room > 1 && len(study) > 0 { + out = append(out, cutRows(study, room-1, width)...) + out = append(out, "") + } return append(out, s.entryList(width, height-len(out))...) } +// listShare is the entry list's promised share of a panel height rows tall. +func (s *ReplayScreen) listShare(height int) int { return min(s.entries()+1, max(1, height/2)) } + // describe is the panel's prose, most useful line first, because a short panel // keeps the beginning of it and drops the end. func (s *ReplayScreen) describe(width int) []string { @@ -520,6 +560,9 @@ func (s *ReplayScreen) entryList(width, n int) []string { // they are padded on the right: the number belongs with the marker in front // of it, and a marker followed by blanks reads as a gap. digits := len(strconv.Itoa(s.entries())) + // The study's marks get a column of their own between the number and the + // label, and only once there is a mark to put in it. + flagged := s.notes.flagged() rows := make([]string, 0, n) for i := start; i < start+n; i++ { label := "opening position" @@ -532,7 +575,11 @@ func (s *ReplayScreen) entryList(width, n int) []string { if i == s.step() { marker = paint(st, &st.Cursor, "> ") } - rows = append(rows, marker+truncateText(padTo(strconv.Itoa(i), digits)+" "+label, max(0, width-2))) + number := padTo(strconv.Itoa(i), digits) + if flagged { + number += " " + s.notes.flags(i) + } + rows = append(rows, marker+truncateText(number+" "+label, max(0, width-2))) } return rows } diff --git a/internal/app/replay_study.go b/internal/app/replay_study.go new file mode 100644 index 0000000..ca56bfc --- /dev/null +++ b/internal/app/replay_study.go @@ -0,0 +1,648 @@ +package app + +import ( + "errors" + "fmt" + "slices" + "strings" + "unicode" + "unicode/utf8" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" + + "github.com/BAKocska/twixtui/internal/game" + "github.com/BAKocska/twixtui/internal/gamestore" + "github.com/BAKocska/twixtui/internal/study" + "github.com/BAKocska/twixtui/internal/ui" +) + +// The glyphs the entry list marks a study's entries with. They are characters +// rather than colours so that the marks survive colour being switched off, and +// ASCII so that every terminal draws them one cell wide. Neither is a character +// of the move notation, so a mark cannot be read as part of the entry beside it. +const ( + bookmarkGlyph = "*" + noteGlyph = "#" +) + +// replayNotes is the study kept beside a replayed game: the notes and bookmarks +// a player has put on its entries. It is read once, when the screen opens, and +// written one change at a time. +// +// The record itself is never written. The study is a file of its own, keyed by +// the game's identifier and the record's digest, so a record that has changed +// since the notes were written refuses them rather than showing notes about a +// game that is no longer the one on screen. +type replayNotes struct { + store *study.Store + target study.Target + // doc is the study as the store last reported it. Every write is made + // against its revision, so a write that another window got in first is + // refused instead of being laid over it. + doc study.Study + // locked is why nothing may be written here, or nil when writing is + // allowed: there is no store, the notes could not be read, or the game has + // no result yet. + locked studyNotice + // problem is what the last request made of the notes ran into, and + // problemAt the entry it was made on. It is shown on that entry only, + // because a refusal belongs to what was asked, and the next entry was not + // asked about. + problem studyNotice + problemAt int + // editor is the note being written, open only while one is. + editor noteEditor +} + +// openNotes finds the study of the game being replayed. Nothing about it stops +// the replay: a study that cannot be read leaves the review as it was and the +// notes read-only, with the reason in the panel, and the file exactly as it was +// found, so the program that can read it still finds it there. +func openNotes(store *study.Store, saved gamestore.Saved, record game.Record, entries int) replayNotes { + n := replayNotes{ + store: store, + target: study.Target{ + GameID: saved.ID, + RecordDigest: record.Digest, + Entries: entries, + // The record's own result decides, as it does for the game store: + // the label beside it is covered by no digest. + Finished: record.Outcome != game.Ongoing, + }, + } + if store == nil { + n.locked = studyNotice{"notes are unavailable here", "no notes here"} + return n + } + doc, err := store.Load(n.target) + if err != nil { + n.locked = studyRefusal(err) + return n + } + n.doc = doc + if !n.target.Finished { + n.locked = studyRefusal(study.ErrUnfinished) + } + return n +} + +// studyNotice is something the notes tell the player, in forms that run from +// the whole sentence down to the few words a status line holds at the +// narrowest size, widest first. The panel has room for the first. The status +// line, which is all there is beside the board at the sizes with no room for +// a panel, takes the widest that fits whole, so a reason is shortened by +// saying less rather than by being cut off in the middle of a word. +type studyNotice []string + +// full is the whole of it, which is what the panel shows. +func (n studyNotice) full() string { + if len(n) == 0 { + return "" + } + return n[0] +} + +// brief is its shortest form, which a status line has room for at the +// narrowest size a board is drawn at. +func (n studyNotice) brief() string { + if len(n) == 0 { + return "" + } + return n[len(n)-1] +} + +// fit is the widest form that fits in width cells, or the shortest one cut to +// width with a mark when none does. +func (n studyNotice) fit(width int) string { + for _, form := range n { + if ansi.StringWidth(form) <= width { + return form + } + } + return truncateText(n.brief(), width) +} + +// of is the notice as the refusal of what was asked: named in front of the +// reason while there is room for both, and the reason alone at the narrowest, +// because the reason is what the player cannot work out for themselves. +func (n studyNotice) of(what string) studyNotice { + return studyNotice{what + ": " + n.full(), what + ": " + n.brief(), n.brief()} +} + +// studyRefusal says in the player's terms why the store would not read or +// write the notes. For the three refusals of a file it could not use, it also +// says what became of the file, which is nothing: the player's notes are +// somewhere, and knowing they were left alone is what makes the refusal +// something other than a loss. The brief form keeps only the reason. +func studyRefusal(err error) studyNotice { + var why, brief string + switch { + case errors.Is(err, study.ErrRecordChanged): + why, brief = "the notes were written for a different record of this game and are left as they are", "record changed" + case errors.Is(err, study.ErrNewerVersion): + why, brief = "the notes were written by a newer twixtui and are left as they are", "newer twixtui" + case errors.Is(err, study.ErrCorrupt): + why, brief = "the notes file is damaged and is left as it is", "notes damaged" + case errors.Is(err, study.ErrUnfinished): + why, brief = "notes are kept on finished games only", "unfinished game" + default: + // The remaining errors carry paths and identifiers, which are text + // from this machine rather than from the program, and drawn as such. + // None of that fits in a few words, so the brief form says only + // where the trouble is and leaves the rest to the panel. + why, brief = err.Error(), "notes file error" + } + return studyNotice{replayLabel(why), brief} +} + +// refuse records what a request on entry ran into. +func (n *replayNotes) refuse(entry int, why studyNotice) { n.problem, n.problemAt = why, entry } + +// flagged reports whether the entry list needs its column of marks at all. A +// game nobody has written on keeps the list it always had, and every cell of +// it goes to the entries. +func (n *replayNotes) flagged() bool { return len(n.doc.Marks) > 0 } + +// flags is an entry's two cells in that column: the bookmark glyph, then the +// note glyph, each a blank when the entry has no such thing. +func (n *replayNotes) flags(entry int) string { + mark := n.doc.At(entry) + bookmark, note := " ", " " + if mark.Bookmark { + bookmark = bookmarkGlyph + } + if mark.Note != "" { + note = noteGlyph + } + return bookmark + note +} + +// toggleBookmark puts a bookmark on the entry on screen, or takes it off, and +// saves at once: a bookmark is one keypress, and a second one to confirm it +// would be a form around a single bit. +func (s *ReplayScreen) toggleBookmark() { + n := &s.notes + entry := s.step() + if n.locked != nil { + n.refuse(entry, n.locked.of("bookmark unchanged")) + return + } + // The note travels with the bookmark because a mark is saved whole. It is + // the note of the revision the write is made against, so a note saved + // elsewhere since cannot be put back to what this screen remembered: that + // write is the one refused as stale. + mark := n.doc.At(entry) + mark.Entry, mark.Bookmark = entry, !mark.Bookmark + doc, err := n.store.Set(n.target, n.doc.Revision, mark) + switch { + case errors.Is(err, study.ErrStale): + // The press is not repeated on the player's behalf. What is stored + // now is shown, and the player decides whether it still wants the + // change. + n.doc = doc + n.refuse(entry, studyNotice{ + "the notes were changed elsewhere and are shown as they are now; press again to change it", + "changed elsewhere", + }.of("bookmark unchanged")) + case err != nil: + n.refuse(entry, studyRefusal(err).of("bookmark unchanged")) + default: + n.doc = doc + n.problem = nil + } +} + +// openNoteEditor opens the note input on the entry on screen, holding that +// entry's note as it is stored, so that editing a note starts from the note. +func (s *ReplayScreen) openNoteEditor() { + n := &s.notes + entry := s.step() + if n.locked != nil { + n.refuse(entry, n.locked.of("no note written")) + return + } + n.problem = nil + n.editor.start(entry, n.doc.At(entry).Note) +} + +// editNote hands one key to the note input: the note is saved, the input is +// abandoned, or the key is text or the field's own editing. +func (s *ReplayScreen) editNote(m tea.KeyPressMsg) { + switch key := m.String(); { + case key == "esc": + // Escape abandons the note and writes nothing. Whatever is stored is + // left as it was, including a version that a refused save has just + // put on screen. + s.notes.editor.cancel() + case matchesKey(key, s.confirm): + s.saveNote() + default: + s.notes.editor.key(m) + } +} + +// saveNote writes the note being edited against the revision the screen last +// read. +// +// Only a write that is taken closes the editor. A refused one leaves the text +// where it was typed, because nothing the player wrote should be lost to a +// store that said no. A write refused because the notes changed elsewhere reads +// what is stored now and shows it under the field, so that the next save is a +// decision made with both versions on screen rather than an overwrite nobody saw +// happen. +// +// That decision is only one while the stored note is on screen whole, so the +// next save is taken only then. A terminal with no room for a panel, or with a +// panel too short or too narrow for all of the note, gets a refusal that says +// so instead, and the player's text stays in the field until the terminal is +// enlarged or the input is abandoned. +func (s *ReplayScreen) saveNote() { + n := &s.notes + e := &n.editor + mark := n.doc.At(e.entry) + text := e.edit.value() + if text == mark.Note { + // Nothing changed, so there is nothing to write: a revision records a + // change, and another window's next save would be refused over none. + e.cancel() + return + } + if e.stale && !s.storedOnScreen() { + // Nothing is written. The input's own note is what says why, so a + // problem left standing from the text is cleared out of its way. + e.problem = nil + return + } + mark.Entry, mark.Note = e.entry, text + doc, err := n.store.Set(n.target, n.doc.Revision, mark) + switch { + case errors.Is(err, study.ErrStale): + n.doc = doc + e.stale = true + e.problem = nil + case err != nil: + e.problem = studyRefusal(err).of("not saved") + default: + n.doc = doc + e.cancel() + } +} + +// studyKept is how many rows of what the notes say about the entry on screen +// are kept from the record's prose in a short panel. The prose is ordered most +// useful line first and loses its tail gracefully; a note the player wrote on +// the entry they are looking at is the reason they came back to it. +const studyKept = 2 + +// studyReserve is how many of the study block's rows are set aside before the +// record's prose is given any, counting the blank line that closes the block. +// The note input is what the player is doing while it is open, and a refusal +// is the answer to what they last asked, so all of either is set aside, the +// way the entry input's rows are; of anything else in the block, the first +// studyKept rows are. +func (s *ReplayScreen) studyReserve(width int, block []string) int { + switch { + case len(block) == 0: + return 0 + case s.notes.editor.open: + return len(block) + 1 + } + return min(len(block), len(s.refusalLines(width))+studyKept) + 1 +} + +// studyRoom is how many rows the study block may take in a panel width cells +// wide and height rows tall: every row above the entry list's promised share, +// less the entry input's and the blank line that closes the block. The block +// is given its rows before the record's prose is given any, so these are the +// rows it is drawn in whenever it needs all of them, which is what lets a save +// be judged on whether they hold the stored note. +func (s *ReplayScreen) studyRoom(width, height int) int { + return height - len(s.jump.lines(shellStyles(s.deps), width)) - s.listShare(height) - 1 +} + +// studyLines is the study block in the panel: the note input while it is open, +// otherwise whatever the notes have to say about the entry on screen — a +// refusal, whether it is bookmarked, and its note. +// +// A note is text from a file, which another program or a hand edit may have +// written anything into, so it is drawn inert, and a note longer than the rows +// it is given is cut with a mark saying so. +func (s *ReplayScreen) studyLines(width, rows int) []string { + if width <= 0 || rows <= 0 { + return nil + } + n := &s.notes + if n.editor.open { + // The note stored now is drawn only when all of it fits in these + // rows, which is the test a save is held to as well. + shown := n.storedFits(width, rows) + return clampLines(n.editorLines(shellStyles(s.deps), width, shown), rows) + } + lines := s.refusalLines(width) + mark := n.doc.At(s.step()) + if mark.Bookmark { + lines = append(lines, truncateText(bookmarkGlyph+" bookmarked", width)) + } + if mark.Note != "" { + lines = append(lines, wrapText(noteGlyph+" note: "+replayLabel(mark.Note), width)...) + } + return cutRows(lines, rows, width) +} + +// refusalLines is the refusal the study block opens with: what the last +// request made on the entry on screen ran into, or else why nothing may be +// written here at all. +func (s *ReplayScreen) refusalLines(width int) []string { + n := &s.notes + switch { + case n.problem != nil && n.problemAt == s.step(): + return wrapText(n.problem.full(), width) + case n.locked != nil && n.store != nil: + // A screen without a store has nothing to report until it is asked: + // that is a caller that keeps no notes, not a game whose notes are + // being withheld. + return wrapText(n.locked.full(), width) + } + return nil +} + +// studyStatus is what the notes have to say on the status line: the refusal of +// the last request made on the entry on screen, in the few words the line has +// room for. At the sizes with no room for a panel the line is the whole of the +// interface beside the board, and a refusal said only in a panel that is not +// drawn is a key that does nothing without saying why. +func (s *ReplayScreen) studyStatus() string { + n := &s.notes + if n.problem == nil || n.problemAt != s.step() { + return "" + } + return n.problem.brief() +} + +// editorLines are the note input's rows: the field, then editorText. +func (n *replayNotes) editorLines(st *ui.Styles, width int, shown bool) []string { + return append([]string{n.editor.render(st, width)}, n.editorText(width, shown)...) +} + +// editorText is the note input's rows under the field: what the input says +// about itself and, once a save has found the notes changed elsewhere and +// shown is set, the note that is stored now. +func (n *replayNotes) editorText(width int, shown bool) []string { + e := &n.editor + said, _ := e.note(shown) + lines := wrapText(said.full(), width) + if e.stale && shown { + stored := "stored now: no note" + if note := n.doc.At(e.entry).Note; note != "" { + stored = "stored now: " + replayLabel(note) + } + // A cell short of the width, because the frame shortens a line that + // fills its width and ends in the truncation mark back to its last + // whole word, and a stored note may well end in that character: the + // word it took would be one the player never saw. + lines = append(lines, wrapText(stored, width-1)...) + } + return lines +} + +// storedFits reports whether rows rows of width cells hold the note input with +// the note stored now whole beneath it: the field, what the input says about +// itself, and every line of the stored note. It is the one measure of that. +// The input draws the stored note only when it passes, and a save may replace +// the note only when the rows the terminal's size gives the input pass it +// too, so the two cannot disagree about what the player has seen. +// +// The note is wrapped a cell short of width, and the widest character is two +// cells, so nothing narrower than three cells can hold every character of it. +func (n *replayNotes) storedFits(width, rows int) bool { + return n.editor.stale && width > 2 && 1+len(n.editorText(width, true)) <= rows +} + +// storedOnScreen reports whether the frame the terminal's size gives draws the +// note stored now whole. The frame is arranged from the size the screen was +// last given, as View arranges it, so a save is judged in Update on the frame +// the player is looking at rather than on whatever a View last happened to +// draw. Without a panel there is only the status line beside the board, and +// the stored note is not on it. +func (s *ReplayScreen) storedOnScreen() bool { + arr := ui.Arrange(s.width, s.height, s.current().Size()) + if arr.TooSmall || arr.Panel == ui.PanelNone { + return false + } + return s.notes.storedFits(arr.PanelW, s.studyRoom(arr.PanelW, arr.PanelH)) +} + +// noteInput is the note input as the status line draws it. At the widths that +// have no room for a panel it is the whole of the interface, as it is for the +// entry input, so the field is drawn here too, after what the input says about +// itself in the widest form that fits whole. +// +// While that is only which entry the note is for, the field keeps at least +// half the row. A refusal outranks the field, as the entry input's problem +// does: the player has to act on it before the text in the field can go +// anywhere, so the field then keeps only the room its prompt and caret need. +func (s *ReplayScreen) noteInput(width int) string { + e := &s.notes.editor + st := shellStyles(s.deps) + said, refused := e.note(e.stale && s.storedOnScreen()) + least := width / 2 + if refused { + least = min(3, width) + } + label := said.fit(width - least - 1) + if label == "" { + return e.render(st, width) + } + return label + " " + e.render(st, width-ansi.StringWidth(label)-1) +} + +// cutRows keeps the first rows lines, marking the last one kept when some were +// dropped, so a note cut short reads as cut rather than as ending there. +func cutRows(lines []string, rows, width int) []string { + if len(lines) <= rows { + return lines + } + lines = lines[:rows] + lines[rows-1] = ansi.Truncate(lines[rows-1], max(0, width-1), "") + ellipsis + return lines +} + +// noteEditor is the note input, which the e key opens on the entry on screen. +// +// It is modal for the reason the entry input is: a note is text, and the +// letters in it are the keys that move a review and leave it. A screen that +// went on answering them would step away from the entry being written about at +// the first h, and leave altogether at the first q. +type noteEditor struct { + open bool + // entry is the entry the note is about, fixed when the input opens, so + // that the note is saved where it was begun. + entry int + edit lineEdit + // problem is why the last save or the last text was refused. It stands + // until the text changes, because a message cleared by the next keypress is + // gone before it has been read. + problem studyNotice + // stale is set once a save has found the notes changed elsewhere. From + // then on the stored note is shown under the field wherever there is room + // for all of it, so both versions are in front of the player when they + // choose which one to keep, and a save is refused wherever there is not. + stale bool +} + +// start opens the input on entry, holding note. +func (e *noteEditor) start(entry int, note string) { + *e = noteEditor{open: true, entry: entry} + e.edit.setValue(note) +} + +// cancel closes the input, forgetting what was typed. +func (e *noteEditor) cancel() { *e = noteEditor{} } + +// key applies a keypress: text is inserted or refused, and anything else is +// the field's own editing and movement. +func (e *noteEditor) key(m tea.KeyPressMsg) { + if m.Text != "" { + e.insert(m.Text) + return + } + if e.edit.key(m) { + e.problem = nil + } +} + +// size is how many bytes the note holds as UTF-8, which is what its bound is +// counted in. +func (e *noteEditor) size() int { + n := 0 + for _, r := range e.edit.runes { + n += utf8.RuneLen(r) + } + return n +} + +// insert takes typed or pasted text. A paste is text from anywhere and can be +// a whole file, so what arrived is measured against the room left before any +// of it is copied, and what is kept is measured again: a byte that is not +// UTF-8 is kept as a replacement character, which is three bytes long. +func (e *noteEditor) insert(text string) { + room := study.MaxNoteBytes - e.size() + if len(text) > room { + e.problem = noteTooLong() + return + } + text = noteText(text) + if len(text) > room { + e.problem = noteTooLong() + return + } + if text == "" { + return + } + e.edit.insert(text) + e.problem = nil +} + +// noteTooLong is the refusal of text that would take a note past its bound. +func noteTooLong() studyNotice { + kib := study.MaxNoteBytes >> 10 + return studyNotice{fmt.Sprintf("a note holds at most %d KiB", kib), fmt.Sprintf("%d KiB at most", kib)} +} + +// noteText is typed or pasted text as the one-line field keeps it. Line breaks +// and tabs become spaces, since the field has one line to show them on, and the +// other control characters are dropped: nothing typed at a keyboard means them +// as part of a note. strings.Map also replaces any byte that is not UTF-8 with +// the replacement character, so what is kept is text a note may hold. +func noteText(text string) string { + return strings.Map(func(r rune) rune { + switch { + case unicode.IsSpace(r): + return ' ' + case unicode.IsControl(r): + return -1 + } + return r + }, text) +} + +// What the input says once a save has found the notes changed elsewhere: that +// the note stored now is shown beneath the field and the next save replaces +// it, or, where there is no room to show all of it, that the next save is +// refused and what will let it be taken. The shortest form of the first +// points at the panel, which is where the note is whenever it is shown. +var ( + staleShown = studyNotice{ + "the note was changed elsewhere and is shown below; saving again replaces it", + "changed elsewhere: saving replaces it", + "save replaces it", + "see above", + } + staleHidden = studyNotice{ + "not saved: the note was changed elsewhere and cannot be shown whole at this size; " + + "enlarge the terminal to compare the two, or press esc to keep it", + "not saved: changed elsewhere; enlarge to compare, or esc to keep it", + "changed elsewhere: enlarge or esc", + "enlarge or esc", + } +) + +// note is what the input says about itself: the problem while there is one, +// then the other version while there is one, and otherwise which entry the note +// is for. shown is whether the stored note is drawn whole beneath the field. +// It also reports whether what it says is a refusal the player has to act on, +// which the entry number is not and the other version on screen is not +// either. The keys that save and cancel are on the status line. +func (e *noteEditor) note(shown bool) (studyNotice, bool) { + switch { + case e.problem != nil: + return e.problem, true + case e.stale && shown: + return staleShown, false + case e.stale: + return staleHidden, true + } + about := fmt.Sprintf("entry %d", e.entry) + return studyNotice{"note on " + about, about}, false +} + +// render draws the field in width cells. +// +// What the field holds is drawn inert. A note another program wrote can carry +// line breaks and escape sequences, and the field keeps them as they are, so +// that saving a note the player has only added to does not rewrite the parts +// they never touched. The copy that is drawn has them made safe instead, split +// at the caret so the caret stays where it is in the text. +func (e *noteEditor) render(st *ui.Styles, width int) string { + if !slices.ContainsFunc(e.edit.runes, unsafeInNote) { + return e.edit.render(st, width) + } + head := inertRunes(e.edit.runes[:e.edit.pos]) + shown := lineEdit{runes: append(head, inertRunes(e.edit.runes[e.edit.pos:])...), pos: len(head)} + return shown.render(st, width) +} + +// unsafeInNote reports a rune a terminal would act on rather than draw, or +// would draw as something other than the single space it stands for. +func unsafeInNote(r rune) bool { + return r != ' ' && (unicode.IsSpace(r) || unicode.IsControl(r) || unicode.Is(unicode.Cf, r)) +} + +// inertRunes is replayLabel for the field: spacing becomes a space and the +// characters a terminal would obey are dropped. Nothing is collapsed, and the +// two sides of the caret are made safe separately, so the caret is drawn +// between the same two characters it sits between in the note. +func inertRunes(runes []rune) []rune { + out := make([]rune, 0, len(runes)) + for _, r := range runes { + switch { + case unicode.IsSpace(r): + out = append(out, ' ') + case unicode.IsControl(r), unicode.Is(unicode.Cf, r): + default: + out = append(out, r) + } + } + return out +} diff --git a/internal/app/replay_study_test.go b/internal/app/replay_study_test.go new file mode 100644 index 0000000..c9a19c3 --- /dev/null +++ b/internal/app/replay_study_test.go @@ -0,0 +1,970 @@ +package app + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "regexp" + "slices" + "strconv" + "strings" + "testing" + "unicode" + "unicode/utf8" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" + + "github.com/BAKocska/twixtui/internal/game" + "github.com/BAKocska/twixtui/internal/gamestore" + "github.com/BAKocska/twixtui/internal/study" + "github.com/BAKocska/twixtui/internal/ui" +) + +// snDeps is the shell's test collaborators with a study store beside the games, +// in the same temporary configuration directory. +func snDeps(t *testing.T) Deps { + t.Helper() + d := shellTestDeps(t) + d.Study = study.Open(d.ConfigDir) + return d +} + +// snTarget names a saved game's study the way the product does: by the game's +// identifier and the digest of the record it holds. +func snTarget(t *testing.T, sv gamestore.Saved) study.Target { + t.Helper() + rec, err := game.DecodeRecord(sv.Record) + if err != nil { + t.Fatal(err) + } + return study.Target{ + GameID: sv.ID, + RecordDigest: rec.Digest, + Entries: rec.Entries, + Finished: rec.Outcome != game.Ongoing, + } +} + +// snLoad reads a study back through a store of its own, which is what another +// window, or the next launch, sees. +func snLoad(t *testing.T, d Deps, target study.Target) study.Study { + t.Helper() + doc, err := study.Open(d.ConfigDir).Load(target) + if err != nil { + t.Fatalf("loading the study back: %v", err) + } + return doc +} + +// snFile is the study file of one game, and snBytes its contents, nil when +// there is no such file. +func snFile(d Deps, id string) string { return filepath.Join(d.Study.Dir(), id+".json") } + +func snBytes(t *testing.T, path string) []byte { + t.Helper() + b, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + t.Fatal(err) + } + return b +} + +// snType presses one key per character, and fails the moment one of them does +// anything to the review behind the note input: leaves it, moves it, or closes +// the input. +func snType(t *testing.T, s *ReplayScreen, text string) { + t.Helper() + step := s.step() + for _, r := range text { + if _, cmd := s.Update(tutorialKeyMsg(string(r))); cmd != nil { + t.Fatalf("typing %q into the note left the screen at %q", text, r) + } + if s.step() != step { + t.Fatalf("typing %q into the note moved the review from step %d to %d at %q", text, step, s.step(), r) + } + if !s.notes.editor.open { + t.Fatalf("typing %q into the note closed the input at %q", text, r) + } + } +} + +// snWriteNote does what a player does to put a note on the entry on screen: +// open the input, clear what it holds, type, confirm. +func snWriteNote(t *testing.T, s *ReplayScreen, text string) { + t.Helper() + s.Update(tutorialKeyMsg("e")) + if !s.notes.editor.open { + t.Fatalf("e did not open the note input on step %d:\n%s", s.step(), s.View().Content) + } + s.Update(tutorialKeyMsg("ctrl+u")) + snType(t, s, text) + if _, cmd := s.Update(tutorialKeyMsg("enter")); cmd != nil { + t.Fatal("saving the note left the screen") + } +} + +// snRow is one row of the entry list once the study's column is drawn in it. +type snRow struct { + number int + marked bool + bookmark bool + noted bool + label string +} + +// snRows reads the list out of panel lines when it carries the study column: +// the marker, the number padded to digits, the two mark cells, the label. A +// list without the column has no rows under this pattern, which is how a test +// tells the column is gone. +func snRows(t *testing.T, lines []string, digits int) []snRow { + t.Helper() + pattern := regexp.MustCompile(`^(> | )(\d[\d ]{` + strconv.Itoa(digits-1) + `}) ([* ])([# ]) (\S.*?)\s*$`) + var rows []snRow + for _, l := range lines { + m := pattern.FindStringSubmatch(l) + if m == nil { + continue + } + n, err := strconv.Atoi(strings.TrimSpace(m[2])) + if err != nil { + t.Fatalf("entry row %q: %v", l, err) + } + rows = append(rows, snRow{ + number: n, marked: m[1] == "> ", bookmark: m[3] == bookmarkGlyph, noted: m[4] == noteGlyph, label: m[5], + }) + } + return rows +} + +// snAssertMarks holds a study to exactly the marks a scenario put in it. +func snAssertMarks(t *testing.T, doc study.Study, want ...study.Mark) { + t.Helper() + if !slices.Equal(doc.Marks, want) { + t.Fatalf("the study holds %+v, want %+v", doc.Marks, want) + } +} + +// TestReplayNoteStaysOnTheEntryItWasWrittenOn is the note's whole identity: it +// belongs to an entry, and in a record with draw offers in it an entry is not a +// ply. Entry 4 of the fixture is a draw offer with one move played, so a note +// filed by ply lands on entry 1, and one filed a step either side of where it +// was written turns up on 3 or 5. +func TestReplayNoteStaysOnTheEntryItWasWrittenOn(t *testing.T) { + d := snDeps(t) + sv := rpConnectionRecord(t) + if err := d.Games.Put(sv); err != nil { + t.Fatal(err) + } + gameFile := filepath.Join(d.Games.Dir(), sv.ID+".json") + gameBefore := snBytes(t, gameFile) + if gameBefore == nil { + t.Fatal("the saved game was not written where the store keeps it") + } + + const note = "the offer, not the ply" + s := rpSized(t, d, sv, 120, 30) + rpJump(t, s, "4") + if s.current().Ply() == 4 { + t.Fatal("the fixture's entry 4 is also its fourth move, which separates nothing") + } + snWriteNote(t, s, note) + if s.notes.editor.open { + t.Fatalf("the note input is still open after a save:\n%s", s.View().Content) + } + snAssertMarks(t, snLoad(t, d, snTarget(t, sv)), study.Mark{Entry: 4, Note: note}) + + // A screen opened afresh, which is what leaving and coming back is, opens + // at the end and finds the note on entry 4 and nowhere else. + again := rpSized(t, d, sv, 120, 30) + if strings.Contains(again.View().Content, note) { + t.Errorf("the note is drawn at step %d, where it was not written", again.step()) + } + for _, c := range []struct { + entry string + want bool + }{{"3", false}, {"4", true}, {"5", false}, {"1", false}} { + rpJump(t, again, c.entry) + if got := strings.Contains(again.View().Content, note); got != c.want { + t.Errorf("at entry %s the note is drawn: %v, want %v:\n%s", c.entry, got, c.want, again.View().Content) + } + } + rpJump(t, again, "4") + lines := again.panel(36, 29) + rows := snRows(t, lines, 2) + if len(rows) == 0 { + t.Fatalf("the list has no column for the study's marks:\n%s", strings.Join(lines, "\n")) + } + for _, r := range rows { + if r.noted != (r.number == 4) || r.bookmark { + t.Errorf("row %d is drawn noted=%v bookmarked=%v; only entry 4 has a note, and nothing a bookmark:\n%s", + r.number, r.noted, r.bookmark, strings.Join(lines, "\n")) + } + } + + if after := snBytes(t, gameFile); !bytes.Equal(after, gameBefore) { + t.Errorf("writing a note rewrote the saved game:\nbefore: %s\nafter: %s", gameBefore, after) + } +} + +// TestReplayBookmarkTogglesAndMarksItsRow is the other half of a mark: one key +// on and the same key off, each saved at once, and the list showing it on the +// row it was put on in this window and the next. +func TestReplayBookmarkTogglesAndMarksItsRow(t *testing.T) { + d := snDeps(t) + sv := rpConnectionRecord(t) + target := snTarget(t, sv) + + s := rpSized(t, d, sv, 120, 30) + rpJump(t, s, "9") + s.Update(tutorialKeyMsg("m")) + snAssertMarks(t, snLoad(t, d, target), study.Mark{Entry: 9, Bookmark: true}) + + check := func(what string, lines []string, cursor int) { + t.Helper() + rows := snRows(t, lines, 2) + found := false + for _, r := range rows { + if r.bookmark != (r.number == 9) || r.noted { + t.Errorf("%s: row %d is drawn bookmarked=%v noted=%v:\n%s", what, r.number, r.bookmark, r.noted, strings.Join(lines, "\n")) + } + if r.marked && r.number != cursor { + t.Errorf("%s: the review is on %d but row %d is marked", what, cursor, r.number) + } + found = found || r.number == 9 + } + if !found { + t.Fatalf("%s: row 9 is not in the list:\n%s", what, strings.Join(lines, "\n")) + } + } + check("the window that marked it", s.panel(36, 29), 9) + + // A new window opens at the final entry. The bookmark stays on row 9 and + // does not follow the cursor. + again := rpSized(t, d, sv, 120, 30) + check("a new window", again.panel(36, 29), 17) + + rpJump(t, again, "9") + again.Update(tutorialKeyMsg("m")) + doc := snLoad(t, d, target) + snAssertMarks(t, doc) + if doc.Revision != 2 { + t.Errorf("two saves left the study at revision %d, want 2", doc.Revision) + } + // With nothing marked the column is gone, and every row is its entry + // again. + for _, lines := range [][]string{again.panel(36, 29), rpSized(t, d, sv, 120, 30).panel(36, 29)} { + if rows := snRows(t, lines, 2); len(rows) != 0 { + t.Errorf("the list keeps a column of marks with none in it:\n%s", strings.Join(lines, "\n")) + } + for _, r := range rpEntryRows(t, lines) { + if strings.HasPrefix(r.label, bookmarkGlyph) { + t.Errorf("row %d still carries a bookmark: %q", r.number, r.label) + } + } + } +} + +// TestReplayEscapeAbandonsANoteWithoutWriting is the input's way out: escape +// writes nothing at all — no file where there was none, and not a byte changed +// where there was one — and leaves the note that was stored on screen. +func TestReplayEscapeAbandonsANoteWithoutWriting(t *testing.T) { + d := snDeps(t) + sv := rpConnectionRecord(t) + s := rpSized(t, d, sv, 120, 30) + rpJump(t, s, "2") + + s.Update(tutorialKeyMsg("e")) + snType(t, s, "a first draft") + if _, cmd := s.Update(tutorialKeyMsg("esc")); cmd != nil { + t.Fatal("escape left the review instead of the note input") + } + if s.notes.editor.open || s.step() != 2 { + t.Fatalf("escape left the input open=%v at step %d", s.notes.editor.open, s.step()) + } + if _, err := os.Stat(d.Study.Dir()); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("an abandoned note left something in %s: %v", d.Study.Dir(), err) + } + + snWriteNote(t, s, "kept") + path := snFile(d, sv.ID) + before := snBytes(t, path) + if before == nil { + t.Fatal("a saved note left no study file") + } + s.Update(tutorialKeyMsg("e")) + snType(t, s, " and more") + s.Update(tutorialKeyMsg("esc")) + if after := snBytes(t, path); !bytes.Equal(after, before) { + t.Fatalf("escape rewrote the study:\nbefore: %s\nafter: %s", before, after) + } + frame := s.View().Content + if !strings.Contains(frame, "kept") || strings.Contains(frame, "and more") { + t.Errorf("after escape the frame should show the stored note and not the abandoned one:\n%s", frame) + } + snAssertMarks(t, snLoad(t, d, snTarget(t, sv)), study.Mark{Entry: 2, Note: "kept"}) +} + +// TestReplayStaleSaveKeepsBothVersions is two windows on one game. The second +// saves between the first one loading and saving, and the first one's save has +// to be refused rather than laid over it: the file keeps the other window's +// note, the input keeps this one's, both are on screen, and only a second +// confirmation — made with both in view — replaces the stored one. +func TestReplayStaleSaveKeepsBothVersions(t *testing.T) { + d := snDeps(t) + sv := rpConnectionRecord(t) + target := snTarget(t, sv) + path := snFile(d, sv.ID) + + s := rpSized(t, d, sv, 120, 30) + rpJump(t, s, "4") + other := study.Open(d.ConfigDir) + if _, err := other.Set(target, 0, study.Mark{Entry: 4, Note: "theirs"}); err != nil { + t.Fatal(err) + } + stored := snBytes(t, path) + + s.Update(tutorialKeyMsg("e")) + snType(t, s, "mine") + s.Update(tutorialKeyMsg("enter")) + if !s.notes.editor.open { + t.Fatal("a save refused as stale closed the note input") + } + if got := s.notes.editor.edit.value(); got != "mine" { + t.Fatalf("a refused save left the input holding %q, want what was typed", got) + } + if after := snBytes(t, path); !bytes.Equal(after, stored) { + t.Fatalf("a stale save overwrote the other window's note:\nbefore: %s\nafter: %s", stored, after) + } + frame := s.View().Content + if !strings.Contains(frame, "mine") || !strings.Contains(frame, "theirs") { + t.Fatalf("the refused save does not show both versions:\n%s", frame) + } + + // Confirming again is the decision, taken with both on screen, and it is + // made against the revision that is stored now. + s.Update(tutorialKeyMsg("enter")) + if s.notes.editor.open { + t.Fatalf("the second save was refused as well:\n%s", s.View().Content) + } + doc := snLoad(t, d, target) + snAssertMarks(t, doc, study.Mark{Entry: 4, Note: "mine"}) + if doc.Revision != 2 { + t.Errorf("the study is at revision %d after two saves, want 2", doc.Revision) + } + + // A bookmark pressed against a revision another window has moved past is + // refused the same way, and the window then shows what is stored. + if _, err := other.Set(target, 2, study.Mark{Entry: 9, Bookmark: true}); err != nil { + t.Fatal(err) + } + stored = snBytes(t, path) + rpJump(t, s, "9") + before := s.View().Content + s.Update(tutorialKeyMsg("m")) + if after := snBytes(t, path); !bytes.Equal(after, stored) { + t.Fatalf("a stale bookmark rewrote the study:\nbefore: %s\nafter: %s", stored, after) + } + if s.View().Content == before { + t.Error("a refused bookmark changed nothing on screen") + } + rows := snRows(t, s.panel(36, 29), 2) + if i := slices.IndexFunc(rows, func(r snRow) bool { return r.number == 9 }); i < 0 || !rows[i].bookmark { + t.Errorf("after the refusal the list does not show the bookmark that is stored on entry 9: %+v", rows) + } + if doc := snLoad(t, d, target); doc.Revision != 3 { + t.Errorf("the study moved to revision %d on a refused bookmark, want 3", doc.Revision) + } +} + +// TestReplayStaleNoteIsReplacedOnlyWhenShownWhole is the refused save at the +// sizes a player may be reading it in. A second confirm is a choice between +// two versions only while both are on screen, so at each size either every +// word of the other window's note is in the frame and confirming again +// replaces it, or some of it is not and confirming again writes nothing, keeps +// what was typed and says why. The sizes are the supported ones — the smallest +// has no panel at all, the next a panel too short for the note — and two +// panels under the board narrower than the one beside it, where the note wraps +// onto more rows than anywhere else. +func TestReplayStaleNoteIsReplacedOnlyWhenShownWhole(t *testing.T) { + const theirs = "theirs-1 theirs-2 theirs-3 theirs-4 theirs-5 theirs-6 theirs-7" + sv := rpConnectionRecord(t) + target := snTarget(t, sv) + // unseen is the first word of the other note the frame does not show, or + // nothing when it shows all of them. + unseen := func(frame string) string { + for _, word := range strings.Fields(theirs) { + if !strings.Contains(frame, word) { + return word + } + } + return "" + } + var shown, hidden int + for _, size := range append(slices.Clone(shellSizes), [2]int{24, 30}, [2]int{20, 40}) { + w, h := size[0], size[1] + d := snDeps(t) + path := snFile(d, sv.ID) + s := rpSized(t, d, sv, w, h) + rpJump(t, s, "4") + if _, err := study.Open(d.ConfigDir).Set(target, 0, study.Mark{Entry: 4, Note: theirs}); err != nil { + t.Fatal(err) + } + stored := snBytes(t, path) + + s.Update(tutorialKeyMsg("e")) + snType(t, s, "mine") + s.Update(tutorialKeyMsg("enter")) + if !s.notes.editor.open { + t.Fatalf("at %dx%d a save refused as stale closed the note input", w, h) + } + frame := s.View().Content + shellAssertFits(t, "a note refused as stale", frame, w, h) + missing := unseen(frame) + + s.Update(tutorialKeyMsg("enter")) + if missing == "" { + shown++ + if s.notes.editor.open { + t.Errorf("at %dx%d the other note is on screen whole and the second save was refused:\n%s", w, h, s.View().Content) + continue + } + snAssertMarks(t, snLoad(t, d, target), study.Mark{Entry: 4, Note: "mine"}) + continue + } + hidden++ + if after := snBytes(t, path); !bytes.Equal(after, stored) { + t.Errorf("at %dx%d %q of the other note is not on screen, and a second save replaced it:\n%s", w, h, missing, frame) + continue + } + if !s.notes.editor.open || s.notes.editor.edit.value() != "mine" { + t.Errorf("at %dx%d the refused save did not leave the input open holding what was typed", w, h) + continue + } + again := s.View().Content + shellAssertFits(t, "a note refused for want of room", again, w, h) + if !strings.Contains(again, "enlarge") { + t.Errorf("at %dx%d the save was refused without saying why:\n%s", w, h, again) + } + + // Enlarging the terminal is the way on the refusal names: the same + // input, given room for the other note, shows it whole and takes the + // save. + s.Update(tea.WindowSizeMsg{Width: 120, Height: 30}) + if missing := unseen(s.View().Content); missing != "" { + t.Fatalf("at 120x30 %q of the other note is still not on screen:\n%s", missing, s.View().Content) + } + s.Update(tutorialKeyMsg("enter")) + if s.notes.editor.open { + t.Fatalf("enlarged from %dx%d, the save is still refused:\n%s", w, h, s.View().Content) + } + snAssertMarks(t, snLoad(t, d, target), study.Mark{Entry: 4, Note: "mine"}) + } + if shown == 0 || hidden == 0 { + t.Fatalf("the other note was on screen whole at %d sizes and not at %d, which tries one side only", shown, hidden) + } +} + +// snUnfinishedImport is an imported record without a result: one the replay +// shows and the notes refuse. +func snUnfinishedImport(t *testing.T) gamestore.Saved { + t.Helper() + g := game.MustNew(rpRules()) + for _, mv := range rpMoves { + if err := g.PlayNotation(mv); err != nil { + t.Fatal(err) + } + } + if g.Result().Over() { + t.Fatal("the fixture finished, which refuses nothing") + } + rec, err := g.Record() + if err != nil { + t.Fatal(err) + } + return gamestore.Saved{ID: "unfinished-import", Kind: gamestore.Imported, Player: "Vertical", Opponent: "Horizontal", Record: rec.Encode()} +} + +// TestReplayUnfinishedGameRefusesNotes is the import that reaches the replay +// without a result: it can be watched, but notes are for finished games, and +// asking for one is answered on screen and leaves nothing on disk. +func TestReplayUnfinishedGameRefusesNotes(t *testing.T) { + d := snDeps(t) + sv := snUnfinishedImport(t) + + s := rpSized(t, d, sv, 120, 30) + s.seek(4) + before := s.View().Content + s.Update(tutorialKeyMsg("m")) + marked := s.View().Content + if marked == before { + t.Error("m on an unfinished game was refused in silence") + } + s.Update(tutorialKeyMsg("e")) + if s.notes.editor.open { + t.Fatal("the note input opened on a game whose notes cannot be saved") + } + if s.View().Content == marked { + t.Error("e on an unfinished game was refused in silence") + } + if rows := snRows(t, s.panel(36, 29), 1); len(rows) != 0 { + t.Errorf("the list of an unfinished game grew a column of marks: %+v", rows) + } + if _, err := os.Stat(d.Study.Dir()); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("refused notes left something in %s: %v", d.Study.Dir(), err) + } +} + +// TestReplayChangedRecordLeavesItsNotesAlone is a study written against one +// record meeting another under the same identifier. The notes are about moves +// that are not these moves, so they are neither shown here nor moved onto this +// record, the refusal is on screen, and the file stays byte for byte what it +// was — still the notes of the record they were written for. +func TestReplayChangedRecordLeavesItsNotesAlone(t *testing.T) { + d := snDeps(t) + sv := rpConnectionRecord(t) + + // The same moves without the draw offers: a finished record of its own. + rs := game.Std + rs.Size = 6 + g := game.MustNew(rs) + for _, mv := range []string{"B1", "F2", "C3", "F3", "D5", "F4", "B6"} { + if err := g.PlayNotation(mv); err != nil { + t.Fatal(err) + } + } + oldRec, err := g.Record() + if err != nil { + t.Fatal(err) + } + oldTarget := study.Target{GameID: sv.ID, RecordDigest: oldRec.Digest, Entries: oldRec.Entries, Finished: true} + if oldTarget.RecordDigest == snTarget(t, sv).RecordDigest { + t.Fatal("the two records digest alike, which changes nothing") + } + const old = "written for the other record" + if _, err := d.Study.Set(oldTarget, 0, study.Mark{Entry: 3, Note: old, Bookmark: true}); err != nil { + t.Fatal(err) + } + if _, err := d.Study.Load(snTarget(t, sv)); !errors.Is(err, study.ErrRecordChanged) { + t.Fatalf("the store does not refuse the study for the changed record: %v", err) + } + path := snFile(d, sv.ID) + before := snBytes(t, path) + + s := rpSized(t, d, sv, 120, 30) + frame := s.View().Content + control := rpSized(t, snDeps(t), sv, 120, 30).View().Content + if frame == control { + t.Errorf("the refusal is not on screen: the frame is the one a game with no notes shows:\n%s", frame) + } + rpJump(t, s, "3") + if frame := s.View().Content; strings.Contains(frame, old) { + t.Errorf("notes for another record are shown on this one:\n%s", frame) + } + if rows := snRows(t, s.panel(36, 29), 2); len(rows) != 0 { + t.Errorf("the list carries marks from another record: %+v", rows) + } + s.Update(tutorialKeyMsg("m")) + s.Update(tutorialKeyMsg("e")) + if s.notes.editor.open { + t.Error("the note input opened over notes that belong to another record") + } + if after := snBytes(t, path); !bytes.Equal(after, before) { + t.Fatalf("the study of the other record was rewritten:\nbefore: %s\nafter: %s", before, after) + } + doc, err := d.Study.Load(oldTarget) + if err != nil { + t.Fatal(err) + } + snAssertMarks(t, doc, study.Mark{Entry: 3, Note: old, Bookmark: true}) +} + +// TestReplayStudyRefusalsAreReadWithoutAPanel is the smallest terminal, where +// the board and the status line are all there is. Every way the notes refuse m, +// e or a save — a game with no result, a caller that keeps no notes, notes +// written for another record, by a newer twixtui or damaged, a write that +// fails, and notes another window changed first — is answered on that line +// with its reason, rather than in a panel that is not drawn. +func TestReplayStudyRefusalsAreReadWithoutAPanel(t *testing.T) { + const w, h = 20, 8 + sv := rpConnectionRecord(t) + target := snTarget(t, sv) + studyFile := func(data string) func(*testing.T, Deps) { + return func(t *testing.T, d Deps) { + t.Helper() + if err := os.MkdirAll(d.Study.Dir(), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(snFile(d, sv.ID), []byte(data), 0o600); err != nil { + t.Fatal(err) + } + } + } + // A directory where the lock file goes: the notes read as they should, + // and every save of them fails before anything is written. + unwritable := func(t *testing.T, d Deps) { + t.Helper() + if err := os.MkdirAll(filepath.Join(d.Study.Dir(), sv.ID+".lock"), 0o700); err != nil { + t.Fatal(err) + } + } + cases := []struct { + name string + deps func(*testing.T) Deps + sv gamestore.Saved + // before runs before the screen opens, and meanwhile once it has, + // which is when another window gets its save in. + before, meanwhile func(*testing.T, Deps) + // typed is pressed first and asks nothing of the notes; each key of + // refused is then pressed on a screen of its own. + typed, refused []string + // reason is a word the status line has to say why with. + reason string + }{ + {name: "an unfinished game", sv: snUnfinishedImport(t), refused: []string{"m", "e"}, reason: "unfinished"}, + {name: "a caller with no store", deps: shellTestDeps, refused: []string{"m", "e"}, reason: "no notes"}, + {name: "notes for another record", before: func(t *testing.T, d Deps) { + t.Helper() + other := target + other.RecordDigest = "another-record" + if _, err := d.Study.Set(other, 0, study.Mark{Entry: 3, Note: "about other moves"}); err != nil { + t.Fatal(err) + } + }, refused: []string{"m", "e"}, reason: "record"}, + {name: "notes from a newer twixtui", before: studyFile(`{"version": 99}`), refused: []string{"m", "e"}, reason: "newer"}, + {name: "a damaged notes file", before: studyFile(`{`), refused: []string{"m", "e"}, reason: "damaged"}, + {name: "a bookmark that cannot be written", before: unwritable, refused: []string{"m"}, reason: "error"}, + {name: "a note that cannot be written", before: unwritable, typed: []string{"e", "x"}, refused: []string{"enter"}, reason: "error"}, + {name: "notes changed elsewhere", meanwhile: func(t *testing.T, d Deps) { + t.Helper() + if _, err := study.Open(d.ConfigDir).Set(target, 0, study.Mark{Entry: 3, Note: "theirs"}); err != nil { + t.Fatal(err) + } + }, refused: []string{"m"}, reason: "elsewhere"}, + } + for _, c := range cases { + for _, key := range c.refused { + deps, saved := snDeps, sv + if c.deps != nil { + deps = c.deps + } + if c.sv.ID != "" { + saved = c.sv + } + d := deps(t) + if c.before != nil { + c.before(t, d) + } + s := rpSized(t, d, saved, w, h) + if arr := ui.Arrange(w, h, s.current().Size()); arr.TooSmall || arr.Panel != ui.PanelNone { + t.Fatalf("%s: a %dx%d terminal has room for a panel, which is not what this is about", c.name, w, h) + } + if c.meanwhile != nil { + c.meanwhile(t, d) + } + for _, k := range c.typed { + s.Update(tutorialKeyMsg(k)) + } + before := s.View().Content + s.Update(tutorialKeyMsg(key)) + frame := s.View().Content + shellAssertFits(t, c.name, frame, w, h) + status := frame[strings.LastIndexByte(frame, '\n')+1:] + if frame == before || !strings.Contains(status, c.reason) { + t.Errorf("%s: %s is refused without the status line saying why: %q", c.name, key, status) + } + } + } +} + +// TestReplayStoredNoteIsDrawnInert is the study file as untrusted text. Another +// program or a hand edit can put anything in a note, and a terminal obeys the +// control characters it is asked to draw, so none may reach the frame — not in +// the panel, and not in the input that holds the note unchanged for editing. +// What is readable around them is kept. +func TestReplayStoredNoteIsDrawnInert(t *testing.T) { + d := snDeps(t) + sv := rpConnectionRecord(t) + const hostile = "\x1b]0;pwned\x07 \x1b[2Jclear\u202eflip\ttab\nline\u009bcsi" + if _, err := d.Study.Set(snTarget(t, sv), 0, study.Mark{Entry: 17, Note: hostile}); err != nil { + t.Fatal(err) + } + s := rpSized(t, d, sv, 120, 30) + + assertInert := func(what, frame string) { + t.Helper() + for _, r := range frame { + if r == '\n' { + continue + } + if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) { + t.Fatalf("%s: the frame carries %U, which a terminal would act on:\n%q", what, r, frame) + } + } + } + frame := s.View().Content + assertInert("the stored note", frame) + for _, want := range []string{"]0;pwned", "clearflip"} { + if !strings.Contains(frame, want) { + t.Errorf("the readable part %q of the note is not drawn:\n%s", want, frame) + } + } + + s.Update(tutorialKeyMsg("e")) + if got := s.notes.editor.edit.value(); got != hostile { + t.Fatalf("the input changed the stored note before anything was typed: %q", got) + } + assertInert("the note input", s.View().Content) + for _, size := range shellSizes { + s.Update(tea.WindowSizeMsg{Width: size[0], Height: size[1]}) + frame := s.View().Content + assertInert("the note input", frame) + shellAssertFits(t, "note input", frame, size[0], size[1]) + } +} + +// TestReplayNoteInputTakesTheReviewKeysAsText is the input being modal. Every +// letter the review answers is a letter of a note while the input is up — q +// does not leave, h does not step, : does not open the entry input — and the +// note saved is exactly what was typed, on the entry the input was opened on. +func TestReplayNoteInputTakesTheReviewKeysAsText(t *testing.T) { + d := snDeps(t) + sv := rpConnectionRecord(t) + s := rpSized(t, d, sv, 120, 30) + rpJump(t, s, "9") + s.Update(tutorialKeyMsg("e")) + const typed = "qhjklgGnpme:?$0 x Q" + snType(t, s, typed) + if s.jump.open { + t.Fatal("typing : into the note opened the entry input") + } + if got := s.notes.editor.edit.value(); got != typed { + t.Fatalf("the input holds %q, want %q", got, typed) + } + s.Update(tutorialKeyMsg("enter")) + if s.notes.editor.open || s.step() != 9 { + t.Fatalf("saving left the input open=%v at step %d", s.notes.editor.open, s.step()) + } + snAssertMarks(t, snLoad(t, d, snTarget(t, sv)), study.Mark{Entry: 9, Note: typed}) +} + +// TestReplayNotePasteIsBoundedBeforeItIsKept is the note's size limit at the +// point text arrives. A paste is text from anywhere; one that would take the +// note past its bound is refused whole, before any of it is kept, and a byte +// that is not UTF-8 is counted as the three-byte character it becomes rather +// than as the one byte it was. +func TestReplayNotePasteIsBoundedBeforeItIsKept(t *testing.T) { + d := snDeps(t) + sv := rpConnectionRecord(t) + s := rpSized(t, d, sv, 120, 30) + rpJump(t, s, "9") + s.Update(tutorialKeyMsg("e")) + + before := s.View().Content + s.Update(tea.PasteMsg{Content: strings.Repeat("a", study.MaxNoteBytes+1)}) + if got := s.notes.editor.edit.value(); got != "" { + t.Fatalf("an oversized paste left %d bytes in the input", len(got)) + } + if s.View().Content == before { + t.Error("an oversized paste was refused in silence") + } + + // Line breaks and the rest of the control characters in a paste are not + // kept as such in a one-line note. + s.Update(tea.PasteMsg{Content: "a\x1b[31mb\nc\td"}) + if got, want := s.notes.editor.edit.value(), "a[31mb c d"; got != want { + t.Fatalf("a paste with control characters arrived as %q, want %q", got, want) + } + + // Filling the note to its bound exactly is allowed; one byte more is not. + filled := study.MaxNoteBytes - len(s.notes.editor.edit.value()) + s.Update(tea.PasteMsg{Content: strings.Repeat("x", filled)}) + if got := len(s.notes.editor.edit.value()); got != study.MaxNoteBytes { + t.Fatalf("a paste that fills the note exactly left it %d bytes, want %d", got, study.MaxNoteBytes) + } + s.Update(tutorialKeyMsg("y")) + if got := len(s.notes.editor.edit.value()); got != study.MaxNoteBytes { + t.Fatalf("a keypress took a full note to %d bytes", got) + } + // Two bytes of room, and one byte that becomes three once kept. + s.Update(shellKeyPress("backspace")) + s.Update(shellKeyPress("backspace")) + s.Update(tea.PasteMsg{Content: "\xff"}) + if got := len(s.notes.editor.edit.value()); got != study.MaxNoteBytes-2 { + t.Fatalf("a byte that is not UTF-8 took the note to %d bytes", got) + } + + s.Update(tutorialKeyMsg("enter")) + if s.notes.editor.open { + t.Fatalf("a note inside the bound was not saved:\n%s", s.View().Content) + } + note := snLoad(t, d, snTarget(t, sv)).At(9).Note + if len(note) != study.MaxNoteBytes-2 || !utf8.ValidString(note) || !strings.HasPrefix(note, "a[31mb c d") { + t.Errorf("the saved note is %d bytes, valid=%v, starting %q", len(note), utf8.ValidString(note), note[:min(len(note), 12)]) + } +} + +// TestReplayNotePasteIsMeasuredBeforeItIsCleaned is the bound applied to what +// arrived rather than to what would be kept of it. A paste longer than the +// room left is refused whole even when cleaning it would leave almost nothing: +// measuring what is kept is the second check, and a paste of control +// characters that is let through to it has already been scanned and copied in +// full, which is the cost measuring what arrived is there to refuse. +func TestReplayNotePasteIsMeasuredBeforeItIsCleaned(t *testing.T) { + d := snDeps(t) + sv := rpConnectionRecord(t) + s := rpSized(t, d, sv, 120, 30) + rpJump(t, s, "9") + s.Update(tutorialKeyMsg("e")) + snType(t, s, "kept") + before := s.View().Content + + // One byte more than the room left, and all but one of them bytes the + // field drops: cleaned, it is a single letter, well inside the bound. + room := study.MaxNoteBytes - len("kept") + paste := "x" + strings.Repeat("\x01", room) + if kept := noteText(paste); len(kept) > room { + t.Fatalf("the paste cleans to %d bytes, which the second check refuses as well", len(kept)) + } + s.Update(tea.PasteMsg{Content: paste}) + if got := s.notes.editor.edit.value(); got != "kept" { + t.Fatalf("a paste longer than the room left arrived, leaving %q in the input", got) + } + bound := strconv.Itoa(study.MaxNoteBytes>>10) + " KiB" + if frame := s.View().Content; frame == before || !strings.Contains(frame, bound) { + t.Errorf("the refused paste is not explained on screen:\n%s", frame) + } +} + +// TestReplayStudyKeysFollowARemappedKeymap is the study keys beside a keymap +// that has moved the review's own keys. The footer still names exactly what +// the screen answers, the rebound movement reaches the entry that is marked, +// and the note is saved by the key the keymap confirms with — the default one +// is no longer it. +func TestReplayStudyKeysFollowARemappedKeymap(t *testing.T) { + d := snDeps(t) + sv := rpConnectionRecord(t) + rpAssertFooterMatchesAnswers(t, d, sv) + + d = snDeps(t) + remapped := ui.DefaultKeymap() + moved := map[ui.Action][]string{ + ui.ActMoveRight: {"]"}, + ui.ActMoveLeft: {"["}, + ui.ActConfirm: {"tab"}, + } + for i, bind := range remapped { + if keys, ok := moved[bind.Action]; ok { + remapped[i].Keys = keys + remapped[i].Label = keys[0] + } + } + d.Keymap = remapped + rpAssertFooterMatchesAnswers(t, d, sv) + + // The probe above pressed m on a screen of its own, so the scenario gets a + // study of its own as well. + keymap := d.Keymap + d = snDeps(t) + d.Keymap = keymap + s := rpSized(t, d, sv, 120, 30) + for range 3 { + s.Update(tutorialKeyMsg("[")) + } + if s.step() != 14 { + t.Fatalf("three presses of the rebound back key reached step %d, want 14", s.step()) + } + s.Update(tutorialKeyMsg("m")) + s.Update(tutorialKeyMsg("e")) + snType(t, s, "left of it") + s.Update(tutorialKeyMsg("enter")) + if !s.notes.editor.open { + t.Fatal("enter saved the note after confirm was rebound away from it") + } + s.Update(tutorialKeyMsg("tab")) + if s.notes.editor.open { + t.Fatalf("the rebound confirm key did not save the note:\n%s", s.View().Content) + } + snAssertMarks(t, snLoad(t, d, snTarget(t, sv)), study.Mark{Entry: 14, Note: "left of it", Bookmark: true}) + s.Update(tutorialKeyMsg("l")) + if s.step() != 14 { + t.Errorf("l moved the review after being rebound away: step %d", s.step()) + } +} + +// TestReplayStudyKeepsTheListInANarrowPanel holds the panel's promise with the +// study in it: a long note, a bookmark and the open input all fit the rows and +// columns they are given, the list keeps its share of the rows with the marks +// in their column, and the input stays on screen at every size — in the panel +// where there is one, and on the status line where there is not. +func TestReplayStudyKeepsTheListInANarrowPanel(t *testing.T) { + d := snDeps(t) + sv := rpConnectionRecord(t) + target := snTarget(t, sv) + long := strings.Repeat("a long note about the ladder ", 60) + rev := int64(0) + for _, m := range []study.Mark{{Entry: 9, Note: long, Bookmark: true}, {Entry: 10, Bookmark: true}, {Entry: 8, Note: "short"}} { + doc, err := d.Study.Set(target, rev, m) + if err != nil { + t.Fatal(err) + } + rev = doc.Revision + } + + for _, editing := range []bool{false, true} { + s := rpOpen(t, d, sv) + s.seek(9) + if editing { + s.Update(tutorialKeyMsg("e")) + if !s.notes.editor.open { + t.Fatal("e did not open the note input") + } + } + for _, height := range []int{4, 6, 10, 29} { + for _, width := range []int{20, 24, 36} { + lines := s.panel(width, height) + all := strings.Join(lines, "\n") + if len(lines) > height { + t.Fatalf("editing=%v: a %dx%d panel produced %d lines:\n%s", editing, width, height, len(lines), all) + } + for _, l := range lines { + if w := ansi.StringWidth(l); w > width { + t.Errorf("editing=%v: a %dx%d panel has a line %d cells wide: %q", editing, width, height, w, l) + } + } + rows := snRows(t, lines, 2) + if want := min(height/2, s.entries()+1); len(rows) < want { + t.Errorf("editing=%v: a %dx%d panel shows %d entry rows, want at least %d:\n%s", + editing, width, height, len(rows), want, all) + } + marked := slices.IndexFunc(rows, func(r snRow) bool { return r.marked }) + if marked < 0 || rows[marked].number != 9 || !rows[marked].bookmark || !rows[marked].noted { + t.Errorf("editing=%v: a %dx%d panel does not mark entry 9 with its bookmark and note:\n%s", + editing, width, height, all) + } + field := slices.ContainsFunc(lines, func(l string) bool { + return strings.HasPrefix(l, "> ") && strings.HasSuffix(l, caret) + }) + if field != editing { + t.Errorf("editing=%v: a %dx%d panel draws the note input: %v:\n%s", editing, width, height, field, all) + } + } + } + for _, size := range shellSizes { + w, h := size[0], size[1] + s.Update(tea.WindowSizeMsg{Width: w, Height: h}) + shellAssertFits(t, "replay with a study", s.View().Content, w, h) + status := s.status(w) + if got := ansi.StringWidth(status); got > w { + t.Errorf("editing=%v: the status line is %d cells wide at %d columns: %q", editing, got, w, status) + } + if editing && !strings.Contains(status, caret) { + t.Errorf("at %dx%d the status line lost the note input: %q", w, h, status) + } + } + } +} diff --git a/internal/cli/game.go b/internal/cli/game.go index 875c43b..d2fcc1f 100644 --- a/internal/cli/game.go +++ b/internal/cli/game.go @@ -167,7 +167,9 @@ Opens at the final entry with a scrolling entry list. Use h/l (or left/right) to step, k/j (or up/down) to move five entries, and g/G for the ends. Press : to enter an entry number: 0 is the initial position, enter jumps and escape cancels. Draw offers count as entries, not moves. A winning connection -is highlighted only at the final entry. Review never changes the saved record.`, +is highlighted only at the final entry. On a finished game, m bookmarks the +entry on screen and e writes a note on it; notes are kept beside the game in +the configuration directory. Review never changes the saved record.`, Args: exactArgs(1), ValidArgsFunction: opts.gameIDCompletions, RunE: func(cmd *cobra.Command, args []string) error { diff --git a/internal/cli/play.go b/internal/cli/play.go index 256f295..817aa5b 100644 --- a/internal/cli/play.go +++ b/internal/cli/play.go @@ -22,6 +22,7 @@ import ( "github.com/BAKocska/twixtui/internal/gamestore" "github.com/BAKocska/twixtui/internal/leaderboard" "github.com/BAKocska/twixtui/internal/netplay" + "github.com/BAKocska/twixtui/internal/study" "github.com/BAKocska/twixtui/internal/ui" ) @@ -738,6 +739,7 @@ func (o *options) deps() (app.Deps, string, error) { Profiles: store, Board: board, Games: games, + Study: study.Open(dir), Theme: th, Styles: &styles, Keymap: ui.DefaultKeymap(), diff --git a/internal/e2e/study_test.go b/internal/e2e/study_test.go new file mode 100644 index 0000000..108acd2 --- /dev/null +++ b/internal/e2e/study_test.go @@ -0,0 +1,245 @@ +package e2e + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "testing" + "time" + + "github.com/BAKocska/twixtui/internal/game" + "github.com/BAKocska/twixtui/internal/gamestore" + "github.com/BAKocska/twixtui/internal/study" +) + +// snNote is the note the scenario writes. Every letter in it is a key the +// replay answers — h and l step, e opens a note, q leaves — so a note input +// that let any of them through would move the review or leave it part way +// through the typing, and the scenario would fail there. +const snNote = "hold the ladder q" + +// TestStudyNoteSurvivesLeavingAndResizing drives RM-01.b in a real terminal, +// against the compiled program: Watch a finished game, jump to an entry that is +// a draw offer rather than a move, write a note on it and bookmark it, leave, +// come back, and find both on that entry and not the one beside it; then resize +// the terminal around them. What is on disk afterwards is the study file with +// that one mark in it, and the saved game byte for byte as it was seeded. +func TestStudyNoteSurvivesLeavingAndResizing(t *testing.T) { + t.Parallel() + cfg := t.TempDir() + saved, record := snSeed(t, cfg) + gameFile := filepath.Join(cfg, "games", saved.ID+".json") + gameBefore, err := os.ReadFile(gameFile) + if err != nil { + t.Fatalf("the seeded game is not where the store keeps it: %v", err) + } + + tm := sessionIn(t, cfg, 120, 32) + // A fresh profile meets the introduction first; this test is about what is + // behind it. + tm.MustWaitFor("skip", 20*time.Second) + tm.SendKeys("q") + tm.MustWaitFor("Watch a finished game", 20*time.Second) + screen := tm.WaitSettled(10 * time.Second) + for range 2 { + tm.SendKeys("j") + screen = tm.WaitChanged(screen, 10*time.Second) + } + if !strings.Contains(screen, "Step through a finished") { + t.Fatalf("two steps down did not reach Watch a finished game:\n%s", screen) + } + tm.SendKeys("Enter") + chooser := tm.MustWaitFor("Tester vs Rival", 20*time.Second) + if strings.Contains(chooser, "step 17 of 17") { + t.Fatalf("the watch list was skipped:\n%s", chooser) + } + tm.SendKeys("Enter") + tm.MustWaitFor("step 17 of 17", 20*time.Second) + end := tm.WaitSettled(10 * time.Second) + tm.AssertFits() + + // Entry 4 is a draw offer with one move played, so a note filed by ply + // would land on entry 1. + tm.SendKeys(":") + tm.WaitChanged(end, 10*time.Second) + tm.SendKeys("4", "Enter") + tm.MustWaitFor("step 4 of 17", 10*time.Second) + at4 := tm.WaitSettled(10 * time.Second) + if !strings.Contains(at4, "moves played: 1") { + t.Fatalf("the jump did not land on the draw offer:\n%s", at4) + } + + tm.SendKeys("e") + tm.MustWaitFor("note on entry 4", 10*time.Second) + tm.SendText(snNote) + typed := tm.MustWaitFor(snNote, 10*time.Second) + if !strings.Contains(typed, "step 4 of 17") || !tm.Alive() { + t.Fatalf("typing the note moved or left the review:\n%s", typed) + } + tm.SendKeys("Enter") + noted := tm.MustWaitFor("note: "+snNote, 10*time.Second) + if strings.Contains(noted, "note on entry 4") { + t.Fatalf("the note input is still open after saving:\n%s", noted) + } + tm.SendKeys("m") + marked := tm.MustWaitFor("bookmarked", 10*time.Second) + row := regexp.MustCompile(`>\s*4\s+\*#\s+h:draw\?`) + if !row.MatchString(marked) { + t.Fatalf("the list does not mark entry 4 with its bookmark and note:\n%s", marked) + } + tm.AssertFits() + + // Leave the review and open the game again: it opens at the final entry, + // where there is no note, and the list still carries the marks on row 4. + // Leaving a screen opened from the menu drops the menu's open form, so + // escape lands on the front list with Watch still highlighted, and the + // list of finished games is chosen again from there. + tm.WaitSettled(10 * time.Second) + tm.SendKeys("Escape") + menu := tm.MustWaitFor("> Watch a finished game", 10*time.Second) + if strings.Contains(menu, "step 4 of 17") { + t.Fatalf("escape did not leave the review:\n%s", menu) + } + tm.WaitSettled(10 * time.Second) + tm.SendKeys("Enter") + chooser = tm.MustWaitFor("Tester vs Rival", 20*time.Second) + if strings.Contains(chooser, "step 17 of 17") { + t.Fatalf("the watch list was skipped on the way back:\n%s", chooser) + } + tm.WaitSettled(10 * time.Second) + tm.SendKeys("Enter") + tm.MustWaitFor("step 17 of 17", 20*time.Second) + reopened := tm.WaitSettled(10 * time.Second) + if strings.Contains(reopened, snNote) { + t.Fatalf("the note is drawn on the final entry, where it was not written:\n%s", reopened) + } + if !regexp.MustCompile(`\b4\s+\*#\s+h:draw\?`).MatchString(reopened) { + t.Fatalf("the reopened list lost the marks on entry 4:\n%s", reopened) + } + + tm.SendKeys(":") + tm.WaitChanged(reopened, 10*time.Second) + tm.SendKeys("4", "Enter") + tm.MustWaitFor("step 4 of 17", 10*time.Second) + back := tm.WaitSettled(10 * time.Second) + if !strings.Contains(back, "note: "+snNote) || !strings.Contains(back, "bookmarked") { + t.Fatalf("the note and bookmark are not on entry 4 after reopening:\n%s", back) + } + tm.SendKeys("l") + tm.MustWaitFor("step 5 of 17", 10*time.Second) + next := tm.WaitSettled(10 * time.Second) + if strings.Contains(next, snNote) || strings.Contains(next, "bookmarked") { + t.Fatalf("entry 5 shows the note or bookmark written on entry 4:\n%s", next) + } + tm.SendKeys("h") + tm.MustWaitFor("step 4 of 17", 10*time.Second) + back = tm.WaitSettled(10 * time.Second) + + // A narrower terminal keeps a smaller panel with the note in it, the + // smallest one keeps only the status line, and the way back to the size the + // scenario started at comes back to the same frame. + narrow := tm.ResizeAndWait(60, 16, 10*time.Second) + tm.AssertFits() + if !strings.Contains(narrow, "note: "+snNote) || !strings.Contains(narrow, "step 4 of 17") { + t.Fatalf("at 60x16 the note on entry 4 is no longer drawn:\n%s", narrow) + } + small := tm.ResizeAndWait(20, 8, 10*time.Second) + if !tm.Alive() { + t.Fatalf("the program died at 20x8:\n%s", small) + } + tm.AssertFits() + restored := tm.ResizeAndWait(120, 32, 10*time.Second) + if restored != back { + t.Fatalf("the review did not come back as it was after resizing\nbefore:\n%s\nafter:\n%s", back, restored) + } + + // Out: the review to the menu, and the menu's quit letter to the shell. + tm.SendKeys("q") + tm.MustWaitFor("> Watch a finished game", 10*time.Second) + tm.WaitSettled(10 * time.Second) + tm.SendKeys("q") + code, exited := tm.WaitExit(20 * time.Second) + if !exited || code != 0 { + t.Fatalf("the program did not exit cleanly: exited=%v status=%d", exited, code) + } + + if after, err := os.ReadFile(gameFile); err != nil || !bytes.Equal(after, gameBefore) { + t.Fatalf("taking notes changed the saved game (err %v):\nbefore: %s\nafter: %s", err, gameBefore, after) + } + raw, err := os.ReadFile(filepath.Join(cfg, "study", saved.ID+".json")) + if err != nil { + t.Fatalf("the study was not written where it is kept: %v", err) + } + var onDisk study.Study + if err := json.Unmarshal(raw, &onDisk); err != nil { + t.Fatalf("the study file is not JSON: %v\n%s", err, raw) + } + want := []study.Mark{{Entry: 4, Note: snNote, Bookmark: true}} + if onDisk.Version != study.Version || onDisk.GameID != saved.ID || onDisk.RecordDigest != record.Digest || + onDisk.Revision != 2 || !slices.Equal(onDisk.Marks, want) { + t.Fatalf("the study file holds %+v, want version %d of game %s, record %s, revision 2, marks %+v\n%s", + onDisk, study.Version, saved.ID, record.Digest, want, raw) + } + // And the program reads it back as the same study, which is what the next + // launch does. + loaded, err := study.Open(cfg).Load(study.Target{ + GameID: saved.ID, RecordDigest: record.Digest, Entries: record.Entries, Finished: true, + }) + if err != nil || !slices.Equal(loaded.Marks, want) { + t.Fatalf("the study loads back as %+v (err %v), want %+v", loaded.Marks, err, want) + } +} + +// snSeed stores one finished game whose record separates entries from moves: +// two draw offers before each of the first five moves, seventeen entries and +// seven moves in all, won by a chain. It is written through the store the +// program itself writes games with, so the fixture cannot drift from what a +// real game leaves behind. +func snSeed(t *testing.T, cfg string) (gamestore.Saved, game.Record) { + t.Helper() + rs := game.Std + rs.Size = 6 + g := game.MustNew(rs) + for i, move := range []string{"B1", "F2", "C3", "F3", "D5", "F4", "B6"} { + if i < 5 { + for range 2 { + if err := g.OfferDraw(g.Turn()); err != nil { + t.Fatal(err) + } + } + } + if err := g.PlayNotation(move); err != nil { + t.Fatalf("playing %s: %v", move, err) + } + } + if g.Entries() != 17 || g.Ply() != 7 || !g.Result().Over() { + t.Fatalf("the fixture is %d entries and %d moves, over=%v: it no longer separates the two or finishes", + g.Entries(), g.Ply(), g.Result().Over()) + } + record, err := g.Record() + if err != nil { + t.Fatal(err) + } + store, err := gamestore.Open(cfg) + if err != nil { + t.Fatal(err) + } + saved := gamestore.Saved{ + ID: gamestore.NewID(), + Kind: gamestore.Hotseat, + Created: time.Date(2026, 2, 2, 9, 0, 0, 0, time.UTC), + Player: "Tester", + Side: "vertical", + Opponent: "Rival", + Record: record.Encode(), + Finished: true, + } + if err := store.Put(saved); err != nil { + t.Fatal(err) + } + return saved, record +} diff --git a/internal/study/crossprocess_test.go b/internal/study/crossprocess_test.go new file mode 100644 index 0000000..25faf34 --- /dev/null +++ b/internal/study/crossprocess_test.go @@ -0,0 +1,379 @@ +//go:build unix || windows + +package study + +import ( + "bufio" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "testing" + "time" +) + +const ( + helperDirEnv = "TWIXTUI_STUDY_HELPER_DIR" + helperModeEnv = "TWIXTUI_STUDY_HELPER_MODE" + helperWorkerEnv = "TWIXTUI_STUDY_HELPER_WORKER" + helperReadyLine = "study-helper: ready" + helperDoneLine = "study-helper: done" + // helperStalePrefix starts the line on which a racing process reports how + // many of its saves were refused as stale and tried again. + helperStalePrefix = "study-helper: stale " + helperRaceMode = "race" + helperWaitMode = "wait" + // goAheadFile is how the other processes are told to go on. It lives in the + // configuration directory, outside the study directory, so nothing that + // reads or sweeps studies touches it. + goAheadFile = "helper-go-ahead" + // racingSets is how many marks each racing process saves. The two + // processes start together and every save is a read, a compare and a + // write with a flush in between, so their cycles overlap many times over. + racingSets = 40 + // maxAttempts bounds how often one save may be refused as stale, so a + // store that never stops refusing fails the test rather than hanging it. + maxAttempts = 10000 + helperGame = "race-game" + helperDigest = "race-record" +) + +var ( + // savedElsewhere is what another window saves while the waiting process + // is held at the study's lock. + savedElsewhere = Mark{Entry: 1, Note: "saved by the other window"} + // waitingMark is what the waiting process is trying to save. + waitingMark = Mark{Entry: 2, Note: "typed while the other window saved", Bookmark: true} +) + +// helperTarget is the finished game every process in these tests studies. +func helperTarget() Target { + return Target{GameID: helperGame, RecordDigest: helperDigest, Entries: 2 * racingSets, Finished: true} +} + +// raceMark is the i-th mark racing process worker saves. The two processes own +// separate entries, so every mark either of them saved must still be there at +// the end. +func raceMark(worker, i int) Mark { + return Mark{Entry: worker*racingSets + i + 1, Note: fmt.Sprintf("worker %d, save %d", worker, i), Bookmark: i%2 == 0} +} + +// Two processes save marks into one study as fast as they can, each retrying +// the way an editor has to when its save is refused as stale. A lock that did +// not cover the whole read, compare and write would let both pass the compare +// against the same revision, and one of their saves would vanish: the revision +// would fall short of the number of successful saves and a mark would be +// missing. +func TestTwoProcessesSavingOneStudyLoseNothing(t *testing.T) { + dir := t.TempDir() + helpers := []*studyHelper{ + startStudyHelper(t, dir, helperRaceMode, 0), + startStudyHelper(t, dir, helperRaceMode, 1), + } + for _, h := range helpers { + h.await(t, h.ready, "got ready to save") + } + if err := os.WriteFile(filepath.Join(dir, goAheadFile), nil, 0o600); err != nil { + t.Fatalf("writing the go-ahead: %v", err) + } + stale := 0 + for worker, h := range helpers { + h.await(t, h.done, "finished saving") + if err := h.finish(t); err != nil { + t.Fatalf("racing process %d failed: %v\n%s", worker, err, h.stop()) + } + stale += h.stale + } + t.Logf("%d saves were refused as stale and tried again", stale) + + got, err := Open(dir).Load(helperTarget()) + if err != nil { + t.Fatalf("loading the study both processes saved: %v", err) + } + if want := int64(2 * racingSets); got.Revision != want { + t.Errorf("the study is at revision %d after %d successful saves", got.Revision, want) + } + if len(got.Marks) != 2*racingSets { + t.Errorf("the study holds %d marks, want %d", len(got.Marks), 2*racingSets) + } + for worker := range 2 { + for i := range racingSets { + want := raceMark(worker, i) + if m := got.At(want.Entry); m != want { + t.Errorf("entry %d holds %+v, want %+v", want.Entry, m, want) + } + } + } +} + +// The other process loads the study and then tries to save while this one +// holds the study's lock. Another window's save lands while it waits. Once it +// has the lock it must read the study again and find that save, so its own +// save is refused as stale instead of replacing the other window's note. +func TestSaveWaitsForTheLockAndSeesTheSaveBeforeIt(t *testing.T) { + dir := t.TempDir() + st := Open(dir) + tg := helperTarget() + + h := startStudyHelper(t, dir, helperWaitMode, 0) + // The other process now holds the study as it was: nothing saved yet. + h.await(t, h.ready, "loaded the study") + + if err := os.MkdirAll(st.Dir(), 0o700); err != nil { + t.Fatal(err) + } + release, err := lockStudy(st.lockPath(tg.GameID)) + if err != nil { + t.Fatalf("taking the study's lock: %v", err) + } + released := false + defer func() { + if !released { + release() + } + }() + + if err := os.WriteFile(filepath.Join(dir, goAheadFile), nil, 0o600); err != nil { + t.Fatalf("writing the go-ahead: %v", err) + } + select { + case <-h.done: + t.Fatalf("the other process saved while this one held the study's lock: %s", h.stop()) + case <-time.After(time.Second): + } + + theirs := Study{Version: Version, GameID: tg.GameID, RecordDigest: tg.RecordDigest, Revision: 1, Marks: []Mark{savedElsewhere}} + data, err := encode(theirs) + if err != nil { + t.Fatal(err) + } + if err := atomicWrite(st.path(tg.GameID), data); err != nil { + t.Fatalf("writing the other window's save: %v", err) + } + released = true + release() + + h.await(t, h.done, "saved its note") + // The other process asserted what it was started for: a stale refusal + // that handed back the other window's save, then a save on top of it. + if err := h.finish(t); err != nil { + t.Fatalf("the other process did not see the save that landed while it waited: %v\n%s", err, h.stop()) + } + got, err := st.Load(tg) + if err != nil { + t.Fatalf("loading the study: %v", err) + } + if got.Revision != 2 || got.At(savedElsewhere.Entry) != savedElsewhere || got.At(waitingMark.Entry) != waitingMark { + t.Fatalf("the study ended as %+v, want revision 2 holding both %+v and %+v", got, savedElsewhere, waitingMark) + } +} + +// studyHelper is another twixtui process and the lines it has reached. +type studyHelper struct { + cmd *exec.Cmd + complaints *strings.Builder + ready, done, scanned chan struct{} + // stale is what a racing process reported; it is written by the scanner + // and may be read once scanned is closed. + stale int +} + +// startStudyHelper starts this test binary again as another process. +func startStudyHelper(t *testing.T, dir, mode string, worker int) *studyHelper { + t.Helper() + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + cmd := exec.Command(exe, "-test.run=^TestStudyHelperSaves$") + cmd.Env = append(os.Environ(), + helperDirEnv+"="+dir, + helperModeEnv+"="+mode, + helperWorkerEnv+"="+strconv.Itoa(worker)) + stdout, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + h := &studyHelper{ + cmd: cmd, + complaints: &strings.Builder{}, + ready: make(chan struct{}), + done: make(chan struct{}), + scanned: make(chan struct{}), + } + cmd.Stderr = cmd.Stdout + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { h.stop() }) + + go func() { + defer close(h.scanned) + lines := bufio.NewScanner(stdout) + for lines.Scan() { + line := strings.TrimSpace(lines.Text()) + switch { + case line == helperReadyLine: + close(h.ready) + case line == helperDoneLine: + close(h.done) + case strings.HasPrefix(line, helperStalePrefix): + n, err := strconv.Atoi(strings.TrimPrefix(line, helperStalePrefix)) + if err != nil { + fmt.Fprintf(h.complaints, "unreadable stale count: %s\n", line) + } + h.stale = n + default: + h.complaints.WriteString(lines.Text()) + h.complaints.WriteByte('\n') + } + } + if err := lines.Err(); err != nil { + fmt.Fprintf(h.complaints, "reading helper output: %v\n", err) + } + }() + return h +} + +// await waits for one of the other process's steps, or says which step it never +// reached and what it complained about. +func (h *studyHelper) await(t *testing.T, step <-chan struct{}, what string) { + t.Helper() + select { + case <-step: + case <-h.scanned: + select { + case <-step: + return + default: + t.Fatalf("the other process exited before it %s: %s", what, h.stop()) + } + case <-time.After(30 * time.Second): + t.Fatalf("the other process never %s: %s", what, h.stop()) + } +} + +// finish reads the other process's output to the end and reports how it +// exited. The output comes first because Wait closes the pipe, which would cut +// the scanner off partway through. +func (h *studyHelper) finish(t *testing.T) error { + t.Helper() + select { + case <-h.scanned: + case <-time.After(30 * time.Second): + t.Fatalf("the other process never exited: %s", h.stop()) + } + return h.cmd.Wait() +} + +// stop joins the process and its output scanner before reading diagnostics. +func (h *studyHelper) stop() string { + if h.cmd.ProcessState == nil { + h.cmd.Process.Kill() + h.cmd.Wait() + } + <-h.scanned + return h.complaints.String() +} + +// TestStudyHelperSaves is not a test of its own: it is the other process the +// tests above need, and it does nothing unless one of them starts it. It goes +// through Open, Load and Set, so the waiting it does and the answers it gets +// are the ones twixtui gets. +func TestStudyHelperSaves(t *testing.T) { + dir := os.Getenv(helperDirEnv) + if dir == "" { + t.Skip("not the process this helper is for") + } + st := Open(dir) + tg := helperTarget() + switch mode := os.Getenv(helperModeEnv); mode { + case helperRaceMode: + worker, err := strconv.Atoi(os.Getenv(helperWorkerEnv)) + if err != nil { + t.Fatalf("reading the worker number: %v", err) + } + fmt.Println(helperReadyLine) + waitForGoAhead(t, filepath.Join(dir, goAheadFile)) + fmt.Printf("%s%d\n", helperStalePrefix, saveRacing(t, st, tg, worker)) + case helperWaitMode: + loaded, err := st.Load(tg) + if err != nil { + t.Fatalf("loading the study: %v", err) + } + fmt.Println(helperReadyLine) + waitForGoAhead(t, filepath.Join(dir, goAheadFile)) + current, err := st.Set(tg, loaded.Revision, waitingMark) + if !errors.Is(err, ErrStale) { + t.Fatalf("saving over a save that landed while this one waited = %v, want ErrStale", err) + } + if current.Revision != 1 || current.At(savedElsewhere.Entry) != savedElsewhere { + t.Fatalf("the stale refusal handed back %+v, want the study the other window saved", current) + } + if _, err := st.Set(tg, current.Revision, waitingMark); err != nil { + t.Fatalf("saving again against the revision the refusal reported: %v", err) + } + default: + t.Fatalf("unknown helper mode %q", mode) + } + fmt.Println(helperDoneLine) +} + +// saveRacing saves one racing process's marks the way an editor has to: it +// loads the study, saves against the revision it loaded, and when the save is +// refused as stale it tries again against the revision the refusal reports. +// It returns how many saves were refused. +func saveRacing(t *testing.T, st *Store, tg Target, worker int) int { + t.Helper() + stale := 0 + for i := range racingSets { + want := raceMark(worker, i) + s, err := st.Load(tg) + if err != nil { + t.Fatalf("loading before save %d: %v", i, err) + } + for attempt := 0; ; attempt++ { + if attempt == maxAttempts { + t.Fatalf("save %d was refused as stale %d times in a row", i, attempt) + } + next, err := st.Set(tg, s.Revision, want) + if errors.Is(err, ErrStale) { + // Revisions only grow, so a refusal has to report a study + // that has moved past the one this save was made against. + if next.Revision <= s.Revision { + t.Fatalf("a stale refusal of a save against revision %d reported revision %d", s.Revision, next.Revision) + } + stale++ + s = next + continue + } + if err != nil { + t.Fatalf("save %d: %v", i, err) + } + if next.Revision != s.Revision+1 || next.At(want.Entry) != want { + t.Fatalf("save %d against revision %d returned %+v", i, s.Revision, next) + } + break + } + } + return stale +} + +// waitForGoAhead blocks until the process that started this one says to go +// on. +func waitForGoAhead(t *testing.T, path string) { + t.Helper() + deadline := time.Now().Add(30 * time.Second) + for { + if _, err := os.Stat(path); err == nil { + return + } + if time.Now().After(deadline) { + t.Fatalf("the go-ahead at %s never arrived", path) + } + time.Sleep(10 * time.Millisecond) + } +} diff --git a/internal/study/files_other.go b/internal/study/files_other.go new file mode 100644 index 0000000..2fd49ac --- /dev/null +++ b/internal/study/files_other.go @@ -0,0 +1,25 @@ +//go:build !windows + +package study + +import "os" + +// openRead opens a study file for reading. Everywhere but Windows an open file +// is no obstacle to replacing it: the reader keeps the file it opened and the +// next open finds the new one. +func openRead(path string) (*os.File, error) { return os.Open(path) } + +// replaceFile puts src in dst's place. Rename within a directory is atomic, so +// a reader sees one whole version of the study or the other. +func replaceFile(src, dst string) error { return os.Rename(src, dst) } + +// syncDir flushes a directory entry, which is what makes a replacement durable +// across a power loss. Not every filesystem permits this on a directory handle, +// and the rename has already succeeded either way, so a failure here is not +// worth failing a save over. +func syncDir(dir string) { + if d, err := os.Open(dir); err == nil { + d.Sync() + d.Close() + } +} diff --git a/internal/study/files_windows.go b/internal/study/files_windows.go new file mode 100644 index 0000000..80676ea --- /dev/null +++ b/internal/study/files_windows.go @@ -0,0 +1,24 @@ +//go:build windows + +package study + +import ( + "os" + + "github.com/BAKocska/twixtui/internal/winfs" +) + +// Reading and replacing a file need more from Windows than the standard library +// asks for, all of it about a file being replaced while somebody has it open; +// internal/winfs says what and why. + +// openRead opens a study file for reading. +func openRead(path string) (*os.File, error) { return winfs.OpenRead(path) } + +// replaceFile puts src in dst's place. +func replaceFile(src, dst string) error { return winfs.Replace(src, dst) } + +// Windows does not offer the directory-fsync operation used on Unix. +// Callers sync file contents before replacing; crash durability is not asserted +// to be equivalent to a successful POSIX directory flush. +func syncDir(dir string) {} diff --git a/internal/study/lock_other.go b/internal/study/lock_other.go new file mode 100644 index 0000000..37db221 --- /dev/null +++ b/internal/study/lock_other.go @@ -0,0 +1,14 @@ +//go:build !unix && !windows + +package study + +// lockStudy does nothing on a platform with no whole-file locking of its own, +// so two saves of one study there — from two windows of one twixtui or from +// two twixtui processes sharing a configuration directory — can interleave the +// revision check and the write, and the later save can replace the earlier one +// without being refused as stale. The platforms twixtui is built and tested for +// — macOS, Linux and Windows — each have an implementation instead, so this is +// reached only by a build for somewhere nobody has looked yet. +func lockStudy(path string) (func(), error) { + return func() {}, nil +} diff --git a/internal/study/lock_unix.go b/internal/study/lock_unix.go new file mode 100644 index 0000000..e94ddc0 --- /dev/null +++ b/internal/study/lock_unix.go @@ -0,0 +1,53 @@ +//go:build unix + +package study + +import ( + "errors" + "fmt" + "os" + "syscall" +) + +// lockStudy takes an exclusive advisory lock covering one game's study and +// returns the release function. A save reads the stored study, compares its +// revision with the one the editor loaded, and writes; the comparison is only +// worth anything while the revision cannot move underneath it. Two windows +// saving at once would otherwise both find the revision they loaded, and the +// second write would replace the first window's note without either of them +// being told. Holding this lock across the read and the write makes the cycle +// one step, so the second writer reads what the first one stored and is +// refused as stale. +// +// The lock is per open file description, so it serialises two Stores inside one +// process as well as two twixtui processes sharing a configuration directory. +// It is held on a lock file of its own rather than on the study's file, because +// atomicWrite replaces that file's inode and a lock on the old inode would be +// invisible to the next writer. It is per study rather than per store because +// studies are saved one at a time and unrelated games have no reason to wait +// for each other. +// +// Saving is the only thing locked here. A reader needs no lock: every save +// lands through a rename, so a reader sees one whole version of a study or +// another, never a half-written one. Loading must not write anything, and +// taking a lock would create the lock file. +func lockStudy(path string) (func(), error) { + f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600) + if err != nil { + return nil, fmt.Errorf("opening lock file %s: %w", path, err) + } + for { + err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX) + if !errors.Is(err, syscall.EINTR) { + break + } + } + if err != nil { + f.Close() + return nil, fmt.Errorf("locking %s: %w", path, err) + } + return func() { + syscall.Flock(int(f.Fd()), syscall.LOCK_UN) + f.Close() + }, nil +} diff --git a/internal/study/lock_windows.go b/internal/study/lock_windows.go new file mode 100644 index 0000000..e6958ad --- /dev/null +++ b/internal/study/lock_windows.go @@ -0,0 +1,30 @@ +//go:build windows + +package study + +import "github.com/BAKocska/twixtui/internal/winfs" + +// lockStudy takes an exclusive lock covering one game's study and returns the +// release function. A save reads the stored study, compares its revision with +// the one the editor loaded, and writes; the comparison is only worth anything +// while the revision cannot move underneath it. Two windows saving at once +// would otherwise both find the revision they loaded, and the second write +// would replace the first window's note without either of them being told. +// Holding this lock across the read and the write makes the cycle one step, so +// the second writer reads what the first one stored and is refused as stale. +// +// Windows holds the lock per handle, so it serialises two Stores inside one +// process as well as two twixtui processes sharing a configuration directory. +// It is held on a lock file of its own rather than on the study's file, because +// atomicWrite replaces that file and a lock on the file that was replaced +// protects nobody. It is per study rather than per store because studies are +// saved one at a time and unrelated games have no reason to wait for each +// other. +// +// Saving is the only thing locked here. A reader needs no lock: every save +// lands through a replacement, so a reader sees one whole version of a study +// or another, never a half-written one. Loading must not write anything, and +// taking a lock would create the lock file. +func lockStudy(path string) (func(), error) { + return winfs.Lock(path, true) +} diff --git a/internal/study/storage.go b/internal/study/storage.go new file mode 100644 index 0000000..d0bb8cf --- /dev/null +++ b/internal/study/storage.go @@ -0,0 +1,108 @@ +package study + +import ( + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "time" +) + +// readDocument returns the contents of the study file at path, or reports that +// there is none: a game nobody has taken notes on has no study yet, and that is +// not an error. +// +// The size is taken from the open file before any of it is read, so a file +// larger than a study may be is refused without being read into memory. The +// read is bounded as well, so a file that grows between the check and the read +// is refused the same way rather than read to its end. +func readDocument(path string) (data []byte, found bool, err error) { + f, err := openRead(path) + if errors.Is(err, os.ErrNotExist) { + return nil, false, nil + } + if err != nil { + return nil, false, fmt.Errorf("reading %s: %w", path, err) + } + defer f.Close() + fi, err := f.Stat() + if err != nil { + return nil, false, fmt.Errorf("reading %s: %w", path, err) + } + if fi.Size() > MaxFileBytes { + return nil, true, fmt.Errorf("%s: %w: it is %d bytes, more than the %d a study may be", path, ErrCorrupt, fi.Size(), MaxFileBytes) + } + data, err = io.ReadAll(io.LimitReader(f, MaxFileBytes+1)) + if err != nil { + return nil, false, fmt.Errorf("reading %s: %w", path, err) + } + if len(data) > MaxFileBytes { + return nil, true, fmt.Errorf("%s: %w: it is more than the %d bytes a study may be", path, ErrCorrupt, MaxFileBytes) + } + return data, true, nil +} + +// atomicWrite replaces path with data, or leaves the previous contents intact. +// The data goes to a temporary file in the same directory, is flushed to the +// device, and is then put in the target's place: a replacement within a +// directory takes effect all at once, so a crash partway through saving a note +// cannot truncate the notes that were already there. What each platform needs +// for that is in replaceFile. +func atomicWrite(path string, data []byte) error { + dir := filepath.Dir(path) + prefix := filepath.Base(path) + ".tmp-" + sweepStaleTemps(dir, prefix) + tmp, err := os.CreateTemp(dir, prefix+"*") + if err != nil { + return fmt.Errorf("creating temporary file in %s: %w", dir, err) + } + name := tmp.Name() + defer func() { + if name != "" { + os.Remove(name) + } + }() + if _, err := tmp.Write(data); err != nil { + tmp.Close() + return fmt.Errorf("writing %s: %w", name, err) + } + if err := tmp.Sync(); err != nil { + tmp.Close() + return fmt.Errorf("flushing %s: %w", name, err) + } + if err := tmp.Close(); err != nil { + return fmt.Errorf("closing %s: %w", name, err) + } + if err := replaceFile(name, path); err != nil { + return fmt.Errorf("replacing %s: %w", path, err) + } + name = "" + syncDir(dir) + return nil +} + +// sweepStaleTemps removes leftovers from a run that died between creating a +// temporary file and renaming it. The caller holds the study's exclusive +// advisory lock, and the prefix names that study's file alone, so no other +// writer can have one of these in flight; the age bound covers the platforms +// where that lock does nothing. Failures are ignored — this is tidying, not +// part of the write. +func sweepStaleTemps(dir, prefix string) { + entries, err := os.ReadDir(dir) + if err != nil { + return + } + cutoff := time.Now().Add(-time.Minute) + for _, e := range entries { + if e.IsDir() || !strings.HasPrefix(e.Name(), prefix) { + continue + } + info, err := e.Info() + if err != nil || info.ModTime().After(cutoff) { + continue + } + os.Remove(filepath.Join(dir, e.Name())) + } +} diff --git a/internal/study/study.go b/internal/study/study.go new file mode 100644 index 0000000..f251478 --- /dev/null +++ b/internal/study/study.go @@ -0,0 +1,386 @@ +// Package study keeps a player's own notes and bookmarks on saved games. +// +// A study lives beside its game rather than inside it. The game's record is +// canonical and carries digests that say what the game was, so nothing written +// here ever touches it; a study is this machine's annotation of one record, +// kept in a directory of its own with one file per saved game, named by the +// game's identifier. Exporting a game therefore exports the record alone, and +// deleting a saved game leaves its study file where it was, unattached but +// recoverable. +// +// A study is tied to the record it was written against, not only to the game's +// identifier: it carries that record's digest. A note on entry 14 is about the +// position after the fourteenth entry of one particular record, so a study +// whose digest no longer matches the game's record is refused rather than +// moved onto a different position without anyone noticing. +// +// Every successful save increments the study's revision, and a save names the +// revision it was made against. Two windows editing the same study cannot +// overwrite each other: the second to save finds that the revision has moved +// on and is refused, which leaves the first window's save on disk and the +// second window's text in its editor, both still there to be reconciled. +package study + +import ( + "bytes" + "cmp" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "os" + "path/filepath" + "slices" + "unicode/utf8" + + "github.com/BAKocska/twixtui/internal/gamestore" +) + +const ( + // Version is the study document format this build reads and writes. + Version = 1 + // MaxNoteBytes bounds one note, counted in UTF-8 bytes. + MaxNoteBytes = 8 << 10 + // MaxFileBytes bounds one study document on disk. Nothing this build + // writes exceeds it, so anything that does was not written by twixtui. + MaxFileBytes = 1 << 20 +) + +// subdir is the directory studies are kept in, inside the configuration +// directory. +const subdir = "study" + +var ( + // ErrRecordChanged reports a stored study written against a different + // record of the game. The study file is left as it is. + ErrRecordChanged = errors.New("study belongs to a different record of this game") + // ErrStale reports a save made against a revision the stored study has + // since moved past. + ErrStale = errors.New("study has been saved elsewhere since it was loaded") + // ErrNewerVersion reports a study document written in a format newer than + // this build knows. + ErrNewerVersion = errors.New("study was written by a newer version of twixtui") + // ErrCorrupt reports a study document that cannot be read as one, or, from + // Set, one that can be read but can take no further save. + ErrCorrupt = errors.New("study file is damaged") + // ErrUnfinished reports a save for a game that has no result yet. + ErrUnfinished = errors.New("game is not finished") + // ErrInvalid reports a mark that cannot be saved. + ErrInvalid = errors.New("invalid study mark") +) + +// Target identifies the saved game a study belongs to. The caller derives it +// from the saved game's decoded, digest-checked record. +type Target struct { + // GameID is the saved game's identifier. It becomes a file name, so it is + // checked with gamestore.ValidateID before it is used. + GameID string + // RecordDigest is the digest of the record the study is about. + RecordDigest string + // Entries is the number of transcript entries in the record. Marks may be + // placed on entries 0 through Entries, where 0 is the initial position. + Entries int + // Finished reports whether the record has a result. Only a finished game's + // study may be saved. + Finished bool +} + +// validate refuses a target that could not name a study file, or that could +// not tell one record's study from another's. +func (t Target) validate() error { + if err := gamestore.ValidateID(t.GameID); err != nil { + return fmt.Errorf("study: %w", err) + } + if t.RecordDigest == "" { + return fmt.Errorf("study: game %s has no record digest to attach a study to", t.GameID) + } + if t.Entries < 0 { + return fmt.Errorf("study: game %s cannot have %d entries", t.GameID, t.Entries) + } + return nil +} + +// Mark is what a player keeps about one entry: a note, a bookmark, or both. +type Mark struct { + Entry int `json:"entry"` + Note string `json:"note,omitempty"` + Bookmark bool `json:"bookmark,omitempty"` +} + +// empty reports a mark that says nothing, which is how a mark is removed. +func (m Mark) empty() bool { return m.Note == "" && !m.Bookmark } + +// check reports, wrapped in kind, why m cannot belong to a record with entries +// transcript entries, or nil when it can. Notes are kept verbatim, control +// characters included, since rendering them inert is the display's job; they +// only have to be text. +func (m Mark) check(entries int, kind error) error { + switch { + case m.Entry < 0 || m.Entry > entries: + return fmt.Errorf("%w: entry %d is outside 0..%d", kind, m.Entry, entries) + case len(m.Note) > MaxNoteBytes: + return fmt.Errorf("%w: the note on entry %d is %d bytes, more than the %d a note may have", kind, m.Entry, len(m.Note), MaxNoteBytes) + case !utf8.ValidString(m.Note): + return fmt.Errorf("%w: the note on entry %d is not valid UTF-8", kind, m.Entry) + } + return nil +} + +// Study is the stored document for one saved game. +type Study struct { + Version int `json:"version"` + GameID string `json:"game_id"` + RecordDigest string `json:"record_digest"` + Revision int64 `json:"revision"` + // Marks is sorted by Entry, holds each entry at most once, and never holds + // a mark with neither a note nor a bookmark. + Marks []Mark `json:"entries"` +} + +// At returns the mark on entry, or an empty mark for that entry when there is +// none. +func (s Study) At(entry int) Mark { + if i, found := s.find(entry); found { + return s.Marks[i] + } + return Mark{Entry: entry} +} + +// find locates entry in the sorted marks, or where it would go. +func (s Study) find(entry int) (int, bool) { + return slices.BinarySearchFunc(s.Marks, entry, func(m Mark, e int) int { return cmp.Compare(m.Entry, e) }) +} + +// with returns the marks with m in place of whatever entry m.Entry held, or +// without that entry when m is empty. The study's own marks are not touched. +func (s Study) with(m Mark) []Mark { + marks := slices.Clone(s.Marks) + i, found := s.find(m.Entry) + switch { + case m.empty() && found: + marks = slices.Delete(marks, i, i+1) + case m.empty(): + case found: + marks[i] = m + default: + marks = slices.Insert(marks, i, m) + } + return marks +} + +// Store is the collection of studies in one configuration directory. +type Store struct { + dir string +} + +// Open prepares the store of studies kept in configDir. The directory is +// created on the first save rather than here or on a load, so looking at a +// game nobody has taken notes on leaves nothing behind. +func Open(configDir string) *Store { + return &Store{dir: filepath.Join(configDir, subdir)} +} + +// Dir returns the directory studies are kept in. +func (st *Store) Dir() string { return st.dir } + +// path is the study file for one game. The identifier has been validated, so +// it names a file inside the directory. +func (st *Store) path(id string) string { + return filepath.Join(st.dir, id+".json") +} + +// lockPath is the lock file for one game's study. An identifier holds only +// lower-case letters, digits and hyphens, so this can never name a study file. +// It is never removed: a writer may be waiting on it, and a new file under the +// same name would be a different lock. +func (st *Store) lockPath(id string) string { + return filepath.Join(st.dir, id+".lock") +} + +// Load reads the study of the game t names. A game with no study yet has an +// empty one at revision 0. +// +// A stored study written against a different record is refused with +// ErrRecordChanged, one from a newer format with ErrNewerVersion, and one that +// cannot be read as a study of this record with ErrCorrupt; each of them comes +// back with no study at all, so nothing from the refused file can be mistaken +// for this record's notes. Loading never writes, not even a lock file. +func (st *Store) Load(t Target) (Study, error) { + if err := t.validate(); err != nil { + return Study{}, err + } + return st.read(t) +} + +// read loads the stored study for a validated target. +func (st *Store) read(t Target) (Study, error) { + path := st.path(t.GameID) + data, found, err := readDocument(path) + if err != nil { + return Study{}, err + } + if !found { + return Study{Version: Version, GameID: t.GameID, RecordDigest: t.RecordDigest}, nil + } + s, err := decode(data, t) + if err != nil { + return Study{}, fmt.Errorf("%s: %w", path, err) + } + return s, nil +} + +// Set saves m in place of whatever mark its entry held, or removes that mark +// when m has neither a note nor a bookmark. baseRevision is the revision the +// caller loaded and edited. +// +// The target and the mark are checked before anything is created, so a refused +// save of an unfinished game or of a bad mark leaves no trace. The stored study +// is then read again under the study's exclusive lock, which is held until the +// write is done: comparing revisions is only worth anything while nobody else +// can move them. A stored revision other than baseRevision means somebody else +// saved first; the save is refused with ErrStale and the current stored study +// is returned, so the caller can show what is there beside its own unsaved +// text. Otherwise the revision advances by one and the study is replaced +// atomically. A save that would make the study larger than MaxFileBytes is +// refused with ErrInvalid, since the file could not be loaded again. +// +// A stored study already at revision math.MaxInt64 is refused with ErrCorrupt +// and left as it is. No run of saves gets a study that far, so something else +// wrote the number, and there is no next revision to give it: one more would +// wrap around to a negative revision that Load refuses, and a save reporting +// success would have made every note in the file unavailable. Refused, the file +// still loads with its notes. The check comes before the revisions are +// compared, because a stale refusal would invite the caller to try again +// against a study that can take no save at all. +func (st *Store) Set(t Target, baseRevision int64, m Mark) (Study, error) { + if err := t.validate(); err != nil { + return Study{}, err + } + if !t.Finished { + return Study{}, fmt.Errorf("%w: notes on game %s can be saved once it has a result", ErrUnfinished, t.GameID) + } + if err := m.check(t.Entries, ErrInvalid); err != nil { + return Study{}, err + } + if err := os.MkdirAll(st.dir, 0o700); err != nil { + return Study{}, fmt.Errorf("creating %s: %w", st.dir, err) + } + release, err := lockStudy(st.lockPath(t.GameID)) + if err != nil { + return Study{}, err + } + defer release() + + cur, err := st.read(t) + if err != nil { + return Study{}, err + } + if cur.Revision == math.MaxInt64 { + return Study{}, fmt.Errorf("%w: game %s is at revision %d, and no save can follow it", + ErrCorrupt, t.GameID, cur.Revision) + } + if cur.Revision != baseRevision { + return cur, fmt.Errorf("%w: game %s is at revision %d, and this edit was made against revision %d", + ErrStale, t.GameID, cur.Revision, baseRevision) + } + next := cur + next.Version = Version + next.Revision = cur.Revision + 1 + next.Marks = cur.with(m) + data, err := encode(next) + if err != nil { + return Study{}, err + } + if len(data) > MaxFileBytes { + return Study{}, fmt.Errorf("%w: the study of game %s would take %d bytes, more than the %d a study may", + ErrInvalid, t.GameID, len(data), MaxFileBytes) + } + if err := atomicWrite(st.path(t.GameID), data); err != nil { + return Study{}, err + } + return next, nil +} + +// encode renders a study the way it is stored: indented and ending in a +// newline, like the other files twixtui keeps. HTML characters are left as +// they are rather than escaped, because a note is plain text, and escaping +// every "<" into six bytes would spend the file's size bound on nothing. +func encode(s Study) ([]byte, error) { + if s.Marks == nil { + s.Marks = []Mark{} + } + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + enc.SetIndent("", " ") + if err := enc.Encode(s); err != nil { + return nil, fmt.Errorf("encoding study of game %s: %w", s.GameID, err) + } + return buf.Bytes(), nil +} + +// decode reads a stored study and checks it against the target it was loaded +// for. +// +// The version is read on its own first, so a document from a newer format is +// reported as that rather than as damage to this one. Within version 1 the +// document has to hold exactly the fields version 1 has: a field this build +// does not know would be dropped by its next save, so such a file is refused +// rather than rewritten without it. Anything from disk is quoted when it +// appears in an error, because an error is shown to the player and the file +// may hold anything. +func decode(data []byte, t Target) (Study, error) { + if !utf8.Valid(data) { + return Study{}, fmt.Errorf("%w: it is not UTF-8 text", ErrCorrupt) + } + var head struct { + Version int `json:"version"` + } + if err := json.Unmarshal(data, &head); err != nil { + return Study{}, fmt.Errorf("%w: %v", ErrCorrupt, err) + } + switch { + case head.Version > Version: + return Study{}, fmt.Errorf("%w: it has version %d, and this build reads version %d", ErrNewerVersion, head.Version, Version) + case head.Version < 1: + return Study{}, fmt.Errorf("%w: it has no valid version", ErrCorrupt) + } + + dec := json.NewDecoder(bytes.NewReader(data)) + dec.DisallowUnknownFields() + var s Study + if err := dec.Decode(&s); err != nil { + return Study{}, fmt.Errorf("%w: %v", ErrCorrupt, err) + } + if _, err := dec.Token(); !errors.Is(err, io.EOF) { + return Study{}, fmt.Errorf("%w: it holds more than one document", ErrCorrupt) + } + switch { + case s.GameID != t.GameID: + return Study{}, fmt.Errorf("%w: it calls itself the study of game %q, not %s", ErrCorrupt, s.GameID, t.GameID) + case s.RecordDigest == "": + return Study{}, fmt.Errorf("%w: it names no record", ErrCorrupt) + case s.RecordDigest != t.RecordDigest: + return Study{}, fmt.Errorf("%w: it was written against record %q, and game %s now has record %s", + ErrRecordChanged, s.RecordDigest, t.GameID, t.RecordDigest) + case s.Revision < 1: + // A study is only ever written by a save, and a save leaves it at + // revision 1 or later. Revision 0 means "nothing saved yet", and a file + // claiming it would let an editor that loaded before the file existed + // overwrite it without being told. + return Study{}, fmt.Errorf("%w: it has revision %d", ErrCorrupt, s.Revision) + } + for i, m := range s.Marks { + if err := m.check(t.Entries, ErrCorrupt); err != nil { + return Study{}, err + } + if m.empty() { + return Study{}, fmt.Errorf("%w: entry %d has neither a note nor a bookmark", ErrCorrupt, m.Entry) + } + if i > 0 && m.Entry <= s.Marks[i-1].Entry { + return Study{}, fmt.Errorf("%w: entry %d is out of order or repeated", ErrCorrupt, m.Entry) + } + } + return s, nil +} diff --git a/internal/study/study_test.go b/internal/study/study_test.go new file mode 100644 index 0000000..5645bff --- /dev/null +++ b/internal/study/study_test.go @@ -0,0 +1,538 @@ +package study + +import ( + "bytes" + "errors" + "fmt" + "math" + "os" + "path/filepath" + "reflect" + "runtime" + "slices" + "strings" + "testing" +) + +const ( + testGame = "k3m9x-study" + testDigest = "3f2a-record-one" + otherDigest = "9c41-record-two" + testEntries = 12 +) + +// finished is the target of a finished game with testEntries entries. +func finished() Target { + return Target{GameID: testGame, RecordDigest: testDigest, Entries: testEntries, Finished: true} +} + +func mustSet(t *testing.T, st *Store, tg Target, base int64, m Mark) Study { + t.Helper() + s, err := st.Set(tg, base, m) + if err != nil { + t.Fatalf("Set(%+v, %d, %+v): %v", tg, base, m, err) + } + return s +} + +func mustLoad(t *testing.T, st *Store, tg Target) Study { + t.Helper() + s, err := st.Load(tg) + if err != nil { + t.Fatalf("Load(%+v): %v", tg, err) + } + return s +} + +// readStored returns the bytes of a study file exactly as they are on disk. +func readStored(t *testing.T, st *Store, id string) []byte { + t.Helper() + data, err := os.ReadFile(filepath.Join(st.Dir(), id+".json")) + if err != nil { + t.Fatalf("reading the stored study: %v", err) + } + return data +} + +// writeStored puts a study file on disk the way something other than Set might +// have left it. +func writeStored(t *testing.T, st *Store, id string, data []byte) { + t.Helper() + if err := os.MkdirAll(st.Dir(), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(st.Dir(), id+".json"), data, 0o600); err != nil { + t.Fatal(err) + } +} + +func assertMissing(t *testing.T, path, what string) { + t.Helper() + if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("%s exists at %s (stat: %v), but nothing should have been written", what, path, err) + } +} + +func assertUnchanged(t *testing.T, st *Store, before []byte, what string) { + t.Helper() + if after := readStored(t, st, testGame); !bytes.Equal(after, before) { + t.Fatalf("%s rewrote the stored study:\nbefore: %s\nafter: %s", what, before, after) + } +} + +// storedDoc is a version 1 study of the test game at revision 3, holding the +// given JSON array of marks. +func storedDoc(marks string) string { + return fmt.Sprintf("{\n \"version\": 1,\n \"game_id\": %q,\n \"record_digest\": %q,\n \"revision\": 3,\n \"entries\": %s\n}\n", + testGame, testDigest, marks) +} + +func TestLoadingAnUnstudiedGameWritesNothing(t *testing.T) { + configDir := filepath.Join(t.TempDir(), "config") + st := Open(configDir) + + got := mustLoad(t, st, finished()) + if got.Version != Version || got.GameID != testGame || got.RecordDigest != testDigest || got.Revision != 0 || len(got.Marks) != 0 { + t.Fatalf("Load of a game with no study = %+v, want an empty version %d study of %s/%s at revision 0", + got, Version, testGame, testDigest) + } + assertMissing(t, configDir, "the configuration directory") + + // Once the directory exists, loading a second game's study still creates + // neither its file nor its lock. + mustSet(t, st, finished(), 0, Mark{Entry: 1, Bookmark: true}) + other := finished() + other.GameID = "another-game" + mustLoad(t, st, other) + assertMissing(t, filepath.Join(st.Dir(), "another-game.json"), "a study file") + assertMissing(t, filepath.Join(st.Dir(), "another-game.lock"), "a lock file") +} + +func TestSavedMarkLoadsBackVerbatim(t *testing.T) { + configDir := t.TempDir() + st := Open(configDir) + // Notes are text, kept exactly as typed: markup, quotes, line breaks and + // even control characters, which only the display has to render inert. + m := Mark{Entry: 3, Note: "Black's peg the ladder & \"line\"\nsecond line \x1b[31m\x07 ✓", Bookmark: true} + + saved := mustSet(t, st, finished(), 0, m) + if saved.Revision != 1 || saved.GameID != testGame || saved.RecordDigest != testDigest || saved.Version != Version { + t.Fatalf("the first save returned %+v, want revision 1 of the version %d study of %s/%s", saved, Version, testGame, testDigest) + } + if got := saved.At(3); got != m { + t.Fatalf("the saved study holds %+v on entry 3, want %+v", got, m) + } + + // Another window opening the same configuration directory sees the save. + loaded := mustLoad(t, Open(configDir), finished()) + if !reflect.DeepEqual(loaded, saved) { + t.Fatalf("the study loaded back as %+v, want what the save returned, %+v", loaded, saved) + } + if got := loaded.At(4); got != (Mark{Entry: 4}) { + t.Fatalf("an entry nobody marked reads %+v, want an empty mark", got) + } +} + +func TestEverySuccessfulSaveAdvancesTheRevisionOnce(t *testing.T) { + st := Open(t.TempDir()) + var rev int64 + for i, m := range []Mark{ + {Entry: 0, Bookmark: true}, + {Entry: 0, Note: "the opening position"}, + {Entry: testEntries, Note: "the final entry", Bookmark: true}, + {Entry: 0}, + } { + saved := mustSet(t, st, finished(), rev, m) + if saved.Revision != rev+1 { + t.Fatalf("save %d went from revision %d to %d, want %d", i, rev, saved.Revision, rev+1) + } + if loaded := mustLoad(t, st, finished()); loaded.Revision != saved.Revision { + t.Fatalf("save %d returned revision %d but the stored study is at %d", i, saved.Revision, loaded.Revision) + } + rev = saved.Revision + } +} + +func TestClearingNoteAndBookmarkRemovesTheMark(t *testing.T) { + st := Open(t.TempDir()) + s := mustSet(t, st, finished(), 0, Mark{Entry: 5, Note: "a slip", Bookmark: true}) + kept := Mark{Entry: 7, Note: "the winning link", Bookmark: true} + s = mustSet(t, st, finished(), s.Revision, kept) + + // A save replaces the whole mark: keeping the bookmark alone drops the note. + bare := Mark{Entry: 7, Bookmark: true} + s = mustSet(t, st, finished(), s.Revision, bare) + if got := s.At(7); got != bare { + t.Fatalf("after keeping only the bookmark, entry 7 holds %+v, want %+v", got, bare) + } + + s = mustSet(t, st, finished(), s.Revision, Mark{Entry: 5}) + if s.Revision != 4 { + t.Fatalf("removing a mark left revision %d, want 4", s.Revision) + } + for _, got := range []Study{s, mustLoad(t, st, finished())} { + if want := []Mark{bare}; !reflect.DeepEqual(got.Marks, want) { + t.Fatalf("after clearing entry 5 the study holds %+v, want only %+v", got.Marks, want) + } + if m := got.At(5); m != (Mark{Entry: 5}) { + t.Fatalf("the cleared entry reads %+v, want an empty mark", m) + } + } +} + +func TestMarksStaySortedAndUnique(t *testing.T) { + st := Open(t.TempDir()) + var s Study + for _, m := range []Mark{ + {Entry: 9, Bookmark: true}, + {Entry: 2, Note: "first thought"}, + {Entry: testEntries, Note: "resigned"}, + {Entry: 0, Bookmark: true}, + {Entry: 2, Note: "second thought", Bookmark: true}, + } { + s = mustSet(t, st, finished(), s.Revision, m) + } + want := []Mark{ + {Entry: 0, Bookmark: true}, + {Entry: 2, Note: "second thought", Bookmark: true}, + {Entry: 9, Bookmark: true}, + {Entry: testEntries, Note: "resigned"}, + } + if !reflect.DeepEqual(s.Marks, want) { + t.Fatalf("the saved study holds %+v, want %+v", s.Marks, want) + } + if got := mustLoad(t, st, finished()); !reflect.DeepEqual(got.Marks, want) { + t.Fatalf("the stored study holds %+v, want %+v", got.Marks, want) + } +} + +func TestStaleSaveIsRefusedAndBothVersionsSurvive(t *testing.T) { + configDir := t.TempDir() + st := Open(configDir) + // Two windows load the same study before either saves. + first := mustLoad(t, st, finished()) + second := mustLoad(t, Open(configDir), finished()) + + theirs := Mark{Entry: 4, Note: "saved by the first window"} + saved := mustSet(t, st, finished(), first.Revision, theirs) + before := readStored(t, st, testGame) + + mine := Mark{Entry: 4, Note: "typed in the second window", Bookmark: true} + current, err := Open(configDir).Set(finished(), second.Revision, mine) + if !errors.Is(err, ErrStale) { + t.Fatalf("saving against revision %d after revision %d was saved = %v, want ErrStale", second.Revision, saved.Revision, err) + } + assertUnchanged(t, st, before, "a stale save") + if !reflect.DeepEqual(current, saved) { + t.Fatalf("the stale refusal handed back %+v, want the stored study %+v", current, saved) + } + + // A revision ahead of the stored one is just as wrong as one behind it. + if _, err := st.Set(finished(), saved.Revision+5, mine); !errors.Is(err, ErrStale) { + t.Fatalf("saving against a revision the study never reached = %v, want ErrStale", err) + } + assertUnchanged(t, st, before, "a save against a future revision") + + // The refusal is not a dead end: saving again against the revision it + // reported replaces the first window's note deliberately. + again := mustSet(t, st, finished(), current.Revision, mine) + if again.Revision != saved.Revision+1 || again.At(4) != mine { + t.Fatalf("saving again against the reported revision gave %+v, want revision %d holding %+v", again, saved.Revision+1, mine) + } +} + +func TestStudyOfAnotherRecordIsRefusedAndKept(t *testing.T) { + st := Open(t.TempDir()) + original := Mark{Entry: 2, Note: "about the first record"} + saved := mustSet(t, st, finished(), 0, original) + before := readStored(t, st, testGame) + + changed := finished() + changed.RecordDigest = otherDigest + got, err := st.Load(changed) + if !errors.Is(err, ErrRecordChanged) { + t.Fatalf("loading the study against another record = %v, want ErrRecordChanged", err) + } + if !reflect.DeepEqual(got, Study{}) { + t.Fatalf("Load handed back %+v beside ErrRecordChanged, want nothing", got) + } + + // The save names the stored revision, so only the record check stands + // between it and moving the note onto a different record. + got, err = st.Set(changed, saved.Revision, Mark{Entry: 2, Note: "about the second record"}) + if !errors.Is(err, ErrRecordChanged) { + t.Fatalf("saving against another record = %v, want ErrRecordChanged", err) + } + if !reflect.DeepEqual(got, Study{}) { + t.Fatalf("Set handed back %+v beside ErrRecordChanged, want nothing", got) + } + assertUnchanged(t, st, before, "a save against another record") + if m := mustLoad(t, st, finished()).At(2); m != original { + t.Fatalf("the original record's study now holds %+v on entry 2, want %+v", m, original) + } +} + +func TestUnfinishedGameIsNeverWritten(t *testing.T) { + configDir := filepath.Join(t.TempDir(), "config") + st := Open(configDir) + unfinished := finished() + unfinished.Finished = false + + if _, err := st.Load(unfinished); err != nil { + t.Fatalf("loading an unfinished game's study: %v", err) + } + if _, err := st.Set(unfinished, 0, Mark{Entry: 1, Note: "too early"}); !errors.Is(err, ErrUnfinished) { + t.Fatalf("saving a note on an unfinished game = %v, want ErrUnfinished", err) + } + assertMissing(t, configDir, "the configuration directory") +} + +func TestInvalidMarksAreRefused(t *testing.T) { + // é is two bytes, so this note has fewer characters than MaxNoteBytes but + // one byte more than it: the bound is on bytes. + tooLong := strings.Repeat("é", MaxNoteBytes/2) + "!" + cases := []struct { + name string + mark Mark + }{ + {"before the initial position", Mark{Entry: -1, Bookmark: true}}, + {"past the last entry", Mark{Entry: testEntries + 1, Bookmark: true}}, + {"clearing past the last entry", Mark{Entry: testEntries + 1}}, + {"a note one byte too long", Mark{Entry: 1, Note: tooLong}}, + {"a note that is not UTF-8", Mark{Entry: 1, Note: "fine so far \xff\xfe"}}, + } + + configDir := filepath.Join(t.TempDir(), "config") + st := Open(configDir) + for _, c := range cases { + if _, err := st.Set(finished(), 0, c.mark); !errors.Is(err, ErrInvalid) { + t.Errorf("saving %s on a new study = %v, want ErrInvalid", c.name, err) + } + } + assertMissing(t, configDir, "the configuration directory") + + saved := mustSet(t, st, finished(), 0, Mark{Entry: 0, Note: "start"}) + before := readStored(t, st, testGame) + for _, c := range cases { + if _, err := st.Set(finished(), saved.Revision, c.mark); !errors.Is(err, ErrInvalid) { + t.Errorf("saving %s on an existing study = %v, want ErrInvalid", c.name, err) + } + } + assertUnchanged(t, st, before, "a refused mark") +} + +func TestMarksAtTheBoundsAreAccepted(t *testing.T) { + exact := strings.Repeat("é", MaxNoteBytes/2) + if len(exact) != MaxNoteBytes { + t.Fatalf("the fixture note is %d bytes, want %d", len(exact), MaxNoteBytes) + } + st := Open(t.TempDir()) + first := Mark{Entry: 0, Note: exact} + last := Mark{Entry: testEntries, Bookmark: true} + s := mustSet(t, st, finished(), 0, first) + mustSet(t, st, finished(), s.Revision, last) + + loaded := mustLoad(t, st, finished()) + if got := loaded.At(0); got != first { + t.Fatalf("the initial position's note of exactly %d bytes came back as %d bytes", MaxNoteBytes, len(got.Note)) + } + if got := loaded.At(testEntries); got != last { + t.Fatalf("the last entry holds %+v, want %+v", got, last) + } +} + +func TestNewerVersionIsRefusedAndKept(t *testing.T) { + st := Open(t.TempDir()) + // A later format may carry fields and shapes this build has never seen; + // all it has to recognise is the version. + data := []byte(fmt.Sprintf("{\n \"version\": 2,\n \"game_id\": %q,\n \"record_digest\": %q,\n \"revision\": 4,\n \"entries\": {\"1\": \"x\"},\n \"threads\": []\n}\n", + testGame, testDigest)) + writeStored(t, st, testGame, data) + + if _, err := st.Load(finished()); !errors.Is(err, ErrNewerVersion) { + t.Fatalf("loading a version 2 study = %v, want ErrNewerVersion", err) + } + if _, err := st.Set(finished(), 4, Mark{Entry: 1, Note: "x"}); !errors.Is(err, ErrNewerVersion) { + t.Fatalf("saving over a version 2 study = %v, want ErrNewerVersion", err) + } + assertUnchanged(t, st, data, "a save over a newer version") +} + +func TestDamagedStudyIsRefusedAndKept(t *testing.T) { + cases := []struct { + name string + data string + }{ + {"not JSON", "{\n \"version\": 1,\n \"game_id\": "}, + {"no version", strings.Replace(storedDoc(`[]`), "\"version\": 1,", "", 1)}, + {"version zero", strings.Replace(storedDoc(`[]`), "\"version\": 1", "\"version\": 0", 1)}, + {"another game's study", strings.Replace(storedDoc(`[]`), testGame, "another-game", 1)}, + {"a mark before the initial position", storedDoc(`[{"entry": -1, "bookmark": true}]`)}, + {"a mark past the last entry", storedDoc(fmt.Sprintf(`[{"entry": %d, "bookmark": true}]`, testEntries+1))}, + {"marks out of order", storedDoc(`[{"entry": 4, "bookmark": true}, {"entry": 2, "bookmark": true}]`)}, + {"one entry marked twice", storedDoc(`[{"entry": 2, "bookmark": true}, {"entry": 2, "note": "again"}]`)}, + {"a mark with nothing in it", storedDoc(`[{"entry": 2}]`)}, + {"a note too long", storedDoc(fmt.Sprintf(`[{"entry": 2, "note": %q}]`, strings.Repeat("a", MaxNoteBytes+1)))}, + {"bytes that are not UTF-8", storedDoc("[{\"entry\": 2, \"note\": \"\xff\"}]")}, + {"a second document after the first", storedDoc(`[]`) + storedDoc(`[]`)}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + st := Open(t.TempDir()) + data := []byte(c.data) + writeStored(t, st, testGame, data) + + got, err := st.Load(finished()) + if !errors.Is(err, ErrCorrupt) { + t.Fatalf("loading = %v, want ErrCorrupt", err) + } + if !reflect.DeepEqual(got, Study{}) { + t.Fatalf("Load handed back %+v beside ErrCorrupt, want nothing", got) + } + if _, err := st.Set(finished(), 3, Mark{Entry: 1, Note: "new"}); !errors.Is(err, ErrCorrupt) { + t.Fatalf("saving over it = %v, want ErrCorrupt", err) + } + assertUnchanged(t, st, data, "a save over a damaged study") + }) + } +} + +func TestStudyFileSizeBound(t *testing.T) { + st := Open(t.TempDir()) + doc := storedDoc(`[{"entry": 2, "note": "fits"}]`) + + // Whitespace after the document leaves one document, so this file is valid + // and exactly as large as a study may be. + exact := doc + strings.Repeat(" ", MaxFileBytes-len(doc)) + writeStored(t, st, testGame, []byte(exact)) + if got := mustLoad(t, st, finished()).At(2).Note; got != "fits" { + t.Fatalf("a study of exactly MaxFileBytes loaded note %q, want %q", got, "fits") + } + + over := []byte(exact + " ") + writeStored(t, st, testGame, over) + if _, err := st.Load(finished()); !errors.Is(err, ErrCorrupt) { + t.Fatalf("loading a study one byte over MaxFileBytes = %v, want ErrCorrupt", err) + } + if _, err := st.Set(finished(), 3, Mark{Entry: 1, Note: "new"}); !errors.Is(err, ErrCorrupt) { + t.Fatalf("saving over a study one byte over MaxFileBytes = %v, want ErrCorrupt", err) + } + assertUnchanged(t, st, over, "a save over an oversize study") +} + +func TestSaveThatWouldOutgrowTheFileIsRefused(t *testing.T) { + st := Open(t.TempDir()) + tg := finished() + tg.Entries = 400 + note := strings.Repeat("a", MaxNoteBytes) + + // Fill a study with full notes until one more would not fit. + full := Study{Version: Version, GameID: testGame, RecordDigest: testDigest, Revision: 1} + var data []byte + for entry := 0; ; entry++ { + next := full + next.Marks = append(slices.Clone(full.Marks), Mark{Entry: entry, Note: note}) + encoded, err := encode(next) + if err != nil { + t.Fatal(err) + } + if len(encoded) > MaxFileBytes { + break + } + full, data = next, encoded + } + writeStored(t, st, testGame, data) + if got := mustLoad(t, st, tg); len(got.Marks) != len(full.Marks) { + t.Fatalf("the full study loaded %d marks, want %d", len(got.Marks), len(full.Marks)) + } + + _, err := st.Set(tg, full.Revision, Mark{Entry: len(full.Marks), Note: note}) + if !errors.Is(err, ErrInvalid) { + t.Fatalf("saving a note the file has no room for = %v, want ErrInvalid", err) + } + assertUnchanged(t, st, data, "a save the file has no room for") +} + +func TestStudyAtTheLastRevisionTakesNoSave(t *testing.T) { + // storedDoc at another revision, with a note to show the study survives. + at := func(rev int64) []byte { + return []byte(strings.Replace(storedDoc(`[{"entry": 2, "note": "kept"}]`), + `"revision": 3`, fmt.Sprintf(`"revision": %d`, rev), 1)) + } + + // No run of saves gets this far, but a file written by something else can, + // and it loads: the revision is a valid one. Advancing it would wrap around + // to a negative revision that the next Load refuses along with every note. + st := Open(t.TempDir()) + data := at(math.MaxInt64) + writeStored(t, st, testGame, data) + loaded := mustLoad(t, st, finished()) + if loaded.Revision != math.MaxInt64 { + t.Fatalf("the study loaded at revision %d, want %d", loaded.Revision, int64(math.MaxInt64)) + } + if _, err := st.Set(finished(), loaded.Revision, Mark{Entry: 1, Note: "new"}); !errors.Is(err, ErrCorrupt) { + t.Fatalf("saving over a study at revision MaxInt64 = %v, want ErrCorrupt", err) + } + assertUnchanged(t, st, data, "a save over a study at the last revision") + if got := mustLoad(t, st, finished()); got.Revision != math.MaxInt64 || got.At(2).Note != "kept" { + t.Fatalf("after the refused save the study loads as %+v, want revision %d still holding its note", got, int64(math.MaxInt64)) + } + + // One revision short, the save is still taken, and the study it leaves at + // the last revision loads. + st = Open(t.TempDir()) + writeStored(t, st, testGame, at(math.MaxInt64-1)) + saved := mustSet(t, st, finished(), math.MaxInt64-1, Mark{Entry: 1, Note: "new"}) + if saved.Revision != math.MaxInt64 { + t.Fatalf("the save one revision short of the last reached revision %d, want %d", saved.Revision, int64(math.MaxInt64)) + } + if got := mustLoad(t, st, finished()); !reflect.DeepEqual(got, saved) { + t.Fatalf("the study saved at the last revision loaded as %+v, want %+v", got, saved) + } +} + +func TestUnusableTargetsAreRefused(t *testing.T) { + root := t.TempDir() + configDir := filepath.Join(root, "config") + st := Open(configDir) + + var targets []Target + for _, id := range []string{"", "../escaped", "..", "a/b", `a\b`, "Upper", "with.dot", "nul\x00", strings.Repeat("a", 33)} { + tg := finished() + tg.GameID = id + targets = append(targets, tg) + } + noDigest := finished() + noDigest.RecordDigest = "" + negative := finished() + negative.Entries = -1 + targets = append(targets, noDigest, negative) + + for _, tg := range targets { + if _, err := st.Load(tg); err == nil { + t.Errorf("Load(%+v) succeeded, want a refusal", tg) + } + if _, err := st.Set(tg, 0, Mark{Entry: 0, Note: "x"}); err == nil { + t.Errorf("Set(%+v) succeeded, want a refusal", tg) + } + } + assertMissing(t, configDir, "the configuration directory") + assertMissing(t, filepath.Join(root, "escaped.json"), "a study outside the store") +} + +func TestSavedStudyIsPrivate(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Windows files do not carry Unix permission bits") + } + st := Open(t.TempDir()) + mustSet(t, st, finished(), 0, Mark{Entry: 1, Note: "only mine"}) + for _, path := range []string{st.Dir(), filepath.Join(st.Dir(), testGame+".json")} { + fi, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if perm := fi.Mode().Perm(); perm&0o077 != 0 { + t.Errorf("%s has mode %v, want nothing for group or others", path, perm) + } + } +}