diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..e9daed5 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,37 @@ +name: ci + +on: + push: + pull_request: + +jobs: + test: + strategy: + fail-fast: false # a failure on one system doesn't cancel the others + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + # Stockfish, so the analysis test runs against the real engine (it's + # skipped where Stockfish is missing, so a failed install isn't fatal) + - name: Install Stockfish (Linux) + if: runner.os == 'Linux' + continue-on-error: true + run: sudo apt-get update && sudo apt-get install -y stockfish + - name: Install Stockfish (macOS) + if: runner.os == 'macOS' + continue-on-error: true + run: brew install stockfish + - name: Install Stockfish (Windows) + if: runner.os == 'Windows' + continue-on-error: true + run: choco install stockfish -y --no-progress + - run: go vet ./... + - run: go test -race ./... + if: runner.os != 'Windows' + - run: go test ./... + if: runner.os == 'Windows' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..d5a0628 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,25 @@ +name: release + +on: + push: + tags: ["v*"] + +permissions: + contents: write + +jobs: + goreleaser: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + with: + fetch-depth: 0 + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + - uses: goreleaser/goreleaser-action@v6 + with: + version: "~> v2" + args: release --clean + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.goreleaser.yaml b/.goreleaser.yaml new file mode 100644 index 0000000..6335353 --- /dev/null +++ b/.goreleaser.yaml @@ -0,0 +1,30 @@ +# Builds release binaries when a version tag (e.g. v0.2.0) is pushed. +# Test locally with: goreleaser release --snapshot --clean +version: 2 +project_name: chess-cli + +builds: + - env: + - CGO_ENABLED=0 + goos: [linux, darwin, windows] + goarch: [amd64, arm64] + ldflags: + - -s -w -X main.version={{.Version}} + +archives: + - formats: [tar.gz] + format_overrides: + - goos: windows + formats: [zip] + files: + - README.md + - LICENSE.md + +checksum: + name_template: checksums.txt + +changelog: + sort: asc + filters: + exclude: + - "^Merge " diff --git a/README.md b/README.md index 004efba..376f191 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@

chess-cli ♟️

A chess tui app written in Go.
- Play locally with a friend or online with Lichess! + Play locally with a friend or online with Lichess!


@@ -10,76 +10,173 @@ chess-cli is a tui (terminal user interface) that allows you to play chess, both offline with a friend or online as a Lichess api client. - - ![home](https://user-images.githubusercontent.com/57846867/182972093-c9917d32-81c3-4ba5-a6ec-a783bf254f33.png) ![game](https://user-images.githubusercontent.com/42559123/183780181-a4cb62c0-8515-4371-8406-932e11e84f77.png) -

♞♞♞♞♞♞♞♞♞♞♞

-# Features +# Install - -- Mouse input support -- Displays move history -- UCI chess notation input -- Saving and restoring local games -- Lichess features: - - Lichess login w/ oauth - - Lichess challenge request for real time, unlimited, or correspondence games, with all variants and options supported - - Challenge a friend or a random player - - Play against the stockfish AI - - Join ongoing games - - Join from your incoming challenges +**Download a binary** for Linux, macOS or Windows from the +[releases page](https://github.com/nate-xyz/chess-cli/releases), unpack it and +run `chess-cli`. +**Or install with Go** (1.24+): +```sh +go install github.com/nate-xyz/chess-cli@latest +``` +**Or build from source:** +```sh +git clone https://github.com/nate-xyz/chess-cli +cd chess-cli +go run . # or: go build -o chess-cli . && ./chess-cli +``` -

♞♞♞♞♞♞♞♞♞♞♞

+A terminal with true colour and a font with the Unicode chess symbols gives the +best result. The board scales with your terminal, so make it big. + +### How the board looks + +Choose under **Options** on the home screen: + +| Rendering | What you get | Where | +|---|---|---| +| **Image** | Lichess boards and piece sets as real images, scaled to the board. 12 piece sets and 6 boards, previewed as you pick | terminals with the [kitty graphics protocol](https://sw.kovidgoyal.net/kitty/graphics-protocol/): kitty, Ghostty, WezTerm | +| **Advanced** | Unicode chess symbols, drawn big with kitty's [text sizing protocol](https://sw.kovidgoyal.net/kitty/text-sizing-protocol/) where available | everywhere; big in kitty 0.40+ | +| **Basic** | Plain symbols in the terminal's 8 standard colours, like the original chess-cli | any terminal, including old ones | + +Support is detected at startup (image rendering falls back to advanced where +images aren't supported, e.g. inside tmux). `CHESS_CLI_IMAGES=0/1` and +`CHESS_CLI_BIG_PIECES=0/1` override the detection. + +Options also has: + +- **Move box**: typed-move box always shown, or only on `Ctrl-K` +- **Clock bar**: clocks as a bar beside the board, or plain text in the sidebar +- **Zen mode**: hides names, ratings, chat and game info during games, like + Lichess's zen mode +- **Sound**: Retro (chiptune) or Wood, or off. chess-cli's own sounds, + played with your system's player (`pw-play`, `paplay` or `aplay` on Linux, + `afplay` on macOS, built in on Windows) + +# Playing + +| | | +|---|---| +| **Mouse** | Click a piece, then click where it should go. Legal moves are dotted, captures marked. | +| **Typing** | `Ctrl-K` opens the move box: UCI (`e2e4`) or standard notation (`Nf3`, `exd5`, `O-O`). Promotions need the piece: `e7e8=Q`, `e8=Q` or `e7e8q`. | +| **Keyboard on the board** | Arrows or `hjkl` move the cursor, `Enter`/`Space` selects, `Esc` cancels, `Tab` goes to the menu. | +| **Going back** | Click a move in the move list, scroll the mouse wheel on the board, or `[` `]` (`Home`/`End` for the start/now). Click the board to return. Works on the game-over screen too. | +| **Drawing** | Right-click a square for a circle, right-drag for an arrow; `Shift` red, `Alt` blue, both yellow. Left-click clears. | +| **Promotion** | A picker opens over the promotion square: click a piece, or press `q` `r` `b` `n`. | +| **Online chat** | `Tab` cycles board → chat → menu. | + +Local games are two players on one keyboard; the board flips each move. Games +can be saved and resumed. + +# Puzzles +*Puzzles* on the home screen: the **daily puzzle**, or **puzzle training** +(new puzzles one after another, five difficulty levels relative to your +rating). **Rated** puzzles update your Lichess puzzle rating and need a login; +**casual** ones work without. Hints, solutions and themes as on Lichess. +# Watching, studies and news -### dependency documentation: +Once you've logged in to Lichess, the home screen also has: -https://lichess.org/api for lichess +- **Watch**: Lichess TV channels (top rated, bullet, blitz, rapid, classical, + Chess960, bots, computer), a player's current game, or any game by link or + ID. Live clocks and moves; scroll back through the game as usual. +- **Studies**: your Lichess studies (private ones too) or any study by link. + Chapters, variations, comments and the study's arrows and circles. `←` `→` + step through the moves, `↑` `↓` jump to the start/end, click any move + (in a variation too) to go there. +- **Chess news**: elite events Lichess is broadcasting (live, coming up, just + finished, with leaders and winners) and the latest Lichess blog posts. -https://pkg.go.dev/github.com/notnil/chess chess lib +Without a login chess-cli doesn't contact Lichess at all (casual puzzles +aside, which you choose explicitly). -https://docs.rocketnine.space/code.rocketnine.space/tslocum/cview/ cview +# Lichess -https://code.rocketnine.space/tslocum/cview/src/branch/master/demos cview demos +Choose *Lichess* on the home screen and log in through your browser (if it +doesn't open, the link is shown in the app). chess-cli uses the +[Lichess Board API](https://lichess.org/api#tag/board): -https://pkg.go.dev/net/http +- Challenge a friend, seek a random opponent, or play Lichess's Stockfish (levels 1–8) +- All variants, rated or casual, real-time, correspondence or unlimited +- Resume ongoing games; accept, decline (`d`) and cancel challenges +- Chat, draw offers, takebacks, resign/abort +- Claim victory or a draw when your opponent leaves +- Rematch from the game-over screen +- `Esc` on the waiting screen withdraws your challenge or seek -https://mholt.github.io/json-to-go/ +**Time controls:** Lichess only allows Rapid, Classical and Correspondence +through the Board API, plus Blitz for direct challenges and games against the AI. +Bullet isn't available to third-party clients. + +Only one chess-cli runs at a time; a second copy tells you one is already +running. + +Your Lichess token and saved games are kept in `~/.config/chess-cli` +(`chess-cli --help` prints the exact folder on your system).

♞♞♞♞♞♞♞♞♞♞♞

-### todo: +# Development + +```sh +go test -race ./... +``` + +The tests include an end-to-end online game: the real UI running on tcell's +mock terminal against a fake Lichess server. -#### general +**Releasing:** push a version tag and GitHub Actions builds and publishes the +binaries with [GoReleaser](https://goreleaser.com): -- Handle all notation types or choose notation to start - -#### local client +```sh +git tag v0.2.0 && git push origin v0.2.0 +``` -- add time options - -#### oauth +### Credits - - handle if oauth rejected mid process +Piece sets come from [Lichess](https://github.com/lichess-org/lila); each +keeps its own licence (GPL, MIT, Apache, CC0, CC BY, CC BY-SA). See +[pkg/assets/pieces](pkg/assets/pieces/README.md). -#### online +### Dependency documentation + +- [Lichess API](https://lichess.org/api) +- [notnil/chess](https://pkg.go.dev/github.com/notnil/chess): rules and move generation +- [cview](https://pkg.go.dev/codeberg.org/tslocum/cview): TUI widgets +- [tcell](https://pkg.go.dev/github.com/gdamore/tcell/v3): terminal handling -- exit option on loader -- challenge construction - - set default interval position for sliders - - custom starting position option for challenges -- client - - chat - - rematch option post game -

♞♞♞♞♞♞♞♞♞♞♞

+### Todo + +#### general + +- Sixel support for image rendering (foot, Konsole, xterm, Windows Terminal) + +#### local client + +- Save clock times with saved games +- Stockfish analysis of a finished game + +#### online + +- Challenge construction + - Set default positions for sliders + - Custom starting position +- Puzzle themes, opening explorer, game history/PGN export +- Variants: the board follows standard chess rules only. Games in variants + like crazyhouse or atomic can be created but the app can't follow them yet; + Chess960 is untested. + +

♞♞♞♞♞♞♞♞♞♞♞

diff --git a/api/api_test.go b/api/api_test.go new file mode 100644 index 0000000..911838a --- /dev/null +++ b/api/api_test.go @@ -0,0 +1,410 @@ +package api + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "runtime" + "strings" + "sync/atomic" + "testing" + "time" +) + +// fakeLichess points the API at a test server for the duration of a test. +func fakeLichess(t *testing.T, h http.Handler) *httptest.Server { + t.Helper() + srv := httptest.NewServer(h) + old, oldUser := HostUrl, UserInfo + HostUrl = srv.URL + UserInfo = UserConfig{ApiToken: "test-token"} + t.Cleanup(func() { + srv.Close() + HostUrl, UserInfo = old, oldUser + }) + return srv +} + +func TestResponseErrorMessages(t *testing.T) { + for _, tc := range []struct { + status int + body string + want string + }{ + {400, `{"error":"Not your turn, or game already over"}`, "lichess: Not your turn, or game already over"}, + {400, `{"error":{"clock.limit":["Invalid value"],"days":["Required"]}}`, "lichess: clock.limit: Invalid value; days: Required"}, + {429, ``, "lichess: rate limited by Lichess, wait a minute and try again"}, + {404, `not json`, "lichess: 404 Not Found"}, + } { + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(tc.status) + fmt.Fprint(w, tc.body) + })) + err := MakeMove("abcd1234", "e2e4") + var apiErr *APIError + if !errors.As(err, &apiErr) || apiErr.Status != tc.status || err.Error() != tc.want { + t.Errorf("status %d: got %v, want %q", tc.status, err, tc.want) + } + } +} + +func TestRequestsSendAuthAndForm(t *testing.T) { + var got *http.Request + var form url.Values + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + got = r + r.ParseForm() + form = r.PostForm + fmt.Fprint(w, `{"ok":true}`) + })) + if err := WriteChat("game1234", "player", "good game"); err != nil { + t.Fatal(err) + } + if got.URL.Path != "/api/board/game/game1234/chat" || got.Header.Get("Authorization") != "Bearer test-token" { + t.Errorf("bad request: %s %v", got.URL.Path, got.Header) + } + if form.Get("room") != "player" || form.Get("text") != "good game" { + t.Errorf("bad form: %v", form) + } +} + +func TestCreateChallengeKeepsAliveUntilDeclined(t *testing.T) { + release := make(chan struct{}) + var form url.Values + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r.ParseForm() + form = r.PostForm + fmt.Fprintln(w, `{"challenge":{"id":"chal1234","status":"created"}}`) + w.(http.Flusher).Flush() + <-release + fmt.Fprintln(w, `{"done":"declined"}`) + })) + p, err := CreateChallenge(CreateChallengeType{ + DestUser: "friend", Variant: "standard", Rated: "false", Color: "white", + TimeOption: TimeRealTime, ClockLimit: "600", ClockIncrement: "5", + }) + if err != nil { + t.Fatal(err) + } + if p.ID != "chal1234" { + t.Fatalf("id %q", p.ID) + } + if form.Get("keepAliveStream") != "true" || form.Get("clock.limit") != "600" || form.Get("clock.increment") != "5" { + t.Errorf("form %v", form) + } + select { + case r := <-p.Done(): + t.Fatalf("finished early: %q", r) + case <-time.After(100 * time.Millisecond): + } + close(release) + if r := <-p.Done(); r != "declined" { + t.Fatalf("done = %q", r) + } +} + +func TestCancelChallengeClosesConnection(t *testing.T) { + closed := make(chan struct{}) + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprintln(w, `{"challenge":{"id":"chal1234"}}`) + w.(http.Flusher).Flush() + <-r.Context().Done() // Lichess cancels the challenge when we hang up + close(closed) + })) + p, err := CreateChallenge(CreateChallengeType{DestUser: "friend", TimeOption: TimeUnlimited}) + if err != nil { + t.Fatal(err) + } + p.Cancel() + select { + case <-closed: + case <-time.After(2 * time.Second): + t.Fatal("connection not closed by Cancel") + } +} + +func TestSeekUsesMinutes(t *testing.T) { + var form url.Values + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r.ParseForm() + form = r.PostForm + // real-time seeks stream keep-alive newlines until paired, then close + fmt.Fprint(w, "\n") + })) + p, err := CreateSeek(CreateChallengeType{Variant: "standard", Rated: "true", Color: "random", + TimeOption: TimeRealTime, ClockLimit: "900", MinTurn: 15, ClockIncrement: "10"}) + if err != nil { + t.Fatal(err) + } + <-p.Done() + if form.Get("time") != "15" || form.Get("increment") != "10" || form.Has("clock.limit") || form.Has("color") { + t.Errorf("seek form %v", form) + } +} + +func TestStreamBoardStateEvents(t *testing.T) { + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + for _, line := range []string{ + `{"type":"gameFull","id":"g1","white":{"id":"harry","name":"Harry"},"black":{"aiLevel":3},"initialFen":"startpos","state":{"type":"gameState","moves":"e2e4","wtime":60000,"btime":60000,"status":"started"}}`, + ``, + `{"type":"chatLine","username":"lichess","text":"Good luck","room":"player"}`, + `{"type":"somethingNew"}`, + `{"type":"opponentGone","gone":true,"claimWinInSeconds":10}`, + `{"type":"gameState","moves":"e2e4 e7e5","status":"started","bdraw":true}`, + } { + fmt.Fprintln(w, line) + } + })) + events := make(chan BoardEvent, 10) + errs := make(chan error, 1) + StreamBoardState(context.Background(), events, errs, "g1") + close(events) + var got []BoardEvent + for ev := range events { + got = append(got, ev) + } + if len(errs) != 0 { + t.Fatal(<-errs) + } + if len(got) != 5 { + t.Fatalf("got %d events: %+v", len(got), got) + } + if got[0].Type != GameFull || got[0].Full.Black.AiLevel != 3 || got[0].Full.State.Moves != "e2e4" { + t.Errorf("gameFull: %+v", got[0].Full) + } + if got[1].Type != ChatLine || got[1].Chat.Text != "Good luck" { + t.Errorf("chat: %+v", got[1]) + } + if got[2].Type != OpponentGone || !got[2].Gone.Gone || got[2].Gone.ClaimWinInSeconds != 10 { + t.Errorf("gone: %+v", got[2]) + } + if got[3].Type != GameState || !got[3].State.Bdraw { + t.Errorf("state: %+v", got[3]) + } + if got[4].Type != EOF { + t.Errorf("last event should be EOF: %+v", got[4]) + } +} + +func TestStreamBoardStateStopsOnCancel(t *testing.T) { + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.(http.Flusher).Flush() + <-r.Context().Done() + })) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + StreamBoardState(ctx, make(chan BoardEvent), make(chan error), "g1") + close(done) + }() + time.Sleep(50 * time.Millisecond) + cancel() + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("stream did not stop on cancel") + } +} + +// browserLogin plays the browser's part of the OAuth flow: it follows the +// login URL's redirect_uri with the given query (code/state/error). +func browserLogin(t *testing.T, authURL string, query func(state string) url.Values) { + u, err := url.Parse(authURL) + if err != nil { + t.Error(err) + return + } + q := u.Query() + if q.Get("code_challenge_method") != "S256" || q.Get("code_challenge") == "" || q.Get("client_id") != ClientID { + t.Errorf("bad auth url: %s", authURL) + } + go func() { + res, err := http.Get(q.Get("redirect_uri") + "?" + query(q.Get("state")).Encode()) + if err == nil { + res.Body.Close() + } + }() +} + +func useTempConfig(t *testing.T) string { + dir := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", dir) + t.Setenv("HOME", dir) // os.UserConfigDir on macOS + t.Setenv("AppData", dir) + return dir +} + +func TestOAuthLoginSavesTokenPrivately(t *testing.T) { + dir := useTempConfig(t) + var tokenForm url.Values + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/token" { + r.ParseForm() + tokenForm = r.PostForm + fmt.Fprint(w, `{"token_type":"Bearer","access_token":"lio_secret","expires_in":31536000}`) + } + })) + UserInfo = UserConfig{} + token, err := AuthUser(context.Background(), func(authURL string) { + browserLogin(t, authURL, func(state string) url.Values { + return url.Values{"code": {"the-code"}, "state": {state}} + }) + }) + if err != nil { + t.Fatal(err) + } + if token != "lio_secret" || tokenForm.Get("code") != "the-code" || tokenForm.Get("code_verifier") == "" { + t.Fatalf("token %q form %v", token, tokenForm) + } + path := filepath.Join(dir, "chess-cli", "config.json") + if runtimeConfig, err := ConfigDir(); err == nil { + path = filepath.Join(runtimeConfig, "config.json") + } + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if runtime.GOOS != "windows" && info.Mode().Perm() != 0o600 { // Windows has no Unix permissions + t.Errorf("config perms %v, want 0600", info.Mode().Perm()) + } + if time.Until(UserInfo.TokenExpirationDate) < 364*24*time.Hour { + t.Errorf("expiry not taken from expires_in: %v", UserInfo.TokenExpirationDate) + } +} + +// Logging in (e.g. again, for rated puzzles) must keep the other settings. +func TestOAuthLoginKeepsSettings(t *testing.T) { + useTempConfig(t) + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, `{"access_token":"new-token","expires_in":3600}`) + })) + if err := UpdateConfig(func(c *UserConfig) { c.Pieces, c.PieceSet, c.Zen = "image", "merida", true }); err != nil { + t.Fatal(err) + } + if _, err := AuthUser(context.Background(), func(authURL string) { + browserLogin(t, authURL, func(state string) url.Values { + return url.Values{"code": {"c"}, "state": {state}} + }) + }); err != nil { + t.Fatal(err) + } + UserInfo = UserConfig{} + if err := LoadConfig(); err != nil { + t.Fatal(err) + } + if UserInfo.ApiToken != "new-token" || UserInfo.Pieces != "image" || UserInfo.PieceSet != "merida" || !UserInfo.Zen { + t.Errorf("settings after login: %+v", UserInfo) + } +} + +func TestOAuthLoginCancelled(t *testing.T) { + useTempConfig(t) + fakeLichess(t, http.NotFoundHandler()) + _, err := AuthUser(context.Background(), func(authURL string) { + browserLogin(t, authURL, func(state string) url.Values { + return url.Values{"error": {"access_denied"}, "state": {state}} + }) + }) + if !errors.Is(err, ErrLoginCancelled) { + t.Fatalf("got %v, want ErrLoginCancelled", err) + } +} + +func TestOAuthIgnoresWrongState(t *testing.T) { + useTempConfig(t) + fakeLichess(t, http.NotFoundHandler()) + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancel() + _, err := AuthUser(ctx, func(authURL string) { + browserLogin(t, authURL, func(string) url.Values { + return url.Values{"code": {"x"}, "state": {"forged"}} + }) + }) + if err == nil || !strings.Contains(err.Error(), "timed out") && !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("forged callback should be ignored until timeout, got %v", err) + } +} + +func TestLegacyConfigMigrated(t *testing.T) { + useTempConfig(t) + work := t.TempDir() + t.Chdir(work) + os.WriteFile(legacyConfigFile, []byte(`{"ApiToken":"old-token"}`), 0o644) + UserInfo = UserConfig{} + if err := LoadConfig(); err != nil { + t.Fatal(err) + } + if UserInfo.ApiToken != "old-token" { + t.Fatalf("token %q", UserInfo.ApiToken) + } + if _, err := os.Stat(legacyConfigFile); !os.IsNotExist(err) { + t.Errorf("world-readable legacy token file should be removed") + } +} + +// After Lichess rejects the token the event stream stops; logging in again +// must be able to start it again. +func TestEventStreamRestartsAfterRejection(t *testing.T) { + useTempConfig(t) + var calls atomic.Int32 + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/stream/event" { + if calls.Add(1) == 1 { + http.Error(w, `{"error":"No such token"}`, http.StatusUnauthorized) + return + } + fmt.Fprintln(w, `{"type":"gameStart","game":{"id":"abcd1234"}}`) + w.(http.Flusher).Flush() + <-r.Context().Done() + } + })) + events := make(chan StreamEventType, 4) + StartEventStream(events) + deadline := time.Now().Add(3 * time.Second) + for streamRunning.Load() && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + if streamRunning.Load() { + t.Fatal("stream kept running after a 401") + } + StartEventStream(events) // e.g. after logging in again + defer StopEventStream() + select { + case e := <-events: + if e.GameID != "abcd1234" { + t.Errorf("event %+v", e) + } + case <-time.After(3 * time.Second): + t.Fatal("stream didn't restart") + } +} + +// The login landing page: success names the account, failures say what +// went wrong (escaped), and nothing is loaded from elsewhere. +func TestLoginPage(t *testing.T) { + var ok, failed, cancelled strings.Builder + if err := writeLoginPage(&ok, "hfwitte", nil); err != nil { + t.Fatal(err) + } + _ = writeLoginPage(&failed, "", errors.New("lichess: grant")) + _ = writeLoginPage(&cancelled, "", ErrLoginCancelled) + if !strings.Contains(ok.String(), "re logged in") || !strings.Contains(ok.String(), "hfwitte") { + t.Error("success page missing title or username") + } + if !strings.Contains(failed.String(), "Login failed") || !strings.Contains(failed.String(), "<bad>") { + t.Error("failure page missing title or not escaping the error") + } + if !strings.Contains(cancelled.String(), "Login cancelled") { + t.Error("cancelled page missing title") + } + for _, page := range []string{ok.String(), failed.String()} { + if strings.Contains(page, "src=") || strings.Contains(page, "http") { + t.Error("login page loads something from elsewhere") + } + } +} diff --git a/api/client.go b/api/client.go new file mode 100644 index 0000000..a45e5e3 --- /dev/null +++ b/api/client.go @@ -0,0 +1,124 @@ +package api + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "sort" + "strings" + "time" +) + +var ( + // apiClient is for ordinary request/response calls. + apiClient = &http.Client{Timeout: 30 * time.Second} + // streamClient has no overall timeout: streams stay open for a whole game. + streamClient = &http.Client{} +) + +// APIError is a non-2xx response from Lichess, with its error message if the +// body had one. +type APIError struct { + Status int + Message string +} + +func (e *APIError) Error() string { + if e.Message == "" { + return fmt.Sprintf("lichess: %d %s", e.Status, http.StatusText(e.Status)) + } + return fmt.Sprintf("lichess: %s", e.Message) +} + +// newRequest builds an authenticated request. form, if non-nil, is sent as an +// application/x-www-form-urlencoded body. +func newRequest(ctx context.Context, method, path string, form url.Values) (*http.Request, error) { + var body io.Reader + if form != nil { + body = strings.NewReader(form.Encode()) + } + req, err := http.NewRequestWithContext(ctx, method, HostUrl+path, body) + if err != nil { + return nil, err + } + if tok := token(); tok != "" { + req.Header.Set("Authorization", "Bearer "+tok) + } + if form != nil { + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } + return req, nil +} + +// call performs a request and, if out is non-nil, decodes the JSON response +// into it. Non-2xx responses become *APIError. +func call(method, path string, form url.Values, out any) error { + req, err := newRequest(context.Background(), method, path, form) + if err != nil { + return err + } + res, err := apiClient.Do(req) + if err != nil { + return err + } + defer res.Body.Close() + if res.StatusCode < 200 || res.StatusCode > 299 { + return responseError(res) + } + if out == nil { + _, _ = io.Copy(io.Discard, res.Body) + return nil + } + return decode(json.NewDecoder(res.Body), out) +} + +// openStream starts a streaming (ndjson) request. The caller must close the +// returned body; cancelling ctx also closes it. +func openStream(ctx context.Context, method, path string, form url.Values) (io.ReadCloser, error) { + req, err := newRequest(ctx, method, path, form) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/x-ndjson") + res, err := streamClient.Do(req) + if err != nil { + return nil, err + } + if res.StatusCode < 200 || res.StatusCode > 299 { + defer res.Body.Close() + return nil, responseError(res) + } + return res.Body, nil +} + +// responseError turns an error response into an *APIError. Lichess sends +// {"error": "message"} or {"error": {"field": ["message", ...]}}. +func responseError(res *http.Response) error { + body, _ := io.ReadAll(io.LimitReader(res.Body, 64<<10)) + e := &APIError{Status: res.StatusCode} + var parsed struct { + Error json.RawMessage `json:"error"` + } + if unmarshal(body, &parsed) == nil && len(parsed.Error) > 0 { + var msg string + var fields map[string][]string + switch { + case unmarshal(parsed.Error, &msg) == nil: + e.Message = msg + case unmarshal(parsed.Error, &fields) == nil: + var parts []string + for field, msgs := range fields { + parts = append(parts, field+": "+strings.Join(msgs, ", ")) + } + sort.Strings(parts) + e.Message = strings.Join(parts, "; ") + } + } + if e.Message == "" && res.StatusCode == http.StatusTooManyRequests { + e.Message = "rate limited by Lichess, wait a minute and try again" + } + return e +} diff --git a/api/defs.go b/api/defs.go index 12ff1b1..3b574ff 100644 --- a/api/defs.go +++ b/api/defs.go @@ -4,28 +4,29 @@ import ( "time" ) +// HostUrl is the Lichess server (a variable so tests can point it at a fake). +var HostUrl = "https://lichess.org" + const ( - HostUrl string = "https://lichess.org" - ClientID string = "chess-cli" - AuthURL string = HostUrl + "/oauth" - TokenURL string = HostUrl + "/api/token" - json_path string = "user_config.json" + ClientID string = "chess-cli" + + // legacyConfigFile is where older versions kept the token (in the working + // directory). LoadConfig migrates it to ConfigDir. + legacyConfigFile string = "user_config.json" ) var ( - UserInfo = UserConfig{ApiToken: "", TokenCreationDate: time.Now(), TokenExpirationDate: time.Now().AddDate(1, 0, 0)} - StreamEventStarted bool = false - Online bool = false - Scopes = []string{ + UserInfo UserConfig + Scopes = []string{ "preference:read", "preference:write", - "email:read", "challenge:read", "challenge:write", "challenge:bulk", "study:read", "study:write", "puzzle:read", + "puzzle:write", "follow:read", "follow:write", "msg:write", @@ -37,20 +38,19 @@ var ( type BoardEventEnum int const ( - GameFull BoardEventEnum = iota - GameState - ChatLine - ChatLineSpectator - GameStateResign - EOF + GameFull BoardEventEnum = iota // full game info, sent first and on reconnect + GameState // moves/clocks/offers changed + ChatLine // a chat message + OpponentGone // the opponent left (or came back) + EOF // the game stream ended normally ) type BoardEvent struct { - Type BoardEventEnum - Full StreamBoardGameFull - State StreamBoardGameState - Chat StreamBoardChat - Resign StreamBoardResign + Type BoardEventEnum + Full StreamBoardGameFull + State StreamBoardGameState + Chat StreamBoardChat + Gone StreamOpponentGone } type StreamEventType struct { @@ -59,11 +59,29 @@ type StreamEventType struct { Source string } -//type for storing user info into a json +// type for storing user info into a json type UserConfig struct { ApiToken string TokenCreationDate time.Time TokenExpirationDate time.Time + // Pieces is how the board is drawn: "text" or "image" (empty = automatic). + Pieces string `json:",omitempty"` + PieceSet string `json:",omitempty"` // image rendering: piece set and board + Board string `json:",omitempty"` + StockfishPath string `json:",omitempty"` // engine chosen in chess-cli (else found automatically) + StockfishLevel int `json:",omitempty"` + MoveBoxAlways bool `json:",omitempty"` // typed-move box always shown, not just on Ctrl-K + ClockBarOff bool `json:",omitempty"` // clocks as plain text in the sidebar, no bar + Zen bool `json:",omitempty"` // zen mode: hide names, ratings, chat and game info + LocalClock int `json:",omitempty"` // local games time control (index; 0 = none) + Sound string `json:",omitempty"` // sound theme: "" (retro), "wood" or "off" + SoundAsked bool `json:",omitempty"` // the first-run screen asked about sound + StockfishAsked bool `json:",omitempty"` // the first-run screen offered to get Stockfish + NoVimKeys bool `json:",omitempty"` // arrow keys only: hjkl (and g/G in lists) don't move + KeysAsked bool `json:",omitempty"` // the first-run screen asked about hjkl + // Puzzle preferences + PuzzleCasual bool `json:",omitempty"` + PuzzleDifficulty string `json:",omitempty"` } type CreateChallengeType struct { @@ -82,4 +100,5 @@ type CreateChallengeType struct { MinTurn float64 OpenEnded bool Level string + Fen string // starting position, for "fromPosition" games } diff --git a/api/features_test.go b/api/features_test.go new file mode 100644 index 0000000..b409cbb --- /dev/null +++ b/api/features_test.go @@ -0,0 +1,151 @@ +package api + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "testing" + "time" +) + +func TestGetNews(t *testing.T) { + now := time.Now() + ms := func(d time.Duration) int64 { return now.Add(d).UnixMilli() } + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/broadcast": + // live elite event (two sections: one shown), upcoming, too far off, low tier + fmt.Fprintf(w, `{"tour":{"id":"live1","name":"Candidates 2026 | Open","tier":5,"dates":[%d,%d],"info":{"format":"8-player double round-robin"}},"round":{"name":"Round 9","ongoing":true}}`+"\n", ms(-48*time.Hour), ms(48*time.Hour)) + fmt.Fprintf(w, `{"tour":{"id":"live2","name":"Candidates 2026 | Women","tier":5,"dates":[%d,%d]}}`+"\n", ms(-48*time.Hour), ms(48*time.Hour)) + fmt.Fprintf(w, `{"tour":{"id":"soon","name":"Sinquefield Cup","tier":5,"dates":[%d,%d]}}`+"\n", ms(10*24*time.Hour), ms(20*24*time.Hour)) + fmt.Fprintf(w, `{"tour":{"id":"far","name":"Next Year Open","tier":5,"dates":[%d]}}`+"\n", ms(200*24*time.Hour)) + fmt.Fprintf(w, `{"tour":{"id":"club","name":"Club Swiss","tier":3,"dates":[%d]}}`+"\n", ms(time.Hour)) + case "/api/broadcast/top": + fmt.Fprintf(w, `{"past":{"currentPageResults":[{"tour":{"id":"done","name":"Grand Prix Final","tier":5,"dates":[%d,%d]}}]}}`, ms(-10*24*time.Hour), ms(-3*24*time.Hour)) + case "/broadcast/live1/players": + fmt.Fprint(w, `[{"name":"Caruana, Fabiano","rank":2},{"name":"Sindarov, Javokhir","rank":1}]`) + case "/broadcast/done/players": + fmt.Fprint(w, `[{"name":"Firouzja, Alireza","rank":1}]`) + case "/blog.atom": + fmt.Fprint(w, ` +New feature2026-11-01T10:00:00Z +Older post2026-10-01T10:00:00Z +Oldest2026-09-01T10:00:00Z`) + default: + http.NotFound(w, r) + } + })) + n, err := GetNews() + if err != nil { + t.Fatal(err) + } + if len(n.Live) != 1 || n.Live[0].Name != "Candidates 2026 | Open" || n.Live[0].Leader != "Sindarov" || !n.Live[0].Live { + t.Errorf("live: %+v", n.Live) + } + if len(n.Upcoming) != 1 || n.Upcoming[0].Name != "Sinquefield Cup" { + t.Errorf("upcoming: %+v", n.Upcoming) + } + if len(n.Finished) != 1 || n.Finished[0].Leader != "Firouzja" { + t.Errorf("finished: %+v", n.Finished) + } + if len(n.Blog) != 2 || n.Blog[0].Title != "New feature" { + t.Errorf("blog: %+v", n.Blog) + } +} + +func TestPuzzleRequests(t *testing.T) { + var submitted map[string]any + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/puzzle/daily": + fmt.Fprint(w, `{"game":{"id":"g1","pgn":"e4 e5"},"puzzle":{"id":"p1","rating":1500,"solution":["g1f3"],"themes":["opening"]}}`) + case "/api/puzzle/next": + if r.URL.Query().Get("difficulty") != "harder" { + http.Error(w, "difficulty", 400) + return + } + fmt.Fprint(w, `{"game":{"id":"g2","pgn":"d4"},"puzzle":{"id":"p2","solution":["d7d5"]}}`) + case "/api/puzzle/batch/mix": + if r.Header.Get("Content-Type") != "application/json" || r.Header.Get("Authorization") != "Bearer test-token" { + http.Error(w, "headers", 400) + return + } + b, _ := io.ReadAll(r.Body) + json.Unmarshal(b, &submitted) + fmt.Fprint(w, `{"rounds":[{"id":"p1","win":true,"ratingDiff":9}],"glicko":{"rating":1509.6}}`) + } + })) + p, err := GetDailyPuzzle() + if err != nil || p.Puzzle.ID != "p1" || p.Game.PGN != "e4 e5" { + t.Fatalf("daily: %+v %v", p, err) + } + if p, err := GetNextPuzzle("harder"); err != nil || p.Puzzle.ID != "p2" { + t.Fatalf("next: %+v %v", p, err) + } + res, err := SubmitPuzzle("p1", true, true) + if err != nil || res.Rounds[0].RatingDiff != 9 || res.Glicko.Rating < 1509 { + t.Fatalf("submit: %+v %v", res, err) + } + sol := submitted["solutions"].([]any)[0].(map[string]any) + if sol["id"] != "p1" || sol["win"] != true || sol["rated"] != true { + t.Errorf("submitted %v", submitted) + } +} + +func TestStreamTv(t *testing.T) { + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/tv/blitz/feed" { + http.NotFound(w, r) + return + } + fmt.Fprintln(w, `{"t":"featured","d":{"id":"tv1","orientation":"black","players":[{"color":"white","user":{"name":"A","title":"GM"},"rating":2800,"seconds":180},{"color":"black","user":{"name":"B"},"rating":2700,"seconds":170}],"fen":"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"}}`) + fmt.Fprintln(w, `{"t":"fen","d":{"fen":"rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1","lm":"e2e4","wc":178,"bc":170}}`) + })) + var got []WatchUpdate + if err := StreamTv(context.Background(), "blitz", func(u WatchUpdate) { got = append(got, u) }); err != nil { + t.Fatal(err) + } + if len(got) != 2 || got[0].Game == nil || got[0].Game.White.Title != "GM" || got[0].Game.Orientation != "black" || + got[0].WhiteClock != 180 || got[1].LastMove != "e2e4" || got[1].WhiteClock != 178 { + t.Errorf("updates: %+v", got) + } +} + +func TestStreamGame(t *testing.T) { + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/stream/game/abcd1234": + fmt.Fprintln(w, `{"id":"abcd1234","speed":"blitz","rated":true,"status":"started","players":{"white":{"user":{"name":"W"},"rating":2000},"black":{"user":{"name":"B"},"rating":2100}}}`) + fmt.Fprintln(w, `{"fen":"rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1","lm":"e2e4","wc":180,"bc":180}`) + fmt.Fprintln(w, `{"id":"abcd1234","status":"resign","winner":"white","players":{"white":{"user":{"name":"W"}},"black":{"user":{"name":"B"}}}}`) + case "/game/export/abcd1234": + fmt.Fprint(w, `{"id":"abcd1234","moves":"e4 e5","clock":{"initial":180,"increment":2},"speed":"blitz"}`) + default: + http.NotFound(w, r) + } + })) + var got []WatchUpdate + if err := StreamGame(context.Background(), "abcd1234", func(u WatchUpdate) { got = append(got, u) }); err != nil { + t.Fatal(err) + } + if len(got) != 3 || got[0].Game == nil || got[0].Game.Black.Rating != 2100 || got[1].LastMove != "e2e4" || + got[2].Status != "resign" || got[2].Winner != "white" { + t.Errorf("updates: %+v", got) + } + g, err := GetGame("abcd1234") + if err != nil || g.Moves != "e4 e5" || g.ClockInitial != 180 || g.ClockIncrement != 2 { + t.Errorf("export: %+v %v", g, err) + } + if _, err := GetGame("../account"); err != ErrBadGameID { + t.Errorf("bad id: %v", err) + } + if err := StreamGame(context.Background(), "x/y", func(WatchUpdate) {}); err != ErrBadGameID { + t.Errorf("bad stream id: %v", err) + } + if !strings.Contains(GameIDFrom("https://lichess.org/abcd1234/black"), "abcd1234") { + t.Error("GameIDFrom") + } +} diff --git a/api/json_types.go b/api/json_types.go index 5904da6..f4a1ffd 100644 --- a/api/json_types.go +++ b/api/json_types.go @@ -2,19 +2,14 @@ package api //API TYPES -//https://lichess.org/api#operation/boardGameStream -type StreamBoardResign struct { - Type string `json:"type"` - Moves string `json:"moves"` - Wtime int `json:"wtime"` - Btime int `json:"btime"` - Winc int `json:"winc"` - Binc int `json:"binc"` - Status string `json:"status"` - Winner string `json:"winner"` +// StreamOpponentGone reports the opponent leaving the game (or returning). +// Once ClaimWinInSeconds reaches 0 you may claim victory or a draw. +type StreamOpponentGone struct { + Type string `json:"type"` + Gone bool `json:"gone"` + ClaimWinInSeconds int `json:"claimWinInSeconds"` } -//https://lichess.org/api#operation/boardGameStream type StreamBoardChat struct { Type string `json:"type"` Username string `json:"username"` @@ -22,7 +17,7 @@ type StreamBoardChat struct { Room string `json:"room"` } -//https://lichess.org/api#operation/boardGameStream +// https://lichess.org/api#operation/boardGameStream type StreamBoardGameState struct { Type string `json:"type"` Moves string `json:"moves"` @@ -38,7 +33,7 @@ type StreamBoardGameState struct { Btakeback bool `json:"btakeback"` } -//https://lichess.org/api#operation/boardGameStream +// https://lichess.org/api#operation/boardGameStream type StreamBoardGameFull struct { Type string `json:"type"` ID string `json:"id"` @@ -52,37 +47,30 @@ type StreamBoardGameFull struct { Initial int `json:"initial"` Increment int `json:"increment"` } `json:"clock"` - Speed string `json:"speed"` - Perf struct { + DaysPerTurn int `json:"daysPerTurn"` + Speed string `json:"speed"` + Perf struct { Name string `json:"name"` } `json:"perf"` - CreatedAt int64 `json:"createdAt"` - White struct { - ID string `json:"id"` - Name string `json:"name"` - Provisional bool `json:"provisional"` - Rating int `json:"rating"` - Title string `json:"title"` - } `json:"white"` - Black struct { - ID string `json:"id"` - Name string `json:"name"` - Rating int `json:"rating"` - Title interface{} `json:"title"` - } `json:"black"` - InitialFen string `json:"initialFen"` - State struct { - Type string `json:"type"` - Moves string `json:"moves"` - Wtime int `json:"wtime"` - Btime int `json:"btime"` - Winc int `json:"winc"` - Binc int `json:"binc"` - Status string `json:"status"` - } `json:"state"` + CreatedAt int64 `json:"createdAt"` + White GamePlayer `json:"white"` + Black GamePlayer `json:"black"` + InitialFen string `json:"initialFen"` + State StreamBoardGameState `json:"state"` +} + +// GamePlayer is one side of a Board API game. AiLevel is set (1-8) when the +// side is Lichess's Stockfish, in which case ID and Name are empty. +type GamePlayer struct { + ID string `json:"id"` + Name string `json:"name"` + Provisional bool `json:"provisional"` + Rating int `json:"rating"` + Title string `json:"title"` + AiLevel int `json:"aiLevel"` } -//https://lichess.org/api#operation/apiStreamEvent +// https://lichess.org/api#operation/apiStreamEvent type StreamEventChallenge struct { Type string `json:"type"` Challenge struct { @@ -132,7 +120,7 @@ type StreamEventChallenge struct { } `json:"challenge"` } -//https://lichess.org/api#operation/apiStreamEvent +// https://lichess.org/api#operation/apiStreamEvent type StreamEventGame struct { Type string `json:"type"` Game struct { @@ -164,7 +152,7 @@ type StreamEventGame struct { } `json:"game"` } -//https://lichess.org/api#operation/apiAccountPlaying +// https://lichess.org/api#operation/apiAccountPlaying type OngoingGameInfo struct { GameID string `json:"gameId"` FullID string `json:"fullId"` @@ -189,7 +177,7 @@ type OngoingGameInfo struct { } `json:"variant"` } -//https://lichess.org/api#operation/challengeList +// https://lichess.org/api#operation/challengeList type ChallengeInfo struct { ID string `json:"id"` URL string `json:"url"` diff --git a/api/login_page.go b/api/login_page.go new file mode 100644 index 0000000..35bf1a5 --- /dev/null +++ b/api/login_page.go @@ -0,0 +1,115 @@ +package api + +import ( + "errors" + "html/template" + "io" +) + +// The page the browser lands on after logging in to Lichess. Everything is +// inline (no fonts, scripts or images from elsewhere), so it works offline +// and tells nobody anything. + +type loginPage struct { + OK bool + Title string + Message string + Username string + Glyph string +} + +func writeLoginPage(w io.Writer, username string, err error) error { + p := loginPage{OK: err == nil, Username: username, Glyph: "♞"} + switch { + case err == nil: + p.Title = "You're logged in" + p.Message = "You can close this tab and go back to chess-cli in your terminal." + case errors.Is(err, ErrLoginCancelled): + p.Title, p.Glyph = "Login cancelled", "♚" + p.Message = "chess-cli wasn't given access. Close this tab, and try again from chess-cli whenever you like." + default: + p.Title, p.Glyph = "Login failed", "♚" + p.Message = err.Error() + ". Close this tab and try again from chess-cli." + } + return loginTemplate.Execute(w, p) +} + +var loginTemplate = template.Must(template.New("login").Parse(` + + + + + +chess-cli · {{.Title}} + + + +
+ +
+ +

{{.Title}}

+ {{if .Username}}

Logged in to Lichess as {{.Username}}

{{end}} +

{{.Message}}

+ {{if .OK}}
$ chess-cli — ready to play
{{end}} +
+
chess-cli · Lichess login
+
+ + +`)) diff --git a/api/news.go b/api/news.go new file mode 100644 index 0000000..6157b0e --- /dev/null +++ b/api/news.go @@ -0,0 +1,240 @@ +package api + +import ( + "context" + "encoding/xml" + "io" + "sort" + "strings" + "time" +) + +// Chess news for the home screen: Lichess's broadcasts of elite events +// (live, coming up, recently finished) and the Lichess blog. + +// Event is a broadcast tournament. +type Event struct { + ID string + Name string + Start time.Time + End time.Time + Location string + Round string // the current or next round + Live bool // a round is being played right now + Leader string // or winner, once finished (individual events only) + team bool +} + +// BlogPost is a Lichess blog entry. +type BlogPost struct { + Title string + Date time.Time +} + +// News is everything for the home screen. +type News struct { + Live, Upcoming, Finished []Event + Blog []BlogPost +} + +type broadcastJSON struct { + Tour struct { + ID string `json:"id"` + Name string `json:"name"` + Tier int `json:"tier"` + Dates []int64 `json:"dates"` + Info struct { + Format string `json:"format"` + Location string `json:"location"` + } `json:"info"` + } `json:"tour"` + Round struct { + Name string `json:"name"` + Ongoing bool `json:"ongoing"` + StartsAt int64 `json:"startsAt"` + } `json:"round"` +} + +func (b broadcastJSON) event() Event { + e := Event{ID: b.Tour.ID, Name: b.Tour.Name, Location: b.Tour.Info.Location, Round: b.Round.Name, Live: b.Round.Ongoing} + if d := b.Tour.Dates; len(d) > 0 { + e.Start, e.End = time.UnixMilli(d[0]), time.UnixMilli(d[len(d)-1]) + } + e.team = strings.Contains(strings.ToLower(b.Tour.Info.Format), "team") + return e +} + +// eliteTier is Lichess's top broadcast tier (world-class events). +const eliteTier = 5 + +// GetNews fetches the elite broadcasts and blog posts. Parts that fail are +// left out; an error is returned only if nothing could be fetched. +func GetNews() (*News, error) { + n := &News{} + now := time.Now() + var firstErr error + seen := map[string]bool{} + + // official broadcasts: live and upcoming + official, err := getNDJSON("/api/broadcast?nb=60") + if err != nil { + firstErr = err + } + for _, b := range official { + if b.Tour.Tier < eliteTier || seen[b.Tour.ID] { + continue + } + seen[b.Tour.ID] = true + e := b.event() + switch { + case !e.Start.IsZero() && e.Start.After(now): + if e.Start.Before(now.Add(45 * 24 * time.Hour)) { + n.Upcoming = append(n.Upcoming, e) + } + case e.End.IsZero() || e.End.Add(24*time.Hour).After(now): + n.Live = append(n.Live, e) + } + } + // recently finished, from the top broadcasts page + var top struct { + Past struct { + Results []broadcastJSON `json:"currentPageResults"` + } `json:"past"` + } + if err := call("GET", "/api/broadcast/top?page=1", nil, &top); err == nil { + for _, b := range top.Past.Results { + e := b.event() + if b.Tour.Tier >= eliteTier && !seen[b.Tour.ID] && e.End.After(now.Add(-21*24*time.Hour)) { + seen[b.Tour.ID] = true + n.Finished = append(n.Finished, e) + } + } + } else if firstErr == nil { + firstErr = err + } + n.Live, n.Upcoming, n.Finished = dedupe(n.Live, 3), dedupe(n.Upcoming, 2), dedupe(n.Finished, 2) + sort.Slice(n.Upcoming, func(i, j int) bool { return n.Upcoming[i].Start.Before(n.Upcoming[j].Start) }) + for _, list := range [][]Event{n.Live, n.Finished} { + for i := range list { + if !list[i].team { + list[i].Leader = leaderOf(list[i].ID) + } + } + } + + if posts, err := getBlog(); err == nil { + n.Blog = posts + } else if firstErr == nil { + firstErr = err + } + if len(n.Live)+len(n.Upcoming)+len(n.Finished)+len(n.Blog) == 0 && firstErr != nil { + return nil, firstErr + } + return n, nil +} + +// dedupe keeps one entry per event (Lichess lists sections like "| Masters" +// and "| Challengers" separately), preferring the main section, and at most +// max events. +func dedupe(events []Event, max int) []Event { + var out []Event + index := map[string]int{} + for _, e := range events { + base := strings.TrimSpace(strings.SplitN(e.Name, "|", 2)[0]) + main := strings.Contains(e.Name, "Masters") || strings.Contains(e.Name, "Open") || !strings.Contains(e.Name, "|") + if i, ok := index[base]; ok { + if main { + out[i] = e + } + continue + } + index[base] = len(out) + out = append(out, e) + } + if len(out) > max { + out = out[:max] + } + return out +} + +// leaderOf is the player ranked first in a broadcast, by surname. +func leaderOf(id string) string { + var players []struct { + Name string `json:"name"` + Rank int `json:"rank"` + Score float64 `json:"score"` + } + if call("GET", "/broadcast/"+id+"/players", nil, &players) != nil { + return "" + } + for _, p := range players { + if p.Rank == 1 { + return strings.TrimSpace(strings.SplitN(p.Name, ",", 2)[0]) + } + } + return "" +} + +func getNDJSON(path string) ([]broadcastJSON, error) { + req, err := newRequest(context.Background(), "GET", path, nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/x-ndjson") + res, err := apiClient.Do(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + if res.StatusCode < 200 || res.StatusCode > 299 { + return nil, responseError(res) + } + var out []broadcastJSON + err = eachLine(res.Body, func(line []byte) { + var b broadcastJSON + if unmarshal(line, &b) == nil { + out = append(out, b) + } + }) + return out, err +} + +// getBlog reads the latest posts from the Lichess blog's Atom feed. +func getBlog() ([]BlogPost, error) { + req, err := newRequest(context.Background(), "GET", "/blog.atom", nil) + if err != nil { + return nil, err + } + res, err := apiClient.Do(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + if res.StatusCode < 200 || res.StatusCode > 299 { + return nil, responseError(res) + } + var feed struct { + Entries []struct { + Title string `xml:"title"` + Published string `xml:"published"` + Updated string `xml:"updated"` + } `xml:"entry"` + } + if err := xml.NewDecoder(io.LimitReader(res.Body, 4<<20)).Decode(&feed); err != nil { + return nil, err + } + sanitize(&feed) + var posts []BlogPost + for _, e := range feed.Entries { + date := e.Published + if date == "" { + date = e.Updated + } + t, _ := time.Parse(time.RFC3339, date) + posts = append(posts, BlogPost{Title: strings.TrimSpace(e.Title), Date: t}) + if len(posts) == 2 { + break + } + } + return posts, nil +} diff --git a/api/oauth.go b/api/oauth.go index a9f3a20..ed4aedc 100644 --- a/api/oauth.go +++ b/api/oauth.go @@ -1,260 +1,334 @@ package api import ( + "context" + "crypto/rand" + "encoding/base64" "encoding/json" "errors" "fmt" - "io" - "log" "net" "net/http" "net/url" "os" - "reflect" + "path/filepath" "strings" + "sync" "time" pkce "github.com/jimlambrt/go-oauth-pkce-code-verifier" "github.com/skratchdot/open-golang/open" ) -func PerformOAuth() (string, error) { - var token string - err := checkForJSON() //check JSON exists, if not, make +// LoginTimeout is how long to wait for the browser login before giving up. +const LoginTimeout = 5 * time.Minute + +// ErrLoginCancelled is returned when the user denies access on Lichess. +var ErrLoginCancelled = errors.New("login was cancelled on Lichess") + +// ConfigDir is where chess-cli keeps its files (~/.config/chess-cli on Linux). +func ConfigDir() (string, error) { + base, err := os.UserConfigDir() if err != nil { return "", err } - if UserInfo.ApiToken == "" { - token, err = AuthUser() //get token - if err != nil { - return "", err - } - } else { - token = UserInfo.ApiToken - } - return token, nil -} - -func TimeCheck() { - if time.Until(UserInfo.TokenExpirationDate) <= 0 { - UserInfo.ApiToken = "" - AuthUser() - } + return filepath.Join(base, "chess-cli"), nil } -func AuthUser() (string, error) { - var token string - UserInfo.TokenCreationDate = time.Now() - UserInfo.TokenExpirationDate = UserInfo.TokenCreationDate.AddDate(1, 0, 0) //add one year - redirectPort, err := findPort() +func configPath() (string, error) { + dir, err := ConfigDir() if err != nil { return "", err } + return filepath.Join(dir, "config.json"), nil +} - RedirectURL := fmt.Sprintf("http://127.0.0.1:%d/", redirectPort) +// configMu guards UserInfo against the login (which runs in the background) +// and saving. Settings are read freely on the UI goroutine; changes go +// through UpdateConfig/SetConfig so they're locked against a save in +// progress. +var configMu sync.Mutex - // initialize the code verifier - var CodeVerifier, _ = pkce.CreateCodeVerifier() +// UpdateConfig changes settings and saves them. +func UpdateConfig(change func(c *UserConfig)) error { + configMu.Lock() + defer configMu.Unlock() + change(&UserInfo) + return saveLocked() +} - // Create code_challenge with S256 method - codeChallenge := CodeVerifier.CodeChallengeS256() +// SetConfig changes settings without saving (e.g. previewing a choice). +func SetConfig(change func(c *UserConfig)) { + configMu.Lock() + defer configMu.Unlock() + change(&UserInfo) +} - params := fmt.Sprintf( - "&response_type=code"+ - "&client_id=%s"+ - "&redirect_uri=%s"+ - "&code_challenge_method=S256"+ - "&code_challenge=%s"+ - "&scope=%s", - //"&state=2", - ClientID, RedirectURL, codeChallenge, strings.Join(Scopes[:], " ")) +// ResetPreferences puts every setting back to its default and saves. The +// Lichess login is kept (log out separately); saved games aren't settings +// and aren't touched. +func ResetPreferences() error { + configMu.Lock() + defer configMu.Unlock() + UserInfo = UserConfig{ + ApiToken: UserInfo.ApiToken, + TokenCreationDate: UserInfo.TokenCreationDate, + TokenExpirationDate: UserInfo.TokenExpirationDate, + } + return saveLocked() +} - fullUrl := fmt.Sprintf("%s?%s", AuthURL, params) +// token is the saved Lichess token, if any. +func token() string { + configMu.Lock() + defer configMu.Unlock() + return UserInfo.ApiToken +} - //set http server - srv := &http.Server{Addr: fmt.Sprintf("127.0.0.1:%d", redirectPort)} +// setToken records a new token (keeping all other settings) and saves it. +func setToken(tok string, expiresIn int64) error { + configMu.Lock() + defer configMu.Unlock() + UserInfo.ApiToken, UserInfo.TokenCreationDate, UserInfo.TokenExpirationDate = tok, time.Now(), time.Time{} + if expiresIn > 0 { + UserInfo.TokenExpirationDate = time.Now().Add(time.Duration(expiresIn) * time.Second) + } + return saveLocked() +} - // define a handler that will get the authorization code, call the token endpoint, and close the HTTP server - http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - // get the authorization code - code := r.URL.Query().Get("code") - if code == "" { - io.WriteString(w, "Error: could not find 'code' URL parameter\n") - cleanup(srv) // close the HTTP server and return - return - } - // trade the authorization code and the code verifier for an access token - token, err = getAccessToken(code, CodeVerifier.String(), RedirectURL, ClientID) - if err != nil { - io.WriteString(w, ` - - -

Error

-

could not retrieve access token

- - `) - cleanup(srv) // close the HTTP server and return - return - } - UserInfo.ApiToken = token - b, err := json.Marshal(&UserInfo) - if err != nil { - io.WriteString(w, ` - - -

Error

-

could not store access token

- - `) - cleanup(srv) // close the HTTP server and return - return - } - err = os.WriteFile(json_path, b, 0644) - if err != nil { - //fmt.Println("could not write config file") - io.WriteString(w, ` - - -

Error

-

could not store access token

- - `) - cleanup(srv) // close the HTTP server and return - return +// LoadConfig reads the saved settings and token, migrating the old +// ./user_config.json (which older versions wrote world-readable into the +// working directory). +func LoadConfig() error { + configMu.Lock() + defer configMu.Unlock() + path, err := configPath() + if err != nil { + return err + } + b, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + if old, oldErr := os.ReadFile(legacyConfigFile); oldErr == nil { + if json.Unmarshal(old, &UserInfo) == nil && UserInfo.ApiToken != "" { + if err := saveLocked(); err != nil { + return err + } + _ = os.Remove(legacyConfigFile) + } } - // return an indication of success to the caller - io.WriteString(w, ` - - -

Login successful!

-

Success, you may close this page.

- - `) - cleanup(srv) // close the HTTP server - }) - err = open.Start(fullUrl) + return nil + } if err != nil { - return "", err + return err } - srv.ListenAndServe() //start http server - return token, nil + return json.Unmarshal(b, &UserInfo) } -// getAccessToken trades the authorization code retrieved from the first OAuth2 leg for an access token -func getAccessToken(code string, codeVerifier string, RedirectURL string, ClientID string) (string, error) { - tokenParameters := url.Values{ - "grant_type": {"authorization_code"}, - "code": {code}, - "code_verifier": {codeVerifier}, - "redirect_uri": {RedirectURL}, - "client_id": {ClientID}, - } - //application/x-www-form-urlencoded - - //fmt.Println(RedirectURL) - - // create the request and execute it - res, err := http.PostForm(TokenURL, tokenParameters) +// SaveConfig writes the settings and token, readable only by the current user. +func SaveConfig() error { + configMu.Lock() + defer configMu.Unlock() + return saveLocked() +} - body, _ := io.ReadAll(res.Body) +func saveLocked() error { + path, err := configPath() if err != nil { - log.Fatalln(err) + return err } - defer res.Body.Close() - - //fmt.Println("HTTP Response Status:", res.StatusCode, http.StatusText(res.StatusCode)) - if res.StatusCode == 400 { - //log.Printf(string(body)) - return "", fmt.Errorf("wrong http code") + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err } - // process the response - - // unmarshal the json into a string map - var responseData map[string]interface{} - err = json.Unmarshal(body, &responseData) + b, err := json.MarshalIndent(&UserInfo, "", " ") if err != nil { - //fmt.Printf("JSON error: %s", err) - return "", err + return err } + tmp := path + ".tmp" + if err := os.WriteFile(tmp, b, 0o600); err != nil { + return err + } + return os.Rename(tmp, path) +} + +// ClearToken forgets the saved token (e.g. after Lichess rejects it). +func ClearToken() error { + configMu.Lock() + defer configMu.Unlock() + // forget the login, keep the preferences + UserInfo.ApiToken, UserInfo.TokenCreationDate, UserInfo.TokenExpirationDate = "", time.Time{}, time.Time{} + return saveLocked() +} - // retrieve the access token out of the map, and return to caller - if !isNil(responseData["access_token"]) { - accessToken := responseData["access_token"].(string) - return accessToken, nil +// HasValidToken reports whether a saved token exists and hasn't expired. +func HasValidToken() bool { + configMu.Lock() + defer configMu.Unlock() + return UserInfo.ApiToken != "" && + (UserInfo.TokenExpirationDate.IsZero() || time.Now().Before(UserInfo.TokenExpirationDate)) +} + +// PerformOAuth returns a usable token: the saved one if still valid, otherwise +// it runs the browser login. showURL is called with the login URL so the UI +// can display it in case the browser doesn't open by itself. +// The settings were loaded at startup (LoadConfig). +func PerformOAuth(ctx context.Context, showURL func(string)) (string, error) { + if HasValidToken() { + return token(), nil } - return "", fmt.Errorf("interface is nil") + return AuthUser(ctx, showURL) } -func isNil(i interface{}) bool { - if i == nil { - return true +func randomString(n int) (string, error) { + b := make([]byte, n) + if _, err := rand.Read(b); err != nil { + return "", err } - switch reflect.TypeOf(i).Kind() { - case reflect.Ptr, reflect.Map, reflect.Array, reflect.Chan, reflect.Slice: - return reflect.ValueOf(i).IsNil() + return base64.RawURLEncoding.EncodeToString(b), nil +} + +// quickUsername is the account's name for the login page, if Lichess +// answers quickly; the page doesn't wait long for it. +func quickUsername() string { + ch := make(chan string, 1) + go func() { + name, _ := GetUsername() + ch <- name + }() + select { + case name := <-ch: + return name + case <-time.After(2 * time.Second): + return "" } - return false } -func findPort() (int, error) { - port := 8000 - // foundOpenPort := false +// AuthUser runs the OAuth2 PKCE flow: it opens the browser at Lichess, waits on +// a localhost redirect for the authorization code, and trades it for a token. +func AuthUser(ctx context.Context, showURL func(string)) (string, error) { + ctx, cancel := context.WithTimeout(ctx, LoginTimeout) + defer cancel() - for port < 8100 { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + return "", fmt.Errorf("could not start local login server: %w", err) + } + redirectURL := fmt.Sprintf("http://%s/", ln.Addr().String()) - host := fmt.Sprintf("127.0.0.1:%d", port) + verifier, err := pkce.CreateCodeVerifier() + if err != nil { + ln.Close() + return "", err + } + state, err := randomString(16) + if err != nil { + ln.Close() + return "", err + } + authURL := HostUrl + "/oauth?" + url.Values{ + "response_type": {"code"}, + "client_id": {ClientID}, + "redirect_uri": {redirectURL}, + "code_challenge_method": {"S256"}, + "code_challenge": {verifier.CodeChallengeS256()}, + "scope": {strings.Join(Scopes, " ")}, + "state": {state}, + }.Encode() - ////fmt.Printf("Trying %s\n", host) - ln, err := net.Listen("tcp", host) - if err != nil { - //fmt.Fprintf(os.Stderr, "Can't listen on port %d: %s", port, err) - ////fmt.Printf("TCP Port %d is not available\n", port) - // move to next port - port++ - continue - } else { - _ = ln.Close() - //fmt.Printf("TCP Port %d is available\n", port) - return port, nil + type result struct { + token string + err error + } + results := make(chan result, 1) + finish := func(w http.ResponseWriter, r result) { + name := "" + if r.err == nil { + name = quickUsername() + } + w.Header().Set("Content-Type", "text/html; charset=utf-8") + _ = writeLoginPage(w, name, r.err) + select { + case results <- r: + default: } } - err := fmt.Errorf("unable to find an open port, failing") - return 0, err + mux := http.NewServeMux() + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + switch { + case q.Get("state") != state: + http.Error(w, "unexpected login callback", http.StatusBadRequest) + case q.Get("error") != "": + if q.Get("error") == "access_denied" { + finish(w, result{err: ErrLoginCancelled}) + } else { + finish(w, result{err: fmt.Errorf("lichess: %s", q.Get("error"))}) + } + case q.Get("code") == "": + finish(w, result{err: errors.New("no authorization code in callback")}) + default: + tok, expiresIn, err := getAccessToken(ctx, q.Get("code"), verifier.String(), redirectURL) + if err == nil { + err = setToken(tok, expiresIn) // keeps the other settings + } + finish(w, result{token: tok, err: err}) + } + }) + srv := &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second} + go srv.Serve(ln) + defer func() { + shutdownCtx, c := context.WithTimeout(context.Background(), 2*time.Second) + defer c() + srv.Shutdown(shutdownCtx) // lets the success page finish sending + }() -} + if showURL != nil { + showURL(authURL) + } + _ = open.Start(authURL) // if this fails the user can still use the shown URL -func cleanup(server *http.Server) { - // we run this as a goroutine so that this function falls through and - // the socket to the browser gets flushed/closed before the server goes away - go server.Close() + select { + case r := <-results: + return r.token, r.err + case <-ctx.Done(): + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + return "", errors.New("login timed out, try again") + } + return "", ctx.Err() + } } -func checkForJSON() error { - TimeCheck() - _, err := os.Stat(json_path) - if err == nil { - jsonFile, err := os.Open(json_path) - if err != nil { - return err - } - defer jsonFile.Close() - byteValue, _ := io.ReadAll(jsonFile) - err = json.Unmarshal(byteValue, &UserInfo) - if err != nil { - return err - } - } else if errors.Is(err, os.ErrNotExist) { // path/to/whatever does *not* exist - b, err := json.Marshal(&UserInfo) - if err != nil { - return err - } - err = os.WriteFile(json_path, b, 0644) - if err != nil { - return err - } - } else { - return err // file may or may not exist. See err for details. +// getAccessToken trades the authorization code for an access token. +func getAccessToken(ctx context.Context, code, codeVerifier, redirectURL string) (string, int64, error) { + form := url.Values{ + "grant_type": {"authorization_code"}, + "code": {code}, + "code_verifier": {codeVerifier}, + "redirect_uri": {redirectURL}, + "client_id": {ClientID}, + } + req, err := http.NewRequestWithContext(ctx, "POST", HostUrl+"/api/token", strings.NewReader(form.Encode())) + if err != nil { + return "", 0, err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + res, err := apiClient.Do(req) + if err != nil { + return "", 0, err + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + return "", 0, responseError(res) + } + var tok struct { + AccessToken string `json:"access_token"` + ExpiresIn int64 `json:"expires_in"` + } + if err := json.NewDecoder(res.Body).Decode(&tok); err != nil { + return "", 0, err + } + if tok.AccessToken == "" { + return "", 0, errors.New("lichess returned no access token") } - return nil + return tok.AccessToken, tok.ExpiresIn, nil } diff --git a/api/puzzles.go b/api/puzzles.go new file mode 100644 index 0000000..d583e33 --- /dev/null +++ b/api/puzzles.go @@ -0,0 +1,111 @@ +package api + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/url" +) + +// Puzzle is a Lichess puzzle and the game it comes from. +type Puzzle struct { + Game struct { + ID string `json:"id"` + PGN string `json:"pgn"` // SAN moves, up to and including the opponent's last move + Clock string `json:"clock"` + Rated bool `json:"rated"` + Perf struct{ Name string } `json:"perf"` + Players []struct { + Name string `json:"name"` + Title string `json:"title"` + Color string `json:"color"` + Rating int `json:"rating"` + } `json:"players"` + } `json:"game"` + Puzzle struct { + ID string `json:"id"` + Rating int `json:"rating"` + Plays int `json:"plays"` + InitialPly int `json:"initialPly"` + Solution []string `json:"solution"` // UCI; the player's moves are at even indexes + Themes []string `json:"themes"` + FEN string `json:"fen"` + LastMove string `json:"lastMove"` + } `json:"puzzle"` +} + +// Puzzle difficulties, relative to the player's puzzle rating (or 1500). +var PuzzleDifficulties = []string{"easiest", "easier", "normal", "harder", "hardest"} + +// GetDailyPuzzle fetches today's puzzle. No login needed. +func GetDailyPuzzle() (*Puzzle, error) { + var p Puzzle + if err := call("GET", "/api/puzzle/daily", nil, &p); err != nil { + return nil, err + } + return &p, nil +} + +// GetNextPuzzle fetches a random puzzle. When logged in, Lichess only sends +// puzzles the player hasn't seen, and difficulty is relative to their rating. +func GetNextPuzzle(difficulty string) (*Puzzle, error) { + q := url.Values{} + if difficulty != "" { + q.Set("difficulty", difficulty) + } + var p Puzzle + if err := call("GET", "/api/puzzle/next?"+q.Encode(), nil, &p); err != nil { + return nil, err + } + return &p, nil +} + +// PuzzleRound is Lichess's answer to a submitted puzzle result. +type PuzzleRound struct { + ID string `json:"id"` + Win bool `json:"win"` + RatingDiff int `json:"ratingDiff"` +} + +// PuzzleResult is what Lichess says after a result is submitted: the round +// and the player's new puzzle rating. +type PuzzleResult struct { + Rounds []PuzzleRound `json:"rounds"` + Glicko struct { + Rating float64 `json:"rating"` + Provisional bool `json:"provisional"` + } `json:"glicko"` +} + +// SubmitPuzzle records a solved (win) or failed puzzle on the player's +// account; rated decides whether it changes their puzzle rating. Needs a +// login with the puzzle:write scope. +func SubmitPuzzle(id string, win, rated bool) (*PuzzleResult, error) { + body, err := json.Marshal(map[string]any{ + "solutions": []map[string]any{{"id": id, "win": win, "rated": rated}}, + }) + if err != nil { + return nil, err + } + req, err := newRequest(context.Background(), "POST", "/api/puzzle/batch/mix", nil) + if err != nil { + return nil, err + } + req.Body = io.NopCloser(bytes.NewReader(body)) + req.ContentLength = int64(len(body)) + req.Header.Set("Content-Type", "application/json") + res, err := apiClient.Do(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + if res.StatusCode < 200 || res.StatusCode > 299 { + return nil, responseError(res) + } + var r PuzzleResult + if err := decode(json.NewDecoder(res.Body), &r); err != nil { + return nil, err + } + return &r, nil +} diff --git a/api/requests.go b/api/requests.go index 01fa5fa..f20f642 100644 --- a/api/requests.go +++ b/api/requests.go @@ -1,665 +1,316 @@ package api import ( + "bufio" + "context" "encoding/json" "fmt" "io" - "log" - "net/http" "net/url" - "strings" + "strconv" ) -//create a challenge against a specific user or get the url -func MakeMove(gameid string, move string) error { - requestUrl := fmt.Sprintf("%s/api/board/game/%s/move/%s", HostUrl, gameid, move) +// Time options used by CreateChallengeType.TimeOption. +const ( + TimeRealTime = 0 + TimeCorrespondence = 1 + TimeUnlimited = 2 +) - // create the request and execute it - req, err := http.NewRequest("POST", requestUrl, nil) - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", UserInfo.ApiToken)) - if err != nil { - return err +// challengeForm builds the shared challenge parameters (clock, variant, colour). +func challengeForm(c CreateChallengeType) url.Values { + f := url.Values{"variant": {c.Variant}} + if c.Color != "" { + f.Set("color", c.Color) } - - //do http request. must be done in this fashion so we can add the auth bear token headers above - client := &http.Client{} - res, err := client.Do(req) - if err != nil { - return err + if c.Fen != "" { + f.Set("fen", c.Fen) } - - if res.StatusCode != http.StatusOK { - //read resp body - body, err := io.ReadAll(res.Body) - if err != nil { - err := fmt.Errorf("%v", err) - return err - } - defer res.Body.Close() - - err = fmt.Errorf("%s\n%s", res.Status, string(body)) - return err + switch c.TimeOption { + case TimeRealTime: + f.Set("clock.limit", c.ClockLimit) + f.Set("clock.increment", c.ClockIncrement) + case TimeCorrespondence: + f.Set("days", c.Days) } - return nil + return f } -//create a challenge against a specific user or get the url (POST) -func CreateChallenge(challenge CreateChallengeType) (error, string) { - requestUrl := fmt.Sprintf("%s/api/challenge/%s", HostUrl, challenge.DestUser) - var reqParam url.Values - switch challenge.TimeOption { - case 0: //realtime - reqParam = url.Values{ - "rated": {challenge.Rated}, - "clock.limit": {challenge.ClockLimit}, - "clock.increment": {challenge.ClockIncrement}, - "color": {challenge.Color}, //enum: 0, 1, or 2 - "variant": {challenge.Variant}, - "keepAliveStream": {"true"}, - } - case 1: //corresondesnce - reqParam = url.Values{ - "rated": {challenge.Rated}, - "days": {challenge.Days}, - "color": {challenge.Color}, - "variant": {challenge.Variant}, - "keepAliveStream": {"true"}, - } - case 2: //unlimited - reqParam = url.Values{ - "rated": {challenge.Rated}, - "color": {challenge.Color}, - "variant": {challenge.Variant}, - "keepAliveStream": {"true"}, - } - } - - //application/x-www-form-urlencoded - - // create the request and add headers - req, err := http.NewRequest("POST", requestUrl, strings.NewReader(reqParam.Encode())) - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", UserInfo.ApiToken)) - req.Header.Add("Content-Type", "application/x-www-form-urlencoded") - - if err != nil { - return err, "" - } - - //do http request. must be done in this fashion so we can add the auth bear token headers above - client := &http.Client{} - res, err := client.Do(req) - if err != nil { - return err, "" - } - //read resp body - body, err := io.ReadAll(res.Body) //TODO: display body error on loading screen - if err != nil { - err := fmt.Errorf("%v", err) - return err, "" - } - defer res.Body.Close() +// Pending is an open challenge or seek. Lichess keeps it alive only while the +// connection stays open, so Cancel withdraws it. +type Pending struct { + ID string // challenge id (empty for real-time seeks) + cancel context.CancelFunc + done chan string +} - if res.StatusCode != http.StatusOK { - err := fmt.Errorf("%s", res.Status) - return err, "" +// Cancel withdraws the challenge or seek by closing its connection. +func (p *Pending) Cancel() { + if p != nil && p.cancel != nil { + p.cancel() } +} - d := json.NewDecoder(strings.NewReader(string(body))) - for { - select { - // case <-quit_stream: - // return nil - default: - var responseData map[string]interface{} - err = d.Decode(&responseData) - if err != nil { - if err != io.EOF { - log.Fatal(err) - return err, "" - } - continue +// Done delivers how the request ended ("accepted", "declined", "canceled", or +// "closed" if the connection dropped), then closes. +func (p *Pending) Done() <-chan string { return p.done } + +// keepAlive drains a kept-alive challenge/seek stream in the background until +// Lichess reports it finished or the connection closes. +func keepAlive(body io.ReadCloser, cancel context.CancelFunc, sc *bufio.Scanner) *Pending { + p := &Pending{cancel: cancel, done: make(chan string, 1)} + go func() { + defer body.Close() + defer close(p.done) + for sc.Scan() { + var msg struct { + Done string `json:"done"` } - if !isNil(responseData["challenge"]) { // retrieve the username out of the map - challenge := responseData["challenge"].(map[string]interface{}) - ChallengeId := challenge["id"].(string) - return nil, ChallengeId + if unmarshal(sc.Bytes(), &msg) == nil && msg.Done != "" { + p.done <- msg.Done + return } - //fmt.Printf("waiting 2") - //return fmt.Errorf("username response interface is nil") } - } - //return fmt.Errorf("username response interface is nil"), "" + p.done <- "closed" + }() + return p } -func CreateAiChallenge(challenge CreateChallengeType) (error, string) { - requestUrl := fmt.Sprintf("%s/api/challenge/ai", HostUrl) - var reqParam url.Values - switch challenge.TimeOption { - case 0: //realtime - reqParam = url.Values{ - "level": {challenge.Level}, - "clock.limit": {challenge.ClockLimit}, - "clock.increment": {challenge.ClockIncrement}, - "color": {challenge.Color}, //enum: 0, 1, or 2 - "variant": {challenge.Variant}, - "keepAliveStream": {"true"}, - } - case 1: //corresondesnce - reqParam = url.Values{ - "level": {challenge.Level}, - "days": {challenge.Days}, - "color": {challenge.Color}, - "variant": {challenge.Variant}, - "keepAliveStream": {"true"}, - } - case 2: //unlimited - reqParam = url.Values{ - "level": {challenge.Level}, - "color": {challenge.Color}, - "variant": {challenge.Variant}, - "keepAliveStream": {"true"}, - } +// CreateChallenge challenges a user. The challenge stays open until accepted, +// declined, or Pending.Cancel is called. +func CreateChallenge(c CreateChallengeType) (*Pending, error) { + if !ValidUsername(c.DestUser) { + return nil, ErrBadUsername } - - //application/x-www-form-urlencoded - - // create the request and add headers - req, err := http.NewRequest("POST", requestUrl, strings.NewReader(reqParam.Encode())) - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", UserInfo.ApiToken)) - req.Header.Add("Content-type", "application/x-www-form-urlencoded") - + f := challengeForm(c) + f.Set("rated", c.Rated) + f.Set("keepAliveStream", "true") + ctx, cancel := context.WithCancel(context.Background()) + body, err := openStream(ctx, "POST", "/api/challenge/"+url.PathEscape(c.DestUser), f) if err != nil { - return err, "" - } - - //do http request. must be done in this fashion so we can add the auth bear token headers above - client := &http.Client{} - res, err := client.Do(req) - if err != nil { - return err, "" - } - - //read resp body - body, err := io.ReadAll(res.Body) //TODO: display body error on loading screen - if err != nil { - err := fmt.Errorf("%v", err) - //log.Fatalln(err) - return err, "" - } - defer res.Body.Close() - - //fmt.Printf("%v", res.StatusCode) - //fmt.Printf(string(body)) - - if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated { - err := fmt.Errorf("%s", res.Status) - return err, "" + cancel() + return nil, err } - - d := json.NewDecoder(strings.NewReader(string(body))) - for { - select { - // case <-quit_stream: - // return nil - default: - var responseData map[string]interface{} - err = d.Decode(&responseData) - if err != nil { - if err != io.EOF { - log.Fatal(err) - return err, "" - } - continue - } - if !isNil(responseData["id"]) { // retrieve the username out of the map - ChallengeId := responseData["id"].(string) - return nil, ChallengeId - } - //fmt.Printf("waiting 2") - //return fmt.Errorf("username response interface is nil") + // The first line is the challenge itself; later lines report completion. + sc := bufio.NewScanner(body) + sc.Buffer(make([]byte, 64<<10), 1<<20) + for sc.Scan() { + var first struct { + Challenge struct { + ID string `json:"id"` + } `json:"challenge"` + ID string `json:"id"` } - } - //return fmt.Errorf("username response interface is nil"), "" -} - -func CreateSeek(challenge CreateChallengeType) error { - requestUrl := fmt.Sprintf("%s/api/board/seek", HostUrl) - var reqParam url.Values - switch challenge.TimeOption { - case 0: //realtime - reqParam = url.Values{ - "rated": {challenge.Rated}, - "clock.limit": {challenge.ClockLimit}, - "clock.increment": {challenge.ClockIncrement}, - "color": {challenge.Color}, //enum: 0, 1, or 2 - "variant": {challenge.Variant}, - "keepAliveStream": {"true"}, + if len(sc.Bytes()) == 0 { + continue // keep-alive newline } - case 1: //corresondesnce - reqParam = url.Values{ - "rated": {challenge.Rated}, - "days": {challenge.Days}, - "color": {challenge.Color}, - "variant": {challenge.Variant}, - "keepAliveStream": {"true"}, + if err := unmarshal(sc.Bytes(), &first); err != nil { + body.Close() + cancel() + return nil, fmt.Errorf("unexpected challenge response: %w", err) } - case 2: //unlimited - reqParam = url.Values{ - "rated": {challenge.Rated}, - "color": {challenge.Color}, - "variant": {challenge.Variant}, - "keepAliveStream": {"true"}, + p := keepAlive(body, cancel, sc) + p.ID = first.Challenge.ID + if p.ID == "" { + p.ID = first.ID } + return p, nil } + body.Close() + cancel() + return nil, fmt.Errorf("challenge stream closed before a challenge was created") +} - //application/x-www-form-urlencoded - - // create the request and add headers - req, err := http.NewRequest("POST", requestUrl, strings.NewReader(reqParam.Encode())) - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", UserInfo.ApiToken)) - req.Header.Add("Content-type", "application/x-www-form-urlencoded") - - if err != nil { - return err - } - - //do http request. must be done in this fashion so we can add the auth bear token headers above - client := &http.Client{} - res, err := client.Do(req) - if err != nil { - return err - } - - //read resp body - body, err := io.ReadAll(res.Body) //TODO: display body error on loading screen - if err != nil { - err := fmt.Errorf("%v", err) - return err +// CreateAiChallenge starts a game against Lichess's Stockfish and returns the +// game id. The game starts immediately. +func CreateAiChallenge(c CreateChallengeType) (string, error) { + f := challengeForm(c) + f.Set("level", c.Level) + var game struct { + ID string `json:"id"` } - defer res.Body.Close() - - if res.StatusCode != http.StatusOK { - err := fmt.Errorf("%s\n%s", res.Status, string(body)) - return err - } else { - return nil + if err := call("POST", "/api/challenge/ai", f, &game); err != nil { + return "", err } + return game.ID, nil } -func GetOngoingGames() ([]OngoingGameInfo, error) { - requestUrl := fmt.Sprintf("%s/api/account/playing", HostUrl) - reqParam := url.Values{"nb": {"11-50"}} - req, err := http.NewRequest("GET", requestUrl, strings.NewReader(reqParam.Encode())) - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", UserInfo.ApiToken)) - req.Header.Add("Content-Type", "application/json") - - if err != nil { +// CreateSeek looks for a random opponent. Real-time seeks stay open until an +// opponent is found or Pending.Cancel is called; correspondence seeks return +// straight away with an id. +func CreateSeek(c CreateChallengeType) (*Pending, error) { + f := url.Values{"rated": {c.Rated}, "variant": {c.Variant}} + if c.Color != "" && c.Color != "random" { + f.Set("color", c.Color) + } + switch c.TimeOption { + case TimeRealTime: + // The seek endpoint takes minutes + increment, unlike challenges. + f.Set("time", strconv.FormatFloat(c.MinTurn, 'f', -1, 64)) + f.Set("increment", c.ClockIncrement) + case TimeCorrespondence: + f.Set("days", c.Days) + default: + return nil, fmt.Errorf("seeks need a clock or days per move; unlimited games are challenge-only") + } + ctx, cancel := context.WithCancel(context.Background()) + body, err := openStream(ctx, "POST", "/api/board/seek", f) + if err != nil { + cancel() return nil, err } - - //do http request. must be done in this fashion so we can add the auth bear token headers above - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - err := fmt.Errorf("bad response: %v", resp.StatusCode) - return nil, err - } - d := json.NewDecoder(resp.Body) - var OngoingGames []OngoingGameInfo - for { - var responseData map[string]interface{} - err := d.Decode(&responseData) - if err != nil { - if err != io.EOF { - return nil, err - } else { - return OngoingGames, nil - } + if c.TimeOption == TimeCorrespondence { + defer body.Close() + defer cancel() + var seek struct { + ID string `json:"id"` } - - if !isNil(responseData["nowPlaying"]) { //make sure response is valid - jsonStr, err := json.Marshal(responseData["nowPlaying"]) - if err != nil { - return nil, err - } - var OngoingGameList []OngoingGameInfo - if err := json.Unmarshal(jsonStr, &OngoingGameList); err != nil { - return nil, err - } - OngoingGames = append(OngoingGames, OngoingGameList...) + if err := decode(json.NewDecoder(body), &seek); err != nil { + return nil, err } + done := make(chan string, 1) + done <- "created" + close(done) + return &Pending{ID: seek.ID, done: done}, nil } + sc := bufio.NewScanner(body) + return keepAlive(body, cancel, sc), nil } -func GetChallenges() ([]ChallengeInfo, []ChallengeInfo, error) { - requestUrl := fmt.Sprintf("%s/api/challenge", HostUrl) - req, err := http.NewRequest("GET", requestUrl, nil) - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", UserInfo.ApiToken)) - //req.Header.Add("Content-Type", "application/json") - - if err != nil { - return nil, nil, err - } - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return nil, nil, err - } - - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - err = fmt.Errorf("bad response: %v ", resp.Status) - return nil, nil, err +// GetOngoingGames lists the user's games in progress. +func GetOngoingGames() ([]OngoingGameInfo, error) { + var res struct { + NowPlaying []OngoingGameInfo `json:"nowPlaying"` } - - d := json.NewDecoder(resp.Body) - var IncomingChallenges []ChallengeInfo - var OutgoingChallenges []ChallengeInfo - - for { - var responseData map[string]interface{} - err := d.Decode(&responseData) - if err != nil { - if err != io.EOF { - return nil, nil, err - } else { - return IncomingChallenges, OutgoingChallenges, nil - } - } - - if !isNil(responseData["in"]) { //make sure response is valid - jsonStr, err := json.Marshal(responseData["in"]) - if err != nil { - return nil, nil, err - } - var In []ChallengeInfo - if err := json.Unmarshal(jsonStr, &In); err != nil { - return nil, nil, err - } - IncomingChallenges = append(IncomingChallenges, In...) - } - - if !isNil(responseData["out"]) { //make sure response is valid - jsonStr, err := json.Marshal(responseData["out"]) - if err != nil { - return nil, nil, err - } - var Out []ChallengeInfo - if err := json.Unmarshal(jsonStr, &Out); err != nil { - return nil, nil, err - } - OutgoingChallenges = append(OutgoingChallenges, Out...) - } + if err := call("GET", "/api/account/playing?nb=50", nil, &res); err != nil { + return nil, err } + return res.NowPlaying, nil } -//get user email -func GetEmail() (string, error) { - req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/account/email", HostUrl), nil) - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", UserInfo.ApiToken)) - if err != nil { - return "", err - } - //do http request. must be done in this fashion so we can add the auth bear token headers above - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return "", err +// GetChallenges lists incoming and outgoing challenges. +func GetChallenges() (in, out []ChallengeInfo, err error) { + var res struct { + In []ChallengeInfo `json:"in"` + Out []ChallengeInfo `json:"out"` } - body, _ := io.ReadAll(resp.Body) - if resp.StatusCode != http.StatusOK { - return "", fmt.Errorf(string(body)) - } - // unmarshal the json into a string map - var responseData map[string]interface{} - err = json.Unmarshal(body, &responseData) - if err != nil { - return "", err - } - - // retrieve the access token out of the map, and return to caller - if !isNil(responseData["email"]) { - return responseData["email"].(string), nil + if err := call("GET", "/api/challenge", nil, &res); err != nil { + return nil, nil, err } - return "", fmt.Errorf("response interface is nil") - + return res.In, res.Out, nil } -//get username from profile json +// GetUsername returns the logged-in user's username. func GetUsername() (string, error) { - req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/account", HostUrl), nil) - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", UserInfo.ApiToken)) - if err != nil { - return "", err - } - //do http request. must be done in this fashion so we can add the auth bear token headers above - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return "", err - } - body, _ := io.ReadAll(resp.Body) - if resp.StatusCode != http.StatusOK { - return "", fmt.Errorf(string(body)) + var acct struct { + Username string `json:"username"` } - // unmarshal the json into a string map - var responseData map[string]interface{} - err = json.Unmarshal(body, &responseData) - if err != nil { + if err := call("GET", "/api/account", nil, &acct); err != nil { return "", err } - - // retrieve the username out of the map, and return to caller - if !isNil(responseData["username"]) { - return responseData["username"].(string), nil + if acct.Username == "" { + return "", fmt.Errorf("lichess account has no username") } - return "", fmt.Errorf("response interface is nil") + return acct.Username, nil } -// //get full user profile json -// func GetProfile() error { -// req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/account", HostUrl), nil) -// req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", UserInfo.ApiToken)) -// if err != nil { -// return err -// } - -// //do http request. must be done in this fashion so we can add the auth bear token headers above -// client := &http.Client{} -// resp, err := client.Do(req) -// if err != nil { -// return err -// } -// body, _ := io.ReadAll(resp.Body) -// if resp.StatusCode != http.StatusOK { -// return fmt.Errorf(string(body)) -// } else if err != nil { -// return err -// } -// // unmarshal the json into a string map -// err = json.Unmarshal(body, &UserProfile) -// if err != nil { -// return err -// } -// return nil -// } - -//application/x-ndjson -//list of friends(and their online/offline status), to be displayed on challenge screen +// GetFriends returns the usernames the user follows. func GetFriends() ([]string, error) { - req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/rel/following", HostUrl), nil) - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", UserInfo.ApiToken)) - req.Header.Add("Content-Type", "application/x-ndjson") + body, err := openStream(context.Background(), "GET", "/api/rel/following", nil) if err != nil { return nil, err } - - //do http request. must be done in this fashion so we can add the auth bear token headers above - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - return nil, fmt.Errorf("GET FRIENDS %v: %v", resp.StatusCode, err) - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("GET FRIENDS bad response: %v", resp.StatusCode) - } - - d := json.NewDecoder(resp.Body) - var allFriends []string + defer body.Close() + var friends []string + d := json.NewDecoder(body) for { - var responseData map[string]interface{} - err := d.Decode(&responseData) - if err != nil { - if err != io.EOF { - return nil, err - } - return allFriends, nil + var u struct { + Username string `json:"username"` } - if !isNil(responseData["username"]) { // retrieve the username out of the map - FriendsString := responseData["username"].(string) - allFriends = append(allFriends, FriendsString) - } else { - return nil, fmt.Errorf("no type in stream event") + if err := decode(d, &u); err == io.EOF { + return friends, nil + } else if err != nil { + return friends, err + } + if u.Username != "" { + friends = append(friends, u.Username) } } } -func AcceptChallenge(gameid string) error { - requestUrl := fmt.Sprintf("%s/api/challenge/%s/accept", HostUrl, gameid) - - // create the request and execute it - req, err := http.NewRequest("POST", requestUrl, nil) - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", UserInfo.ApiToken)) - if err != nil { - return err - } - - //do http request - client := &http.Client{} - res, err := client.Do(req) - if err != nil { - return err - } - - if res.StatusCode != http.StatusOK { - err := fmt.Errorf("reponse %v", res.Status) - return err - } - return nil +// AcceptChallenge accepts an incoming challenge. +func AcceptChallenge(id string) error { + return call("POST", "/api/challenge/"+url.PathEscape(id)+"/accept", nil, nil) } -func AbortGame(gameid string) error { - requestUrl := fmt.Sprintf("%s/api/board/game/%s/abort", HostUrl, gameid) - - // create the request and execute it - req, err := http.NewRequest("POST", requestUrl, nil) - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", UserInfo.ApiToken)) - if err != nil { - return err - } - - //do http request - client := &http.Client{} - res, err := client.Do(req) - if err != nil { - return err - } - - if res.StatusCode != http.StatusOK { - err := fmt.Errorf("%v", res.Status) - return err +// DeclineChallenge declines an incoming challenge. reason may be empty, or one +// of Lichess's reasons: generic, later, tooFast, tooSlow, timeControl, rated, +// casual, standard, variant, noBot, onlyBot. +func DeclineChallenge(id, reason string) error { + var f url.Values + if reason != "" { + f = url.Values{"reason": {reason}} } - return nil + return call("POST", "/api/challenge/"+url.PathEscape(id)+"/decline", f, nil) } -func ResignGame(gameid string) error { - requestUrl := fmt.Sprintf("%s/api/board/game/%s/resign", HostUrl, gameid) - - // create the request and execute it - req, err := http.NewRequest("POST", requestUrl, nil) - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", UserInfo.ApiToken)) - if err != nil { - return err - } +// CancelChallenge withdraws an outgoing challenge. +func CancelChallenge(id string) error { + return call("POST", "/api/challenge/"+url.PathEscape(id)+"/cancel", nil, nil) +} - //do http request - client := &http.Client{} - res, err := client.Do(req) - if err != nil { - return err - } +func boardAction(gameID, action string) error { + return call("POST", "/api/board/game/"+url.PathEscape(gameID)+"/"+action, nil, nil) +} - if res.StatusCode != http.StatusOK { - err := fmt.Errorf("%v", res.Status) - return err +func yesNo(b bool) string { + if b { + return "yes" } - return nil + return "no" } -func HandleDraw(gameid string, accept bool) error { - var acceptStr string - if accept { - acceptStr = "yes" - } else { - acceptStr = "no" - } - requestUrl := fmt.Sprintf("%s/api/board/game/%s/draw/%s", HostUrl, gameid, acceptStr) +// MakeMove plays a move (UCI notation) in a Board API game. +func MakeMove(gameID, move string) error { return boardAction(gameID, "move/"+url.PathEscape(move)) } - // create the request and execute it - req, err := http.NewRequest("POST", requestUrl, nil) - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", UserInfo.ApiToken)) - if err != nil { - return err - } +// AbortGame aborts a game that hasn't really started yet. +func AbortGame(gameID string) error { return boardAction(gameID, "abort") } - //do http request - client := &http.Client{} - res, err := client.Do(req) - if err != nil { - return err - } +// ResignGame resigns a game. +func ResignGame(gameID string) error { return boardAction(gameID, "resign") } - if res.StatusCode != http.StatusOK { - err := fmt.Errorf("%v", res.Status) - return err - } - return nil +// HandleDraw offers/accepts (true) or declines (false) a draw. +func HandleDraw(gameID string, accept bool) error { + return boardAction(gameID, "draw/"+yesNo(accept)) +} +// HandleTakeback proposes/accepts (true) or declines (false) a takeback. +func HandleTakeback(gameID string, accept bool) error { + return boardAction(gameID, "takeback/"+yesNo(accept)) } -func HandleTakeback(gameid string, accept bool) error { - var acceptStr string - if accept { - acceptStr = "yes" - } else { - acceptStr = "no" - } - requestUrl := fmt.Sprintf("%s/api/board/game/%s/takeback/%s", HostUrl, gameid, acceptStr) +// ClaimVictory claims the win when the opponent has left the game. +func ClaimVictory(gameID string) error { return boardAction(gameID, "claim-victory") } - // create the request and execute it - req, err := http.NewRequest("POST", requestUrl, nil) - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", UserInfo.ApiToken)) - if err != nil { - return err - } +// ClaimDraw claims a draw when the opponent has left the game. (Threefold +// repetition is claimed by offering a draw.) +func ClaimDraw(gameID string) error { return boardAction(gameID, "claim-draw") } - //do http request - client := &http.Client{} - res, err := client.Do(req) - if err != nil { - return err - } +// ChatMessage is one line of game chat. +type ChatMessage struct { + User string `json:"user"` + Text string `json:"text"` +} - if res.StatusCode != http.StatusOK { - err := fmt.Errorf("%v", res.Status) - return err - } - return nil +// WriteChat posts to a game's chat. room is "player" or "spectator". +func WriteChat(gameID, room, text string) error { + return call("POST", "/api/board/game/"+url.PathEscape(gameID)+"/chat", + url.Values{"room": {room}, "text": {text}}, nil) +} +// GetChat fetches the player chat history of a game. +func GetChat(gameID string) ([]ChatMessage, error) { + var msgs []ChatMessage + err := call("GET", "/api/board/game/"+url.PathEscape(gameID)+"/chat", nil, &msgs) + return msgs, err } diff --git a/api/sanitize.go b/api/sanitize.go new file mode 100644 index 0000000..b07c3eb --- /dev/null +++ b/api/sanitize.go @@ -0,0 +1,155 @@ +package api + +import ( + "encoding/json" + "errors" + "reflect" + "regexp" + "strings" +) + +// Everything decoded from the network goes through sanitize before the UI +// sees it. Text like chat, player names, blog titles and error messages ends +// up on the terminal, and the terminal library passes control characters +// straight through, so a string containing ESC could inject escape sequences +// (move the cursor, change the title, worse with some terminals). JSON can +// carry those as \u001b escapes, so they're removed after decoding. + +// cleanString removes control characters (keeping newline and tab), C1 +// controls, and Unicode bidirectional overrides (which can make text display +// differently from what it says). +func cleanString(s string) string { + clean := true + for _, r := range s { + if unsafeRune(r) { + clean = false + break + } + } + if clean { + return s + } + return strings.Map(func(r rune) rune { + if unsafeRune(r) { + return -1 + } + return r + }, s) +} + +func unsafeRune(r rune) bool { + switch { + case r == '\n' || r == '\t': + return false + case r < 0x20, r >= 0x7f && r <= 0x9f: + return true + case r >= 0x202a && r <= 0x202e, r >= 0x2066 && r <= 0x2069, r == 0x200e, r == 0x200f, r == 0x061c: + return true + } + return false +} + +// sanitize cleans every string reachable from v (a pointer), in place. +func sanitize(v any) { + sanitizeValue(reflect.ValueOf(v), 0) +} + +func sanitizeValue(v reflect.Value, depth int) { + if depth > 32 || !v.IsValid() { + return + } + switch v.Kind() { + case reflect.Pointer, reflect.Interface: + if !v.IsNil() { + if v.Kind() == reflect.Interface { + // values inside interfaces aren't addressable: rebuild them + inner := v.Elem() + if inner.Kind() == reflect.String && v.CanSet() { + v.Set(reflect.ValueOf(cleanString(inner.String()))) + return + } + if inner.Kind() == reflect.Map || inner.Kind() == reflect.Slice || inner.Kind() == reflect.Pointer { + sanitizeValue(inner, depth+1) + } + return + } + sanitizeValue(v.Elem(), depth+1) + } + case reflect.String: + if v.CanSet() { + v.SetString(cleanString(v.String())) + } + case reflect.Struct: + for i := 0; i < v.NumField(); i++ { + if v.Type().Field(i).IsExported() { + sanitizeValue(v.Field(i), depth+1) + } + } + case reflect.Slice, reflect.Array: + if v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.Uint8 { + return // []byte / json.RawMessage: cleaned when decoded further + } + for i := 0; i < v.Len(); i++ { + sanitizeValue(v.Index(i), depth+1) + } + case reflect.Map: + for _, k := range v.MapKeys() { + val := v.MapIndex(k) + if val.Kind() == reflect.String { + v.SetMapIndex(k, reflect.ValueOf(cleanString(val.String())).Convert(val.Type())) + continue + } + if val.Kind() == reflect.Interface && val.Elem().Kind() == reflect.String { + v.SetMapIndex(k, reflect.ValueOf(cleanString(val.Elem().String()))) + continue + } + if val.Kind() == reflect.Pointer || val.Kind() == reflect.Map || val.Kind() == reflect.Interface { + sanitizeValue(val, depth+1) + } else if val.Kind() == reflect.Slice { + sanitizeValue(val, depth+1) + } else if val.Kind() == reflect.Struct { + // struct values in maps aren't addressable: copy, clean, store + cp := reflect.New(val.Type()).Elem() + cp.Set(val) + sanitizeValue(cp, depth+1) + v.SetMapIndex(k, cp) + } + } + } +} + +// unmarshal is json.Unmarshal followed by sanitize. +func unmarshal(data []byte, v any) error { + if err := json.Unmarshal(data, v); err != nil { + return err + } + sanitize(v) + return nil +} + +// decode reads the next JSON value from d into v and sanitizes it. +func decode(d *json.Decoder, v any) error { + if err := d.Decode(v); err != nil { + return err + } + sanitize(v) + return nil +} + +var ( + usernameRe = regexp.MustCompile(`^[A-Za-z0-9_-]{2,30}$`) + gameIDRe = regexp.MustCompile(`^[A-Za-z0-9]{8}$`) +) + +// ErrBadUsername / ErrBadGameID: what was typed can't be a Lichess +// username or game ID (checked before it goes into a request's URL). +var ( + ErrBadUsername = errors.New("that isn't a valid Lichess username") + ErrBadGameID = errors.New("that isn't a valid Lichess game ID") +) + +// ValidUsername reports whether s could be a Lichess username. +func ValidUsername(s string) bool { return usernameRe.MatchString(s) } + +// ValidGameID reports whether s could be a Lichess game ID. +func ValidGameID(s string) bool { return gameIDRe.MatchString(s) } diff --git a/api/sanitize_test.go b/api/sanitize_test.go new file mode 100644 index 0000000..1cb075a --- /dev/null +++ b/api/sanitize_test.go @@ -0,0 +1,86 @@ +package api + +import ( + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestCleanString(t *testing.T) { + for in, want := range map[string]string{ + "plain text": "plain text", + "gg\x1b]0;pwned\x07 wp": "gg]0;pwned wp", + "line one\nline two\tok": "line one\nline two\tok", + "csi\u009b31m": "csi31m", + "abc\u202edcba": "abcdcba", + "ünïcødé ♞ 象棋": "ünïcødé ♞ 象棋", + "\x00\x01\x7f": "", + } { + if got := cleanString(in); got != want { + t.Errorf("cleanString(%q) = %q, want %q", in, got, want) + } + } +} + +func TestSanitizeNested(t *testing.T) { + type inner struct{ Name string } + v := struct { + Title string + List []inner + Ptr *inner + Map map[string]string + Structs map[string]inner + Any any + private string + }{ + Title: "a\x1bb", + List: []inner{{"c\x1bd"}}, + Ptr: &inner{"e\x1bf"}, + Map: map[string]string{"k": "g\x1bh"}, + Structs: map[string]inner{"k": {"i\x1bj"}}, + Any: map[string]any{"x": "k\x1bl"}, + private: "m\x1bn", + } + sanitize(&v) + all := fmt.Sprint(v.Title, v.List, *v.Ptr, v.Map, v.Structs, v.Any) + if strings.ContainsRune(all, 0x1b) { + t.Errorf("control character left: %q", all) + } +} + +// End to end: a Lichess response with an escape sequence in a player's name +// arrives clean. +func TestResponsesAreSanitized(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, `{"username":"bad\u001b[2Jguy"}`) + })) + defer srv.Close() + old := HostUrl + HostUrl = srv.URL + defer func() { HostUrl = old }() + var out struct{ Username string } + if err := call("GET", "/api/account", nil, &out); err != nil { + t.Fatal(err) + } + if out.Username != "bad[2Jguy" { + t.Errorf("username = %q", out.Username) + } +} + +func TestValidation(t *testing.T) { + for _, ok := range []string{"DrNykterstein", "bob", "a_b-c9"} { + if !ValidUsername(ok) { + t.Errorf("%q rejected", ok) + } + } + for _, bad := range []string{"", "x", "../account", "a/b", "bob?x=1", "has space", strings.Repeat("a", 31)} { + if ValidUsername(bad) { + t.Errorf("%q accepted as a username", bad) + } + } + if !ValidGameID("q7ZvsdUF") || ValidGameID("q7ZvsdUF/") || ValidGameID("..") || ValidGameID("short") { + t.Error("game ID validation") + } +} diff --git a/api/stream.go b/api/stream.go index a1ab565..bae1e0c 100644 --- a/api/stream.go +++ b/api/stream.go @@ -1,173 +1,191 @@ package api import ( + "context" "encoding/json" - "fmt" + "errors" "io" - "log" "net/http" + "net/url" + "sync" + "sync/atomic" + "time" ) -//starts event stream for a user after login -func StreamEvent(EventChannel chan<- StreamEventType, got_token chan struct{}) error { - <-got_token - StreamEventStarted = true - req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/stream/event", HostUrl), nil) - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", UserInfo.ApiToken)) - req.Header.Add("Content-Type", "application/x-ndjson") - if err != nil { - //WriteLocal("STREAM EVENT REQ ERR", fmt.Sprintf("stream event get request failed: %v", err)) - log.Fatal(err) - } - //do http request. must be done in this fashion so we can add the auth bear token headers above - client := &http.Client{} - resp, err := client.Do(req) +var ( + online atomic.Bool + streamRunning atomic.Bool +) - if err != nil { - log.Fatal(fmt.Errorf("%v: %v", resp.StatusCode, err)) - return fmt.Errorf("%v: %v", resp.StatusCode, err) - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - //WriteLocal("STREAM EVENT RESP ERR", fmt.Sprintf("bad response: %v", resp.StatusCode)) - log.Fatal(fmt.Errorf("bad response: %v", resp.StatusCode)) +// IsOnline reports whether the account event stream is currently connected. +func IsOnline() bool { return online.Load() } + +// StartEventStream makes sure the account's event stream (game starts and +// finishes, challenges) is running, sending events to events. Call it after +// logging in; it does nothing if the stream is already running. The stream +// reconnects with backoff if the connection drops, and stops if the token is +// rejected (a later login starts it again). +func StartEventStream(events chan<- StreamEventType) { + if streamRunning.CompareAndSwap(false, true) { + ctx, cancel := context.WithCancel(context.Background()) + streamMu.Lock() + streamStop = cancel + streamMu.Unlock() + go streamEvents(ctx, events) } +} - Online = true +// StopEventStream stops the account event stream (e.g. when logging out). +func StopEventStream() { + streamMu.Lock() + defer streamMu.Unlock() + if streamStop != nil { + streamStop() + streamStop = nil + } +} - d := json.NewDecoder(resp.Body) +var ( + streamMu sync.Mutex + streamStop context.CancelFunc +) - for { - var responseData map[string]interface{} - err := d.Decode(&responseData) - if err != nil { - if err != io.EOF { - return err - } - continue +func streamEvents(ctx context.Context, events chan<- StreamEventType) { + defer streamRunning.Store(false) + backoff := time.Second + for ctx.Err() == nil { + start := time.Now() + err := streamEventsOnce(ctx, events) + online.Store(false) + var apiErr *APIError + if errors.As(err, &apiErr) && apiErr.Status == http.StatusUnauthorized { + return // token revoked or expired; reconnecting won't help } - if !isNil(responseData["type"]) { - - streamEvent := responseData["type"].(string) - var streamEventID string - var streamSource string - switch streamEvent { - case "gameStart", "gameFinish": //game type stream event - game := responseData["game"].(map[string]interface{}) - streamEventID = game["id"].(string) - streamSource = game["source"].(string) - - // jsonStr, err := json.Marshal(responseData) - // if err != nil { - // log.Fatal(err) - // } - // if err := json.Unmarshal(jsonStr, &CurrentStreamEventGame); err != nil { - // log.Fatal(err) - // } - - case "challenge", "challengeCanceled", "challengeDeclined": //challenge type stream event - challenge := responseData["challenge"].(map[string]interface{}) - streamEventID = challenge["id"].(string) + if time.Since(start) > time.Minute { + backoff = time.Second // it was a healthy connection; retry quickly + } + select { + case <-ctx.Done(): + return + case <-time.After(backoff): + } + backoff = min(backoff*2, time.Minute) + } +} - // jsonStr, err := json.Marshal(responseData) - // if err != nil { - // log.Fatal(err) - // } - // if err := json.Unmarshal(jsonStr, &CurrentStreamEventChallenge); err != nil { - // log.Fatal(err) - // } +func streamEventsOnce(ctx context.Context, events chan<- StreamEventType) error { + body, err := openStream(ctx, "GET", "/api/stream/event", nil) + if err != nil { + return err + } + defer body.Close() + online.Store(true) + d := json.NewDecoder(body) + for { + var ev struct { + Type string `json:"type"` + Game struct { + ID string `json:"id"` + Source string `json:"source"` + } `json:"game"` + Challenge struct { + ID string `json:"id"` + } `json:"challenge"` + } + if err := decode(d, &ev); err != nil { + if err == io.EOF { + return io.ErrUnexpectedEOF } - EventChannel <- StreamEventType{streamEvent, streamEventID, streamSource} - } else { - Online = false - return fmt.Errorf("invalid stream event") + return err + } + out := StreamEventType{EventType: ev.Type} + switch ev.Type { + case "gameStart", "gameFinish": + out.GameID, out.Source = ev.Game.ID, ev.Game.Source + case "challenge", "challengeCanceled", "challengeDeclined": + out.GameID = ev.Challenge.ID + default: + continue // unknown event types are ignored, not fatal + } + select { + case events <- out: + case <-ctx.Done(): + return ctx.Err() } } } -//https://lichess.org/api/board/game/stream/{gameId} -//after initializing a game, this function streams the the state of the board of the game -func StreamBoardState(EventChannel chan<- BoardEvent, StreamError chan<- error, game string) { - req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/board/game/stream/%s", HostUrl, game), nil) - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", UserInfo.ApiToken)) - req.Header.Add("Content-Type", "application/x-ndjson") - if err != nil { - StreamError <- fmt.Errorf("stream event get request failed: %v", err) +// StreamBoardState streams one game's events (full state, moves, chat, the +// opponent leaving) until the game stream ends, an error occurs, or ctx is +// cancelled. Exactly one of these happens at the end: an EOF event is sent, +// an error is sent on errs, or ctx is done. +func StreamBoardState(ctx context.Context, events chan<- BoardEvent, errs chan<- error, gameID string) { + send := func(ev BoardEvent) bool { + select { + case events <- ev: + return true + case <-ctx.Done(): + return false + } + } + fail := func(err error) { + select { + case errs <- err: + case <-ctx.Done(): + } } - client := &http.Client{} - resp, err := client.Do(req) + body, err := openStream(ctx, "GET", "/api/board/game/stream/"+url.PathEscape(gameID), nil) if err != nil { - StreamError <- fmt.Errorf("%v: %v", resp.Status, err) + fail(err) + return } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - StreamError <- fmt.Errorf("%v", resp.Status) - } - - d := json.NewDecoder(resp.Body) + defer body.Close() + d := json.NewDecoder(body) for { - var responseData map[string]interface{} - err := d.Decode(&responseData) - - if err != nil { - if err != io.EOF { - StreamError <- err + var raw json.RawMessage + if err := decode(d, &raw); err != nil { + if ctx.Err() != nil { return - } else { - EventChannel <- BoardEvent{Type: EOF} + } + if err == io.EOF { + send(BoardEvent{Type: EOF}) return } + fail(err) + return } - - if !isNil(responseData["type"]) { //make sure response is valid - var bEvent BoardEvent - streamEvent := responseData["type"].(string) - - switch streamEvent { - - case "gameFull": - bEvent.Type = GameFull - jsonStr, err := json.Marshal(responseData) - if err != nil { - log.Fatal(err) - } - if err := json.Unmarshal(jsonStr, &bEvent.Full); err != nil { - log.Fatal(err) - } - - case "gameState": - bEvent.Type = GameState - jsonStr, err := json.Marshal(responseData) - if err != nil { - log.Fatal(err) - } - if err := json.Unmarshal(jsonStr, &bEvent.State); err != nil { - log.Fatal(err) - } - - case "chatLine": - bEvent.Type = ChatLine - - case "chatLineSpectator": - bEvent.Type = ChatLineSpectator - - case "gameStateResign": - bEvent.Type = GameStateResign - jsonStr, err := json.Marshal(responseData) - if err != nil { - log.Fatal(err) - } - if err := json.Unmarshal(jsonStr, &bEvent.Resign); err != nil { - log.Fatal(err) - } - - } - EventChannel <- bEvent //signal what event just happened - } else { - StreamError <- fmt.Errorf("invalid ndjson") + var head struct { + Type string `json:"type"` + } + if err := unmarshal(raw, &head); err != nil { + fail(err) + return + } + var ev BoardEvent + switch head.Type { + case "gameFull": + ev.Type = GameFull + err = unmarshal(raw, &ev.Full) + case "gameState": + ev.Type = GameState + err = unmarshal(raw, &ev.State) + case "chatLine": + ev.Type = ChatLine + err = unmarshal(raw, &ev.Chat) + case "opponentGone": + ev.Type = OpponentGone + err = unmarshal(raw, &ev.Gone) + default: + continue + } + if err != nil { + fail(err) + return + } + if !send(ev) { return } } diff --git a/api/study.go b/api/study.go new file mode 100644 index 0000000..fe075ec --- /dev/null +++ b/api/study.go @@ -0,0 +1,111 @@ +package api + +import ( + "context" + "errors" + "io" + "net/url" + "regexp" + "sort" + "strings" + "time" +) + +// Lichess studies: a user's list of studies, and a study's chapters as PGN +// (with variations, comments and the arrows and circles drawn in it). +// Private studies need the study:read scope, which the login asks for. + +// StudyInfo is one study in a user's list. +type StudyInfo struct { + ID string + Name string + Updated time.Time +} + +// ErrBadStudyID: what was typed isn't a Lichess study link or ID. +var ErrBadStudyID = errors.New("that isn't a Lichess study link or ID") + +var studyIDRe = regexp.MustCompile(`^[a-zA-Z0-9]{8}$`) + +// ValidStudyID reports whether s looks like a study (or chapter) ID. +func ValidStudyID(s string) bool { return studyIDRe.MatchString(s) } + +// StudyIDFrom takes a study link (lichess.org/study/abcd1234[/chapter]) or a +// bare ID and returns the study and chapter IDs (chapter may be ""). +func StudyIDFrom(s string) (study, chapter string) { + s = strings.TrimSpace(s) + if i := strings.IndexAny(s, "?#"); i >= 0 { + s = s[:i] + } + if i := strings.Index(s, "/study/"); i >= 0 { + s = s[i+len("/study/"):] + } + parts := strings.Split(strings.Trim(s, "/"), "/") + study = parts[0] + if len(parts) > 1 && ValidStudyID(parts[1]) { + chapter = parts[1] + } + return study, chapter +} + +// ListStudies lists a user's studies, most recently changed first. With a +// token for that user it includes their private studies. +func ListStudies(username string) ([]StudyInfo, error) { + if !ValidUsername(username) { + return nil, ErrBadUsername + } + req, err := newRequest(context.Background(), "GET", "/api/study/by/"+url.PathEscape(username), nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/x-ndjson") + res, err := apiClient.Do(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + if res.StatusCode < 200 || res.StatusCode > 299 { + return nil, responseError(res) + } + var out []StudyInfo + err = eachLine(res.Body, func(line []byte) { + var s struct { + ID string `json:"id"` + Name string `json:"name"` + UpdatedAt int64 `json:"updatedAt"` + } + if unmarshal(line, &s) == nil && ValidStudyID(s.ID) { + out = append(out, StudyInfo{ID: s.ID, Name: strings.TrimSpace(s.Name), Updated: time.UnixMilli(s.UpdatedAt)}) + } + }) + sort.SliceStable(out, func(i, j int) bool { return out[i].Updated.After(out[j].Updated) }) + return out, err +} + +// maxStudyPGN caps a study download (Lichess allows 64 chapters). +const maxStudyPGN = 16 << 20 + +// GetStudyPGN downloads all of a study's chapters as PGN. +func GetStudyPGN(id string) (string, error) { + if !ValidStudyID(id) { + return "", ErrBadStudyID + } + q := url.Values{"comments": {"true"}, "variations": {"true"}, "clocks": {"false"}, "orientation": {"true"}} + req, err := newRequest(context.Background(), "GET", "/api/study/"+id+".pgn?"+q.Encode(), nil) + if err != nil { + return "", err + } + res, err := apiClient.Do(req) + if err != nil { + return "", err + } + defer res.Body.Close() + if res.StatusCode < 200 || res.StatusCode > 299 { + return "", responseError(res) + } + body, err := io.ReadAll(io.LimitReader(res.Body, maxStudyPGN)) + if err != nil { + return "", err + } + return cleanString(string(body)), nil // no terminal escapes from comments +} diff --git a/api/study_test.go b/api/study_test.go new file mode 100644 index 0000000..3b5e66b --- /dev/null +++ b/api/study_test.go @@ -0,0 +1,43 @@ +package api + +import ( + "fmt" + "net/http" + "strings" + "testing" +) + +func TestStudies(t *testing.T) { + fakeLichess(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/study/by/harry": + fmt.Fprintln(w, `{"id":"old00001","name":"Old","updatedAt":1000}`) + fmt.Fprintln(w, `{"id":"new00001","name":"New \u001b[31mred","updatedAt":2000}`) + fmt.Fprintln(w, `{"id":"../evil","name":"Bad id","updatedAt":3000}`) + case "/api/study/abcd1234.pgn": + fmt.Fprint(w, "[Event \"x\"]\n\n1. e4 { hi \x1b]0;title\x07 } *") + default: + http.NotFound(w, r) + } + })) + list, err := ListStudies("harry") + if err != nil { + t.Fatal(err) + } + if len(list) != 2 || list[0].ID != "new00001" || list[0].Name != "New [31mred" { + t.Errorf("studies: %+v", list) + } + if _, err := ListStudies("bad/name"); err != ErrBadUsername { + t.Errorf("bad username: %v", err) + } + pgn, err := GetStudyPGN("abcd1234") + if err != nil { + t.Fatal(err) + } + if strings.ContainsAny(pgn, "\x1b\x07") || !strings.Contains(pgn, "1. e4") { + t.Errorf("pgn not cleaned: %q", pgn) + } + if _, err := GetStudyPGN("../x"); err != ErrBadStudyID { + t.Errorf("bad id: %v", err) + } +} diff --git a/api/watch.go b/api/watch.go new file mode 100644 index 0000000..aec29b0 --- /dev/null +++ b/api/watch.go @@ -0,0 +1,261 @@ +package api + +import ( + "bufio" + "context" + "encoding/json" + "net/url" + "strings" +) + +// Watching games: Lichess TV and any ongoing game. No login needed. Lichess +// sends ongoing games 3 moves behind, so the API can't help cheaters. + +// TV channels the board can show (standard-rules games), in menu order. +var TvChannels = []struct{ Key, Name string }{ + {"best", "Top rated"}, {"bullet", "Bullet"}, {"blitz", "Blitz"}, {"rapid", "Rapid"}, + {"classical", "Classical"}, {"chess960", "Chess960"}, {"bot", "Bots"}, {"computer", "Computer"}, +} + +// WatchPlayer is one side of a watched game. +type WatchPlayer struct { + Name string + Title string + Rating int +} + +// WatchUpdate is one message from a watch stream: a new game (Game set), +// a position, or the game ending (Status set). +type WatchUpdate struct { + Game *WatchGame // a new game starts (TV changes game, or the first message) + FEN string + LastMove string // UCI + WhiteClock, BlackClock int // seconds; -1 if unknown + Status string // set when the game is over, e.g. "mate", "resign" + Winner string +} + +// WatchGame describes a watched game. +type WatchGame struct { + ID string + White, Black WatchPlayer + Orientation string // "white" or "black": which side TV shows at the bottom + Speed string + Rated bool + Moves string // SAN moves so far, when known + InitialFEN string + ClockInitial int // seconds each side started with; 0 if unknown + ClockIncrement int // seconds added per move + DaysPerTurn int // correspondence +} + +// StreamTv follows a TV channel until ctx is cancelled or the stream ends. +func StreamTv(ctx context.Context, channel string, fn func(WatchUpdate)) error { + body, err := openStream(ctx, "GET", "/api/tv/"+url.PathEscape(channel)+"/feed", nil) + if err != nil { + return err + } + defer body.Close() + return eachLine(body, func(line []byte) { + var msg struct { + T string `json:"t"` + D struct { + ID string `json:"id"` + Orientation string `json:"orientation"` + FEN string `json:"fen"` + LM string `json:"lm"` + WC *int `json:"wc"` + BC *int `json:"bc"` + Players []struct { + Color string `json:"color"` + Rating int `json:"rating"` + Seconds int `json:"seconds"` + User struct { + Name string `json:"name"` + Title string `json:"title"` + } `json:"user"` + } `json:"players"` + } `json:"d"` + } + if unmarshal(line, &msg) != nil { + return + } + u := WatchUpdate{FEN: msg.D.FEN, LastMove: msg.D.LM, WhiteClock: -1, BlackClock: -1} + if msg.D.WC != nil { + u.WhiteClock = *msg.D.WC + } + if msg.D.BC != nil { + u.BlackClock = *msg.D.BC + } + if msg.T == "featured" { + g := &WatchGame{ID: msg.D.ID, Orientation: msg.D.Orientation} + for _, p := range msg.D.Players { + wp := WatchPlayer{Name: p.User.Name, Title: p.User.Title, Rating: p.Rating} + if p.Color == "white" { + g.White, u.WhiteClock = wp, p.Seconds + } else { + g.Black, u.BlackClock = wp, p.Seconds + } + } + u.Game = g + } + if u.FEN != "" || u.Game != nil { + fn(u) + } + }) +} + +// gameJSON is a game as Lichess exports it (and as the game stream starts). +type gameJSON struct { + ID string `json:"id"` + Speed string `json:"speed"` + Rated bool `json:"rated"` + Status string `json:"status"` + Winner string `json:"winner"` + Moves string `json:"moves"` + InitialFen string `json:"initialFen"` + FEN string `json:"fen"` + LastMove string `json:"lastMove"` + Clock struct { + Initial int `json:"initial"` + Increment int `json:"increment"` + } `json:"clock"` + DaysPerTurn int `json:"daysPerTurn"` + Players struct { + White, Black struct { + Rating int `json:"rating"` + User struct { + Name string `json:"name"` + Title string `json:"title"` + } `json:"user"` + AiLevel int `json:"aiLevel"` + } + } `json:"players"` +} + +func (g gameJSON) watchGame() *WatchGame { + player := func(name, title string, rating, ai int) WatchPlayer { + if name == "" && ai > 0 { + name = "Stockfish level " + string(rune('0'+ai)) + } + return WatchPlayer{Name: name, Title: title, Rating: rating} + } + return &WatchGame{ + ID: g.ID, Speed: g.Speed, Rated: g.Rated, Moves: g.Moves, InitialFEN: g.InitialFen, Orientation: "white", + ClockInitial: g.Clock.Initial, ClockIncrement: g.Clock.Increment, DaysPerTurn: g.DaysPerTurn, + White: player(g.Players.White.User.Name, g.Players.White.User.Title, g.Players.White.Rating, g.Players.White.AiLevel), + Black: player(g.Players.Black.User.Name, g.Players.Black.User.Title, g.Players.Black.Rating, g.Players.Black.AiLevel), + } +} + +// GetGame fetches a game with its moves so far. +func GetGame(id string) (*WatchGame, error) { + if !ValidGameID(id) { + return nil, ErrBadGameID + } + var g gameJSON + if err := callJSON("/game/export/"+url.PathEscape(id)+"?moves=true&clocks=false&evals=false", &g); err != nil { + return nil, err + } + return g.watchGame(), nil +} + +// GetCurrentGame fetches a player's ongoing (or last) game. +func GetCurrentGame(username string) (*WatchGame, error) { + if !ValidUsername(username) { + return nil, ErrBadUsername + } + var g gameJSON + if err := callJSON("/api/user/"+url.PathEscape(username)+"/current-game?moves=true&clocks=false&evals=false", &g); err != nil { + return nil, err + } + return g.watchGame(), nil +} + +// callJSON is a GET asking for JSON (some endpoints default to PGN). +func callJSON(path string, out any) error { + req, err := newRequest(context.Background(), "GET", path, nil) + if err != nil { + return err + } + req.Header.Set("Accept", "application/json") + res, err := apiClient.Do(req) + if err != nil { + return err + } + defer res.Body.Close() + if res.StatusCode < 200 || res.StatusCode > 299 { + return responseError(res) + } + return decode(json.NewDecoder(res.Body), out) +} + +// StreamGame follows an ongoing game until it ends or ctx is cancelled. The +// first update describes the game; the last has its Status. +func StreamGame(ctx context.Context, id string, fn func(WatchUpdate)) error { + if !ValidGameID(id) { + return ErrBadGameID + } + body, err := openStream(ctx, "GET", "/api/stream/game/"+url.PathEscape(id), nil) + if err != nil { + return err + } + defer body.Close() + return eachLine(body, func(line []byte) { + var msg struct { + gameJSON + LM string `json:"lm"` + WC *int `json:"wc"` + BC *int `json:"bc"` + } + if unmarshal(line, &msg) != nil { + return + } + u := WatchUpdate{FEN: msg.FEN, LastMove: msg.LM, WhiteClock: -1, BlackClock: -1} + if msg.WC != nil { + u.WhiteClock = *msg.WC + } + if msg.BC != nil { + u.BlackClock = *msg.BC + } + if msg.ID != "" { // a game description: the first message, and the last + if msg.Status != "" && msg.Status != "started" && msg.Status != "created" { + u.Status, u.Winner = msg.Status, msg.Winner + } else { + u.Game = msg.watchGame() + } + if u.LastMove == "" { + u.LastMove = msg.LastMove + } + } + fn(u) + }) +} + +// GameIDFrom extracts a game ID from a Lichess link or a bare ID. +func GameIDFrom(s string) string { + s = strings.TrimSpace(s) + if i := strings.Index(s, "lichess.org/"); i >= 0 { + s = s[i+len("lichess.org/"):] + } + s = strings.Trim(s, "/") + if i := strings.IndexAny(s, "/?#"); i >= 0 { + s = s[:i] + } + if len(s) > 8 { // links to a player's view add 4 characters + s = s[:8] + } + return s +} + +// eachLine calls fn for each non-empty line of an ndjson stream. +func eachLine(r interface{ Read([]byte) (int, error) }, fn func([]byte)) error { + sc := bufio.NewScanner(r) + sc.Buffer(make([]byte, 64<<10), 1<<20) + for sc.Scan() { + if line := sc.Bytes(); len(line) > 0 { + fn(line) + } + } + return sc.Err() +} diff --git a/go.mod b/go.mod index cc3f034..9caac2d 100644 --- a/go.mod +++ b/go.mod @@ -1,15 +1,17 @@ module github.com/nate-xyz/chess-cli -go 1.24.0 +go 1.26.0 require ( - code.rocketnine.space/tslocum/cview v1.5.7 - github.com/gdamore/tcell v1.4.0 + codeberg.org/tslocum/cview v1.6.3 github.com/gdamore/tcell/v3 v3.1.2 github.com/jimlambrt/go-oauth-pkce-code-verifier v0.0.0-20201220003123-6363600dffda github.com/notnil/chess v1.7.2 github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 - golang.org/x/text v0.33.0 + golang.org/x/image v0.48.0 + golang.org/x/sys v0.50.0 + golang.org/x/term v0.39.0 + golang.org/x/text v0.44.0 ) require ( @@ -20,11 +22,4 @@ require ( github.com/lucasb-eyer/go-colorful v1.3.0 // indirect github.com/mattn/go-runewidth v0.0.19 // indirect github.com/rivo/uniseg v0.4.7 // indirect - golang.org/x/sys v0.40.0 // indirect - golang.org/x/term v0.39.0 // indirect -) - -replace ( - code.rocketnine.space/tslocum/cbind => codeberg.org/tslocum/cbind v0.1.8 - code.rocketnine.space/tslocum/cview => codeberg.org/tslocum/cview v1.6.3 ) diff --git a/go.sum b/go.sum index a9f6dfa..9a8410c 100644 --- a/go.sum +++ b/go.sum @@ -7,19 +7,14 @@ github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfa github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA= github.com/clipperhouse/uax29/v2 v2.3.0 h1:SNdx9DVUqMoBuBoW3iLOj4FQv3dN5mDtuqwuhIGpJy4= github.com/clipperhouse/uax29/v2 v2.3.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g= -github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg= github.com/gdamore/encoding v1.0.1 h1:YzKZckdBL6jVt2Gc+5p82qhrGiqMdG/eNs6Wy0u3Uhw= github.com/gdamore/encoding v1.0.1/go.mod h1:0Z0cMFinngz9kS1QfMjCP8TY7em3bZYeeklsSDPivEo= -github.com/gdamore/tcell v1.4.0 h1:vUnHwJRvcPQa3tzi+0QI4U9JINXYJlOz9yiaiPQ2wMU= -github.com/gdamore/tcell v1.4.0/go.mod h1:vxEiSDZdW3L+Uhjii9c3375IlDmR05bzxY404ZVSMo0= github.com/gdamore/tcell/v3 v3.1.2 h1:qEaXnDaYZpCIMDfa3XFHkxrwFBINUuDiePwj39vErZ8= github.com/gdamore/tcell/v3 v3.1.2/go.mod h1:MikpZpivMtggrw1kL999dI2VuXw6Wya4724VAh3DzIg= github.com/jimlambrt/go-oauth-pkce-code-verifier v0.0.0-20201220003123-6363600dffda h1:bQONHNUnOORYC/LwlHqYTRdK40usp79dLXFffPKxLz0= github.com/jimlambrt/go-oauth-pkce-code-verifier v0.0.0-20201220003123-6363600dffda/go.mod h1:dRScMNYlkRbOXpUiqNHR6mSBOzXgepLOFIX5M4RFgbk= -github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag= github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= -github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw= github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= github.com/notnil/chess v1.7.2 h1:9Khpc/5a2jvSlDZaOLiowB9QSof6iwPgjiRvlu3Ce4E= @@ -31,6 +26,8 @@ github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966/go.mod h1:s github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/image v0.48.0 h1:1AvuPcuoOTJpA7s4VZ5umrb90T3So0rkB/bSGmxkxik= +golang.org/x/image v0.48.0/go.mod h1:mmtg64iqJKGqEgy+r13dfybl85tmxUd2lMnmaiSdWYY= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -41,14 +38,13 @@ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190626150813-e07cf5db2756/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ= -golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= +golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -59,8 +55,8 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= -golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE= -golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8= +golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= +golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= diff --git a/main.go b/main.go index c5f47a0..976ef1f 100644 --- a/main.go +++ b/main.go @@ -1,17 +1,74 @@ package main import ( + "errors" + "fmt" "os" "runtime" - cv "code.rocketnine.space/tslocum/cview" - "github.com/gdamore/tcell/encoding" + cv "codeberg.org/tslocum/cview" + _ "github.com/gdamore/tcell/v3/encoding" // support non-UTF-8 terminals api "github.com/nate-xyz/chess-cli/api" pkg "github.com/nate-xyz/chess-cli/pkg" ) +// version is set at release build time (see .goreleaser.yaml). +var version = "dev" + +const usage = `chess-cli: play chess in the terminal, locally or on Lichess. + +Usage: chess-cli [--version | --help | --reset] + + --reset put all settings back to their defaults; the first-run setup + runs next time (your Lichess login and saved games are kept) + +Files are kept in %s +` + func main() { - encoding.Register() + if len(os.Args) > 1 { + switch os.Args[1] { + case "-v", "--version", "version": + fmt.Println("chess-cli", version) + return + case "--reset": + if dir, err := api.ConfigDir(); err == nil { + if err := pkg.LockInstance(dir); errors.Is(err, pkg.ErrAlreadyRunning) { + fmt.Fprintf(os.Stderr, "%v: quit it first, then reset.\n", err) + os.Exit(1) + } + } + if err := api.LoadConfig(); err != nil && !errors.Is(err, os.ErrNotExist) { + fmt.Fprintf(os.Stderr, "Couldn't read the settings (%v); writing defaults.\n", err) + } + if err := api.ResetPreferences(); err != nil { + fmt.Fprintln(os.Stderr, "Couldn't reset:", err) + os.Exit(1) + } + fmt.Println("Settings reset to defaults. Your Lichess login and saved games are kept.") + fmt.Println("Run chess-cli to go through the first-run setup again.") + return + default: + dir, err := api.ConfigDir() + if err != nil { + dir = "your user config directory" + } + fmt.Printf(usage, dir) + if os.Args[1] != "-h" && os.Args[1] != "--help" && os.Args[1] != "help" { + os.Exit(2) + } + return + } + } + if dir, err := api.ConfigDir(); err == nil { + if err := pkg.LockInstance(dir); errors.Is(err, pkg.ErrAlreadyRunning) { + fmt.Fprintf(os.Stderr, "%v.\nSwitch to that window, or quit it first.\n", err) + os.Exit(1) + } + } + _ = api.LoadConfig() // for saved preferences; a broken file is reported at login + pkg.SetupRendering() // must run before the UI takes over the terminal + shell := os.Getenv("SHELL") if shell == "" { if runtime.GOOS == "windows" { @@ -29,8 +86,6 @@ func main() { pkg.Root.App = App pkg.StreamChannel = make(chan api.StreamEventType, 1) - pkg.Ready = make(chan struct{}) - go api.StreamEvent(pkg.StreamChannel, pkg.Ready) go pkg.StreamConsumer(pkg.StreamChannel) pkg.InitUI() diff --git a/pkg/analysis.go b/pkg/analysis.go new file mode 100644 index 0000000..18a93c6 --- /dev/null +++ b/pkg/analysis.go @@ -0,0 +1,335 @@ +package pkg + +import ( + "context" + "math" + "time" + + "github.com/notnil/chess" +) + +// Computer analysis of a finished game with the local Stockfish, worked out +// the way Lichess does it, so the numbers mean the same: +// - win% from the engine's centipawns (capped at ±1000; mate counts as +// ±1000): 50 + 50·(2/(1+e^(−0.00368208·cp)) − 1) +// - a move's accuracy from the win% it threw away: +// 103.1668·e^(−0.04354·drop) − 3.1669, +1, kept within 0–100 +// - a side's game accuracy: the mean of its move accuracies weighted by +// how volatile the position was (win% spread over a sliding window), +// averaged with their harmonic mean +// - inaccuracy / mistake / blunder: the move cost 0.1 / 0.2 / 0.3 in +// winning chances (win% on a −1…1 scale) +// - average centipawn loss, with the same ±1000 cap +// - phases: the middlegame starts once there are 10 or fewer queens, +// rooks, bishops and knights on the board, or either side's back rank +// has fewer than 4 of its pieces left; the endgame at 6 or fewer. +// (Lichess also starts the middlegame when the pieces get mixed up +// across the board; that rule isn't here, so the middlegame can start a +// little later than on Lichess.) + +type judgment int + +const ( + judgeNone judgment = iota + judgeInaccuracy + judgeMistake + judgeBlunder +) + +func (j judgment) glyph() string { + return [...]string{"", "?!", "?", "??"}[j] +} + +func (j judgment) name() string { + return [...]string{"", "Inaccuracy", "Mistake", "Blunder"}[j] +} + +func (j judgment) plural() string { + return [...]string{"", "Inaccuracies", "Mistakes", "Blunders"}[j] +} + +// colour is the tag the move list and summary use for a judgment (Lichess's +// colours). +func (j judgment) colour() string { + return [...]string{"", "[#56b4e9]", "[#e69f00]", "[#df5353]"}[j] +} + +type phase int + +const ( + phaseOpening phase = iota + phaseMiddlegame + phaseEndgame +) + +var phaseNames = [...]string{"Opening", "Middlegame", "Endgame"} + +// sideStats are one side's numbers, for the whole game or a phase. +type sideStats struct { + moves int + accuracy float64 // %; -1 if no moves + acpl int + counts [4]int // by judgment +} + +// analysis is a game's computer analysis, filled in as the engine goes. +type analysis struct { + positions []*chess.Position // the game: positions[i] is before move i+1 + moves []*chess.Move + scores []Score // per position, from White's side + best []string // the engine's move in each position (UCI) + done int // positions analysed so far + + // worked out once complete (summarize) + win []float64 // White's win% per position + acc []float64 // the mover's accuracy per move + judged []judgment // per move + mid int // the position the middlegame starts at (len(positions) if never) + end int // the position the endgame starts at + total [2]sideStats + byPhase [3][2]sideStats // [phase][white, black] +} + +func newAnalysis(positions []*chess.Position, moves []*chess.Move) *analysis { + return &analysis{ + positions: positions, + moves: moves, + scores: make([]Score, len(positions)), + best: make([]string, len(positions)), + } +} + +func (a *analysis) complete() bool { return a.done == len(a.positions) } + +// cpOf is a score in centipawns from White's side, capped at ±1000 (mate +// counts as the cap). +func cpOf(s Score) int { + switch { + case s.Mate > 0: + return 1000 + case s.Mate < 0: + return -1000 + } + return max(-1000, min(1000, s.CP)) +} + +// winningChances is −1 (Black wins) … 1 (White wins). +func winningChances(s Score) float64 { + return 2/(1+math.Exp(-0.00368208*float64(cpOf(s)))) - 1 +} + +func winPercent(s Score) float64 { return 50 + 50*winningChances(s) } + +// moveAccuracy is how accurate a move was, from the mover's win% before and +// after it. +func moveAccuracy(before, after float64) float64 { + if after >= before { + return 100 + } + raw := 103.1668100711649*math.Exp(-0.04354415386753951*(before-after)) - 3.166924740191411 + return max(0, min(100, raw+1)) +} + +func judge(drop float64) judgment { + switch { + case drop >= 0.3: + return judgeBlunder + case drop >= 0.2: + return judgeMistake + case drop >= 0.1: + return judgeInaccuracy + } + return judgeNone +} + +// gamePhase finds where the middlegame and endgame start. +func gamePhases(positions []*chess.Position) (mid, end int) { + mid, end = len(positions), len(positions) + for i, p := range positions { + pieces, back := 0, [2]int{} + for sq, pc := range p.Board().SquareMap() { + if t := pc.Type(); t != chess.Pawn && t != chess.King { + pieces++ + } + if pc.Color() == chess.White && sq.Rank() == chess.Rank1 { + back[0]++ + } + if pc.Color() == chess.Black && sq.Rank() == chess.Rank8 { + back[1]++ + } + } + if mid == len(positions) && (pieces <= 10 || back[0] < 4 || back[1] < 4) { + mid = i + } + if mid < len(positions) && pieces <= 6 { + end = i + break + } + } + return mid, end +} + +// phaseOf is the phase a move (made from position i) belongs to. +func (a *analysis) phaseOf(i int) phase { + switch { + case i >= a.end: + return phaseEndgame + case i >= a.mid: + return phaseMiddlegame + } + return phaseOpening +} + +// side is 0 for White, 1 for Black: who made the move from position i. +func (a *analysis) side(i int) int { + if a.positions[i].Turn() == chess.White { + return 0 + } + return 1 +} + +// summarize works out everything from the scores. +func (a *analysis) summarize() { + n := len(a.moves) + a.win = make([]float64, len(a.scores)) + for i, s := range a.scores { + a.win[i] = winPercent(s) + } + a.mid, a.end = gamePhases(a.positions) + a.acc = make([]float64, n) + a.judged = make([]judgment, n) + + // volatility weights, one per move (Lichess's windows) + window := max(2, min(8, len(a.win)/10)) + weights := make([]float64, n) + for i := 0; i < n; i++ { + lo := max(0, i+2-window) + hi := min(len(a.win), lo+window) + weights[i] = max(0.5, min(12, stdDev(a.win[lo:hi]))) + } + + type acc struct{ v, w float64 } + var accs [2][]acc + var phaseAccs [3][2][]float64 + var loss [2]int + var phaseLoss [3][2]int + for i := 0; i < n; i++ { + s := a.side(i) + before, after := a.win[i], a.win[i+1] + wcBefore, wcAfter := winningChances(a.scores[i]), winningChances(a.scores[i+1]) + cpBefore, cpAfter := cpOf(a.scores[i]), cpOf(a.scores[i+1]) + if s == 1 { // from Black's side + before, after = 100-before, 100-after + wcBefore, wcAfter = -wcBefore, -wcAfter + cpBefore, cpAfter = -cpBefore, -cpAfter + } + a.acc[i] = moveAccuracy(before, after) + a.judged[i] = judge(wcBefore - wcAfter) + l := max(0, cpBefore-cpAfter) + ph := a.phaseOf(i) + + accs[s] = append(accs[s], acc{a.acc[i], weights[i]}) + phaseAccs[ph][s] = append(phaseAccs[ph][s], a.acc[i]) + loss[s] += l + phaseLoss[ph][s] += l + a.total[s].moves++ + a.total[s].counts[a.judged[i]]++ + a.byPhase[ph][s].moves++ + a.byPhase[ph][s].counts[a.judged[i]]++ + } + for s := 0; s < 2; s++ { + t := &a.total[s] + t.accuracy = -1 + if t.moves > 0 { + var sum, wsum, inv float64 + for _, x := range accs[s] { + sum += x.v * x.w + wsum += x.w + inv += 1 / max(x.v, 0.0001) + } + weighted := sum / wsum + harmonic := float64(len(accs[s])) / inv + t.accuracy = (weighted + harmonic) / 2 + t.acpl = loss[s] / t.moves + } + for ph := 0; ph < 3; ph++ { + p := &a.byPhase[ph][s] + p.accuracy = -1 + if p.moves > 0 { + p.accuracy = mean(phaseAccs[ph][s]) + p.acpl = phaseLoss[ph][s] / p.moves + } + } + } +} + +func mean(xs []float64) float64 { + if len(xs) == 0 { + return 0 + } + var s float64 + for _, x := range xs { + s += x + } + return s / float64(len(xs)) +} + +func stdDev(xs []float64) float64 { + m := mean(xs) + var s float64 + for _, x := range xs { + s += (x - m) * (x - m) + } + return math.Sqrt(s / float64(len(xs))) +} + +// analysisTime is how long the engine looks at each position. +const ( + analysisTime = 300 * time.Millisecond + analysisDepth = 20 +) + +// run analyses the game with the engine at path, handing each position's +// score and best move to result (on the engine's goroutine; record them with +// set on the UI goroutine). Positions where the game is over aren't searched. +func (a *analysis) run(ctx context.Context, path string, result func(i int, sc Score, best string)) error { + e, err := StartEngine(path, 8) + if err != nil { + return err + } + defer e.Close() + start := a.positions[0].String() + uci := make([]string, len(a.moves)) + for i, m := range a.moves { + uci[i] = chess.UCINotation{}.Encode(a.positions[i], m) + } + for i, p := range a.positions { + var sc Score + best := "" + switch p.Status() { + case chess.Checkmate: + sc = Score{Mate: 1} + if p.Turn() == chess.White { + sc = Score{Mate: -1} + } + case chess.Stalemate, chess.InsufficientMaterial: + default: + sc, best, err = e.Evaluate(ctx, start, uci[:i], analysisTime, analysisDepth) + if err != nil { + return err + } + } + result(i, sc, best) + } + return nil +} + +// set records position i's result; once all are in, the numbers are worked +// out. +func (a *analysis) set(i int, sc Score, best string) { + a.scores[i], a.best[i] = sc, best + a.done = max(a.done, i+1) + if a.complete() { + a.summarize() + } +} diff --git a/pkg/analysis_test.go b/pkg/analysis_test.go new file mode 100644 index 0000000..ca1496b --- /dev/null +++ b/pkg/analysis_test.go @@ -0,0 +1,173 @@ +package pkg + +import ( + "context" + "math" + "strings" + "testing" + "time" + + "github.com/notnil/chess" +) + +// gameOf plays SAN moves from the start. +func gameOf(t *testing.T, sans ...string) *chess.Game { + t.Helper() + g := chess.NewGame() + for _, s := range sans { + if err := g.MoveStr(s); err != nil { + t.Fatalf("%s: %v", s, err) + } + } + return g +} + +func TestAnalysisFormulas(t *testing.T) { + near := func(got, want float64) bool { return math.Abs(got-want) < 0.01 } + if !near(winPercent(Score{}), 50) { + t.Errorf("win%% at 0 = %v, want 50", winPercent(Score{})) + } + if winPercent(Score{CP: 5000}) != winPercent(Score{Mate: 3}) || winPercent(Score{Mate: -2}) != winPercent(Score{CP: -1000}) { + t.Error("mate and big scores should share the ±1000 cap") + } + // Lichess: a 10-point win% drop is 103.1668·e^(−0.4354) − 3.1669 + 1 + if got := moveAccuracy(60, 50); !near(got, 103.1668100711649*math.Exp(-0.4354415386753951)-3.166924740191411+1) { + t.Errorf("accuracy for a 10%% drop = %v", got) + } + if moveAccuracy(50, 55) != 100 || moveAccuracy(100, 0) != 0 { + t.Error("accuracy should be 100 for no loss and 0 for throwing a won game away") + } + for drop, want := range map[float64]judgment{0.05: judgeNone, 0.1: judgeInaccuracy, 0.25: judgeMistake, 0.31: judgeBlunder} { + if got := judge(drop); got != want { + t.Errorf("drop %v judged %v, want %v", drop, got, want) + } + } +} + +func TestGamePhases(t *testing.T) { + g := gameOf(t, "e4", "e5") + if mid, end := gamePhases(g.Positions()); mid != 3 || end != 3 { + t.Errorf("opening only: mid %d end %d, want neither (3)", mid, end) + } + // a king and pawn ending is an endgame from the start + kp, _ := chess.FEN("4k3/8/8/8/8/8/4P3/4K3 w - - 0 1") + pos := chess.NewGame(kp).Positions() + if mid, end := gamePhases(pos); mid != 0 || end != 0 { + t.Errorf("K+P: mid %d end %d, want 0 and 0", mid, end) + } +} + +// White plays well, then blunders: the blunder is found, costs accuracy and +// centipawns, and only White's numbers suffer. +func TestAnalysisSummary(t *testing.T) { + g := gameOf(t, "e4", "e5", "Nf3", "Nc6", "Bc4", "Nf6", "Ng5", "d5") + a := newAnalysis(g.Positions(), g.Moves()) + // position 7 is after Ng5 (White's move from 6); make that the blunder + cps := []int{20, 30, 25, 30, 30, 35, 30, -400, -380} + for i, cp := range cps { + a.set(i, Score{CP: cp}, "") + } + if !a.complete() { + t.Fatal("not complete") + } + if a.judged[6] != judgeBlunder { + t.Errorf("Ng5 judged %v, want blunder", a.judged[6]) + } + w, b := a.total[0], a.total[1] + if w.counts[judgeBlunder] != 1 || b.counts[judgeBlunder]+b.counts[judgeMistake]+b.counts[judgeInaccuracy] != 0 { + t.Errorf("counts white %v black %v", w.counts, b.counts) + } + if !(w.accuracy < b.accuracy) || w.acpl < 100 || b.acpl > 10 { + t.Errorf("white %.1f%% acpl %d, black %.1f%% acpl %d", w.accuracy, w.acpl, b.accuracy, b.acpl) + } + if a.byPhase[phaseOpening][0].moves != 4 || a.byPhase[phaseOpening][0].acpl != w.acpl { + t.Errorf("opening stats %+v", a.byPhase[phaseOpening][0]) + } +} + +// The engine run with the real Stockfish (skipped when it isn't +// installed): a result for every position, the final mate scored without +// searching. +func TestAnalysisRunStockfish(t *testing.T) { + path := realStockfish(t) + g := gameOf(t, "f3", "e5", "g4", "Qh4#") + a := newAnalysis(g.Positions(), g.Moves()) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + got := 0 + err := a.run(ctx, path, func(i int, sc Score, best string) { + a.set(i, sc, best) + got++ + }) + if err != nil { + t.Fatal(err) + } + if got != 5 || !a.complete() { + t.Fatalf("%d results, complete %v", got, a.complete()) + } + if a.scores[4] != (Score{Mate: -1}) || a.best[4] != "" { + t.Errorf("final position %+v best %q, want White mated", a.scores[4], a.best[4]) + } + if a.scores[3].Mate >= 0 { // after g4, Black mates in one + t.Errorf("after g4: %+v, want Black mating", a.scores[3]) + } + if a.judged[2] != judgeBlunder { + t.Errorf("g4 judged %v, want blunder", a.judged[2]) + } +} + +// The analysis on the game-over screen, from scores (no engine): graph, +// table, marks in the move list and the note for the move shown. +func TestAnalysisPanel(t *testing.T) { + startTestApp(t, 160, 50) + sans := []string{"e4", "e5", "Nf3", "Nc6", "Bc4", "Nf6", "Ng5", "d5"} + cps := []int{20, 30, 25, 30, 30, 35, 30, -400, -380} + var p *analysisPanel + onUI(func() { + Root.NewGame() + g := Root.gameState.Game + for _, s := range sans { + m, err := chess.AlgebraicNotation{}.Decode(g.Position(), s) + if err == nil { + err = g.Move(m) + } + if err != nil { + t.Error(s, err) // not Fatal: this is the UI goroutine + return + } + } + gotoPostLocal() + pg := Root.pgame.postGame + p = pg.analysis + a := newAnalysis(pg.positions, pg.moves) + p.a, p.graph.a = a, a + p.side.ResizeItem(p.graph, 9, 0) + for i, cp := range cps { + a.set(i, Score{CP: cp}, "") + } + a.best[6] = "c4f7" // Bxf7+ instead of Ng5 + p.finished() + pg.Board.ShowPly(7) + }) + waitFor(t, "the note for Ng5", func() bool { return strings.Contains(p.note.GetText(true), "4. Ng5??") }) + onUI(func() { + note := p.note.GetText(true) + if !strings.Contains(note, "Blunder") || !strings.Contains(note, "best was Bxf7+") { + t.Errorf("note %q", note) + } + table := p.table.GetText(true) + for _, want := range []string{"Accuracy", "Avg cp loss", "Blunders", "Opening"} { + if !strings.Contains(table, want) { + t.Errorf("table has no %q:\n%s", want, table) + } + } + if !strings.Contains(p.history.GetText(true), "Ng5??") { + t.Errorf("move list not marked:\n%s", p.history.GetText(true)) + } + _, _, _, gh := p.graph.GetRect() + if gh != 9 { + t.Errorf("graph %d rows, want 9", gh) + } + }) + onUI(func() { gotoWelcome() }) +} diff --git a/pkg/analysis_view.go b/pkg/analysis_view.go new file mode 100644 index 0000000..e685923 --- /dev/null +++ b/pkg/analysis_view.go @@ -0,0 +1,308 @@ +package pkg + +import ( + "context" + "errors" + "fmt" + "strings" + + cv "codeberg.org/tslocum/cview" + tc "github.com/gdamore/tcell/v3" + "github.com/notnil/chess" +) + +// The analysis on a game-over screen: an evaluation graph (White's winning +// chances over the game, the phases marked, the move shown highlighted; click +// it to go to a move), a table of each side's accuracy, centipawn loss and +// mistakes, overall and by phase, and ?! ? ?? marks in the move list. + +// evalGraph draws White's win% per position as a filled area: light is +// White's share, dark Black's, so the middle row is equality. +type evalGraph struct { + *cv.Box + a *analysis + board *BoardView +} + +var ( + colGraphWhite = tc.NewRGBColor(0xe0, 0xdc, 0xcf) + colGraphBlack = tc.NewRGBColor(0x3a, 0x36, 0x32) + colGraphPending = tc.NewRGBColor(0x24, 0x22, 0x20) + colGraphPhase = tc.NewRGBColor(0xb0, 0x8f, 0x3c) + colGraphShown = tc.NewRGBColor(0x5a, 0x7f, 0xbf) +) + +func newEvalGraph(board *BoardView) *evalGraph { + g := &evalGraph{Box: cv.NewBox(), board: board} + return g +} + +// positionAt is the position drawn in column c of a w-wide graph. +func (g *evalGraph) positionAt(c, w int) int { + n := len(g.a.positions) + return min(n-1, c*n/max(1, w)) +} + +func (g *evalGraph) Draw(screen tc.Screen) { + g.Box.Draw(screen) + if g.a == nil { + return + } + x, y, w, h := g.GetInnerRect() + if w <= 0 || h <= 0 { + return + } + limited := uiLimited() + white, black, pending, phaseCol, shownCol := colGraphWhite, colGraphBlack, colGraphPending, colGraphPhase, colGraphShown + if limited { + white, black, pending, phaseCol, shownCol = tc.ColorSilver, tc.ColorGray, tc.ColorBlack, tc.ColorOlive, tc.ColorNavy + } + g.board.mu.Lock() + shown := g.board.shownPly + g.board.mu.Unlock() + a := g.a + blocks := []rune(" ▁▂▃▄▅▆▇█") + for c := 0; c < w; c++ { + i := g.positionAt(c, w) + first := c == 0 || g.positionAt(c-1, w) != i + bg := black + mark := false + switch { + case i >= a.done: + bg = pending + case a.complete() && first && i > 0 && (i == a.mid || i == a.end): + mark = true + } + level := 0 + if i < a.done { + level = int(winPercent(a.scores[i]) / 100 * float64(h*8)) + } + for r := 0; r < h; r++ { // r = 0 is the bottom row + eighths := max(0, min(8, level-r*8)) + fg, cellBg := white, bg + ch := blocks[eighths] + if mark { + cellBg = phaseCol + if eighths == 8 { + fg = phaseCol + } + } + if i == shown && i < a.done { + cellBg = blend(cellBg, shownCol, 0.6) + if eighths == 8 { + fg = blend(fg, shownCol, 0.4) + } + } + screen.SetContent(x+c, y+h-1-r, ch, nil, tc.StyleDefault.Foreground(fg).Background(cellBg)) + } + } +} + +// MouseHandler: a click (or drag) goes to that move. +func (g *evalGraph) MouseHandler() func(action cv.MouseAction, event *tc.EventMouse, setFocus func(p cv.Primitive)) (bool, cv.Primitive) { + return g.WrapMouseHandler(func(action cv.MouseAction, event *tc.EventMouse, setFocus func(p cv.Primitive)) (bool, cv.Primitive) { + mx, my := event.Position() + if !g.InRect(mx, my) || g.a == nil { + return false, nil + } + switch action { + case cv.MouseLeftDown, cv.MouseLeftClick: + x, _, w, _ := g.GetInnerRect() + if mx >= x && mx < x+w { + g.board.ShowPly(g.positionAt(mx-x, w)) + } + case cv.MouseScrollUp: + g.board.mu.Lock() + g.board.step(1) + g.board.mu.Unlock() + case cv.MouseScrollDown: + g.board.mu.Lock() + g.board.step(-1) + g.board.mu.Unlock() + } + return true, nil + }) +} + +// analysisTable is the summary: each side's numbers, overall and by phase. +func analysisTable(a *analysis) string { + var b strings.Builder + pct := func(s sideStats) string { + if s.accuracy < 0 { + return " –" + } + return fmt.Sprintf("%3.0f%%", s.accuracy) + } + row := func(label, w, bl string) { + fmt.Fprintf(&b, "%-12s %-8s %s\n", label, w, bl) + } + b.WriteString("[::b] White Black[::-]\n") + row("Accuracy", pct(a.total[0]), pct(a.total[1])) + row("Avg cp loss", fmt.Sprint(a.total[0].acpl), fmt.Sprint(a.total[1].acpl)) + for _, j := range []judgment{judgeInaccuracy, judgeMistake, judgeBlunder} { + label := j.colour() + fmt.Sprintf("%-12s", j.plural()) + "[-]" + fmt.Fprintf(&b, "%s %-8d %d\n", label, a.total[0].counts[j], a.total[1].counts[j]) + } + b.WriteString("[::b]By phase acc·acpl acc·acpl[::-]\n") + for ph := phaseOpening; ph <= phaseEndgame; ph++ { + w, bl := a.byPhase[ph][0], a.byPhase[ph][1] + if w.moves+bl.moves == 0 { + continue + } + cell := func(s sideStats) string { + if s.moves == 0 { + return "–" + } + return fmt.Sprintf("%.0f%%·%d", s.accuracy, s.acpl) + } + row(phaseNames[ph], cell(w), cell(bl)) + } + return b.String() +} + +// moveNote describes the move that led to position ply: its judgment and +// what the engine preferred. +func moveNote(a *analysis, ply int) string { + if !a.complete() || ply < 1 || ply > len(a.moves) { + return "" + } + i := ply - 1 + p := a.positions[i] + san := chess.AlgebraicNotation{}.Encode(p, a.moves[i]) + num := fmt.Sprintf("%d. ", moveNumber(p)) + if p.Turn() == chess.Black { + num = fmt.Sprintf("%d… ", moveNumber(p)) + } + j := a.judged[i] + text := fmt.Sprintf("[::b]%s%s[::-]", num, san) + if j != judgeNone { + text += j.colour() + j.glyph() + " " + j.name() + "[-]" + } + if best := a.best[i]; best != "" && j != judgeNone { + for _, m := range p.ValidMoves() { // these know about check, for the + + if (chess.UCINotation{}).Encode(p, m) == best { + text += " · best was " + chess.AlgebraicNotation{}.Encode(p, m) + } + } + } + return text + fmt.Sprintf("\n[#a0a0a0]accuracy %.0f%% · eval %s[-]", a.acc[i], scoreText(a.scores[ply])) +} + +// scoreText is a score as Lichess writes it: +1.3, -0.4, #3, #-2. +func scoreText(s Score) string { + if s.Mate != 0 { + return fmt.Sprintf("#%d", s.Mate) + } + return fmt.Sprintf("%+.1f", float64(s.CP)/100) +} + +// moveMarks are the analysis's ?! ? ?? for the move list. +func moveMarks(a *analysis) []moveMark { + marks := make([]moveMark, len(a.moves)) + for i, j := range a.judged { + if j != judgeNone { + marks[i] = moveMark{text: j.colour() + j.glyph() + "[-]", width: len(j.glyph())} + } + } + return marks +} + +// analysisPanel is the analysis part of a game-over sidebar. +type analysisPanel struct { + side *cv.Flex + history *cv.TextView + board *BoardView + graph *evalGraph + setT func(string) // the graph box's title + table *cv.TextView + note *cv.TextView + + a *analysis + cancel context.CancelFunc + gen int // which run's results are wanted +} + +func newAnalysisPanel(side *cv.Flex, history *cv.TextView, board *BoardView) *analysisPanel { + p := &analysisPanel{side: side, history: history, board: board, graph: newEvalGraph(board), table: textBox(cv.AlignLeft), note: textBox(cv.AlignLeft)} + p.setT = boxed(p.graph.Box, "") + return p +} + +// reset hides the analysis (a new game ended). +func (p *analysisPanel) reset() { + if p.cancel != nil { + p.cancel() + p.cancel = nil + } + p.gen++ + p.a = nil + p.graph.a = nil + for _, it := range []cv.Primitive{p.graph, p.table, p.note} { + p.side.ResizeItem(it, 0, 0) + } +} + +// start analyses the game with the local Stockfish; status reports +// problems (no Stockfish, the engine failing). +func (p *analysisPanel) start(positions []*chess.Position, moves []*chess.Move, status func(string)) { + if p.a != nil || len(moves) == 0 { + return // running or done already, or nothing to analyse + } + path := findEngine() + if path == "" { + status("[yellow]Computer analysis needs Stockfish.[-] Get it from Home → Local → Play local Stockfish.") + return + } + a := newAnalysis(positions, moves) + p.a, p.graph.a = a, a + p.side.ResizeItem(p.graph, 9, 0) + p.setT(fmt.Sprintf("Analysing… 0/%d", len(positions))) + ctx, cancel := context.WithCancel(context.Background()) + p.cancel = cancel + p.gen++ + gen := p.gen + go func() { + err := a.run(ctx, path, func(i int, sc Score, best string) { + Root.App.QueueUpdateDraw(func() { + if gen != p.gen { + return + } + a.set(i, sc, best) + if a.complete() { + p.finished() + } else { + p.setT(fmt.Sprintf("Analysing… %d/%d", a.done, len(positions))) + } + }) + }) + if err != nil && !errors.Is(err, context.Canceled) { + Root.App.QueueUpdateDraw(func() { + if gen == p.gen { + p.setT("Analysis stopped") + status(fmt.Sprintf("[red]Analysis failed: %v[-]", cv.Escape(err.Error()))) + } + }) + } + }() +} + +// finished shows the numbers once every position is analysed. +func (p *analysisPanel) finished() { + a := p.a + p.setT("Computer analysis · Stockfish") + p.table.SetText(analysisTable(a)) + p.side.ResizeItem(p.table, strings.Count(p.table.GetText(false), "\n"), 0) + p.side.ResizeItem(p.note, 2, 0) + p.history.SetText(moveListFrom(a.positions, a.moves, moveMarks(a))) + p.board.mu.Lock() + ply := p.board.shownPly + p.board.mu.Unlock() + p.shown(ply) +} + +// shown updates the note for the move the board is showing. +func (p *analysisPanel) shown(ply int) { + if p.a != nil { + p.note.SetText(moveNote(p.a, ply)) + } +} diff --git a/pkg/assets/pieces/README.md b/pkg/assets/pieces/README.md new file mode 100644 index 0000000..16de5ee --- /dev/null +++ b/pkg/assets/pieces/README.md @@ -0,0 +1,25 @@ +# Piece sets + +The piece sets used by image rendering, from Lichess. Only sets whose licences +allow them in a GPLv3 program are included (Lichess also has sets under +non-commercial licences, which aren't). + +| Set | Author | Licence | +|---|---|---| +| cburnett | [Colin M.L. Burnett](https://en.wikipedia.org/wiki/User:Cburnett) | GPL-2.0-or-later | +| merida | Armando Hernandez Marroquin | GPL-2.0-or-later | +| mpchess | [Maxime Chupin](https://github.com/chupinmaxime) | GPL-3.0-or-later | +| chessnut | [Alexis Luengas](https://github.com/LexLuengas/chessnut-pieces) | Apache-2.0 | +| fantasy | [Maurizio Monge](https://github.com/maurimo/chess-art) | MIT | +| spatial | [Maurizio Monge](https://github.com/maurimo/chess-art) | MIT | +| celtic | [Maurizio Monge](https://github.com/maurimo/chess-art) | MIT | +| rhosgfx | [RhosGFX](https://rhosgfx.itch.io/) | CC0-1.0 | +| kiwen-suwi | [neverRare](https://github.com/neverRare) | CC-BY-4.0 | +| totoy | Kosal Sen | CC-BY-4.0 | +| papercut | [Nikolay Anzarov](https://nikoichu.itch.io/) | CC-BY-4.0 | +| shapes | [flugsio](https://github.com/flugsio/chess_shapes) | CC-BY-SA-4.0 | + +Each folder has the original SVGs, PNGs rendered from them (embedded in the +program) and a LICENSE.md. To add a set, put its 12 SVGs (`wK.svg` … `bP.svg`) +in a new folder with a LICENSE.md, run `scripts/render-pieces.sh`, and add it +to `pieceSets` in `pkg/images.go`. diff --git a/pkg/assets/pieces/cburnett/bB.png b/pkg/assets/pieces/cburnett/bB.png new file mode 100644 index 0000000..76841f2 Binary files /dev/null and b/pkg/assets/pieces/cburnett/bB.png differ diff --git a/pkg/assets/pieces/cburnett/bB.svg b/pkg/assets/pieces/cburnett/bB.svg new file mode 100644 index 0000000..51a8751 --- /dev/null +++ b/pkg/assets/pieces/cburnett/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/cburnett/bK.png b/pkg/assets/pieces/cburnett/bK.png new file mode 100644 index 0000000..b68b400 Binary files /dev/null and b/pkg/assets/pieces/cburnett/bK.png differ diff --git a/pkg/assets/pieces/cburnett/bK.svg b/pkg/assets/pieces/cburnett/bK.svg new file mode 100644 index 0000000..543b910 --- /dev/null +++ b/pkg/assets/pieces/cburnett/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/cburnett/bN.png b/pkg/assets/pieces/cburnett/bN.png new file mode 100644 index 0000000..9f93569 Binary files /dev/null and b/pkg/assets/pieces/cburnett/bN.png differ diff --git a/pkg/assets/pieces/cburnett/bN.svg b/pkg/assets/pieces/cburnett/bN.svg new file mode 100644 index 0000000..fc29188 --- /dev/null +++ b/pkg/assets/pieces/cburnett/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/cburnett/bP.png b/pkg/assets/pieces/cburnett/bP.png new file mode 100644 index 0000000..95c5c8e Binary files /dev/null and b/pkg/assets/pieces/cburnett/bP.png differ diff --git a/pkg/assets/pieces/cburnett/bP.svg b/pkg/assets/pieces/cburnett/bP.svg new file mode 100644 index 0000000..c97ccf5 --- /dev/null +++ b/pkg/assets/pieces/cburnett/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/cburnett/bQ.png b/pkg/assets/pieces/cburnett/bQ.png new file mode 100644 index 0000000..835e447 Binary files /dev/null and b/pkg/assets/pieces/cburnett/bQ.png differ diff --git a/pkg/assets/pieces/cburnett/bQ.svg b/pkg/assets/pieces/cburnett/bQ.svg new file mode 100644 index 0000000..0bd3233 --- /dev/null +++ b/pkg/assets/pieces/cburnett/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/cburnett/bR.png b/pkg/assets/pieces/cburnett/bR.png new file mode 100644 index 0000000..bcf3da1 Binary files /dev/null and b/pkg/assets/pieces/cburnett/bR.png differ diff --git a/pkg/assets/pieces/cburnett/bR.svg b/pkg/assets/pieces/cburnett/bR.svg new file mode 100644 index 0000000..1f87576 --- /dev/null +++ b/pkg/assets/pieces/cburnett/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/cburnett/wB.png b/pkg/assets/pieces/cburnett/wB.png new file mode 100644 index 0000000..d427058 Binary files /dev/null and b/pkg/assets/pieces/cburnett/wB.png differ diff --git a/pkg/assets/pieces/cburnett/wB.svg b/pkg/assets/pieces/cburnett/wB.svg new file mode 100644 index 0000000..8eee13f --- /dev/null +++ b/pkg/assets/pieces/cburnett/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/cburnett/wK.png b/pkg/assets/pieces/cburnett/wK.png new file mode 100644 index 0000000..ec71d43 Binary files /dev/null and b/pkg/assets/pieces/cburnett/wK.png differ diff --git a/pkg/assets/pieces/cburnett/wK.svg b/pkg/assets/pieces/cburnett/wK.svg new file mode 100644 index 0000000..3370721 --- /dev/null +++ b/pkg/assets/pieces/cburnett/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/cburnett/wN.png b/pkg/assets/pieces/cburnett/wN.png new file mode 100644 index 0000000..a9f3f1c Binary files /dev/null and b/pkg/assets/pieces/cburnett/wN.png differ diff --git a/pkg/assets/pieces/cburnett/wN.svg b/pkg/assets/pieces/cburnett/wN.svg new file mode 100644 index 0000000..afd1fc8 --- /dev/null +++ b/pkg/assets/pieces/cburnett/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/cburnett/wP.png b/pkg/assets/pieces/cburnett/wP.png new file mode 100644 index 0000000..e40a3ee Binary files /dev/null and b/pkg/assets/pieces/cburnett/wP.png differ diff --git a/pkg/assets/pieces/cburnett/wP.svg b/pkg/assets/pieces/cburnett/wP.svg new file mode 100644 index 0000000..c252c58 --- /dev/null +++ b/pkg/assets/pieces/cburnett/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/cburnett/wQ.png b/pkg/assets/pieces/cburnett/wQ.png new file mode 100644 index 0000000..a10d123 Binary files /dev/null and b/pkg/assets/pieces/cburnett/wQ.png differ diff --git a/pkg/assets/pieces/cburnett/wQ.svg b/pkg/assets/pieces/cburnett/wQ.svg new file mode 100644 index 0000000..c40c4e0 --- /dev/null +++ b/pkg/assets/pieces/cburnett/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/cburnett/wR.png b/pkg/assets/pieces/cburnett/wR.png new file mode 100644 index 0000000..99590dd Binary files /dev/null and b/pkg/assets/pieces/cburnett/wR.png differ diff --git a/pkg/assets/pieces/cburnett/wR.svg b/pkg/assets/pieces/cburnett/wR.svg new file mode 100644 index 0000000..8564f6b --- /dev/null +++ b/pkg/assets/pieces/cburnett/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/celtic/bB.png b/pkg/assets/pieces/celtic/bB.png new file mode 100644 index 0000000..69c3ce5 Binary files /dev/null and b/pkg/assets/pieces/celtic/bB.png differ diff --git a/pkg/assets/pieces/celtic/bB.svg b/pkg/assets/pieces/celtic/bB.svg new file mode 100644 index 0000000..88ed220 --- /dev/null +++ b/pkg/assets/pieces/celtic/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/celtic/bK.png b/pkg/assets/pieces/celtic/bK.png new file mode 100644 index 0000000..d354189 Binary files /dev/null and b/pkg/assets/pieces/celtic/bK.png differ diff --git a/pkg/assets/pieces/celtic/bK.svg b/pkg/assets/pieces/celtic/bK.svg new file mode 100644 index 0000000..3f4e72b --- /dev/null +++ b/pkg/assets/pieces/celtic/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/celtic/bN.png b/pkg/assets/pieces/celtic/bN.png new file mode 100644 index 0000000..3223b07 Binary files /dev/null and b/pkg/assets/pieces/celtic/bN.png differ diff --git a/pkg/assets/pieces/celtic/bN.svg b/pkg/assets/pieces/celtic/bN.svg new file mode 100644 index 0000000..a85ad9d --- /dev/null +++ b/pkg/assets/pieces/celtic/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/celtic/bP.png b/pkg/assets/pieces/celtic/bP.png new file mode 100644 index 0000000..5efc152 Binary files /dev/null and b/pkg/assets/pieces/celtic/bP.png differ diff --git a/pkg/assets/pieces/celtic/bP.svg b/pkg/assets/pieces/celtic/bP.svg new file mode 100644 index 0000000..d61bc99 --- /dev/null +++ b/pkg/assets/pieces/celtic/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/celtic/bQ.png b/pkg/assets/pieces/celtic/bQ.png new file mode 100644 index 0000000..4760789 Binary files /dev/null and b/pkg/assets/pieces/celtic/bQ.png differ diff --git a/pkg/assets/pieces/celtic/bQ.svg b/pkg/assets/pieces/celtic/bQ.svg new file mode 100644 index 0000000..b0e2cf2 --- /dev/null +++ b/pkg/assets/pieces/celtic/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/celtic/bR.png b/pkg/assets/pieces/celtic/bR.png new file mode 100644 index 0000000..e93fb7a Binary files /dev/null and b/pkg/assets/pieces/celtic/bR.png differ diff --git a/pkg/assets/pieces/celtic/bR.svg b/pkg/assets/pieces/celtic/bR.svg new file mode 100644 index 0000000..8ac7363 --- /dev/null +++ b/pkg/assets/pieces/celtic/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/celtic/wB.png b/pkg/assets/pieces/celtic/wB.png new file mode 100644 index 0000000..081332c Binary files /dev/null and b/pkg/assets/pieces/celtic/wB.png differ diff --git a/pkg/assets/pieces/celtic/wB.svg b/pkg/assets/pieces/celtic/wB.svg new file mode 100644 index 0000000..180d98f --- /dev/null +++ b/pkg/assets/pieces/celtic/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/celtic/wK.png b/pkg/assets/pieces/celtic/wK.png new file mode 100644 index 0000000..cfe348d Binary files /dev/null and b/pkg/assets/pieces/celtic/wK.png differ diff --git a/pkg/assets/pieces/celtic/wK.svg b/pkg/assets/pieces/celtic/wK.svg new file mode 100644 index 0000000..caeb6b3 --- /dev/null +++ b/pkg/assets/pieces/celtic/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/celtic/wN.png b/pkg/assets/pieces/celtic/wN.png new file mode 100644 index 0000000..2f41bab Binary files /dev/null and b/pkg/assets/pieces/celtic/wN.png differ diff --git a/pkg/assets/pieces/celtic/wN.svg b/pkg/assets/pieces/celtic/wN.svg new file mode 100644 index 0000000..52ab49f --- /dev/null +++ b/pkg/assets/pieces/celtic/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/celtic/wP.png b/pkg/assets/pieces/celtic/wP.png new file mode 100644 index 0000000..0c49fe5 Binary files /dev/null and b/pkg/assets/pieces/celtic/wP.png differ diff --git a/pkg/assets/pieces/celtic/wP.svg b/pkg/assets/pieces/celtic/wP.svg new file mode 100644 index 0000000..0e6ac4d --- /dev/null +++ b/pkg/assets/pieces/celtic/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/celtic/wQ.png b/pkg/assets/pieces/celtic/wQ.png new file mode 100644 index 0000000..c4a6978 Binary files /dev/null and b/pkg/assets/pieces/celtic/wQ.png differ diff --git a/pkg/assets/pieces/celtic/wQ.svg b/pkg/assets/pieces/celtic/wQ.svg new file mode 100644 index 0000000..40be4db --- /dev/null +++ b/pkg/assets/pieces/celtic/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/celtic/wR.png b/pkg/assets/pieces/celtic/wR.png new file mode 100644 index 0000000..f7b4b35 Binary files /dev/null and b/pkg/assets/pieces/celtic/wR.png differ diff --git a/pkg/assets/pieces/celtic/wR.svg b/pkg/assets/pieces/celtic/wR.svg new file mode 100644 index 0000000..56f2664 --- /dev/null +++ b/pkg/assets/pieces/celtic/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/chessnut/bB.png b/pkg/assets/pieces/chessnut/bB.png new file mode 100644 index 0000000..a3e0755 Binary files /dev/null and b/pkg/assets/pieces/chessnut/bB.png differ diff --git a/pkg/assets/pieces/chessnut/bB.svg b/pkg/assets/pieces/chessnut/bB.svg new file mode 100644 index 0000000..8944055 --- /dev/null +++ b/pkg/assets/pieces/chessnut/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/chessnut/bK.png b/pkg/assets/pieces/chessnut/bK.png new file mode 100644 index 0000000..42d52a2 Binary files /dev/null and b/pkg/assets/pieces/chessnut/bK.png differ diff --git a/pkg/assets/pieces/chessnut/bK.svg b/pkg/assets/pieces/chessnut/bK.svg new file mode 100644 index 0000000..a231ff2 --- /dev/null +++ b/pkg/assets/pieces/chessnut/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/chessnut/bN.png b/pkg/assets/pieces/chessnut/bN.png new file mode 100644 index 0000000..0013958 Binary files /dev/null and b/pkg/assets/pieces/chessnut/bN.png differ diff --git a/pkg/assets/pieces/chessnut/bN.svg b/pkg/assets/pieces/chessnut/bN.svg new file mode 100644 index 0000000..39126a2 --- /dev/null +++ b/pkg/assets/pieces/chessnut/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/chessnut/bP.png b/pkg/assets/pieces/chessnut/bP.png new file mode 100644 index 0000000..d42661f Binary files /dev/null and b/pkg/assets/pieces/chessnut/bP.png differ diff --git a/pkg/assets/pieces/chessnut/bP.svg b/pkg/assets/pieces/chessnut/bP.svg new file mode 100644 index 0000000..337915d --- /dev/null +++ b/pkg/assets/pieces/chessnut/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/chessnut/bQ.png b/pkg/assets/pieces/chessnut/bQ.png new file mode 100644 index 0000000..58596c9 Binary files /dev/null and b/pkg/assets/pieces/chessnut/bQ.png differ diff --git a/pkg/assets/pieces/chessnut/bQ.svg b/pkg/assets/pieces/chessnut/bQ.svg new file mode 100644 index 0000000..89b1902 --- /dev/null +++ b/pkg/assets/pieces/chessnut/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/chessnut/bR.png b/pkg/assets/pieces/chessnut/bR.png new file mode 100644 index 0000000..494eaad Binary files /dev/null and b/pkg/assets/pieces/chessnut/bR.png differ diff --git a/pkg/assets/pieces/chessnut/bR.svg b/pkg/assets/pieces/chessnut/bR.svg new file mode 100644 index 0000000..3b3d47d --- /dev/null +++ b/pkg/assets/pieces/chessnut/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/chessnut/wB.png b/pkg/assets/pieces/chessnut/wB.png new file mode 100644 index 0000000..6d442a5 Binary files /dev/null and b/pkg/assets/pieces/chessnut/wB.png differ diff --git a/pkg/assets/pieces/chessnut/wB.svg b/pkg/assets/pieces/chessnut/wB.svg new file mode 100644 index 0000000..7a2fb6c --- /dev/null +++ b/pkg/assets/pieces/chessnut/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/chessnut/wK.png b/pkg/assets/pieces/chessnut/wK.png new file mode 100644 index 0000000..122230a Binary files /dev/null and b/pkg/assets/pieces/chessnut/wK.png differ diff --git a/pkg/assets/pieces/chessnut/wK.svg b/pkg/assets/pieces/chessnut/wK.svg new file mode 100644 index 0000000..de4bc29 --- /dev/null +++ b/pkg/assets/pieces/chessnut/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/chessnut/wN.png b/pkg/assets/pieces/chessnut/wN.png new file mode 100644 index 0000000..5fe440f Binary files /dev/null and b/pkg/assets/pieces/chessnut/wN.png differ diff --git a/pkg/assets/pieces/chessnut/wN.svg b/pkg/assets/pieces/chessnut/wN.svg new file mode 100644 index 0000000..7ccaeda --- /dev/null +++ b/pkg/assets/pieces/chessnut/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/chessnut/wP.png b/pkg/assets/pieces/chessnut/wP.png new file mode 100644 index 0000000..fea098b Binary files /dev/null and b/pkg/assets/pieces/chessnut/wP.png differ diff --git a/pkg/assets/pieces/chessnut/wP.svg b/pkg/assets/pieces/chessnut/wP.svg new file mode 100644 index 0000000..e27c1b9 --- /dev/null +++ b/pkg/assets/pieces/chessnut/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/chessnut/wQ.png b/pkg/assets/pieces/chessnut/wQ.png new file mode 100644 index 0000000..31f5b20 Binary files /dev/null and b/pkg/assets/pieces/chessnut/wQ.png differ diff --git a/pkg/assets/pieces/chessnut/wQ.svg b/pkg/assets/pieces/chessnut/wQ.svg new file mode 100644 index 0000000..f748b85 --- /dev/null +++ b/pkg/assets/pieces/chessnut/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/chessnut/wR.png b/pkg/assets/pieces/chessnut/wR.png new file mode 100644 index 0000000..4bb84d9 Binary files /dev/null and b/pkg/assets/pieces/chessnut/wR.png differ diff --git a/pkg/assets/pieces/chessnut/wR.svg b/pkg/assets/pieces/chessnut/wR.svg new file mode 100644 index 0000000..6648406 --- /dev/null +++ b/pkg/assets/pieces/chessnut/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/fantasy/bB.png b/pkg/assets/pieces/fantasy/bB.png new file mode 100644 index 0000000..a31144f Binary files /dev/null and b/pkg/assets/pieces/fantasy/bB.png differ diff --git a/pkg/assets/pieces/fantasy/bB.svg b/pkg/assets/pieces/fantasy/bB.svg new file mode 100644 index 0000000..bc68ec8 --- /dev/null +++ b/pkg/assets/pieces/fantasy/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/fantasy/bK.png b/pkg/assets/pieces/fantasy/bK.png new file mode 100644 index 0000000..3926822 Binary files /dev/null and b/pkg/assets/pieces/fantasy/bK.png differ diff --git a/pkg/assets/pieces/fantasy/bK.svg b/pkg/assets/pieces/fantasy/bK.svg new file mode 100644 index 0000000..52e411f --- /dev/null +++ b/pkg/assets/pieces/fantasy/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/fantasy/bN.png b/pkg/assets/pieces/fantasy/bN.png new file mode 100644 index 0000000..c17c028 Binary files /dev/null and b/pkg/assets/pieces/fantasy/bN.png differ diff --git a/pkg/assets/pieces/fantasy/bN.svg b/pkg/assets/pieces/fantasy/bN.svg new file mode 100644 index 0000000..caaba40 --- /dev/null +++ b/pkg/assets/pieces/fantasy/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/fantasy/bP.png b/pkg/assets/pieces/fantasy/bP.png new file mode 100644 index 0000000..e6801a9 Binary files /dev/null and b/pkg/assets/pieces/fantasy/bP.png differ diff --git a/pkg/assets/pieces/fantasy/bP.svg b/pkg/assets/pieces/fantasy/bP.svg new file mode 100644 index 0000000..67d5c9e --- /dev/null +++ b/pkg/assets/pieces/fantasy/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/fantasy/bQ.png b/pkg/assets/pieces/fantasy/bQ.png new file mode 100644 index 0000000..470940f Binary files /dev/null and b/pkg/assets/pieces/fantasy/bQ.png differ diff --git a/pkg/assets/pieces/fantasy/bQ.svg b/pkg/assets/pieces/fantasy/bQ.svg new file mode 100644 index 0000000..246be11 --- /dev/null +++ b/pkg/assets/pieces/fantasy/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/fantasy/bR.png b/pkg/assets/pieces/fantasy/bR.png new file mode 100644 index 0000000..2f6cf26 Binary files /dev/null and b/pkg/assets/pieces/fantasy/bR.png differ diff --git a/pkg/assets/pieces/fantasy/bR.svg b/pkg/assets/pieces/fantasy/bR.svg new file mode 100644 index 0000000..ca02a6a --- /dev/null +++ b/pkg/assets/pieces/fantasy/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/fantasy/wB.png b/pkg/assets/pieces/fantasy/wB.png new file mode 100644 index 0000000..eb9a001 Binary files /dev/null and b/pkg/assets/pieces/fantasy/wB.png differ diff --git a/pkg/assets/pieces/fantasy/wB.svg b/pkg/assets/pieces/fantasy/wB.svg new file mode 100644 index 0000000..4ca47c9 --- /dev/null +++ b/pkg/assets/pieces/fantasy/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/fantasy/wK.png b/pkg/assets/pieces/fantasy/wK.png new file mode 100644 index 0000000..faac6b3 Binary files /dev/null and b/pkg/assets/pieces/fantasy/wK.png differ diff --git a/pkg/assets/pieces/fantasy/wK.svg b/pkg/assets/pieces/fantasy/wK.svg new file mode 100644 index 0000000..7ad06f2 --- /dev/null +++ b/pkg/assets/pieces/fantasy/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/fantasy/wN.png b/pkg/assets/pieces/fantasy/wN.png new file mode 100644 index 0000000..6b372b4 Binary files /dev/null and b/pkg/assets/pieces/fantasy/wN.png differ diff --git a/pkg/assets/pieces/fantasy/wN.svg b/pkg/assets/pieces/fantasy/wN.svg new file mode 100644 index 0000000..beaff33 --- /dev/null +++ b/pkg/assets/pieces/fantasy/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/fantasy/wP.png b/pkg/assets/pieces/fantasy/wP.png new file mode 100644 index 0000000..55bf5e0 Binary files /dev/null and b/pkg/assets/pieces/fantasy/wP.png differ diff --git a/pkg/assets/pieces/fantasy/wP.svg b/pkg/assets/pieces/fantasy/wP.svg new file mode 100644 index 0000000..7aba494 --- /dev/null +++ b/pkg/assets/pieces/fantasy/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/fantasy/wQ.png b/pkg/assets/pieces/fantasy/wQ.png new file mode 100644 index 0000000..200c3b6 Binary files /dev/null and b/pkg/assets/pieces/fantasy/wQ.png differ diff --git a/pkg/assets/pieces/fantasy/wQ.svg b/pkg/assets/pieces/fantasy/wQ.svg new file mode 100644 index 0000000..e46811e --- /dev/null +++ b/pkg/assets/pieces/fantasy/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/fantasy/wR.png b/pkg/assets/pieces/fantasy/wR.png new file mode 100644 index 0000000..38ee5d0 Binary files /dev/null and b/pkg/assets/pieces/fantasy/wR.png differ diff --git a/pkg/assets/pieces/fantasy/wR.svg b/pkg/assets/pieces/fantasy/wR.svg new file mode 100644 index 0000000..2bc9da8 --- /dev/null +++ b/pkg/assets/pieces/fantasy/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/kiwen-suwi/bB.png b/pkg/assets/pieces/kiwen-suwi/bB.png new file mode 100644 index 0000000..fc52ab4 Binary files /dev/null and b/pkg/assets/pieces/kiwen-suwi/bB.png differ diff --git a/pkg/assets/pieces/kiwen-suwi/bB.svg b/pkg/assets/pieces/kiwen-suwi/bB.svg new file mode 100644 index 0000000..5be8e7b --- /dev/null +++ b/pkg/assets/pieces/kiwen-suwi/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/kiwen-suwi/bK.png b/pkg/assets/pieces/kiwen-suwi/bK.png new file mode 100644 index 0000000..fa49c7d Binary files /dev/null and b/pkg/assets/pieces/kiwen-suwi/bK.png differ diff --git a/pkg/assets/pieces/kiwen-suwi/bK.svg b/pkg/assets/pieces/kiwen-suwi/bK.svg new file mode 100644 index 0000000..02e141b --- /dev/null +++ b/pkg/assets/pieces/kiwen-suwi/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/kiwen-suwi/bN.png b/pkg/assets/pieces/kiwen-suwi/bN.png new file mode 100644 index 0000000..7837700 Binary files /dev/null and b/pkg/assets/pieces/kiwen-suwi/bN.png differ diff --git a/pkg/assets/pieces/kiwen-suwi/bN.svg b/pkg/assets/pieces/kiwen-suwi/bN.svg new file mode 100644 index 0000000..dbdc5e4 --- /dev/null +++ b/pkg/assets/pieces/kiwen-suwi/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/kiwen-suwi/bP.png b/pkg/assets/pieces/kiwen-suwi/bP.png new file mode 100644 index 0000000..1e27cee Binary files /dev/null and b/pkg/assets/pieces/kiwen-suwi/bP.png differ diff --git a/pkg/assets/pieces/kiwen-suwi/bP.svg b/pkg/assets/pieces/kiwen-suwi/bP.svg new file mode 100644 index 0000000..2fefd97 --- /dev/null +++ b/pkg/assets/pieces/kiwen-suwi/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/kiwen-suwi/bQ.png b/pkg/assets/pieces/kiwen-suwi/bQ.png new file mode 100644 index 0000000..efd6db9 Binary files /dev/null and b/pkg/assets/pieces/kiwen-suwi/bQ.png differ diff --git a/pkg/assets/pieces/kiwen-suwi/bQ.svg b/pkg/assets/pieces/kiwen-suwi/bQ.svg new file mode 100644 index 0000000..460f485 --- /dev/null +++ b/pkg/assets/pieces/kiwen-suwi/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/kiwen-suwi/bR.png b/pkg/assets/pieces/kiwen-suwi/bR.png new file mode 100644 index 0000000..b6fa1e5 Binary files /dev/null and b/pkg/assets/pieces/kiwen-suwi/bR.png differ diff --git a/pkg/assets/pieces/kiwen-suwi/bR.svg b/pkg/assets/pieces/kiwen-suwi/bR.svg new file mode 100644 index 0000000..c113173 --- /dev/null +++ b/pkg/assets/pieces/kiwen-suwi/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/kiwen-suwi/wB.png b/pkg/assets/pieces/kiwen-suwi/wB.png new file mode 100644 index 0000000..35824ba Binary files /dev/null and b/pkg/assets/pieces/kiwen-suwi/wB.png differ diff --git a/pkg/assets/pieces/kiwen-suwi/wB.svg b/pkg/assets/pieces/kiwen-suwi/wB.svg new file mode 100644 index 0000000..c9d2b98 --- /dev/null +++ b/pkg/assets/pieces/kiwen-suwi/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/kiwen-suwi/wK.png b/pkg/assets/pieces/kiwen-suwi/wK.png new file mode 100644 index 0000000..da4df13 Binary files /dev/null and b/pkg/assets/pieces/kiwen-suwi/wK.png differ diff --git a/pkg/assets/pieces/kiwen-suwi/wK.svg b/pkg/assets/pieces/kiwen-suwi/wK.svg new file mode 100644 index 0000000..b16fad9 --- /dev/null +++ b/pkg/assets/pieces/kiwen-suwi/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/kiwen-suwi/wN.png b/pkg/assets/pieces/kiwen-suwi/wN.png new file mode 100644 index 0000000..65391e2 Binary files /dev/null and b/pkg/assets/pieces/kiwen-suwi/wN.png differ diff --git a/pkg/assets/pieces/kiwen-suwi/wN.svg b/pkg/assets/pieces/kiwen-suwi/wN.svg new file mode 100644 index 0000000..4e6e620 --- /dev/null +++ b/pkg/assets/pieces/kiwen-suwi/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/kiwen-suwi/wP.png b/pkg/assets/pieces/kiwen-suwi/wP.png new file mode 100644 index 0000000..535b19b Binary files /dev/null and b/pkg/assets/pieces/kiwen-suwi/wP.png differ diff --git a/pkg/assets/pieces/kiwen-suwi/wP.svg b/pkg/assets/pieces/kiwen-suwi/wP.svg new file mode 100644 index 0000000..a30c4dc --- /dev/null +++ b/pkg/assets/pieces/kiwen-suwi/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/kiwen-suwi/wQ.png b/pkg/assets/pieces/kiwen-suwi/wQ.png new file mode 100644 index 0000000..786818e Binary files /dev/null and b/pkg/assets/pieces/kiwen-suwi/wQ.png differ diff --git a/pkg/assets/pieces/kiwen-suwi/wQ.svg b/pkg/assets/pieces/kiwen-suwi/wQ.svg new file mode 100644 index 0000000..9182d4c --- /dev/null +++ b/pkg/assets/pieces/kiwen-suwi/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/kiwen-suwi/wR.png b/pkg/assets/pieces/kiwen-suwi/wR.png new file mode 100644 index 0000000..2f70222 Binary files /dev/null and b/pkg/assets/pieces/kiwen-suwi/wR.png differ diff --git a/pkg/assets/pieces/kiwen-suwi/wR.svg b/pkg/assets/pieces/kiwen-suwi/wR.svg new file mode 100644 index 0000000..8e031c9 --- /dev/null +++ b/pkg/assets/pieces/kiwen-suwi/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/merida/bB.png b/pkg/assets/pieces/merida/bB.png new file mode 100644 index 0000000..bf58864 Binary files /dev/null and b/pkg/assets/pieces/merida/bB.png differ diff --git a/pkg/assets/pieces/merida/bB.svg b/pkg/assets/pieces/merida/bB.svg new file mode 100644 index 0000000..1709847 --- /dev/null +++ b/pkg/assets/pieces/merida/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/merida/bK.png b/pkg/assets/pieces/merida/bK.png new file mode 100644 index 0000000..0c3f20d Binary files /dev/null and b/pkg/assets/pieces/merida/bK.png differ diff --git a/pkg/assets/pieces/merida/bK.svg b/pkg/assets/pieces/merida/bK.svg new file mode 100644 index 0000000..beaa21b --- /dev/null +++ b/pkg/assets/pieces/merida/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/merida/bN.png b/pkg/assets/pieces/merida/bN.png new file mode 100644 index 0000000..b052439 Binary files /dev/null and b/pkg/assets/pieces/merida/bN.png differ diff --git a/pkg/assets/pieces/merida/bN.svg b/pkg/assets/pieces/merida/bN.svg new file mode 100644 index 0000000..c5ff441 --- /dev/null +++ b/pkg/assets/pieces/merida/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/merida/bP.png b/pkg/assets/pieces/merida/bP.png new file mode 100644 index 0000000..1a4d407 Binary files /dev/null and b/pkg/assets/pieces/merida/bP.png differ diff --git a/pkg/assets/pieces/merida/bP.svg b/pkg/assets/pieces/merida/bP.svg new file mode 100644 index 0000000..2bcb5c1 --- /dev/null +++ b/pkg/assets/pieces/merida/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/merida/bQ.png b/pkg/assets/pieces/merida/bQ.png new file mode 100644 index 0000000..dc0c1bd Binary files /dev/null and b/pkg/assets/pieces/merida/bQ.png differ diff --git a/pkg/assets/pieces/merida/bQ.svg b/pkg/assets/pieces/merida/bQ.svg new file mode 100644 index 0000000..9754451 --- /dev/null +++ b/pkg/assets/pieces/merida/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/merida/bR.png b/pkg/assets/pieces/merida/bR.png new file mode 100644 index 0000000..7597399 Binary files /dev/null and b/pkg/assets/pieces/merida/bR.png differ diff --git a/pkg/assets/pieces/merida/bR.svg b/pkg/assets/pieces/merida/bR.svg new file mode 100644 index 0000000..a9be8b0 --- /dev/null +++ b/pkg/assets/pieces/merida/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/merida/wB.png b/pkg/assets/pieces/merida/wB.png new file mode 100644 index 0000000..e4fa971 Binary files /dev/null and b/pkg/assets/pieces/merida/wB.png differ diff --git a/pkg/assets/pieces/merida/wB.svg b/pkg/assets/pieces/merida/wB.svg new file mode 100644 index 0000000..951b795 --- /dev/null +++ b/pkg/assets/pieces/merida/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/merida/wK.png b/pkg/assets/pieces/merida/wK.png new file mode 100644 index 0000000..c0b4900 Binary files /dev/null and b/pkg/assets/pieces/merida/wK.png differ diff --git a/pkg/assets/pieces/merida/wK.svg b/pkg/assets/pieces/merida/wK.svg new file mode 100644 index 0000000..5ea308f --- /dev/null +++ b/pkg/assets/pieces/merida/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/merida/wN.png b/pkg/assets/pieces/merida/wN.png new file mode 100644 index 0000000..487cd77 Binary files /dev/null and b/pkg/assets/pieces/merida/wN.png differ diff --git a/pkg/assets/pieces/merida/wN.svg b/pkg/assets/pieces/merida/wN.svg new file mode 100644 index 0000000..a3fd414 --- /dev/null +++ b/pkg/assets/pieces/merida/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/merida/wP.png b/pkg/assets/pieces/merida/wP.png new file mode 100644 index 0000000..b611a0a Binary files /dev/null and b/pkg/assets/pieces/merida/wP.png differ diff --git a/pkg/assets/pieces/merida/wP.svg b/pkg/assets/pieces/merida/wP.svg new file mode 100644 index 0000000..b255c0e --- /dev/null +++ b/pkg/assets/pieces/merida/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/merida/wQ.png b/pkg/assets/pieces/merida/wQ.png new file mode 100644 index 0000000..eeba7c4 Binary files /dev/null and b/pkg/assets/pieces/merida/wQ.png differ diff --git a/pkg/assets/pieces/merida/wQ.svg b/pkg/assets/pieces/merida/wQ.svg new file mode 100644 index 0000000..cba7551 --- /dev/null +++ b/pkg/assets/pieces/merida/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/merida/wR.png b/pkg/assets/pieces/merida/wR.png new file mode 100644 index 0000000..5eb6d18 Binary files /dev/null and b/pkg/assets/pieces/merida/wR.png differ diff --git a/pkg/assets/pieces/merida/wR.svg b/pkg/assets/pieces/merida/wR.svg new file mode 100644 index 0000000..de003a7 --- /dev/null +++ b/pkg/assets/pieces/merida/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/mpchess/bB.png b/pkg/assets/pieces/mpchess/bB.png new file mode 100644 index 0000000..46b6ab5 Binary files /dev/null and b/pkg/assets/pieces/mpchess/bB.png differ diff --git a/pkg/assets/pieces/mpchess/bB.svg b/pkg/assets/pieces/mpchess/bB.svg new file mode 100644 index 0000000..0d8646f --- /dev/null +++ b/pkg/assets/pieces/mpchess/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/mpchess/bK.png b/pkg/assets/pieces/mpchess/bK.png new file mode 100644 index 0000000..e32cd32 Binary files /dev/null and b/pkg/assets/pieces/mpchess/bK.png differ diff --git a/pkg/assets/pieces/mpchess/bK.svg b/pkg/assets/pieces/mpchess/bK.svg new file mode 100644 index 0000000..999895e --- /dev/null +++ b/pkg/assets/pieces/mpchess/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/mpchess/bN.png b/pkg/assets/pieces/mpchess/bN.png new file mode 100644 index 0000000..7fc2a6f Binary files /dev/null and b/pkg/assets/pieces/mpchess/bN.png differ diff --git a/pkg/assets/pieces/mpchess/bN.svg b/pkg/assets/pieces/mpchess/bN.svg new file mode 100644 index 0000000..9a2cbb9 --- /dev/null +++ b/pkg/assets/pieces/mpchess/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/mpchess/bP.png b/pkg/assets/pieces/mpchess/bP.png new file mode 100644 index 0000000..195d8af Binary files /dev/null and b/pkg/assets/pieces/mpchess/bP.png differ diff --git a/pkg/assets/pieces/mpchess/bP.svg b/pkg/assets/pieces/mpchess/bP.svg new file mode 100644 index 0000000..6e4cd7e --- /dev/null +++ b/pkg/assets/pieces/mpchess/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/mpchess/bQ.png b/pkg/assets/pieces/mpchess/bQ.png new file mode 100644 index 0000000..620cd80 Binary files /dev/null and b/pkg/assets/pieces/mpchess/bQ.png differ diff --git a/pkg/assets/pieces/mpchess/bQ.svg b/pkg/assets/pieces/mpchess/bQ.svg new file mode 100644 index 0000000..7fa7a32 --- /dev/null +++ b/pkg/assets/pieces/mpchess/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/mpchess/bR.png b/pkg/assets/pieces/mpchess/bR.png new file mode 100644 index 0000000..08f3430 Binary files /dev/null and b/pkg/assets/pieces/mpchess/bR.png differ diff --git a/pkg/assets/pieces/mpchess/bR.svg b/pkg/assets/pieces/mpchess/bR.svg new file mode 100644 index 0000000..05d27f2 --- /dev/null +++ b/pkg/assets/pieces/mpchess/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/mpchess/wB.png b/pkg/assets/pieces/mpchess/wB.png new file mode 100644 index 0000000..c0235e6 Binary files /dev/null and b/pkg/assets/pieces/mpchess/wB.png differ diff --git a/pkg/assets/pieces/mpchess/wB.svg b/pkg/assets/pieces/mpchess/wB.svg new file mode 100644 index 0000000..d7ce3bc --- /dev/null +++ b/pkg/assets/pieces/mpchess/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/mpchess/wK.png b/pkg/assets/pieces/mpchess/wK.png new file mode 100644 index 0000000..ae27466 Binary files /dev/null and b/pkg/assets/pieces/mpchess/wK.png differ diff --git a/pkg/assets/pieces/mpchess/wK.svg b/pkg/assets/pieces/mpchess/wK.svg new file mode 100644 index 0000000..319681a --- /dev/null +++ b/pkg/assets/pieces/mpchess/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/mpchess/wN.png b/pkg/assets/pieces/mpchess/wN.png new file mode 100644 index 0000000..1d68e80 Binary files /dev/null and b/pkg/assets/pieces/mpchess/wN.png differ diff --git a/pkg/assets/pieces/mpchess/wN.svg b/pkg/assets/pieces/mpchess/wN.svg new file mode 100644 index 0000000..e298c39 --- /dev/null +++ b/pkg/assets/pieces/mpchess/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/mpchess/wP.png b/pkg/assets/pieces/mpchess/wP.png new file mode 100644 index 0000000..52b385e Binary files /dev/null and b/pkg/assets/pieces/mpchess/wP.png differ diff --git a/pkg/assets/pieces/mpchess/wP.svg b/pkg/assets/pieces/mpchess/wP.svg new file mode 100644 index 0000000..5680b34 --- /dev/null +++ b/pkg/assets/pieces/mpchess/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/mpchess/wQ.png b/pkg/assets/pieces/mpchess/wQ.png new file mode 100644 index 0000000..632da6d Binary files /dev/null and b/pkg/assets/pieces/mpchess/wQ.png differ diff --git a/pkg/assets/pieces/mpchess/wQ.svg b/pkg/assets/pieces/mpchess/wQ.svg new file mode 100644 index 0000000..6915012 --- /dev/null +++ b/pkg/assets/pieces/mpchess/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/mpchess/wR.png b/pkg/assets/pieces/mpchess/wR.png new file mode 100644 index 0000000..65c7a2f Binary files /dev/null and b/pkg/assets/pieces/mpchess/wR.png differ diff --git a/pkg/assets/pieces/mpchess/wR.svg b/pkg/assets/pieces/mpchess/wR.svg new file mode 100644 index 0000000..c97e286 --- /dev/null +++ b/pkg/assets/pieces/mpchess/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/papercut/bB.png b/pkg/assets/pieces/papercut/bB.png new file mode 100644 index 0000000..1f14772 Binary files /dev/null and b/pkg/assets/pieces/papercut/bB.png differ diff --git a/pkg/assets/pieces/papercut/bB.svg b/pkg/assets/pieces/papercut/bB.svg new file mode 100644 index 0000000..e1babd1 --- /dev/null +++ b/pkg/assets/pieces/papercut/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/papercut/bK.png b/pkg/assets/pieces/papercut/bK.png new file mode 100644 index 0000000..d77de08 Binary files /dev/null and b/pkg/assets/pieces/papercut/bK.png differ diff --git a/pkg/assets/pieces/papercut/bK.svg b/pkg/assets/pieces/papercut/bK.svg new file mode 100644 index 0000000..32743b9 --- /dev/null +++ b/pkg/assets/pieces/papercut/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/papercut/bN.png b/pkg/assets/pieces/papercut/bN.png new file mode 100644 index 0000000..afd1a95 Binary files /dev/null and b/pkg/assets/pieces/papercut/bN.png differ diff --git a/pkg/assets/pieces/papercut/bN.svg b/pkg/assets/pieces/papercut/bN.svg new file mode 100644 index 0000000..9b3be70 --- /dev/null +++ b/pkg/assets/pieces/papercut/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/papercut/bP.png b/pkg/assets/pieces/papercut/bP.png new file mode 100644 index 0000000..69d7eaf Binary files /dev/null and b/pkg/assets/pieces/papercut/bP.png differ diff --git a/pkg/assets/pieces/papercut/bP.svg b/pkg/assets/pieces/papercut/bP.svg new file mode 100644 index 0000000..d86cac2 --- /dev/null +++ b/pkg/assets/pieces/papercut/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/papercut/bQ.png b/pkg/assets/pieces/papercut/bQ.png new file mode 100644 index 0000000..cd16b76 Binary files /dev/null and b/pkg/assets/pieces/papercut/bQ.png differ diff --git a/pkg/assets/pieces/papercut/bQ.svg b/pkg/assets/pieces/papercut/bQ.svg new file mode 100644 index 0000000..3c64273 --- /dev/null +++ b/pkg/assets/pieces/papercut/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/papercut/bR.png b/pkg/assets/pieces/papercut/bR.png new file mode 100644 index 0000000..40ffb11 Binary files /dev/null and b/pkg/assets/pieces/papercut/bR.png differ diff --git a/pkg/assets/pieces/papercut/bR.svg b/pkg/assets/pieces/papercut/bR.svg new file mode 100644 index 0000000..464da17 --- /dev/null +++ b/pkg/assets/pieces/papercut/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/papercut/wB.png b/pkg/assets/pieces/papercut/wB.png new file mode 100644 index 0000000..21feda9 Binary files /dev/null and b/pkg/assets/pieces/papercut/wB.png differ diff --git a/pkg/assets/pieces/papercut/wB.svg b/pkg/assets/pieces/papercut/wB.svg new file mode 100644 index 0000000..bee741d --- /dev/null +++ b/pkg/assets/pieces/papercut/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/papercut/wK.png b/pkg/assets/pieces/papercut/wK.png new file mode 100644 index 0000000..957e7bb Binary files /dev/null and b/pkg/assets/pieces/papercut/wK.png differ diff --git a/pkg/assets/pieces/papercut/wK.svg b/pkg/assets/pieces/papercut/wK.svg new file mode 100644 index 0000000..53c258b --- /dev/null +++ b/pkg/assets/pieces/papercut/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/papercut/wN.png b/pkg/assets/pieces/papercut/wN.png new file mode 100644 index 0000000..016eb9f Binary files /dev/null and b/pkg/assets/pieces/papercut/wN.png differ diff --git a/pkg/assets/pieces/papercut/wN.svg b/pkg/assets/pieces/papercut/wN.svg new file mode 100644 index 0000000..b6877a3 --- /dev/null +++ b/pkg/assets/pieces/papercut/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/papercut/wP.png b/pkg/assets/pieces/papercut/wP.png new file mode 100644 index 0000000..dba77d8 Binary files /dev/null and b/pkg/assets/pieces/papercut/wP.png differ diff --git a/pkg/assets/pieces/papercut/wP.svg b/pkg/assets/pieces/papercut/wP.svg new file mode 100644 index 0000000..07c081e --- /dev/null +++ b/pkg/assets/pieces/papercut/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/papercut/wQ.png b/pkg/assets/pieces/papercut/wQ.png new file mode 100644 index 0000000..be29f8e Binary files /dev/null and b/pkg/assets/pieces/papercut/wQ.png differ diff --git a/pkg/assets/pieces/papercut/wQ.svg b/pkg/assets/pieces/papercut/wQ.svg new file mode 100644 index 0000000..f1e4c8e --- /dev/null +++ b/pkg/assets/pieces/papercut/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/papercut/wR.png b/pkg/assets/pieces/papercut/wR.png new file mode 100644 index 0000000..226f02e Binary files /dev/null and b/pkg/assets/pieces/papercut/wR.png differ diff --git a/pkg/assets/pieces/papercut/wR.svg b/pkg/assets/pieces/papercut/wR.svg new file mode 100644 index 0000000..6bbedac --- /dev/null +++ b/pkg/assets/pieces/papercut/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/rhosgfx/bB.png b/pkg/assets/pieces/rhosgfx/bB.png new file mode 100644 index 0000000..d269690 Binary files /dev/null and b/pkg/assets/pieces/rhosgfx/bB.png differ diff --git a/pkg/assets/pieces/rhosgfx/bB.svg b/pkg/assets/pieces/rhosgfx/bB.svg new file mode 100644 index 0000000..b2aeb13 --- /dev/null +++ b/pkg/assets/pieces/rhosgfx/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/rhosgfx/bK.png b/pkg/assets/pieces/rhosgfx/bK.png new file mode 100644 index 0000000..969877c Binary files /dev/null and b/pkg/assets/pieces/rhosgfx/bK.png differ diff --git a/pkg/assets/pieces/rhosgfx/bK.svg b/pkg/assets/pieces/rhosgfx/bK.svg new file mode 100644 index 0000000..a726621 --- /dev/null +++ b/pkg/assets/pieces/rhosgfx/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/rhosgfx/bN.png b/pkg/assets/pieces/rhosgfx/bN.png new file mode 100644 index 0000000..fe1920f Binary files /dev/null and b/pkg/assets/pieces/rhosgfx/bN.png differ diff --git a/pkg/assets/pieces/rhosgfx/bN.svg b/pkg/assets/pieces/rhosgfx/bN.svg new file mode 100644 index 0000000..0bf9be8 --- /dev/null +++ b/pkg/assets/pieces/rhosgfx/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/rhosgfx/bP.png b/pkg/assets/pieces/rhosgfx/bP.png new file mode 100644 index 0000000..dbfa3ce Binary files /dev/null and b/pkg/assets/pieces/rhosgfx/bP.png differ diff --git a/pkg/assets/pieces/rhosgfx/bP.svg b/pkg/assets/pieces/rhosgfx/bP.svg new file mode 100644 index 0000000..e97fce6 --- /dev/null +++ b/pkg/assets/pieces/rhosgfx/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/rhosgfx/bQ.png b/pkg/assets/pieces/rhosgfx/bQ.png new file mode 100644 index 0000000..a435bf9 Binary files /dev/null and b/pkg/assets/pieces/rhosgfx/bQ.png differ diff --git a/pkg/assets/pieces/rhosgfx/bQ.svg b/pkg/assets/pieces/rhosgfx/bQ.svg new file mode 100644 index 0000000..cb352ff --- /dev/null +++ b/pkg/assets/pieces/rhosgfx/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/rhosgfx/bR.png b/pkg/assets/pieces/rhosgfx/bR.png new file mode 100644 index 0000000..509c2c4 Binary files /dev/null and b/pkg/assets/pieces/rhosgfx/bR.png differ diff --git a/pkg/assets/pieces/rhosgfx/bR.svg b/pkg/assets/pieces/rhosgfx/bR.svg new file mode 100644 index 0000000..5ce91a9 --- /dev/null +++ b/pkg/assets/pieces/rhosgfx/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/rhosgfx/wB.png b/pkg/assets/pieces/rhosgfx/wB.png new file mode 100644 index 0000000..e00558d Binary files /dev/null and b/pkg/assets/pieces/rhosgfx/wB.png differ diff --git a/pkg/assets/pieces/rhosgfx/wB.svg b/pkg/assets/pieces/rhosgfx/wB.svg new file mode 100644 index 0000000..16fc2ea --- /dev/null +++ b/pkg/assets/pieces/rhosgfx/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/rhosgfx/wK.png b/pkg/assets/pieces/rhosgfx/wK.png new file mode 100644 index 0000000..016c85e Binary files /dev/null and b/pkg/assets/pieces/rhosgfx/wK.png differ diff --git a/pkg/assets/pieces/rhosgfx/wK.svg b/pkg/assets/pieces/rhosgfx/wK.svg new file mode 100644 index 0000000..a21a5eb --- /dev/null +++ b/pkg/assets/pieces/rhosgfx/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/rhosgfx/wN.png b/pkg/assets/pieces/rhosgfx/wN.png new file mode 100644 index 0000000..c9f1e23 Binary files /dev/null and b/pkg/assets/pieces/rhosgfx/wN.png differ diff --git a/pkg/assets/pieces/rhosgfx/wN.svg b/pkg/assets/pieces/rhosgfx/wN.svg new file mode 100644 index 0000000..9650e74 --- /dev/null +++ b/pkg/assets/pieces/rhosgfx/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/rhosgfx/wP.png b/pkg/assets/pieces/rhosgfx/wP.png new file mode 100644 index 0000000..803b7e9 Binary files /dev/null and b/pkg/assets/pieces/rhosgfx/wP.png differ diff --git a/pkg/assets/pieces/rhosgfx/wP.svg b/pkg/assets/pieces/rhosgfx/wP.svg new file mode 100644 index 0000000..ceb32e2 --- /dev/null +++ b/pkg/assets/pieces/rhosgfx/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/rhosgfx/wQ.png b/pkg/assets/pieces/rhosgfx/wQ.png new file mode 100644 index 0000000..a36a9cc Binary files /dev/null and b/pkg/assets/pieces/rhosgfx/wQ.png differ diff --git a/pkg/assets/pieces/rhosgfx/wQ.svg b/pkg/assets/pieces/rhosgfx/wQ.svg new file mode 100644 index 0000000..c0af0ab --- /dev/null +++ b/pkg/assets/pieces/rhosgfx/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/rhosgfx/wR.png b/pkg/assets/pieces/rhosgfx/wR.png new file mode 100644 index 0000000..d4a1523 Binary files /dev/null and b/pkg/assets/pieces/rhosgfx/wR.png differ diff --git a/pkg/assets/pieces/rhosgfx/wR.svg b/pkg/assets/pieces/rhosgfx/wR.svg new file mode 100644 index 0000000..ba3d4e3 --- /dev/null +++ b/pkg/assets/pieces/rhosgfx/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/shapes/bB.png b/pkg/assets/pieces/shapes/bB.png new file mode 100644 index 0000000..3247cd8 Binary files /dev/null and b/pkg/assets/pieces/shapes/bB.png differ diff --git a/pkg/assets/pieces/shapes/bB.svg b/pkg/assets/pieces/shapes/bB.svg new file mode 100644 index 0000000..1ef308a --- /dev/null +++ b/pkg/assets/pieces/shapes/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/shapes/bK.png b/pkg/assets/pieces/shapes/bK.png new file mode 100644 index 0000000..ba8d4b5 Binary files /dev/null and b/pkg/assets/pieces/shapes/bK.png differ diff --git a/pkg/assets/pieces/shapes/bK.svg b/pkg/assets/pieces/shapes/bK.svg new file mode 100644 index 0000000..cb4906c --- /dev/null +++ b/pkg/assets/pieces/shapes/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/shapes/bN.png b/pkg/assets/pieces/shapes/bN.png new file mode 100644 index 0000000..cbd878f Binary files /dev/null and b/pkg/assets/pieces/shapes/bN.png differ diff --git a/pkg/assets/pieces/shapes/bN.svg b/pkg/assets/pieces/shapes/bN.svg new file mode 100644 index 0000000..7128572 --- /dev/null +++ b/pkg/assets/pieces/shapes/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/shapes/bP.png b/pkg/assets/pieces/shapes/bP.png new file mode 100644 index 0000000..719f185 Binary files /dev/null and b/pkg/assets/pieces/shapes/bP.png differ diff --git a/pkg/assets/pieces/shapes/bP.svg b/pkg/assets/pieces/shapes/bP.svg new file mode 100644 index 0000000..456c846 --- /dev/null +++ b/pkg/assets/pieces/shapes/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/shapes/bQ.png b/pkg/assets/pieces/shapes/bQ.png new file mode 100644 index 0000000..84c7c96 Binary files /dev/null and b/pkg/assets/pieces/shapes/bQ.png differ diff --git a/pkg/assets/pieces/shapes/bQ.svg b/pkg/assets/pieces/shapes/bQ.svg new file mode 100644 index 0000000..741a4be --- /dev/null +++ b/pkg/assets/pieces/shapes/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/shapes/bR.png b/pkg/assets/pieces/shapes/bR.png new file mode 100644 index 0000000..c4c254c Binary files /dev/null and b/pkg/assets/pieces/shapes/bR.png differ diff --git a/pkg/assets/pieces/shapes/bR.svg b/pkg/assets/pieces/shapes/bR.svg new file mode 100644 index 0000000..afd3269 --- /dev/null +++ b/pkg/assets/pieces/shapes/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/shapes/wB.png b/pkg/assets/pieces/shapes/wB.png new file mode 100644 index 0000000..8f7cb51 Binary files /dev/null and b/pkg/assets/pieces/shapes/wB.png differ diff --git a/pkg/assets/pieces/shapes/wB.svg b/pkg/assets/pieces/shapes/wB.svg new file mode 100644 index 0000000..c69ff1a --- /dev/null +++ b/pkg/assets/pieces/shapes/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/shapes/wK.png b/pkg/assets/pieces/shapes/wK.png new file mode 100644 index 0000000..a2d691e Binary files /dev/null and b/pkg/assets/pieces/shapes/wK.png differ diff --git a/pkg/assets/pieces/shapes/wK.svg b/pkg/assets/pieces/shapes/wK.svg new file mode 100644 index 0000000..f3239bd --- /dev/null +++ b/pkg/assets/pieces/shapes/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/shapes/wN.png b/pkg/assets/pieces/shapes/wN.png new file mode 100644 index 0000000..1f89c68 Binary files /dev/null and b/pkg/assets/pieces/shapes/wN.png differ diff --git a/pkg/assets/pieces/shapes/wN.svg b/pkg/assets/pieces/shapes/wN.svg new file mode 100644 index 0000000..41220c4 --- /dev/null +++ b/pkg/assets/pieces/shapes/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/shapes/wP.png b/pkg/assets/pieces/shapes/wP.png new file mode 100644 index 0000000..e44e92f Binary files /dev/null and b/pkg/assets/pieces/shapes/wP.png differ diff --git a/pkg/assets/pieces/shapes/wP.svg b/pkg/assets/pieces/shapes/wP.svg new file mode 100644 index 0000000..4efa812 --- /dev/null +++ b/pkg/assets/pieces/shapes/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/shapes/wQ.png b/pkg/assets/pieces/shapes/wQ.png new file mode 100644 index 0000000..5d0f6a6 Binary files /dev/null and b/pkg/assets/pieces/shapes/wQ.png differ diff --git a/pkg/assets/pieces/shapes/wQ.svg b/pkg/assets/pieces/shapes/wQ.svg new file mode 100644 index 0000000..9f7ea7f --- /dev/null +++ b/pkg/assets/pieces/shapes/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/shapes/wR.png b/pkg/assets/pieces/shapes/wR.png new file mode 100644 index 0000000..87a1618 Binary files /dev/null and b/pkg/assets/pieces/shapes/wR.png differ diff --git a/pkg/assets/pieces/shapes/wR.svg b/pkg/assets/pieces/shapes/wR.svg new file mode 100644 index 0000000..c5d60af --- /dev/null +++ b/pkg/assets/pieces/shapes/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/spatial/bB.png b/pkg/assets/pieces/spatial/bB.png new file mode 100644 index 0000000..6655e0d Binary files /dev/null and b/pkg/assets/pieces/spatial/bB.png differ diff --git a/pkg/assets/pieces/spatial/bB.svg b/pkg/assets/pieces/spatial/bB.svg new file mode 100644 index 0000000..b5734c8 --- /dev/null +++ b/pkg/assets/pieces/spatial/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/spatial/bK.png b/pkg/assets/pieces/spatial/bK.png new file mode 100644 index 0000000..4ade3e8 Binary files /dev/null and b/pkg/assets/pieces/spatial/bK.png differ diff --git a/pkg/assets/pieces/spatial/bK.svg b/pkg/assets/pieces/spatial/bK.svg new file mode 100644 index 0000000..ddf037c --- /dev/null +++ b/pkg/assets/pieces/spatial/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/spatial/bN.png b/pkg/assets/pieces/spatial/bN.png new file mode 100644 index 0000000..c1b2416 Binary files /dev/null and b/pkg/assets/pieces/spatial/bN.png differ diff --git a/pkg/assets/pieces/spatial/bN.svg b/pkg/assets/pieces/spatial/bN.svg new file mode 100644 index 0000000..94928ee --- /dev/null +++ b/pkg/assets/pieces/spatial/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/spatial/bP.png b/pkg/assets/pieces/spatial/bP.png new file mode 100644 index 0000000..ea5bb3f Binary files /dev/null and b/pkg/assets/pieces/spatial/bP.png differ diff --git a/pkg/assets/pieces/spatial/bP.svg b/pkg/assets/pieces/spatial/bP.svg new file mode 100644 index 0000000..87be083 --- /dev/null +++ b/pkg/assets/pieces/spatial/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/spatial/bQ.png b/pkg/assets/pieces/spatial/bQ.png new file mode 100644 index 0000000..8f311bc Binary files /dev/null and b/pkg/assets/pieces/spatial/bQ.png differ diff --git a/pkg/assets/pieces/spatial/bQ.svg b/pkg/assets/pieces/spatial/bQ.svg new file mode 100644 index 0000000..a15d269 --- /dev/null +++ b/pkg/assets/pieces/spatial/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/spatial/bR.png b/pkg/assets/pieces/spatial/bR.png new file mode 100644 index 0000000..4b171b4 Binary files /dev/null and b/pkg/assets/pieces/spatial/bR.png differ diff --git a/pkg/assets/pieces/spatial/bR.svg b/pkg/assets/pieces/spatial/bR.svg new file mode 100644 index 0000000..271dbcd --- /dev/null +++ b/pkg/assets/pieces/spatial/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/spatial/wB.png b/pkg/assets/pieces/spatial/wB.png new file mode 100644 index 0000000..54b71e0 Binary files /dev/null and b/pkg/assets/pieces/spatial/wB.png differ diff --git a/pkg/assets/pieces/spatial/wB.svg b/pkg/assets/pieces/spatial/wB.svg new file mode 100644 index 0000000..20345f5 --- /dev/null +++ b/pkg/assets/pieces/spatial/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/spatial/wK.png b/pkg/assets/pieces/spatial/wK.png new file mode 100644 index 0000000..0de9c95 Binary files /dev/null and b/pkg/assets/pieces/spatial/wK.png differ diff --git a/pkg/assets/pieces/spatial/wK.svg b/pkg/assets/pieces/spatial/wK.svg new file mode 100644 index 0000000..ca198d7 --- /dev/null +++ b/pkg/assets/pieces/spatial/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/spatial/wN.png b/pkg/assets/pieces/spatial/wN.png new file mode 100644 index 0000000..f99773d Binary files /dev/null and b/pkg/assets/pieces/spatial/wN.png differ diff --git a/pkg/assets/pieces/spatial/wN.svg b/pkg/assets/pieces/spatial/wN.svg new file mode 100644 index 0000000..d641bcf --- /dev/null +++ b/pkg/assets/pieces/spatial/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/spatial/wP.png b/pkg/assets/pieces/spatial/wP.png new file mode 100644 index 0000000..06702a8 Binary files /dev/null and b/pkg/assets/pieces/spatial/wP.png differ diff --git a/pkg/assets/pieces/spatial/wP.svg b/pkg/assets/pieces/spatial/wP.svg new file mode 100644 index 0000000..ea3cd6a --- /dev/null +++ b/pkg/assets/pieces/spatial/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/spatial/wQ.png b/pkg/assets/pieces/spatial/wQ.png new file mode 100644 index 0000000..3c209cc Binary files /dev/null and b/pkg/assets/pieces/spatial/wQ.png differ diff --git a/pkg/assets/pieces/spatial/wQ.svg b/pkg/assets/pieces/spatial/wQ.svg new file mode 100644 index 0000000..1a94749 --- /dev/null +++ b/pkg/assets/pieces/spatial/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/spatial/wR.png b/pkg/assets/pieces/spatial/wR.png new file mode 100644 index 0000000..10a59a9 Binary files /dev/null and b/pkg/assets/pieces/spatial/wR.png differ diff --git a/pkg/assets/pieces/spatial/wR.svg b/pkg/assets/pieces/spatial/wR.svg new file mode 100644 index 0000000..c5f86a4 --- /dev/null +++ b/pkg/assets/pieces/spatial/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/totoy/bB.png b/pkg/assets/pieces/totoy/bB.png new file mode 100644 index 0000000..320333f Binary files /dev/null and b/pkg/assets/pieces/totoy/bB.png differ diff --git a/pkg/assets/pieces/totoy/bB.svg b/pkg/assets/pieces/totoy/bB.svg new file mode 100644 index 0000000..fce2e88 --- /dev/null +++ b/pkg/assets/pieces/totoy/bB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/totoy/bK.png b/pkg/assets/pieces/totoy/bK.png new file mode 100644 index 0000000..a419097 Binary files /dev/null and b/pkg/assets/pieces/totoy/bK.png differ diff --git a/pkg/assets/pieces/totoy/bK.svg b/pkg/assets/pieces/totoy/bK.svg new file mode 100644 index 0000000..d3c16ca --- /dev/null +++ b/pkg/assets/pieces/totoy/bK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/totoy/bN.png b/pkg/assets/pieces/totoy/bN.png new file mode 100644 index 0000000..0c1f0d6 Binary files /dev/null and b/pkg/assets/pieces/totoy/bN.png differ diff --git a/pkg/assets/pieces/totoy/bN.svg b/pkg/assets/pieces/totoy/bN.svg new file mode 100644 index 0000000..07e3bfb --- /dev/null +++ b/pkg/assets/pieces/totoy/bN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/totoy/bP.png b/pkg/assets/pieces/totoy/bP.png new file mode 100644 index 0000000..ca95ba6 Binary files /dev/null and b/pkg/assets/pieces/totoy/bP.png differ diff --git a/pkg/assets/pieces/totoy/bP.svg b/pkg/assets/pieces/totoy/bP.svg new file mode 100644 index 0000000..2543165 --- /dev/null +++ b/pkg/assets/pieces/totoy/bP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/totoy/bQ.png b/pkg/assets/pieces/totoy/bQ.png new file mode 100644 index 0000000..018c62d Binary files /dev/null and b/pkg/assets/pieces/totoy/bQ.png differ diff --git a/pkg/assets/pieces/totoy/bQ.svg b/pkg/assets/pieces/totoy/bQ.svg new file mode 100644 index 0000000..3d5f4bf --- /dev/null +++ b/pkg/assets/pieces/totoy/bQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/totoy/bR.png b/pkg/assets/pieces/totoy/bR.png new file mode 100644 index 0000000..b3e2349 Binary files /dev/null and b/pkg/assets/pieces/totoy/bR.png differ diff --git a/pkg/assets/pieces/totoy/bR.svg b/pkg/assets/pieces/totoy/bR.svg new file mode 100644 index 0000000..c9acee1 --- /dev/null +++ b/pkg/assets/pieces/totoy/bR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/totoy/wB.png b/pkg/assets/pieces/totoy/wB.png new file mode 100644 index 0000000..4e238bd Binary files /dev/null and b/pkg/assets/pieces/totoy/wB.png differ diff --git a/pkg/assets/pieces/totoy/wB.svg b/pkg/assets/pieces/totoy/wB.svg new file mode 100644 index 0000000..10cd7d5 --- /dev/null +++ b/pkg/assets/pieces/totoy/wB.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/totoy/wK.png b/pkg/assets/pieces/totoy/wK.png new file mode 100644 index 0000000..ff18e9e Binary files /dev/null and b/pkg/assets/pieces/totoy/wK.png differ diff --git a/pkg/assets/pieces/totoy/wK.svg b/pkg/assets/pieces/totoy/wK.svg new file mode 100644 index 0000000..77da8e8 --- /dev/null +++ b/pkg/assets/pieces/totoy/wK.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/totoy/wN.png b/pkg/assets/pieces/totoy/wN.png new file mode 100644 index 0000000..7075ebe Binary files /dev/null and b/pkg/assets/pieces/totoy/wN.png differ diff --git a/pkg/assets/pieces/totoy/wN.svg b/pkg/assets/pieces/totoy/wN.svg new file mode 100644 index 0000000..2b525b3 --- /dev/null +++ b/pkg/assets/pieces/totoy/wN.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/totoy/wP.png b/pkg/assets/pieces/totoy/wP.png new file mode 100644 index 0000000..4e7f5e4 Binary files /dev/null and b/pkg/assets/pieces/totoy/wP.png differ diff --git a/pkg/assets/pieces/totoy/wP.svg b/pkg/assets/pieces/totoy/wP.svg new file mode 100644 index 0000000..65b752c --- /dev/null +++ b/pkg/assets/pieces/totoy/wP.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/totoy/wQ.png b/pkg/assets/pieces/totoy/wQ.png new file mode 100644 index 0000000..41198ed Binary files /dev/null and b/pkg/assets/pieces/totoy/wQ.png differ diff --git a/pkg/assets/pieces/totoy/wQ.svg b/pkg/assets/pieces/totoy/wQ.svg new file mode 100644 index 0000000..724b952 --- /dev/null +++ b/pkg/assets/pieces/totoy/wQ.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/assets/pieces/totoy/wR.png b/pkg/assets/pieces/totoy/wR.png new file mode 100644 index 0000000..564b5f4 Binary files /dev/null and b/pkg/assets/pieces/totoy/wR.png differ diff --git a/pkg/assets/pieces/totoy/wR.svg b/pkg/assets/pieces/totoy/wR.svg new file mode 100644 index 0000000..4612036 --- /dev/null +++ b/pkg/assets/pieces/totoy/wR.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/pkg/board.go b/pkg/board.go new file mode 100644 index 0000000..5e12c62 --- /dev/null +++ b/pkg/board.go @@ -0,0 +1,861 @@ +package pkg + +import ( + "fmt" + "image" + "math" + "strings" + "sync" + + cv "codeberg.org/tslocum/cview" + tc "github.com/gdamore/tcell/v3" + "github.com/notnil/chess" +) + +// BoardView is a chess board primitive that scales to fill whatever space the +// layout gives it. Squares grow with the terminal; in terminals with kitty's +// text sizing protocol the pieces grow with them (see textsize.go). +// +// Mouse: click a piece, then click a destination. Keyboard (when focused): +// arrows / hjkl move a cursor, Enter or Space selects, Esc clears, Tab leaves. +// Promotions open a picker over the promotion square (click a piece or press +// q/r/b/n; Esc or a click elsewhere cancels). +type BoardView struct { + *cv.Box + + mu sync.Mutex + pos *chess.Position + white bool // true = white at the bottom + selected chess.Square + targets map[chess.Square]bool + lastFrom chess.Square + lastTo chess.Square + cursor chess.Square + keyboard bool // the cursor shows: keys moved it (a click hides it again) + onSquare func(sq chess.Square) + onTab func() + promo *promoPick + right bool // draw against the right edge instead of centred + + history []*chess.Position // the game so far, for stepping back (see board_extras.go) + historyMoves []*chess.Move + back int // how many moves back the board is showing (0 = now) + shapes []boardShape + dragFrom chess.Square // right-button drag start, for arrows + result boardResult // set when the game shown is over (see result.go) + topBar clockBar // clock bars beside the players (see board_extras.go) + bottomBar clockBar + onShown func(ply int) // tells a linked move list the move shown (linkMoveList) + shownPly int + browse bool // browsing a line (studies): no "return to now" label or click, no cursor + viewOnly bool // a game you watch: no moving, so no cursor and no board keys + sounds bool // a game board: a new move plays its sound + glyph moveGlyph // a move symbol (!, ??...) on glyphSq, see glyphs.go + glyphSq chess.Square + + // geometry from the last Draw, used to map mouse clicks to squares + ox, oy, sqW, sqH int +} + +// promoPick is an open promotion picker: four squares in a column over the +// promotion square, each offering one piece. +type promoPick struct { + from, to chess.Square + color chess.Color + squares map[chess.Square]chess.PieceType + done func(uci string) +} + +// makePiece builds a Piece from type and colour (the chess library keeps its +// own constructor unexported). +func makePiece(t chess.PieceType, c chess.Color) chess.Piece { + for p := chess.WhiteKing; p <= chess.BlackPawn; p++ { + if p.Type() == t && p.Color() == c { + return p + } + } + return chess.NoPiece +} + +// promoOrder is the order pieces appear in the picker, nearest the edge first. +var promoOrder = []chess.PieceType{chess.Queen, chess.Knight, chess.Rook, chess.Bishop} + +// NewBoardView makes a board. onSquare is called when the user clicks or +// presses Enter on a square; pass nil for a display-only board. +func NewBoardView(onSquare func(sq chess.Square)) *BoardView { + return &BoardView{ + Box: cv.NewBox(), + pos: chess.StartingPosition(), + white: true, + selected: chess.NoSquare, + lastFrom: chess.NoSquare, + lastTo: chess.NoSquare, + cursor: chess.E2, + dragFrom: chess.NoSquare, + topBar: clockBar{frac: -1}, + bottomBar: clockBar{frac: -1}, + onSquare: onSquare, + } +} + +// SetPosition sets the position to show and which side sits at the bottom. +// If the position changed, any selection or open promotion picker is dropped, +// since it no longer applies (e.g. the opponent just moved). +func (b *BoardView) SetPosition(pos *chess.Position, white bool) { + b.mu.Lock() + defer b.mu.Unlock() + if b.pos == nil || pos.String() != b.pos.String() || white != b.white { + b.selected, b.targets, b.promo = chess.NoSquare, nil, nil + b.shapes = nil + b.result = boardResult{} + } + b.pos = pos + b.white = white +} + +// takesKeys reports whether the board is one you play on, which uses +// hjkl, [ ] and Space itself. Locked by caller, or before Draw. +func (b *BoardView) takesKeys() bool { + return b.onSquare != nil && !b.browse && !b.viewOnly +} + +// PromotionOpen reports whether the promotion picker is showing. +func (b *BoardView) PromotionOpen() bool { + b.mu.Lock() + defer b.mu.Unlock() + return b.promo != nil +} + +// CancelPromotion closes the promotion picker without moving. +func (b *BoardView) CancelPromotion() { + b.mu.Lock() + defer b.mu.Unlock() + b.promo = nil + b.selected, b.targets = chess.NoSquare, nil +} + +// SetLastMove highlights the from/to squares of the previous move. +func (b *BoardView) SetLastMove(from, to chess.Square) { + b.mu.Lock() + defer b.mu.Unlock() + b.lastFrom, b.lastTo = from, to +} + +// SetSelection highlights a selected square and the squares it can move to. +func (b *BoardView) SetSelection(sq chess.Square, targets map[chess.Square]bool) { + b.mu.Lock() + defer b.mu.Unlock() + b.selected = sq + b.targets = targets +} + +// Selected returns the currently selected square (or chess.NoSquare). +func (b *BoardView) Selected() chess.Square { + b.mu.Lock() + defer b.mu.Unlock() + return b.selected +} + +// ClearSelection removes the selection and move targets. +func (b *BoardView) ClearSelection() { b.SetSelection(chess.NoSquare, nil) } + +// SetTabFunc sets what happens when Tab is pressed while the board has focus. +func (b *BoardView) SetTabFunc(f func()) { b.onTab = f } + +// squareAt maps a display row/col (0,0 = top-left) to a board square. +func squareAt(row, col int, white bool) chess.Square { + if white { + return chess.NewSquare(chess.File(col), chess.Rank(7-row)) + } + return chess.NewSquare(chess.File(7-col), chess.Rank(row)) +} + +// displayOf is the inverse of squareAt. +func displayOf(sq chess.Square, white bool) (row, col int) { + if white { + return 7 - int(sq.Rank()), int(sq.File()) + } + return int(sq.Rank()), 7 - int(sq.File()) +} + +const ( + labelW = 2 // columns reserved left of the board for rank labels + labelH = 1 // rows reserved below the board for file labels +) + +// How a board is drawn this frame. +type boardStyle int + +const ( + styleGlyph boardStyle = iota // one Unicode symbol per square + styleSized // symbols scaled up with kitty text sizing + styleImage // piece images with kitty graphics + styleBasic // symbols in the 8 standard colours, for any terminal +) + +// boardGeometry picks the largest square size that fits w x h cells. Terminal +// cells are about twice as tall as wide, so squares are ~2x wider than tall. +// With big pieces, squares are exactly 2s x s cells so a piece scaled by s +// (the protocol allows 1-7) fills one square. With images, aspect is the +// cell's height/width in pixels, so squares come out as square as possible. +func boardGeometry(w, h int, style boardStyle, aspect float64) (sqW, sqH int) { + w -= labelW + h -= labelH + switch style { + case styleSized: + for s := min(7, h/8); s >= 1; s-- { + if 8*2*s <= w { + return 2 * s, s + } + } + return 0, 0 + case styleImage: + for s := h / 8; s >= 1; s-- { + sw := max(1, int(math.Round(float64(s)*aspect))) + if 8*sw <= w { + return sw, s + } + } + return 0, 0 + } + for s := h / 8; s >= 2; s-- { + if 8*(2*s+2) <= w { + return 2*s + 2, s + } + } + if h >= 8 && w >= 8*2 { + return min(4, w/8), 1 + } + return 0, 0 +} + +// styleFor decides how to draw on this screen: images need the cell size in +// pixels, which some terminals don't report. +func styleFor(screen tc.Screen) (style boardStyle, cellW, cellH int) { + if PiecesSetting() == PiecesBasic { + return styleBasic, 0, 0 + } + if useImages() { + if cw, ch, ok := cellPixels(screen); ok { + return styleImage, cw, ch + } + } + if TextSizingMode() { + return styleSized, 0, 0 + } + return styleGlyph, 0, 0 +} + +// fit is the board Draw would make in a w x h area (not counting the right +// margin): square size in rows, and the columns and rows it takes, with +// labels and clock bars. sqH is 0 if no board fits. +func (b *BoardView) fit(screen tc.Screen, w, h int) (sqH, totalW, totalH int) { + style, cw, ch := styleFor(screen) + aspect := 2.0 + if style == styleImage && cw > 0 { + aspect = float64(ch) / float64(cw) + } + b.mu.Lock() + bars := b.hasClockBars() + b.mu.Unlock() + if bars { + h -= 2 + } + sqW, sqH := boardGeometry(w, h, style, aspect) + if sqW == 0 { + return 0, 0, 0 + } + totalW, totalH = 8*sqW+labelW, 8*sqH+labelH + if bars { + totalH += 2 + } + return sqH, totalW, totalH +} + +var ( + colLight = tc.NewRGBColor(145, 130, 109) + colDark = tc.NewRGBColor(108, 81, 59) + colWhiteBody = tc.NewRGBColor(255, 248, 220) + colBlackBody = tc.NewRGBColor(18, 18, 18) + colLabel = tc.NewRGBColor(170, 160, 140) + + tintSelected = tc.NewRGBColor(110, 150, 70) + tintLastMove = tc.NewRGBColor(205, 190, 80) + tintCapture = tc.NewRGBColor(200, 70, 60) + tintCursor = tc.NewRGBColor(80, 130, 200) + colDot = tc.NewRGBColor(60, 90, 40) + colPromo = tc.NewRGBColor(200, 195, 185) + colPromoDark = tc.NewRGBColor(95, 90, 85) + + // Lichess's default ("brown") board + lichessLastMove = tc.NewRGBColor(155, 199, 0) + lichessSelected = tc.NewRGBColor(20, 85, 30) + lichessPromo = tc.NewRGBColor(0xb0, 0xb0, 0xb0) +) + +// Big pieces are drawn at this fraction of the square, centred, leaving a +// little margin. +const pieceScaleN, pieceScaleD = 9, 10 + +// bigGlyphs are the pieces drawn with text sizing. The filled glyphs are used +// for both colours (coloured by fg); the pawn gets U+FE0E so it renders as +// text, not emoji. +var bigGlyphs = map[chess.PieceType]string{ + chess.King: "♚", chess.Queen: "♛", chess.Rook: "♜", + chess.Bishop: "♝", chess.Knight: "♞", chess.Pawn: "♟\uFE0E", +} + +func blend(a, b tc.Color, t float64) tc.Color { + ar, ag, ab := a.RGB() + br, bg, bb := b.RGB() + mix := func(x, y int32) int32 { return int32(float64(x)*(1-t) + float64(y)*t) } + return tc.NewRGBColor(mix(ar, br), mix(ag, bg), mix(ab, bb)) +} + +// Draw renders the board, scaled to the primitive's current size. +func (b *BoardView) Draw(screen tc.Screen) { + if !b.GetVisible() { + return + } + b.Box.Draw(screen) + + b.mu.Lock() + defer b.mu.Unlock() + b.notifyShown() + + style, cellW, cellH := styleFor(screen) + aspect := 2.0 + if style == styleImage { + aspect = float64(cellH) / float64(cellW) + } + x, y, w, h := b.GetInnerRect() + if b.right { + w -= boardMargin + } + bars := b.hasClockBars() + if bars { + y++ // a row for each bar + h -= 2 + } + sqW, sqH := boardGeometry(w, h, style, aspect) + b.sqW, b.sqH = sqW, sqH + if sqW == 0 { + msg := "Enlarge the terminal to see the board" + for i, r := range msg { + if i < w { + screen.SetContent(x+i, y+h/2, r, nil, tc.StyleDefault) + } + } + return + } + + // stepping back through history: draw the earlier position instead + if b.back > 0 { + savedPos, savedFrom, savedTo := b.pos, b.lastFrom, b.lastTo + b.pos, b.lastFrom, b.lastTo = b.shown() + defer func() { b.pos, b.lastFrom, b.lastTo = savedPos, savedFrom, savedTo }() + } + + totalW := 8*sqW + labelW + totalH := 8*sqH + labelH + b.ox = x + (w-totalW)/2 + labelW + if b.right { + b.ox = x + w - totalW + labelW + } + b.oy = y + (h-totalH)/2 + + focused := b.HasFocus() + var cells []sizedCell + var images []imgPlacement + // images: the largest square that fits the square's pixels, centred + pieceSize := min(sqW*cellW, sqH*cellH) + checkSq := b.checkSquare() + place := func(sx, sy, img, z int) { + dx, dy := (sqW*cellW-pieceSize)/2, (sqH*cellH-pieceSize)/2 + images = append(images, imgPlacement{x: sx + dx/cellW, y: sy + dy/cellH, px: dx % cellW, py: dy % cellH, img: img, z: z}) + } + // the keyboard cursor: only on a board you can move on, after using keys + showCursor := focused && b.keyboard && b.takesKeys() + for row := 0; row < 8; row++ { + for col := 0; col < 8; col++ { + sq := squareAt(row, col, b.white) + sx, sy := b.ox+col*sqW, b.oy+row*sqH + var look squareLook + if style == styleBasic { + look = b.basicLookOf(sq, showCursor && sq == b.cursor) + } else { + look = b.lookOf(sq, showCursor && sq == b.cursor, style == styleImage) + } + if sq == checkSq { // a king in check glows red, as on Lichess + switch style { + case styleImage: + place(sx, sy, imgCheck, zMarker) + case styleBasic: + look.bg = tc.ColorMaroon + default: + look.bg = blend(look.bg, colCheck, 0.7) + } + } + kb := badgeNone + if look.piece.Type() == chess.King && b.promo == nil { + kb = b.badgeFor(look.piece.Color()) + } + if kb != badgeNone && style != styleImage { + if style == styleBasic { + look.bg = badgeBasic(kb) + } else { + look.bg = blend(look.bg, badgeTc(kb), 0.55) + } + } + for cy := 0; cy < sqH; cy++ { + for cx := 0; cx < sqW; cx++ { + screen.SetContent(sx+cx, sy+cy, ' ', nil, tc.StyleDefault.Background(look.bg)) + } + } + switch { + case style == styleImage: + if look.dot { + place(sx, sy, imgDot, zMarker) + } + if look.capture { + place(sx, sy, imgRing, zMarker) + } + if look.piece != chess.NoPiece { + place(sx, sy, pieceImageID(look.piece), zPiece) + } + case style == styleSized: + cells = append(cells, look.sized(sx, sy, sqW, sqH)) + case look.piece != chess.NoPiece: + name := look.piece.Type().String() + if style == styleBasic && look.piece.Color() == chess.White { + name = strings.ToUpper(name) // outline symbols for white + } + glyph := []rune(PiecesMap[rune(name[0])]) + screen.SetContent(sx+sqW/2, sy+sqH/2, glyph[0], glyph[1:], tc.StyleDefault.Foreground(look.fg).Background(look.bg).Bold(style == styleBasic)) + case look.dot: + fg := colDot + if style == styleBasic { + fg = look.fg + } + screen.SetContent(sx+sqW/2, sy+sqH/2, '•', nil, tc.StyleDefault.Foreground(fg).Background(look.bg)) + } + if b.glyph != 0 && sq == b.glyphSq && b.promo == nil && style != styleSized { // big pieces fill the square + g := b.glyph + switch style { + case styleImage: + bs := badgeSizeFor(pieceSize) + dx := sqW*cellW - bs + images = append(images, imgPlacement{x: sx + dx/cellW, y: sy, px: dx % cellW, img: imgGlyph(g), z: zBadge}) + default: + bg, fg := g.tc(), tc.ColorWhite + if style == styleBasic { + bg, fg = g.basic(), tc.ColorWhite + } + text := []rune(g.text()) + for i, r := range text { + screen.SetContent(sx+sqW-len(text)+i, sy, r, nil, tc.StyleDefault.Foreground(fg).Background(bg).Bold(true)) + } + } + } + if kb != badgeNone { + switch style { + case styleImage: // badge in the square's top-right corner + bs := badgeSizeFor(pieceSize) + dx := sqW*cellW - bs + images = append(images, imgPlacement{x: sx + dx/cellW, y: sy, px: dx % cellW, img: imgBadge(kb), z: zBadge}) + case styleGlyph, styleBasic: + fg := tc.ColorWhite + screen.SetContent(sx+sqW-1, sy, badgeText[kb], nil, tc.StyleDefault.Foreground(fg).Background(look.bg).Bold(true)) + } + } + } + } + switch style { + case styleSized: + queueSized(screen, rect{b.ox, b.oy, 8 * sqW, 8 * sqH}, cells) + case styleImage: + var overlay *image.RGBA + key := "" + if len(b.shapes) > 0 { + key = fmt.Sprint(b.shapes, b.white, sqW*cellW, sqH*cellH) + overlay = shapesImage(b.shapes, b.white, sqW*cellW, sqH*cellH) + images = append(images, imgPlacement{x: b.ox, y: b.oy, img: imgOverlay, z: zShapes}) + } + queueImages(pieceSize, currentPieceSet(), images) + queueOverlay(overlay, key) + } + if b.back > 0 && !b.browse && b.oy > y { + label := b.historyLabel() + lx := b.ox + 8*sqW - len([]rune(label)) + for i, r := range label { + screen.SetContent(lx+i, b.oy-1, r, nil, tc.StyleDefault.Foreground(tc.ColorBlack).Background(tintLastMove)) + } + } + + if bars { + bg := b.GetBackgroundColor() + if b.back == 0 || b.browse { // the history banner uses this row (not in studies) + drawClockBar(screen, b.ox, b.oy-1, 8*sqW, b.topBar, style == styleBasic, bg) + } + drawClockBar(screen, b.ox, b.oy+8*sqH+labelH, 8*sqW, b.bottomBar, style == styleBasic, bg) + } + labelStyle := tc.StyleDefault.Foreground(colLabel).Background(b.GetBackgroundColor()) + for i := 0; i < 8; i++ { + rank := squareAt(i, 0, b.white).Rank().String() + screen.SetContent(b.ox-2, b.oy+i*sqH+sqH/2, rune(rank[0]), nil, labelStyle) + file := squareAt(0, i, b.white).File().String() + screen.SetContent(b.ox+i*sqW+sqW/2, b.oy+8*sqH, rune(file[0]), nil, labelStyle) + } +} + +// squareLook is what one square shows. +type squareLook struct { + bg, fg tc.Color + piece chess.Piece + dot bool // empty square the selected piece can move to + capture bool // occupied square the selected piece can capture on +} + +// sized turns a look into a multicell character filling the square. +// +// Each glyph is followed by a space: kitty centres text by its width in the +// main (monospace) font, which usually has no chess symbols and measures them +// as zero wide, leaving the piece's left edge at the centre. The trailing +// space gives it a width close to the piece's, so the piece lands centred. +func (l squareLook) sized(x, y, sqW, sqH int) sizedCell { + c := sizedCell{x: x, y: y, s: sqH, w: sqW / sqH, fg: l.fg, bg: l.bg, text: " "} + switch { + case l.piece != chess.NoPiece: + c.text, c.n, c.d = bigGlyphs[l.piece.Type()]+" ", pieceScaleN, pieceScaleD + case l.dot: + // ⬤, not ●: kitty draws ● itself and tiles it across the block + c.text, c.fg, c.n, c.d = "⬤ ", colDot, 2, 5 + } + return c +} + +// lookOf works out a square's colours and contents: base colour, then +// promotion picker, selection, capture targets, last move and cursor. +// lichess picks the Lichess board colours (used with piece images). +func (b *BoardView) lookOf(sq chess.Square, cursor, lichess bool) squareLook { + light, dark := colLight, colDark + if lichess { + t := currentBoard() + light, dark = t.light, t.dark + } + l := squareLook{bg: dark, piece: b.pos.Board().Piece(sq)} + if (int(sq.File())+int(sq.Rank()))%2 == 1 { + l.bg = light + } + if b.promo != nil { + if pt, ok := b.promo.squares[sq]; ok { + l.piece = makePiece(pt, b.promo.color) + switch { + case lichess: + l.bg = lichessPromo + case b.promo.color == chess.White: + l.bg = colPromoDark + default: + l.bg = colPromo + } + } else { + l.bg = blend(l.bg, tc.ColorBlack, 0.55) + } + } else { + target := b.targets[sq] + switch { + case sq == b.selected && lichess: + l.bg = blend(l.bg, lichessSelected, 0.5) + case sq == b.selected: + l.bg = blend(l.bg, tintSelected, 0.6) + case target && l.piece != chess.NoPiece && !lichess: + l.bg = blend(l.bg, tintCapture, 0.5) + case (sq == b.lastFrom || sq == b.lastTo) && lichess: + l.bg = blend(l.bg, lichessLastMove, 0.41) + case sq == b.lastFrom || sq == b.lastTo: + l.bg = blend(l.bg, tintLastMove, 0.4) + } + l.dot = target && l.piece == chess.NoPiece + l.capture = target && l.piece != chess.NoPiece + } + if tint, ok := b.shapeTint(sq); ok && !lichess { + l.bg = blend(l.bg, tint, 0.6) + } + if cursor { + l.bg = blend(l.bg, tintCursor, 0.5) + } + l.fg = colBlackBody + if l.piece != chess.NoPiece && l.piece.Color() == chess.White { + l.fg = colWhiteBody + } + return l +} + +// basicLookOf is lookOf for basic rendering: only the 8 standard colours +// (which every colour terminal has, and which follow its colour scheme), and +// both sides in black, white as outline symbols, like a printed diagram. +func (b *BoardView) basicLookOf(sq chess.Square, cursor bool) squareLook { + l := squareLook{bg: tc.ColorOlive, fg: tc.ColorBlack, piece: b.pos.Board().Piece(sq)} + if (int(sq.File())+int(sq.Rank()))%2 == 1 { + l.bg = tc.ColorSilver + } + if b.promo != nil { + if pt, ok := b.promo.squares[sq]; ok { + l.piece = makePiece(pt, b.promo.color) + l.bg = tc.ColorSilver + } else { + l.bg = tc.ColorBlack + l.fg = tc.ColorSilver + } + } else { + target := b.targets[sq] + switch { + case sq == b.selected: + l.bg = tc.ColorGreen + case target && l.piece != chess.NoPiece: + l.bg = tc.ColorMaroon + case sq == b.lastFrom || sq == b.lastTo: + l.bg = tc.ColorTeal + } + l.dot = target && l.piece == chess.NoPiece + } + if _, ok := b.shapeTint(sq); ok { + l.bg = tc.ColorGreen + } + if cursor { + l.bg, l.fg = tc.ColorNavy, tc.ColorSilver + } + return l +} + +// InputHandler handles keyboard navigation on the board. +func (b *BoardView) InputHandler() func(event *tc.EventKey, setFocus func(p cv.Primitive)) { + return b.WrapInputHandler(func(event *tc.EventKey, setFocus func(p cv.Primitive)) { + b.mu.Lock() + row, col := displayOf(b.cursor, b.white) + takes := b.onSquare != nil && !b.browse && !b.viewOnly + shown := b.keyboard && takes + b.mu.Unlock() + // The first key just shows the cursor where it is. + reveal := func() bool { + if shown { + return false + } + b.mu.Lock() + b.keyboard = takes + b.mu.Unlock() + return true + } + move := func(dr, dc int) { + if reveal() { + return + } + row = min(7, max(0, row+dr)) + col = min(7, max(0, col+dc)) + b.mu.Lock() + b.cursor = squareAt(row, col, b.white) + b.mu.Unlock() + } + switch event.Key() { + case tc.KeyUp: + move(-1, 0) + case tc.KeyDown: + move(1, 0) + case tc.KeyLeft: + move(0, -1) + case tc.KeyRight: + move(0, 1) + case tc.KeyEnter: + if !reveal() { + b.activate(b.cursor) + } + case tc.KeyEscape: + b.CancelPromotion() + case tc.KeyHome, tc.KeyEnd: + b.mu.Lock() + if event.Key() == tc.KeyHome { + b.step(len(b.history)) + } else { + b.back = 0 + } + b.mu.Unlock() + case tc.KeyTab, tc.KeyBacktab: + if b.onTab != nil { + b.onTab() + } + case tc.KeyRune: + if sq, ok := b.promoSquareFor(event.Str()); ok { + b.activate(sq) + return + } + switch event.Str() { + case "[", "]": + b.mu.Lock() + if event.Str() == "[" { + b.step(1) + } else { + b.step(-1) + } + b.mu.Unlock() + case "k", "j", "h", "l": + if vimKeys() { + d := map[string][2]int{"k": {-1, 0}, "j": {1, 0}, "h": {0, -1}, "l": {0, 1}}[event.Str()] + move(d[0], d[1]) + } + case " ": + if !reveal() { + b.activate(b.cursor) + } + } + } + }) +} + +// MouseHandler maps clicks to squares. It deliberately does not take focus, +// so the move input field keeps keyboard focus while you click around. +func (b *BoardView) MouseHandler() func(action cv.MouseAction, event *tc.EventMouse, setFocus func(p cv.Primitive)) (bool, cv.Primitive) { + return b.WrapMouseHandler(func(action cv.MouseAction, event *tc.EventMouse, setFocus func(p cv.Primitive)) (bool, cv.Primitive) { + mx, my := event.Position() + if !b.InRect(mx, my) { + return false, nil + } + b.mu.Lock() + ox, oy, sqW, sqH, white := b.ox, b.oy, b.sqW, b.sqH, b.white + sq := chess.NoSquare + if sqW > 0 && mx >= ox && my >= oy && (mx-ox)/sqW <= 7 && (my-oy)/sqH <= 7 { + sq = squareAt((my-oy)/sqH, (mx-ox)/sqW, white) + } + switch action { + case cv.MouseScrollUp: + b.step(1) + case cv.MouseScrollDown: + b.step(-1) + case cv.MouseRightDown: + b.dragFrom = sq + case cv.MouseRightUp: + if b.dragFrom != chess.NoSquare && sq != chess.NoSquare { + b.toggleShape(boardShape{from: b.dragFrom, to: sq, color: shapeColorFor(event.Modifiers())}) + } + b.dragFrom = chess.NoSquare + } + if action != cv.MouseLeftDown { + b.mu.Unlock() + return true, nil + } + b.shapes = nil + if b.back > 0 && !b.browse { // viewing history: a click comes back to the present + b.back = 0 + b.mu.Unlock() + return true, nil + } + if sq == chess.NoSquare { + b.mu.Unlock() + return true, nil + } + b.cursor = sq + b.keyboard = false // playing with the mouse: no cursor + b.mu.Unlock() + b.activate(sq) + return true, nil + }) +} + +// promoSquareFor maps q/r/b/n (either case) to the picker square offering that piece. +func (b *BoardView) promoSquareFor(key string) (chess.Square, bool) { + b.mu.Lock() + defer b.mu.Unlock() + if b.promo == nil { + return chess.NoSquare, false + } + want, ok := map[string]chess.PieceType{"q": chess.Queen, "r": chess.Rook, "b": chess.Bishop, "n": chess.Knight}[strings.ToLower(key)] + if !ok { + return chess.NoSquare, false + } + for sq, pt := range b.promo.squares { + if pt == want { + return sq, true + } + } + return chess.NoSquare, false +} + +func (b *BoardView) activate(sq chess.Square) { + if b.onSquare != nil { + b.onSquare(sq) + } +} + +// HandleSquare implements click-to-move for a game: select one of the mover's +// pieces, then pick a legal destination. doMove is given a UCI move string. +// Moving a pawn to the last rank opens the promotion picker; the move is made +// once a piece is chosen. Returns true if a move was attempted. +func (b *BoardView) HandleSquare(game *chess.Game, sq chess.Square, canMove bool, doMove func(uci string)) bool { + b.mu.Lock() + promo := b.promo + b.mu.Unlock() + if promo != nil { + b.CancelPromotion() + if pt, ok := promo.squares[sq]; ok { + promo.done(promo.from.String() + promo.to.String() + pt.String()) + return true + } + return false // clicked elsewhere: cancel + } + + pos := game.Position() + selected := b.Selected() + + if selected != chess.NoSquare && selected != sq { + var matches []*chess.Move + for _, m := range game.ValidMoves() { + if m.S1() == selected && m.S2() == sq { + matches = append(matches, m) + } + } + switch { + case len(matches) == 0: + // not a legal destination: fall through to (re)selection below + case !canMove: + b.ClearSelection() + return false + case len(matches) == 1: + b.ClearSelection() + doMove(chess.UCINotation{}.Encode(pos, matches[0])) + return true + default: // promotion: let the player choose the piece + b.openPromotion(selected, sq, pos.Turn(), doMove) + return false + } + } + + piece := pos.Board().Piece(sq) + if sq == selected || piece == chess.NoPiece || piece.Color() != pos.Turn() { + b.ClearSelection() + return false + } + targets := map[chess.Square]bool{} + for _, m := range game.ValidMoves() { + if m.S1() == sq { + targets[m.S2()] = true + } + } + b.SetSelection(sq, targets) + return false +} + +func (b *BoardView) openPromotion(from, to chess.Square, color chess.Color, doMove func(string)) { + b.mu.Lock() + defer b.mu.Unlock() + row, col := displayOf(to, b.white) + dir := 1 // promotion square at the top edge: picker extends downwards + if row == 7 { + dir = -1 + } + squares := map[chess.Square]chess.PieceType{} + for i, pt := range promoOrder { + squares[squareAt(row+i*dir, col, b.white)] = pt + } + b.promo = &promoPick{from: from, to: to, color: color, squares: squares, done: doMove} + b.targets = nil + b.cursor = to +} diff --git a/pkg/board_extras.go b/pkg/board_extras.go new file mode 100644 index 0000000..36a6a0e --- /dev/null +++ b/pkg/board_extras.go @@ -0,0 +1,471 @@ +package pkg + +import ( + "fmt" + "image" + "image/color" + "math" + + cv "codeberg.org/tslocum/cview" + tc "github.com/gdamore/tcell/v3" + "github.com/notnil/chess" +) + +// Two Lichess board features: stepping back through the game, and drawing +// circles and arrows. +// +// History: the mouse wheel on the board (or [ and ], Home and End) shows +// earlier positions. Any click goes back to the current position, and a new +// move does too. +// +// Drawing: right-click a square for a circle, right-drag for an arrow; with +// Shift red, Alt blue, Shift+Alt yellow (green otherwise). Drawing the same +// shape again removes it; a left click clears them all. Shapes are cleared +// when the position changes. + +// boardShape is a circle (from == to) or an arrow. +type boardShape struct { + from, to chess.Square + color int // index into shapeColors +} + +// Lichess's brush colours. +var shapeColors = []color.NRGBA{ + {0x15, 0x78, 0x1b, 0xff}, // green + {0x88, 0x20, 0x20, 0xff}, // red + {0x00, 0x30, 0x88, 0xff}, // blue + {0xe6, 0x8f, 0x00, 0xff}, // yellow +} + +func shapeColorFor(mod tc.ModMask) int { + shift, alt := mod&tc.ModShift != 0, mod&tc.ModAlt != 0 + switch { + case shift && alt: + return 3 + case shift: + return 1 + case alt: + return 2 + } + return 0 +} + +// SetHistory gives the board the game so far, for stepping back through it. +// positions has one more entry than moves (the start position). +func (b *BoardView) SetHistory(positions []*chess.Position, moves []*chess.Move) { + b.mu.Lock() + newMove := b.sounds && len(b.history) > 0 && len(positions) == len(b.history)+1 && len(moves) > 0 + if len(positions) != len(b.history) { + b.back = 0 // a move was made: back to the present + } + b.history, b.historyMoves = positions, moves + b.mu.Unlock() + if newMove { + playSound(moveSound(moves[len(moves)-1])) + } +} + +// EnableSounds makes a new move on this board play its sound. +func (b *BoardView) EnableSounds() { b.mu.Lock(); b.sounds = true; b.mu.Unlock() } + +// ViewingHistory reports whether an earlier position is showing. +func (b *BoardView) ViewingHistory() bool { + b.mu.Lock() + defer b.mu.Unlock() + return b.back > 0 +} + +// step moves through history: positive = further back. Locked by caller. +func (b *BoardView) step(n int) { + b.back = max(0, min(len(b.history)-1, b.back+n)) + if b.back > 0 { + b.selected, b.targets, b.promo = chess.NoSquare, nil, nil + } +} + +// shown is the position to draw and its last move: the current one, or an +// earlier one while stepping back. Locked by caller. +func (b *BoardView) shown() (pos *chess.Position, from, to chess.Square) { + if b.back == 0 || len(b.history) == 0 { + return b.pos, b.lastFrom, b.lastTo + } + i := len(b.history) - 1 - b.back + from, to = chess.NoSquare, chess.NoSquare + if i > 0 && i-1 < len(b.historyMoves) { + m := b.historyMoves[i-1] + from, to = m.S1(), m.S2() + } + return b.history[i], from, to +} + +// ShowPly shows the position after ply half-moves (0 = the start). +func (b *BoardView) ShowPly(ply int) { + b.mu.Lock() + defer b.mu.Unlock() + b.back = 0 + b.step(len(b.history) - 1 - ply) +} + +// linkMoveList connects a move list (moveListText) to the board: clicking a +// move shows the position after it, and the move the board is showing is +// highlighted (following the wheel and [ ] too). +func linkMoveList(tv *cv.TextView, b *BoardView) { + tv.SetRegions(true) + moveLists = append(moveLists, tv) + applyUIColours() + syncing := false + tv.SetHighlightedFunc(func(added, _, _ []string) { + var ply int + if syncing || len(added) == 0 { + return + } + if _, err := fmt.Sscanf(added[0], "m%d", &ply); err != nil { + return + } + b.ShowPly(ply) + // the click focused the list; keep the focus where it was + if prev := Root.App.GetFocus(); prev != nil && prev != tv { + go Root.App.QueueUpdateDraw(func() { Root.App.SetFocus(prev) }) + } + }) + b.mu.Lock() + defer b.mu.Unlock() + b.shownPly = -1 + b.onShown = func(ply int) { // UI goroutine + syncing = true + defer func() { syncing = false }() + if ply <= 0 { + tv.Highlight() + return + } + tv.Highlight(fmt.Sprintf("m%d", ply)) + tv.ScrollToHighlight() + } +} + +// notifyShown tells the move list which move is showing, if it changed. +// Locked by caller (Draw). +func (b *BoardView) notifyShown() { + if b.onShown == nil { + return + } + ply := len(b.history) - 1 - b.back + if ply == b.shownPly { + return + } + b.shownPly = ply + f := b.onShown + go Root.App.QueueUpdateDraw(func() { f(ply) }) +} + +// historyLabel describes the position shown while stepping back. +func (b *BoardView) historyLabel() string { + i := len(b.history) - 1 - b.back + return fmt.Sprintf(" move %d of %d · scroll down or ] to return ", i, len(b.history)-1) +} + +// toggleShape adds a shape, or removes it if it's already drawn (in any +// colour). Locked by caller. +func (b *BoardView) toggleShape(s boardShape) { + for i, x := range b.shapes { + if x.from == s.from && x.to == s.to { + b.shapes = append(b.shapes[:i], b.shapes[i+1:]...) + if x.color == s.color { + return + } + break + } + } + b.shapes = append(b.shapes, s) +} + +// SetShapes replaces the circles and arrows drawn on the board. +func (b *BoardView) SetShapes(shapes []boardShape) { + b.mu.Lock() + defer b.mu.Unlock() + b.shapes = append([]boardShape(nil), shapes...) +} + +// shapeTint is the square tint for shapes in text modes (where arrows can't +// be drawn): the circled square, or an arrow's ends. +func (b *BoardView) shapeTint(sq chess.Square) (tc.Color, bool) { + for i := len(b.shapes) - 1; i >= 0; i-- { + s := b.shapes[i] + if s.from == sq || s.to == sq { + c := shapeColors[s.color] + return tc.NewRGBColor(int32(c.R), int32(c.G), int32(c.B)), true + } + } + return 0, false +} + +// shapesImage draws the shapes over the board, Lichess style, as one +// transparent image of the board's size in pixels. +func shapesImage(shapes []boardShape, white bool, sqPxW, sqPxH int) *image.RGBA { + img := image.NewRGBA(image.Rect(0, 0, 8*sqPxW, 8*sqPxH)) + unit := float64(min(sqPxW, sqPxH)) + centre := func(sq chess.Square) (float64, float64) { + row, col := displayOf(sq, white) + return (float64(col) + 0.5) * float64(sqPxW), (float64(row) + 0.5) * float64(sqPxH) + } + for _, s := range shapes { + c := shapeColors[s.color] + x1, y1 := centre(s.from) + if s.from == s.to { + r, w := unit*0.47, unit*0.07 + paint(img, c, 0.8, x1-r, y1-r, x1+r, y1+r, func(x, y float64) float64 { + return w/2 - math.Abs(math.Hypot(x-x1, y-y1)-(r-w/2)) + }) + continue + } + x2, y2 := centre(s.to) + dx, dy := x2-x1, y2-y1 + l := math.Hypot(dx, dy) + ux, uy := dx/l, dy/l + head, halfHead, halfShaft := unit*0.42, unit*0.26, unit*0.08 + // the shaft starts a little off the centre and stops at the head + sx, sy := x1+ux*unit*0.25, y1+uy*unit*0.25 + ex, ey := x2-ux*head, y2-uy*head + pad := head + 2 + paint(img, c, 0.8, math.Min(x1, x2)-pad, math.Min(y1, y2)-pad, math.Max(x1, x2)+pad, math.Max(y1, y2)+pad, + func(x, y float64) float64 { + // signed distance inside the shaft or the head (positive = inside) + t := (x-sx)*ux + (y-sy)*uy // along the arrow, from the shaft start + n := -(x-sx)*uy + (y-sy)*ux + shaftLen := (ex-sx)*ux + (ey-sy)*uy + shaft := math.Min(halfShaft-math.Abs(n), math.Min(t, shaftLen+1-t)) + // head: triangle from (ex,ey) widening back to the tip at (x2,y2) + th := (x-ex)*ux + (y-ey)*uy + tri := math.Min(th, head-th) // between base and tip + if tri > -1 { + width := halfHead * (1 - th/head) + tri = math.Min(tri, (width-math.Abs(n))*head/math.Hypot(head, halfHead)) + } + return math.Max(shaft, tri) + }) + } + return img +} + +// paint fills the pixels where inside(x, y) > 0 within a box, blending +// colour c at the given opacity, antialiased over one pixel. +func paint(img *image.RGBA, c color.NRGBA, opacity, x0, y0, x1, y1 float64, inside func(x, y float64) float64) { + b := img.Bounds() + for y := max(b.Min.Y, int(y0)); y < min(b.Max.Y, int(math.Ceil(y1))); y++ { + for x := max(b.Min.X, int(x0)); x < min(b.Max.X, int(math.Ceil(x1))); x++ { + cover := math.Max(0, math.Min(1, inside(float64(x)+0.5, float64(y)+0.5)+0.5)) + if cover == 0 { + continue + } + a := cover * opacity + i := img.PixOffset(x, y) + p := img.Pix[i : i+4 : i+4] + // "over" compositing in premultiplied RGBA + p[0] = uint8(float64(c.R)*a + float64(p[0])*(1-a)) + p[1] = uint8(float64(c.G)*a + float64(p[1])*(1-a)) + p[2] = uint8(float64(c.B)*a + float64(p[2])*(1-a)) + p[3] = uint8(255*a + float64(p[3])*(1-a)) + } + } +} + +// Clock bars: a bar above and below the board, beside each player, showing +// how much of their time is left. Remaining time is gold, time used greys +// out, drawn in braille dots (two dot columns per cell, so the bar moves in +// half-cell steps). The running clock's bar is the brighter gold. + +// clockBar is one player's clock: the time (label, e.g. "1:29") and a bar +// of the time left (frac 0-1, or < 0 for no bar, e.g. correspondence). +type clockBar struct { + label string + right string // shown at the other end, e.g. the time control + frac float64 + active bool // this clock is running + title string // a player's title (GM, IM...), before the label + plain bool // a player line (studies), not a clock: the label in plain text +} + +func (c clockBar) shown() bool { return c.label != "" || c.frac >= 0 } + +// SetClockBars sets the clocks for the players at the top and bottom of the +// board. A zero clockBar hides one. +func (b *BoardView) SetClockBars(top, bottom clockBar) { + b.mu.Lock() + defer b.mu.Unlock() + b.topBar, b.bottomBar = top, bottom +} + +// HideClockBars removes the clocks. +func (b *BoardView) HideClockBars() { b.SetClockBars(clockBar{frac: -1}, clockBar{frac: -1}) } + +func (b *BoardView) hasClockBars() bool { return b.topBar.shown() || b.bottomBar.shown() } + +// clockLabel formats seconds as m:ss (or h:mm:ss). +func clockLabel(s int) string { + s = max(0, s) + if s >= 3600 { + return fmt.Sprintf("%d:%02d:%02d", s/3600, s/60%60, s%60) + } + return fmt.Sprintf("%d:%02d", s/60, s%60) +} + +var ( + colBarActive = tc.PaletteColor(220) // gold + colBarIdle = tc.PaletteColor(178) // darker gold + colBarUsed = tc.PaletteColor(240) // grey + colTitle = tc.NewHexColor(0xbf811d) // Lichess's colour for titles (GM, IM...) +) + +// drawClockBar draws a clock width cells wide at x, y: the time, then the bar. +func drawClockBar(screen tc.Screen, x, y, width int, bar clockBar, basic bool, bg tc.Color) { + if !bar.shown() || width <= 0 { + return + } + gold, used := colBarIdle, colBarUsed + if bar.active { + gold = colBarActive + } + if basic { + gold, used = tc.ColorOlive, tc.ColorGray + if bar.active { + gold = tc.ColorYellow + } + } + if bar.plain { // a player: title in Lichess's orange, then name and rating + x0 := x + put := func(s string, style tc.Style) { + for _, r := range s { + if x < x0+width { + screen.SetContent(x, y, r, nil, style) + x++ + } + } + } + title, text := colTitle, tc.PaletteColor(252) + if basic { + title, text = tc.ColorOlive, tc.ColorSilver + } + if bar.title != "" { + put(bar.title+" ", tc.StyleDefault.Foreground(title).Background(bg).Bold(true)) + } + put(bar.label, tc.StyleDefault.Foreground(text).Background(bg)) + if right := []rune(bar.right); len(right) > 0 && x+1+len(right) <= x0+width { + for i, r := range right { + screen.SetContent(x0+width-len(right)+i, y, r, nil, tc.StyleDefault.Foreground(text).Background(bg).Bold(true)) + } + } + return + } + textCol := tc.PaletteColor(250) + if basic { + textCol = tc.ColorSilver + } + if bar.label != "" { + // the running clock's time is highlighted, like on Lichess + style := tc.StyleDefault.Foreground(textCol).Background(bg) + if bar.active { + style = tc.StyleDefault.Foreground(tc.ColorBlack).Background(gold).Bold(true) + } + label := []rune(" " + bar.label + " ") + for i, r := range label { + if i < width { + screen.SetContent(x+i, y, r, nil, style) + } + } + x += len(label) + 1 + width -= len(label) + 1 + } + if bar.right != "" { + right := []rune(" " + bar.right) + if len(right) < width { + for i, r := range right { + screen.SetContent(x+width-len(right)+i, y, r, nil, tc.StyleDefault.Foreground(textCol).Background(bg)) + } + width -= len(right) + 1 + } + } + if bar.frac < 0 || width <= 0 { + return + } + units := int(math.Round(math.Max(0, math.Min(1, bar.frac)) * float64(2*width))) + for i := 0; i < width; i++ { + r, fg := '⣿', gold + switch { + case 2*i+2 <= units: // both dot columns: time left + case 2*i+1 == units: // left column only + r = '⡇' + default: // time used + fg = used + } + screen.SetContent(x+i, y, r, nil, tc.StyleDefault.Foreground(fg).Background(bg)) + } +} + +// A king in check glows red, as on Lichess: a radial gradient behind it with +// image rendering, a red square otherwise. + +var colCheck = tc.NewRGBColor(0xe7, 0, 0) + +// shownMove is the move that led to the position shown, or nil (the start, +// or a board without its history). Locked by caller. +func (b *BoardView) shownMove() *chess.Move { + if len(b.history) == 0 || len(b.historyMoves) != len(b.history)-1 { + return nil + } + i := len(b.history) - 1 - b.back // index of the position shown + if i < 1 { + return nil + } + return b.historyMoves[i-1] +} + +// checkSquare is the square of the king in check in the position shown +// (checkmate too), or chess.NoSquare. Locked by caller. +func (b *BoardView) checkSquare() chess.Square { + m := b.shownMove() + if m == nil || !m.HasTag(chess.Check) { + return chess.NoSquare + } + pos, _, _ := b.shown() + if pos == nil { + return chess.NoSquare + } + king := chess.WhiteKing + if pos.Turn() == chess.Black { + king = chess.BlackKing + } + for sq, p := range pos.Board().SquareMap() { + if p == king { + return sq + } + } + return chess.NoSquare +} + +// checkGlowImage is the glow, size pixels square: Lichess's gradient, red at +// the centre fading out by the edge of the square (radial-gradient(ellipse +// at center, red 0%, #e70000 25%, rgba(169,0,0,0) 89%)). +func checkGlowImage(size int) *image.RGBA { + img := image.NewRGBA(image.Rect(0, 0, size, size)) + c := float64(size) / 2 + r := c * math.Sqrt2 // to the corners, as CSS's default + type stop struct{ at, r, g, b, a float64 } + stops := []stop{{0, 255, 0, 0, 1}, {0.25, 231, 0, 0, 1}, {0.89, 169, 0, 0, 0}, {1, 158, 0, 0, 0}} + for y := 0; y < size; y++ { + for x := 0; x < size; x++ { + d := math.Hypot(float64(x)+0.5-c, float64(y)+0.5-c) / r + s0, s1 := stops[len(stops)-2], stops[len(stops)-1] + for i := 1; i < len(stops); i++ { + if d <= stops[i].at { + s0, s1 = stops[i-1], stops[i] + break + } + } + t := math.Max(0, math.Min(1, (d-s0.at)/(s1.at-s0.at))) + a := s0.a + (s1.a-s0.a)*t + lerp := func(u, v float64) uint8 { return uint8((u + (v-u)*t) * a) } // premultiplied + img.SetRGBA(x, y, color.RGBA{lerp(s0.r, s1.r), lerp(s0.g, s1.g), lerp(s0.b, s1.b), uint8(255 * a)}) + } + } + return img +} diff --git a/pkg/board_extras_test.go b/pkg/board_extras_test.go new file mode 100644 index 0000000..7c4c3de --- /dev/null +++ b/pkg/board_extras_test.go @@ -0,0 +1,118 @@ +package pkg + +import ( + "testing" + + tc "github.com/gdamore/tcell/v3" + "github.com/notnil/chess" +) + +func TestHistoryStepping(t *testing.T) { + game, _ := gameFromSAN("", "e4 e5 Nf3") + b := NewBoardView(nil) + b.SetPosition(game.Position(), true) + b.SetHistory(game.Positions(), game.Moves()) + + b.mu.Lock() + b.step(1) // back one: after 1. e4 e5 + pos, from, to := b.shown() + b.mu.Unlock() + if pos.Board().Piece(chess.F3) != chess.NoPiece || from != chess.E7 || to != chess.E5 { + t.Errorf("one back: %v %v-%v", pos, from, to) + } + b.mu.Lock() + b.step(100) // clamps at the start + pos, from, _ = b.shown() + b.mu.Unlock() + if pos.String() != chess.StartingPosition().String() || from != chess.NoSquare { + t.Errorf("start: %v", pos) + } + if !b.ViewingHistory() { + t.Error("should be viewing history") + } + // a new move brings the board back to the present + game.MoveStr("Nc6") + b.SetHistory(game.Positions(), game.Moves()) + if b.ViewingHistory() { + t.Error("a new move should return to the present") + } +} + +func TestShapes(t *testing.T) { + b := NewBoardView(nil) + arrow := boardShape{from: chess.E2, to: chess.E4, color: 0} + b.toggleShape(arrow) + b.toggleShape(boardShape{from: chess.D4, to: chess.D4, color: 1}) + if len(b.shapes) != 2 { + t.Fatalf("shapes: %v", b.shapes) + } + // same arrow in another colour replaces it; same colour removes it + b.toggleShape(boardShape{from: chess.E2, to: chess.E4, color: 2}) + if len(b.shapes) != 2 || b.shapes[1].color != 2 { + t.Errorf("recolour: %v", b.shapes) + } + b.toggleShape(boardShape{from: chess.E2, to: chess.E4, color: 2}) + if len(b.shapes) != 1 { + t.Errorf("remove: %v", b.shapes) + } + if shapeColorFor(tc.ModShift|tc.ModAlt) != 3 || shapeColorFor(tc.ModShift) != 1 || shapeColorFor(tc.ModAlt) != 2 || shapeColorFor(0) != 0 { + t.Error("brush colours") + } + // the arrow image has paint along the arrow and none in the far corner + img := shapesImage([]boardShape{arrow}, true, 20, 20) + if img.RGBAAt(4*20+10, 5*20+10).A == 0 { // e3, mid-shaft + t.Error("arrow shaft not drawn") + } + if img.RGBAAt(5, 5).A != 0 { + t.Error("paint where there's no shape") + } + // a new position clears the shapes + b.SetPosition(chess.NewGame().Position(), false) + if len(b.shapes) != 0 { + t.Error("shapes kept after the position changed") + } +} + +func TestResultBadges(t *testing.T) { + b := NewBoardView(nil) + b.SetResult(chess.Black, "mate") + if b.badgeFor(chess.Black) != badgeWin || b.badgeFor(chess.White) != badgeMate { + t.Error("mate badges") + } + b.SetResult(chess.White, "resign") + if b.badgeFor(chess.Black) != badgeLoss { + t.Error("resignation badge") + } + b.SetResult(chess.NoColor, "stalemate") + if b.badgeFor(chess.White) != badgeDraw || b.badgeFor(chess.Black) != badgeDraw { + t.Error("draw badges") + } + for k := badgeWin; k <= badgeDraw; k++ { + img := badgeImage(k, 24) + if img.RGBAAt(12, 12).A == 0 { + t.Errorf("badge %d empty in the middle", k) + } + } + if resultText(chess.White, "timeout") != "[::b]1–0[::-]\nWhite wins by time" { + t.Error(resultText(chess.White, "timeout")) + } +} + +func TestDrawBoardStyles(t *testing.T) { + // every style draws without panicking on a small and a large screen + for _, size := range [][2]int{{40, 12}, {200, 60}} { + s := newMockScreen(t, size[0], size[1]) + b := NewBoardView(nil) + b.SetRect(0, 0, size[0], size[1]) + game, _ := gameFromSAN("", "f3 e5 g4 Qh4") + b.SetPosition(game.Position(), true) + b.SetResult(chess.Black, "mate") + b.SetClockBars(clockBar{label: "1:00", frac: 0.5, right: "3+2", active: true}, clockBar{label: "2:00", frac: 1}) + b.toggleShape(boardShape{from: chess.E2, to: chess.E4}) + b.Draw(s) + b.mu.Lock() + b.step(1) + b.mu.Unlock() + b.Draw(s) + } +} diff --git a/pkg/board_test.go b/pkg/board_test.go new file mode 100644 index 0000000..b1e4289 --- /dev/null +++ b/pkg/board_test.go @@ -0,0 +1,304 @@ +package pkg + +import ( + "testing" + + cv "codeberg.org/tslocum/cview" + tc "github.com/gdamore/tcell/v3" + "github.com/gdamore/tcell/v3/vt" + "github.com/notnil/chess" +) + +func TestBoardGeometryFitsAndGrows(t *testing.T) { + prev := 0 + for _, sz := range [][2]int{{30, 10}, {60, 20}, {80, 26}, {120, 40}, {200, 60}, {300, 90}} { + w, h := sz[0], sz[1] + sqW, sqH := boardGeometry(w, h, styleGlyph, 2) + if sqW == 0 { + t.Fatalf("%dx%d: no board", w, h) + } + if 8*sqW+labelW > w || 8*sqH+labelH > h { + t.Errorf("%dx%d: board %dx%d squares overflows", w, h, sqW, sqH) + } + if sqH < prev { + t.Errorf("%dx%d: squares shrank (%d < %d)", w, h, sqH, prev) + } + prev = sqH + } + if w, _ := boardGeometry(10, 5, styleGlyph, 2); w != 0 { + t.Errorf("tiny area should report no board") + } +} + +func TestSquareMappingRoundTrip(t *testing.T) { + for _, white := range []bool{true, false} { + for sq := chess.A1; sq <= chess.H8; sq++ { + r, c := displayOf(sq, white) + if got := squareAt(r, c, white); got != sq { + t.Fatalf("white=%v %v -> (%d,%d) -> %v", white, sq, r, c, got) + } + } + } + if squareAt(7, 0, true) != chess.A1 || squareAt(7, 0, false) != chess.H8 { + t.Errorf("bottom-left square wrong for orientation") + } +} + +func TestHandleSquareSelectAndMove(t *testing.T) { + b := NewBoardView(nil) + g := chess.NewGame(chess.UseNotation(chess.UCINotation{})) + var played string + do := func(uci string) { played = uci } + + b.HandleSquare(g, chess.E7, true, do) // opponent's piece: ignored + if b.Selected() != chess.NoSquare { + t.Fatalf("selected a black piece on white's turn") + } + b.HandleSquare(g, chess.E2, true, do) + if b.Selected() != chess.E2 || !b.targets[chess.E4] || b.targets[chess.E5] { + t.Fatalf("bad selection/targets: %v %v", b.Selected(), b.targets) + } + b.HandleSquare(g, chess.E4, true, do) + if played != "e2e4" || b.Selected() != chess.NoSquare { + t.Fatalf("played %q, selected %v", played, b.Selected()) + } + b.HandleSquare(g, chess.G1, true, do) + b.HandleSquare(g, chess.G1, true, do) // click again: deselect + if b.Selected() != chess.NoSquare { + t.Fatalf("second click should deselect") + } +} + +func TestPromotionPicker(t *testing.T) { + fen, _ := chess.FEN("8/4P3/8/8/8/8/k7/4K3 w - - 0 1") + for _, tc := range []struct { + name string + pick func(b *BoardView, g *chess.Game, do func(string)) + want string + white bool + }{ + {"queen by click", func(b *BoardView, g *chess.Game, do func(string)) { b.HandleSquare(g, chess.E8, true, do) }, "e7e8q", true}, + {"knight by click", func(b *BoardView, g *chess.Game, do func(string)) { b.HandleSquare(g, chess.E7, true, do) }, "e7e8n", true}, + {"rook by click", func(b *BoardView, g *chess.Game, do func(string)) { b.HandleSquare(g, chess.E6, true, do) }, "e7e8r", true}, + {"bishop by click", func(b *BoardView, g *chess.Game, do func(string)) { b.HandleSquare(g, chess.E5, true, do) }, "e7e8b", true}, + {"knight by key", func(b *BoardView, g *chess.Game, do func(string)) { + sq, ok := b.promoSquareFor("N") + if !ok { + t.Fatal("no picker square for n") + } + b.HandleSquare(g, sq, true, do) + }, "e7e8n", true}, + // board flipped (black at bottom): e8 is on the bottom row, picker goes up + {"flipped rook by click", func(b *BoardView, g *chess.Game, do func(string)) { b.HandleSquare(g, chess.E6, true, do) }, "e7e8r", false}, + {"cancel by clicking away", func(b *BoardView, g *chess.Game, do func(string)) { b.HandleSquare(g, chess.A1, true, do) }, "", true}, + } { + t.Run(tc.name, func(t *testing.T) { + g := chess.NewGame(fen) + b := NewBoardView(nil) + b.SetPosition(g.Position(), tc.white) + played := "" + do := func(u string) { played = u } + b.HandleSquare(g, chess.E7, true, do) + if b.HandleSquare(g, chess.E8, true, do) || played != "" { + t.Fatalf("promotion should wait for a choice, played %q", played) + } + if !b.PromotionOpen() { + t.Fatal("picker not open") + } + tc.pick(b, g, do) + if played != tc.want { + t.Fatalf("played %q, want %q", played, tc.want) + } + if b.PromotionOpen() { + t.Fatal("picker still open") + } + }) + } +} + +// newTestScreen is a real terminfo screen attached to tcell's mock terminal, +// finalised when the test ends. +func newTestScreen(t *testing.T, w, h int) tc.Screen { + t.Helper() + s := newMockScreen(t, w, h) + t.Cleanup(s.Fini) + return s +} + +func newMockScreen(t *testing.T, w, h int) tc.Screen { + t.Helper() + mt := vt.NewMockTerm(vt.MockOptSize{X: vt.Col(w), Y: vt.Row(h)}, vt.MockOptColors(1<<24)) + s, err := tc.NewTerminfoScreenFromTty(mt) + if err != nil { + t.Fatal(err) + } + if err := s.Init(); err != nil { + t.Fatal(err) + } + return s +} + +func TestParseMoveInput(t *testing.T) { + promo, _ := chess.FEN("r3k2r/1P6/8/8/8/8/8/R3K2R w KQkq - 0 1") + start := chess.NewGame(chess.UseNotation(chess.UCINotation{})) + for _, tc := range []struct { + game *chess.Game + in string + want string + }{ + {start, "e2e4", "e2e4"}, + {start, "E2E4", "e2e4"}, + {start, "e2-e4", "e2e4"}, + {start, "Nf3", "g1f3"}, + {start, "e4", "e2e4"}, + {start, "Ng1f3", "g1f3"}, + {chess.NewGame(promo), "b7b8=N", "b7b8n"}, + {chess.NewGame(promo), "b7b8n", "b7b8n"}, + {chess.NewGame(promo), "b7b8N", "b7b8n"}, + {chess.NewGame(promo), "b8=R", "b7b8r"}, + {chess.NewGame(promo), "bxa8=Q", "b7a8q"}, + {chess.NewGame(promo), "O-O", "e1g1"}, + {chess.NewGame(promo), "0-0-0", "e1c1"}, + {chess.NewGame(promo), "b7b8", ""}, // promotion needs a piece + {start, "e2e5", ""}, + {start, "Nf6", ""}, + {start, "", ""}, + } { + got, err := parseMoveInput(tc.game, tc.in) + if tc.want == "" { + if err == nil { + t.Errorf("%q: expected an error, got %q", tc.in, got) + } + continue + } + if err != nil || got != tc.want { + t.Errorf("%q: got %q, %v; want %q", tc.in, got, err, tc.want) + } + } +} + +// The keyboard cursor stays hidden until a key is used (the first key only +// shows it), a click hides it, and a study board never shows it. +func TestBoardCursorShowsOnKeys(t *testing.T) { + key := func(b *BoardView, k tc.Key) { + b.InputHandler()(tc.NewEventKey(k, "", tc.ModNone), func(cv.Primitive) {}) + } + var picked []chess.Square + b := NewBoardView(func(sq chess.Square) { picked = append(picked, sq) }) + if b.keyboard { + t.Fatal("cursor shown before any key") + } + key(b, tc.KeyUp) + if !b.keyboard || b.cursor != chess.E2 { + t.Fatalf("first key: shown %v on %v, want shown on e2", b.keyboard, b.cursor) + } + key(b, tc.KeyUp) + if b.cursor != chess.E3 { + t.Errorf("second key moved cursor to %v, want e3", b.cursor) + } + key(b, tc.KeyEnter) + if len(picked) != 1 || picked[0] != chess.E3 { + t.Errorf("Enter picked %v, want [e3]", picked) + } + + study := NewBoardView(func(chess.Square) {}) + study.browse = true + key(study, tc.KeyUp) + key(study, tc.KeyEnter) + if study.keyboard { + t.Error("study board shows a cursor") + } +} + +// The game layout adapts: sidebar beside a good-sized board, the board on +// top in a narrow tall terminal, the board alone in a small one, and in a +// wide one the sidebar stops growing and the two are centred. +func TestGameLayoutAdapts(t *testing.T) { + sq := func(w, h int) int { + _, s := boardGeometry(w, h, styleGlyph, 2) + return s + } + for _, c := range []struct { + w, h int + want layoutMode + }{ + {120, 36, layoutSide}, + {250, 60, layoutSide}, + {100, 30, layoutSide}, + {80, 24, layoutBoard}, // beside a sidebar the squares would be one row high + {70, 50, layoutStacked}, + {56, 22, layoutBoard}, + } { + if got := layoutFor(c.w, c.h, sq); got != c.want { + t.Errorf("%dx%d: layout %d, want %d", c.w, c.h, got, c.want) + } + } + + startTestApp(t, 160, 50) + onUI(func() { + Root.Switch("study") + Root.study.show(parseStudyPGN(testStudyPGN), "") + }) + // draw lays the screen out at w x h and runs check on the result, all in + // one go on the UI goroutine: onUI redraws the app at its own size + // afterwards, which would move everything again before a later look. + draw := func(board *BoardView, w, h int, check func(l *boardLayout)) { + onUI(func() { + _, p := Root.nav.GetFrontPanel() + scr := newMockScreen(t, w, h) + p.SetRect(0, 0, w, h) + p.Draw(scr) + check(layoutOf[board]) + }) + } + defer onUI(func() { Root.nav.SetRect(0, 0, 160, 50) }) + + draw(Root.study.Board, 250, 60, func(l *boardLayout) { + _, _, sw, _ := l.side.GetRect() + lx, _, lw, _ := l.left.GetRect() + _, _, rw, _ := l.right.GetRect() + if sw != maxSidebar || lw == 0 || lx != 0 || lw-rw > 1 || rw-lw > 1 { + t.Errorf("wide: sidebar %d (want %d), margins %d and %d (want equal, non-zero)", sw, maxSidebar, lw, rw) + } + }) + draw(Root.study.Board, 70, 50, func(l *boardLayout) { + _, by, _, bh := l.board.GetRect() + _, sy, _, _ := l.side.GetRect() + if by != 0 || sy != by+bh { + t.Errorf("narrow: board at row %d (%d high), sidebar at row %d; want board on top, sidebar below", by, bh, sy) + } + }) + draw(Root.study.Board, 56, 22, func(l *boardLayout) { + if _, _, bw, _ := l.board.GetRect(); bw != 56 { + t.Errorf("small: board %d wide, want the whole width", bw) + } + }) + // the menu focused: the board stays, the menu shows under it + onUI(func() { Root.App.SetFocus(Root.study.List) }) + draw(Root.study.Board, 56, 22, func(l *boardLayout) { + _, by, bw, bh := l.board.GetRect() + _, my, mw, mh := Root.study.List.GetRect() + if bw != 56 || bh < 14 || my != by+bh || mw != 56 || mh != Root.study.List.GetItemCount() { + t.Errorf("small with the menu focused: board %dx%d at row %d, menu %dx%d at row %d; want the board, the menu under it", + bw, bh, by, mw, mh, my) + } + }) + // typing a move in a small local game: the board stays in view + onUI(func() { + startNewLocalGame() + Root.lgame.Move.show() + }) + draw(Root.lgame.Board, 56, 22, func(l *boardLayout) { + _, by, bw, bh := l.board.GetRect() + _, iy, _, ih := Root.lgame.Move.input.GetRect() + if bw != 56 || bh < 14 || iy != by+bh || ih != 1 { + t.Errorf("typing a move: board %dx%d, move box at row %d (%d high); want the board with the box under it", bw, bh, iy, ih) + } + }) + onUI(func() { + Root.lgame.Move.hide() + gotoWelcome() + Root.Switch("study") + }) + onUI(func() { Root.App.SetFocus(Root.study.Board) }) +} diff --git a/pkg/check_glow_test.go b/pkg/check_glow_test.go new file mode 100644 index 0000000..89a715c --- /dev/null +++ b/pkg/check_glow_test.go @@ -0,0 +1,88 @@ +package pkg + +import ( + "testing" + + tc "github.com/gdamore/tcell/v3" + "github.com/notnil/chess" +) + +func boardAfter(t *testing.T, moves ...string) *BoardView { + t.Helper() + g := chess.NewGame() + for _, m := range moves { + if err := g.MoveStr(m); err != nil { + t.Fatal(err) + } + } + b := NewBoardView(nil) + b.SetPosition(g.Position(), true) + b.SetHistory(g.Positions(), g.Moves()) + return b +} + +func TestCheckSquare(t *testing.T) { + b := boardAfter(t, "e4", "f5", "Qh5+") + b.mu.Lock() + if sq := b.checkSquare(); sq != chess.E8 { + t.Errorf("check: glow on %v, want e8", sq) + } + b.step(1) // back to before the check + if sq := b.checkSquare(); sq != chess.NoSquare { + t.Errorf("stepped back: glow on %v, want none", sq) + } + b.mu.Unlock() + + mate := boardAfter(t, "f3", "e5", "g4", "Qh4#") + mate.mu.Lock() + if sq := mate.checkSquare(); sq != chess.E1 { + t.Errorf("checkmate: glow on %v, want e1", sq) + } + mate.mu.Unlock() + + quiet := boardAfter(t, "e4", "e5") + quiet.mu.Lock() + if sq := quiet.checkSquare(); sq != chess.NoSquare { + t.Errorf("no check, but glow on %v", sq) + } + quiet.mu.Unlock() +} + +func TestCheckGlowImage(t *testing.T) { + img := checkGlowImage(64) + centre, corner := img.RGBAAt(32, 32), img.RGBAAt(0, 0) + if centre.R < 200 || centre.A < 200 || centre.G != 0 { + t.Errorf("centre %v: want bright opaque red", centre) + } + if corner.A != 0 { + t.Errorf("corner %v: want transparent", corner) + } + if mid := img.RGBAAt(32, 4); mid.A == 0 || mid.A >= centre.A { + t.Errorf("edge %v: want fading", mid) + } +} + +// In text and basic rendering the checked king's square is red. +func TestCheckGlowDrawn(t *testing.T) { + for _, mode := range []string{PiecesText, PiecesBasic} { + previewPieces(mode) + scr := newMockScreen(t, 120, 40) + b := boardAfter(t, "e4", "f5", "Qh5+") + b.SetRect(0, 0, 120, 40) + b.Draw(scr) + b.mu.Lock() + row, col := displayOf(chess.E8, b.white) + x, y := b.ox+col*b.sqW, b.oy+row*b.sqH + b.mu.Unlock() + _, st, _ := scr.Get(x, y) + want := blend(colLight, colCheck, 0.7) // e8 is a light square + if mode == PiecesBasic { + want = tc.ColorMaroon + } + if st.GetBackground() != want { + t.Errorf("%s: e8 background %v, want %v", mode, st.GetBackground(), want) + } + scr.Fini() + } + previewPieces("") +} diff --git a/pkg/defs.go b/pkg/defs.go index daf818a..80dddb9 100644 --- a/pkg/defs.go +++ b/pkg/defs.go @@ -1,7 +1,7 @@ package pkg import ( - cv "code.rocketnine.space/tslocum/cview" + cv "codeberg.org/tslocum/cview" "github.com/nate-xyz/chess-cli/api" "github.com/notnil/chess" "golang.org/x/text/cases" @@ -10,19 +10,13 @@ import ( var ( Root = new(State) - killGame chan string - NewChessGame *chess.Game //used in online.go in the LichessGame() function to update the board position from new stream event newChallenge api.CreateChallengeType //used initUI.go in initConstruct() in order to save settings from a challenge construction CurrentChallenge api.CreateChallengeType currentGameID string - gameStateChan chan api.BoardEvent StreamChannel chan api.StreamEventType - LastSelectedCell PiecePosition GameListIDArr []string OutChallengeGameID []string InChallengeGameID []string - EventStreamArr []api.StreamEventType - Ready chan struct{} caser = cases.Title(language.English) ) @@ -30,14 +24,15 @@ const ( ApplicationTitle string = `[blue]chess-cli ♟️ [white] Play locally with a [yellow]friend[white] or online with [red]Lichess!` LichessTitle string = "[blue]chess-cli[white]: [red]lichess[white] client" - LichessRibbon string = "CHESS-CLI | LICHESS CLIENT | Press 'Ctrl-c' to quit" - welcomeRibbonstr string = "WELCOME TO CHESS-CLI ! | Press 'Ctrl-c' to quit" - gameRibbonstr string = "CHESS-CLI -> local game | Press 'Ctrl-c' to quit" - challengeRibbonstr string = "CHESS-CLI -> create a challenge | Press 'Ctrl-c' to quit" - gameOnlineRibbonstr string = "CHESS-CLI -> online game | Press 'Ctrl-c' to quit" - OngoingRibbonstr string = "CHESS-CLI -> Ongoing Games | Press 'Ctrl-c' to quit" - EmptyChar string = "博" - saved_path string = "saved_games.json" + LichessRibbon string = " chess-cli · Lichess │ ↑↓ + Enter, or press a letter │ Ctrl-C quit" + welcomeRibbonstr string = " chess-cli │ ↑↓ + Enter, or press a letter │ Ctrl-C quit" + gameRibbonstr string = " chess-cli · local game │ Ctrl-K type a move │ click or arrows/hjkl + Enter to move │ Tab menu │ Ctrl-C quit" + challengeRibbonstr string = " chess-cli · new challenge │ ↑↓ + Enter, or press a letter │ Ctrl-C quit" + gameOnlineRibbonstr string = " chess-cli · Lichess game │ Ctrl-K type a move │ click or arrows/hjkl + Enter to move │ Tab chat/menu │ Ctrl-C quit" + postRibbonstr string = " chess-cli · game over │ click a move, scroll or [ ] to look back │ Tab board ⇄ menu │ Ctrl-C quit" + OngoingRibbonstr string = " chess-cli · ongoing games │ ↑↓ or 1-9 to pick │ Tab menu │ Ctrl-C quit" + savedRibbonstr string = " chess-cli · saved games │ ↑↓ or 1-9 to pick │ Tab menu │ Ctrl-C quit" + saved_path string = "saved_games.json" // legacy location, see savedGamesPath ) type State struct { @@ -55,12 +50,14 @@ type State struct { ponline *OnlinePostGame ongoing *Ongoing challenges *Challenges + puzzle *PuzzleScreen + watch *WatchScreen + study *StudyScreen sglist *SavedGameList } type Login struct { Token string - Email string Online bool StreamStart bool Name string @@ -94,11 +91,6 @@ type PiecePosition struct { Symbol string } -type BothInc struct { - wtime int64 - btime int64 -} - var ( PiecesMap = map[rune]string{ 'K': "♔", @@ -112,7 +104,7 @@ var ( 'r': "♜", 'b': "♝", 'n': "♞", - 'p': "🨾", + 'p': "♟\uFE0E", // U+FE0E: text, not emoji } KnightIconMap = map[int]string{ diff --git a/pkg/engine.go b/pkg/engine.go new file mode 100644 index 0000000..66f6d0e --- /dev/null +++ b/pkg/engine.go @@ -0,0 +1,283 @@ +package pkg + +import ( + "bufio" + "context" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "sync" + "sync/atomic" + "time" +) + +// A local chess engine (Stockfish), spoken to over UCI: the standard text +// protocol on its stdin/stdout. + +// stockfishLevels are Lichess-style levels 1-8: Stockfish's skill level +// (0-20), how long it may think and how deep it may search. +var stockfishLevels = []struct { + skill, movetimeMS, depth int +}{ + {0, 50, 1}, {2, 100, 2}, {5, 150, 4}, {8, 200, 6}, + {11, 300, 8}, {14, 400, 12}, {17, 700, 16}, {20, 1000, 22}, +} + +// FindStockfish returns the Stockfish to use: $CHESS_CLI_STOCKFISH, then +// "stockfish" on the PATH, then where installers put it (in case the PATH +// hasn't caught up, e.g. a shell opened before winget installed it). "" +// if none. +func FindStockfish() string { + if p := os.Getenv("CHESS_CLI_STOCKFISH"); p != "" { + return p + } + if p, err := exec.LookPath("stockfish"); err == nil { + return p + } + for _, p := range stockfishLocations() { + if st, err := os.Stat(p); err == nil && !st.IsDir() { + return p + } + } + return "" +} + +// stockfishLocations are the usual install locations on this system. +func stockfishLocations() []string { + home, _ := os.UserHomeDir() + switch runtime.GOOS { + case "windows": + var ps []string + if d := os.Getenv("LOCALAPPDATA"); d != "" { + ps = append(ps, filepath.Join(d, "Microsoft", "WinGet", "Links", "stockfish.exe")) // winget + } + if home != "" { + ps = append(ps, filepath.Join(home, "scoop", "shims", "stockfish.exe")) // Scoop + } + if d := os.Getenv("ProgramData"); d != "" { + ps = append(ps, filepath.Join(d, "chocolatey", "bin", "stockfish.exe")) // Chocolatey + } + for _, env := range []string{"ProgramFiles", "ProgramFiles(x86)"} { + if d := os.Getenv(env); d != "" { + ps = append(ps, filepath.Join(d, "Stockfish", "stockfish.exe")) + } + } + return ps + case "darwin": + return []string{"/opt/homebrew/bin/stockfish", "/usr/local/bin/stockfish", "/opt/local/bin/stockfish"} // Homebrew (Apple silicon, Intel), MacPorts + } + return []string{"/usr/games/stockfish", "/usr/bin/stockfish", "/usr/local/bin/stockfish", "/snap/bin/stockfish", + filepath.Join(home, ".local", "bin", "stockfish")} +} + +// Engine is a running UCI engine. +type Engine struct { + cmd *exec.Cmd + in io.WriteCloser + lines chan string // the engine's output, line by line + level int + + mu sync.Mutex // one search at a time + closed atomic.Bool +} + +// StartEngine runs the engine at path and sets it up for a level (1-8). +func StartEngine(path string, level int) (*Engine, error) { + cmd := exec.Command(path) + in, err := cmd.StdinPipe() + if err != nil { + return nil, err + } + out, err := cmd.StdoutPipe() + if err != nil { + return nil, err + } + if err := cmd.Start(); err != nil { + return nil, err + } + e := &Engine{cmd: cmd, in: in, lines: make(chan string, 64), level: max(1, min(8, level))} + go func() { + sc := bufio.NewScanner(out) + sc.Buffer(make([]byte, 64<<10), 1<<20) + for sc.Scan() { + e.lines <- sc.Text() + } + close(e.lines) + }() + if err := e.handshake(); err != nil { + e.Close() + return nil, err + } + return e, nil +} + +func (e *Engine) send(cmd string) error { + _, err := io.WriteString(e.in, cmd+"\n") + return err +} + +// waitFor reads lines until one starts with prefix, returning it. +func (e *Engine) waitFor(ctx context.Context, prefix string) (string, error) { + for { + select { + case line, ok := <-e.lines: + if !ok { + return "", errors.New("the engine stopped") + } + if strings.HasPrefix(line, prefix) { + return line, nil + } + case <-ctx.Done(): + return "", ctx.Err() + } + } +} + +func (e *Engine) handshake() error { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := e.send("uci"); err != nil { + return err + } + if _, err := e.waitFor(ctx, "uciok"); err != nil { + return fmt.Errorf("not a UCI chess engine? %w", err) + } + lv := stockfishLevels[e.level-1] + _ = e.send(fmt.Sprintf("setoption name Skill Level value %d", lv.skill)) + _ = e.send("ucinewgame") + _ = e.send("isready") + _, err := e.waitFor(ctx, "readyok") + return err +} + +// BestMove asks for a move (UCI) in a position given as a start FEN plus the +// UCI moves played since, so the engine knows about repetitions. +func (e *Engine) BestMove(ctx context.Context, startFEN string, moves []string) (string, error) { + e.mu.Lock() + defer e.mu.Unlock() + if e.closed.Load() { + return "", errors.New("the engine was closed") + } + pos := "position fen " + startFEN + if len(moves) > 0 { + pos += " moves " + strings.Join(moves, " ") + } + lv := stockfishLevels[e.level-1] + if err := e.send(pos); err != nil { + return "", err + } + if err := e.send(fmt.Sprintf("go movetime %d depth %d", lv.movetimeMS, lv.depth)); err != nil { + return "", err + } + line, err := e.waitFor(ctx, "bestmove") + if err != nil { + _ = e.send("stop") + return "", err + } + f := strings.Fields(line) + if len(f) < 2 || f[1] == "(none)" { + return "", errors.New("the engine has no move") + } + return f[1], nil +} + +// Score is an engine evaluation from White's side: centipawns, or mate in +// Mate moves (positive: White mates; negative: Black mates; 0: no mate). +type Score struct { + CP int + Mate int +} + +// Evaluate searches a position (start FEN plus UCI moves) at full strength +// for up to movetime, and returns its score from White's side and the best +// move (UCI; "" when the game is over). +func (e *Engine) Evaluate(ctx context.Context, startFEN string, moves []string, movetime time.Duration, depth int) (Score, string, error) { + e.mu.Lock() + defer e.mu.Unlock() + if e.closed.Load() { + return Score{}, "", errors.New("the engine was closed") + } + pos := "position fen " + startFEN + if len(moves) > 0 { + pos += " moves " + strings.Join(moves, " ") + } + if err := e.send(pos); err != nil { + return Score{}, "", err + } + if err := e.send(fmt.Sprintf("go movetime %d depth %d", movetime.Milliseconds(), depth)); err != nil { + return Score{}, "", err + } + var sc Score + for { + var line string + select { + case l, ok := <-e.lines: + if !ok { + return Score{}, "", errors.New("the engine stopped") + } + line = l + case <-ctx.Done(): + _ = e.send("stop") + _, _ = e.waitFor(context.Background(), "bestmove") // keep the engine in step + return Score{}, "", ctx.Err() + } + f := strings.Fields(line) + if len(f) == 0 { + continue + } + if f[0] == "info" { + for i := 1; i+2 < len(f); i++ { + if f[i] == "score" && (f[i+1] == "cp" || f[i+1] == "mate") { + var v int + if _, err := fmt.Sscan(f[i+2], &v); err == nil { + switch { + case f[i+1] == "cp": + sc = Score{CP: v} + case v == 0: // checkmated already: as lost as can be + sc = Score{Mate: -1} + default: + sc = Score{Mate: v} + } + } + } + } + continue + } + if f[0] == "bestmove" { + best := "" + if len(f) > 1 && f[1] != "(none)" { + best = f[1] + } + // The engine scores for the side to move; turn it to White's side. + if len(moves)%2 == 1 != (strings.Fields(startFEN)[1] == "b") { + sc = Score{CP: -sc.CP, Mate: -sc.Mate} + } + return sc, best, nil + } + } +} + +// Close quits the engine (killing it if it doesn't go quietly). +func (e *Engine) Close() { + if e == nil { + return + } + if e.closed.Swap(true) { + return + } + _ = e.send("quit") // ends any search too; BestMove sees the output close + _ = e.in.Close() + done := make(chan struct{}) + go func() { _ = e.cmd.Wait(); close(done) }() + select { + case <-done: + case <-time.After(time.Second): + _ = e.cmd.Process.Kill() + <-done + } +} diff --git a/pkg/engine_game.go b/pkg/engine_game.go new file mode 100644 index 0000000..ba1be61 --- /dev/null +++ b/pkg/engine_game.go @@ -0,0 +1,134 @@ +package pkg + +import ( + "context" + "fmt" + "time" + + "github.com/nate-xyz/chess-cli/api" + "github.com/notnil/chess" +) + +// Playing a local Stockfish: the local game screen with the board turned to +// your side; Stockfish replies on its own. + +func (g *GameScreen) vsEngine() bool { return g.engine != nil } + +// engineTurn reports whether it's Stockfish's move. +func (g *GameScreen) engineTurn() bool { + return g.engine != nil && Root.gameState.Game.Position().Turn() == g.engineColor +} + +// whiteAtBottom: against Stockfish your side stays at the bottom; two-player +// games turn the board to whoever is moving. +func (g *GameScreen) whiteAtBottom() bool { + if g.engine != nil { + return g.engineColor == chess.Black + } + return Root.gameState.Game.Position().Turn() == chess.White +} + +// stopEngine ends the Stockfish game's engine, if any. +func (g *GameScreen) stopEngine() { + if g.engine != nil { + e := g.engine + g.engine = nil + g.engineGen++ + go e.Close() + } +} + +// findEngine is the Stockfish to use: the one chosen in chess-cli, one on the +// system, or one chess-cli downloaded. "" if there's none. +func findEngine() string { + if p := api.UserInfo.StockfishPath; p != "" { + return p + } + if p := FindStockfish(); p != "" { + return p + } + return downloadedStockfish() +} + +// checkEngine tries an engine, so a bad path is caught when it's chosen. +func checkEngine(path string) error { + e, err := StartEngine(path, 1) + if err != nil { + return err + } + e.Close() + return nil +} + +// startEngineGame starts a game against Stockfish at a level (1-8), with +// the player as player. +func startEngineGame(path string, level int, player chess.Color) { + g := Root.lgame + g.stopEngine() + Root.NewGame() + g.startClock() + g.tickClock() + g.engineColor = player.Other() + g.engineLevel = level + g.engineGen++ + gen := g.engineGen + Root.gameState.Status = "Starting Stockfish…" + Root.Switch("localgame") + playSound(soundStart) + DrawBoard(g.Board, player == chess.White) + g.UpdateStatus() + g.Board.ClearSelection() + go func() { + e, err := StartEngine(path, level) + Root.App.QueueUpdateDraw(func() { + if gen != g.engineGen { + if e != nil { + go e.Close() + } + return + } + if err != nil { + Root.gameState.Status = fmt.Sprintf("[red]Couldn't start Stockfish: %v[-]\n", err) + g.UpdateStatus() + return + } + g.engine = e + g.UpdateUserInfo() + g.UpdateStatus() + if g.engineTurn() { + g.engineMove() + } + }) + }() +} + +// engineMove asks Stockfish for its move and plays it. +func (g *GameScreen) engineMove() { + e, gen := g.engine, g.engineGen + game := Root.gameState.Game + start := game.Positions()[0].String() + var moves []string + for i, m := range game.Moves() { + moves = append(moves, chess.UCINotation{}.Encode(game.Positions()[i], m)) + } + g.UpdateStatus() + go func() { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + uci, err := e.BestMove(ctx, start, moves) + Root.App.QueueUpdateDraw(func() { + if gen != g.engineGen || g.engine != e { + return // the game was left or restarted meanwhile + } + if err != nil { + Root.gameState.Status = fmt.Sprintf("[red]Stockfish: %v[-]\n", err) + g.UpdateStatus() + return + } + if err := g.DoMove(uci); err != nil { + Root.gameState.Status = fmt.Sprintf("[red]Stockfish played an illegal move (%s): %v[-]\n", uci, err) + g.UpdateStatus() + } + }) + }() +} diff --git a/pkg/engine_test.go b/pkg/engine_test.go new file mode 100644 index 0000000..1cf05b1 --- /dev/null +++ b/pkg/engine_test.go @@ -0,0 +1,95 @@ +package pkg + +import ( + "context" + "os" + "runtime" + "strings" + "testing" + "time" + + "github.com/notnil/chess" +) + +func TestMain(m *testing.M) { + soundsMuted.Store(true) // tests never make a noise + os.Exit(m.Run()) +} + +// realStockfish is the installed Stockfish; the test is skipped without one. +func realStockfish(t *testing.T) string { + t.Helper() + path := findEngine() + if path == "" { + t.Skip("Stockfish isn't installed") + } + return path +} + +func TestEngineBestMove(t *testing.T) { + e, err := StartEngine(realStockfish(t), 3) + if err != nil { + t.Fatal(err) + } + defer e.Close() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + start := chess.StartingPosition().String() + move, err := e.BestMove(ctx, start, []string{"e2e4"}) + if err != nil { + t.Fatal(err) + } + game := chess.NewGame() + game.MoveStr("e4") + if _, err := (chess.UCINotation{}).Decode(game.Position(), move); err != nil { + t.Errorf("engine move %q isn't legal after 1. e4: %v", move, err) + } +} + +func TestEngineRejectsNonEngine(t *testing.T) { + if err := checkEngine("/bin/true"); err == nil { + t.Error("/bin/true accepted as a chess engine") + } +} + +// A game against Stockfish on the real UI: the engine replies. +func TestEngineGame(t *testing.T) { + path := realStockfish(t) + startTestApp(t, 160, 50) + onUI(func() { startEngineGame(path, 2, chess.White) }) + g := Root.lgame + waitFor(t, "engine started", func() bool { return g.engine != nil }) + onUI(func() { + if err := g.DoMove("e2e4"); err != nil { + t.Error(err) + } + }) + waitFor(t, "engine reply", func() bool { return len(Root.gameState.Game.Moves()) == 2 }) + onUI(func() { + if g.engineTurn() || !g.whiteAtBottom() { + t.Error("after the reply it should be white's turn, white at the bottom") + } + gotoWelcome() // leaving stops the engine + }) + waitFor(t, "engine stopped", func() bool { return g.engine == nil }) +} + +// Where installers put Stockfish: the package managers' folders on each +// system, so it's found even before the PATH catches up. +func TestStockfishLocations(t *testing.T) { + locs := strings.Join(stockfishLocations(), "\n") + var want []string + switch runtime.GOOS { + case "windows": + want = []string{`WinGet\Links\stockfish.exe`, `scoop\shims\stockfish.exe`, `chocolatey\bin\stockfish.exe`} + case "darwin": + want = []string{"/opt/homebrew/bin/stockfish", "/usr/local/bin/stockfish"} + default: + want = []string{"/usr/games/stockfish", "/usr/bin/stockfish"} + } + for _, w := range want { + if !strings.Contains(locs, w) { + t.Errorf("%s not looked in on %s", w, runtime.GOOS) + } + } +} diff --git a/pkg/events.go b/pkg/events.go new file mode 100644 index 0000000..d5f0364 --- /dev/null +++ b/pkg/events.go @@ -0,0 +1,51 @@ +package pkg + +import ( + "sync" + + "github.com/nate-xyz/chess-cli/api" +) + +// Account events (game starts, challenges) arrive on one stream. StreamConsumer +// is its only reader and fans each event out to whoever has subscribed, so +// screens that wait for a game (the loader) don't race each other for events. +var ( + eventsMu sync.Mutex + eventSubs = map[int]chan api.StreamEventType{} + nextSubID int +) + +// subscribeEvents returns a channel of account events and a function to stop +// receiving them. +func subscribeEvents() (<-chan api.StreamEventType, func()) { + eventsMu.Lock() + defer eventsMu.Unlock() + id := nextSubID + nextSubID++ + ch := make(chan api.StreamEventType, 16) + eventSubs[id] = ch + return ch, func() { + eventsMu.Lock() + defer eventsMu.Unlock() + delete(eventSubs, id) + } +} + +// StreamConsumer reads account events and distributes them to subscribers. +func StreamConsumer(events <-chan api.StreamEventType) { + for e := range events { + Root.App.QueueUpdateDraw(func() { + if name, _ := Root.nav.GetFrontPanel(); name == "lichesswelcome" { + Root.wonline.UpdateTitle("") + } + }) + eventsMu.Lock() + for _, ch := range eventSubs { + select { + case ch <- e: + default: // a slow subscriber shouldn't stall the stream + } + } + eventsMu.Unlock() + } +} diff --git a/pkg/gamestate.go b/pkg/gamestate.go index c91303f..1cd1f33 100644 --- a/pkg/gamestate.go +++ b/pkg/gamestate.go @@ -1,7 +1,12 @@ package pkg import ( - cv "code.rocketnine.space/tslocum/cview" + "context" + "errors" + "net/http" + "sync/atomic" + + cv "codeberg.org/tslocum/cview" "github.com/nate-xyz/chess-cli/api" "github.com/notnil/chess" ) @@ -12,30 +17,45 @@ func (s *State) NewGame() { s.gameState = game } -func (s *State) Login() error { - s.User = new(Login) - err := s.User.Init() - if err != nil { - return err - } - return nil -} - -func (user *Login) Init() error { +// Init logs in (reusing a saved token if it's still valid) and loads the +// account details. showURL is called with the browser login URL, if needed. +func (user *Login) Init(ctx context.Context, showURL func(string)) error { var err error - user.Token, err = api.PerformOAuth() + user.Token, err = api.PerformOAuth(ctx, showURL) if err != nil { return err } err = user.GetLichessUserInfo() - if err != nil { - return err + var apiErr *api.APIError + if errors.As(err, &apiErr) && apiErr.Status == http.StatusUnauthorized { + // the saved token was revoked: log in again + if err := api.ClearToken(); err != nil { + return err + } + if user.Token, err = api.AuthUser(ctx, showURL); err != nil { + return err + } + err = user.GetLichessUserInfo() } - return nil + return err +} + +// frontPanel is the screen showing, readable from any goroutine (background +// tickers use it to stay idle when their screen isn't open). +var frontPanel atomic.Value + +func showing(panel string) bool { + p, _ := frontPanel.Load().(string) + return p == panel } func (s *State) Switch(panel string) { + frontPanel.Store(panel) s.nav.SetCurrentPanel(panel) + if panel == "onlinegame" || panel == "watch" { + applyLayoutPrefs() + } + focusMoveBox(panel) } func (s *State) RefreshAll(p ...cv.Primitive) { diff --git a/pkg/glyphs.go b/pkg/glyphs.go new file mode 100644 index 0000000..7c2d111 --- /dev/null +++ b/pkg/glyphs.go @@ -0,0 +1,179 @@ +package pkg + +import ( + "image" + "image/color" + "math" + "sync" + + tc "github.com/gdamore/tcell/v3" + "github.com/notnil/chess" + "golang.org/x/image/font" + "golang.org/x/image/font/gofont/gobold" + "golang.org/x/image/font/opentype" + "golang.org/x/image/math/fixed" +) + +// Annotation symbols on the board, as Lichess shows them in studies: a +// coloured disc in the top-right corner of the square the move went to, +// with the move's symbol (!, ??, □...) or, failing that, its position or +// idea symbol (±, ⊕, →...). + +// moveGlyph is a symbol, by its NAG number; 0 is none. +type moveGlyph int + +// boardGlyphs are the symbols drawn on the board, move symbols first (the +// order they're preferred in), each with its own image. +var boardGlyphs = []moveGlyph{1, 2, 3, 4, 5, 6, 7, 22, 10, 13, 14, 15, 16, 17, 18, 19, 32, 36, 40, 44, 132, 138, 140, 146} + +// Lichess's colours for move symbols; the others share one colour. +var glyphColors = map[moveGlyph]color.NRGBA{ + 1: {0x22, 0xac, 0x38, 0xff}, // ! good + 2: {0xe6, 0x9d, 0x00, 0xff}, // ? mistake + 3: {0x16, 0x82, 0x26, 0xff}, // !! brilliant + 4: {0xdf, 0x53, 0x53, 0xff}, // ?? blunder + 5: {0xea, 0x45, 0xd8, 0xff}, // !? interesting + 6: {0x56, 0xb4, 0xe9, 0xff}, // ?! dubious +} + +var glyphOther = color.NRGBA{0xa7, 0x08, 0x4e, 0xff} // ⊕, ±, → ... as on Lichess + +func (g moveGlyph) color() color.NRGBA { + if c, ok := glyphColors[g]; ok { + return c + } + return glyphOther +} + +// glyphBasic is the nearest of the 8 standard colours, for basic rendering. +func (g moveGlyph) basic() tc.Color { + switch g { + case 1, 3: + return tc.ColorGreen + case 2: + return tc.ColorOlive + case 4: + return tc.ColorMaroon + case 6: + return tc.ColorNavy + } + return tc.ColorPurple +} + +func (g moveGlyph) text() string { t, _ := nagText(int(g)); return t } + +func (g moveGlyph) tc() tc.Color { + c := g.color() + return tc.NewRGBColor(int32(c.R), int32(c.G), int32(c.B)) +} + +// glyphOf is the symbol to show for a move: its first move symbol, or its +// first other symbol. +func glyphOf(nags []int) moveGlyph { + for _, want := range []bool{true, false} { + for _, n := range nags { + if t, isMove := nagText(n); t != "" && isMove == want && glyphIndex(moveGlyph(n)) >= 0 { + return moveGlyph(n) + } + } + } + return 0 +} + +func glyphIndex(g moveGlyph) int { + for i, x := range boardGlyphs { + if x == g { + return i + } + } + return -1 +} + +// SetGlyph shows a symbol on a square (g = 0 removes it). +func (b *BoardView) SetGlyph(sq chess.Square, g moveGlyph) { + b.mu.Lock() + defer b.mu.Unlock() + b.glyphSq, b.glyph = sq, g +} + +var glyphFont = sync.OnceValue(func() *opentype.Font { + f, _ := opentype.Parse(gobold.TTF) + return f +}) + +// glyphImage draws a symbol's badge: the coloured disc with the symbol in +// white, size pixels square. +func glyphImage(g moveGlyph, size int) *image.RGBA { + img := image.NewRGBA(image.Rect(0, 0, size, size)) + s := float64(size) + c := s / 2 + white := color.NRGBA{0xff, 0xff, 0xff, 0xff} + paint(img, g.color(), 1, 0, 0, s, s, func(x, y float64) float64 { return c - 0.5 - math.Hypot(x-c, y-c) }) + ring := func(x, y float64) float64 { return 0.04*s - math.Abs(math.Hypot(x-c, y-c)-0.26*s) } + switch t := g.text(); t { + case "⊕": // the font has no circled plus or dot: drawn + arm := 0.04 * s + paint(img, white, 1, 0, 0, s, s, func(x, y float64) float64 { + plus := math.Max(math.Min(arm-math.Abs(x-c), 0.26*s-math.Abs(y-c)), math.Min(arm-math.Abs(y-c), 0.26*s-math.Abs(x-c))) + return math.Max(ring(x, y), plus) + }) + case "□": // the font's square is tiny + half, w := 0.19*s, 0.05*s + paint(img, white, 1, 0, 0, s, s, func(x, y float64) float64 { + d := math.Max(math.Abs(x-c), math.Abs(y-c)) + return w/2 - math.Abs(d-(half-w/2)) + }) + case "⨀": + paint(img, white, 1, 0, 0, s, s, func(x, y float64) float64 { + return math.Max(ring(x, y), 0.08*s-math.Hypot(x-c, y-c)) + }) + case "⩲": // nor these: two characters stacked + stackText(img, "+", "=") + case "⩱": + stackText(img, "=", "+") + case "∓": + stackText(img, "−", "+") + case "⇆": + stackText(img, "←", "→") + default: + drawText(img, t, 0.62, c) + } + return img +} + +// drawText draws white text centred horizontally, its ink centred on y. +// size is the font size as a fraction of the badge; wide text (+−, =∞) is +// shrunk to fit inside the disc. +func drawText(img *image.RGBA, text string, size, y float64) { + s := float64(img.Bounds().Dx()) + face, err := opentype.NewFace(glyphFont(), &opentype.FaceOptions{Size: size * s, DPI: 72, Hinting: font.HintingNone}) + if err != nil { + return + } + d := &font.Drawer{Dst: img, Src: image.White, Face: face} + ink, _ := d.BoundString(text) + w := float64(ink.Max.X-ink.Min.X) / 64 + if maxW := 0.6 * s; w > maxW { + face.Close() + face, err = opentype.NewFace(glyphFont(), &opentype.FaceOptions{Size: size * s * maxW / w, DPI: 72, Hinting: font.HintingNone}) + if err != nil { + return + } + d.Face = face + ink, _ = d.BoundString(text) + w = float64(ink.Max.X-ink.Min.X) / 64 + } + defer face.Close() + h := float64(ink.Max.Y-ink.Min.Y) / 64 + x0 := (s-w)/2 - float64(ink.Min.X)/64 + y0 := y - h/2 - float64(ink.Min.Y)/64 + d.Dot = fixed.Point26_6{X: fixed.Int26_6(x0 * 64), Y: fixed.Int26_6(y0 * 64)} + d.DrawString(text) +} + +// stackText draws two characters one above the other. +func stackText(img *image.RGBA, top, bottom string) { + s := float64(img.Bounds().Dx()) + drawText(img, top, 0.46, 0.35*s) + drawText(img, bottom, 0.46, 0.67*s) +} diff --git a/pkg/goto.go b/pkg/goto.go index 2da480e..bb9baff 100644 --- a/pkg/goto.go +++ b/pkg/goto.go @@ -1,6 +1,8 @@ package pkg import ( + "context" + "errors" "fmt" "github.com/nate-xyz/chess-cli/api" @@ -8,13 +10,23 @@ import ( ) func gotoWelcome() { + if loginCancel != nil { + loginCancel() // leaving the Lichess screen abandons a login in progress + } + Root.lgame.stopEngine() + previewPieces("") // first-run setup and Options preview styles; home shows the real setting + resetWelcome() + refreshNews() Root.Switch("welcome") - } func startNewLocalGame() { + Root.lgame.stopEngine() Root.NewGame() + Root.lgame.startClock() + Root.lgame.tickClock() Root.Switch("localgame") + playSound(soundStart) DrawBoard(Root.lgame.Board, Root.gameState.Game.Position().Turn() == chess.White) @@ -22,43 +34,138 @@ func startNewLocalGame() { } func gotoPostLocal() { - Root.gameState.Status += Root.gameState.Game.Outcome().String() - Root.pgame.UpdateResult() - DrawMoveHistory(Root.ponline.History) - DrawBoard(Root.ponline.Board, true) - Root.Switch("postlocal") + game := Root.gameState.Game + gotoPostLocalResult(winnerOf(game.Outcome()), gameMethod(game)) +} + +// gotoPostLocalResult ends a local game with a result (e.g. on time). +func gotoPostLocalResult(winner chess.Color, method string) { + Root.lgame.clock.on = false + clockActive.Store(false) + Root.gameState.Status = resultText(winner, method) + "\n\n" + Root.gameState.Status + g := Root.lgame + white := g.whiteAtBottom() + me := chess.NoColor // two players: any win is a victory + if g.engine != nil { + me = g.engineColor.Other() + } + playSound(resultSound(winner, me)) + g.stopEngine() + Root.pgame.show("postlocal", g.Board, g.OppInfo, g.UserInfo, white, winner, method) } +// Login state; UI goroutine only. +var ( + loginURL string // shown while waiting for the browser login + loginCancel context.CancelFunc // non-nil while a login is in progress +) + +func loggedIn() bool { return Root.User != nil && Root.User.Name != "" } + +// gotoLichess opens the Lichess screen, logging in first if needed. The login +// runs in the background so the UI stays responsive while the browser is open. func gotoLichess() { - err := Root.Login() - if err != nil { - Root.App.QueueUpdate(func() { - Root.wonline.UpdateTitle(fmt.Sprintf("%v", err)) + Root.Switch("lichesswelcome") + if loggedIn() || loginCancel != nil { + Root.wonline.UpdateTitle("") + return + } + Root.wonline.UpdateTitle("\n[yellow]Logging in…[-]") + startLogin(func() { Root.wonline.UpdateTitle("") }, func(err error) { + if err != nil { + Root.wonline.UpdateTitle(fmt.Sprintf("\n[red]Login failed:[-] %v\nGo back and choose Lichess again to retry.", err)) + return + } + Root.wonline.UpdateTitle("") + }) +} + +// startLogin logs in to Lichess in the background (reusing a saved token if +// valid). onURL runs when the browser login link is ready (it's in loginURL); +// done runs when it finishes, unless it was cancelled by leaving the screen. +// Both run on the UI goroutine. +func startLogin(onURL func(), done func(err error)) { + if loginCancel != nil { + return // already in progress + } + ctx, cancel := context.WithCancel(context.Background()) + loginCancel = cancel + go func() { + user := new(Login) + err := user.Init(ctx, func(url string) { + Root.App.QueueUpdateDraw(func() { + loginURL = url + onURL() + }) }) - } else { - Root.RefreshAll() + Root.App.QueueUpdateDraw(func() { + loginCancel, loginURL = nil, "" + cancel() + if err == nil { + Root.User = user + } else if ctx.Err() != nil && !errors.Is(err, api.ErrLoginCancelled) { + return // cancelled by leaving the screen + } + done(err) + }) + }() +} + +// requireLogin wraps a Lichess menu action so it only runs once logged in. +func requireLogin(f func()) func() { + return func() { + if !loggedIn() { + Root.wonline.UpdateTitle("\n[yellow]Finish logging in first.[-]") + return + } + f() } - Root.Switch("lichesswelcome") } func gotoLichessAfterLogin() { Root.Switch("lichesswelcome") + Root.wonline.UpdateTitle("") } + func gotoLichessFromGame() { - killGame <- "GoHome" + Root.ongame.endGame("") } func startNewOnlineGame() { Root.NewGame() + og := Root.ongame + if og.cancel != nil { + og.cancel() + } + og.ctx, og.cancel = context.WithCancel(context.Background()) + og.ended, og.canClaim, og.lowWarned = false, false, false + og.Full, og.State, og.Gone = api.StreamBoardGameFull{}, api.StreamBoardGameState{}, api.StreamOpponentGone{} + og.hidePopup() + og.Chat.Clear() + og.Board.ClearSelection() + og.UserTimer.SetText("") + og.OppTimer.SetText("") + og.UpdateList() Root.Switch("onlinegame") - go Root.ongame.LichessGame(currentGameID) + playSound(soundStart) + go og.LichessGame(currentGameID) } func (online *OnlineGame) gotoPostOnline() { - Root.ponline.UpdateResult() - DrawMoveHistory(Root.ponline.History) - DrawBoard(Root.ponline.Board, true) - Root.Switch("postonline") + winner, method := colorFromName(online.State.Winner), online.State.Status + if method != "aborted" && method != "noStart" { + Root.gameState.Status = resultText(winner, method) + "\n\n" + Root.gameState.Status + } + if method == "aborted" || method == "noStart" { + method = "" // no result marks on the board + } else { + me := chess.Black + if online.IsWhite() { + me = chess.White + } + playSound(resultSound(winner, me)) + } + Root.ponline.show("postonline", online.Board, online.OppInfo, online.UserInfo, online.IsWhite(), winner, method) Root.RefreshAll() } @@ -67,34 +174,40 @@ func gotoChallengeConstruction() { } func gotoLoaderFromChallenge() { - CurrentChallenge = newChallenge + c := newChallenge newChallenge = api.CreateChallengeType{} - Root.Switch("loader") //goto loader - go WaitForLichessGameResponse() //thread to update loading screen and wait for board event + startRequest(c) +} + +// fetchThen runs a Lichess fetch in the background, then show on the UI +// goroutine, reporting errors in the Lichess screen title. +func fetchThen(what string, fetch func() error, show func()) { + Root.wonline.UpdateTitle(fmt.Sprintf("\n[gray]Loading %s…[-]", what)) + go func() { + err := fetch() + Root.App.QueueUpdateDraw(func() { + if err != nil { + Root.wonline.UpdateTitle(fmt.Sprintf("\n[red]%s: %v[-]", what, err)) + return + } + Root.wonline.UpdateTitle("") + show() + }) + }() } func gotoOngoing() { - err := Root.User.GetOngoing() - if err != nil { - Root.wonline.UpdateTitle(fmt.Sprintf("Ongoing Games: %v", err)) - if Root.User.OngoingGames == nil { - return - } - } - Root.ongoing.UpdateList() - Root.Switch("ongoing") + fetchThen("ongoing games", Root.User.GetOngoing, func() { + Root.ongoing.UpdateList() + Root.Switch("ongoing") + }) } func gotoChallenges() { - err := Root.User.GetChallenges() - if err != nil { - Root.wonline.UpdateTitle(fmt.Sprintf("Challenges: %v", err)) - if Root.User.IncomingChallenges == nil && Root.User.OutgoingChallenges == nil { - return - } - } - Root.challenges.UpdateList() - Root.Switch("listchallenge") + fetchThen("challenges", Root.User.GetChallenges, func() { + Root.challenges.UpdateList() + Root.Switch("listchallenge") + }) } func gotoSaved() { diff --git a/pkg/images.go b/pkg/images.go new file mode 100644 index 0000000..b21c0fe --- /dev/null +++ b/pkg/images.go @@ -0,0 +1,332 @@ +package pkg + +import ( + "bytes" + "compress/zlib" + "embed" + "encoding/base64" + "fmt" + "image" + "image/color" + _ "image/png" + "math" + "strings" + "sync" + + tc "github.com/gdamore/tcell/v3" + "github.com/nate-xyz/chess-cli/api" + "github.com/notnil/chess" + xdraw "golang.org/x/image/draw" +) + +// Piece images via kitty's graphics protocol +// (https://sw.kovidgoyal.net/kitty/graphics-protocol/), supported by kitty, +// Ghostty and others. +// +// The board squares are still ordinary cells coloured by tcell; only the +// pieces (and the legal-move markers) are images, placed on top of the +// squares. Each piece is scaled to the square's size in pixels and uploaded +// once; moving a piece just moves a placement, so nothing is re-sent until +// the board changes size or the piece set changes. The piece sets come from +// Lichess (see assets/pieces/README.md for their licences). + +//go:embed assets/pieces/*/*.png +var pieceFiles embed.FS + +// pieceSets are the bundled piece sets, Lichess's default first. +var pieceSets = []string{"cburnett", "merida", "mpchess", "chessnut", "fantasy", "spatial", + "celtic", "kiwen-suwi", "totoy", "papercut", "rhosgfx", "shapes"} + +// boardTheme is a board's square colours (Lichess's flat-colour boards). +type boardTheme struct { + name string + light, dark tc.Color +} + +var boardThemes = []boardTheme{ + {"brown", tc.NewRGBColor(0xf0, 0xd9, 0xb5), tc.NewRGBColor(0xb5, 0x88, 0x63)}, + {"blue", tc.NewRGBColor(0xde, 0xe3, 0xe6), tc.NewRGBColor(0x8c, 0xa2, 0xad)}, + {"green", tc.NewRGBColor(0xff, 0xff, 0xdd), tc.NewRGBColor(0x86, 0xa6, 0x66)}, + {"purple", tc.NewRGBColor(0x9f, 0x90, 0xb0), tc.NewRGBColor(0x7d, 0x4a, 0x8d)}, + {"ic", tc.NewRGBColor(0xec, 0xec, 0xec), tc.NewRGBColor(0xc1, 0xc1, 0x8e)}, + {"grey", tc.NewRGBColor(0xdc, 0xdc, 0xdc), tc.NewRGBColor(0xab, 0xab, 0xab)}, +} + +// currentPieceSet and currentBoard are the chosen piece set and board. +func currentPieceSet() string { + for _, s := range pieceSets { + if s == api.UserInfo.PieceSet { + return s + } + } + return pieceSets[0] +} + +func currentBoard() boardTheme { + for _, t := range boardThemes { + if t.name == api.UserInfo.Board { + return t + } + } + return boardThemes[0] +} + +// Image ids: 1-12 the pieces, then the move dot and the capture ring. Offset +// so they're unlikely to clash with anything else using the protocol. +const ( + imgBase = 0x5c4e00 + imgDot = imgBase + 13 + imgRing = imgBase + 14 + imgOverlay = imgBase + 15 // drawn circles and arrows + imgBadges = imgBase + 16 // result badges: +0 win, +1 mate, +2 loss, +3 draw + imgGlyphs = imgBase + 20 // annotation symbols, in boardGlyphs order + imgCheck = imgBase + 44 // the red glow behind a king in check + imgCount = 44 + + zMarker = 1 // z-indexes: above the cell text, pieces over markers, + zPiece = 2 // shapes over pieces + zShapes = 3 + zBadge = 4 +) + +func imgBadge(k badge) int { return imgBadges + int(k) - int(badgeWin) } + +func imgGlyph(g moveGlyph) int { return imgGlyphs + glyphIndex(g) } + +// badgeSizeFor is a result badge's size for a piece size. +func badgeSizeFor(pieceSize int) int { return max(8, pieceSize*2/5) } + +func pieceImageID(p chess.Piece) int { + return imgBase + int(p) // chess.Piece: WhiteKing = 1 ... BlackPawn = 12 +} + +// imgPlacement is one image placed at cell (x, y), offset (px, py) pixels +// into that cell. +type imgPlacement struct { + x, y, px, py int + img, z int +} + +type imageLayer struct { + sync.Mutex + frame []imgPlacement // collected by board Draw calls this frame + frameSize int // square size in pixels the frame's boards want + frameSet string // piece set the frame's boards want + + overlay *image.RGBA // the frame's drawn shapes, if any + overlayKey string // identifies the overlay's content + sentOverlay string // key of the overlay on the terminal + + prev []imgPlacement // placements on the terminal now + uploaded int // size in pixels of the uploaded images (0 = none) + uploadedSet string // and their piece set + prevW int + prevH int + + sources map[chess.Piece]image.Image + sourcesSet string +} + +var imgLayer imageLayer + +// cellPixels is the size of one terminal cell in pixels, if known. +func cellPixels(screen tc.Screen) (w, h int, ok bool) { + tty, ok := screen.Tty() + if !ok { + return 0, 0, false + } + ws, err := tty.WindowSize() + if err != nil { + return 0, 0, false + } + w, h = ws.CellDimensions() + return w, h, w > 0 && h > 0 +} + +// queueImages records image placements for this frame. Called from Draw. +func queueImages(size int, set string, ps []imgPlacement) { + imgLayer.Lock() + defer imgLayer.Unlock() + imgLayer.frameSize, imgLayer.frameSet = size, set + imgLayer.frame = append(imgLayer.frame, ps...) +} + +// queueOverlay records the board's drawn shapes for this frame. +func queueOverlay(img *image.RGBA, key string) { + imgLayer.Lock() + defer imgLayer.Unlock() + imgLayer.overlay, imgLayer.overlayKey = img, key +} + +// flushImages runs after each frame (after tcell has drawn): uploads the +// images if the size changed and updates the placements that changed. +func flushImages(screen tc.Screen) { + tty, ok := screen.Tty() + if !ok { + return + } + w, h := screen.Size() + imgLayer.Lock() + out := imgLayer.commands(w, h) + imgLayer.Unlock() + if out != "" { + _, _ = tty.Write([]byte(out)) + } +} + +// commands works out the escape codes to bring the terminal's images up to +// date with this frame (for a w x h screen), and takes the frame. Locked. +func (il *imageLayer) commands(w, h int) string { + frame, size, set := il.frame, il.frameSize, il.frameSet + overlay, overlayKey := il.overlay, il.overlayKey + il.frame, il.overlay, il.overlayKey = nil, nil, "" + if len(frame) == 0 && len(il.prev) == 0 { + return "" + } + + var b strings.Builder + b.WriteString("\x1b7") + if w != il.prevW || h != il.prevH { + // after a resize tcell has cleared and redrawn the screen: start over + deletePlacements(&b, il.prev, 0) + il.prev = nil + il.prevW, il.prevH = w, h + } + if len(frame) > 0 && (size != il.uploaded || set != il.uploadedSet) { + for id := imgBase + 1; id <= imgBase+imgCount; id++ { + fmt.Fprintf(&b, "\x1b_Ga=d,d=I,i=%d,q=2\x1b\\", id) // placements and data + } + il.prev = nil + il.uploadImages(&b, size, set) + il.uploaded, il.uploadedSet = size, set + il.sentOverlay = "" + } + if overlay != nil && overlayKey != il.sentOverlay { + // replace the shapes image; its placement has to be made again + fmt.Fprintf(&b, "\x1b_Ga=d,d=I,i=%d,q=2\x1b\\", imgOverlay) + transmit(&b, imgOverlay, overlay) + il.sentOverlay = overlayKey + for i := range il.prev { + if il.prev[i].img == imgOverlay { + il.prev[i].z = -1 // never equal: placed again below + } + } + } + for i, p := range frame { + if i < len(il.prev) { + if il.prev[i] == p { + continue + } + if il.prev[i].img != p.img { // placement ids are per image + deletePlacements(&b, il.prev[i:i+1], i) + } + } + fmt.Fprintf(&b, "\x1b[%d;%dH\x1b_Ga=p,i=%d,p=%d,X=%d,Y=%d,z=%d,C=1,q=2\x1b\\", + p.y+1, p.x+1, p.img, i+1, p.px, p.py, p.z) + } + if len(il.prev) > len(frame) { + deletePlacements(&b, il.prev[len(frame):], len(frame)) + } + il.prev = frame + b.WriteString("\x1b8") + return b.String() +} + +// deletePlacements removes placements, the first of which has id first+1. +func deletePlacements(b *strings.Builder, ps []imgPlacement, first int) { + for i, p := range ps { + fmt.Fprintf(b, "\x1b_Ga=d,d=i,i=%d,p=%d,q=2\x1b\\", p.img, first+i+1) + } +} + +// uploadImages sends all the images at size x size pixels, as zlib-compressed +// RGBA in chunks (the protocol's limit is 4096 bytes of base64 per chunk). +func (il *imageLayer) uploadImages(b *strings.Builder, size int, set string) { + if il.sources == nil || il.sourcesSet != set { + il.sources, il.sourcesSet = loadPieceSet(set), set + } + for p := chess.WhiteKing; p <= chess.BlackPawn; p++ { + if src, ok := il.sources[p]; ok { + dst := image.NewRGBA(image.Rect(0, 0, size, size)) + xdraw.CatmullRom.Scale(dst, dst.Bounds(), src, src.Bounds(), xdraw.Over, nil) + transmit(b, pieceImageID(p), dst) + } + } + transmit(b, imgDot, markerImage(size, false)) + transmit(b, imgRing, markerImage(size, true)) + for k := badgeWin; k <= badgeDraw; k++ { + transmit(b, imgBadge(k), badgeImage(k, badgeSizeFor(size))) + } + for _, g := range boardGlyphs { + transmit(b, imgGlyph(g), glyphImage(g, badgeSizeFor(size))) + } + transmit(b, imgCheck, checkGlowImage(size)) +} + +// loadPieceSet decodes a piece set's embedded images. +func loadPieceSet(set string) map[chess.Piece]image.Image { + sources := map[chess.Piece]image.Image{} + for p := chess.WhiteKing; p <= chess.BlackPawn; p++ { + name := "assets/pieces/" + set + "/" + "wb"[p.Color()-1:p.Color()] + strings.ToUpper(p.Type().String()) + ".png" + f, err := pieceFiles.Open(name) + if err != nil { + continue + } + if img, _, err := image.Decode(f); err == nil { + sources[p] = img + } + f.Close() + } + return sources +} + +// colMoveDest is Lichess's legal-move marker colour. +var colMoveDest = color.NRGBA{20, 85, 30, 128} + +// markerImage draws Lichess's legal-move markers: a dot for an empty square, +// or for a capture a tint in the corners around a circle. +func markerImage(size int, ring bool) *image.RGBA { + img := image.NewRGBA(image.Rect(0, 0, size, size)) + c := float64(size) / 2 + for y := 0; y < size; y++ { + for x := 0; x < size; x++ { + d := math.Hypot(float64(x)+0.5-c, float64(y)+0.5-c) + var cover float64 // fraction of the pixel covered, for smooth edges + if ring { + cover = d - 0.56*float64(size) + 0.5 + } else { + cover = 0.17*float64(size) - d + 0.5 + } + cover = math.Max(0, math.Min(1, cover)) + if cover > 0 { + col := colMoveDest + col.A = uint8(float64(col.A) * cover) + img.Set(x, y, col) + } + } + } + return img +} + +// transmit uploads an image (a=t: store without showing) under an id. +func transmit(b *strings.Builder, id int, img *image.RGBA) { + var z bytes.Buffer + w := zlib.NewWriter(&z) + _, _ = w.Write(img.Pix) + _ = w.Close() + data := base64.StdEncoding.EncodeToString(z.Bytes()) + sz := img.Bounds().Size() + for first := true; first || len(data) > 0; first = false { + chunk := data[:min(4096, len(data))] + data = data[len(chunk):] + more := 0 + if len(data) > 0 { + more = 1 + } + if first { + fmt.Fprintf(b, "\x1b_Ga=t,f=32,o=z,i=%d,s=%d,v=%d,q=2,m=%d;%s\x1b\\", id, sz.X, sz.Y, more, chunk) + } else { + fmt.Fprintf(b, "\x1b_Gm=%d;%s\x1b\\", more, chunk) + } + } +} diff --git a/pkg/images_test.go b/pkg/images_test.go new file mode 100644 index 0000000..2e9a2a0 --- /dev/null +++ b/pkg/images_test.go @@ -0,0 +1,78 @@ +package pkg + +import ( + "strings" + "testing" + + "github.com/notnil/chess" +) + +// The image layer uploads pieces once per size and set, then only sends the +// placements that changed. +func TestImageLayerCommands(t *testing.T) { + var il imageLayer + place := func(ps ...imgPlacement) string { + il.frame, il.frameSize, il.frameSet = ps, 40, "cburnett" + return il.commands(100, 50) + } + wk := imgPlacement{x: 10, y: 5, img: pieceImageID(chess.WhiteKing), z: zPiece} + bk := imgPlacement{x: 20, y: 5, img: pieceImageID(chess.BlackKing), z: zPiece} + + first := place(wk, bk) + if !strings.Contains(first, "a=t,f=32,o=z") { + t.Error("first frame didn't upload the pieces") + } + if strings.Count(first, "a=p,") != 2 { + t.Errorf("first frame placements: %d", strings.Count(first, "a=p,")) + } + if !strings.HasPrefix(first, "\x1b7") || !strings.HasSuffix(first, "\x1b8") { + t.Error("cursor not saved/restored around the images") + } + + // same frame again: nothing to send + if out := place(wk, bk); strings.Contains(out, "a=p,") || strings.Contains(out, "a=t,") { + t.Errorf("unchanged frame sent %q", out) + } + + // one piece moves: one placement, no upload + moved := wk + moved.x = 11 + out := place(moved, bk) + if strings.Count(out, "a=p,") != 1 || strings.Contains(out, "a=t,") { + t.Errorf("one move sent %q", out) + } + + // a piece disappears: its placement is deleted + out = place(moved) + if !strings.Contains(out, "a=d,d=i,i=") || strings.Contains(out, "a=p,") { + t.Errorf("removal sent %q", out) + } + + // a different image at the same placement index: old one deleted first + out = place(imgPlacement{x: 11, y: 5, img: pieceImageID(chess.WhiteQueen), z: zPiece}) + if !strings.Contains(out, "a=d,d=i,") || strings.Count(out, "a=p,") != 1 { + t.Errorf("image swap sent %q", out) + } + + // new piece set: everything uploaded again + il.frame, il.frameSize, il.frameSet = []imgPlacement{wk}, 40, "merida" + if out := il.commands(100, 50); !strings.Contains(out, "a=t,") { + t.Error("piece set change didn't re-upload") + } + + // board gone: all placements removed, then nothing more + if out := place(); !strings.Contains(out, "a=d,d=i,") { + t.Errorf("leaving the board sent %q", out) + } + if out := place(); out != "" { + t.Errorf("idle sent %q", out) + } +} + +func TestPieceImagesExist(t *testing.T) { + for _, set := range pieceSets { + if n := len(loadPieceSet(set)); n != 12 { + t.Errorf("piece set %s: %d of 12 pieces", set, n) + } + } +} diff --git a/pkg/instance_other.go b/pkg/instance_other.go new file mode 100644 index 0000000..57fc4ad --- /dev/null +++ b/pkg/instance_other.go @@ -0,0 +1,11 @@ +//go:build !unix + +package pkg + +import "errors" + +// ErrAlreadyRunning means another chess-cli is running for this user. +var ErrAlreadyRunning = errors.New("chess-cli is already running") + +// LockInstance: not enforced on this platform yet. +func LockInstance(dir string) error { return nil } diff --git a/pkg/instance_unix.go b/pkg/instance_unix.go new file mode 100644 index 0000000..58054d5 --- /dev/null +++ b/pkg/instance_unix.go @@ -0,0 +1,49 @@ +//go:build unix + +package pkg + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + + "golang.org/x/sys/unix" +) + +// ErrAlreadyRunning means another chess-cli is running for this user. +var ErrAlreadyRunning = errors.New("chess-cli is already running") + +var instanceLock *os.File // held open (and locked) for the life of the process + +// LockInstance makes sure only one chess-cli runs at a time: two would both +// follow the Lichess event stream and write the same config and saved games. +// It takes an exclusive lock on a file in dir; the system releases it when +// the process exits, even after a crash, so it can't go stale. +func LockInstance(dir string) error { + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + f, err := os.OpenFile(filepath.Join(dir, "chess-cli.lock"), os.O_RDWR|os.O_CREATE, 0o600) + if err != nil { + return err + } + if err := unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { + defer f.Close() + if errors.Is(err, unix.EWOULDBLOCK) { + b := make([]byte, 32) + n, _ := f.ReadAt(b, 0) + if pid, err := strconv.Atoi(strings.TrimSpace(string(b[:n]))); err == nil && pid > 0 { + return fmt.Errorf("%w (process %d, in another terminal)", ErrAlreadyRunning, pid) + } + return ErrAlreadyRunning + } + return err + } + _ = f.Truncate(0) + _, _ = f.WriteAt([]byte(strconv.Itoa(os.Getpid())+"\n"), 0) + instanceLock = f + return nil +} diff --git a/pkg/instance_unix_test.go b/pkg/instance_unix_test.go new file mode 100644 index 0000000..fad416c --- /dev/null +++ b/pkg/instance_unix_test.go @@ -0,0 +1,39 @@ +//go:build unix + +package pkg + +import ( + "errors" + "os" + "os/exec" + "testing" +) + +// The lock is per process, so the second instance is a child process. +func TestLockInstance(t *testing.T) { + if dir := os.Getenv("LOCK_TEST_DIR"); dir != "" { // the child + if err := LockInstance(dir); errors.Is(err, ErrAlreadyRunning) { + os.Exit(3) + } + os.Exit(0) + } + dir := t.TempDir() + if err := LockInstance(dir); err != nil { + t.Fatal(err) + } + defer func() { instanceLock.Close(); instanceLock = nil }() + cmd := exec.Command(os.Args[0], "-test.run=TestLockInstance") + cmd.Env = append(os.Environ(), "LOCK_TEST_DIR="+dir) + err := cmd.Run() + var exit *exec.ExitError + if !errors.As(err, &exit) || exit.ExitCode() != 3 { + t.Fatalf("second instance wasn't refused: %v", err) + } + instanceLock.Close() // first instance exits: the lock is free again + instanceLock = nil + cmd = exec.Command(os.Args[0], "-test.run=TestLockInstance") + cmd.Env = append(os.Environ(), "LOCK_TEST_DIR="+dir) + if err := cmd.Run(); err != nil { + t.Fatalf("lock not released: %v", err) + } +} diff --git a/pkg/keyprefs.go b/pkg/keyprefs.go new file mode 100644 index 0000000..655c6a0 --- /dev/null +++ b/pkg/keyprefs.go @@ -0,0 +1,82 @@ +package pkg + +import ( + "strings" + + cv "codeberg.org/tslocum/cview" + "github.com/nate-xyz/chess-cli/api" +) + +// Moving around with the arrow keys, or also with vim's hjkl (on the board +// and in lists, where g and G go to the first and last item too). Chosen at +// first run and in Options; on unless turned off. + +func vimKeys() bool { return !api.UserInfo.NoVimKeys } + +func setVimKeys(on bool) { + _ = api.UpdateConfig(func(c *api.UserConfig) { c.NoVimKeys, c.KeysAsked = !on, true }) + applyKeyPrefs() +} + +// keyRibbons are the hint ribbons that mention the movement keys; their +// text has "arrows/hjkl", shown as "arrows" when hjkl is off. +var keyRibbons = map[*cv.TextView]string{} + +// applyKeyPrefs sets the lists' keys and the ribbons for the setting. +func applyKeyPrefs() { + if vimKeys() { + cv.Keys.MoveUp2, cv.Keys.MoveDown2 = []string{"k"}, []string{"j"} + cv.Keys.MoveLeft2, cv.Keys.MoveRight2 = []string{"h"}, []string{"l"} + cv.Keys.MoveFirst2, cv.Keys.MoveLast2 = []string{"g"}, []string{"G"} + } else { + cv.Keys.MoveUp2, cv.Keys.MoveDown2, cv.Keys.MoveLeft2, cv.Keys.MoveRight2 = nil, nil, nil, nil + cv.Keys.MoveFirst2, cv.Keys.MoveLast2 = nil, nil + } + for tv, text := range keyRibbons { + tv.SetText(keysText(text)) + } +} + +func keysText(text string) string { + if vimKeys() { + return text + } + return strings.ReplaceAll(text, "arrows/hjkl", "arrows") +} + +// boardKeys are the keys a playable board uses itself. +func boardKeys() string { + if vimKeys() { + return "hjkl[] " + } + return "[] " +} + +// onboardKeys asks arrows or arrows and hjkl. +func onboardKeys(list *cv.List, info *cv.TextView, next func()) { + list.SetChangedFunc(nil) + list.Clear() + for i, c := range []struct { + text, explain string + vim bool + }{ + {"Arrow keys and hjkl [green](recommended)[-]", " hjkl move too, like vim (g and G in lists)", true}, + {"Arrow keys only", " h, j, k and l are just letters", false}, + } { + c := c + item := cv.NewListItem(c.text) + item.SetShortcut(numberKey(i)) + item.SetSecondaryText(c.explain) + item.SetSelectedFunc(func() { + setVimKeys(c.vim) + next() + }) + list.AddItem(item) + } + list.SetCurrentItem(0) + info.SetText("[::b]Moving around[::-]\n\nThe arrow keys move the cursor on the board and through menus. " + + "chess-cli can also take [::b]h j k l[::-] (left, down, up, right), as in vim and many terminal programs.\n\n" + + "Menu letters work either way; on the board you can always click, or type a move with Ctrl-K.\n\n" + + "[#a0a0a0]This can be changed in Options.[-]") + Root.App.SetFocus(list) +} diff --git a/pkg/layout.go b/pkg/layout.go new file mode 100644 index 0000000..8642737 --- /dev/null +++ b/pkg/layout.go @@ -0,0 +1,593 @@ +package pkg + +import ( + "sync/atomic" + + cv "codeberg.org/tslocum/cview" + tc "github.com/gdamore/tcell/v3" + "github.com/nate-xyz/chess-cli/api" + "github.com/notnil/chess" +) + +// Game screen layout. Normally a sidebar on the left (players, clocks, +// moves, menu) and the board as big as the height allows on the right, with +// the shortcut ribbon along the bottom: +// +// ┌──────────────┬───────────────────────┐ +// │ opponent │ │ +// │ status │ │ +// │ moves │ board │ +// │ menu │ │ +// │ you │ │ +// ├──────────────┴───────────────────────┤ +// │ ribbon: shortcuts │ +// └──────────────────────────────────────┘ +// +// It adapts to the terminal (layoutFor): +// - wide: the sidebar stops growing at maxSidebar and the two are centred +// together, so a fullscreen terminal has no gulf in the middle; +// - narrow but tall: the board on top, centred, the sidebar below; +// - small: just the board, as big as possible (with the clock bars, if +// on). Whatever has the keyboard in the sidebar (the move box after +// Ctrl-K, the menu after Tab, the chat box) shows in a strip under the +// board, so the board is always in view; Esc goes back. + +const ( + minSidebar = 30 // columns kept for the sidebar + maxSidebar = 60 // the sidebar grows no wider; more room goes to margins + minSideRows = 12 // rows kept for the sidebar under a stacked board + boardMargin = 2 // columns between the board and the right edge (~ one row's height) + goodSquare = 3 // square rows that are big enough: keep the sidebar beside +) + +type layoutMode int + +const ( + layoutSide layoutMode = iota // sidebar beside the board + layoutStacked // board on top, sidebar below + layoutBoard // board only (sidebar on demand) +) + +// layoutFor picks the layout giving the biggest board, preferring the +// sidebar beside it, then below it, on a tie or once squares are big enough. +// sq reports the square size for a board area w x h. +func layoutFor(w, h int, sq func(w, h int) int) layoutMode { + side := sq(w-minSidebar-boardMargin, h) + if side >= goodSquare { + return layoutSide + } + stacked := 0 + if h > minSideRows { + stacked = sq(w, h-minSideRows) + } + alone := sq(w, h) + switch { + case side >= stacked && side >= alone: + return layoutSide + case stacked >= alone: + return layoutStacked + } + return layoutBoard +} + +// boardLayout arranges a sidebar and a board (see above) each time it's +// drawn. +type boardLayout struct { + *cv.Flex + side *cv.Flex + board *BoardView + left *cv.Box // margins when the terminal is wide + right *cv.Box + mode layoutMode + shape [5]int // what the items were last set to + strip cv.Primitive // small layout: the sidebar item with the keyboard, under the board + strips []cv.Primitive // strips added to the Flex, to take out again +} + +// stripHeight is how many rows a sidebar item needs in the small layout's +// strip. +func stripHeight(p cv.Primitive) int { + if l, ok := p.(*cv.List); ok { + return max(1, min(8, l.GetItemCount())) + } + return 1 // the move box, chat input +} + +func (l *boardLayout) Draw(screen tc.Screen) { + _, _, w, h := l.GetRect() + sq := func(w, h int) int { s, _, _ := l.board.fit(screen, w, h); return s } + l.mode = layoutFor(w, h, sq) + var shape [5]int + shape[0] = int(l.mode) + switch l.mode { + case layoutSide: + _, bw, _ := l.board.fit(screen, w-minSidebar-boardMargin, h) + bw += boardMargin + sw := min(w-bw, maxSidebar) + extra := max(0, w-bw-sw) + shape[1], shape[2], shape[3], shape[4] = extra/2, sw, bw, extra-extra/2 + case layoutStacked: + _, _, bh := l.board.fit(screen, w, h-minSideRows) + shape[1] = bh + case layoutBoard: + var strip cv.Primitive + if l.side.HasFocus() { // Tab or Ctrl-K: that part of the sidebar under the board + strip = Root.App.GetFocus() + shape[1] = stripHeight(strip) + } + if strip != l.strip { + l.strip, l.shape = strip, [5]int{-1} + } + } + if shape != l.shape { + l.shape = shape + l.arrange(shape) + } + l.Flex.Draw(screen) +} + +// arrange sets the Flex's items for a layout. +func (l *boardLayout) arrange(shape [5]int) { + for _, p := range []cv.Primitive{l.left, l.side, l.board, l.right} { + l.RemoveItem(p) + } + for _, p := range l.strips { + l.RemoveItem(p) + } + l.strips = nil + l.board.mu.Lock() + l.board.right = layoutMode(shape[0]) == layoutSide + l.board.mu.Unlock() + switch layoutMode(shape[0]) { + case layoutSide: + l.SetDirection(cv.FlexColumn) + l.AddItem(l.left, shape[1], 0, false) + l.AddItem(l.side, shape[2], 0, false) + l.AddItem(l.board, shape[3], 0, true) + l.AddItem(l.right, shape[4], 0, false) + case layoutStacked: + l.SetDirection(cv.FlexRow) + l.AddItem(l.board, shape[1], 0, true) + l.AddItem(l.side, 0, 1, false) + case layoutBoard: + l.SetDirection(cv.FlexRow) + l.AddItem(l.board, 0, 1, true) + if shape[1] > 0 && l.strip != nil { + l.AddItem(l.strip, shape[1], 0, false) + l.strips = append(l.strips, l.strip) + } + } +} + +// layoutOf finds a game screen's layout from its board. +var layoutOf = map[*BoardView]*boardLayout{} + +// newGameLayout builds a game screen around a board and its sidebar. The +// board starts with keyboard focus. +func newGameLayout(board *BoardView, side *cv.Flex, ribbon string) *cv.Flex { + board.right = true + side.SetPadding(1, 0, 2, 2) // breathing room from the left edge and the board + body := &boardLayout{Flex: cv.NewFlex(), side: side, board: board, left: cv.NewBox(), right: cv.NewBox(), shape: [5]int{-1}} + body.AddItem(side, 0, 1, false) + body.AddItem(board, 0, 0, true) + layoutOf[board] = body + + root := cv.NewFlex() + root.SetDirection(cv.FlexRow) + root.AddItem(body, 0, 1, true) + root.AddItem(ribbonPrimitive(ribbon, board), 1, 0, false) + return root +} + +// moveBox is the typed-move field: hidden until Ctrl-K, closed again by Esc +// or after a move is entered. +type moveBox struct { + side *cv.Flex + input *cv.InputField + board *BoardView +} + +func newMoveBox(side *cv.Flex, board *BoardView, submit func(text string)) *moveBox { + m := &moveBox{side: side, board: board, input: cv.NewInputField()} + m.input.SetLabel("Move: ") + m.input.SetPlaceholder("e4, Nf3, e7e8=Q…") + m.input.SetDoneFunc(func(key tc.Key) { + text := m.input.GetText() + m.input.SetText("") + if key == tc.KeyEnter && moveBoxAlways() { + // always-on: stay in the box for the next move + } else { + m.hide() + } + if key == tc.KeyEnter && text != "" { + submit(text) + } + }) + moveBoxes = append(moveBoxes, m) + return m +} + +// moveBoxes are all the screens' move boxes, for the always-on setting. +var moveBoxes []*moveBox + +// moveBoxAlways reports whether the move box is always shown (Options), +// rather than opened with Ctrl-K. +func moveBoxAlways() bool { return api.UserInfo.MoveBoxAlways } + +// setMoveBoxAlways changes the setting and shows or hides the boxes. +func setMoveBoxAlways(on bool) { + _ = api.UpdateConfig(func(c *api.UserConfig) { c.MoveBoxAlways = on }) + size := 0 + if on { + size = 1 + } + for _, m := range moveBoxes { + m.side.ResizeItem(m.input, size, 0) + } +} + +// focusMoveBox puts the keyboard in the move box of a game screen being +// opened, when the box is always on. Returns false if it isn't. +func focusMoveBox(panel string) bool { + if !moveBoxAlways() { + return false + } + var m *moveBox + switch panel { + case "localgame": + m = Root.lgame.Move + case "onlinegame": + m = Root.ongame.Move + case "puzzle": + m = Root.puzzle.Move + } + if m == nil { + return false + } + m.show() + return true +} + +func (m *moveBox) show() { + m.side.ResizeItem(m.input, 1, 0) + Root.App.SetFocus(m.input) +} + +// hide closes the box (it stays visible when always on) and gives the +// keyboard back to the board. +func (m *moveBox) hide() { + if !moveBoxAlways() { + m.side.ResizeItem(m.input, 0, 0) + } + Root.App.SetFocus(m.board) +} + +// isCtrlK matches Ctrl-K however the terminal reports it (as a control code, +// or as "k" with the Ctrl modifier under the kitty keyboard protocol). +func isCtrlK(ev *tc.EventKey) bool { + return ev.Key() == tc.KeyCtrlK || + (ev.Key() == tc.KeyRune && (ev.Str() == "k" || ev.Str() == "K") && ev.Modifiers()&tc.ModCtrl != 0) +} + +// globalKeys is the application's key capture (cview sends keys straight to +// the focused widget, so screen-wide shortcuts live here): Ctrl-K opens the +// move box on game screens, Esc leaves the Options screen. +func globalKeys(ev *tc.EventKey) *tc.EventKey { + switch name, _ := Root.nav.GetFrontPanel(); name { + case "localgame": + if isCtrlK(ev) { + Root.lgame.Move.show() + return nil + } + case "onlinegame": + if isCtrlK(ev) { + Root.ongame.Move.show() + return nil + } + case "puzzle": + if isCtrlK(ev) { + Root.puzzle.Move.show() + return nil + } + case "watch": + if ev.Key() == tc.KeyRune && ev.Str() == "f" { + Root.watch.flip() + return nil + } + case "study": + if ev.Key() == tc.KeyRune && ev.Str() == "f" { + Root.study.flip() + return nil + } + case "options": + if ev.Key() == tc.KeyEscape { + optionsBack() + return nil + } + } + return menuKeys(ev) +} + +// textBox is a read-only text view for the sidebar. +func textBox(align int) *cv.TextView { + tv := cv.NewTextView() + tv.SetDynamicColors(true) + tv.SetWordWrap(true) + tv.SetTextAlign(align) + tv.SetScrollBarVisibility(cv.ScrollBarNever) // a bar beside the board looks like an eval bar + return tv +} + +// Menus highlight the item under the mouse pointer. cview's List only moves +// its selection on hover; the selection is hidden while the list isn't +// focused, so it's shown while the pointer is over the list. +var hoverLists []*hoverList + +type hoverList struct { + *cv.List + over bool // pointer is over the list + onLeave func() // when the pointer leaves the list +} + +// onHoverLeave runs f when the pointer leaves the menu l (made by menuList). +// Hovering moves a list's selection; f can put it back. +func onHoverLeave(l *cv.List, f func()) { + for _, h := range hoverLists { + if h.List == l { + h.onLeave = f + } + } +} + +// menuList makes a compact list (no secondary text) that highlights on hover. +func menuList() *cv.List { + l := cv.NewList() + l.ShowSecondaryText(false) + l.SetHover(true) + l.SetWrapAround(true) + l.SetSelectedFocusOnly(true) + hoverLists = append(hoverLists, &hoverList{List: l}) + return l +} + +// trackHover is the application's mouse capture: it shows a menu's +// highlight while the pointer is over it. +func trackHover(ev *tc.EventMouse, action cv.MouseAction) (*tc.EventMouse, cv.MouseAction) { + if ev == nil { + return ev, action + } + x, y := ev.Position() + changed := false + for _, l := range hoverLists { + if over := l.InRect(x, y); over != l.over { + l.over = over + l.SetSelectedFocusOnly(!over) + changed = true + if !over && l.onLeave != nil && Root.App.GetFocus() != l.List { + l.onLeave() + } + } + } + if changed { + go Root.App.QueueUpdateDraw(func() {}) + } + return ev, action +} + +// postGame is a game-over screen in the game layout: the final board on the +// right (step back through it as usual); the players, the result, the moves +// and a menu in the sidebar. The menu has the focus; Tab goes to the board. +type postGame struct { + Board *BoardView + Top *cv.TextView // the player at the top of the board + Result *cv.TextView + History *cv.TextView + List *cv.List + Bottom *cv.TextView + + analysis *analysisPanel + positions []*chess.Position // the game that ended, for the analysis + moves []*chess.Move +} + +func newPostGame(items []*cv.ListItem, ribbon string) (*postGame, cv.Primitive) { + p := &postGame{ + Board: NewBoardView(nil), + Top: textBox(cv.AlignLeft), + Result: textBox(cv.AlignLeft), + History: textBox(cv.AlignLeft), + List: menuList(), + Bottom: textBox(cv.AlignLeft), + } + items = append([]*cv.ListItem{menuItem("Computer analysis", 'a', func() { + p.analysis.start(p.positions, p.moves, func(msg string) { p.Result.SetText(p.Result.GetText(false) + "\n" + msg) }) + })}, items...) + for _, item := range items { + p.List.AddItem(item) + } + linkMoveList(p.History, p.Board) + side := cv.NewFlex() + side.SetDirection(cv.FlexRow) + p.analysis = newAnalysisPanel(side, p.History, p.Board) + p.Board.mu.Lock() + linked := p.Board.onShown + p.Board.onShown = func(ply int) { linked(ply); p.analysis.shown(ply) } + p.Board.mu.Unlock() + side.AddItem(p.Top, 2, 0, false) + side.AddItem(p.Result, 0, 1, false) + side.AddItem(p.analysis.graph, 0, 0, false) + side.AddItem(p.analysis.table, 0, 0, false) + side.AddItem(p.analysis.note, 0, 0, false) + side.AddItem(p.History, 0, 2, false) + side.AddItem(p.List, len(items)+1, 0, true) + side.AddItem(p.Bottom, 2, 0, false) + + p.Board.SetTabFunc(func() { Root.App.SetFocus(p.List) }) + p.List.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { + if event.Key() == tc.KeyTab { + Root.App.SetFocus(p.Board) + return nil + } + return event + }) + return p, newGameLayout(p.Board, side, ribbon) +} + +// menuItem is a menu entry: text, shortcut key and what it does. +func menuItem(text string, key rune, f func()) *cv.ListItem { + item := cv.NewListItem(text) + item.SetShortcut(key) + item.SetSelectedFunc(f) + return item +} + +// show fills the screen from the game that just ended (Root.gameState, its +// board and player boxes) and switches to it. +func (p *postGame) show(panel string, from *BoardView, top, bottom *cv.TextView, white bool, winner chess.Color, method string) { + p.Top.SetText(top.GetText(false)) + p.Bottom.SetText(bottom.GetText(false)) + p.Result.SetText(Root.gameState.Status) + Root.gameState.Status = "" + p.analysis.reset() + p.positions = append([]*chess.Position(nil), Root.gameState.Game.Positions()...) + p.moves = append([]*chess.Move(nil), Root.gameState.Game.Moves()...) + DrawMoveHistory(p.History) + DrawBoard(p.Board, white) + p.Board.copyClockBars(from) + if method != "" { + p.Board.SetResult(winner, method) + } + Root.Switch(panel) + Root.App.SetFocus(p.List) +} + +// copyClockBars shows another board's clocks, stopped: the final times. +func (b *BoardView) copyClockBars(from *BoardView) { + from.mu.Lock() + top, bottom := from.topBar, from.bottomBar + from.mu.Unlock() + top.active, bottom.active = false, false + b.SetClockBars(top, bottom) +} + +// Sidebar boxes: a thin muted-grey frame with a title, a little brighter +// while focused. +var ( + colBoxBorder = tc.PaletteColor(240) + colBoxFocused = tc.PaletteColor(246) + colBoxTitle = tc.PaletteColor(246) +) + +// boxed frames a sidebar box and returns a function to change its title. +// The title is drawn here rather than by cview, whose title ends in a reset +// that some terminals show as a grey block. +func boxed(b *cv.Box, title string) func(string) { + sidebarBoxes = append(sidebarBoxes, b) + b.SetBorder(true) + b.SetBorderColor(colBoxBorder) + b.SetBorderColorFocused(colBoxFocused) + b.SetDrawFunc(func(screen tc.Screen, x, y, w, h int) (int, int, int, int) { + _, style, _ := screen.Get(x+1, y) // the border's style + for i, r := range []rune(" " + title + " ") { + if 2+i < w-1 { + screen.SetContent(x+1+i, y, r, nil, style.Foreground(colBoxTitle)) + } + } + return x + 2, y + 1, max(0, w-4), max(0, h-2) // inside the frame, a space each side + }) + return func(t string) { title = t } +} + +// The UI is "limited" with basic rendering, or on a terminal with fewer than +// 256 colours: then only the standard colours are used, with no dark tints +// (they'd all be black) and plain underlines (old terminals can misread the +// styled ones). screenColors is the terminal's colour count, kept after each +// frame (afterDraw), from the app's own screen only. +var ( + screenColors atomic.Int32 + wasLimited atomic.Bool +) + +func uiLimited() bool { + n := screenColors.Load() + return PiecesSetting() == PiecesBasic || (n > 0 && n < 256) +} + +// Text views and boxes whose colours depend on uiLimited. +var ( + moveLists []*cv.TextView + sidebarBoxes []*cv.Box +) + +// colUnderline is the side lines' underline: dim, so it doesn't crowd the text. +var colUnderline = tc.PaletteColor(240) + +// applyUIColours sets the move lists' highlight and the boxes' borders for +// a full or a limited terminal. UI goroutine. +func applyUIColours() { + lim := uiLimited() + for _, tv := range moveLists { + if lim { + tv.SetHighlightBackgroundColor(tc.ColorSilver) + tv.SetHighlightForegroundColor(tc.ColorBlack) + } else { + tv.SetHighlightBackgroundColor(colCurrentMove) + tv.SetHighlightForegroundColor(tc.ColorWhite) + } + } + for _, b := range sidebarBoxes { + if lim { + b.SetBorderColor(tc.ColorSilver) + b.SetBorderColorFocused(tc.ColorWhite) + } else { + b.SetBorderColor(colBoxBorder) + b.SetBorderColorFocused(colBoxFocused) + } + } + if Root.study != nil { + Root.study.shownAt = nil // redraw the move list's tints + Root.study.showNode() + } +} + +// checkLimited re-applies the colours when the rendering mode or terminal +// changes between full and limited. Called after each frame. +func checkLimited(screen tc.Screen) { + screenColors.Store(int32(screen.Colors())) + if lim := uiLimited(); wasLimited.Swap(lim) != lim && Root.App != nil { + go Root.App.QueueUpdateDraw(applyUIColours) + } +} + +// underlineScreen draws a text view with the terminal's underline styles, +// which cview's markup can't express: an underline with blink (which +// chess-cli never uses otherwise) is dashed, with strikethrough too dotted, +// with italic double, with both curly (see underlineTags). +type underlineScreen struct{ tc.Screen } + +func (s underlineScreen) Put(x, y int, str string, style tc.Style) (string, int) { + switch { + case !style.HasUnderline(): + case uiLimited(): // a plain underline only + style = style.Blink(false).StrikeThrough(false).Italic(false) + case style.HasBlink(): + u := tc.UnderlineStyleDashed + switch strike, italic := style.HasStrikeThrough(), style.HasItalic(); { + case strike && italic: + u = tc.UnderlineStyleCurly + case strike: + u = tc.UnderlineStyleDotted + case italic: + u = tc.UnderlineStyleDouble + } + style = style.Blink(false).StrikeThrough(false).Italic(false).Underline(u, colUnderline) + default: + style = style.Underline(tc.UnderlineStyleSolid, colUnderline) + } + return s.Screen.Put(x, y, str, style) +} + +// styledText is a text view drawn through underlineScreen. +type styledText struct{ *cv.TextView } + +func (t styledText) Draw(screen tc.Screen) { t.TextView.Draw(underlineScreen{screen}) } diff --git a/pkg/lichess.go b/pkg/lichess.go index 53e6b01..f4b0275 100644 --- a/pkg/lichess.go +++ b/pkg/lichess.go @@ -1,250 +1,251 @@ package pkg import ( + "context" + "errors" "fmt" - "log" - "os" "strings" "time" + cv "codeberg.org/tslocum/cview" "github.com/nate-xyz/chess-cli/api" "github.com/notnil/chess" ) +// streamRetries is how many times in a row the game stream may fail to +// reconnect before the game screen gives up. +const streamRetries = 5 + /* -LichessGame() is called after a gameID string has been retrieved from the event stream by WaitForLichessGameResponse() -This function then starts a board stream with the gameID and loops and modifies the gamestate and view based on events from the board stream. +LichessGame runs one online game: it streams the game from Lichess +(reconnecting if the connection drops), applies each update on the UI +goroutine, and ticks the clocks. It returns when the game ends or the user +leaves (both cancel online.ctx via endGame). */ func (online *OnlineGame) LichessGame(gameID string) { - killGame = make(chan string) - gameStateChan = make(chan api.BoardEvent, 1) - streamDoneErr := make(chan error) - go api.StreamBoardState(gameStateChan, streamDoneErr, gameID) - - updateInc := make(chan BothInc) - stopTicker := make(chan bool) - go online.TimerLoop(stopTicker, updateInc) - - for { //loop + ctx := online.ctx + events := make(chan api.BoardEvent, 16) + streamErr := make(chan error, 1) + go runGameStream(ctx, gameID, events, streamErr) + go online.loadChatHistory(ctx, gameID) + + tick := time.NewTicker(100 * time.Millisecond) + defer tick.Stop() + for { select { - case s := <-killGame: - Root.App.QueueUpdate(func() { - stopTicker <- true - if s != "GoHome" { - Root.gameState.Status += fmt.Sprintf("[green]Game ended due to %v.[white]\n", s) - online.gotoPostOnline() - } else { - gotoLichessAfterLogin() - } - }) + case <-ctx.Done(): return - case err := <-streamDoneErr: - Root.App.QueueUpdate(func() { - stopTicker <- true - Root.gameState.Status += fmt.Sprintf("Game ended due to %v.\n", err) - online.gotoPostOnline() - }) + case err := <-streamErr: + Root.App.QueueUpdateDraw(func() { online.endGame(fmt.Sprintf("the connection to Lichess was lost (%v)", err)) }) return - case b := <-gameStateChan: - switch b.Type { - case api.GameFull: //full game state json - online.Full = b.Full - currentFEN, err := MoveTranslationToFEN(b.Full.State.Moves) //get the current FEN from the move history - if err != nil { - WriteLocal("BoardStateError MoveTranslation", fmt.Sprintf("%v ", err)+currentFEN) - log.Fatal(err) - os.Exit(1) - } - fen, err := chess.FEN(currentFEN) - if err != nil { - WriteLocal("BoardStateError chess FEN", fmt.Sprintf("%v ", err)+currentFEN) - log.Fatal(err) - os.Exit(1) - } - if b.Full.State.Moves == "" { - Root.gameState.MoveHistoryArray = nil - } else { - Root.gameState.MoveHistoryArray = strings.Split(b.Full.State.Moves, " ") - } - NewChessGame = chess.NewGame(fen) - - Root.App.QueueUpdate(online.InitTimeView) - Root.App.QueueUpdate(UpdateChessGame) - Root.App.QueueUpdate(online.UpdateAll) - Root.App.GetScreen().Beep() - - if b.Full.State.Status != "started" { //the game has ended. - go Root.App.QueueUpdate(func() { - stopTicker <- true - Root.gameState.Status += fmt.Sprintf("Game ended due to %v.\n", b.Full.State.Status) - online.gotoPostOnline() - }) - return - } - - case api.GameState: // game state json - online.State = b.State - MoveArr := strings.Split(b.State.Moves, " ") - Root.gameState.MoveCount = len(MoveArr) - _ = GetCapturePiecesArr(b.State.Moves) - currentFEN, err := MoveTranslationToFEN(b.State.Moves) - if err != nil { - stopTicker <- true - WriteLocal("BoardStateError MoveTranslation", fmt.Sprintf("%v", err)) - log.Fatal(err) - os.Exit(1) - } - fen, err := chess.FEN(currentFEN) - if err != nil { - stopTicker <- true - WriteLocal("BoardStateError chess FEN", fmt.Sprintf("%v", err)) - log.Fatal(err) - os.Exit(1) - } - if b.State.Moves == "" { - Root.gameState.MoveHistoryArray = nil - } else { - Root.gameState.MoveHistoryArray = MoveArr - } - NewChessGame = chess.NewGame(fen) - - updateInc <- BothInc{ - btime: int64(b.State.Btime), - wtime: int64(b.State.Wtime), - } - - Root.App.QueueUpdate(UpdateChessGame) - Root.App.QueueUpdate(online.UpdateAll) - Root.App.GetScreen().Beep() - - if (b.State.Bdraw && Root.User.Name == online.Full.White.ID) || (b.State.Wdraw && Root.User.Name == online.Full.Black.ID) { - // b.State.Bdraw = false //this is to reset globals - // b.State.Wdraw = false - Root.App.QueueUpdate(func() { - modal := NewOptionWindow("Your opponent has offered a draw.", "Accept ✅ ", "Reject ❌ ", online.doAcceptDraw, online.doRejectDraw) - online.PopUp = modal - online.Grid.AddItem(modal, 4, 2, 1, 1, 0, 0, false) - }) - } - - if (b.State.Btakeback && Root.User.Name == online.Full.White.ID) || (b.State.Wtakeback && Root.User.Name == online.Full.Black.ID) { - // api.BoardGameState.Btakeback = false - // api.BoardGameState.Wtakeback = false - Root.App.QueueUpdate(func() { - modal := NewOptionWindow("Your opponent has proposed a takeback.", "Accept ✅ ", "Reject ❌ ", online.doAcceptTakeBack, online.doRejectTakeBack) - online.PopUp = modal - online.Grid.AddItem(modal, 4, 2, 1, 1, 0, 0, false) - }) - } - - if b.State.Status != "started" { - go Root.App.QueueUpdate(func() { - stopTicker <- true - if b.State.Winner != "" { - Root.gameState.Status += fmt.Sprintf("Winner is [blue]%v![white]\n", b.State.Winner) - } - Root.gameState.Status += fmt.Sprintf("Game ended due to [red]%v.[white]\n", b.State.Status) - online.gotoPostOnline() - }) - return - } - - case api.ChatLine: - case api.ChatLineSpectator: - case api.GameStateResign: - online.Resign = b.Resign - go Root.App.QueueUpdate(func() { - stopTicker <- true - Root.gameState.Status += "Game ended due to resignation.\n" - online.gotoPostOnline() - }) - return - case api.EOF: - Root.App.QueueUpdate(func() { - stopTicker <- true - Root.gameState.Status += "Game ended due lost connection.\n" - online.gotoPostOnline() - }) - Root.App.QueueUpdate(online.gotoPostOnline) + case <-tick.C: + Root.App.QueueUpdateDraw(online.tick) + case ev := <-events: + Root.App.QueueUpdateDraw(func() { online.handleEvent(ev) }) + if ev.Type == api.EOF { return } - } } } -func (online *OnlineGame) TimerLoop(d <-chan bool, bi <-chan BothInc) { - ticker1 := time.NewTicker(time.Millisecond * 500) - ticker2 := time.NewTicker(time.Millisecond * 10) - - var Btime int64 - var Wtime int64 - var start time.Time +// runGameStream keeps the game stream open, reconnecting after drops. Lichess +// resends the full game state on every connect, so reconnecting is seamless. +func runGameStream(ctx context.Context, gameID string, events chan<- api.BoardEvent, fatal chan<- error) { + failures := 0 for { + errs := make(chan error, 1) + connected := time.Now() + api.StreamBoardState(ctx, events, errs, gameID) + if ctx.Err() != nil { + return + } + var err error select { - case b := <-bi: - Wtime = b.wtime - Btime = b.btime - start = time.Now() - case <-d: + case err = <-errs: + default: + return // the stream ended normally (EOF was delivered) + } + var apiErr *api.APIError + if errors.As(err, &apiErr) && apiErr.Status < 500 && apiErr.Status != 429 { + fatal <- err // e.g. game not found: retrying won't help return - case <-ticker1.C: //every half second - if Root.gameState.MoveCount >= 2 { - var currB int64 = Btime - var currW int64 = Wtime - if Root.gameState.MoveCount%2 == 0 { - currW -= time.Since(start).Milliseconds() - } else { - currB -= time.Since(start).Milliseconds() - } - online.LiveUpdateTime(currB, currW) - Root.App.QueueUpdateDraw(func() {}, online.UserTimer, online.OppTimer) - } - case <-ticker2.C: //every ms - if Root.gameState.MoveCount >= 2 { - var currB int64 = Btime - var currW int64 = Wtime - if Root.gameState.MoveCount%2 == 0 { - currW -= time.Since(start).Milliseconds() - } else { - currB -= time.Since(start).Milliseconds() - } - - if currB < 10000 || currW < 10000 { //start drawing millis when less than ten seconds - online.LiveUpdateTime(currB, currW) - Root.App.QueueUpdateDraw(func() {}, online.UserTimer, online.OppTimer) - } - } + } + if time.Since(connected) > 30*time.Second { + failures = 0 // it was a working connection, not a failing reconnect + } + failures++ + if failures > streamRetries { + fatal <- err + return + } + Root.App.QueueUpdateDraw(func() { + Root.gameState.Status += "[yellow]Connection dropped, reconnecting…[-]\n" + Root.ongame.UpdateStatus() + }) + select { + case <-time.After(time.Duration(failures) * time.Second): + case <-ctx.Done(): + return + } + } +} +// handleEvent applies one game-stream event. UI goroutine only. +func (online *OnlineGame) handleEvent(ev api.BoardEvent) { + if online.ended { + return + } + switch ev.Type { + case api.GameFull: + online.Full = ev.Full + online.applyState(ev.Full.State) + case api.GameState: + online.applyState(ev.State) + case api.ChatLine: + online.addChat(ev.Chat.Username, ev.Chat.Text, ev.Chat.Room) + case api.OpponentGone: + online.Gone = ev.Gone + online.goneSince = time.Now() + if ev.Gone.Gone { + Root.gameState.Status += "[yellow]Your opponent left the game.[-]\n" + } else { + Root.gameState.Status += "[green]Your opponent is back.[-]\n" + } + online.UpdateList() + online.UpdateStatus() + case api.EOF: + if online.State.Status == "" || online.State.Status == "started" { + online.endGame("the game stream closed") } } } -//consumes stream events for a user after stream for a user started after login -func StreamConsumer(EventChannel <-chan api.StreamEventType) { - for { - e := <-EventChannel - if api.Online { - n, _ := Root.nav.GetFrontPanel() - if n == "lichesswelcome" { - // Root.wonline.UpdateTitle(fmt.Sprintf("%s: %s", e.EventType, e.GameID)) - // time.Sleep(time.Second) - Root.wonline.UpdateTitle("") - } - // if n == "ponline" && e.GameID == currentGameID { - // Root.App.QueueUpdate(func() { - // modal := NewOptionWindow( - // fmt.Sprintf("%s: %s", e.EventType, e.GameID), - // "Ok ✅ ", "Go Home 🏠", - // func() { - // Root.ponline.Grid.RemoveItem(Root.ponline.PopUp) - // }, - // gotoLichessAfterLogin) - // Root.ponline.PopUp = modal - // Root.ponline.Grid.AddItem(modal, 2, 2, 1, 1, 0, 0, false) - // }) - // } +// applyState updates the board, history, clocks and offers from a game state. +func (online *OnlineGame) applyState(st api.StreamBoardGameState) { + prevMoves := online.State.Moves + online.State = st + game, err := gameFromMoves(online.Full.InitialFen, st.Moves) + if err != nil { + Root.gameState.Status += fmt.Sprintf("[red]Could not follow the game: %v[-]\n", err) + online.UpdateStatus() + return + } + Root.gameState.Game = game + if st.Moves == "" { + Root.gameState.MoveHistoryArray = nil + } else { + Root.gameState.MoveHistoryArray = strings.Split(st.Moves, " ") + } + Root.gameState.MoveCount = len(Root.gameState.MoveHistoryArray) + _ = GetCapturePiecesArr(st.Moves) + online.clockW, online.clockB = int64(st.Wtime), int64(st.Btime) + online.clockAt = time.Now() + + online.UpdateAll() + if st.Moves != prevMoves && prevMoves != "" { + Root.App.GetScreen().Beep() + } + + online.updateOffers(st) + + if st.Status != "" && st.Status != "started" { + msg := fmt.Sprintf("the game ended: [red]%s[-]", st.Status) + if st.Winner != "" { + msg = fmt.Sprintf("%s wins (%s)", caser.String(st.Winner), st.Status) + } + online.endGame(msg) + } +} + +// updateOffers shows or hides the popup for the opponent's draw/takeback offer. +func (online *OnlineGame) updateOffers(st api.StreamBoardGameState) { + white := online.IsWhite() + drawOffered := (white && st.Bdraw) || (!white && st.Wdraw) + takebackOffered := (white && st.Btakeback) || (!white && st.Wtakeback) + switch { + case drawOffered && online.popupKind != "draw": + online.showPopup("draw", NewOptionWindow("Your opponent offers a draw.", "Accept ✅ ", "Decline ❌ ", online.doAcceptDraw, online.doRejectDraw)) + case takebackOffered && online.popupKind != "takeback": + online.showPopup("takeback", NewOptionWindow("Your opponent proposes a takeback.", "Accept ✅ ", "Decline ❌ ", online.doAcceptTakeBack, online.doRejectTakeBack)) + case !drawOffered && !takebackOffered: + online.hidePopup() + } +} + +func (online *OnlineGame) showPopup(kind string, p *cv.Flex) { + online.hidePopup() + online.PopUp = p + online.popupKind = kind + online.Side.AddItemAtIndex(2, p, 7, 0, false) // under the opponent's name and clock +} + +func (online *OnlineGame) hidePopup() { + if online.PopUp != nil { + online.Side.RemoveItem(online.PopUp) + online.PopUp = nil + } + online.popupKind = "" +} + +// tick redraws the running clock and the opponent-gone countdown. UI goroutine. +func (online *OnlineGame) tick() { + if online.ended || online.Full.ID == "" { + return + } + w, b := online.clockW, online.clockB + if Root.gameState.MoveCount >= 2 { + elapsed := time.Since(online.clockAt).Milliseconds() + if Root.gameState.Game.Position().Turn() == chess.White { + w = max(0, w-elapsed) + } else { + b = max(0, b-elapsed) + } + } + online.LiveUpdateTime(b, w) + if online.Gone.Gone { + before := online.canClaim + online.canClaim = time.Since(online.goneSince) >= time.Duration(online.Gone.ClaimWinInSeconds)*time.Second + if online.canClaim != before { + online.UpdateList() + online.UpdateStatus() + } + } +} + +// endGame stops the game screen and shows the result. UI goroutine only. +func (online *OnlineGame) endGame(reason string) { + if online.ended { + return + } + online.ended = true + online.cancel() + online.hidePopup() + if reason == "" { + gotoLichessAfterLogin() + return + } + Root.gameState.Status += "Game over: " + reason + "\n" + online.gotoPostOnline() +} + +// gameFromMoves rebuilds a game from its starting position and UCI moves. +// Keeping the full move list (rather than just a FEN) gives correct +// repetition detection and the last-move highlight. +func gameFromMoves(initialFEN, moves string) (*chess.Game, error) { + opts := []func(*chess.Game){chess.UseNotation(chess.UCINotation{})} + if initialFEN != "" && initialFEN != "startpos" { + fen, err := chess.FEN(initialFEN) + if err != nil { + return nil, err + } + opts = append(opts, fen) + } + game := chess.NewGame(opts...) + for _, m := range strings.Fields(moves) { + if err := game.MoveStr(m); err != nil { + return nil, fmt.Errorf("move %q: %w", m, err) } - EventStreamArr = append([]api.StreamEventType{e}, EventStreamArr...) } + return game, nil } diff --git a/pkg/local_clock.go b/pkg/local_clock.go new file mode 100644 index 0000000..2601169 --- /dev/null +++ b/pkg/local_clock.go @@ -0,0 +1,191 @@ +package pkg + +import ( + "fmt" + "sync/atomic" + "time" + + "github.com/nate-xyz/chess-cli/api" + "github.com/notnil/chess" +) + +// Clocks for local games (two players, or against Stockfish). White's clock +// starts after White's first move; each move adds the increment; running out +// loses on time. + +// localClocks are the time controls on offer: minutes + seconds per move, +// and for the FIDE classical control, extra minutes after move 40. +var localClocks = []struct{ minutes, increment, bonusAt40 int }{ + {0, 0, 0}, // none + {1, 0, 0}, {3, 0, 0}, {3, 2, 0}, {5, 0, 0}, {5, 3, 0}, {10, 0, 0}, {10, 5, 0}, {15, 10, 0}, + {30, 0, 0}, {30, 20, 0}, {45, 15, 0}, {60, 30, 0}, {90, 30, 0}, {120, 30, 0}, + {90, 30, 30}, // FIDE classical: 90 min for 40 moves, then +30 min; 30 s per move throughout +} + +// localClockIndex is the chosen time control (0 = no clock). +func localClockIndex() int { + i := api.UserInfo.LocalClock + if i < 0 || i >= len(localClocks) { + return 0 + } + return i +} + +func localClockName(i int) string { + c := localClocks[i] + switch { + case c.minutes == 0: + return "none" + case c.bonusAt40 > 0: + return fmt.Sprintf("%d/40+%d+%ds", c.minutes, c.bonusAt40, c.increment) + } + return fmt.Sprintf("%d+%d", c.minutes, c.increment) +} + +// nextLocalClock cycles the time control. +func nextLocalClock() { + next := (localClockIndex() + 1) % len(localClocks) + _ = api.UpdateConfig(func(c *api.UserConfig) { c.LocalClock = next }) +} + +// clockActive mirrors GameScreen.clock.on for the background ticker. +var clockActive atomic.Bool + +// localClock is a running pair of clocks. +type localClock struct { + on bool + white time.Duration + black time.Duration + initial time.Duration + increment time.Duration + since time.Time // when the side to move's clock last started (zero = not running) + tc string + bonusAt40 time.Duration // added to each side's clock after their 40th move + lowWhite bool // the low-time sound has played for this side + lowBlack bool +} + +// startClock sets up the clocks for a new game with the chosen control. +func (g *GameScreen) startClock() { + c := localClocks[localClockIndex()] + g.clock = localClock{} + clockActive.Store(c.minutes > 0) + if c.minutes == 0 { + return + } + d := time.Duration(c.minutes) * time.Minute + g.clock = localClock{on: true, white: d, black: d, initial: d, + increment: time.Duration(c.increment) * time.Second, tc: localClockName(localClockIndex()), + bonusAt40: time.Duration(c.bonusAt40) * time.Minute} +} + +// clockMoved updates the clocks after a move by mover. +func (g *GameScreen) clockMoved(mover chess.Color) { + c := &g.clock + if !c.on { + return + } + now := time.Now() + if !c.since.IsZero() { + used := now.Sub(c.since) + if mover == chess.White { + c.white -= used + } else { + c.black -= used + } + } + bonus := time.Duration(0) + // the mover's 40th move has just been played: second time period starts + if c.bonusAt40 > 0 && len(Root.gameState.Game.Moves()) == 80-int(chess.Black-mover) { + bonus = c.bonusAt40 + } + if mover == chess.White { + c.white += c.increment + bonus + } else { + c.black += c.increment + bonus + } + c.since = now // the other side's clock starts (after White's first move) +} + +// remaining is each side's time now, counting the running clock down. +func (g *GameScreen) remaining() (w, b time.Duration) { + c := g.clock + w, b = c.white, c.black + if !c.since.IsZero() { + if Root.gameState.Game.Position().Turn() == chess.White { + w -= time.Since(c.since) + } else { + b -= time.Since(c.since) + } + } + return max(0, w), max(0, b) +} + +// tickClock shows the clocks and checks for a flag fall. UI goroutine. +func (g *GameScreen) tickClock() { + if !g.clock.on || Root.gameState == nil { + g.Board.HideClockBars() + g.UserTimer.SetText("") + g.OppTimer.SetText("") + return + } + w, b := g.remaining() + running := !g.clock.since.IsZero() + whiteToMove := Root.gameState.Game.Position().Turn() == chess.White + if running && (w == 0 || b == 0) { + winner := chess.Black + if w > 0 { + winner = chess.White + } + gotoPostLocalResult(winner, "timeout") // stops the clock + return + } + if running && g.clock.white > 0 { + low, left := &g.clock.lowWhite, w + if !whiteToMove { + low, left = &g.clock.lowBlack, b + } + if !*low && lowTime(left, g.clock.initial) && !g.engineTurn() { + *low = true + playSound(soundLowTime) + } + } + bar := func(d time.Duration, active bool) clockBar { + return clockBar{label: clockLabel(int(d.Round(time.Second) / time.Second)), right: g.clock.tc, + frac: min(1, float64(d)/float64(g.clock.initial)), active: active && running} + } + wc, bc := bar(w, whiteToMove), bar(b, !whiteToMove) + top, bottom := bc, wc + if !g.whiteAtBottom() { + top, bottom = wc, bc + } + if clockBarsOn() { + g.Board.SetClockBars(top, bottom) + g.UserTimer.SetText("") + g.OppTimer.SetText("") + return + } + g.Board.HideClockBars() + text := func(c clockBar) string { + if c.active { + return "[black:#c8c8c8] " + c.label + " [-:-] [#a0a0a0]" + c.right + "[-]" + } + return " " + c.label + " [#a0a0a0]" + c.right + "[-]" + } + g.OppTimer.SetText(text(top)) + g.UserTimer.SetText(text(bottom)) +} + +// clockTicker refreshes the local game's clocks while it's on screen. +func (g *GameScreen) clockTicker() { + for range time.Tick(200 * time.Millisecond) { + if !showing("localgame") || !clockActive.Load() { + continue + } + Root.App.QueueUpdateDraw(func() { + if name, _ := Root.nav.GetFrontPanel(); name == "localgame" && g.clock.on { + g.tickClock() + } + }) + } +} diff --git a/pkg/local_clock_test.go b/pkg/local_clock_test.go new file mode 100644 index 0000000..dd4ab63 --- /dev/null +++ b/pkg/local_clock_test.go @@ -0,0 +1,91 @@ +package pkg + +import ( + "math/rand/v2" + "strings" + "testing" + "time" + + "github.com/nate-xyz/chess-cli/api" + "github.com/notnil/chess" +) + +func TestLocalClock(t *testing.T) { + startTestApp(t, 160, 50) + g := Root.lgame + onUI(func() { + api.UserInfo.LocalClock = 3 // 3+2 + startNewLocalGame() + if !g.clock.on || g.clock.white != 3*time.Minute { + t.Fatalf("clock not set up: %+v", g.clock) + } + // White's clock doesn't run before White's first move + if !g.clock.since.IsZero() { + t.Error("clock running before the first move") + } + if err := g.DoMove("e2e4"); err != nil { + t.Fatal(err) + } + if g.clock.white != 3*time.Minute+2*time.Second { + t.Errorf("white after first move = %v, want 3:02 (no time used, +2 increment)", g.clock.white) + } + // black's clock is running now; make it run out + g.clock.black = time.Millisecond + }) + time.Sleep(20 * time.Millisecond) + onUI(func() { g.tickClock() }) + waitFor(t, "loss on time", func() bool { + name, _ := Root.nav.GetFrontPanel() + return name == "postlocal" && strings.Contains(Root.pgame.Result.GetText(true), "White wins by time") + }) + onUI(func() { api.UserInfo.LocalClock = 0 }) +} + +// FIDE classical: each side gets 30 minutes more after their 40th move, once. +func TestLocalClockFIDEBonus(t *testing.T) { + startTestApp(t, 160, 50) + g := Root.lgame + onUI(func() { + defer func() { api.UserInfo.LocalClock = 0 }() + api.UserInfo.LocalClock = len(localClocks) - 1 + if name := localClockName(api.UserInfo.LocalClock); name != "90/40+30+30s" { + t.Fatalf("last clock is %q, want the FIDE control", name) + } + startNewLocalGame() + game := Root.gameState.Game + rng := rand.New(rand.NewPCG(1, 2)) + for ply := 1; ply <= 82; ply++ { + // a random game that keeps going (no mate, no forced draw) + var played bool + for try := 0; try < 50 && !played; try++ { + valid := game.ValidMoves() + g2 := game.Clone() + m := valid[rng.IntN(len(valid))] + if g2.Move(m) == nil && g2.Outcome() == chess.NoOutcome { + played = game.Move(m) == nil + } + } + if !played { + t.Fatalf("couldn't find a move at ply %d", ply) + } + mover := chess.White + if ply%2 == 0 { + mover = chess.Black + } + wBefore, bBefore := g.clock.white, g.clock.black + g.clock.since = time.Time{} // no thinking time, so only increments and bonuses count + g.clockMoved(mover) + gained := g.clock.white - wBefore + if mover == chess.Black { + gained = g.clock.black - bBefore + } + want := 30 * time.Second + if ply == 79 || ply == 80 { // White's and Black's 40th moves + want += 30 * time.Minute + } + if gained != want { + t.Errorf("ply %d (%v): gained %v, want %v", ply, mover, gained, want) + } + } + }) +} diff --git a/pkg/login.go b/pkg/login.go index f15d8f9..019db4b 100644 --- a/pkg/login.go +++ b/pkg/login.go @@ -9,24 +9,15 @@ import ( func (user *Login) GetLichessUserInfo() error { var err error if user.Token != "" { - if user.Email == "" { - user.Email, err = api.GetEmail() - if err != nil { - return err - } - } if user.Name == "" { user.Name, err = api.GetUsername() if err != nil { return err } } - user.Friends, err = api.GetFriends() - if err != nil { - return err - } - if !api.StreamEventStarted { - Ready <- struct{}{} //start event stream + user.Friends, _ = api.GetFriends() // only used for suggestions; not worth failing login over + if StreamChannel != nil { + api.StartEventStream(StreamChannel) } return nil } diff --git a/pkg/menukeys.go b/pkg/menukeys.go new file mode 100644 index 0000000..f9fc80c --- /dev/null +++ b/pkg/menukeys.go @@ -0,0 +1,182 @@ +package pkg + +import ( + "time" + + cv "codeberg.org/tslocum/cview" + tc "github.com/gdamore/tcell/v3" +) + +// Menu keys that work the same everywhere: a menu's letter shortcuts work +// wherever the keyboard is on its screen (not only when the menu itself has +// focus), unless you're typing in a text box or the board needs that key. +// Screens with more than one menu cycle through them with Tab. + +type screenMenus struct { + lists []*cv.List + tab bool // Tab moves between the menus (screens without their own Tab) +} + +var menusByScreen = map[string]*screenMenus{} + +// registerMenus records the menus on a screen (a panel name). +func registerMenus(screen string, tab bool, lists ...*cv.List) { + menusByScreen[screen] = &screenMenus{lists: lists, tab: tab} +} + +// menuKeys is part of the global key handler. It returns nil when it used +// the key. +func menuKeys(ev *tc.EventKey) *tc.EventKey { + name, _ := Root.nav.GetFrontPanel() + sm := menusByScreen[name] + if sm == nil { + return ev + } + focus := Root.App.GetFocus() + switch f := focus.(type) { + case *cv.InputField: + return ev // typing + case *BoardView: + if ev.Key() == tc.KeyRune && f.takesKeys() { + if f.PromotionOpen() || containsRune(boardKeys(), ev.Str()) { + return ev + } + } + } + + if sm.tab && (ev.Key() == tc.KeyTab || ev.Key() == tc.KeyBacktab) { + step := 1 + if ev.Key() == tc.KeyBacktab { + step = -1 + } + cur := -1 + for i, l := range sm.lists { + if focus == l { + cur = i + } + } + for n := 1; n <= len(sm.lists); n++ { + l := sm.lists[((cur+step*n)%len(sm.lists)+len(sm.lists))%len(sm.lists)] + if l.GetItemCount() > 0 { + Root.App.SetFocus(l) + return nil + } + } + return ev + } + + if ev.Key() != tc.KeyRune || ev.Str() == " " { + return ev + } + // The focused menu gets its own shortcuts first. + for _, l := range sm.lists { + if focus == l && hasShortcut(l, ev.Str()) { + return ev + } + } + for _, l := range sm.lists { + if focus != l && hasShortcut(l, ev.Str()) { + Root.App.SetFocus(l) + l.InputHandler()(ev, Root.App.SetFocus) + return nil + } + } + return ev +} + +// numberKey is the shortcut for the i-th entry of a list of games or +// challenges: 1-9, then none. Letters are for menu actions. +func numberKey(i int) rune { + if i < 9 { + return rune('1' + i) + } + return 0 +} + +func hasShortcut(l *cv.List, key string) bool { + for _, it := range l.GetItems() { + if it.GetShortcut() != 0 && string(it.GetShortcut()) == key { + return true + } + } + return false +} + +func containsRune(set, s string) bool { + for _, r := range set { + if string(r) == s { + return true + } + } + return false +} + +// forwardKeys makes a decorative box hand the keyboard to target, passing +// the key on so it isn't lost (pressing ↓ on a title moves the menu). +func forwardKeys(box interface { + SetInputCapture(func(*tc.EventKey) *tc.EventKey) +}, target cv.Primitive) { + box.SetInputCapture(func(ev *tc.EventKey) *tc.EventKey { + if target == nil { + return ev + } + Root.App.SetFocus(target) + if h := target.InputHandler(); h != nil { + h(ev, Root.App.SetFocus) + } + return nil + }) +} + +// confirmItem makes a menu item ask for a second press before doing f +// (resign, abort): the first press changes its text to ask, for a few +// seconds. +func confirmItem(item *cv.ListItem, text, ask string, f func()) { + var armed time.Time + item.SetMainText(text) + item.SetSelectedFunc(func() { + if time.Since(armed) < 3*time.Second { + armed = time.Time{} + item.SetMainText(text) + f() + return + } + armed = time.Now() + item.SetMainText("[red::b]" + ask + "[-::-]") + time.AfterFunc(3*time.Second, func() { + Root.App.QueueUpdateDraw(func() { + if !armed.IsZero() && time.Since(armed) >= 3*time.Second { + item.SetMainText(text) + } + }) + }) + }) +} + +// fitMenuColumn makes column col of a grid as wide as its menu needs (the +// widest entry or description, with the shortcut), so descriptions aren't +// cut off; the other columns share the rest. cols are the grid's columns +// otherwise (used when the menu wouldn't leave room for the rest). +func fitMenuColumn(g *cv.Grid, list *cv.List, cols []int, col int) { + const minRest = 30 // columns kept for the rest of the screen + g.SetDrawFunc(func(_ tc.Screen, x, y, w, h int) (int, int, int, int) { + c := append([]int(nil), cols...) + if need := menuWidth(list); need <= w-minRest { + c[col] = need + } + g.SetColumns(c...) // the grid's own lock, not the box's held here + return x, y, w, h + }) +} + +// menuWidth is the columns a list needs to show all of every entry. +func menuWidth(l *cv.List) int { + widest, shortcut := 0, 0 + for _, it := range l.GetItems() { + widest = max(widest, cv.TaggedStringWidth(it.GetMainText()), cv.TaggedStringWidth(it.GetSecondaryText())) + if it.GetShortcut() != 0 { + shortcut = 4 // "(x) " + } + } + return shortcut + widest + 2 +} diff --git a/pkg/menukeys_test.go b/pkg/menukeys_test.go new file mode 100644 index 0000000..c561b94 --- /dev/null +++ b/pkg/menukeys_test.go @@ -0,0 +1,130 @@ +package pkg + +import ( + "testing" + + cv "codeberg.org/tslocum/cview" + tc "github.com/gdamore/tcell/v3" +) + +// press sends a key through the whole app, as the terminal would. +func press(s tc.Screen, k tc.Key, str string) { + s.EventQ() <- tc.NewEventKey(k, str, tc.ModNone) +} + +func shownPanel() string { + name, _ := Root.nav.GetFrontPanel() + return name +} + +// Menu shortcuts work wherever the keyboard is on the screen; a playable +// board keeps its own keys, typing in a text box keeps letters, and screens +// with several menus cycle with Tab. +func TestMenuKeysEverywhere(t *testing.T) { + scr := startTestApp(t, 160, 50) + + // Study: the board has the keyboard; x is the menu's Leave. + onUI(func() { + Root.Switch("study") + Root.study.show(parseStudyPGN(testStudyPGN), "") + Root.App.SetFocus(Root.study.Board) + }) + press(scr, tc.KeyRune, "x") + waitFor(t, "study x leaves", func() bool { return shownPanel() == "welcome" }) + + // Local game: hjkl stay with the board (l moves the cursor, it doesn't + // leave); x leaves even with the board focused. + onUI(func() { startNewLocalGame() }) + waitFor(t, "local game", func() bool { return shownPanel() == "localgame" }) + onUI(func() { Root.App.SetFocus(Root.lgame.Board) }) + press(scr, tc.KeyRune, "l") + press(scr, tc.KeyRune, "l") + waitFor(t, "cursor moved by l", func() bool { + b := Root.lgame.Board + return b.keyboard && b.cursor.String() == "f2" + }) + if shownPanel() != "localgame" { + t.Fatalf("l left the game (now on %s)", shownPanel()) + } + // typing a move: letters go to the box, not the menu + onUI(func() { Root.lgame.Move.show() }) + press(scr, tc.KeyRune, "x") + waitFor(t, "x typed in the move box", func() bool { return Root.lgame.Move.input.GetText() == "x" }) + onUI(func() { + Root.lgame.Move.input.SetText("") + Root.lgame.Move.hide() + Root.App.SetFocus(Root.lgame.Board) + }) + press(scr, tc.KeyRune, "x") + waitFor(t, "x leaves the local game", func() bool { return shownPanel() == "welcome" }) + + // Saved games: Tab moves from the game list to the menu. + onUI(func() { gotoSaved() }) + waitFor(t, "saved", func() bool { return shownPanel() == "saved" }) + var gameList, options *cv.List + onUI(func() { + sm := menusByScreen["saved"] + gameList, options = sm.lists[0], sm.lists[1] + Root.App.SetFocus(gameList) + }) + press(scr, tc.KeyTab, "") + waitFor(t, "Tab to the menu", func() bool { return Root.App.GetFocus() == options }) + press(scr, tc.KeyRune, "b") + waitFor(t, "b goes back", func() bool { return shownPanel() != "saved" }) +} + +// The first key on a title or other box that hands the keyboard to a menu +// isn't lost: ↓ moves the menu straight away. +func TestForwardKeysKeepsTheKey(t *testing.T) { + scr := startTestApp(t, 160, 50) + onUI(func() { gotoWelcome() }) + waitFor(t, "welcome", func() bool { return shownPanel() == "welcome" }) + var list *cv.List + onUI(func() { + list = menusByScreen["welcome"].lists[0] + list.SetCurrentItem(0) + Root.App.SetFocus(newsBox) + }) + press(scr, tc.KeyDown, "") + waitFor(t, "↓ moved the menu", func() bool { return Root.App.GetFocus() == list && list.GetCurrentItemIndex() == 1 }) +} + +// Resign and abort need a second press. +func TestConfirmItem(t *testing.T) { + startTestApp(t, 160, 50) + done := 0 + item := cv.NewListItem("") + confirmItem(item, "Resign", "Resign? Press again", func() { done++ }) + l := cv.NewList() + l.AddItem(item) + enter := func() { l.InputHandler()(tc.NewEventKey(tc.KeyEnter, "", tc.ModNone), func(cv.Primitive) {}) } + onUI(func() { + enter() + if done != 0 || item.GetMainText() != "[red::b]Resign? Press again[-::-]" { + t.Errorf("first press: done %d, text %q", done, item.GetMainText()) + } + enter() + if done != 1 || item.GetMainText() != "Resign" { + t.Errorf("second press: done %d, text %q", done, item.GetMainText()) + } + }) +} + +// The home menu's column is as wide as its longest description, so nothing +// is cut off, at the size it used to cut "rated or casual". +func TestMenuColumnFits(t *testing.T) { + startTestApp(t, 160, 50) + defer onUI(func() { Root.nav.SetRect(0, 0, 160, 50) }) + onUI(func() { + gotoWelcome() + list := menusByScreen["welcome"].lists[0] + _, p := Root.nav.GetFrontPanel() + scr := newMockScreen(t, 143, 45) + p.SetRect(0, 0, 143, 45) + p.Draw(scr) + _, _, w, _ := list.GetInnerRect() + if need := menuWidth(list); w < need { + t.Errorf("home menu %d wide, needs %d", w, need) + } + }) +} diff --git a/pkg/modes_test.go b/pkg/modes_test.go new file mode 100644 index 0000000..8ea4bdc --- /dev/null +++ b/pkg/modes_test.go @@ -0,0 +1,137 @@ +package pkg + +import ( + "strings" + "testing" + + tc "github.com/gdamore/tcell/v3" + "github.com/notnil/chess" +) + +// Studies in each rendering mode: full terminals get the greys, tints and +// styled underlines; basic rendering (the original chess-cli look, for old +// terminals) only standard colours and plain underlines, and the move +// symbols still show on the board. +func TestStudyRenderingModes(t *testing.T) { + scr := startTestApp(t, 160, 50) + ss := Root.study + defer onUI(func() { previewPieces(""); applyUIColours() }) + + find := func(text string) (x, y int, ok bool) { + w, h := scr.Size() + for y := 0; y < h; y++ { + var row strings.Builder + for x := 0; x < w; x++ { + s, _, _ := scr.Get(x, y) + row.WriteString(s) + } + if i := strings.Index(row.String(), text); i >= 0 { + return len([]rune(row.String()[:i])), y, true + } + } + return 0, 0, false + } + styleAt := func(text string, dx int) tc.Style { + x, y, ok := find(text) + if !ok { + t.Fatalf("%q not on screen", text) + } + _, st, _ := scr.Get(x+dx, y) + return st + } + draw := func() { + onUI(func() { Root.App.Draw() }) + onUI(func() {}) // let queued colour changes run + onUI(func() { Root.App.Draw() }) + } + + for _, mode := range []string{PiecesText, PiecesBasic} { + t.Run(mode, func(t *testing.T) { + basic := mode == PiecesBasic + onUI(func() { + previewPieces(mode) + Root.Switch("study") + ss.show(parseStudyPGN(testStudyPGN), "") + }) + draw() + onUI(func() { ss.goTo(ss.ch.nodes[4]) }) // 2... Nc6: side lines branch here + draw() + var cur, nested tc.Style + onUI(func() { cur, nested = styleAt("Nc6", 0), styleAt("(3. Bc4)", 1) }) + wantBg := colCurrentMove + if basic { + wantBg = tc.ColorSilver + } + if cur.GetBackground() != wantBg { + t.Errorf("current move background %v, want %v", cur.GetBackground(), wantBg) + } + wantUl := tc.UnderlineStyleDashed + if basic { + wantUl = tc.UnderlineStyleSolid + } + if nested.GetUnderlineStyle() != wantUl || nested.HasBlink() || nested.HasStrikeThrough() { + t.Errorf("nested side line underline %v (blink %v), want %v", nested.GetUnderlineStyle(), nested.HasBlink(), wantUl) + } + + onUI(func() { ss.goTo(ss.ch.nodes[3]) }) // 2. Nf3: has a comment + draw() + var comment tc.Style + onUI(func() { comment = styleAt("Attacks e5.", 0) }) + tinted := comment.GetBackground() == tc.NewHexColor(0x1e2a1e) + if tinted == basic { + t.Errorf("comment tinted %v in %s mode", tinted, mode) + } + + // the move symbol on the board: 3. Bc4!? on c4 + onUI(func() { ss.goTo(ss.ch.nodes[9]) }) + draw() + onUI(func() { + b := ss.Board + b.mu.Lock() + row, col := displayOf(b.glyphSq, b.white) + x, y := b.ox+(col+1)*b.sqW-2, b.oy+row*b.sqH + b.mu.Unlock() + s1, st, _ := scr.Get(x, y) + s2, _, _ := scr.Get(x+1, y) + want := moveGlyph(5).tc() + if basic { + want = moveGlyph(5).basic() + } + if s1+s2 != "!?" || st.GetBackground() != want { + t.Errorf("badge %q on %v, want `!?` on %v", s1+s2, st.GetBackground(), want) + } + }) + }) + } +} + +// Pieces in advanced rendering without big pieces (any terminal but kitty) +// are upright Unicode chess symbols; black pawns used to be U+1FA3E, the +// pawn rotated 270 degrees, and showed sideways. +func TestTextModePawns(t *testing.T) { + scr := startTestApp(t, 160, 50) + ss := Root.study + defer onUI(func() { previewPieces("") }) + onUI(func() { + previewPieces(PiecesText) + Root.Switch("study") + ss.show(parseStudyPGN(testStudyPGN), "") + }) + onUI(func() { Root.App.Draw() }) + onUI(func() { + ss.goTo(ss.ch.nodes[0]) + Root.App.Draw() + }) + onUI(func() { + b := ss.Board + b.mu.Lock() + defer b.mu.Unlock() + for sq, want := range map[chess.Square]string{chess.E7: "♟︎", chess.E1: "♚"} { + row, col := displayOf(sq, b.white) + got, _, w := scr.Get(b.ox+col*b.sqW+b.sqW/2, b.oy+row*b.sqH+b.sqH/2) + if got != want || w != 1 { + t.Errorf("%v shows %q (width %d), want %q (width 1)", sq, got, w, want) + } + } + }) +} diff --git a/pkg/movelist_test.go b/pkg/movelist_test.go new file mode 100644 index 0000000..a1e06ce --- /dev/null +++ b/pkg/movelist_test.go @@ -0,0 +1,96 @@ +package pkg + +import ( + "strings" + "testing" + + "github.com/notnil/chess" +) + +func TestMoveListRegions(t *testing.T) { + game := chess.NewGame() + for _, m := range []string{"e4", "e5", "Nf3"} { + if err := game.MoveStr(m); err != nil { + t.Fatal(err) + } + } + text := moveListText(game) + for _, want := range []string{`["m1"]e4[""]`, `["m2"]e5[""]`, `["m3"]Nf3[""]`} { + if !strings.Contains(text, want) { + t.Errorf("move list missing %s:\n%s", want, text) + } + } +} + +// Clicking a move shows the position after it; stepping highlights the move. +func TestMoveListClick(t *testing.T) { + startTestApp(t, 160, 50) + g := Root.lgame + onUI(func() { + startNewLocalGame() + for _, m := range []string{"e2e4", "e7e5", "g1f3"} { + if err := g.DoMove(m); err != nil { + t.Fatal(err) + } + } + g.History.Highlight("m1") // what a click on "e4" does + if !g.Board.ViewingHistory() { + t.Fatal("clicking a move didn't go back") + } + g.Board.mu.Lock() + pos, _, to := g.Board.shown() + g.Board.mu.Unlock() + if pos.String() != Root.gameState.Game.Positions()[1].String() || to != chess.E4 { + t.Errorf("shown %v (last move to %v), want the position after 1. e4", pos, to) + } + g.Board.ShowPly(2) // e.g. ] on the board + }) + waitFor(t, "move list follows the board", func() bool { + hl := g.History.GetHighlights() // waitFor runs this on the UI goroutine + return len(hl) == 1 && hl[0] == "m2" + }) + onUI(func() { + g.History.Highlight("m3") // the last move: back to the present + if g.Board.ViewingHistory() { + t.Error("clicking the last move should show the current position") + } + }) +} + +// The game-over screen has the game layout: players, result, moves, final +// clocks, with the menu focused. +func TestPostLocalLayout(t *testing.T) { + startTestApp(t, 160, 50) + g := Root.lgame + onUI(func() { + startNewLocalGame() + for _, m := range []string{"f2f3", "e7e5", "g2g4", "d8h4"} { // fool's mate + if err := g.DoMove(m); err != nil { + t.Fatal(err) + } + } + }) + waitFor(t, "game over screen", func() bool { + name, _ := Root.nav.GetFrontPanel() + return name == "postlocal" + }) + onUI(func() { + p := Root.pgame + if r := p.Result.GetText(true); !strings.Contains(r, "Black wins by checkmate") { + t.Errorf("result = %q", r) + } + if h := p.History.GetText(true); !strings.Contains(h, "Qh4") { + t.Errorf("moves = %q", h) + } + if p.Top.GetText(true) == "" || p.Bottom.GetText(true) == "" { + t.Error("players not shown") + } + if Root.App.GetFocus() != p.List { + t.Error("menu not focused") + } + p.History.Highlight("m2") + if !p.Board.ViewingHistory() { + t.Error("can't step back on the game-over board") + } + }) +} diff --git a/pkg/news.go b/pkg/news.go new file mode 100644 index 0000000..a499d1a --- /dev/null +++ b/pkg/news.go @@ -0,0 +1,188 @@ +package pkg + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + cv "codeberg.org/tslocum/cview" + "github.com/nate-xyz/chess-cli/api" +) + +// Chess news on the home screen: elite events Lichess is broadcasting (live, +// coming up, just finished, with leaders/winners) and the latest Lichess +// blog posts. Only fetched when logged in to Lichess, so offline use stays +// offline; refreshed at most every 15 minutes, and simply not shown if it +// can't be fetched. + +var ( + newsBox *cv.TextView + newsFetched time.Time // when the news on screen was fetched + newsLoading bool + newsStarted bool // fetched once this run (always done at startup) +) + +const newsInterval = 15 * time.Minute + +// The last news fetched is saved, so the home screen can show it straight +// away next time while fresh news loads. +type newsCache struct { + Fetched time.Time + News *api.News +} + +func newsCachePath() (string, error) { + dir, err := api.ConfigDir() + if err != nil { + return "", err + } + return filepath.Join(dir, "news-cache.json"), nil +} + +func loadNewsCache() *newsCache { + path, err := newsCachePath() + if err != nil { + return nil + } + b, err := os.ReadFile(path) + if err != nil { + return nil + } + var c newsCache + if json.Unmarshal(b, &c) != nil || c.News == nil { + return nil + } + return &c +} + +func saveNewsCache(c newsCache) { + path, err := newsCachePath() + if err != nil { + return + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return + } + if b, err := json.Marshal(c); err == nil { + tmp := path + ".tmp" + if os.WriteFile(tmp, b, 0o600) == nil { + _ = os.Rename(tmp, path) + } + } +} + +// showNews puts news on the home screen, noting its age if it's old. It +// leaves the screen alone if nothing changed. +func showNews(n *api.News, fetched time.Time) { + text := newsText(n) + if text != "" && time.Since(fetched) > time.Hour { + text += "\n[#707070]as of " + fetched.Local().Format("Jan 2 15:04") + "[-]" + } + if text != newsBox.GetText(false) { + newsBox.SetText(text) + } +} + +// refreshNews shows the news and fetches fresh news in the background: always +// at startup (the saved news from last run shows meanwhile), then at most +// every 15 minutes. UI goroutine. +func refreshNews() { + if newsBox == nil || !api.HasValidToken() { + if newsBox != nil { + newsBox.SetText("") + } + return + } + if newsFetched.IsZero() { + if c := loadNewsCache(); c != nil { + showNews(c.News, c.Fetched) + newsFetched = c.Fetched + } + } + if newsLoading || newsStarted && time.Since(newsFetched) < newsInterval { + return + } + newsLoading, newsStarted = true, true + go func() { + n, err := api.GetNews() + if err == nil { + saveNewsCache(newsCache{Fetched: time.Now(), News: n}) + } + Root.App.QueueUpdateDraw(func() { + newsLoading = false + if err != nil { + return // keep whatever was shown; try again next time + } + newsFetched = time.Now() + showNews(n, newsFetched) + }) + }() +} + +func newsText(n *api.News) string { + var b strings.Builder + line := func(tag, text string) { + fmt.Fprintf(&b, "%s %s\n", tag, text) + } + if len(n.Live)+len(n.Upcoming)+len(n.Finished)+len(n.Blog) == 0 { + return "" + } + b.WriteString("[::b]Chess news[::-]\n\n") + for _, e := range n.Live { + text := cv.Escape(eventName(e.Name)) + if e.Round != "" { + text += " · " + cv.Escape(e.Round) + } + if e.Leader != "" { + text += " · [::b]" + cv.Escape(e.Leader) + "[::-] leads" + } + tag := "[#e0a030]● On now[-]" + if e.Live { + tag = "[red]● LIVE[-] " + } + line(tag, text) + } + for _, e := range n.Upcoming { + line("[#6fa8dc]◷ Soon[-] ", cv.Escape(eventName(e.Name))+" · "+dateRange(e.Start, e.End)) + } + for _, e := range n.Finished { + text := cv.Escape(eventName(e.Name)) + if e.Leader != "" { + text = "[::b]" + cv.Escape(e.Leader) + "[::-] wins " + text + } + line("[green]✓ Result[-]", text) + } + if len(n.Blog) > 0 { + b.WriteString("\n") + for _, p := range n.Blog { + line("[#a0a0a0]Lichess blog[-]", cv.Escape(p.Title)+" [#a0a0a0]· "+p.Date.Format("Jan 2")+"[-]") + } + } + return b.String() +} + +// eventName shortens a broadcast name to its event and main section: +// "Total Chess Tour 2026 | Group Stage | Combined" → "Total Chess Tour 2026 · Group Stage". +func eventName(name string) string { + parts := strings.Split(name, "|") + for i := range parts { + parts[i] = strings.TrimSpace(parts[i]) + } + if len(parts) > 2 { + parts = parts[:2] + } + return strings.Join(parts, " · ") +} + +func dateRange(start, end time.Time) string { + switch { + case end.IsZero() || start.Format("Jan 2") == end.Format("Jan 2"): + return start.Format("Jan 2") + case start.Month() == end.Month(): + return start.Format("Jan 2") + "–" + end.Format("2") + } + return start.Format("Jan 2") + " – " + end.Format("Jan 2") +} diff --git a/pkg/news_test.go b/pkg/news_test.go new file mode 100644 index 0000000..d15a344 --- /dev/null +++ b/pkg/news_test.go @@ -0,0 +1,26 @@ +package pkg + +import ( + "strings" + "testing" + "time" + + "github.com/nate-xyz/chess-cli/api" +) + +func TestNewsCacheRoundTrip(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + n := &api.News{Live: []api.Event{{Name: "Candidates 2026 | Open", Leader: "Sindarov", Live: true}}, + Blog: []api.BlogPost{{Title: "Hello", Date: time.Date(2026, 10, 21, 0, 0, 0, 0, time.UTC)}}} + saveNewsCache(newsCache{Fetched: time.Now(), News: n}) + c := loadNewsCache() + if c == nil || len(c.News.Live) != 1 || c.News.Live[0].Leader != "Sindarov" { + t.Fatalf("cache: %+v", c) + } + text := newsText(c.News) + for _, want := range []string{"LIVE", "Candidates 2026 · Open", "Sindarov", "Hello", "Oct 21"} { + if !strings.Contains(text, want) { + t.Errorf("news text missing %q:\n%s", want, text) + } + } +} diff --git a/pkg/online.go b/pkg/online.go index 423e773..7c3ac49 100644 --- a/pkg/online.go +++ b/pkg/online.go @@ -1,94 +1,183 @@ package pkg import ( + "context" "fmt" + "strings" + cv "codeberg.org/tslocum/cview" "github.com/nate-xyz/chess-cli/api" ) -func UpdateChessGame() { - Root.gameState.Game = NewChessGame +// IsWhite reports whether the logged-in user plays white in this game. +// Lichess ids are lower-case usernames, so compare case-insensitively. +func (og *OnlineGame) IsWhite() bool { + me := Root.User.Name + return strings.EqualFold(og.Full.White.ID, me) || strings.EqualFold(og.Full.White.Name, me) } -func (on *OnlineGame) doAbort() { - err := api.AbortGame(currentGameID) - if err != nil { - Root.gameState.Status += fmt.Sprintf("[red]%v[white]\n", err) - Root.ongame.UpdateStatus() - return +// opponent returns the other side of the game. +func (og *OnlineGame) opponent() api.GamePlayer { + if og.IsWhite() { + return og.Full.Black } - killGame <- "abort" + return og.Full.White } -func (on *OnlineGame) doResign() { - err := api.ResignGame(currentGameID) - if err != nil { - Root.gameState.Status += fmt.Sprintf("[red]%v[white]\n", err) - Root.ongame.UpdateStatus() - return - } - killGame <- "resign" +// background runs a Lichess call off the UI goroutine and reports a failure in +// the status panel. onOK, if set, runs on the UI goroutine after success. +func (og *OnlineGame) background(what string, call func() error, onOK func()) { + go func() { + err := call() + Root.App.QueueUpdateDraw(func() { + if err != nil { + Root.gameState.Status += fmt.Sprintf("[red]%s failed: %v[-]\n", what, err) + og.UpdateStatus() + return + } + if onOK != nil { + onOK() + } + }) + }() } -func (on *OnlineGame) doOfferDraw() { - err := api.HandleDraw(currentGameID, true) - if err != nil { - Root.gameState.Status += fmt.Sprintf("[red]%v[white]\n", err) - Root.ongame.UpdateStatus() - return - } +// The game ends through the stream (Lichess sends the final status), so these +// only send the request. +func (og *OnlineGame) doAbort() { + og.background("Abort", func() error { return api.AbortGame(currentGameID) }, nil) +} +func (og *OnlineGame) doResign() { + og.background("Resign", func() error { return api.ResignGame(currentGameID) }, nil) +} +func (og *OnlineGame) doClaimVictory() { + og.background("Claim victory", func() error { return api.ClaimVictory(currentGameID) }, nil) } -func (on *OnlineGame) doAcceptDraw() { - err := api.HandleDraw(currentGameID, true) - if err != nil { - Root.gameState.Status += fmt.Sprintf("[red]%v[white]\n", err) - on.UpdateStatus() - on.Grid.RemoveItem(on.PopUp) - return - } - on.Grid.RemoveItem(on.PopUp) +func (og *OnlineGame) doClaimDraw() { + og.background("Claim draw", func() error { return api.ClaimDraw(currentGameID) }, nil) } -func (on *OnlineGame) doRejectDraw() { - err := api.HandleDraw(currentGameID, false) - if err != nil { - Root.gameState.Status += fmt.Sprintf("[red]%v[white]\n", err) - on.UpdateStatus() - on.Grid.RemoveItem(on.PopUp) - return +func (og *OnlineGame) doOfferDraw() { + og.background("Draw offer", func() error { return api.HandleDraw(currentGameID, true) }, func() { + Root.gameState.Status += "Draw offered.\n" + og.UpdateStatus() + }) +} + +func (og *OnlineGame) doProposeTakeBack() { + og.background("Takeback", func() error { return api.HandleTakeback(currentGameID, true) }, func() { + Root.gameState.Status += "Takeback proposed.\n" + og.UpdateStatus() + }) +} + +func (og *OnlineGame) answerOffer(what string, call func() error) { + og.hidePopup() + og.popupKind = what // don't reopen for the same offer while the answer is in flight + og.background(what, call, nil) +} + +func (og *OnlineGame) doAcceptDraw() { + og.answerOffer("draw", func() error { return api.HandleDraw(currentGameID, true) }) +} +func (og *OnlineGame) doRejectDraw() { + og.answerOffer("draw", func() error { return api.HandleDraw(currentGameID, false) }) +} +func (og *OnlineGame) doAcceptTakeBack() { + og.answerOffer("takeback", func() error { return api.HandleTakeback(currentGameID, true) }) +} +func (og *OnlineGame) doRejectTakeBack() { + og.answerOffer("takeback", func() error { return api.HandleTakeback(currentGameID, false) }) +} + +// addChat appends a chat line. UI goroutine only. +func (og *OnlineGame) addChat(user, text, room string) { + name := "[blue]" + cv.Escape(user) + "[-]" + if strings.EqualFold(user, Root.User.Name) { + name = "[green]" + cv.Escape(user) + "[-]" + } else if user == "lichess" { + name = "[gray]lichess[-]" } - on.Grid.RemoveItem(on.PopUp) + if room == "spectator" { + name += " [gray](spectator)[-]" + } + fmt.Fprintf(og.Chat, "%s: %s\n", name, cv.Escape(text)) + og.Chat.ScrollToEnd() } -func (on *OnlineGame) doProposeTakeBack() { - err := api.HandleTakeback(currentGameID, true) - if err != nil { - Root.gameState.Status += fmt.Sprintf("[red]%v[white]\n", err) - on.UpdateStatus() +func (og *OnlineGame) sendChat(text string) { + text = strings.TrimSpace(text) + if text == "" { return } + gameID := currentGameID + go func() { + if err := api.WriteChat(gameID, "player", text); err != nil { + Root.App.QueueUpdateDraw(func() { + fmt.Fprintf(og.Chat, "[red]message not sent: %v[-]\n", err) + }) + } + }() } -func (on *OnlineGame) doAcceptTakeBack() { - err := api.HandleTakeback(currentGameID, true) - if err != nil { - Root.gameState.Status += fmt.Sprintf("[red]%v[white]\n", err) - on.UpdateStatus() - on.Grid.RemoveItem(on.PopUp) +// loadChatHistory shows messages sent before we connected (e.g. when resuming +// a game). New messages arrive on the game stream. +func (og *OnlineGame) loadChatHistory(ctx context.Context, gameID string) { + msgs, err := api.GetChat(gameID) + if err != nil || ctx.Err() != nil { return } - on.Grid.RemoveItem(on.PopUp) + Root.App.QueueUpdateDraw(func() { + if ctx.Err() != nil { + return + } + og.Chat.Clear() + for _, m := range msgs { + og.addChat(m.User, m.Text, "player") + } + }) } -func (on *OnlineGame) doRejectTakeBack() { - err := api.HandleTakeback(currentGameID, false) - if err != nil { - Root.gameState.Status += fmt.Sprintf("[red]%v[white]\n", err) - on.UpdateStatus() - on.Grid.RemoveItem(on.PopUp) +// rematch challenges the same opponent with the same settings and colours +// swapped (or starts a new game at the same AI level). +func (og *OnlineGame) rematch() { + f := og.Full + if f.ID == "" { return } - on.Grid.RemoveItem(on.PopUp) + c := api.CreateChallengeType{ + Variant: f.Variant.Key, + Rated: fmt.Sprint(f.Rated), + RatedBool: f.Rated, + Color: "white", + } + if og.IsWhite() { + c.Color = "black" + } + if f.Variant.Key == "fromPosition" { + c.Fen = f.InitialFen + } + switch { + case f.Speed == "correspondence": + c.TimeOption = api.TimeCorrespondence + c.Days = fmt.Sprint(max(1, f.DaysPerTurn)) + case f.Clock.Initial > 0 || f.Clock.Increment > 0: + c.TimeOption = api.TimeRealTime + c.ClockLimit = fmt.Sprint(f.Clock.Initial / 1000) + c.ClockIncrement = fmt.Sprint(f.Clock.Increment / 1000) + c.MinTurn = float64(f.Clock.Initial) / 60000 + default: + c.TimeOption = api.TimeUnlimited + } + opp := og.opponent() + if opp.AiLevel > 0 { + c.Type = 2 + c.Level = fmt.Sprint(opp.AiLevel) + } else { + c.Type = 1 + c.DestUser = opp.Name + } + startRequest(c) } diff --git a/pkg/online_test.go b/pkg/online_test.go new file mode 100644 index 0000000..b830c96 --- /dev/null +++ b/pkg/online_test.go @@ -0,0 +1,224 @@ +package pkg + +import ( + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "os" + "strings" + "sync" + "testing" + "time" + + cv "codeberg.org/tslocum/cview" + tc "github.com/gdamore/tcell/v3" + "github.com/nate-xyz/chess-cli/api" + "github.com/notnil/chess" +) + +// startTestApp runs the real UI on tcell's mock terminal. The tests share +// one app: it's left running until the test binary exits, because cview +// 1.6.3 has unsynchronised shutdown (Run clears its screen field without +// locking, and Stop finalises the screen while a draw may be running), which +// the race detector flags. That's in cview, not this code. +func startTestApp(t *testing.T, w, h int) tc.Screen { + t.Helper() + testApp.Do(func() { + dir, err := os.MkdirTemp("", "chess-cli-test") + if err != nil { + t.Fatal(err) + } + os.Setenv("XDG_CONFIG_HOME", dir) // never touch the real config + os.Chdir(dir) + testScreen = newMockScreen(t, w, h) + app := cv.NewApplication() + app.SetScreen(testScreen) + app.EnableMouse(true) + Root.App = app + InitUI() + go app.Run() + }) + waitFor(t, "first draw", func() bool { _, _, rw, _ := Root.nav.GetRect(); return rw == w }) + return testScreen +} + +var ( + testApp sync.Once + testScreen tc.Screen +) + +// onUI runs f on the UI goroutine and waits for it. +func onUI(f func()) { + done := make(chan struct{}) + Root.App.QueueUpdateDraw(func() { f(); close(done) }) + <-done +} + +func waitFor(t *testing.T, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + ok := false + onUI(func() { ok = cond() }) + if ok { + return + } + time.Sleep(20 * time.Millisecond) + } + t.Fatalf("timed out waiting for %s", what) +} + +// clickSquare clicks the centre of a square on a board. +func clickSquare(s tc.Screen, b *BoardView, sq chess.Square) { + b.mu.Lock() + r, c := displayOf(sq, b.white) + x, y := b.ox+c*b.sqW+b.sqW/2, b.oy+r*b.sqH+b.sqH/2 + b.mu.Unlock() + s.EventQ() <- tc.NewEventMouse(x, y, tc.Button1, 0) + s.EventQ() <- tc.NewEventMouse(x, y, tc.ButtonNone, 0) +} + +// fakeGame is a scripted Lichess game between Harry (white) and bob. +type fakeGame struct { + mu sync.Mutex + moves []string + chats []string + challenge url.Values + send chan string // lines to push down the game stream +} + +func (f *fakeGame) ServeHTTP(w http.ResponseWriter, r *http.Request) { + r.ParseForm() + f.mu.Lock() + defer f.mu.Unlock() + switch { + case r.URL.Path == "/api/board/game/stream/g1": + f.mu.Unlock() + fmt.Fprintln(w, `{"type":"gameFull","id":"g1","rated":false,"variant":{"key":"standard","name":"Standard"},`+ + `"clock":{"initial":300000,"increment":3000},"speed":"blitz",`+ + `"white":{"id":"harry","name":"Harry","rating":1500},"black":{"id":"bob","name":"bob","rating":1600},`+ + `"initialFen":"startpos","state":{"type":"gameState","moves":"","wtime":300000,"btime":300000,"winc":3000,"binc":3000,"status":"started"}}`) + w.(http.Flusher).Flush() + for { + select { + case line := <-f.send: + fmt.Fprintln(w, line) + w.(http.Flusher).Flush() + case <-r.Context().Done(): + f.mu.Lock() + return + } + } + case strings.HasPrefix(r.URL.Path, "/api/board/game/g1/move/"): + f.moves = append(f.moves, strings.TrimPrefix(r.URL.Path, "/api/board/game/g1/move/")) + fmt.Fprint(w, `{"ok":true}`) + case r.URL.Path == "/api/board/game/g1/chat" && r.Method == "GET": + fmt.Fprint(w, `[{"user":"bob","text":"have fun [red]"}]`) + case r.URL.Path == "/api/board/game/g1/chat": + f.chats = append(f.chats, r.PostForm.Get("text")) + fmt.Fprint(w, `{"ok":true}`) + case r.URL.Path == "/api/challenge/bob": + f.challenge = r.PostForm + fmt.Fprintln(w, `{"challenge":{"id":"rematch1"}}`) + default: + http.NotFound(w, r) + } +} + +func (f *fakeGame) state(moves, extra string) string { + return fmt.Sprintf(`{"type":"gameState","moves":%q,"wtime":290000,"btime":295000,"winc":3000,"binc":3000,"status":"started"%s}`, moves, extra) +} + +func TestOnlineGameEndToEnd(t *testing.T) { + fake := &fakeGame{send: make(chan string, 10)} + srv := httptest.NewServer(fake) + defer srv.Close() + oldHost := api.HostUrl + api.HostUrl = srv.URL + defer func() { api.HostUrl = oldHost }() + api.UserInfo = api.UserConfig{ApiToken: "test"} + + s := startTestApp(t, 160, 50) + onUI(func() { + Root.User = &Login{Name: "Harry"} + currentGameID = "g1" + startNewOnlineGame() + }) + og := Root.ongame + waitFor(t, "game to load", func() bool { return og.Full.ID == "g1" && og.Board.sqW > 0 }) + // the clocks appear beside the board (moving it down a row): wait for + // that before clicking squares + waitFor(t, "clocks", func() bool { + og.Board.mu.Lock() + defer og.Board.mu.Unlock() + return og.Board.hasClockBars() + }) + + // chat history loads, and user text can't inject colour tags + waitFor(t, "chat history", func() bool { return strings.Contains(og.Chat.GetText(true), "have fun [red]") }) + + // play e2e4 with the mouse + clickSquare(s, og.Board, chess.E2) + clickSquare(s, og.Board, chess.E4) + waitFor(t, "move sent", func() bool { + fake.mu.Lock() + defer fake.mu.Unlock() + return len(fake.moves) == 1 && fake.moves[0] == "e2e4" + }) + + // opponent replies and offers a draw (sent twice: must not stack popups) + fake.send <- fake.state("e2e4", "") + fake.send <- fake.state("e2e4 e7e5", `,"bdraw":true`) + fake.send <- fake.state("e2e4 e7e5", `,"bdraw":true`) + waitFor(t, "opponent move + draw offer", func() bool { + return len(Root.gameState.MoveHistoryArray) == 2 && og.popupKind == "draw" && og.PopUp != nil + }) + + // decline it: popup goes away and doesn't come back for the same offer + onUI(og.doRejectDraw) + waitFor(t, "popup hidden", func() bool { return og.PopUp == nil }) + + // chat + onUI(func() { og.sendChat("good luck") }) + waitFor(t, "chat sent", func() bool { + fake.mu.Lock() + defer fake.mu.Unlock() + return len(fake.chats) == 1 && fake.chats[0] == "good luck" + }) + fake.send <- `{"type":"chatLine","username":"bob","text":"you too","room":"player"}` + waitFor(t, "chat received", func() bool { return strings.Contains(og.Chat.GetText(true), "you too") }) + + // opponent leaves: claim options appear once the countdown passes + fake.send <- `{"type":"opponentGone","gone":true,"claimWinInSeconds":0}` + waitFor(t, "claim victory offered", func() bool { + for i := 0; i < og.List.GetItemCount(); i++ { + if og.List.GetItem(i).GetMainText() == "Claim Victory" { + return true + } + } + return false + }) + + // bob resigns: game over screen + fake.send <- `{"type":"gameState","moves":"e2e4 e7e5","wtime":290000,"btime":295000,"status":"resign","winner":"white"}` + waitFor(t, "post-game screen", func() bool { + name, _ := Root.nav.GetFrontPanel() + return name == "postonline" && og.ended + }) + + // rematch: same clock, colours swapped + onUI(og.rematch) + waitFor(t, "rematch challenge", func() bool { + fake.mu.Lock() + defer fake.mu.Unlock() + return fake.challenge != nil + }) + fake.mu.Lock() + c := fake.challenge + fake.mu.Unlock() + if c.Get("color") != "black" || c.Get("clock.limit") != "300" || c.Get("clock.increment") != "3" || c.Get("rated") != "false" { + t.Errorf("rematch challenge %v", c) + } + onUI(cancelLoader) +} diff --git a/pkg/online_util.go b/pkg/online_util.go deleted file mode 100644 index 16637a1..0000000 --- a/pkg/online_util.go +++ /dev/null @@ -1,83 +0,0 @@ -package pkg - -import ( - "strings" - - "github.com/nate-xyz/chess-cli/api" - "github.com/notnil/chess" -) - -func MoveTranslationToFEN(sequence string) (string, error) { - sequence_array := strings.Split(sequence, " ") - game := chess.NewGame(chess.UseNotation(chess.UCINotation{})) - if sequence != "" { - for _, move := range sequence_array { - if game.Outcome() == chess.NoOutcome { - err := game.MoveStr(move) - if err != nil { - return "", err // handle error - } - continue - } - } - } - return game.Position().String(), nil -} - -func containedInEventStream(a []api.StreamEventType, gameid string) (string, bool) { - for _, e := range a { - if e.GameID == gameid { - return e.EventType, true - } - } - return "", false -} - -func EventContainedInEventStream(a []api.StreamEventType, eventtype string) (api.StreamEventType, bool) { - for _, e := range a { - if e.EventType == eventtype { - return e, true - } - } - return api.StreamEventType{}, false -} - -// func getEvents(a []api.StreamEventType, gameid string) ([]api.StreamEventType, bool) { -// n := make([]api.StreamEventType, 0) -// for _, e := range a { -// if e.GameID == gameid { -// n = append(n, e) -// } -// } -// if len(n) > 0 { -// return n, true -// } -// return n, false -// } - -// func GameOutcome(sequence string) (string, string) { -// sequence_array := strings.Split(sequence, " ") -// game := chess.NewGame(chess.UseNotation(chess.UCINotation{})) - -// for _, move := range sequence_array { -// if game.Outcome() == chess.NoOutcome { -// err := game.MoveStr(move) -// if err != nil { -// // handle error -// //fmt.Printf("%v\n", err) -// return "", "" -// } -// continue -// } -// } -// outcome_str := fmt.Sprintf("Game completed. %s by %s.", game.Outcome(), game.Method()) -// var name_str string -// if game.Outcome()[0] == '1' { -// name_str = fmt.Sprintf("White (%s) wins.", api.BoardFullGame.White.Name) -// } -// if game.Outcome()[0] == '0' { -// name_str = fmt.Sprintf("Black (%s) wins.", api.BoardFullGame.Black.Name) -// } - -// return outcome_str, name_str -// } diff --git a/pkg/pgn.go b/pkg/pgn.go new file mode 100644 index 0000000..fee7ca1 --- /dev/null +++ b/pkg/pgn.go @@ -0,0 +1,646 @@ +package pkg + +import ( + "fmt" + "image/color" + "regexp" + "strconv" + "strings" + "unicode" + + tc "github.com/gdamore/tcell/v3" + "github.com/notnil/chess" +) + +// Reading annotated PGN, as Lichess exports studies: several games +// (chapters), each a tree of moves with variations, comments, move and +// position symbols ($1, !?), and the arrows and circles drawn in the study +// ([%cal Ge2e4] and [%csl Rd5] inside comments). + +// studyNode is a move in a chapter's tree (or the start, for the root). +type studyNode struct { + id int + move *chess.Move // nil at the root + san string + pos *chess.Position // the position after the move + parent *studyNode + children []*studyNode // [0] continues the line; the rest are variations + comment string + nags []int + shapes []boardShape + ply int // half-moves from the chapter's start position +} + +// studyChapter is one game of the PGN. +type studyChapter struct { + headers map[string]string + root *studyNode + nodes []*studyNode // by id + white bool // white at the bottom (the study's orientation) + problem string // the first move that couldn't be read, if any +} + +// name is the chapter's title: Lichess's ChapterName, or the Event. +func (c *studyChapter) name() string { + if n := c.headers["ChapterName"]; n != "" { + return n + } + ev := c.headers["Event"] + if _, after, ok := strings.Cut(ev, ": "); ok && c.headers["StudyName"] != "" { + return after + } + if ev == "" || ev == "?" { + return "Chapter" + } + return ev +} + +// studyName is the study's name: Lichess's StudyName, or the Event, which +// Lichess writes as "Study name: Chapter name". +func (c *studyChapter) studyName() string { + if n := c.headers["StudyName"]; n != "" { + return n + } + ev, ch := c.headers["Event"], c.headers["ChapterName"] + if ch != "" && strings.HasSuffix(ev, ": "+ch) { + return strings.TrimSuffix(ev, ": "+ch) + } + return "" +} + +// chapterID is Lichess's ID for the chapter (from its link), or "". +func (c *studyChapter) chapterID() string { + u := strings.TrimRight(c.headers["ChapterURL"], "/") + if i := strings.LastIndex(u, "/"); i >= 0 { + return u[i+1:] + } + return "" +} + +// parseStudyPGN reads every game in a PGN text. +func parseStudyPGN(text string) []*studyChapter { + p := &pgnParser{src: []rune(text)} + p.run() + return p.chapters +} + +type pgnParser struct { + src []rune + i int + chapters []*studyChapter + + c *studyChapter + moves bool // the current chapter's movetext has started + cur *studyNode // the last move read (or the root) + broken bool // a move in this line couldn't be read: skip to the line's end + stack []pgnFrame +} + +type pgnFrame struct { + cur *studyNode + broken bool +} + +func (p *pgnParser) run() { + for p.i < len(p.src) { + r := p.src[p.i] + switch { + case unicode.IsSpace(r): + p.i++ + case r == '[': + if p.c == nil || p.moves { + p.startChapter() + } + p.header() + case r == '{': + p.need() + p.moves = true + end := p.until('}') + p.addComment(string(p.src[p.i+1 : end])) + p.i = end + 1 + case r == ';': + p.need() + p.moves = true + end := p.until('\n') + p.addComment(string(p.src[p.i+1 : end])) + p.i = end + 1 + case r == '(': + p.need() + p.moves = true + p.i++ + p.stack = append(p.stack, pgnFrame{p.cur, p.broken}) + if p.cur.parent != nil { // the variation replaces the last move + p.cur = p.cur.parent + } else { + p.broken = true // a variation before any move: not valid + } + case r == ')': + p.i++ + if n := len(p.stack); n > 0 { + p.cur, p.broken = p.stack[n-1].cur, p.stack[n-1].broken + p.stack = p.stack[:n-1] + } + case r == '$': + p.need() + p.moves = true + start := p.i + 1 + p.i = start + for p.i < len(p.src) && unicode.IsDigit(p.src[p.i]) { + p.i++ + } + if n, err := strconv.Atoi(string(p.src[start:p.i])); err == nil && !p.broken { + p.cur.nags = append(p.cur.nags, n) + } + default: + p.need() + p.moves = true + start := p.i + for p.i < len(p.src) && !unicode.IsSpace(p.src[p.i]) && !strings.ContainsRune("(){}[];$", p.src[p.i]) { + p.i++ + } + p.token(string(p.src[start:p.i])) + } + } +} + +// until finds the next r from the current position (or the end). +func (p *pgnParser) until(r rune) int { + for j := p.i + 1; j < len(p.src); j++ { + if p.src[j] == r { + return j + } + } + return len(p.src) +} + +// need starts a chapter if movetext comes without headers. +func (p *pgnParser) need() { + if p.c == nil { + p.startChapter() + } +} + +func (p *pgnParser) startChapter() { + p.c = &studyChapter{headers: map[string]string{}, white: true} + p.chapters = append(p.chapters, p.c) + p.moves, p.broken, p.stack = false, false, nil + p.c.root = p.newNode(nil, "", chess.StartingPosition(), nil) + p.cur = p.c.root +} + +func (p *pgnParser) newNode(m *chess.Move, san string, pos *chess.Position, parent *studyNode) *studyNode { + n := &studyNode{id: len(p.c.nodes), move: m, san: san, pos: pos, parent: parent} + if parent != nil { + n.ply = parent.ply + 1 + parent.children = append(parent.children, n) + } + p.c.nodes = append(p.c.nodes, n) + return n +} + +// header reads [Key "Value"]. +func (p *pgnParser) header() { + end := p.i + 1 + inQuote := false + for ; end < len(p.src); end++ { + switch c := p.src[end]; { + case c == '\\' && inQuote: + end++ + case c == '"': + inQuote = !inQuote + case c == ']' && !inQuote: + goto done + } + } +done: + body := strings.TrimSpace(string(p.src[p.i+1 : min(end, len(p.src))])) + p.i = end + 1 + key, value, _ := strings.Cut(body, " ") + value = strings.TrimSpace(value) + value = strings.TrimSuffix(strings.TrimPrefix(value, `"`), `"`) + value = strings.ReplaceAll(strings.ReplaceAll(value, `\"`, `"`), `\\`, `\`) + p.c.headers[key] = value + switch key { + case "FEN": + if opt, err := chess.FEN(value); err == nil { + p.c.root.pos = chess.NewGame(opt).Position() + } else { + p.c.problem = "the chapter's start position (FEN) isn't valid" + } + case "Orientation": + p.c.white = value != "black" + } +} + +// moveGlyphs are move symbols written after the move, as NAGs. +var moveGlyphs = map[string]int{"!": 1, "?": 2, "!!": 3, "??": 4, "!?": 5, "?!": 6} + +func (p *pgnParser) token(tok string) { + switch tok { + case "1-0", "0-1", "1/2-1/2", "½-½", "*": + return + } + // move numbers: "12." "12..." or glued to the move, "12...e5" + tok = strings.TrimLeft(tok, "0123456789") + tok = strings.TrimLeft(tok, ".…") + if tok == "" || p.broken { + return + } + san := strings.TrimRight(tok, "!?") + glyph := tok[len(san):] + san = strings.TrimRight(san, "+#") + san = strings.ReplaceAll(san, "0-0", "O-O") + if san == "--" || san == "Z0" { // a null move: can't be followed + p.problem(tok) + return + } + m, err := chess.AlgebraicNotation{}.Decode(p.cur.pos, san) + if err != nil { + p.problem(tok) + return + } + // reuse a move already there (a repeated variation) + for _, ch := range p.cur.children { + if ch.move.String() == m.String() { + p.cur = ch + p.addGlyph(glyph) + return + } + } + p.cur = p.newNode(m, chess.AlgebraicNotation{}.Encode(p.cur.pos, m), p.cur.pos.Update(m), p.cur) + p.addGlyph(glyph) +} + +func (p *pgnParser) addGlyph(g string) { + if n, ok := moveGlyphs[g]; ok { + p.cur.nags = append(p.cur.nags, n) + } +} + +func (p *pgnParser) problem(tok string) { + p.broken = true + if p.c.problem == "" { + p.c.problem = fmt.Sprintf("couldn't follow the move %q (after %s)", tok, describeNode(p.cur)) + } +} + +func describeNode(n *studyNode) string { + if n.move == nil { + return "the start" + } + return moveLabel(n) +} + +// moveLabel is a move with its number, e.g. "12... Nf6". +func moveLabel(n *studyNode) string { + num := moveNumber(n.parent.pos) + if n.parent.pos.Turn() == chess.White { + return fmt.Sprintf("%d. %s", num, n.san) + } + return fmt.Sprintf("%d... %s", num, n.san) +} + +// addComment attaches a comment to the last move (or the chapter start), +// taking out the drawing commands. +func (p *pgnParser) addComment(text string) { + if p.broken { + return + } + text, shapes := commentShapes(text) + p.cur.shapes = append(p.cur.shapes, shapes...) + text = strings.Join(strings.Fields(text), " ") + if text == "" { + return + } + if p.cur.comment != "" { + p.cur.comment += " " + } + p.cur.comment += text +} + +// commentShapes takes the [%...] commands out of a comment, returning the +// text left and the arrows (%cal) and circles (%csl) drawn. +func commentShapes(text string) (string, []boardShape) { + var shapes []boardShape + var rest strings.Builder + for { + i := strings.Index(text, "[%") + if i < 0 { + rest.WriteString(text) + break + } + rest.WriteString(text[:i]) + end := strings.IndexByte(text[i:], ']') + if end < 0 { + break + } + cmd := strings.Fields(text[i+2 : i+end]) + text = text[i+end+1:] + if len(cmd) < 2 || (cmd[0] != "cal" && cmd[0] != "csl") { + continue // %clk, %eval, %emt... + } + for _, spec := range strings.Split(cmd[1], ",") { + if s, ok := parseShape(spec, cmd[0] == "cal"); ok { + shapes = append(shapes, s) + } + } + } + return rest.String(), shapes +} + +var shapeColorCodes = map[byte]int{'G': 0, 'R': 1, 'B': 2, 'Y': 3} + +// parseShape reads "Ge2e4" (arrow) or "Rd5" (circle). +func parseShape(spec string, arrow bool) (boardShape, bool) { + spec = strings.TrimSpace(spec) + if len(spec) < 3 { + return boardShape{}, false + } + color, ok := shapeColorCodes[spec[0]] + if !ok { + return boardShape{}, false + } + from, ok1 := parseSquare(spec[1:3]) + to := from + ok2 := true + if arrow { + if len(spec) < 5 { + return boardShape{}, false + } + to, ok2 = parseSquare(spec[3:5]) + } + return boardShape{from: from, to: to, color: color}, ok1 && ok2 +} + +func parseSquare(s string) (chess.Square, bool) { + if len(s) != 2 || s[0] < 'a' || s[0] > 'h' || s[1] < '1' || s[1] > '8' { + return chess.NoSquare, false + } + return chess.Square(int(s[1]-'1')*8 + int(s[0]-'a')), true +} + +// nagText is how a NAG is shown: move symbols right after the move, +// position symbols after a space. +func nagText(n int) (string, bool) { + switch n { + case 1: + return "!", true + case 2: + return "?", true + case 3: + return "!!", true + case 4: + return "??", true + case 5: + return "!?", true + case 6: + return "?!", true + case 7: + return "□", true + case 22: + return "⨀", true + } + // Lichess's position and observation symbols + pos := map[int]string{10: "=", 13: "∞", 14: "⩲", 15: "⩱", 16: "±", 17: "∓", 18: "+−", 19: "−+", + 32: "↑↑", 36: "↑", 40: "→", 44: "=∞", 132: "⇆", 138: "⊕", 140: "∆", 146: "N"}[n] + return pos, false +} + +// tagLike matches what cview would read as a colour or region tag. +var tagLike = regexp.MustCompile(`(\[(?:[a-zA-Z]+|#[0-9a-zA-Z]{6}|-)?(?::(?:[a-zA-Z]+|#[0-9a-zA-Z]{6}|-)?(?::(?:[bdilrsu]+|-)?)?)?|\["[a-zA-Z0-9_,;: \-.]*")\]`) + +// escapeText escapes text for a cview text view. Unlike cview.Escape it +// leaves other bracketed text alone: "[11...dxe5 12. dxe5]" isn't a tag, and +// escaping it breaks when the line wraps inside it. +func escapeText(s string) string { + return tagLike.ReplaceAllStringFunc(s, func(m string) string { + if m == "[]" { + return "[ ]" + } + return m[:len(m)-1] + "[]" + }) +} + +// tint styles text lines (not the indent): the current move's comment gets +// a faint background, the side lines that branch off at it are underlined. +// Each line is styled on its own, +// so the colour never runs past the end of a line. +func tint(text string, on bool, style string) string { + if !on || uiLimited() { // dark tints are all black on a limited terminal + return text + } + lines := strings.Split(text, "\n") + for i, l := range lines { + body := strings.TrimLeft(l, " ") + if body != "" { + lines[i] = l[:len(l)-len(body)] + style + body + styleReset[style] + } + } + return strings.Join(lines, "\n") +} + +// Colours in the move list. +const ( + pgnVariation = "[#a0a0a0]" + pgnComment = "[#8fbf8f]" + tintComment = "[:#1e2a1e]" // faint green behind the current move's comment +) + +// styleReset undoes a tint style. +var styleReset = map[string]string{tintComment: "[:-]"} + +// underlineTags underline the side lines branching off at the current move, +// heavier the deeper they're nested: solid, dashed, dotted, double, curly. +// cview only knows a plain underline, so levels past the first are marked +// with blink (never used otherwise) plus strikethrough/italic, which +// underlineScreen turns into the terminal's underline styles. +var underlineTags = []string{"[::u]", "[::ul]", "[::uls]", "[::uli]", "[::ulis]"} + +// underlineBranch underlines a side line written at depth (its own lines, +// nested lines one level heavier for each level of nesting; a comment goes +// with the line it belongs to). +func underlineBranch(text string, depth int) string { + lines := strings.Split(text, "\n") + for i, l := range lines { + body := strings.TrimLeft(l, " ") + if body == "" { + continue + } + level := (len(l)-len(body))/2 - depth + if strings.HasPrefix(body, pgnComment) { // comments are indented one more + level-- + } + tag := underlineTags[max(0, min(level, len(underlineTags)-1))] + lines[i] = l[:len(l)-len(body)] + tag + body + "[::-]" + } + return strings.Join(lines, "\n") +} + +// colCurrentMove is behind the move showing, in every move list. +var colCurrentMove = tc.NewHexColor(0x3a3a3a) + +// studyMoveText is a chapter's moves for the sidebar, Lichess style: the +// main line flows; a comment or variations break it, each on its own +// indented line. Every move is a region, n, for clicking. +// +// cur is the move showing: its comment and the side lines that branch off +// at it are tinted, so you can see what the board is talking about. +func studyMoveText(c *studyChapter, cur *studyNode) string { + var b strings.Builder + if c.root.comment != "" { + b.WriteString(tint(pgnComment+escapeText(c.root.comment)+"[-]\n", cur == c.root, tintComment)) + } + if len(c.root.children) > 0 { + writeLine(&b, c.root.children[0], c.root.children[1:], 0, "", cur) + } + if len(c.root.children) == 0 && c.root.comment == "" { + b.WriteString("[#a0a0a0]No moves in this chapter.[-]") + } + if score, how := chapterResult(c); score != "" { + b.WriteString("\n[::b]" + score + "[::-]\n[#a0a0a0]" + escapeText(how) + "[-]\n") + } + return b.String() +} + +// chapterResult is how the chapter's game ended, as Lichess shows it under +// the moves: the score ("1–0") and e.g. "Checkmate • White is victorious". +// From the Result and Termination tags and the main line's final position; +// "" if the game isn't over (or the result is unknown). +func chapterResult(c *studyChapter) (score, how string) { + line := c.root.line() + end := line[len(line)-1].pos + result := c.tag("Result") + reason := "" + switch end.Status() { + case chess.Checkmate: + reason = "Checkmate" + if result == "" { + result = map[chess.Color]string{chess.White: "0-1", chess.Black: "1-0"}[end.Turn()] + } + case chess.Stalemate: + reason, result = "Stalemate", "1/2-1/2" + } + if reason == "" { + switch strings.ToLower(c.tag("Termination")) { + case "time forfeit": + reason = "Time out" + case "abandoned": + reason = "Abandoned" + case "rules infraction": + reason = "Rules infraction" + case "adjudication": + reason = "Adjudicated" + case "stalemate": + reason = "Stalemate" + case "insufficient material": + reason = "Insufficient material" + } + } + var winner string + switch result { + case "1-0": + score, winner = "1–0", "White is victorious" + case "0-1": + score, winner = "0–1", "Black is victorious" + case "1/2-1/2", "½-½": + score, winner = "½–½", "Draw" + default: + return "", "" + } + if reason != "" { + return score, reason + " • " + winner + } + return score, winner +} + +// writeLine writes the line starting with move n (and its continuation), +// where alts are n's alternatives, written as variations after it. open +// starts the line ("(" for a variation). +func writeLine(b *strings.Builder, n *studyNode, alts []*studyNode, depth int, open string, cur *studyNode) { + color := "" + if depth > 0 { + color = pgnVariation + } + indent := strings.Repeat(" ", depth) + needNumber := true // a black move needs "12..." after a break + b.WriteString(indent + color + open + "[-]") + for n != nil { + white := n.parent.pos.Turn() == chess.White + switch { + case white: + fmt.Fprintf(b, "%s%d.[-] ", color, moveNumber(n.parent.pos)) + case needNumber: + fmt.Fprintf(b, "%s%d...[-] ", color, moveNumber(n.parent.pos)) + } + needNumber = false + fmt.Fprintf(b, `%s["n%d"]%s%s[""][-] `, color, n.id, n.san, nagSuffix(n, color)) + var next *studyNode + var nextAlts []*studyNode + if len(n.children) > 0 { + next, nextAlts = n.children[0], n.children[1:] + } + if n.comment != "" || len(alts) > 0 { + b.WriteString("\n") + if n.comment != "" { + b.WriteString(tint(indent+" "+pgnComment+escapeText(n.comment)+"[-]\n", n == cur, tintComment)) + } + for _, a := range alts { + var sub strings.Builder + writeLine(&sub, a, nil, depth+1, "(", cur) + branch := strings.TrimRight(sub.String(), " \n") + pgnVariation + ")[-]\n" + if n == cur { + branch = underlineBranch(branch, depth+1) + } + b.WriteString(branch) + } + if next != nil { + b.WriteString(indent) + } + needNumber = true + } + n, alts = next, nextAlts + } + if !strings.HasSuffix(b.String(), "\n") { + b.WriteString("\n") + } +} + +// nagSuffix is the symbols shown after a move, the move symbols in their +// Lichess colours; lineColor is the line's colour tag to go back to ("" = none). +func nagSuffix(n *studyNode, lineColor string) string { + var move, pos string + for _, x := range n.nags { + t, isMove := nagText(x) + switch { + case isMove && glyphColors[moveGlyph(x)] != (color.NRGBA{}): + c := glyphColors[moveGlyph(x)] + back := lineColor + if back == "" { + back = "[-]" + } + move += fmt.Sprintf("[#%02x%02x%02x]%s%s", c.R, c.G, c.B, t, back) + case isMove: + move += t + case t != "": + pos += " " + t + } + } + return move + pos +} + +// line is the path from the root to n, continued along the main line of +// what follows n to its end. +func (n *studyNode) line() []*studyNode { + var path []*studyNode + for x := n; x != nil; x = x.parent { + path = append(path, x) + } + for i, j := 0, len(path)-1; i < j; i, j = i+1, j-1 { + path[i], path[j] = path[j], path[i] + } + for x := n; len(x.children) > 0; { + x = x.children[0] + path = append(path, x) + } + return path +} diff --git a/pkg/pgn_test.go b/pkg/pgn_test.go new file mode 100644 index 0000000..aa1be0b --- /dev/null +++ b/pkg/pgn_test.go @@ -0,0 +1,211 @@ +package pkg + +import ( + "regexp" + "strings" + "testing" + + "github.com/notnil/chess" +) + +// A Lichess study export: two chapters, variations, comments, symbols, +// drawings, a chapter from a position, and a chapter with a bad move. +const testStudyPGN = `[Event "Openings: Italian"] +[Site "https://lichess.org/study/abcd1234/ch000001"] +[Result "*"] +[StudyName "Openings"] +[ChapterName "Italian"] +[ChapterURL "https://lichess.org/study/abcd1234/ch000001"] +[Orientation "black"] + +{ The Italian Game. [%csl Ge4] } +1. e4 e5 2. Nf3 { Attacks e5. [%cal Gf3e5,Rb8c6] } 2... Nc6 (2... d6 { Philidor } 3. d4 (3. Bc4) 3... Nf6) 3. Bc4!? $14 Bc5 (3... Nf6?! 4. Ng5) * + +[Event "Openings: Endgame"] +[ChapterName "Endgame"] +[FEN "8/8/8/4k3/8/8/4P3/4K3 w - - 0 1"] +[SetUp "1"] + +1. Kd2 Kd4 2. e3+ Ke4 * + +[Event "Openings: Broken"] +[ChapterName "Broken"] + +1. e4 e5 2. Ke3 Nc6 3. d4 * +` + +func TestParseStudyPGN(t *testing.T) { + chs := parseStudyPGN(testStudyPGN) + if len(chs) != 3 { + t.Fatalf("got %d chapters, want 3", len(chs)) + } + c := chs[0] + if c.name() != "Italian" || c.chapterID() != "ch000001" || c.white { + t.Errorf("chapter: name %q id %q white %v", c.name(), c.chapterID(), c.white) + } + if c.problem != "" { + t.Errorf("unexpected problem: %s", c.problem) + } + if c.root.comment != "The Italian Game." || len(c.root.shapes) != 1 || c.root.shapes[0] != (boardShape{chess.E4, chess.E4, 0}) { + t.Errorf("root comment %q shapes %v", c.root.comment, c.root.shapes) + } + // main line + var main []string + for _, n := range c.root.line()[1:] { + main = append(main, n.san) + } + if got := strings.Join(main, " "); got != "e4 e5 Nf3 Nc6 Bc4 Bc5" { + t.Errorf("main line = %q", got) + } + nf3 := c.root.children[0].children[0].children[0] + if nf3.comment != "Attacks e5." || len(nf3.shapes) != 2 || nf3.shapes[1] != (boardShape{chess.B8, chess.C6, 1}) { + t.Errorf("Nf3 comment %q shapes %v", nf3.comment, nf3.shapes) + } + // 2... d6 is a variation of 2... Nc6, with its own variation 3. Bc4 + if len(nf3.children) != 2 || nf3.children[1].san != "d6" { + t.Fatalf("variations after Nf3: %v", nf3.children) + } + d6 := nf3.children[1] + if d6.comment != "Philidor" || len(d6.children) != 2 { + t.Fatalf("d6: comment %q, %d continuations (want 3. d4 and 3. Bc4)", d6.comment, len(d6.children)) + } + if d4, alt := d6.children[0], d6.children[1]; d4.san != "d4" || alt.san != "Bc4" || d4.children[0].san != "Nf6" { + t.Errorf("after 2... d6: %q (then %q), alternative %q", d4.san, d4.children[0].san, alt.san) + } + bc4 := nf3.children[0].children[0] + if bc4.san != "Bc4" || plainTags(nagSuffix(bc4, "")) != "!? ⩲" { + t.Errorf("Bc4 %q nags %q", bc4.san, plainTags(nagSuffix(bc4, ""))) + } + if alt := bc4.children[1]; alt.san != "Nf6" || plainTags(nagSuffix(alt, "")) != "?!" || alt.children[0].san != "Ng5" { + t.Errorf("3... Nf6?! line wrong") + } + + // chapter from a position + e := chs[1] + if e.name() != "Endgame" || !e.white || e.problem != "" { + t.Errorf("endgame: %q white %v problem %q", e.name(), e.white, e.problem) + } + if line := e.root.line(); len(line) != 5 || line[3].san != "e3+" { + t.Errorf("endgame line: %d moves", len(line)-1) + } + + // a move that can't be played: the chapter keeps what came before + b := chs[2] + if !strings.Contains(b.problem, `"Ke3"`) || len(b.root.line()) != 3 { + t.Errorf("broken chapter: problem %q, %d moves", b.problem, len(b.root.line())-1) + } +} + +func TestStudyMoveText(t *testing.T) { + c := parseStudyPGN(testStudyPGN)[0] + text := studyMoveText(c, nil) + for _, want := range []string{ + "The Italian Game.", + `["n1"]e4[""]`, + "Attacks e5.", + `(`, "Philidor", + `["n5"]d6[""]`, + "3...", + `Bc4[#ea45d8]!?[-] ⩲[""]`, // "interesting", in Lichess's pink + } { + if !strings.Contains(text, want) { + t.Errorf("missing %q in:\n%s", want, text) + } + } + if strings.Contains(text, "%cal") || strings.Contains(text, "%csl") { + t.Error("drawing commands left in the text") + } + t.Log("\n" + text) +} + +func TestEscapeText(t *testing.T) { + for in, want := range map[string]string{ + "[11...dxe5 12. dxe5 Nd7 13. c4 holds the advantage]": "[11...dxe5 12. dxe5 Nd7 13. c4 holds the advantage]", + "[red]": "[red[]", + "[#ff0000]": "[#ff0000[]", + `["region"]`: `["region"[]`, + "plain (text)": "plain (text)", + } { + if got := escapeText(in); got != want { + t.Errorf("escapeText(%q) = %q, want %q", in, got, want) + } + } +} + +func TestStudyCommentEscapes(t *testing.T) { + c := parseStudyPGN(`1. e4 { see [this] [%clk 0:01:00] } *`)[0] + if c.root.children[0].comment != "see [this]" { + t.Errorf("comment = %q", c.root.children[0].comment) + } + if text := studyMoveText(c, nil); !strings.Contains(text, "see [this[]") { + t.Errorf("comment brackets not escaped:\n%s", text) + } +} + +func TestStudyName(t *testing.T) { + c := parseStudyPGN(`[Event "My 60 Memorable Games: Fischer - Sherwin: Too little, too late"] +[ChapterName "Fischer - Sherwin: Too little, too late"] + +1. e4 *`)[0] + if c.studyName() != "My 60 Memorable Games" || c.name() != "Fischer - Sherwin: Too little, too late" { + t.Errorf("study %q, chapter %q", c.studyName(), c.name()) + } +} + +var colourTag = regexp.MustCompile(`\[(#[0-9a-f]{6}|-)\]`) + +// plainTags drops colour tags. +func plainTags(s string) string { return colourTag.ReplaceAllString(s, "") } + +func TestGlyphs(t *testing.T) { + if glyphOf([]int{14, 4, 1}) != 4 || glyphOf([]int{14, 138}) != 14 || glyphOf([]int{999}) != 0 { + t.Error("glyphOf: the first move symbol, else the first other symbol") + } + for _, g := range boardGlyphs { + img := glyphImage(g, 40) + c := img.RGBAAt(20, 3) // the disc's top edge: the glyph's colour + want := g.color() + if c.R != want.R || c.G != want.G || c.B != want.B { + t.Errorf("%s badge colour %v, want %v", g.text(), c, want) + } + white := 0 + for y := 0; y < 40; y++ { + for x := 0; x < 40; x++ { + if p := img.RGBAAt(x, y); p.R > 200 && p.G > 200 && p.B > 200 { + white++ + } + } + } + if white < 20 { + t.Errorf("%s badge has no symbol drawn (%d white pixels)", g.text(), white) + } + } +} + +// The current move's comment and its side lines get different tints. +func TestStudyTints(t *testing.T) { + c := parseStudyPGN(testStudyPGN)[0] + atNf3 := studyMoveText(c, c.nodes[3]) // 2. Nf3 has a comment + if !strings.Contains(atNf3, tintComment+" Attacks e5.") && !strings.Contains(atNf3, tintComment+pgnComment+"Attacks e5.") { + t.Errorf("comment not tinted:\n%s", atNf3) + } + if strings.Contains(atNf3, "[::u") { + t.Error("no side lines branch at 2. Nf3, but some are tinted") + } + atNc6 := studyMoveText(c, c.nodes[4]) // 2... d6 branches off at 2... Nc6 + if !strings.Contains(atNc6, "[::u]"+pgnVariation+"(") || strings.Contains(atNc6, tintComment) { + t.Errorf("side lines not tinted (or a comment wrongly is):\n%s", atNc6) + } +} + +func TestUnderlineLevels(t *testing.T) { + // a side line at depth 1 with lines nested 1-5 levels deeper + text := " (a\n (b)\n (c)\n (d)\n (e)\n (f)\n " + pgnComment + "note)\n" + got := strings.Split(underlineBranch(text, 1), "\n") + want := []string{"[::u](a", "[::ul](b)", "[::uls](c)", "[::uli](d)", "[::ulis](e)", "[::ulis](f)", "[::u]" + pgnComment + "note)"} + for i, w := range want { + if !strings.Contains(got[i], w) { + t.Errorf("line %d = %q, want %q", i, got[i], w) + } + } +} diff --git a/pkg/prefs.go b/pkg/prefs.go new file mode 100644 index 0000000..e97438f --- /dev/null +++ b/pkg/prefs.go @@ -0,0 +1,82 @@ +package pkg + +import ( + "fmt" + + "github.com/nate-xyz/chess-cli/api" +) + +// Display preferences from Options. + +// clockBarsOn: clocks as a bar beside the board (else plain text in the sidebar). +func clockBarsOn() bool { return !api.UserInfo.ClockBarOff } + +// zenMode hides distractions in games, like Lichess's zen mode: names, +// ratings, chat and game info. The board, clocks and moves stay. +func zenMode() bool { return api.UserInfo.Zen } + +func setClockBars(on bool) { + _ = api.UpdateConfig(func(c *api.UserConfig) { c.ClockBarOff = !on }) + applyLayoutPrefs() +} + +func setZen(on bool) { + _ = api.UpdateConfig(func(c *api.UserConfig) { c.Zen = on }) + applyLayoutPrefs() +} + +// applyLayoutPrefs shows or hides the parts of the game screens these +// settings affect. Called when a setting changes and when a screen opens. +func applyLayoutPrefs() { + if og := Root.ongame; og != nil && og.Side != nil { + chat, input := 2, 1 + if zenMode() { + chat, input = 0, 0 + } + og.Side.ResizeItem(og.Chat, 0, chat) + og.Side.ResizeItem(og.ChatInput, input, 0) + timer := 0 + if !clockBarsOn() { + timer = 1 + og.Board.HideClockBars() + } + og.Side.ResizeItem(og.OppTimer, timer, 0) + og.Side.ResizeItem(og.UserTimer, timer, 0) + if Root.gameState != nil && og.Full.ID != "" { // a game is loaded + og.UpdateUserInfo() + og.UpdateStatus() + } + } + if ws := Root.watch; ws != nil && ws.Side != nil { + timer := 0 + if !clockBarsOn() { + timer = 1 + } + ws.Side.ResizeItem(ws.TopClock, timer, 0) + ws.Side.ResizeItem(ws.BotClock, timer, 0) + ws.updateInfo() + ws.updateClocks() + } +} + +// timeControlText describes a time control: "10+5", "½+0", +// "Correspondence · 3 days", "∞ Unlimited". Times in seconds. +func timeControlText(initial, increment int, speed string, days int) string { + switch { + case speed == "correspondence" || days > 0: + if days == 1 { + return "Correspondence · 1 day" + } + if days > 1 { + return fmt.Sprintf("Correspondence · %d days", days) + } + return "Correspondence" + case speed == "unlimited" || initial == 0 && increment == 0: + return "∞ Unlimited" + } + minutes := map[int]string{15: "¼", 30: "½", 45: "¾", 90: "1½"}[initial] + if minutes == "" { + minutes = fmt.Sprint(initial / 60) + } + return fmt.Sprintf("%s+%d", minutes, increment) +} diff --git a/pkg/prefs_test.go b/pkg/prefs_test.go new file mode 100644 index 0000000..50dd47e --- /dev/null +++ b/pkg/prefs_test.go @@ -0,0 +1,167 @@ +package pkg + +import ( + "strings" + "testing" + + cv "codeberg.org/tslocum/cview" + tc "github.com/gdamore/tcell/v3" + "github.com/nate-xyz/chess-cli/api" + "github.com/notnil/chess" +) + +func TestTimeControlText(t *testing.T) { + for _, c := range []struct { + initial, inc int + speed string + days int + want string + }{ + {600, 5, "rapid", 0, "10+5"}, + {180, 2, "blitz", 0, "3+2"}, + {30, 0, "ultraBullet", 0, "½+0"}, + {0, 0, "correspondence", 3, "Correspondence · 3 days"}, + {0, 0, "correspondence", 1, "Correspondence · 1 day"}, + {0, 0, "unlimited", 0, "∞ Unlimited"}, + } { + if got := timeControlText(c.initial, c.inc, c.speed, c.days); got != c.want { + t.Errorf("timeControlText(%d, %d, %q, %d) = %q, want %q", c.initial, c.inc, c.speed, c.days, got, c.want) + } + } +} + +// Changing display options with no game loaded must be safe. +func TestApplyLayoutPrefsWithoutGame(t *testing.T) { + startTestApp(t, 160, 50) + onUI(func() { + setZen(true) + setClockBars(false) + setZen(false) + setClockBars(true) + }) +} + +func TestRandomQuoteNeverEmpty(t *testing.T) { + for i := 0; i < 500; i++ { + if GetRandomQuote() == "" { + t.Fatal("empty quote") + } + } +} + +// Reset all settings: defaults everywhere, the login kept, and the +// first-run setup shown again. +func TestResetSettings(t *testing.T) { + startTestApp(t, 160, 50) + onUI(func() { + _ = api.UpdateConfig(func(c *api.UserConfig) { + c.ApiToken, c.Zen, c.Sound, c.MoveBoxAlways, c.Pieces, c.SoundAsked = "tok", true, SoundWood, true, PiecesBasic, true + }) + resetSettings() + }) + onUI(func() { + defer func() { + _ = api.UpdateConfig(func(c *api.UserConfig) { *c = api.UserConfig{Pieces: PiecesText, SoundAsked: true} }) + }() + c := api.UserInfo + if c.ApiToken != "tok" { + t.Error("reset lost the login") + } + if c.Zen || c.Sound != "" || c.MoveBoxAlways || c.Pieces != "" || c.SoundAsked { + t.Errorf("settings not reset: %+v", c) + } + if shownPanel() != "onboard" || Root.App.GetFocus() != onboardList { + t.Errorf("after reset: on %s, want the first-run setup", shownPanel()) + } + gotoWelcome() + }) +} + +// First-run setup offers Stockfish when there's none, once. +func TestOnboardingOffersStockfish(t *testing.T) { + scr := startTestApp(t, 160, 50) + if findEngine() != "" { + t.Skip("Stockfish is installed here: the step is skipped") + } + onUI(func() { + _ = api.UpdateConfig(func(c *api.UserConfig) { + c.Pieces, c.SoundAsked, c.KeysAsked, c.StockfishAsked = PiecesText, true, true, false + }) + runOnboarding() + }) + waitFor(t, "the Stockfish question", func() bool { + return shownPanel() == "onboard" && onboardList.GetItemCount() == 3 && + strings.HasPrefix(onboardList.GetItem(0).GetMainText(), "Download Stockfish") + }) + press(scr, tc.KeyRune, "3") // Not now + waitFor(t, "home", func() bool { return shownPanel() == "welcome" }) + onUI(func() { + if !api.UserInfo.StockfishAsked { + t.Error("not remembered as asked") + } + if needsOnboarding() { + t.Error("setup would show again") + } + }) +} + +// First-run setup asks arrows or hjkl; arrows only frees h j k l: the +// board ignores them, lists don't move on them, and the ribbons stop +// mentioning them. +func TestOnboardingKeys(t *testing.T) { + scr := startTestApp(t, 160, 50) + defer onUI(func() { setVimKeys(true) }) + onUI(func() { + _ = api.UpdateConfig(func(c *api.UserConfig) { + c.Pieces, c.SoundAsked, c.KeysAsked, c.StockfishAsked = PiecesText, true, false, true + }) + runOnboarding() + }) + waitFor(t, "the keys question", func() bool { + return shownPanel() == "onboard" && strings.HasPrefix(onboardList.GetItem(1).GetMainText(), "Arrow keys only") + }) + press(scr, tc.KeyRune, "2") + waitFor(t, "home", func() bool { return shownPanel() == "welcome" }) + onUI(func() { + if vimKeys() || !api.UserInfo.KeysAsked { + t.Fatalf("hjkl still on (asked %v)", api.UserInfo.KeysAsked) + } + b := NewBoardView(func(chess.Square) {}) + b.InputHandler()(tc.NewEventKey(tc.KeyRune, "k", tc.ModNone), func(cv.Primitive) {}) + if b.keyboard { + t.Error("k still moves on the board") + } + for tv := range keyRibbons { + if strings.Contains(tv.GetText(false), "hjkl") { + t.Errorf("ribbon still says hjkl: %q", tv.GetText(false)) + } + } + if len(cv.Keys.MoveUp2) != 0 { + t.Error("lists still move on k") + } + setVimKeys(true) + if len(cv.Keys.MoveUp2) == 0 || boardKeys() != "hjkl[] " { + t.Error("turning hjkl back on didn't") + } + }) +} + +// Leaving first-run setup leaves no previewed style behind: the home screen +// and everything after it draw with the real setting. (On a terminal where +// basic rendering is recommended, the preview used to stick.) +func TestOnboardingClearsPreview(t *testing.T) { + startTestApp(t, 160, 50) + onUI(func() { + _ = api.UpdateConfig(func(c *api.UserConfig) { c.Pieces, c.SoundAsked, c.KeysAsked, c.StockfishAsked = "", true, true, true }) + runOnboarding() + previewPieces(PiecesBasic) // as if basic were highlighted + _ = SetPiecesSetting(PiecesText) + gotoWelcome() + rendering.Lock() + left := rendering.pieces + rendering.Unlock() + if left != "" || PiecesSetting() != PiecesText { + t.Errorf("after setup: preview %q, setting %q; want no preview, text", left, PiecesSetting()) + } + }) +} diff --git a/pkg/primitives.go b/pkg/primitives.go index 45c350c..ca5b383 100644 --- a/pkg/primitives.go +++ b/pkg/primitives.go @@ -1,7 +1,9 @@ package pkg import ( - cv "code.rocketnine.space/tslocum/cview" + "strings" + + cv "codeberg.org/tslocum/cview" tc "github.com/gdamore/tcell/v3" ) @@ -10,11 +12,9 @@ func titlePrimitive(text string, toFocus cv.Primitive) *cv.TextView { tv.SetTextAlign(cv.AlignCenter) tv.SetVerticalAlign(cv.AlignMiddle) tv.SetDynamicColors(true) + tv.SetWordWrap(true) // a narrow column wraps the title instead of cutting it tv.SetText(text) - tv.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(toFocus) - return nil - }) + forwardKeys(tv, toFocus) return tv } @@ -24,11 +24,11 @@ func ribbonPrimitive(text string, toFocus cv.Primitive) *cv.TextView { tv.SetVerticalAlign(cv.AlignTop) tv.SetBackgroundColor(tc.ColorKhaki) tv.SetTextColor(tc.ColorFireBrick) - tv.SetText(text) - tv.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(toFocus) - return nil - }) + tv.SetText(keysText(text)) + if strings.Contains(text, "arrows/hjkl") { + keyRibbons[tv] = text + } + forwardKeys(tv, toFocus) return tv } @@ -37,23 +37,13 @@ func quoutePrimitive(text string, toFocus cv.Primitive) *cv.TextView { tv.SetTextAlign(cv.AlignCenter) tv.SetVerticalAlign(cv.AlignTop) tv.SetTextColor(tc.ColorLightSlateGray) + tv.SetWordWrap(true) + tv.SetPadding(1, 1, 10, 10) tv.SetText(text) - tv.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(toFocus) - return nil - }) + forwardKeys(tv, toFocus) return tv } -func boardPrimitive(handler func(row, col int)) *cv.Table { - table := cv.NewTable() - table.SetSelectable(true, true) - table.SetSelectionChangedFunc(handler) - table.SetSortClicked(false) - table.SetFixed(11, 11) - return table -} - func NewOptionWindow(msg, op1, op2 string, handler1, handler2 func()) *cv.Flex { subFlex := cv.NewFlex() button1 := cv.NewButton(op1) @@ -85,10 +75,7 @@ func NewOptionWindow(msg, op1, op2 string, handler1, handler2 func()) *cv.Flex { func Center(width, height int, p cv.Primitive, toFocus cv.Primitive) cv.Primitive { spacer := cv.NewBox() - spacer.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(toFocus) - return nil - }) + forwardKeys(spacer, toFocus) subFlex := cv.NewFlex() subFlex.SetDirection(cv.FlexRow) subFlex.AddItem(spacer, 0, 1, false) diff --git a/pkg/prompt.go b/pkg/prompt.go new file mode 100644 index 0000000..17f2f99 --- /dev/null +++ b/pkg/prompt.go @@ -0,0 +1,53 @@ +package pkg + +import ( + "strings" + + cv "codeberg.org/tslocum/cview" + tc "github.com/gdamore/tcell/v3" +) + +// A small boxed prompt for one line of text, shown over a blank screen. +// Enter submits (non-empty text), Esc cancels back to the home screen. + +var prompt struct { + label *cv.TextView + input *cv.InputField + done func(string) +} + +func promptInit() cv.Primitive { + prompt.label = textBox(cv.AlignLeft) + prompt.input = cv.NewInputField() + prompt.input.SetDoneFunc(func(key tc.Key) { + text := strings.TrimSpace(prompt.input.GetText()) + prompt.input.SetText("") + if key != tc.KeyEnter || text == "" || prompt.done == nil { + gotoWelcome() + return + } + prompt.done(text) + }) + box := cv.NewFlex() + box.SetDirection(cv.FlexRow) + box.SetBorder(true) + box.SetPadding(1, 0, 2, 2) + box.AddItem(prompt.label, 3, 0, false) + box.AddItem(prompt.input, 1, 0, true) + return Center(72, 8, box, prompt.input) +} + +// askText shows the prompt; done gets the text entered. +func askText(question, label string, done func(string)) { + prompt.label.SetText(question + "\n[#a0a0a0](Enter to confirm, Esc to cancel)[-]") + prompt.input.SetLabel(label) + prompt.done = done + Root.Switch("prompt") + Root.App.SetFocus(prompt.input) +} + +// promptError shows a problem with what was entered, keeping the prompt open. +func promptError(question, msg string) { + prompt.label.SetText(question + "\n[red]" + cv.Escape(msg) + "[-]") + Root.App.SetFocus(prompt.input) +} diff --git a/pkg/puzzle.go b/pkg/puzzle.go new file mode 100644 index 0000000..d4cd893 --- /dev/null +++ b/pkg/puzzle.go @@ -0,0 +1,451 @@ +package pkg + +import ( + "errors" + "fmt" + "net/http" + "strings" + "time" + + cv "codeberg.org/tslocum/cview" + tc "github.com/gdamore/tcell/v3" + "github.com/nate-xyz/chess-cli/api" + "github.com/notnil/chess" +) + +// Lichess puzzles: the daily puzzle, or puzzle training (a new puzzle each +// time, at a chosen difficulty), rated or casual like on Lichess. +// +// A puzzle starts after the opponent's move; the solution alternates the +// player's moves (which must be found) with the opponent's replies (played +// automatically). As on Lichess, any move that checkmates also counts, and +// the first wrong move fails the puzzle, though you can keep trying. + +type PuzzleScreen struct { + Board *BoardView + Side *cv.Flex + Info *cv.TextView + Status *cv.TextView + History *cv.TextView + List *cv.List + Move *moveBox + + p *api.Puzzle + daily bool + game *chess.Game + color chess.Color // the side the player plays + idx int // next solution move + gen int // bumped per puzzle, so stale timers do nothing + failed bool + done bool // solved, or solution shown + recorded string + loading bool +} + +func puzzleRated() bool { return !api.UserInfo.PuzzleCasual } + +func puzzleDifficulty() string { + if d := api.UserInfo.PuzzleDifficulty; d != "" { + return d + } + return "normal" +} + +func savePuzzlePrefs(casual bool, difficulty string) { + _ = api.UpdateConfig(func(c *api.UserConfig) { c.PuzzleCasual, c.PuzzleDifficulty = casual, difficulty }) +} + +func (ps *PuzzleScreen) Init() cv.Primitive { + ps.Board = NewBoardView(ps.onSquare) + ps.Board.EnableSounds() + ps.Info = textBox(cv.AlignLeft) + ps.Status = textBox(cv.AlignLeft) + ps.History = textBox(cv.AlignLeft) + ps.List = menuList() + linkMoveList(ps.History, ps.Board) + + side := cv.NewFlex() + side.SetDirection(cv.FlexRow) + ps.Side = side + ps.Move = newMoveBox(side, ps.Board, func(text string) { + if ps.done || ps.game == nil || ps.game.Position().Turn() != ps.color { + return + } + uci, err := parseMoveInput(ps.game, text) + if err != nil { + ps.setStatus(invalidMoveHint(text)) + ps.Move.show() + return + } + ps.tryMove(uci) + }) + side.AddItem(ps.Info, 5, 0, false) + side.AddItem(ps.Status, 0, 1, false) + side.AddItem(ps.History, 0, 1, false) + side.AddItem(ps.Move.input, 0, 0, false) + side.AddItem(ps.List, 4, 0, false) + + ps.Board.SetTabFunc(func() { Root.App.SetFocus(ps.List) }) + ps.List.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { + if event.Key() == tc.KeyTab || event.Key() == tc.KeyEscape { + Root.App.SetFocus(ps.Board) + return nil + } + return event + }) + registerMenus("puzzle", false, ps.List) + return newGameLayout(ps.Board, side, " chess-cli · puzzles │ Ctrl-K type a move │ click or arrows/hjkl + Enter to move │ Tab menu │ Ctrl-C quit") +} + +// startPuzzle opens the puzzle screen and loads a puzzle. Rated puzzles need +// a Lichess login, which is started first if there's no saved one. +func startPuzzle(daily bool) { + ps := Root.puzzle + ps.gen++ + ps.p, ps.game, ps.daily, ps.loading = nil, nil, daily, true + ps.Info.SetText("") + ps.History.SetText("") + ps.Board.ClearSelection() + ps.updateMenu() + Root.Switch("puzzle") + + if puzzleRated() && !api.HasValidToken() { + ps.showLogin() + return + } + ps.fetch() +} + +func (ps *PuzzleScreen) showLogin() { + ps.setStatus("[yellow]Rated puzzles need a Lichess login. Logging in…[-]") + startLogin(func() { + ps.setStatus("[yellow]Rated puzzles need a Lichess login.[-]\nLog in through your browser; it should open by itself. If it didn't, open this link:\n" + cv.Escape(loginURL)) + }, func(err error) { + if err != nil { + ps.setStatus(fmt.Sprintf("[red]Login failed:[-] %v\nChoose Casual mode on the Puzzles menu to play without logging in.", err)) + return + } + ps.fetch() + }) +} + +func (ps *PuzzleScreen) fetch() { + what := "puzzle" + if ps.daily { + what = "daily puzzle" + } + ps.setStatus(fmt.Sprintf("[#a0a0a0]Loading the %s…[-]", what)) + gen, daily, difficulty := ps.gen, ps.daily, puzzleDifficulty() + go func() { + var p *api.Puzzle + var err error + if daily { + p, err = api.GetDailyPuzzle() + } else { + p, err = api.GetNextPuzzle(difficulty) + } + Root.App.QueueUpdateDraw(func() { + if gen != ps.gen { + return + } + ps.loading = false + if err == nil { + err = ps.load(p) + } + if err != nil { + ps.setStatus(fmt.Sprintf("[red]Couldn't load the %s: %v[-]", what, err)) + ps.updateMenu() + } + }) + }() +} + +// load sets up a fetched puzzle: replays the game up to the puzzle position. +func (ps *PuzzleScreen) load(p *api.Puzzle) error { + game, err := puzzleGame(p) + if err != nil { + return err + } + if len(p.Puzzle.Solution) == 0 { + return errors.New("the puzzle has no solution") + } + ps.p, ps.game = p, game + ps.color = game.Position().Turn() + ps.idx, ps.failed, ps.done, ps.recorded = 0, false, false, "" + ps.updateInfo() + ps.setStatus(fmt.Sprintf("Your turn: find the best move for %s.", colorName(ps.color))) + ps.updateMenu() + ps.redraw() + Root.App.SetFocus(ps.Board) + return nil +} + +// puzzleGame rebuilds the puzzle's game from its PGN (which ends with the +// opponent's move), falling back to the FEN if Lichess sent one. +func puzzleGame(p *api.Puzzle) (*chess.Game, error) { + game := chess.NewGame() + ok := p.Game.PGN != "" + for _, san := range strings.Fields(p.Game.PGN) { + if err := game.MoveStr(san); err != nil { + ok = false + break + } + } + if ok { + return game, nil + } + if p.Puzzle.FEN != "" { + fen, err := chess.FEN(p.Puzzle.FEN) + if err != nil { + return nil, err + } + return chess.NewGame(fen), nil + } + return nil, errors.New("couldn't read the puzzle's moves") +} + +func colorName(c chess.Color) string { + if c == chess.White { + return "White" + } + return "Black" +} + +func (ps *PuzzleScreen) setStatus(s string) { ps.Status.SetText(s) } + +func (ps *PuzzleScreen) updateInfo() { + p := ps.p + title := "Puzzle" + if ps.daily { + title = "Daily puzzle" + } + mode := "Casual" + if puzzleRated() { + mode = "Rated" + } + text := fmt.Sprintf("[::b]%s[::-] [#a0a0a0]#%s[-]\nRating [::b]%d[::-] · played %d times\n%s", title, p.Puzzle.ID, p.Puzzle.Rating, p.Puzzle.Plays, mode) + if !ps.daily { + text += " · " + puzzleDifficulty() + } + if ps.recorded != "" { + text += "\n" + ps.recorded + } + ps.Info.SetText(text) +} + +func (ps *PuzzleScreen) updateMenu() { + l := ps.List + l.Clear() + add := func(text string, key rune, f func()) { + item := cv.NewListItem(text) + item.SetShortcut(key) + item.SetSelectedFunc(f) + l.AddItem(item) + } + if ps.p != nil && !ps.done { + add("Hint", 'i', ps.hint) + add("View solution", 's', ps.reveal) + } + if ps.p != nil && ps.done || ps.p == nil && !ps.loading { + add("Next puzzle", 'n', func() { startPuzzle(false) }) + } + add("Leave puzzles", 'x', gotoWelcome) + ps.Side.ResizeItem(l, l.GetItemCount(), 0) +} + +func (ps *PuzzleScreen) redraw() { + if ps.game == nil { + return + } + ps.Board.SetPosition(ps.game.Position(), ps.color == chess.White) + ps.Board.SetHistory(ps.game.Positions(), ps.game.Moves()) + from, to := chess.NoSquare, chess.NoSquare + if moves := ps.game.Moves(); len(moves) > 0 { + last := moves[len(moves)-1] + from, to = last.S1(), last.S2() + } + ps.Board.SetLastMove(from, to) + ps.History.SetText(moveListText(ps.game)) + ps.History.ScrollToEnd() +} + +func (ps *PuzzleScreen) onSquare(sq chess.Square) { + if ps.game == nil { + return + } + canMove := !ps.done && ps.game.Position().Turn() == ps.color + ps.Board.HandleSquare(ps.game, sq, canMove, ps.tryMove) +} + +// play makes a UCI move on the puzzle game. +func (ps *PuzzleScreen) play(uci string) error { + m, err := chess.UCINotation{}.Decode(ps.game.Position(), uci) + if err != nil { + return err + } + return ps.game.Move(m) +} + +func (ps *PuzzleScreen) tryMove(uci string) { + if ps.done || ps.game == nil { + return + } + before := ps.game.Clone() + if err := ps.play(uci); err != nil { + ps.setStatus(fmt.Sprintf("[red]%v[-]", err)) + return + } + correct := uci == ps.p.Puzzle.Solution[ps.idx] || ps.game.Method() == chess.Checkmate + if !correct { + ps.game = before + ps.redraw() + ps.setStatus("[red]✗ That's not the move.[-] Try again, or view the solution.") + playSound(soundError) + if !ps.failed { + ps.failed = true + ps.record(false) + } + return + } + ps.idx++ + ps.redraw() + if ps.idx >= len(ps.p.Puzzle.Solution) || ps.game.Outcome() != chess.NoOutcome { + ps.finish() + return + } + ps.setStatus("[green]✓ Best move![-] Keep going.") + playSound(soundConfirm) + ps.later(500*time.Millisecond, func() { + if ps.idx < len(ps.p.Puzzle.Solution) && ps.play(ps.p.Puzzle.Solution[ps.idx]) == nil { + ps.idx++ + ps.redraw() + ps.setStatus(fmt.Sprintf("[green]✓ Best move![-] Your turn again: find the best move for %s.", colorName(ps.color))) + } + }) +} + +// later runs f on the UI goroutine after d, unless a new puzzle started. +func (ps *PuzzleScreen) later(d time.Duration, f func()) { + gen := ps.gen + time.AfterFunc(d, func() { + Root.App.QueueUpdateDraw(func() { + if gen == ps.gen { + f() + } + }) + }) +} + +func (ps *PuzzleScreen) finish() { + ps.done = true + if ps.failed { + ps.setStatus("Puzzle complete, [yellow]but not solved first time.[-]" + ps.themes()) + } else { + ps.setStatus("[green]✓ Solved![-]" + ps.themes()) + playSound(soundVictory) + ps.record(true) + } + ps.updateMenu() +} + +func (ps *PuzzleScreen) themes() string { + if len(ps.p.Puzzle.Themes) == 0 { + return "" + } + return "\n\n[#a0a0a0]Themes: " + cv.Escape(strings.Join(ps.p.Puzzle.Themes, ", ")) + "[-]\n[#a0a0a0]From game lichess.org/" + cv.Escape(ps.p.Game.ID) + "[-]" +} + +// hint selects the piece to move, as Lichess's hint does. +func (ps *PuzzleScreen) hint() { + if ps.done || ps.game.Position().Turn() != ps.color { + return + } + m, err := chess.UCINotation{}.Decode(ps.game.Position(), ps.p.Puzzle.Solution[ps.idx]) + if err != nil { + return + } + targets := map[chess.Square]bool{} + for _, v := range ps.game.ValidMoves() { + if v.S1() == m.S1() { + targets[v.S2()] = true + } + } + ps.Board.SetSelection(m.S1(), targets) + Root.App.SetFocus(ps.Board) +} + +// reveal plays the rest of the solution, one move at a time. It counts as +// a failed puzzle. +func (ps *PuzzleScreen) reveal() { + if ps.done { + return + } + if !ps.failed { + ps.failed = true + ps.record(false) + } + ps.done = true + ps.Board.ClearSelection() + ps.setStatus("Solution:") + ps.updateMenu() + var step func() + step = func() { + if ps.idx >= len(ps.p.Puzzle.Solution) || ps.play(ps.p.Puzzle.Solution[ps.idx]) != nil { + ps.setStatus("That was the solution." + ps.themes()) + return + } + ps.idx++ + ps.redraw() + ps.later(700*time.Millisecond, step) + } + ps.later(300*time.Millisecond, step) +} + +// record sends the result to Lichess (if logged in), once per puzzle. +func (ps *PuzzleScreen) record(win bool) { + if !api.HasValidToken() { + ps.recorded = "[#a0a0a0]Not logged in: result not saved[-]" + ps.updateInfo() + return + } + id, rated, gen := ps.p.Puzzle.ID, puzzleRated(), ps.gen + go func() { + res, err := api.SubmitPuzzle(id, win, rated) + Root.App.QueueUpdateDraw(func() { + if gen != ps.gen { + return + } + var apiErr *api.APIError + switch { + case errors.As(err, &apiErr) && (apiErr.Status == http.StatusUnauthorized || apiErr.Status == http.StatusForbidden): + ps.recorded = "[yellow]Result not saved: log in again to allow puzzles[-]" + ps.addRelogin() + case err != nil: + ps.recorded = fmt.Sprintf("[red]Result not saved: %v[-]", err) + case rated && len(res.Rounds) > 0: + diff := res.Rounds[0].RatingDiff + col := "green" + if diff < 0 { + col = "red" + } + ps.recorded = fmt.Sprintf("Your rating: [::b]%.0f[::-] [%s]%+d[-]", res.Glicko.Rating, col, diff) + default: + ps.recorded = "[#a0a0a0]Saved to your Lichess history[-]" + } + ps.updateInfo() + }) + }() +} + +// addRelogin offers a fresh login, for tokens from before puzzle support +// (they lack the puzzle:write scope). +func (ps *PuzzleScreen) addRelogin() { + item := cv.NewListItem("Log in again") + item.SetSelectedFunc(func() { + _ = api.ClearToken() + Root.User = nil + startPuzzle(ps.daily) + }) + ps.List.InsertItem(0, item) + ps.Side.ResizeItem(ps.List, ps.List.GetItemCount(), 0) +} diff --git a/pkg/puzzle_test.go b/pkg/puzzle_test.go new file mode 100644 index 0000000..77eb88d --- /dev/null +++ b/pkg/puzzle_test.go @@ -0,0 +1,82 @@ +package pkg + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/nate-xyz/chess-cli/api" + "github.com/notnil/chess" +) + +// Lichess's daily puzzle example: White to move, solution Kxh2 Ng4+ Qxg4 Bxg4 Bxd8. +const dailyPuzzleJSON = `{"game":{"id":"FyCFwzjd","perf":{"key":"blitz","name":"Blitz"},"rated":true, +"players":[{"name":"h21","id":"h21","color":"white","rating":1974},{"name":"ratomir","id":"ratomir","color":"black","rating":1954}], +"pgn":"d4 Nf6 Bg5 d5 Nf3 e6 e3 Nbd7 Bd3 Bd6 O-O O-O Nbd2 c6 Rc1 Re8 c3 e5 dxe5 Nxe5 Nxe5 Bxe5 Bb1 Bxh2+","clock":"3+2"}, +"puzzle":{"id":"m5n0s","rating":1957,"plays":85080,"solution":["g1h2","f6g4","d1g4","c8g4","g5d8"], +"themes":["opening","advantage","long","hangingPiece"],"initialPly":23}}` + +func TestPuzzleFlow(t *testing.T) { + var mu sync.Mutex + var submitted []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/puzzle/daily": + io.WriteString(w, dailyPuzzleJSON) + case "/api/puzzle/batch/mix": + b, _ := io.ReadAll(r.Body) + mu.Lock() + submitted = append(submitted, string(b)) + mu.Unlock() + io.WriteString(w, `{"rounds":[{"id":"m5n0s","win":false,"ratingDiff":-12}],"glicko":{"rating":1488.4}}`) + default: + http.NotFound(w, r) + } + })) + defer srv.Close() + oldHost := api.HostUrl + api.HostUrl = srv.URL + defer func() { api.HostUrl = oldHost }() + + startTestApp(t, 160, 50) + api.UserInfo = api.UserConfig{ApiToken: "test"} + ps := Root.puzzle + onUI(func() { startPuzzle(true) }) + waitFor(t, "puzzle to load", func() bool { return ps.game != nil }) + onUI(func() { + if ps.color != chess.White || ps.idx != 0 { + t.Errorf("color %v idx %d", ps.color, ps.idx) + } + }) + + // a wrong move is taken back and fails the puzzle (recorded once) + onUI(func() { ps.tryMove("g1h1") }) + waitFor(t, "failure recorded", func() bool { + mu.Lock() + defer mu.Unlock() + return len(submitted) == 1 && strings.Contains(ps.recorded, "-12") + }) + onUI(func() { + if !ps.failed || ps.game.Position().Turn() != chess.White { + t.Error("wrong move not taken back") + } + }) + + // the right move: the opponent replies by itself + onUI(func() { ps.tryMove("g1h2") }) + waitFor(t, "opponent reply", func() bool { return ps.idx == 2 }) + onUI(func() { ps.tryMove("d1g4") }) + waitFor(t, "second reply", func() bool { return ps.idx == 4 }) + onUI(func() { ps.tryMove("g5d8") }) + waitFor(t, "done", func() bool { return ps.done }) + time.Sleep(50 * time.Millisecond) + mu.Lock() + defer mu.Unlock() + if len(submitted) != 1 || !strings.Contains(submitted[0], `"win":false`) || !strings.Contains(submitted[0], `"rated":true`) { + t.Errorf("submitted %v", submitted) + } +} diff --git a/pkg/render.go b/pkg/render.go new file mode 100644 index 0000000..d6f5723 --- /dev/null +++ b/pkg/render.go @@ -0,0 +1,152 @@ +package pkg + +import ( + "os" + "strings" + "sync" + + "github.com/nate-xyz/chess-cli/api" +) + +// How pieces are drawn, chosen on the Options screen: +// +// - PiecesText: Unicode chess symbols, scaled up to fill the squares in +// terminals with kitty's text sizing protocol (see textsize.go). +// - PiecesImage: the Lichess board colours and cburnett piece images, drawn +// with kitty's graphics protocol (see images.go) in terminals that +// support it. Elsewhere the board falls back to text. +// - PiecesBasic: plain symbols in the 8 standard colours, like the +// original chess-cli; for older or limited terminals. +const ( + PiecesText = "text" + PiecesImage = "image" + PiecesBasic = "basic" +) + +var rendering struct { + sync.Mutex + graphics bool // terminal supports the kitty graphics protocol + pieces string // user's choice; "" = automatic +} + +// SetupRendering asks the terminal what it can draw and loads the saved +// choice. Call it before the UI takes over the terminal, after the config is +// loaded. CHESS_CLI_BIG_PIECES and CHESS_CLI_IMAGES (0 or 1) override the +// detection. +func SetupRendering() { + sized, graphics := probeTerminal() + if v, ok := envBool("CHESS_CLI_BIG_PIECES"); ok { + sized = v + } + if v, ok := envBool("CHESS_CLI_IMAGES"); ok { + graphics = v + } + textSizing.Lock() + textSizing.enabled = sized + textSizing.Unlock() + + rendering.Lock() + rendering.graphics = graphics + rendering.pieces = api.UserInfo.Pieces + rendering.Unlock() +} + +func envBool(name string) (value, set bool) { + switch strings.ToLower(os.Getenv(name)) { + case "0", "off", "false", "no": + return false, true + case "1", "on", "true", "yes": + return true, true + } + return false, false +} + +// GraphicsSupported reports whether piece images can be shown. +func GraphicsSupported() bool { + rendering.Lock() + defer rendering.Unlock() + return rendering.graphics +} + +// PiecesSetting is the chosen piece style: the saved choice, or images when +// the terminal supports them. +func PiecesSetting() string { + rendering.Lock() + defer rendering.Unlock() + switch rendering.pieces { + case PiecesText, PiecesImage, PiecesBasic: + return rendering.pieces + } + if rendering.graphics { + return PiecesImage + } + return PiecesText +} + +// previewPieces switches the piece style without saving it. +func previewPieces(style string) { + rendering.Lock() + rendering.pieces = style + rendering.Unlock() +} + +// RecommendedPieces is the best style this terminal can show. +func RecommendedPieces() string { + switch { + case GraphicsSupported(): + return PiecesImage + case trueColor(): + return PiecesText + } + return PiecesBasic +} + +// trueColor guesses whether the terminal shows 24-bit colour. +func trueColor() bool { + ct := strings.ToLower(os.Getenv("COLORTERM")) + return ct == "truecolor" || ct == "24bit" || TextSizingMode() || + strings.Contains(os.Getenv("TERM"), "kitty") || strings.Contains(os.Getenv("TERM"), "direct") +} + +// terminalName describes the terminal, as best the environment tells. +func terminalName() string { + name := os.Getenv("TERM_PROGRAM") + switch { + case name == "iTerm.app": + name = "iTerm2" + case name == "Apple_Terminal": + name = "Terminal.app" + case name == "vscode": + name = "the VS Code terminal" + case os.Getenv("KITTY_WINDOW_ID") != "" || strings.HasSuffix(os.Getenv("TERM"), "kitty"): + name = "kitty" + case os.Getenv("WT_SESSION") != "": + name = "Windows Terminal" + case name == "" && os.Getenv("TERM") != "": + name = os.Getenv("TERM") + case name == "": + name = "an unknown terminal" + } + if v := os.Getenv("TERM_PROGRAM_VERSION"); v != "" && os.Getenv("TERM_PROGRAM") != "" { + name += " " + v + } + if os.Getenv("TMUX") != "" { + name += ", inside tmux" + } else if strings.HasPrefix(os.Getenv("TERM"), "screen") { + name += ", inside screen" + } + return name +} + +// SetPiecesSetting changes the piece style and saves it. +func SetPiecesSetting(style string) error { + rendering.Lock() + rendering.pieces = style + rendering.Unlock() + return api.UpdateConfig(func(c *api.UserConfig) { c.Pieces = style }) +} + +// useImages reports whether boards should be drawn with images now. +func useImages() bool { + return GraphicsSupported() && PiecesSetting() == PiecesImage +} diff --git a/pkg/result.go b/pkg/result.go new file mode 100644 index 0000000..95e2993 --- /dev/null +++ b/pkg/result.go @@ -0,0 +1,210 @@ +package pkg + +import ( + "image" + "image/color" + "math" + "strings" + + tc "github.com/gdamore/tcell/v3" + "github.com/notnil/chess" +) + +// Game results on the board, as Lichess shows them: a badge on each king when +// the game is over. Green crown for the winner, red # for a checkmated king, +// red flag for a loss on resignation or time, grey = for a draw. In text +// modes the king squares are tinted and get a badge character. + +type badge int + +const ( + badgeNone badge = iota + badgeWin + badgeMate + badgeLoss + badgeDraw +) + +// boardResult is a finished game's result: winner (chess.NoColor for a draw) +// and how it ended ("mate", "resign", "timeout", "stalemate", "draw", ...). +type boardResult struct { + set bool + winner chess.Color + method string +} + +// SetResult marks the game shown as over. The marks go when the position +// changes (a new game). +func (b *BoardView) SetResult(winner chess.Color, method string) { + b.mu.Lock() + defer b.mu.Unlock() + b.result = boardResult{set: true, winner: winner, method: method} +} + +// badgeFor is the badge for a king of colour c. Locked by caller. +func (b *BoardView) badgeFor(c chess.Color) badge { + r := b.result + switch { + case !r.set || b.back > 0: + return badgeNone + case r.winner == chess.NoColor: + return badgeDraw + case r.winner == c: + return badgeWin + case r.method == "mate": + return badgeMate + } + return badgeLoss +} + +var badgeColors = map[badge]color.NRGBA{ + badgeWin: {0x62, 0x99, 0x24, 0xff}, + badgeMate: {0xcc, 0x33, 0x33, 0xff}, + badgeLoss: {0xcc, 0x33, 0x33, 0xff}, + badgeDraw: {0x88, 0x88, 0x88, 0xff}, +} + +// badgeText is the character shown in text modes. +var badgeText = map[badge]rune{badgeWin: '✓', badgeMate: '#', badgeLoss: '⚑', badgeDraw: '½'} + +func badgeTc(k badge) tc.Color { + c := badgeColors[k] + return tc.NewRGBColor(int32(c.R), int32(c.G), int32(c.B)) +} + +func badgeBasic(k badge) tc.Color { + switch k { + case badgeWin: + return tc.ColorGreen + case badgeDraw: + return tc.ColorGray + } + return tc.ColorMaroon +} + +// badgeImage draws a badge: a coloured disc with a white symbol. +func badgeImage(k badge, size int) *image.RGBA { + img := image.NewRGBA(image.Rect(0, 0, size, size)) + s := float64(size) + c := s / 2 + white := color.NRGBA{0xff, 0xff, 0xff, 0xff} + paint(img, badgeColors[k], 1, 0, 0, s, s, func(x, y float64) float64 { return c - 0.5 - math.Hypot(x-c, y-c) }) + bar := func(x0, y0, x1, y1 float64) { // a white rectangle, in units of the badge size + paint(img, white, 1, x0*s, y0*s, x1*s, y1*s, func(x, y float64) float64 { + return math.Min(math.Min(x-x0*s, x1*s-x), math.Min(y-y0*s, y1*s-y)) + }) + } + poly := func(pts ...[2]float64) { // a white convex polygon (clockwise, badge units) + paint(img, white, 1, 0, 0, s, s, func(x, y float64) float64 { return convexInside(pts, x/s, y/s) * s }) + } + switch k { + case badgeMate: // # + bar(0.36, 0.22, 0.44, 0.78) + bar(0.56, 0.22, 0.64, 0.78) + bar(0.22, 0.36, 0.78, 0.44) + bar(0.22, 0.56, 0.78, 0.64) + case badgeDraw: // = + bar(0.25, 0.36, 0.75, 0.45) + bar(0.25, 0.55, 0.75, 0.64) + case badgeLoss: // flag + bar(0.30, 0.22, 0.37, 0.80) + poly([2]float64{0.37, 0.22}, [2]float64{0.75, 0.37}, [2]float64{0.37, 0.52}) + case badgeWin: // crown + bar(0.26, 0.60, 0.74, 0.72) + poly([2]float64{0.26, 0.60}, [2]float64{0.26, 0.30}, [2]float64{0.42, 0.60}) + poly([2]float64{0.38, 0.60}, [2]float64{0.50, 0.24}, [2]float64{0.62, 0.60}) + poly([2]float64{0.58, 0.60}, [2]float64{0.74, 0.30}, [2]float64{0.74, 0.60}) + } + return img +} + +// convexInside is the signed distance inside a convex polygon (positive = +// inside), for either winding. +func convexInside(pts [][2]float64, x, y float64) float64 { + d := math.Inf(1) + area := 0.0 + for i := range pts { + a, b := pts[i], pts[(i+1)%len(pts)] + area += a[0]*b[1] - b[0]*a[1] + } + sign := 1.0 + if area < 0 { + sign = -1 + } + for i := range pts { + a, b := pts[i], pts[(i+1)%len(pts)] + ex, ey := b[0]-a[0], b[1]-a[1] + l := math.Hypot(ex, ey) + dist := sign * ((x-a[0])*ey - (y-a[1])*ex) / l + d = math.Min(d, -dist) + } + return d +} + +// methodText describes how a game ended. +var methodText = map[string]string{ + "mate": "checkmate", "resign": "resignation", "timeout": "time", "outoftime": "time", + "stalemate": "stalemate", "draw": "agreement", "repetition": "repetition", + "fiftymoves": "the 50-move rule", "material": "insufficient material", "aborted": "abort", +} + +// resultText is a result for the sidebar: a big score and a line saying how. +func resultText(winner chess.Color, method string) string { + how := methodText[method] + if how == "" { + how = method + } + switch winner { + case chess.White: + return "[::b]1–0[::-]\nWhite wins by " + how + case chess.Black: + return "[::b]0–1[::-]\nBlack wins by " + how + } + if how == "agreement" { + return "[::b]½–½[::-]\nDraw" + } + return "[::b]½–½[::-]\nDraw by " + how +} + +// gameMethod maps the chess library's ending to a method name. +func gameMethod(g *chess.Game) string { + switch g.Method() { + case chess.Checkmate: + return "mate" + case chess.Resignation: + return "resign" + case chess.Stalemate: + return "stalemate" + case chess.ThreefoldRepetition, chess.FivefoldRepetition: + return "repetition" + case chess.FiftyMoveRule, chess.SeventyFiveMoveRule: + return "fiftymoves" + case chess.InsufficientMaterial: + return "material" + case chess.DrawOffer: + return "draw" + } + return strings.ToLower(g.Method().String()) +} + +// winnerOf maps an outcome to the winning colour (NoColor for a draw). +func winnerOf(o chess.Outcome) chess.Color { + switch o { + case chess.WhiteWon: + return chess.White + case chess.BlackWon: + return chess.Black + } + return chess.NoColor +} + +// colorFromName maps "white"/"black" to a colour ("" = NoColor). +func colorFromName(s string) chess.Color { + switch strings.ToLower(s) { + case "white": + return chess.White + case "black": + return chess.Black + } + return chess.NoColor +} diff --git a/pkg/save.go b/pkg/save.go index 84e534d..fdc96a8 100644 --- a/pkg/save.go +++ b/pkg/save.go @@ -3,11 +3,13 @@ package pkg import ( "encoding/json" "errors" - "io" + "fmt" "math/rand" "os" + "path/filepath" "time" + "github.com/nate-xyz/chess-cli/api" "github.com/notnil/chess" ) @@ -65,7 +67,9 @@ func (gs *GameState) SaveGame(new bool) { } } Root.sglist.Games = append(Root.sglist.Games, saved) - writeToSavedGames() + if err := writeToSavedGames(); err != nil { + Root.gameState.Status += fmt.Sprintf("[red]Could not save: %v[-]\n", err) + } } func RestoreGame(info SavedInfo) error { @@ -82,6 +86,10 @@ func RestoreGame(info SavedInfo) error { return err } Root.gameState.Game = chess.NewGame(fen) + Root.lgame.stopEngine() + Root.lgame.clock = localClock{} // saved games have no clock + clockActive.Store(false) + Root.lgame.tickClock() DrawBoard(Root.lgame.Board, Root.gameState.Game.Position().Turn() == chess.White) DrawMoveHistory(Root.lgame.History) Root.lgame.UpdateStatus() @@ -89,45 +97,58 @@ func RestoreGame(info SavedInfo) error { return nil } +// savedGamesPath is ~/.config/chess-cli/saved_games.json (or the platform +// equivalent). Older versions saved to ./saved_games.json; if the new file +// doesn't exist yet, that file is copied over (and left in place). +func savedGamesPath() (string, error) { + dir, err := api.ConfigDir() + if err != nil { + return "", err + } + return filepath.Join(dir, "saved_games.json"), nil +} + func checkForSavedGames() error { - _, err := os.Stat(saved_path) - if err == nil { - jsonFile, err := os.Open(saved_path) - if err != nil { - return err - } - defer jsonFile.Close() - byteValue, _ := io.ReadAll(jsonFile) - err = json.Unmarshal(byteValue, &Root.sglist) - if err != nil { - return err - } - } else if errors.Is(err, os.ErrNotExist) { - b, err := json.Marshal(&Root.sglist) - if err != nil { - return err + path, err := savedGamesPath() + if err != nil { + return err + } + b, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + b, err = os.ReadFile(saved_path) // legacy location + if errors.Is(err, os.ErrNotExist) { + return nil } - err = os.WriteFile(saved_path, b, 0644) - if err != nil { - return err + if err == nil { + if err := json.Unmarshal(b, &Root.sglist); err != nil { + return err + } + return writeToSavedGames() } - } else { + } + if err != nil { return err } - return nil + return json.Unmarshal(b, &Root.sglist) } func writeToSavedGames() error { - list := Root.sglist - b, err := json.Marshal(*list) + path, err := savedGamesPath() if err != nil { return err } - err = os.WriteFile(saved_path, b, 0644) + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + b, err := json.MarshalIndent(Root.sglist, "", " ") if err != nil { return err } - return nil + tmp := path + ".tmp" + if err := os.WriteFile(tmp, b, 0o600); err != nil { + return err + } + return os.Rename(tmp, path) } func RandStringRunes(n int) string { diff --git a/pkg/send_and_wait.go b/pkg/send_and_wait.go index 58bbc54..233b80c 100644 --- a/pkg/send_and_wait.go +++ b/pkg/send_and_wait.go @@ -1,126 +1,155 @@ package pkg import ( + cv "codeberg.org/tslocum/cview" + "context" "fmt" - "log" "time" "github.com/nate-xyz/chess-cli/api" ) -func SendChallengeRequest(gchan chan<- string, errchan chan<- error) { - if api.UserInfo.ApiToken != "" { - var err error - var id string - switch CurrentChallenge.Type { - case 0: - err = api.CreateSeek(CurrentChallenge) - if err == nil { - gchan <- "Seek created. Searching for opponent..." - return - } - case 1: //challenge friend - err, id = api.CreateChallenge(CurrentChallenge) - case 2: //lichess ai - err, id = api.CreateAiChallenge(CurrentChallenge) +// loaderCancel withdraws the request currently shown on the loading screen. +// Only touched on the UI goroutine. +var loaderCancel context.CancelFunc + +// startRequest sends a new game request (seek, challenge or AI game), shows the +// loading screen, and moves to the game once Lichess starts it. +func startRequest(c api.CreateChallengeType) { + CurrentChallenge = c + ctx, cancel := context.WithCancel(context.Background()) + loaderCancel = cancel + Root.loader.Message.SetText("Requesting a new game from Lichess…") + Root.Switch("loader") + events, unsubscribe := subscribeEvents() // subscribe before sending, so no gameStart is missed + go waitForGame(ctx, c, events, unsubscribe) +} + +// cancelLoader is bound to Esc on the loading screen. +func cancelLoader() { + if loaderCancel != nil { + loaderCancel() + } +} + +func waitForGame(ctx context.Context, c api.CreateChallengeType, events <-chan api.StreamEventType, unsubscribe func()) { + defer unsubscribe() + show := func(msg string) { + Root.App.QueueUpdateDraw(func() { Root.loader.Message.SetText(msg) }) + } + start := func(gameID string) { + Root.App.QueueUpdateDraw(func() { + loaderCancel = nil + currentGameID = gameID + startNewOnlineGame() + }) + } + // leave shows a final message, then returns to the Lichess menu (or + // straight away if the user presses Esc). + leave := func(msg string) { + show(msg + "\n\n[gray](returning to the menu, Esc to go now)[-]") + select { + case <-time.After(4 * time.Second): + case <-ctx.Done(): + } + Root.App.QueueUpdateDraw(func() { + loaderCancel = nil + gotoLichessAfterLogin() + }) + } + + var ( + pending *api.Pending + gameID string + err error + ) + switch c.Type { + case 0: // random opponent + pending, err = api.CreateSeek(c) + if err == nil && c.TimeOption == api.TimeCorrespondence { + leave("Correspondence seek created. When someone accepts, the game will appear under Ongoing Games.") + return + } + show("Seek created. Searching for an opponent…\n\n[gray]Esc to cancel[-]") + case 1: // a specific user + pending, err = api.CreateChallenge(c) + if err == nil { + gameID = pending.ID + show(fmt.Sprintf("Waiting for [blue]%s[-] to accept the challenge.\n%s/%s\n\n[gray]Esc to cancel[-]", + cv.Escape(c.DestUser), api.HostUrl, gameID)) } - if err != nil { - errchan <- err - } else { - gchan <- id + case 2: // Lichess AI: the game starts immediately + gameID, err = api.CreateAiChallenge(c) + if err == nil { + start(gameID) + return } - } else { - log.Fatal(fmt.Errorf("tried to send api request with no api token")) } -} + if err != nil { + leave(fmt.Sprintf("[red]Could not create the game:[-] %v", err)) + return + } + defer pending.Cancel() -func WaitForLichessGameResponse() { - var localid string - getgameid := make(chan string, 1) - ticker := time.NewTicker(time.Millisecond * 250) - var icon_index int = 0 - RequestError := make(chan error, 1) - var RandomSeek bool = CurrentChallenge.Type == 0 - go SendChallengeRequest(getgameid, RequestError) //send the request - load_msg := "Requesting new game from Lichess, please wait." - Root.loader.DrawMessage(load_msg) + done := pending.Done() + spinner := time.NewTicker(250 * time.Millisecond) + defer spinner.Stop() + icon := 0 for { select { - case e := <-RequestError: - load_msg = fmt.Sprintf("ERROR: %v", e) - Root.loader.DrawMessage(load_msg) - go func() { - time.Sleep(time.Second * 5) - Root.App.QueueUpdate(gotoLichessAfterLogin) - }() - case id := <-getgameid: - if !RandomSeek { - localid = id - } else { - load_msg = id - Root.loader.DrawMessage(load_msg) + case <-ctx.Done(): + pending.Cancel() + Root.App.QueueUpdateDraw(func() { + loaderCancel = nil + gotoLichessAfterLogin() + }) + return + + case e := <-events: + switch { + case e.EventType == "gameStart" && gameID != "" && e.GameID == gameID: + start(e.GameID) + return + case e.EventType == "gameStart" && c.Type == 0 && e.Source != "friend" && e.Source != "ai": + start(e.GameID) + return + case e.EventType == "challengeDeclined" && e.GameID == gameID: + leave(fmt.Sprintf("[red]%s declined the challenge.[-]", cv.Escape(c.DestUser))) + return + case e.EventType == "challengeCanceled" && e.GameID == gameID: + leave("The challenge was cancelled.") + return } - case e := <-StreamChannel: // receive event directly - EventStreamArr = append([]api.StreamEventType{e}, EventStreamArr...) - if !RandomSeek { //friend or AI challenge - if e.GameID == localid { - load_msg = "Game started, going to game screen. (FROM ARRAY)" - Root.loader.DrawMessage(load_msg) - currentGameID = e.GameID - Root.App.QueueUpdate(startNewOnlineGame) //goto game - return //necessary for QueueUpdate - } - } else { - if e.EventType == "gameStart" && e.Source != "friend" { //TODO: check to make sure match random seek request - load_msg = "Found random opponent!" - Root.loader.DrawMessage(load_msg) - go func() { - currentGameID = e.GameID - time.Sleep(time.Second) - Root.App.QueueUpdate(startNewOnlineGame) - }() - } + + case result, ok := <-done: + if !ok { + done = nil + continue } - case <-ticker.C: - if !RandomSeek { - if localid != "" { - s, b := containedInEventStream(EventStreamArr, localid) - if b { - switch s { - case "challenge": - load_msg = fmt.Sprintf("Waiting for %v to accept the challenge %v/%v.", CurrentChallenge.DestUser, api.HostUrl, localid) - Root.loader.DrawMessage(load_msg) - case "gameFinish": - return - case "challengeCanceled", "challengeDeclined": - return - case "gameStart": - load_msg = "Game started, going to game screen. (FROM STREAM)" - Root.loader.DrawMessage(load_msg) - currentGameID = localid - Root.App.QueueUpdate(startNewOnlineGame) ///goto game - return //necessary for QueueUpdate - } - } else { - load_msg = fmt.Sprintf("Waiting for %v to accept the challenge %v/%v.", CurrentChallenge.DestUser, api.HostUrl, localid) - Root.loader.DrawMessage(load_msg) - } - } - } else { - e, b := EventContainedInEventStream(EventStreamArr, "gameStart") //TODO: check to make sure match random seek request - if b && (e.Source != "friend") { - load_msg = "Found random opponent!" - Root.loader.DrawMessage(load_msg) - go func() { - currentGameID = e.GameID - time.Sleep(time.Second) - Root.App.QueueUpdate(startNewOnlineGame) - }() + switch result { + case "accepted": + show("Accepted! Starting the game…") + done = nil // gameStart arrives on the event stream + case "declined": + leave(fmt.Sprintf("[red]%s declined the challenge.[-]", cv.Escape(c.DestUser))) + return + case "canceled": + leave("The challenge was cancelled.") + return + default: + if c.Type == 0 { + // a real-time seek's stream closes once paired; wait for gameStart + done = nil + continue } + leave("[red]Lost the connection to Lichess; the request was withdrawn.[-]") + return } - icon_index = Root.loader.DrawIcon(icon_index) - default: - Root.loader.DrawMessage(load_msg) + + case <-spinner.C: + i := icon + Root.App.QueueUpdateDraw(func() { Root.loader.DrawIcon(i) }) + icon = (icon + 1) % len(KnightIconMap) } } } diff --git a/pkg/sound.go b/pkg/sound.go new file mode 100644 index 0000000..9ba0c78 --- /dev/null +++ b/pkg/sound.go @@ -0,0 +1,362 @@ +package pkg + +import ( + "bytes" + "encoding/binary" + "math" + "math/rand/v2" + "os" + "path/filepath" + "sync" + "sync/atomic" + "time" + + "github.com/nate-xyz/chess-cli/api" + "github.com/notnil/chess" +) + +// Sound: chess-cli's own sounds, synthesised here (no audio files), in two +// themes: Retro (chiptune square waves, the default) and Wood (a softer +// piece-on-board thock). They're written once as small WAV files in the +// cache folder and played with the system's player (see sound_*.go), so +// there's no audio library and the builds stay static. + +type soundEvent int + +const ( + soundMove soundEvent = iota + soundCapture + soundCheck + soundCastle + soundStart // a game starts + soundVictory // you won (or a two-player game was decided) + soundDefeat + soundDraw + soundLowTime + soundError // an illegal or wrong move + soundConfirm // a right move in a puzzle + soundEventCount +) + +var soundNames = [...]string{"move", "capture", "check", "castle", "start", "victory", "defeat", "draw", "lowtime", "error", "confirm"} + +// Sound themes, as saved in the config ("" is the default, Retro). +const ( + SoundRetro = "retro" + SoundWood = "wood" + SoundOff = "off" +) + +var soundThemes = []string{SoundRetro, SoundWood, SoundOff} + +var soundThemeNames = map[string]string{SoundRetro: "Retro", SoundWood: "Wood", SoundOff: "Off"} + +// soundTheme is the chosen theme. +func soundTheme() string { + switch t := api.UserInfo.Sound; t { + case SoundWood, SoundOff: + return t + } + return SoundRetro +} + +func setSoundTheme(t string) { + _ = api.UpdateConfig(func(c *api.UserConfig) { c.Sound = t }) +} + +// soundsMuted turns sound off without changing the setting (tests). +var soundsMuted atomic.Bool + +var lastSound atomic.Int64 // unix nanos of the last sound started + +// playSound plays a sound in the chosen theme, without waiting. Sounds +// closer together than 35 ms are dropped (e.g. holding → in a study). +func playSound(ev soundEvent) { playSoundIn(soundTheme(), ev) } + +func playSoundIn(theme string, ev soundEvent) { + if theme == SoundOff || soundsMuted.Load() { + return + } + now := time.Now().UnixNano() + if last := lastSound.Load(); now-last < int64(35*time.Millisecond) || !lastSound.CompareAndSwap(last, now) { + return + } + go func() { + data := soundData(theme, ev) + path, err := soundFile(theme, ev, data) + if err != nil { + return + } + _ = playWAV(path, data) + }() +} + +// moveSound is the sound for a move: capture, check, castling or a move. +func moveSound(m *chess.Move) soundEvent { + switch { + case m == nil: + return soundMove + case m.HasTag(chess.Check): + return soundCheck + case m.HasTag(chess.Capture) || m.HasTag(chess.EnPassant): + return soundCapture + case m.HasTag(chess.KingSideCastle) || m.HasTag(chess.QueenSideCastle): + return soundCastle + } + return soundMove +} + +// resultSound is the sound at the end of a game: winner is chess.NoColor +// for a draw; me is the player's colour (chess.NoColor when two people +// play on one keyboard: any decisive result is a victory). +func resultSound(winner, me chess.Color) soundEvent { + switch { + case winner == chess.NoColor: + return soundDraw + case me == chess.NoColor || winner == me: + return soundVictory + } + return soundDefeat +} + +// lowTime reports whether a clock is low enough for the warning sound: +// under 10 seconds, or a tenth of the starting time in very fast games. +func lowTime(left, initial time.Duration) bool { + return initial >= 30*time.Second && left > 0 && left < min(10*time.Second, initial/10+5*time.Second) +} + +var ( + soundCache sync.Map // theme/event -> []byte + soundFilesMu sync.Mutex +) + +func soundData(theme string, ev soundEvent) []byte { + key := theme + "/" + soundNames[ev] + if b, ok := soundCache.Load(key); ok { + return b.([]byte) + } + b := wavBytes(synthesise(theme, ev)) + soundCache.Store(key, b) + return b +} + +// soundFile writes a sound to the cache folder (once) and returns its path. +func soundFile(theme string, ev soundEvent, data []byte) (string, error) { + dir, err := os.UserCacheDir() + if err != nil { + return "", err + } + dir = filepath.Join(dir, "chess-cli", "sounds") + // the version changes when the sounds do, so old files aren't reused + p := filepath.Join(dir, theme+"-"+soundNames[ev]+"-v1.wav") + soundFilesMu.Lock() + defer soundFilesMu.Unlock() + if st, err := os.Stat(p); err == nil && st.Size() == int64(len(data)) { + return p, nil + } + if err := os.MkdirAll(dir, 0o755); err != nil { + return "", err + } + tmp := p + ".tmp" + if err := os.WriteFile(tmp, data, 0o644); err != nil { + return "", err + } + return p, os.Rename(tmp, p) +} + +// Synthesis. + +const sampleRate = 22050 + +type wave int + +const ( + square wave = iota + triangle + sine + noise +) + +// note is one sound in a mix: a wave from f0 gliding to f1 Hz, starting at +// start seconds, lasting dur, with an attack and an exponential decay. +type note struct { + start, dur float64 + f0, f1 float64 + w wave + amp float64 + decay float64 // time constant in seconds (0 = flat) + lowpass float64 // 0-1 smoothing for noise (0 = none) +} + +func synthesise(theme string, ev soundEvent) []float64 { + var notes []note + if theme == SoundWood { + notes = woodSound(ev) + } else { + notes = retroSound(ev) + } + end := 0.0 + for _, n := range notes { + end = math.Max(end, n.start+n.dur) + } + out := make([]float64, int((end+0.01)*sampleRate)) + rng := rand.New(rand.NewPCG(uint64(ev)+1, 7)) // the same noise every time + for _, n := range notes { + i0 := int(n.start * sampleRate) + count := int(n.dur * sampleRate) + phase, lp := 0.0, 0.0 + for i := 0; i < count && i0+i < len(out); i++ { + t := float64(i) / sampleRate + f := n.f0 + (n.f1-n.f0)*t/n.dur + phase += f / sampleRate + var v float64 + switch n.w { + case square: + v = 1 + if math.Mod(phase, 1) >= 0.5 { + v = -1 + } + case triangle: + v = 4*math.Abs(math.Mod(phase, 1)-0.5) - 1 + case sine: + v = math.Sin(2 * math.Pi * phase) + case noise: + v = rng.Float64()*2 - 1 + if n.lowpass > 0 { + lp += (v - lp) * (1 - n.lowpass) + v = lp * 2 + } + } + env := math.Min(1, t/0.002) // 2 ms attack: no click + if n.decay > 0 { + env *= math.Exp(-t / n.decay) + } + env *= math.Min(1, (n.dur-t)/0.004) // and a 4 ms release + out[i0+i] += v * n.amp * env + } + } + return out +} + +// Notes in Hz. +const ( + c5, d5, e5, f5, g5, a5, b5 = 523.25, 587.33, 659.25, 698.46, 783.99, 880.0, 987.77 + c6, e6, g6 = 1046.5, 1318.5, 1568.0 + bb4, eb5 = 466.16, 622.25 +) + +// retroSound: square-wave blips, like an 8-bit console. +func retroSound(ev soundEvent) []note { + blip := func(start, f0, f1, dur, amp float64) note { + return note{start: start, dur: dur, f0: f0, f1: f1, w: square, amp: amp, decay: dur / 2} + } + arp := func(freqs []float64, step, last float64) []note { + var ns []note + for i, f := range freqs { + d := step + if i == len(freqs)-1 { + d = last + } + ns = append(ns, note{start: float64(i) * step, dur: d, f0: f, f1: f, w: square, amp: 0.16, decay: d * 0.7}) + } + return ns + } + switch ev { + case soundMove: + return []note{blip(0, 700, 520, 0.05, 0.2)} + case soundCapture: + return []note{ + {start: 0, dur: 0.06, w: noise, amp: 0.28, decay: 0.025}, + blip(0, 420, 200, 0.08, 0.2), + } + case soundCheck: + return []note{blip(0, 990, 990, 0.05, 0.18), blip(0.06, 1320, 1320, 0.07, 0.18)} + case soundCastle: + return []note{blip(0, 700, 520, 0.05, 0.2), blip(0.07, 620, 460, 0.05, 0.2)} + case soundStart: + return arp([]float64{c5, e5, g5, c6}, 0.07, 0.16) + case soundVictory: + return arp([]float64{g5, c6, e6, g6}, 0.08, 0.3) + case soundDefeat: + return arp([]float64{c5, bb4, 392, 311.13}, 0.11, 0.3) + case soundDraw: + return arp([]float64{e5, e5}, 0.13, 0.22) + case soundLowTime: + return []note{blip(0, 1760, 1760, 0.06, 0.14), blip(0.12, 1760, 1760, 0.06, 0.14)} + case soundError: + return []note{{start: 0, dur: 0.14, f0: 140, f1: 110, w: square, amp: 0.16, decay: 0.1}} + case soundConfirm: + return arp([]float64{g5, c6}, 0.06, 0.12) + } + return nil +} + +// woodSound: a soft thock for moves, gentle chimes for the rest. +func woodSound(ev soundEvent) []note { + thock := func(start, amp float64) []note { + return []note{ + {start: start, dur: 0.09, f0: 210, f1: 150, w: sine, amp: amp, decay: 0.025}, + {start: start, dur: 0.02, w: noise, amp: amp * 0.7, decay: 0.006, lowpass: 0.6}, + } + } + chime := func(freqs []float64, step float64) []note { + var ns []note + for i, f := range freqs { + ns = append(ns, + note{start: float64(i) * step, dur: 0.45, f0: f, f1: f, w: sine, amp: 0.16, decay: 0.15}, + note{start: float64(i) * step, dur: 0.3, f0: 2 * f, f1: 2 * f, w: sine, amp: 0.04, decay: 0.08}) + } + return ns + } + switch ev { + case soundMove: + return thock(0, 0.5) + case soundCapture: + return append(thock(0, 0.55), thock(0.045, 0.45)...) + case soundCheck: + return append(thock(0, 0.5), chime([]float64{e6}, 0)...) + case soundCastle: + return append(thock(0, 0.45), thock(0.09, 0.45)...) + case soundStart: + return chime([]float64{e5, b5}, 0.12) + case soundVictory: + return chime([]float64{c5, e5, g5, c6}, 0.11) + case soundDefeat: + return chime([]float64{g5, e5, c5}, 0.14) + case soundDraw: + return chime([]float64{d5, d5}, 0.16) + case soundLowTime: + return chime([]float64{a5, a5}, 0.14) + case soundError: + return []note{ + {start: 0, dur: 0.16, f0: 120, f1: 100, w: sine, amp: 0.35, decay: 0.06}, + {start: 0, dur: 0.05, w: noise, amp: 0.15, decay: 0.02, lowpass: 0.8}, + } + case soundConfirm: + return chime([]float64{g5, d5 * 2}, 0.08) + } + return nil +} + +// wavBytes encodes samples (-1..1) as a 16-bit mono WAV file. +func wavBytes(samples []float64) []byte { + var b bytes.Buffer + data := len(samples) * 2 + w := func(v any) { _ = binary.Write(&b, binary.LittleEndian, v) } + b.WriteString("RIFF") + w(uint32(36 + data)) + b.WriteString("WAVEfmt ") + w(uint32(16)) + w(uint16(1)) // PCM + w(uint16(1)) // mono + w(uint32(sampleRate)) + w(uint32(sampleRate * 2)) + w(uint16(2)) + w(uint16(16)) + b.WriteString("data") + w(uint32(data)) + for _, s := range samples { + w(int16(math.Max(-1, math.Min(1, s)) * 32000)) + } + return b.Bytes() +} diff --git a/pkg/sound_other.go b/pkg/sound_other.go new file mode 100644 index 0000000..0b5175f --- /dev/null +++ b/pkg/sound_other.go @@ -0,0 +1,50 @@ +//go:build !windows + +package pkg + +import ( + "errors" + "os/exec" + "runtime" + "sync" +) + +// Playing a WAV file with the system's player: afplay on macOS; on Linux +// and the BSDs PipeWire's pw-play, PulseAudio's paplay or ALSA's aplay, +// whichever is installed. + +var soundPlayer = sync.OnceValue(func() []string { + candidates := [][]string{{"pw-play"}, {"paplay"}, {"aplay", "-q"}} + if runtime.GOOS == "darwin" { + candidates = [][]string{{"afplay"}} + } + for _, c := range candidates { + if p, err := exec.LookPath(c[0]); err == nil { + return append([]string{p}, c[1:]...) + } + } + return nil +}) + +// soundAvailable reports whether chess-cli can play sound here. +func soundAvailable() bool { return soundPlayer() != nil } + +func playWAV(path string, _ []byte) error { + player := soundPlayer() + if player == nil { + return errors.New("no audio player found") + } + cmd := exec.Command(player[0], append(player[1:], path)...) + if err := cmd.Start(); err != nil { + return err + } + return cmd.Wait() +} + +// soundHelp says what to install when there's no player. +func soundHelp() string { + if runtime.GOOS == "darwin" { + return "afplay not found" + } + return "no audio player found (install pipewire, pulseaudio-utils or alsa-utils)" +} diff --git a/pkg/sound_test.go b/pkg/sound_test.go new file mode 100644 index 0000000..7e75c75 --- /dev/null +++ b/pkg/sound_test.go @@ -0,0 +1,107 @@ +package pkg + +import ( + "encoding/binary" + "math" + "os" + "path/filepath" + "testing" + "time" + + cv "codeberg.org/tslocum/cview" + tc "github.com/gdamore/tcell/v3" + "github.com/nate-xyz/chess-cli/api" + "github.com/notnil/chess" +) + +func TestSoundsSynthesise(t *testing.T) { + for _, theme := range []string{SoundRetro, SoundWood} { + for ev := soundEvent(0); ev < soundEventCount; ev++ { + b := soundData(theme, ev) + if string(b[0:4]) != "RIFF" || string(b[8:12]) != "WAVE" || binary.LittleEndian.Uint32(b[24:28]) != sampleRate { + t.Fatalf("%s/%s: not a %d Hz WAV", theme, soundNames[ev], sampleRate) + } + n := int(binary.LittleEndian.Uint32(b[40:44])) / 2 + secs := float64(n) / sampleRate + peak := 0.0 + for i := 0; i < n; i++ { + peak = math.Max(peak, math.Abs(float64(int16(binary.LittleEndian.Uint16(b[44+2*i:]))))) + } + if secs < 0.03 || secs > 1 { + t.Errorf("%s/%s lasts %.2fs", theme, soundNames[ev], secs) + } + if peak < 3000 || peak >= 32767 { + t.Errorf("%s/%s peak %v: too quiet or clipping", theme, soundNames[ev], peak) + } + } + } +} + +func TestSoundFileCached(t *testing.T) { + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + data := soundData(SoundRetro, soundMove) + p, err := soundFile(SoundRetro, soundMove, data) + if err != nil { + t.Fatal(err) + } + if got, _ := os.ReadFile(p); len(got) != len(data) || filepath.Ext(p) != ".wav" { + t.Errorf("cached file %s: %d bytes", p, len(got)) + } +} + +func TestWhichSound(t *testing.T) { + g := chess.NewGame() + for _, m := range []string{"e4", "d5", "exd5", "Qxd5", "Nc3", "Qe5+"} { + if err := g.MoveStr(m); err != nil { + t.Fatal(err) + } + } + moves := g.Moves() + if moveSound(moves[0]) != soundMove || moveSound(moves[2]) != soundCapture || moveSound(moves[5]) != soundCheck { + t.Error("move / capture / check sounds") + } + if resultSound(chess.White, chess.White) != soundVictory || resultSound(chess.White, chess.Black) != soundDefeat || + resultSound(chess.NoColor, chess.White) != soundDraw || resultSound(chess.Black, chess.NoColor) != soundVictory { + t.Error("result sounds") + } + if !lowTime(8*time.Second, 5*time.Minute) || lowTime(20*time.Second, 5*time.Minute) || lowTime(5*time.Second, 0) { + t.Error("low time: under 10 s, not without a clock") + } + if !lowTime(9*time.Second, time.Minute) || lowTime(12*time.Second, time.Minute) { + t.Error("low time in a 1-minute game") + } +} + +func TestSoundSetting(t *testing.T) { + startTestApp(t, 160, 50) + onUI(func() { + defer setSoundTheme("") + if soundTheme() != SoundRetro { + t.Errorf("default theme %q, want retro", soundTheme()) + } + setSoundTheme(SoundOff) + if soundTheme() != SoundOff || api.UserInfo.Sound != SoundOff { + t.Error("turning sound off") + } + }) +} + +// The first-run screen asks about sound after the rendering choice. +func TestOnboardSound(t *testing.T) { + startTestApp(t, 160, 50) + onUI(func() { + defer func() { api.UserInfo.Sound, api.UserInfo.SoundAsked = "", false }() + api.UserInfo.SoundAsked = false + info := textBox(0) + list := menuList() + onboardSound(list, info) + if list.GetItemCount() != 3 { + t.Fatalf("%d sound choices", list.GetItemCount()) + } + list.SetCurrentItem(2) // No sound + list.InputHandler()(tc.NewEventKey(tc.KeyEnter, "", tc.ModNone), func(cv.Primitive) {}) + if !api.UserInfo.SoundAsked || soundTheme() != SoundOff { + t.Errorf("after choosing no sound: asked %v, theme %q", api.UserInfo.SoundAsked, soundTheme()) + } + }) +} diff --git a/pkg/sound_windows.go b/pkg/sound_windows.go new file mode 100644 index 0000000..fdbb5a3 --- /dev/null +++ b/pkg/sound_windows.go @@ -0,0 +1,42 @@ +//go:build windows + +package pkg + +import ( + "sync" + "syscall" + "unsafe" +) + +// Playing a WAV on Windows with winmm's PlaySound, from memory: built into +// Windows, no cgo needed. + +var procPlaySound = syscall.NewLazyDLL("winmm.dll").NewProc("PlaySoundW") + +const ( + sndAsync = 0x0001 + sndNoDefault = 0x0002 + sndMemory = 0x0004 +) + +func soundAvailable() bool { return procPlaySound.Find() == nil } + +// playing keeps the sound being played alive (PlaySound reads it while it +// plays asynchronously). +var ( + playingMu sync.Mutex + playing []byte +) + +func playWAV(_ string, data []byte) error { + playingMu.Lock() + defer playingMu.Unlock() + playing = data + r, _, err := procPlaySound.Call(uintptr(unsafe.Pointer(&playing[0])), 0, sndAsync|sndNoDefault|sndMemory) + if r == 0 { + return err + } + return nil +} + +func soundHelp() string { return "Windows sound isn't available" } diff --git a/pkg/stockfish_download.go b/pkg/stockfish_download.go new file mode 100644 index 0000000..1029e57 --- /dev/null +++ b/pkg/stockfish_download.go @@ -0,0 +1,280 @@ +package pkg + +import ( + "archive/tar" + "archive/zip" + "compress/gzip" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "path" + "path/filepath" + "runtime" + "strings" + "time" + + "github.com/nate-xyz/chess-cli/api" +) + +// Downloading Stockfish for people who don't have it: the official release +// from GitHub, checked against the SHA-256 GitHub publishes, unpacked into +// chess-cli's config folder (no system install, no admin rights). Stockfish +// is GPLv3; its licence is kept next to it. + +const stockfishReleases = "https://api.github.com/repos/official-stockfish/Stockfish/releases/latest" + +var downloadClient = &http.Client{Timeout: 10 * time.Minute} + +// stockfishAssetName is the release file for this OS and CPU, e.g. +// "stockfish-linux-x86-64-universal.tar.gz". +func stockfishAssetName() (string, error) { + arch := map[string]string{"amd64": "x86-64", "arm64": "arm64", "riscv64": "riscv64"}[runtime.GOARCH] + switch { + case runtime.GOOS == "darwin": + return "stockfish-macos-universal.tar.gz", nil + case runtime.GOOS == "linux" && arch != "": + return "stockfish-linux-" + arch + "-universal.tar.gz", nil + case runtime.GOOS == "windows" && (arch == "x86-64" || arch == "arm64"): + return "stockfish-windows-" + arch + "-universal.zip", nil + } + return "", fmt.Errorf("no Stockfish download for %s/%s; install it yourself", runtime.GOOS, runtime.GOARCH) +} + +// downloadedStockfishDir is where a downloaded Stockfish lives. +func downloadedStockfishDir() (string, error) { + dir, err := api.ConfigDir() + if err != nil { + return "", err + } + return filepath.Join(dir, "stockfish"), nil +} + +// downloadedStockfish is the path of a previously downloaded Stockfish, or "". +func downloadedStockfish() string { + dir, err := downloadedStockfishDir() + if err != nil { + return "" + } + name := "stockfish" + if runtime.GOOS == "windows" { + name += ".exe" + } + p := filepath.Join(dir, name) + if st, err := os.Stat(p); err == nil && !st.IsDir() { + return p + } + return "" +} + +// DownloadStockfish fetches and unpacks the latest Stockfish, reporting +// progress (0-1), and returns the engine's path. +func DownloadStockfish(progress func(done, total int64)) (string, error) { + assetName, err := stockfishAssetName() + if err != nil { + return "", err + } + var release struct { + Tag string `json:"tag_name"` + Assets []struct { + Name string `json:"name"` + URL string `json:"browser_download_url"` + Size int64 `json:"size"` + Digest string `json:"digest"` + } `json:"assets"` + } + res, err := downloadClient.Get(stockfishReleases) + if err != nil { + return "", err + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + return "", fmt.Errorf("GitHub: %s", res.Status) + } + if err := json.NewDecoder(res.Body).Decode(&release); err != nil { + return "", err + } + var url, digest string + var size int64 + for _, a := range release.Assets { + if a.Name == assetName { + url, digest, size = a.URL, strings.TrimPrefix(a.Digest, "sha256:"), a.Size + } + } + if url == "" { + return "", fmt.Errorf("%s isn't in Stockfish's latest release", assetName) + } + if digest == "" { + return "", errors.New("GitHub didn't give a checksum for the download, so it can't be verified") + } + + dir, err := downloadedStockfishDir() + if err != nil { + return "", err + } + if err := os.MkdirAll(dir, 0o755); err != nil { + return "", err + } + archive := filepath.Join(dir, assetName+".part") + defer os.Remove(archive) + if err := downloadFile(url, archive, size, digest, progress); err != nil { + return "", err + } + return unpackStockfish(archive, assetName, dir) +} + +// downloadFile saves url to dst, checking its SHA-256. +func downloadFile(url, dst string, size int64, wantSHA string, progress func(done, total int64)) error { + res, err := downloadClient.Get(url) + if err != nil { + return err + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + return fmt.Errorf("download: %s", res.Status) + } + if size <= 0 { + size = res.ContentLength + } + f, err := os.Create(dst) + if err != nil { + return err + } + defer f.Close() + h := sha256.New() + buf := make([]byte, 256<<10) + var done int64 + for { + n, err := res.Body.Read(buf) + if n > 0 { + if _, werr := f.Write(buf[:n]); werr != nil { + return werr + } + h.Write(buf[:n]) + done += int64(n) + if progress != nil { + progress(done, size) + } + } + if err == io.EOF { + break + } + if err != nil { + return err + } + } + if got := hex.EncodeToString(h.Sum(nil)); !strings.EqualFold(got, wantSHA) { + return errors.New("the download is corrupt (checksum mismatch); try again") + } + return f.Close() +} + +// unpackStockfish extracts the engine (and its licence) from the archive: +// the engine is the file named after the archive, e.g. +// stockfish/stockfish-linux-x86-64-universal. +func unpackStockfish(archive, assetName, dir string) (string, error) { + base := strings.TrimSuffix(strings.TrimSuffix(assetName, ".tar.gz"), ".zip") + engineName := "stockfish" + if strings.HasSuffix(assetName, ".zip") { + engineName += ".exe" + } + enginePath := filepath.Join(dir, engineName) + found := false + extract := func(name string, r io.Reader) error { + switch b := path.Base(name); { + case b == base || b == base+".exe": + found = true + return writeFile(enginePath, r, 0o755) + case b == "Copying.txt": + return writeFile(filepath.Join(dir, "Copying.txt"), r, 0o644) + } + return nil + } + if strings.HasSuffix(assetName, ".zip") { + z, err := zip.OpenReader(archive) + if err != nil { + return "", err + } + defer z.Close() + for _, f := range z.File { + rc, err := f.Open() + if err != nil { + return "", err + } + err = extract(f.Name, rc) + rc.Close() + if err != nil { + return "", err + } + } + } else { + f, err := os.Open(archive) + if err != nil { + return "", err + } + defer f.Close() + gz, err := gzip.NewReader(f) + if err != nil { + return "", err + } + tr := tar.NewReader(gz) + for { + hdr, err := tr.Next() + if err == io.EOF { + break + } + if err != nil { + return "", err + } + if hdr.Typeflag == tar.TypeReg { + if err := extract(hdr.Name, tr); err != nil { + return "", err + } + } + } + } + if !found { + return "", errors.New("couldn't find the engine in the download") + } + return enginePath, nil +} + +func writeFile(p string, r io.Reader, mode os.FileMode) error { + tmp := p + ".tmp" + f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode) + if err != nil { + return err + } + if _, err := io.Copy(f, io.LimitReader(r, 512<<20)); err != nil { + f.Close() + return err + } + if err := f.Close(); err != nil { + return err + } + return os.Rename(tmp, p) +} + +// installHint is how to install Stockfish yourself on this system. +func installHint() string { + switch runtime.GOOS { + case "darwin": + return "brew install stockfish" + case "windows": + return "winget install stockfish" + case "linux": + for _, pm := range []struct{ bin, cmd string }{ + {"apt", "sudo apt install stockfish"}, {"dnf", "sudo dnf install stockfish"}, + {"pacman", "sudo pacman -S stockfish"}, {"zypper", "sudo zypper install stockfish"}, + } { + if _, err := os.Stat("/usr/bin/" + pm.bin); err == nil { + return pm.cmd + } + } + } + return "see stockfishchess.org/download" +} diff --git a/pkg/stockfish_download_test.go b/pkg/stockfish_download_test.go new file mode 100644 index 0000000..5129d46 --- /dev/null +++ b/pkg/stockfish_download_test.go @@ -0,0 +1,95 @@ +package pkg + +import ( + "archive/tar" + "archive/zip" + "bytes" + "compress/gzip" + "crypto/sha256" + "encoding/hex" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestUnpackStockfishTar(t *testing.T) { + dir := t.TempDir() + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + tw := tar.NewWriter(gz) + add := func(name, body string) { + tw.WriteHeader(&tar.Header{Name: name, Mode: 0o755, Size: int64(len(body)), Typeflag: tar.TypeReg}) + tw.Write([]byte(body)) + } + add("stockfish/README.md", "readme") + add("stockfish/Copying.txt", "GPL") + add("stockfish/stockfish-linux-x86-64-universal", "ENGINE") + add("../../escape", "nope") // must not be written anywhere + tw.Close() + gz.Close() + archive := filepath.Join(dir, "sf.tar.gz") + os.WriteFile(archive, buf.Bytes(), 0o644) + + path, err := unpackStockfish(archive, "stockfish-linux-x86-64-universal.tar.gz", dir) + if err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(path); string(b) != "ENGINE" { + t.Errorf("engine = %q", b) + } + if st, _ := os.Stat(path); runtime.GOOS != "windows" && st.Mode().Perm()&0o100 == 0 { // no executable bit on Windows + t.Error("engine isn't executable") + } + if _, err := os.Stat(filepath.Join(dir, "Copying.txt")); err != nil { + t.Error("licence not kept") + } + if _, err := os.Stat(filepath.Join(dir, "..", "..", "escape")); err == nil { + t.Error("archive wrote outside its folder") + } +} + +func TestUnpackStockfishZip(t *testing.T) { + dir := t.TempDir() + var buf bytes.Buffer + zw := zip.NewWriter(&buf) + w, _ := zw.Create("stockfish/stockfish-windows-x86-64-universal.exe") + w.Write([]byte("EXE")) + zw.Close() + archive := filepath.Join(dir, "sf.zip") + os.WriteFile(archive, buf.Bytes(), 0o644) + path, err := unpackStockfish(archive, "stockfish-windows-x86-64-universal.zip", dir) + if err != nil { + t.Fatal(err) + } + if !strings.HasSuffix(path, "stockfish.exe") { + t.Errorf("path %s", path) + } +} + +func TestDownloadChecksum(t *testing.T) { + body := []byte("the real engine") + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(body) })) + defer srv.Close() + sum := sha256.Sum256(body) + dst := filepath.Join(t.TempDir(), "f") + if err := downloadFile(srv.URL, dst, int64(len(body)), hex.EncodeToString(sum[:]), nil); err != nil { + t.Fatalf("good download rejected: %v", err) + } + if err := downloadFile(srv.URL, dst, int64(len(body)), strings.Repeat("0", 64), nil); err == nil { + t.Error("corrupt download accepted") + } +} + +func TestStockfishAssetName(t *testing.T) { + name, err := stockfishAssetName() + if err != nil { + t.Skip(err) + } + if !strings.HasPrefix(name, "stockfish-") || !(strings.HasSuffix(name, ".tar.gz") || strings.HasSuffix(name, ".zip")) { + t.Errorf("asset %q", name) + } +} diff --git a/pkg/study.go b/pkg/study.go new file mode 100644 index 0000000..ff2f409 --- /dev/null +++ b/pkg/study.go @@ -0,0 +1,418 @@ +package pkg + +import ( + "fmt" + "strings" + + cv "codeberg.org/tslocum/cview" + tc "github.com/gdamore/tcell/v3" + "github.com/nate-xyz/chess-cli/api" + "github.com/notnil/chess" +) + +// Studies: reading a Lichess study, chapter by chapter. The board shows the +// current line from the chapter's start to its end; ← → (or the wheel, [ ]) +// step along it, and clicking a move, in a variation too, switches to that +// line. Comments and symbols are in the move list; the study's arrows and +// circles are drawn on the board. + +type StudyScreen struct { + Board *BoardView + Info *cv.TextView + Moves *cv.TextView + Chapters *cv.List + List *cv.List + Side *cv.Flex + + gen int // bumped for each study opened; stale downloads are dropped + name string + chapters []*studyChapter + ch *studyChapter + cur *studyNode + line []*studyNode // the line on the board: root ... end + white bool + syncing bool // highlighting a move ourselves, not a click + shownAt *studyNode // the node the move list was last drawn for + chapterTitle func(string) + infoW int // the width the top box was sized for + soundAt *studyNode // the move whose sound last played +} + +const studyRibbon = " chess-cli · study │ ← → moves, ↑ ↓ start/end │ click a move to go there │ f flip │ Tab menu │ Ctrl-C quit" + +func (ss *StudyScreen) Init() cv.Primitive { + ss.Board = NewBoardView(func(chess.Square) {}) // clicks: drawing only + ss.Board.browse = true + ss.Info = textBox(cv.AlignLeft) + ss.Moves = textBox(cv.AlignLeft) + ss.Moves.SetRegions(true) + boxed(ss.Moves.Box, "Moves") + moveLists = append(moveLists, ss.Moves) + applyUIColours() + ss.Chapters = menuList() + ss.Chapters.SetScrollBarVisibility(cv.ScrollBarNever) + ss.chapterTitle = boxed(ss.Chapters.Box, "Chapters") + onHoverLeave(ss.Chapters, func() { // hovering moved the selection: back to the chapter showing + for i, c := range ss.chapters { + if c == ss.ch { + ss.Chapters.SetCurrentItem(i) + } + } + }) + ss.List = menuList() + for _, it := range []struct { + text string + key rune + f func() + }{{"Flip board", 'f', ss.flip}, {"Leave", 'x', gotoWelcome}} { + ss.List.AddItem(menuItem(it.text, it.key, it.f)) + } + + ss.Moves.SetHighlightedFunc(func(added, _, _ []string) { + var id int + if ss.syncing || len(added) == 0 || ss.ch == nil { + return + } + if _, err := fmt.Sscanf(added[0], "n%d", &id); err != nil || id < 0 || id >= len(ss.ch.nodes) { + return + } + ss.goTo(ss.ch.nodes[id]) + // the click focused the move list; keep the focus where it was + if prev := Root.App.GetFocus(); prev != nil && prev != ss.Moves { + go Root.App.QueueUpdateDraw(func() { Root.App.SetFocus(prev) }) + } + }) + ss.Board.mu.Lock() + ss.Board.onShown = func(ply int) { // the wheel or [ ] moved along the line + if ply >= 0 && ply < len(ss.line) && ss.line[ply] != ss.cur { + ss.cur = ss.line[ply] + ss.showNode() + } + } + ss.Board.mu.Unlock() + + side := cv.NewFlex() + side.SetDirection(cv.FlexRow) + side.AddItem(ss.Info, 4, 0, false) + ss.Info.SetDrawFunc(func(_ tc.Screen, x, y, w, h int) (int, int, int, int) { + if ss.infoW != 0 && w != ss.infoW { // the window was resized: refit the tags + ss.infoW = w + go Root.App.QueueUpdateDraw(ss.fitInfo) + } + return x, y, w, h + }) + side.AddItem(styledText{ss.Moves}, 0, 1, false) // nested side lines get styled underlines + side.AddItem(ss.Chapters, 0, 0, false) + side.AddItem(ss.List, 2, 0, false) + ss.Side = side + + // keys on the board: arrows walk the line (Lichess's keys) + ss.Board.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { + switch event.Key() { + case tc.KeyLeft: + ss.step(-1) + case tc.KeyRight: + ss.step(1) + case tc.KeyUp, tc.KeyHome: + ss.step(-len(ss.line)) + case tc.KeyDown, tc.KeyEnd: + ss.step(len(ss.line)) + case tc.KeyTab: + if ss.Chapters.GetItemCount() > 1 { + Root.App.SetFocus(ss.Chapters) + } else { + Root.App.SetFocus(ss.List) + } + default: + if event.Key() == tc.KeyRune && (event.Str() == "[" || event.Str() == "]") { + ss.step(map[string]int{"[": -1, "]": 1}[event.Str()]) + return nil + } + return event + } + return nil + }) + ss.Chapters.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { + switch event.Key() { + case tc.KeyTab: + Root.App.SetFocus(ss.List) + return nil + case tc.KeyEscape: + Root.App.SetFocus(ss.Board) + return nil + } + return event + }) + ss.List.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { + if event.Key() == tc.KeyTab || event.Key() == tc.KeyEscape { + Root.App.SetFocus(ss.Board) + return nil + } + return event + }) + registerMenus("study", false, ss.List, ss.Chapters) + return newGameLayout(ss.Board, side, studyRibbon) +} + +// openStudy downloads a study and shows it, starting at chapter (an ID, or +// "" for the first). +func openStudy(id, chapter string) { + ss := Root.study + ss.gen++ + gen := ss.gen + ss.name, ss.chapters, ss.ch, ss.cur, ss.line = "", nil, nil, nil, nil + ss.Chapters.Clear() + ss.Side.ResizeItem(ss.Chapters, 0, 0) + ss.Moves.SetText("") + ss.Info.SetText("[#a0a0a0]Loading the study…[-]") + ss.Board.SetPosition(chess.StartingPosition(), true) + ss.Board.SetHistory(nil, nil) + ss.Board.SetLastMove(chess.NoSquare, chess.NoSquare) + ss.Board.HideClockBars() + ss.Board.SetGlyph(chess.NoSquare, 0) + Root.Switch("study") + Root.App.SetFocus(ss.Board) + go func() { + pgn, err := api.GetStudyPGN(id) + Root.App.QueueUpdateDraw(func() { + if gen != ss.gen { + return + } + if err != nil { + ss.Info.SetText(fmt.Sprintf("[red]Couldn't open the study: %s[-]", cv.Escape(err.Error()))) + return + } + ss.show(parseStudyPGN(pgn), chapter) + }) + }() +} + +// show displays a downloaded study. +func (ss *StudyScreen) show(chapters []*studyChapter, chapter string) { + if len(chapters) == 0 { + ss.Info.SetText("[yellow]This study has no chapters.[-]") + return + } + ss.chapters = chapters + ss.name = chapters[0].studyName() + start := 0 + ss.Chapters.Clear() + for i, c := range chapters { + i := i + item := cv.NewListItem("") + item.SetSelectedFunc(func() { ss.selectChapter(i) }) + ss.Chapters.AddItem(item) + if chapter != "" && c.chapterID() == chapter { + start = i + } + } + rows := 0 + if len(chapters) > 1 { + rows = min(len(chapters), 10) + 2 // and the box + } + ss.Side.ResizeItem(ss.Chapters, rows, 0) + ss.selectChapter(start) +} + +func (ss *StudyScreen) selectChapter(i int) { + if i < 0 || i >= len(ss.chapters) { + return + } + c := ss.chapters[i] + ss.ch, ss.white = c, c.white + ss.Chapters.SetCurrentItem(i) + width := len(fmt.Sprint(len(ss.chapters))) + for j := range ss.chapters { // numbered, and the one showing marked + mark := " " + if j == i { + mark = "▸ " + } + ss.Chapters.GetItem(j).SetMainText(mark + ss.chapterLabel(j, width)) + } + ss.chapterTitle(fmt.Sprintf("Chapter %d of %d", i+1, len(ss.chapters))) + info := "[::b]" + ss.chapterLabel(i, 0) + "[::-]" + if ss.name != "" { + info = "[#a0a0a0]" + escapeText(ss.name) + "[-]\n" + info + } + if tags := chapterTags(c); tags != "" { + info += "\n[#a0a0a0]" + escapeText(tags) + "[-]" + } + ss.Info.SetText(info) + ss.fitInfo() + ss.shownAt = nil + ss.Moves.ScrollToBeginning() + ss.goTo(c.root) +} + +// fitInfo sizes the top box to its text, wrapped to the sidebar's width. +func (ss *StudyScreen) fitInfo() { + _, _, w, _ := ss.Side.GetInnerRect() + if w <= 0 { + w = 40 + } + rows := 0 + for _, line := range strings.Split(ss.Info.GetText(false), "\n") { + rows += max(1, len(cv.WordWrap(line, w))) + } + ss.infoW = w + ss.Side.ResizeItem(ss.Info, min(rows, 9)+1, 0) // and a blank line under it + ss.Info.ScrollToBeginning() +} + +// chapterLabel is "12. Fischer - Sherwin: …", the number padded to width. +func (ss *StudyScreen) chapterLabel(i, width int) string { + title := escapeText(ss.chapters[i].name()) + if len(ss.chapters) == 1 { + return title + } + return fmt.Sprintf("%*d. %s", width, i+1, title) +} + +// goTo shows node n: the board gets n's line and steps to it. +func (ss *StudyScreen) goTo(n *studyNode) { + ss.cur = n + ss.line = n.line() + positions := make([]*chess.Position, len(ss.line)) + moves := make([]*chess.Move, 0, len(ss.line)-1) + for i, x := range ss.line { + positions[i] = x.pos + if x.move != nil { + moves = append(moves, x.move) + } + } + end := ss.line[len(ss.line)-1] + b := ss.Board + b.SetPosition(end.pos, ss.white) + b.SetHistory(nil, nil) // a new line, even if it's as long as the last + b.SetHistory(positions, moves) + if end.move != nil { + b.SetLastMove(end.move.S1(), end.move.S2()) + } else { + b.SetLastMove(chess.NoSquare, chess.NoSquare) + } + b.ShowPly(n.ply) + top, bottom := playerBar(ss.ch, chess.Black), playerBar(ss.ch, chess.White) + if !ss.white { + top, bottom = bottom, top + } + b.SetClockBars(top, bottom) + b.mu.Lock() + b.shownPly = n.ply // already showing it + b.mu.Unlock() + ss.showNode() +} + +// showNode highlights the current move and draws its arrows and circles. +func (ss *StudyScreen) showNode() { + n := ss.cur + if n == nil || ss.ch == nil { + return + } + if n != ss.shownAt { // redraw the list with this move's comment and side lines tinted + ss.shownAt = n + text := studyMoveText(ss.ch, n) + if ss.ch.problem != "" { + text += "\n[yellow]Stopped reading part of this chapter: " + escapeText(ss.ch.problem) + "[-]\n" + } + ss.Moves.SetText(text) + } + ss.syncing = true + if n.move == nil { + ss.Moves.Highlight() + } else { + ss.Moves.Highlight(fmt.Sprintf("n%d", n.id)) + ss.Moves.ScrollToHighlight() + } + ss.syncing = false + ss.Board.SetShapes(n.shapes) + if n.move != nil && n != ss.soundAt && Root.nav != nil { + if name, _ := Root.nav.GetFrontPanel(); name == "study" { + playSound(moveSound(n.move)) + } + } + ss.soundAt = n + if n.move != nil { + ss.Board.SetGlyph(n.move.S2(), glyphOf(n.nags)) + } else { + ss.Board.SetGlyph(chess.NoSquare, 0) + } +} + +// step moves along the line: positive = forward. +func (ss *StudyScreen) step(n int) { + if ss.cur == nil || len(ss.line) == 0 { + return + } + i := max(0, min(len(ss.line)-1, ss.cur.ply-ss.line[0].ply+n)) + ss.cur = ss.line[i] + ss.Board.ShowPly(ss.cur.ply - ss.line[0].ply) + ss.Board.mu.Lock() + ss.Board.shownPly = ss.cur.ply - ss.line[0].ply + ss.Board.mu.Unlock() + ss.showNode() +} + +func (ss *StudyScreen) flip() { + ss.white = !ss.white + if ss.cur != nil { + ss.goTo(ss.cur) + } +} + +// loadMyStudies fills a menu with the user's studies (loaded in the +// background), each opening the study. +func loadMyStudies(list *cv.List, back func()) { + list.Clear() + list.AddItem(cv.NewListItem("[#a0a0a0]Loading your studies…[-]")) + name := "" + if loggedIn() { + name = Root.User.Name + } + go func() { + var err error + if name == "" { + name, err = api.GetUsername() + } + var studies []api.StudyInfo + if err == nil { + studies, err = api.ListStudies(name) + } + Root.App.QueueUpdateDraw(func() { + list.Clear() + add := func(text, explain string, f func()) { + item := cv.NewListItem(text) + item.SetSecondaryText(explain) + item.SetSelectedFunc(f) + list.AddItem(item) + } + switch { + case err != nil: + add("[red]Couldn't load your studies[-]", err.Error(), back) + case len(studies) == 0: + add("No studies yet", "Make one on lichess.org/study", back) + } + for _, s := range studies { + s := s + add(cv.Escape(s.Name), "Updated "+s.Updated.Format("2 Jan 2006"), func() { openStudy(s.ID, "") }) + } + item := cv.NewListItem("Back") + item.SetShortcut('b') + item.SetSecondaryText("Go back to studies") + item.SetSelectedFunc(back) + list.AddItem(item) + }) + }() +} + +// askStudy asks for a study link or ID and opens it. +func askStudy() { + const q = "Which study?" + askText(q, "Link or ID: ", func(text string) { + id, chapter := api.StudyIDFrom(text) + if !api.ValidStudyID(id) { + promptError(q, api.ErrBadStudyID.Error()) + return + } + openStudy(id, chapter) + }) +} diff --git a/pkg/study_tags.go b/pkg/study_tags.go new file mode 100644 index 0000000..67c9342 --- /dev/null +++ b/pkg/study_tags.go @@ -0,0 +1,138 @@ +package pkg + +import ( + "fmt" + "strconv" + "strings" + "time" + + "github.com/notnil/chess" +) + +// A study chapter's tags (PGN headers), shown as Lichess does: the game's +// details under the chapter title, and each player beside the board with +// their title, name, rating and result. + +// tag is a header's value, or "" if it's missing or unknown ("?", "-"). +func (c *studyChapter) tag(key string) string { + v := strings.TrimSpace(c.headers[key]) + if v == "?" || v == "-" || v == "????.??.??" || v == "*" { + return "" + } + return v +} + +// chapterTags is the line of game details: where, when, round, time +// control, opening, annotator and variant, those that are known. +func chapterTags(c *studyChapter) string { + var parts []string + add := func(s string) { + if s != "" { + parts = append(parts, s) + } + } + if site := c.tag("Site"); !strings.Contains(site, "lichess.org/") { // Lichess puts the study link there + add(site) + } + add(pgnDate(c.tag("Date"))) + if r := c.tag("Round"); r != "" { + add("Round " + r) + } + add(pgnTimeControl(c.tag("TimeControl"))) + opening := strings.TrimSpace(c.tag("ECO") + " " + c.tag("Opening")) + add(opening) + if a := c.tag("Annotator"); a != "" && !strings.Contains(a, "lichess.org/") { + add("Annotated by " + a) + } + if v := c.tag("Variant"); v != "" && v != "Standard" && v != "From Position" { + add(v) + } + return strings.Join(parts, " · ") +} + +// pgnDate turns "1972.07.11" into "11 Jul 1972" (or "Jul 1972", "1972" +// when the day or month is unknown). +func pgnDate(d string) string { + f := strings.Split(d, ".") + if len(f) != 3 || strings.Contains(f[0], "?") { + return d + } + if t, err := time.Parse("2006.01.02", d); err == nil { + return t.Format("2 Jan 2006") + } + if t, err := time.Parse("2006.01", f[0]+"."+f[1]); err == nil { + return t.Format("Jan 2006") + } + return f[0] +} + +// pgnTimeControl reads a PGN TimeControl: "5400+30" is "90+30", and +// "40/7200:3600" is "120 min for 40 moves, then 60 min". +func pgnTimeControl(tcText string) string { + if tcText == "" { + return "" + } + mins := func(s string) (string, bool) { + n, err := strconv.Atoi(s) + if err != nil { + return "", false + } + if n%60 == 0 { + return strconv.Itoa(n / 60), true + } + return fmt.Sprintf("%.1f", float64(n)/60), true + } + var periods []string + for _, p := range strings.Split(tcText, ":") { + switch { + case strings.Contains(p, "/"): + moves, secs, _ := strings.Cut(p, "/") + m, ok := mins(secs) + if !ok { + return tcText + } + periods = append(periods, fmt.Sprintf("%s min for %s moves", m, moves)) + case strings.Contains(p, "+"): + base, inc, _ := strings.Cut(p, "+") + m, ok := mins(base) + if _, err := strconv.Atoi(inc); !ok || err != nil { + return tcText + } + periods = append(periods, m+"+"+inc) + default: + m, ok := mins(p) + if !ok { + return tcText + } + periods = append(periods, m+" min") + } + } + return strings.Join(periods, ", then ") +} + +// playerBar is a player's line beside the board: title, name and rating, +// and their result at the other end. A zero bar (hidden) if there's no name. +func playerBar(c *studyChapter, side chess.Color) clockBar { + key := "White" + if side == chess.Black { + key = "Black" + } + name := c.tag(key) + if name == "" { + return clockBar{frac: -1} + } + label := name + if elo := c.tag(key + "Elo"); elo != "" && elo != "0" { + label += " " + elo + } + bar := clockBar{title: c.tag(key + "Title"), label: label, frac: -1, plain: true} + switch c.tag("Result") { + case "1-0": + bar.right = map[chess.Color]string{chess.White: "1", chess.Black: "0"}[side] + case "0-1": + bar.right = map[chess.Color]string{chess.White: "0", chess.Black: "1"}[side] + case "1/2-1/2", "½-½": + bar.right = "½" + } + return bar +} diff --git a/pkg/study_tags_test.go b/pkg/study_tags_test.go new file mode 100644 index 0000000..7d403ee --- /dev/null +++ b/pkg/study_tags_test.go @@ -0,0 +1,77 @@ +package pkg + +import ( + "strings" + "testing" + + "github.com/notnil/chess" +) + +const taggedPGN = `[Event "1972 World Chess Championship: Game 1"] +[Site "Reykjavík ISL"] +[Date "1972.07.11"] +[Round "1"] +[White "Boris Vasilyevich Spassky"] +[Black "Robert James Fischer"] +[WhiteTitle "GM"] +[BlackTitle "GM"] +[WhiteElo "2660"] +[BlackElo "2785"] +[Result "1-0"] +[TimeControl "40/9000:3600"] +[ECO "E56"] +[Opening "Nimzo-Indian Defense: Normal Variation"] +[Annotator "https://lichess.org/@/someone"] +[ChapterName "Game 1"] + +1. d4 Nf6 1-0` + +func TestChapterTags(t *testing.T) { + c := parseStudyPGN(taggedPGN)[0] + want := "Reykjavík ISL · 11 Jul 1972 · Round 1 · 150 min for 40 moves, then 60 min · E56 Nimzo-Indian Defense: Normal Variation" + if got := chapterTags(c); got != want { + t.Errorf("tags:\n got %q\nwant %q", got, want) + } + w, b := playerBar(c, chess.White), playerBar(c, chess.Black) + if w.title != "GM" || w.label != "Boris Vasilyevich Spassky 2660" || w.right != "1" || !w.plain { + t.Errorf("white: %+v", w) + } + if b.label != "Robert James Fischer 2785" || b.right != "0" { + t.Errorf("black: %+v", b) + } + if bar := playerBar(parseStudyPGN(`1. e4 *`)[0], chess.White); bar.shown() { + t.Error("no player, but a player line") + } +} + +func TestPGNDatesAndClocks(t *testing.T) { + for in, want := range map[string]string{"1972.07.11": "11 Jul 1972", "1972.07.??": "Jul 1972", "1972.??.??": "1972", "oops": "oops"} { + if got := pgnDate(in); got != want { + t.Errorf("pgnDate(%q) = %q, want %q", in, got, want) + } + } + for in, want := range map[string]string{"5400+30": "90+30", "180+2": "3+2", "600": "10 min", "40/7200:3600": "120 min for 40 moves, then 60 min", "weird": "weird"} { + if got := pgnTimeControl(in); got != want { + t.Errorf("pgnTimeControl(%q) = %q, want %q", in, got, want) + } + } +} + +func TestChapterResult(t *testing.T) { + for pgn, want := range map[string]string{ + taggedPGN: "1–0 White is victorious", + `[Result "0-1"]` + "\n\n1. f3 e5 2. g4 Qh4# 0-1": "0–1 Checkmate • Black is victorious", + "1. f3 e5 2. g4 Qh4# *": "0–1 Checkmate • Black is victorious", // the position says so + `[Result "1-0"]` + "\n" + `[Termination "Time forfeit"]` + "\n\n1. e4 1-0": "1–0 Time out • White is victorious", + `[Result "1/2-1/2"]` + "\n\n1. e4 e5 1/2-1/2": "½–½ Draw", + "1. e4 e5 *": "", + } { + score, how := chapterResult(parseStudyPGN(pgn)[0]) + if got := strings.TrimSpace(score + " " + how); got != want { + t.Errorf("%q: got %q, want %q", pgn, got, want) + } + } + if text := studyMoveText(parseStudyPGN(taggedPGN)[0], nil); !strings.Contains(text, "[::b]1–0[::-]") { + t.Errorf("result missing from the move list:\n%s", text) + } +} diff --git a/pkg/study_test.go b/pkg/study_test.go new file mode 100644 index 0000000..ea72b44 --- /dev/null +++ b/pkg/study_test.go @@ -0,0 +1,167 @@ +package pkg + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + tc "github.com/gdamore/tcell/v3" + "github.com/nate-xyz/chess-cli/api" + "github.com/notnil/chess" +) + +func TestStudyScreen(t *testing.T) { + startTestApp(t, 160, 50) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/study/abcd1234.pgn" || r.URL.Query().Get("variations") != "true" { + http.NotFound(w, r) + return + } + w.Write([]byte(testStudyPGN)) + })) + defer srv.Close() + oldHost := api.HostUrl + api.HostUrl = srv.URL + defer func() { api.HostUrl = oldHost }() + + ss := Root.study + onUI(func() { openStudy("abcd1234", "") }) + waitFor(t, "study loaded", func() bool { return ss.ch != nil }) + onUI(func() { + if ss.ch.name() != "Italian" || ss.white { + t.Errorf("chapter %q, white at bottom %v (the study says black)", ss.ch.name(), ss.white) + } + if ss.Chapters.GetItemCount() != 3 { + t.Errorf("%d chapters listed", ss.Chapters.GetItemCount()) + } + if !strings.Contains(ss.Info.GetText(true), "Openings") { + t.Errorf("info = %q", ss.Info.GetText(true)) + } + // the start: the chapter's circle on e4 + if len(ss.Board.shapes) != 1 { + t.Errorf("start shapes = %v", ss.Board.shapes) + } + + // → steps along the main line + ss.step(3) // 1. e4 e5 2. Nf3 + if ss.cur.san != "Nf3" || len(ss.Board.shapes) != 2 { + t.Errorf("after 3 steps: %q, shapes %v", ss.cur.san, ss.Board.shapes) + } + if hl := ss.Moves.GetHighlights(); len(hl) != 1 || hl[0] != "n3" { + t.Errorf("highlight = %v", hl) + } + + // clicking a move in a variation switches to that line + ss.Moves.Highlight("n8") // 3... Nf6 in the 2... d6 line + if ss.cur.san != "Nf6" || ss.cur.parent.san != "d4" { + t.Fatalf("clicked into the variation, at %q", ss.cur.san) + } + ss.Board.mu.Lock() + pos, _, to := ss.Board.shown() + ss.Board.mu.Unlock() + if pos.String() != ss.cur.pos.String() || to != chess.F6 { + t.Errorf("board shows %v", pos) + } + ss.step(-1) + if ss.cur.san != "d4" { + t.Errorf("← from Nf6 = %q, want d4", ss.cur.san) + } + ss.step(-100) + if ss.cur != ss.ch.root { + t.Error("↑ should go to the start") + } + + // the players' lines stay while stepping back (no history banner in studies) + ss.Board.mu.Lock() + browse, back := ss.Board.browse, ss.Board.back + ss.Board.mu.Unlock() + if !browse || back == 0 { + t.Errorf("browse %v back %v", browse, back) + } + + // another chapter, from a position + ss.selectChapter(1) + if ss.cur != ss.ch.root || ss.ch.name() != "Endgame" || !ss.white { + t.Errorf("chapter 2: %q", ss.ch.name()) + } + ss.Board.mu.Lock() + pos, _, _ = ss.Board.shown() + ss.Board.mu.Unlock() + if !strings.HasPrefix(pos.String(), "8/8/8/4k3/8/8/4P3/4K3") { + t.Errorf("endgame start = %v", pos) + } + + // a chapter with a move that can't be read says so + ss.selectChapter(2) + if !strings.Contains(ss.Moves.GetText(true), "Stopped reading") { + t.Error("no warning about the unreadable move") + } + }) + + // the wheel / [ ] on the board moves the highlight and the shapes + onUI(func() { + ss.selectChapter(0) + ss.Board.ShowPly(3) + }) + waitFor(t, "board stepping updates the study", func() bool { + return ss.cur != nil && ss.cur.san == "Nf3" && len(ss.Moves.GetHighlights()) == 1 + }) +} + +func TestStudyIDFrom(t *testing.T) { + for in, want := range map[string][2]string{ + "abcd1234": {"abcd1234", ""}, + "https://lichess.org/study/abcd1234": {"abcd1234", ""}, + "https://lichess.org/study/abcd1234/efgh5678": {"abcd1234", "efgh5678"}, + "lichess.org/study/abcd1234/efgh5678#3": {"abcd1234", "efgh5678"}, + } { + s, c := api.StudyIDFrom(in) + if s != want[0] || c != want[1] { + t.Errorf("StudyIDFrom(%q) = %q, %q", in, s, c) + } + } + if api.ValidStudyID("../../x") || api.ValidStudyID("abc") { + t.Error("bad study IDs accepted") + } +} + +// Side lines branching at the current move are underlined, heavier the +// deeper they're nested: solid, then dashed. +func TestStudyUnderlines(t *testing.T) { + scr := startTestApp(t, 160, 50) + ss := Root.study + onUI(func() { + Root.Switch("study") + ss.show(parseStudyPGN(testStudyPGN), "") + ss.goTo(ss.ch.nodes[4]) // 2... Nc6, where 2... d6 branches off + }) + waitFor(t, "drawn", func() bool { Root.App.Draw(); return true }) + underlineAt := func(text string) tc.UnderlineStyle { + w, h := scr.Size() + for y := 0; y < h; y++ { + var row strings.Builder + for x := 0; x < w; x++ { + s, _, _ := scr.Get(x, y) + row.WriteString(s) + } + if i := strings.Index(row.String(), text); i >= 0 { + x := len([]rune(row.String()[:i])) + _, style, _ := scr.Get(x+1, y) + return style.GetUnderlineStyle() + } + } + t.Fatalf("%q not on screen", text) + return 0 + } + var top, nested, comment tc.UnderlineStyle + onUI(func() { + top, nested, comment = underlineAt("(2... d6"), underlineAt("(3. Bc4)"), underlineAt("Philidor") + }) + if top != tc.UnderlineStyleSolid || comment != tc.UnderlineStyleSolid { + t.Errorf("first level: line %v, its comment %v, want solid", top, comment) + } + if nested != tc.UnderlineStyleDashed { + t.Errorf("nested line: %v, want dashed", nested) + } +} diff --git a/pkg/textsize.go b/pkg/textsize.go new file mode 100644 index 0000000..009fc46 --- /dev/null +++ b/pkg/textsize.go @@ -0,0 +1,183 @@ +package pkg + +import ( + "fmt" + "strings" + "sync" + + tc "github.com/gdamore/tcell/v3" +) + +// Big pieces via kitty's text sizing protocol +// (https://sw.kovidgoyal.net/kitty/text-sizing-protocol/): the terminal draws +// a character scaled up to fill an s*w by s block of cells, in its own font, +// so pieces are real Unicode glyphs, just bigger. +// +// tcell doesn't know about these "multicell" characters, so the board locks +// its cells in tcell (tcell won't draw there; the same mechanism tcell +// provides for sixel images) and the pieces are written straight to the +// terminal after each frame, but only when something on the board changed. + +// sizedCell is one multicell character: text drawn in a (s*w) x s block at x,y. +type sizedCell struct { + x, y, s, w int + n, d int // fractional scale within the block (0 = none) + fg, bg tc.Color + text string +} + +type rect struct{ x, y, w, h int } + +var textSizing struct { + sync.Mutex + enabled bool + screens map[tc.Screen]*sizedScreen // each screen's multicells (one in the app; tests draw several) +} + +// sizedScreen is one screen's multicells: this frame's, and what's on the +// terminal now. +type sizedScreen struct { + frame []sizedCell // collected by board Draw calls this frame + regions []rect + + prevCells []sizedCell + prevRegions []rect + prevW int + prevH int +} + +// sizedFor is a screen's state. Locked by caller. +func sizedFor(screen tc.Screen) *sizedScreen { + if textSizing.screens == nil { + textSizing.screens = map[tc.Screen]*sizedScreen{} + } + st := textSizing.screens[screen] + if st == nil { + st = &sizedScreen{} + textSizing.screens[screen] = st + } + return st +} + +// TextSizingMode reports whether big pieces are on. +func TextSizingMode() bool { + textSizing.Lock() + defer textSizing.Unlock() + return textSizing.enabled +} + +// queueSized records a board region and its multicell characters for this +// frame and locks the region so tcell leaves it alone. Called from Draw. +func queueSized(screen tc.Screen, r rect, cells []sizedCell) { + screen.LockRegion(r.x, r.y, r.w, r.h, true) + textSizing.Lock() + st := sizedFor(screen) + st.regions = append(st.regions, r) + st.frame = append(st.frame, cells...) + textSizing.Unlock() +} + +// afterDraw runs after every full frame (cview's after-draw hook): tcell's +// drawing is flushed, then big pieces and piece images go on top. +func afterDraw(screen tc.Screen) { + checkLimited(screen) // the app's own screen: its colours decide limited mode + flushTextSizing(screen) + flushImages(screen) +} + +// flushTextSizing runs after every full frame. It +// erases multicells from boards that are gone or moved, lets tcell repaint +// those cells, and (re)sends the board's multicells if anything changed. +func flushTextSizing(screen tc.Screen) { + textSizing.Lock() + defer textSizing.Unlock() + if !textSizing.enabled { + screen.Show() + return + } + ts := sizedFor(screen) + frame, regions := ts.frame, ts.regions + ts.frame, ts.regions = nil, nil + tty, ok := screen.Tty() + if !ok { + screen.Show() + return + } + + var out strings.Builder + out.WriteString("\x1b7") // save cursor position and attributes (tcell tracks both) + + // Boards no longer drawn here: erase their multicells (writing a space on + // a multicell's top-left cell erases the whole block), then unlock so + // tcell repaints whatever is there now. + removed := false + for _, pr := range ts.prevRegions { + if containsRect(regions, pr) { + continue + } + removed = true + for _, c := range ts.prevCells { + if c.x >= pr.x && c.y >= pr.y && c.x < pr.x+pr.w && c.y < pr.y+pr.h { + fmt.Fprintf(&out, "\x1b[%d;%dH\x1b[0m ", c.y+1, c.x+1) + } + } + screen.LockRegion(pr.x, pr.y, pr.w, pr.h, false) + } + for _, r := range regions { // an unlock above may have overlapped a current board + screen.LockRegion(r.x, r.y, r.w, r.h, true) + } + out.WriteString("\x1b8") + if removed { + _, _ = tty.Write([]byte(out.String())) + } + screen.Show() // flush tcell's own drawing first; the multicells go on top + + w, h := screen.Size() + if removed || w != ts.prevW || h != ts.prevH || !sameCells(frame, ts.prevCells) { + _, _ = tty.Write([]byte(encodeSized(frame))) + } + ts.prevCells, ts.prevRegions, ts.prevW, ts.prevH = frame, regions, w, h +} + +// encodeSized renders multicell characters as escape codes, leaving the +// cursor and attributes as they were. +func encodeSized(cells []sizedCell) string { + if len(cells) == 0 { + return "" + } + var b strings.Builder + b.WriteString("\x1b7") + for _, c := range cells { + fr, fg, fb := c.fg.RGB() + br, bgc, bb := c.bg.RGB() + meta := fmt.Sprintf("s=%d:w=%d", c.s, c.w) + if c.d > 0 { + meta += fmt.Sprintf(":n=%d:d=%d:v=2:h=2", c.n, c.d) + } + fmt.Fprintf(&b, "\x1b[%d;%dH\x1b[0;38;2;%d;%d;%d;48;2;%d;%d;%dm\x1b]66;%s;%s\a", + c.y+1, c.x+1, fr, fg, fb, br, bgc, bb, meta, c.text) + } + b.WriteString("\x1b8") + return b.String() +} + +func sameCells(a, b []sizedCell) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +func containsRect(rs []rect, r rect) bool { + for _, x := range rs { + if x == r { + return true + } + } + return false +} diff --git a/pkg/textsize_detect_other.go b/pkg/textsize_detect_other.go new file mode 100644 index 0000000..2950ddf --- /dev/null +++ b/pkg/textsize_detect_other.go @@ -0,0 +1,7 @@ +//go:build !unix + +package pkg + +// probeTerminal: the terminals with kitty's protocols don't run on Windows, +// so don't probe. CHESS_CLI_BIG_PIECES=1 can still force big pieces on. +func probeTerminal() (textSizing, graphics bool) { return false, false } diff --git a/pkg/textsize_detect_unix.go b/pkg/textsize_detect_unix.go new file mode 100644 index 0000000..9619d41 --- /dev/null +++ b/pkg/textsize_detect_unix.go @@ -0,0 +1,89 @@ +//go:build unix + +package pkg + +import ( + "os" + "regexp" + "strconv" + "strings" + "time" + + "golang.org/x/sys/unix" + "golang.org/x/term" +) + +var cprPattern = regexp.MustCompile(`\x1b\[(\d+);(\d+)R`) + +// probeTerminal asks the terminal which of kitty's protocols it supports, +// in one go before the UI starts. +// +// Text sizing, as its spec recommends: report the cursor position, draw a +// space two cells wide (w=2), report again, draw a space scaled 2x (s=2), +// report again. If the cursor moved two cells each time, both parts are +// supported. Terminals that don't support it just don't move the cursor. +// +// Graphics: a query for a 1x1 image (a=q stores nothing) is sent first; +// terminals that support the protocol answer "OK" before the cursor reports, +// others ignore it. +func probeTerminal() (textSizing, graphics bool) { + in, out := int(os.Stdin.Fd()), os.Stdout + if !term.IsTerminal(in) || !term.IsTerminal(int(out.Fd())) { + return false, false + } + old, err := term.MakeRaw(in) + if err != nil { + return false, false + } + defer term.Restore(in, old) + + _, _ = out.WriteString("\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\" + + "\r\x1b[6n\x1b]66;w=2; \a\x1b[6n\x1b]66;s=2; \a\x1b[6n") + cols, reply := readCursorReports(in, 3, 500*time.Millisecond) + _, _ = out.WriteString("\r\x1b[J") // erase the test characters + + textSizing = len(cols) == 3 && cols[1]-cols[0] == 2 && cols[2]-cols[1] == 2 + graphics = strings.Contains(string(reply), "_Gi=31;OK") + return textSizing, graphics +} + +func readCursorColumns(fd, n int, timeout time.Duration) []int { + cols, _ := readCursorReports(fd, n, timeout) + return cols +} + +// readCursorReports reads cursor position reports until it has n of them or +// the timeout passes, and returns their columns and everything read. +func readCursorReports(fd, n int, timeout time.Duration) ([]int, []byte) { + deadline := time.Now().Add(timeout) + var buf []byte + chunk := make([]byte, 256) + for { + matches := cprPattern.FindAllSubmatch(buf, -1) + if len(matches) >= n { + cols := make([]int, 0, n) + for _, m := range matches[:n] { + c, _ := strconv.Atoi(string(m[2])) + cols = append(cols, c) + } + return cols, buf + } + left := time.Until(deadline) + if left <= 0 { + return nil, buf + } + fds := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}} + ready, err := unix.Poll(fds, int(left.Milliseconds())+1) + if err == unix.EINTR { + continue + } + if err != nil || ready == 0 { + return nil, buf + } + k, err := unix.Read(fd, chunk) + if err != nil || k <= 0 { + return nil, buf + } + buf = append(buf, chunk[:k]...) + } +} diff --git a/pkg/textsize_detect_unix_test.go b/pkg/textsize_detect_unix_test.go new file mode 100644 index 0000000..8bd1aeb --- /dev/null +++ b/pkg/textsize_detect_unix_test.go @@ -0,0 +1,37 @@ +//go:build unix + +package pkg + +import ( + "os" + "testing" + "time" +) + +func TestReadCursorColumns(t *testing.T) { + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer r.Close() + defer w.Close() + // kitty: the cursor moves 2 cells after each test character + go w.WriteString("\x1b[12;1R\x1b[12;3R\x1b[1") + go func() { time.Sleep(20 * time.Millisecond); w.WriteString("2;5R") }() + cols := readCursorColumns(int(r.Fd()), 3, time.Second) + if len(cols) != 3 || cols[0] != 1 || cols[1] != 3 || cols[2] != 5 { + t.Fatalf("cols = %v", cols) + } + + // a terminal that never answers: give up at the timeout + r2, w2, _ := os.Pipe() + defer r2.Close() + defer w2.Close() + start := time.Now() + if cols := readCursorColumns(int(r2.Fd()), 3, 100*time.Millisecond); cols != nil { + t.Fatalf("expected nil, got %v", cols) + } + if time.Since(start) > time.Second { + t.Fatal("timeout not respected") + } +} diff --git a/pkg/textsize_test.go b/pkg/textsize_test.go new file mode 100644 index 0000000..4b6fff0 --- /dev/null +++ b/pkg/textsize_test.go @@ -0,0 +1,148 @@ +package pkg + +import ( + "bytes" + "strings" + "sync" + "testing" + + tc "github.com/gdamore/tcell/v3" + "github.com/notnil/chess" +) + +// captureScreen is a real (mock-terminal) screen whose raw tty writes are +// also recorded, so tests can see the escape codes sent for big pieces. +type captureScreen struct { + tc.Screen + tty *captureTty +} + +type captureTty struct { + tc.Tty + mu sync.Mutex + buf bytes.Buffer +} + +func (c *captureTty) Write(p []byte) (int, error) { + c.mu.Lock() + c.buf.Write(p) + c.mu.Unlock() + return c.Tty.Write(p) +} + +func (c *captureTty) take() string { + c.mu.Lock() + defer c.mu.Unlock() + s := c.buf.String() + c.buf.Reset() + return s +} + +func (c captureScreen) Tty() (tc.Tty, bool) { return c.tty, true } + +func newCaptureScreen(t *testing.T, w, h int) captureScreen { + s := newTestScreen(t, w, h) + real, _ := s.Tty() + return captureScreen{Screen: s, tty: &captureTty{Tty: real}} +} + +func withTextSizing(t *testing.T) { + textSizing.Lock() + old := textSizing.enabled + textSizing.enabled = true + textSizing.screens = nil // each test's screen starts with nothing on it + textSizing.Unlock() + t.Cleanup(func() { + textSizing.Lock() + textSizing.enabled = old + textSizing.screens = nil + textSizing.Unlock() + }) +} + +func TestSizedGeometry(t *testing.T) { + for _, sz := range [][2]int{{40, 12}, {80, 26}, {160, 50}, {300, 120}} { + sqW, sqH := boardGeometry(sz[0], sz[1], styleSized, 2) + if sqH < 1 || sqH > 7 || sqW != 2*sqH { + t.Errorf("%v: square %dx%d, want 2s x s with 1 <= s <= 7", sz, sqW, sqH) + } + if 8*sqW+labelW > sz[0] || 8*sqH+labelH > sz[1] { + t.Errorf("%v: board overflows", sz) + } + } + if w, _ := boardGeometry(300, 120, styleSized, 2); w != 14 { + t.Errorf("scale should cap at 7 (square 14 wide), got %d", w) + } +} + +func TestEncodeSized(t *testing.T) { + got := encodeSized([]sizedCell{ + {x: 4, y: 2, s: 3, w: 2, n: 9, d: 10, fg: colWhiteBody, bg: colLight, text: "♚"}, + {x: 10, y: 2, s: 3, w: 2, fg: colWhiteBody, bg: colDark, text: " "}, + }) + want := "\x1b7" + + "\x1b[3;5H\x1b[0;38;2;255;248;220;48;2;145;130;109m\x1b]66;s=3:w=2:n=9:d=10:v=2:h=2;♚\a" + + "\x1b[3;11H\x1b[0;38;2;255;248;220;48;2;108;81;59m\x1b]66;s=3:w=2; \a" + + "\x1b8" + if got != want { + t.Errorf("got %q\nwant %q", got, want) + } +} + +func TestTextSizingFlush(t *testing.T) { + withTextSizing(t) + s := newCaptureScreen(t, 120, 40) + b := NewBoardView(nil) + b.SetRect(0, 0, 120, 40) + draw := func() string { + b.Draw(s) + flushTextSizing(s) + return s.tty.take() + } + + out := draw() + if n := strings.Count(out, "\x1b]66;"); n != 64 { + t.Fatalf("first frame sent %d multicells, want 64", n) + } + // pieces carry a trailing space so kitty centres them (see squareLook.sized) + if !strings.Contains(out, ";♚ \a") || !strings.Contains(out, ";♟\uFE0E \a") { + t.Errorf("pieces missing or unpadded in %q", out[:200]) + } + if out := draw(); out != "" { + t.Errorf("unchanged board was re-sent: %q", out) + } + + g := chess.NewGame() + b.HandleSquare(g, chess.E2, true, func(string) {}) + if out := draw(); strings.Count(out, "\x1b]66;") != 64 { + t.Errorf("selection change wasn't sent") + } + + // board hidden (e.g. switched screens): multicells erased, nothing new sent + flushTextSizing(s) + out = s.tty.take() + if strings.Contains(out, "\x1b]66;") || strings.Count(out, "\x1b[0m ") != 64 { + t.Errorf("hiding the board should erase its 64 multicells, got %q", out) + } +} + +// Two screens keep separate multicell state: drawing a board on one must not +// make the other erase or resend anything (in tests the background app +// redraws its own screen while a test draws on another). +func TestTextSizingPerScreen(t *testing.T) { + withTextSizing(t) + a, other := newCaptureScreen(t, 120, 40), newCaptureScreen(t, 160, 50) + ba, bo := NewBoardView(nil), NewBoardView(nil) + ba.SetRect(0, 0, 120, 40) + bo.SetRect(0, 0, 160, 50) + ba.Draw(a) + flushTextSizing(a) + a.tty.take() + bo.Draw(other) // another screen draws in between + flushTextSizing(other) + ba.Draw(a) + flushTextSizing(a) + if out := a.tty.take(); out != "" { + t.Errorf("the other screen's board leaked into this one: %q", out[:min(len(out), 120)]) + } +} diff --git a/pkg/ui_construct_challenge.go b/pkg/ui_construct_challenge.go index 543faa4..61f038c 100644 --- a/pkg/ui_construct_challenge.go +++ b/pkg/ui_construct_challenge.go @@ -3,7 +3,7 @@ package pkg import ( "fmt" - cv "code.rocketnine.space/tslocum/cview" + cv "codeberg.org/tslocum/cview" ) func initConstruct() *cv.Grid { @@ -45,7 +45,9 @@ func initConstruct() *cv.Grid { var seventhfriendsOptions func() var eightSubmitOption func() var updateTree func([]string) - var Minutes float64 = 0.25 + // 10+0 by default: rapid, which Lichess allows for every kind of game + // started through the Board API (bullet isn't allowed at all) + var Minutes float64 = 10 var Seconds int var Days int = 1 var BotPowerLevel int = 1 @@ -213,17 +215,18 @@ func initConstruct() *cv.Grid { //slider 1: Minutes per side slider1 := cv.NewSlider() - slider1.SetLabel("Minutes per side: 0.25") slider1.SetChangedFunc(func(value int) { Minutes = m[value] slider1.SetLabel(fmt.Sprintf("Minutes per side: %3v", m[value])) }) slider1.SetMax(len(m) - 1) slider1.SetIncrement(1) + // open at the current value, so what's shown is what's sent + slider1.SetProgress(indexOf(m, Minutes)) + slider1.SetLabel(fmt.Sprintf("Minutes per side: %3v", Minutes)) //slider 2: slider2 := cv.NewSlider() - slider2.SetLabel("Increment in seconds: 0") slider2.SetChangedFunc(func(value int) { Seconds = s[value] @@ -231,6 +234,8 @@ func initConstruct() *cv.Grid { }) slider2.SetMax(len(s) - 1) slider2.SetIncrement(1) + slider2.SetProgress(indexOf(s, Seconds)) + slider2.SetLabel(fmt.Sprintf("Increment in seconds: %3d", Seconds)) form.AddFormItem(slider1) form.AddFormItem(slider2) @@ -238,13 +243,14 @@ func initConstruct() *cv.Grid { d := []int{1, 2, 3, 5, 7, 10, 14} //slider 1: Days slider1 := cv.NewSlider() - slider1.SetLabel("Days per turn: 1") slider1.SetChangedFunc(func(value int) { Days = d[value] slider1.SetLabel(fmt.Sprintf("Days per turn: %3v", d[value])) }) slider1.SetMax(len(d) - 1) slider1.SetIncrement(1) + slider1.SetProgress(indexOf(d, Days)) + slider1.SetLabel(fmt.Sprintf("Days per turn: %3v", Days)) form.AddFormItem(slider1) @@ -598,12 +604,24 @@ func initConstruct() *cv.Grid { firstOption() grid.SetColumns(-1, -1) + fitMenuColumn(grid, list, []int{-1, -1}, 1) grid.SetRows(-1, -2, 1) grid.AddItem(list, 1, 1, 1, 1, 0, 0, true) grid.AddItem(tv, 0, 0, 1, 2, 0, 0, false) grid.AddItem(tree, 1, 0, 1, 1, 0, 0, false) grid.AddItem(Ribbon, 2, 0, 1, 2, 0, 0, false) + registerMenus("challenge", false, list) return grid } + +// indexOf is the position of v in values (0 if it isn't there). +func indexOf[T comparable](values []T, v T) int { + for i, x := range values { + if x == v { + return i + } + } + return 0 +} diff --git a/pkg/ui_init.go b/pkg/ui_init.go index 0fc866b..dae3dba 100644 --- a/pkg/ui_init.go +++ b/pkg/ui_init.go @@ -1,7 +1,7 @@ package pkg import ( - cv "code.rocketnine.space/tslocum/cview" + cv "codeberg.org/tslocum/cview" ) func InitUI() { @@ -35,8 +35,30 @@ func InitUI() { panels.AddPanel("ongoing", ongoing.Init(), true, false) panels.AddPanel("listchallenge", challenges.Init(), true, false) panels.AddPanel("saved", sgame.Init(), true, false) + panels.AddPanel("options", optionsInit(), true, false) + Root.puzzle = new(PuzzleScreen) + panels.AddPanel("puzzle", Root.puzzle.Init(), true, false) + Root.watch = new(WatchScreen) + panels.AddPanel("watch", Root.watch.Init(), true, false) + Root.study = new(StudyScreen) + panels.AddPanel("study", Root.study.Init(), true, false) + panels.AddPanel("prompt", promptInit(), true, false) + setMoveBoxAlways(moveBoxAlways()) // apply the saved settings + applyKeyPrefs() + refreshNews() + onboard := needsOnboarding() + if onboard { + panels.AddPanel("onboard", onboardInit(), true, false) + } Root.nav = panels Root.sglist = new(SavedGameList) Root.sglist.Init() Root.App.SetRoot(panels, true) + if onboard { + Root.Switch("onboard") + Root.App.SetFocus(onboardList) + } + Root.App.SetAfterDrawFunc(afterDraw) + Root.App.SetMouseCapture(trackHover) + Root.App.SetInputCapture(globalKeys) } diff --git a/pkg/ui_init_local.go b/pkg/ui_init_local.go index 0b9734c..a891228 100644 --- a/pkg/ui_init_local.go +++ b/pkg/ui_init_local.go @@ -2,31 +2,50 @@ package pkg import ( "fmt" + "strings" - cv "code.rocketnine.space/tslocum/cview" + "github.com/nate-xyz/chess-cli/api" + + cv "codeberg.org/tslocum/cview" tc "github.com/gdamore/tcell/v3" ) +// resetWelcome puts the home screen back to its main menu. +var resetWelcome = func() {} + func WelcomeInit() *cv.Grid { List := cv.NewList() List.SetHover(true) List.SetWrapAround(true) //list construction - var secondList func() + var secondList, puzzleList, watchList, studyList func() + var mainList func() - mainList := func() { + mainList = func() { List.Clear() - choices := []string{"Local", "Online", "Quit"} - explain := []string{"Play a local chess game", "Play a game on lichess", "Press to exit"} - shortcuts := []rune{'l', 'o', 'q'} - selectFunc := []ListSelectedFunc{secondList, gotoLichess, Root.App.Stop} - - for i := 0; i < len(choices); i++ { - item := cv.NewListItem(choices[i]) - item.SetSecondaryText(explain[i]) - item.SetShortcut(rune(shortcuts[i])) - item.SetSelectedFunc(selectFunc[i]) + online := api.HasValidToken() // Watch and Studies only once you've logged in to Lichess + for _, c := range []struct { + text, explain string + key rune + f ListSelectedFunc + needsLogin bool + }{ + {"Local", "Play a local chess game", 'l', secondList, false}, + {"Online", "Play a game on lichess", 'o', gotoLichess, false}, + {"Puzzles", "Lichess puzzles: daily or training, rated or casual", 'p', puzzleList, false}, + {"Watch", "Lichess TV, a player's game, or any game", 'w', watchList, true}, + {"Studies", "Your Lichess studies, or any study by link", 't', studyList, true}, + {"Options", "How the board and pieces look", 's', gotoOptions, false}, + {"Quit", "Press to exit", 'q', Root.App.Stop, false}, + } { + if c.needsLogin && !online { + continue + } + item := cv.NewListItem(c.text) + item.SetSecondaryText(c.explain) + item.SetShortcut(c.key) + item.SetSelectedFunc(c.f) List.AddItem(item) } } @@ -35,9 +54,14 @@ func WelcomeInit() *cv.Grid { List.Clear() standard := cv.NewListItem("New") standard.SetShortcut('n') - standard.SetSecondaryText("Begin a new game") + standard.SetSecondaryText("Two players, one keyboard") standard.SetSelectedFunc(startNewLocalGame) + engine := cv.NewListItem("Play local Stockfish") + engine.SetShortcut('f') + engine.SetSecondaryText("Play the Stockfish engine on this computer, offline") + engine.SetSelectedFunc(func() { stockfishList(List, secondList) }) + ongoing := cv.NewListItem("Saved") ongoing.SetSecondaryText("Select a game from your saved games") ongoing.SetShortcut('s') @@ -52,13 +76,102 @@ func WelcomeInit() *cv.Grid { quit.SetShortcut('q') quit.SetSecondaryText("Press to exit") quit.SetSelectedFunc(Root.App.Stop) + clock := cv.NewListItem("Clock: " + localClockName(localClockIndex())) + clock.SetShortcut('c') + clock.SetSecondaryText("Time control for local games; Enter for the next") + clock.SetSelectedFunc(func() { + nextLocalClock() + cur := List.GetCurrentItemIndex() + secondList() + List.SetCurrentItem(cur) + }) List.AddItem(standard) + List.AddItem(engine) + List.AddItem(clock) List.AddItem(ongoing) List.AddItem(back) List.AddItem(quit) } + puzzleList = func() { + cur := List.GetCurrentItemIndex() + List.Clear() + add := func(text, explain string, key rune, f func()) { + item := cv.NewListItem(text) + item.SetSecondaryText(explain) + item.SetShortcut(key) + item.SetSelectedFunc(f) + List.AddItem(item) + } + add("Daily puzzle", "Today's Lichess puzzle", 'd', func() { startPuzzle(true) }) + add("Puzzle training", "New puzzles, one after another", 'p', func() { startPuzzle(false) }) + mode, other := "Rated", "casual: no rating change, no login needed" + if !puzzleRated() { + mode, other = "Casual", "rated: changes your Lichess puzzle rating" + } + add("Mode: "+mode, "Switch to "+other, 'r', func() { + savePuzzlePrefs(puzzleRated(), puzzleDifficulty()) + puzzleList() + }) + add("Difficulty: "+puzzleDifficulty(), "Relative to your puzzle rating; Enter for the next level", 'f', func() { + d := api.PuzzleDifficulties + next := d[0] + for i, x := range d { + if x == puzzleDifficulty() { + next = d[(i+1)%len(d)] + } + } + savePuzzlePrefs(!puzzleRated(), next) + puzzleList() + }) + add("Back", "Go back to main options", 'b', mainList) + List.SetCurrentItem(cur) + } + + watchList = func() { + List.Clear() + add := func(text, explain string, key rune, f func()) { + item := cv.NewListItem(text) + item.SetSecondaryText(explain) + item.SetShortcut(key) + item.SetSelectedFunc(f) + List.AddItem(item) + } + keys := "tuzrc9om" // best, bullet, blitz, rapid, classical, 960, bots, computer + for i, ch := range api.TvChannels { + ch := ch + explain := "The best " + strings.ToLower(ch.Name) + " game on Lichess right now" + if ch.Key == "best" { + explain = "Lichess TV: the top-rated game being played" + } + add("TV: "+ch.Name, explain, rune(keys[i]), func() { WatchTv(ch.Key, ch.Name) }) + } + add("Watch a player…", "Follow someone's current game", 'p', func() { askWatch("player") }) + add("Watch a game…", "Paste a Lichess game link or ID", 'g', func() { askWatch("game") }) + add("Back", "Go back to main options", 'b', mainList) + } + + studyList = func() { + List.Clear() + for _, c := range []struct { + text, explain string + key rune + f func() + }{ + {"My studies", "The studies on your Lichess account, private ones too", 'm', func() { loadMyStudies(List, studyList) }}, + {"Open a study…", "Paste a Lichess study link or ID", 'o', askStudy}, + {"Back", "Go back to main options", 'b', mainList}, + } { + item := cv.NewListItem(c.text) + item.SetSecondaryText(c.explain) + item.SetShortcut(c.key) + item.SetSelectedFunc(c.f) + List.AddItem(item) + } + } + mainList() + resetWelcome = mainList titleBox := titlePrimitive(ApplicationTitle, List) welcomeRibbon := ribbonPrimitive(welcomeRibbonstr, List) @@ -66,198 +179,114 @@ func WelcomeInit() *cv.Grid { grid := cv.NewGrid() grid.SetColumns(-2, -1) + fitMenuColumn(grid, List, []int{-2, -1}, 1) grid.SetRows(-1, -2, -1, 1) grid.SetBorders(false) + newsBox = textBox(cv.AlignLeft) + newsBox.SetPadding(0, 0, 4, 2) + forwardKeys(newsBox, List) + grid.AddItem(List, 1, 1, 1, 1, 0, 0, true) - grid.AddItem(titleBox, 0, 0, 2, 1, 0, 0, false) + grid.AddItem(titleBox, 0, 0, 1, 1, 0, 0, false) + grid.AddItem(newsBox, 1, 0, 1, 1, 0, 0, false) grid.AddItem(quoteBox, 2, 0, 1, 2, 0, 0, false) grid.AddItem(welcomeRibbon, 3, 0, 1, 2, 0, 0, false) + registerMenus("welcome", false, List) return grid } -//local game grid -func (g *GameScreen) Init() *cv.Grid { - Input := cv.NewInputField() - Input.SetDoneFunc(func(key tc.Key) { - Root.gameState.NextMove = Input.GetText() - Input.SetText("") - if key == tc.KeyEnter { - if contains(Root.gameState.LegalMoves, Root.gameState.NextMove) { - err := g.DoMove(Root.gameState.NextMove) - if err != nil { - Root.gameState.Status += fmt.Sprintf("%v", err) - Root.lgame.UpdateStatus() - } - } else { - Root.gameState.Status += "Last input [red]invalid.[white]\n" - Root.lgame.UpdateStatus() - } - } else { - Root.gameState.NextMove = "" - } - }) - Input.SetLabel("Enter your move: ") +// local game screen +func (g *GameScreen) Init() cv.Primitive { + Board := NewBoardView(LocalSquareHandler) + Board.EnableSounds() - List := cv.NewList() - List.SetSelectedFocusOnly(true) - List.SetHover(true) - optionsList := []string{"Leave", "Save", "Save as new", "Quit"} - optionsExplain := []string{"Go back Home", "Save this game locally", "Save without rewrite", "Close chess-cli"} + List := menuList() + optionsList := []string{"Leave game", "Save", "Save as new", "Quit"} optionsFunc := []ListSelectedFunc{gotoWelcome, func() { doSave(false) }, func() { doSave(true) }, Root.App.Stop} + keys := []rune{'x', 's', 'a', 'q'} for i, opt := range optionsList { item := cv.NewListItem(opt) - item.SetSecondaryText(optionsExplain[i]) + item.SetShortcut(keys[i]) item.SetSelectedFunc(optionsFunc[i]) List.AddItem(item) } - Board := boardPrimitive(LocalTableHandler) - - Status := cv.NewTextView() - Status.SetWordWrap(true) - Status.SetDynamicColors(true) - Status.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(Input) - return nil - }) - - History := cv.NewTextView() - History.SetWordWrap(true) - History.SetDynamicColors(true) - History.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(Input) - return nil - }) - - UserInfo := cv.NewTextView() - UserInfo.SetTextAlign(cv.AlignLeft) - UserInfo.SetVerticalAlign(cv.AlignTop) - UserInfo.SetDynamicColors(true) + OppInfo := textBox(cv.AlignLeft) + OppInfo.SetText("[red]Black") + OppTimer := textBox(cv.AlignLeft) + Status := textBox(cv.AlignLeft) + History := textBox(cv.AlignLeft) + UserTimer := textBox(cv.AlignLeft) + UserInfo := textBox(cv.AlignLeft) UserInfo.SetText("[Blue]White") - UserInfo.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(Input) - return nil - }) - UserTimer := cv.NewTextView() - UserTimer.SetTextAlign(cv.AlignLeft) - UserTimer.SetDynamicColors(true) - UserTimer.SetText("∞") - UserTimer.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(Input) - return nil - }) - - OppTimer := cv.NewTextView() - OppTimer.SetTextAlign(cv.AlignLeft) - OppTimer.SetDynamicColors(true) - OppTimer.SetText("∞") - OppTimer.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(Input) - return nil + side := cv.NewFlex() + side.SetDirection(cv.FlexRow) + g.Move = newMoveBox(side, Board, func(text string) { + if g.engineTurn() { + Root.gameState.Status += "Wait for Stockfish's move. " + g.UpdateStatus() + return + } + if uci, err := parseMoveInput(Root.gameState.Game, text); err == nil { + if err := g.DoMove(uci); err != nil { + Root.gameState.Status += fmt.Sprintf("%v", err) + g.UpdateStatus() + } + } else { + Root.gameState.Status += invalidMoveHint(text) + g.UpdateStatus() + g.Move.show() // let them try again + } }) - - OppInfo := cv.NewTextView() - OppInfo.SetTextAlign(cv.AlignLeft) - OppInfo.SetVerticalAlign(cv.AlignBottom) - OppInfo.SetDynamicColors(true) - OppInfo.SetText("[red]Black") - OppInfo.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(Input) - return nil + side.AddItem(OppInfo, 2, 0, false) + side.AddItem(OppTimer, 1, 0, false) + side.AddItem(Status, 0, 1, false) + side.AddItem(History, 0, 2, false) + side.AddItem(g.Move.input, 0, 0, false) + side.AddItem(List, len(optionsList), 0, false) + side.AddItem(UserTimer, 1, 0, false) + side.AddItem(UserInfo, 2, 0, false) + + // Tab: board <-> menu + Board.SetTabFunc(func() { Root.App.SetFocus(List) }) + List.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { + if event.Key() == tc.KeyTab || event.Key() == tc.KeyEscape { + Root.App.SetFocus(Board) + return nil + } + return event }) - Ribbon := ribbonPrimitive(gameRibbonstr, Input) - - grid := cv.NewGrid() - grid.SetColumns(-1, -2, -1) - grid.SetRows(-1, 1, 1, -1, 10, 1) - grid.SetBorders(false) - - grid.AddItem(Input, 4, 1, 1, 1, 0, 0, true) - grid.AddItem(Center(30, 10, Board, Input), 0, 1, 4, 1, 0, 0, false) - grid.AddItem(Status, 0, 0, 2, 1, 0, 0, false) - grid.AddItem(History, 2, 0, 2, 1, 0, 0, false) - grid.AddItem(Ribbon, 5, 0, 1, 3, 0, 0, false) - grid.AddItem(OppInfo, 0, 2, 1, 1, 0, 0, false) - grid.AddItem(OppTimer, 1, 2, 1, 1, 0, 0, false) - grid.AddItem(UserTimer, 2, 2, 1, 1, 0, 0, false) - grid.AddItem(UserInfo, 3, 2, 1, 1, 0, 0, false) - grid.AddItem(List, 4, 0, 1, 1, 0, 0, false) + go g.clockTicker() + screen := newGameLayout(Board, side, gameRibbonstr) g.Board = Board g.Status = Status g.History = History + linkMoveList(History, Board) g.UserInfo = UserInfo g.UserTimer = UserTimer g.OppInfo = OppInfo g.OppTimer = OppTimer g.List = List + registerMenus("localgame", false, List) - return grid + return screen } -func (p *PostGameScreen) Init() *cv.Grid { - postList := cv.NewList() //list construction - postList.SetWrapAround(true) - postList.SetHover(true) - choices := []string{"New", "Ongoing", "Home", "Quit"} - explain := []string{"Play a new game", "Select from your saved games", "Back to the welcome screen", "Press to exit"} - shortcuts := []rune{'n', 'o', 'h', 'q'} - selectFunc := []ListSelectedFunc{startNewLocalGame, gotoSaved, gotoWelcome, Root.App.Stop} - for i := 0; i < len(choices); i++ { - item := cv.NewListItem(choices[i]) - item.SetSecondaryText(explain[i]) - item.SetShortcut(rune(shortcuts[i])) - item.SetSelectedFunc(selectFunc[i]) - postList.AddItem(item) - } - - gameBox := cv.NewTable() - gameBox.SetSelectable(false, false) - gameBox.SetSortClicked(false) - gameBox.SetFixed(10, 10) - gameBox.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(postList) - return nil - }) - - historyBox := cv.NewTextView() - historyBox.SetWordWrap(true) - historyBox.SetDynamicColors(true) - historyBox.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(postList) - return nil - }) - - resultBox := cv.NewTextView() - resultBox.SetWordWrap(true) - resultBox.SetDynamicColors(true) - resultBox.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(postList) - return nil - }) - - Ribbon := ribbonPrimitive(gameRibbonstr, postList) - - grid := cv.NewGrid() - grid.SetColumns(-2, -1) - grid.SetRows(-1, -3, -1, 1) - grid.SetBorders(false) - - grid.AddItem(postList, 2, 1, 1, 1, 0, 0, true) - grid.AddItem(resultBox, 0, 0, 1, 1, 0, 0, false) - grid.AddItem(Center(28, 10, gameBox, postList), 1, 0, 2, 1, 0, 0, false) - grid.AddItem(Ribbon, 3, 0, 1, 2, 0, 0, false) - grid.AddItem(historyBox, 0, 1, 2, 1, 0, 0, false) - - p.Board = gameBox - p.Result = resultBox - p.History = historyBox - - return grid +func (p *PostGameScreen) Init() cv.Primitive { + pg, screen := newPostGame([]*cv.ListItem{ + menuItem("New game", 'n', startNewLocalGame), + menuItem("Saved games", 's', gotoSaved), + menuItem("Home", 'h', gotoWelcome), + menuItem("Quit", 'q', Root.App.Stop), + }, postRibbonstr) + p.postGame = pg + registerMenus("postlocal", false, pg.List) + return screen } func (sg *SavedGames) Init() *cv.Grid { @@ -280,25 +309,24 @@ func (sg *SavedGames) Init() *cv.Grid { options.SetSelectedFocusOnly(true) options.SetWrapAround(true) options.SetHover(true) - optionsList := []string{"Leave", "Quit"} + optionsList := []string{"Back", "Quit"} optionsExplain := []string{"Go back Home", "Close chess-cli"} optionsFunc := []ListSelectedFunc{gotoWelcome, Root.App.Stop} + keys := []rune{'b', 'q'} for i, opt := range optionsList { item := cv.NewListItem(opt) item.SetSecondaryText(optionsExplain[i]) + item.SetShortcut(keys[i]) item.SetSelectedFunc(optionsFunc[i]) options.AddItem(item) } title := titlePrimitive("Select a saved game.", gameList) - preview := boardPrimitive(func(row, col int) {}) - preview.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(gameList) - return nil - }) + preview := NewBoardView(nil) + forwardKeys(preview, gameList) - ribbon := ribbonPrimitive(OngoingRibbonstr, gameList) + ribbon := ribbonPrimitive(savedRibbonstr, gameList) grid := cv.NewGrid() grid.SetColumns(-1, -2, -4) @@ -308,12 +336,13 @@ func (sg *SavedGames) Init() *cv.Grid { //row col rowSpan colSpan grid.AddItem(gameList, 1, 2, 2, 1, 0, 0, true) grid.AddItem(title, 0, 0, 1, 3, 0, 0, false) - grid.AddItem(Center(30, 10, preview, gameList), 1, 0, 1, 2, 0, 0, false) + grid.AddItem(preview, 1, 0, 1, 2, 0, 0, false) grid.AddItem(ribbon, 3, 0, 1, 3, 0, 0, false) grid.AddItem(options, 2, 1, 1, 1, 0, 0, false) sg.List = gameList sg.Preview = preview + registerMenus("saved", true, gameList, options) return grid } diff --git a/pkg/ui_init_online.go b/pkg/ui_init_online.go index 315d57e..7708318 100644 --- a/pkg/ui_init_online.go +++ b/pkg/ui_init_online.go @@ -3,7 +3,7 @@ package pkg import ( "fmt" - cv "code.rocketnine.space/tslocum/cview" + cv "codeberg.org/tslocum/cview" tc "github.com/gdamore/tcell/v3" "github.com/nate-xyz/chess-cli/api" ) @@ -20,7 +20,7 @@ func (w *WelcomeOnline) Init() *cv.Grid { "Back to welcome screen", "Press to exit"} shortcuts := []rune{'n', 'o', 'c', 'b', 'q'} - selectFunc := []ListSelectedFunc{gotoChallengeConstruction, gotoOngoing, gotoChallenges, gotoWelcome, Root.App.Stop} + selectFunc := []ListSelectedFunc{requireLogin(gotoChallengeConstruction), requireLogin(gotoOngoing), requireLogin(gotoChallenges), gotoWelcome, Root.App.Stop} for i := 0; i < len(choices); i++ { item := cv.NewListItem(choices[i]) item.SetSecondaryText(explain[i]) @@ -35,6 +35,7 @@ func (w *WelcomeOnline) Init() *cv.Grid { grid := cv.NewGrid() grid.SetColumns(-2, -1) + fitMenuColumn(grid, welcomeList, []int{-2, -1}, 1) grid.SetRows(-1, -2, -1, 1) grid.SetBorders(false) @@ -44,6 +45,7 @@ func (w *WelcomeOnline) Init() *cv.Grid { grid.AddItem(welcomeRibbon, 3, 0, 1, 2, 0, 0, false) Root.wonline.Title = titleBox + registerMenus("lichesswelcome", false, welcomeList) return grid } @@ -61,7 +63,15 @@ func (l *Loader) Init() *cv.Grid { loaderMsgBox.SetTextAlign(cv.AlignCenter) loaderMsgBox.SetVerticalAlign(cv.AlignMiddle) - loaderRibbon := ribbonPrimitive("CHESS-CLI -> Loading, please wait...", loaderMsgBox) + loaderMsgBox.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { + if event.Key() == tc.KeyEscape || event.Str() == "q" { + cancelLoader() + return nil + } + return event + }) + + loaderRibbon := ribbonPrimitive(" chess-cli · waiting for Lichess │ Esc to cancel", loaderMsgBox) grid := cv.NewGrid() grid.SetColumns(-1) @@ -78,197 +88,110 @@ func (l *Loader) Init() *cv.Grid { return grid } -func (g *OnlineGame) Init() *cv.Grid { - inputBox := cv.NewInputField() - inputBox.SetDoneFunc(func(key tc.Key) { - Root.gameState.NextMove = inputBox.GetText() - inputBox.SetText("") - +func (g *OnlineGame) Init() cv.Primitive { + gameBox := NewBoardView(g.OnlineSquareHandler) + gameBox.EnableSounds() + + chatView := cv.NewTextView() + chatView.SetDynamicColors(true) + chatView.SetWordWrap(true) + chatView.SetScrollable(true) + chatView.SetBorder(true) + chatView.SetTitle(" Chat ") + chatInput := cv.NewInputField() + chatInput.SetLabel("Say: ") + chatInput.SetDoneFunc(func(key tc.Key) { if key == tc.KeyEnter { - if contains(Root.gameState.LegalMoves, Root.gameState.NextMove) { - err := g.DoMove(Root.gameState.NextMove) - if err != nil { - Root.gameState.Status += fmt.Sprintf("%v", err) - Root.lgame.UpdateStatus() - } - } else { - Root.gameState.Status += "Last input [red]invalid.[white]\n" - g.UpdateStatus() - } - - } else { - Root.gameState.NextMove = "" + g.sendChat(chatInput.GetText()) + chatInput.SetText("") } }) - inputBox.SetLabel("Enter your move: ") - - gameBox := boardPrimitive(g.OnlineTableHandler) - statusBox := cv.NewTextView() - statusBox.SetWordWrap(true) - statusBox.SetDynamicColors(true) - statusBox.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(inputBox) - return nil - }) - - historyBox := cv.NewTextView() - historyBox.SetWordWrap(true) - historyBox.SetDynamicColors(true) - historyBox.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(inputBox) - return nil - }) - - userInfoBox := cv.NewTextView() - userInfoBox.SetTextAlign(cv.AlignLeft) - userInfoBox.SetVerticalAlign(cv.AlignTop) - userInfoBox.SetDynamicColors(true) - userInfoBox.SetText("USER INFO") - userInfoBox.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(inputBox) - return nil - }) - - userTimerBox := cv.NewTextView() - userTimerBox.SetTextAlign(cv.AlignLeft) - userTimerBox.SetDynamicColors(true) - userTimerBox.SetText("∞") - userTimerBox.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(inputBox) - return nil + options := menuList() // filled by UpdateList + + // Tab cycles: board -> chat -> menu -> board + gameBox.SetTabFunc(func() { Root.App.SetFocus(chatInput) }) + chatInput.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { + switch event.Key() { + case tc.KeyTab: + Root.App.SetFocus(options) + return nil + case tc.KeyEscape: + Root.App.SetFocus(gameBox) + return nil + } + return event }) - - oppTimerBox := cv.NewTextView() - oppTimerBox.SetTextAlign(cv.AlignLeft) - oppTimerBox.SetDynamicColors(true) - oppTimerBox.SetText("∞") - oppTimerBox.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(inputBox) - return nil + options.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { + if event.Key() == tc.KeyTab || event.Key() == tc.KeyEscape { + Root.App.SetFocus(gameBox) + return nil + } + return event }) - oppInfoBox := cv.NewTextView() - oppInfoBox.SetTextAlign(cv.AlignLeft) - oppInfoBox.SetVerticalAlign(cv.AlignBottom) - oppInfoBox.SetDynamicColors(true) - oppInfoBox.SetText("OPP INFO") - oppInfoBox.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(inputBox) - return nil + statusBox := textBox(cv.AlignLeft) + historyBox := textBox(cv.AlignLeft) + oppInfoBox := textBox(cv.AlignLeft) + oppTimerBox := textBox(cv.AlignLeft) + userTimerBox := textBox(cv.AlignLeft) + userInfoBox := textBox(cv.AlignLeft) + + side := cv.NewFlex() + side.SetDirection(cv.FlexRow) + g.Move = newMoveBox(side, gameBox, func(text string) { + if uci, err := parseMoveInput(Root.gameState.Game, text); err == nil { + if err := g.DoMove(uci); err != nil { + Root.gameState.Status += fmt.Sprintf("%v", err) + g.UpdateStatus() + } + } else { + Root.gameState.Status += invalidMoveHint(text) + g.UpdateStatus() + g.Move.show() // let them try again + } }) - - options := cv.NewList() - optionsList := []string{"Back", "Quit"} - optionsExplain := []string{"Go back Home", "Close chess-cli"} - optionsFunc := []ListSelectedFunc{gotoLichessFromGame, Root.App.Stop} - for i, opt := range optionsList { - item := cv.NewListItem(opt) - item.SetSecondaryText(optionsExplain[i]) - item.SetSelectedFunc(optionsFunc[i]) - options.AddItem(item) - } - options.SetSelectedFocusOnly(true) - options.SetHover(true) - options.SetWrapAround(true) - - Ribbon := ribbonPrimitive(gameOnlineRibbonstr, inputBox) - - grid := cv.NewGrid() - grid.SetColumns(-1, -2, -1) - grid.SetRows(-1, 1, 1, -1, 12, 1) - grid.SetBorders(false) - - //row, col, rowSpan, colSpain - grid.AddItem(inputBox, 4, 1, 1, 1, 0, 0, true) - grid.AddItem(Center(30, 10, gameBox, inputBox), 0, 1, 4, 1, 0, 0, false) - grid.AddItem(statusBox, 0, 0, 2, 1, 0, 0, false) - grid.AddItem(historyBox, 2, 0, 2, 1, 0, 0, false) - grid.AddItem(Ribbon, 5, 0, 1, 3, 0, 0, false) - - grid.AddItem(oppInfoBox, 0, 2, 1, 1, 0, 0, false) - grid.AddItem(oppTimerBox, 1, 2, 1, 1, 0, 0, false) - grid.AddItem(userTimerBox, 2, 2, 1, 1, 0, 0, false) - grid.AddItem(userInfoBox, 3, 2, 1, 1, 0, 0, false) - grid.AddItem(options, 4, 0, 1, 1, 0, 0, false) - - g.Grid = grid + side.AddItem(oppInfoBox, 2, 0, false) + side.AddItem(oppTimerBox, 0, 0, false) + side.AddItem(statusBox, 0, 1, false) + side.AddItem(historyBox, 0, 1, false) + side.AddItem(chatView, 0, 2, false) + side.AddItem(chatInput, 1, 0, false) + side.AddItem(g.Move.input, 0, 0, false) + side.AddItem(options, 2, 0, false) + side.AddItem(userTimerBox, 0, 0, false) + side.AddItem(userInfoBox, 2, 0, false) + + screen := newGameLayout(gameBox, side, gameOnlineRibbonstr) + + g.Side = side + g.Chat = chatView + g.ChatInput = chatInput g.Board = gameBox g.Status = statusBox g.History = historyBox + linkMoveList(historyBox, gameBox) g.OppTimer = oppTimerBox g.OppInfo = oppInfoBox g.UserTimer = userTimerBox g.UserInfo = userInfoBox g.List = options + registerMenus("onlinegame", false, options) - return grid + return screen } -func (pg *OnlinePostGame) Init() *cv.Grid { - postList := cv.NewList() //list construction - postList.SetWrapAround(true) - postList.SetHover(true) - choices := []string{"Home", "New", "Ongoing", "Quit"} - explain := []string{"Back to the welcome screen", "Create a new game", "Select from ongoing games", "Press to exit"} - shortcuts := []rune{'h', 'n', 'o', 'q'} - selectFunc := []ListSelectedFunc{gotoLichessAfterLogin, gotoChallengeConstruction, gotoOngoing, Root.App.Stop} - - for i := 0; i < len(choices); i++ { - item := cv.NewListItem(choices[i]) - item.SetSecondaryText(explain[i]) - item.SetShortcut(rune(shortcuts[i])) - item.SetSelectedFunc(selectFunc[i]) - postList.AddItem(item) - } - - gameBox := cv.NewTable() - gameBox.SetSelectable(false, false) - gameBox.SetSortClicked(false) - gameBox.SetFixed(10, 10) - gameBox.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(postList) - return nil - }) - - historyBox := cv.NewTextView() - historyBox.SetWordWrap(true) - historyBox.SetDynamicColors(true) - historyBox.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(postList) - return nil - }) - - resultBox := cv.NewTextView() - resultBox.SetWordWrap(true) - resultBox.SetDynamicColors(true) - resultBox.SetTextAlign(cv.AlignCenter) - resultBox.SetVerticalAlign(cv.AlignBottom) - resultBox.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(postList) - return nil - }) - - Ribbon := ribbonPrimitive(gameRibbonstr, postList) - - grid := cv.NewGrid() - grid.SetColumns(-1, -2, -1) - grid.SetRows(-1, -3, -1, 1) - grid.SetBorders(false) - - //row col rowSpan colSpan - grid.AddItem(postList, 1, 2, 1, 1, 0, 0, true) - grid.AddItem(resultBox, 0, 0, 1, 3, 0, 0, false) - grid.AddItem(Center(30, 10, gameBox, postList), 1, 1, 1, 1, 0, 0, false) - grid.AddItem(Ribbon, 3, 0, 1, 3, 0, 0, false) - grid.AddItem(historyBox, 1, 0, 2, 1, 0, 0, false) - - pg.Grid = grid - pg.Board = gameBox - pg.Result = resultBox - pg.History = historyBox - - return grid +func (pg *OnlinePostGame) Init() cv.Primitive { + p, screen := newPostGame([]*cv.ListItem{ + menuItem("Rematch", 'r', func() { Root.ongame.rematch() }), + menuItem("New game", 'n', gotoChallengeConstruction), + menuItem("Ongoing games", 'o', gotoOngoing), + menuItem("Lichess menu", 'h', gotoLichessAfterLogin), + menuItem("Quit", 'q', Root.App.Stop), + }, postRibbonstr) + pg.postGame = p + registerMenus("postonline", false, p.List) + return screen } func (ong *Ongoing) Init() *cv.Grid { @@ -297,12 +220,14 @@ func (ong *Ongoing) Init() *cv.Grid { }) options := cv.NewList() - optionsList := []string{"Leave", "Quit"} - optionsExplain := []string{"Go back Home", "Close chess-cli"} + optionsList := []string{"Back", "Quit"} + optionsExplain := []string{"Back to the Lichess menu", "Close chess-cli"} optionsFunc := []ListSelectedFunc{gotoLichessAfterLogin, Root.App.Stop} + keys := []rune{'b', 'q'} for i, opt := range optionsList { item := cv.NewListItem(opt) item.SetSecondaryText(optionsExplain[i]) + item.SetShortcut(keys[i]) item.SetSelectedFunc(optionsFunc[i]) options.AddItem(item) } @@ -313,11 +238,8 @@ func (ong *Ongoing) Init() *cv.Grid { title := titlePrimitive("Select an ongoing game.", gameList) - preview := boardPrimitive(func(row, col int) {}) - preview.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { - Root.App.SetFocus(gameList) - return nil - }) + preview := NewBoardView(nil) + forwardKeys(preview, gameList) grid := cv.NewGrid() grid.SetColumns(-1, -2, -4) @@ -327,12 +249,13 @@ func (ong *Ongoing) Init() *cv.Grid { //row col rowSpan colSpan grid.AddItem(gameList, 1, 2, 2, 1, 0, 0, true) grid.AddItem(title, 0, 0, 1, 3, 0, 0, false) - grid.AddItem(Center(30, 10, preview, gameList), 1, 0, 1, 2, 0, 0, false) + grid.AddItem(preview, 1, 0, 1, 2, 0, 0, false) grid.AddItem(ribbon, 3, 0, 1, 3, 0, 0, false) grid.AddItem(options, 2, 1, 1, 1, 0, 0, false) ong.List = gameList ong.Preview = preview + registerMenus("ongoing", true, gameList, options) return grid } @@ -343,36 +266,81 @@ func (c *Challenges) Init() *cv.Grid { incoming := cv.NewList() incoming.AddItem(cv.NewListItem("placeholder in")) incoming.SetSelectedFunc(func(i int, li *cv.ListItem) { - gameID := InChallengeGameID[i] - for _, chal := range Root.User.IncomingChallenges { - if chal.ID == gameID { - currentGameID = gameID - err := api.AcceptChallenge(gameID) + if i >= len(InChallengeGameID) { + return + } + id := InChallengeGameID[i] + li.SetSecondaryText("[gray]accepting…[-]") + go func() { + err := api.AcceptChallenge(id) + Root.App.QueueUpdateDraw(func() { if err != nil { - gotoLichess() + li.SetSecondaryText(fmt.Sprintf("[red]%v[-]", err)) + return } + currentGameID = id startNewOnlineGame() - } + }) + }() + }) + // d declines the highlighted incoming challenge + incoming.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { + if event.Str() != "d" { + return event } - + i := incoming.GetCurrentItemIndex() + if i < 0 || i >= len(InChallengeGameID) { + return nil + } + id := InChallengeGameID[i] + go func() { + err := api.DeclineChallenge(id, "") + Root.App.QueueUpdateDraw(func() { + if err != nil { + Root.wonline.UpdateTitle(fmt.Sprintf("\n[red]Decline failed: %v[-]", err)) + } + gotoChallenges() + }) + }() + return nil + }) + // selecting an outgoing challenge cancels it + outgoing.SetSelectedFunc(func(i int, li *cv.ListItem) { + if i >= len(OutChallengeGameID) { + return + } + id := OutChallengeGameID[i] + li.SetSecondaryText("[gray]cancelling…[-]") + go func() { + err := api.CancelChallenge(id) + Root.App.QueueUpdateDraw(func() { + if err != nil { + li.SetSecondaryText(fmt.Sprintf("[red]%v[-]", err)) + return + } + gotoChallenges() + }) + }() }) options := cv.NewList() options.SetSelectedFocusOnly(true) options.SetHover(true) optionsList := []string{"Back", "Quit"} - optionsExplain := []string{"Go back Home", "Close chess-cli"} + optionsExplain := []string{"Back to the Lichess menu", "Close chess-cli"} optionsFunc := []ListSelectedFunc{gotoLichessAfterLogin, Root.App.Stop} + keys := []rune{'b', 'q'} for i, opt := range optionsList { item := cv.NewListItem(opt) item.SetSecondaryText(optionsExplain[i]) + item.SetShortcut(keys[i]) item.SetSelectedFunc(optionsFunc[i]) options.AddItem(item) } - outtitle := titlePrimitive("Outgoing Challenges.", outgoing) - intitle := titlePrimitive("Incoming Challenges.", incoming) - ribbon := ribbonPrimitive("CHESS-CLI -> Challenges", incoming) + outtitle := titlePrimitive("Outgoing challenges\n[gray]Enter cancels[-]", outgoing) + intitle := titlePrimitive("Incoming challenges\n[gray]Enter accepts, d declines[-]", incoming) + ribbon := ribbonPrimitive(" chess-cli · challenges │ ↑↓ or 1-9 to pick │ Tab next list │ Ctrl-C quit", incoming) grid := cv.NewGrid() grid.SetColumns(-1, -3, -3, -1) @@ -388,6 +356,7 @@ func (c *Challenges) Init() *cv.Grid { c.Out = outgoing c.In = incoming + registerMenus("listchallenge", true, incoming, outgoing, options) return grid } diff --git a/pkg/ui_onboard.go b/pkg/ui_onboard.go new file mode 100644 index 0000000..18dd1ff --- /dev/null +++ b/pkg/ui_onboard.go @@ -0,0 +1,217 @@ +package pkg + +import ( + "fmt" + + cv "codeberg.org/tslocum/cview" + "github.com/nate-xyz/chess-cli/api" +) + +// The first-run screen: says what the terminal supports, recommends a piece +// style and lets you try each one on a sample board. Shown until a style has +// been saved; it can be changed later in Options. + +// needsOnboarding: no rendering style chosen yet, or never asked about +// sound, or about Stockfish when there's none (people upgrading get just the +// new questions). +func needsOnboarding() bool { + return api.UserInfo.Pieces == "" || !api.UserInfo.SoundAsked || !api.UserInfo.KeysAsked || needsStockfishStep() +} + +// keysStep asks about hjkl (if not asked yet), then Stockfish. +func keysStep(list *cv.List, info *cv.TextView) { + if api.UserInfo.KeysAsked { + onboardStockfish(list, info) + return + } + onboardKeys(list, info, func() { onboardStockfish(list, info) }) +} + +func needsStockfishStep() bool { return !api.UserInfo.StockfishAsked && findEngine() == "" } + +// onboardStockfish offers to download Stockfish, for games against the +// computer and analysis, when there's none on this computer. +func onboardStockfish(list *cv.List, info *cv.TextView) { + if !needsStockfishStep() { + gotoWelcome() + return + } + finish := func() { + _ = api.UpdateConfig(func(c *api.UserConfig) { c.StockfishAsked = true }) + gotoWelcome() + } + list.SetChangedFunc(nil) + list.Clear() + add := func(text, explain string, f func()) { + item := cv.NewListItem(text) + item.SetShortcut(numberKey(list.GetItemCount())) + item.SetSecondaryText(" " + explain) + item.SetSelectedFunc(f) + list.AddItem(item) + } + add("Download Stockfish [green](recommended)[-]", "the official release from GitHub, about 80 MB", func() { + if !downloading { + downloadEngine(list, finish) + } + }) + add("I'll install it myself", installHint(), finish) + add("Not now", "later: Home → Local → Play local Stockfish", finish) + list.SetCurrentItem(0) + info.SetText("[::b]Stockfish?[::-]\n\nStockfish is the chess engine chess-cli uses to play against you offline " + + "and to analyse your games when they end: accuracy, mistakes and an evaluation graph.\n\n" + + "It isn't on this computer yet. chess-cli can download it for you, or you can install it yourself.\n\n[#a0a0a0]Stockfish is free software (GPLv3), from stockfishchess.org.[-]") + Root.App.SetFocus(list) +} + +var onboardList *cv.List + +// resetSettings puts all settings back to their defaults, applies them and +// runs the first-run setup again. +func resetSettings() { + if err := api.ResetPreferences(); err != nil { + optionsScreen.note.SetText("[red]Couldn't reset: " + cv.Escape(err.Error()) + "[-]") + return + } + setMoveBoxAlways(moveBoxAlways()) + applyLayoutPrefs() + applyKeyPrefs() + previewPieces("") + runOnboarding() +} + +// runOnboarding shows the first-run setup (again). +func runOnboarding() { + if Root.nav.HasPanel("onboard") { + Root.nav.RemovePanel("onboard") + } + Root.nav.AddPanel("onboard", onboardInit(), true, false) + Root.Switch("onboard") + Root.App.SetFocus(onboardList) +} + +// soundStep moves the first-run screen on to the sound question. +var soundStep = func() {} + +// onboardSound asks whether to have sound, playing a sample of each +// choice as it's highlighted. +func onboardSound(list *cv.List, info *cv.TextView) { + list.SetChangedFunc(nil) + list.Clear() + choices := []struct{ theme, text, explain string }{ + {SoundRetro, "Yes, retro sounds [green](recommended)[-]", " chiptune blips, like an old console"}, + {SoundWood, "Yes, wood sounds", " a soft click of pieces on a board"}, + {SoundOff, "No sound", " chess-cli stays quiet"}, + } + for i, c := range choices { + c := c + item := cv.NewListItem(c.text) + item.SetShortcut(numberKey(i)) + item.SetSecondaryText(c.explain) + item.SetSelectedFunc(func() { + _ = api.UpdateConfig(func(cfg *api.UserConfig) { cfg.Sound, cfg.SoundAsked = c.theme, true }) + keysStep(list, info) + }) + list.AddItem(item) + } + list.SetCurrentItem(0) + list.SetChangedFunc(func(i int, _ *cv.ListItem) { playSoundIn(choices[i].theme, soundMove) }) + note := "" + if !soundAvailable() { + note = "\n[yellow]" + cv.Escape(soundHelp()) + "[-]: you can still choose now and hear it later.\n" + } + info.SetText("[::b]Sound?[::-]\n\nchess-cli can play sounds for moves, captures, checks, low time and " + + "the end of a game, made for the terminal. Use ↑↓ to hear each, Enter to choose.\n" + note + + "\n[#a0a0a0]This can be changed in Options.[-]") + Root.App.SetFocus(list) +} + +func onboardInit() cv.Primitive { + preview := newPreviewBoard() + list := cv.NewList() + onboardList = list + list.SetHover(true) + list.SetWrapAround(true) + info := textBox(cv.AlignLeft) + forwardKeys(preview, list) + + rec := RecommendedPieces() + styles := []string{PiecesImage, PiecesText, PiecesBasic} + names := map[string]string{PiecesImage: "Image rendering", PiecesText: "Advanced rendering", PiecesBasic: "Basic rendering"} + explain := map[string]string{ + PiecesImage: "Lichess boards and pieces as pictures", + PiecesText: "Unicode chess symbols", + PiecesBasic: "plain symbols and 8 colours, for any terminal", + } + if TextSizingMode() { + explain[PiecesText] = "Unicode chess symbols, drawn big" + } + if !GraphicsSupported() { + explain[PiecesImage] = "not available in this terminal" + } + for _, st := range styles { + st := st + text := names[st] + if st == rec { + text += " [green](recommended)[-]" + } + item := cv.NewListItem(text) + item.SetShortcut(numberKey(len(list.GetItems()))) + item.SetSecondaryText(" " + explain[st]) + item.SetSelectedFunc(func() { + _ = SetPiecesSetting(st) + soundStep() + }) + list.AddItem(item) + } + for i, st := range styles { + if st == rec { + list.SetCurrentItem(i) + } + } + list.SetChangedFunc(func(i int, _ *cv.ListItem) { previewPieces(styles[i]) }) + previewPieces(rec) + + supports := "[red]✗[-] images" + if GraphicsSupported() { + supports = "[green]✓[-] images" + } + if TextSizingMode() { + supports += " [green]✓[-] big text" + } else { + supports += " [red]✗[-] big text" + } + if trueColor() { + supports += " [green]✓[-] true colour" + } else { + supports += " [yellow]?[-] true colour" + } + soundStep = func() { + if api.UserInfo.SoundAsked { + keysStep(list, info) + return + } + onboardSound(list, info) + } + if api.UserInfo.Pieces != "" { // only the later questions are new + defer soundStep() + } + info.SetText(fmt.Sprintf("[::b]Welcome to chess-cli![::-]\n\nYou're using [::b]%s[::-].\n%s\n\n"+ + "We recommend [green]%s[-] here. Use ↑↓ to preview each style, Enter to choose.\n\n"+ + "[#a0a0a0]This can be changed in Options.[-]", cv.Escape(terminalName()), supports, names[rec])) + + right := cv.NewFlex() + right.SetDirection(cv.FlexRow) + right.AddItem(info, 0, 1, false) + right.AddItem(list, 7, 0, true) + right.AddItem(cv.NewBox(), 0, 1, false) + right.SetPadding(1, 0, 2, 2) + + body := newPreviewLayout(preview, right) + + root := cv.NewFlex() + root.SetDirection(cv.FlexRow) + root.AddItem(body, 0, 1, true) + root.AddItem(ribbonPrimitive(" chess-cli · first run │ ↑↓ preview │ Enter to choose │ Ctrl-C quit", list), 1, 0, false) + registerMenus("onboard", false, list) + return root +} diff --git a/pkg/ui_options.go b/pkg/ui_options.go new file mode 100644 index 0000000..9828007 --- /dev/null +++ b/pkg/ui_options.go @@ -0,0 +1,289 @@ +package pkg + +import ( + "fmt" + + "github.com/nate-xyz/chess-cli/api" + + cv "codeberg.org/tslocum/cview" + tc "github.com/gdamore/tcell/v3" + "github.com/notnil/chess" +) + +type optionsState struct { + list *cv.List + preview *BoardView + note *cv.TextView + sub string // "" = main list, or "pieces" / "boards" submenu + before string // setting when the submenu opened, restored by Esc +} + +var optionsScreen optionsState + +// optionsInit builds the Options screen: piece style, with a live preview. +func optionsInit() cv.Primitive { + list := cv.NewList() + list.SetHover(true) + list.SetWrapAround(true) + + preview := newPreviewBoard() + forwardKeys(preview, list) + + note := textBox(cv.AlignLeft) + title := titlePrimitive("[blue]Options[white]", list) + + right := cv.NewFlex() + right.SetDirection(cv.FlexRow) + right.AddItem(list, 0, 3, true) + right.AddItem(note, 0, 1, false) + + right.SetPadding(0, 0, 2, 0) + body := newPreviewLayout(preview, right) + + root := cv.NewFlex() + root.SetDirection(cv.FlexRow) + root.AddItem(title, 3, 0, false) + root.AddItem(body, 0, 1, true) + root.AddItem(ribbonPrimitive(" chess-cli · options │ ↑↓ preview │ Enter to choose │ Esc back │ Ctrl-C quit", list), 1, 0, false) + + optionsScreen.list, optionsScreen.preview, optionsScreen.note = list, preview, note + registerMenus("options", false, list) + return root +} + +// newPreviewBoard shows a sample position with a last move, a selected +// piece and its moves, to preview how boards look. +// previewLayout is a sample board on the left and text on the right (first +// run, Options): the board gets the width it needs and the text the rest, +// so explanations aren't cut off in a big terminal. +type previewLayout struct { + *cv.Flex + board *BoardView + text cv.Primitive + last int +} + +// The text column's width: wide enough for every explanation when there's +// room (the board is only a sample here), never less than the minimum. +const ( + textWidth = 76 + minTextWidth = 50 + minPreviewWidth = 40 // the sample board keeps at least this +) + +func newPreviewLayout(board *BoardView, text cv.Primitive) *previewLayout { + l := &previewLayout{Flex: cv.NewFlex(), board: board, text: text, last: -1} + l.AddItem(board, 0, 3, false) + l.AddItem(text, 0, 2, true) + return l +} + +func (l *previewLayout) Draw(screen tc.Screen) { + _, _, w, h := l.GetRect() + text := max(minTextWidth, min(textWidth, w-minPreviewWidth)) // small terminal: share the room + _, bw, _ := l.board.fit(screen, max(0, w-text), h) + bw = min(w, bw+4) // a little room around the board + if bw != l.last { + l.last = bw + l.ResizeItem(l.board, bw, 0) + l.ResizeItem(l.text, 0, 1) + } + l.Flex.Draw(screen) +} + +func newPreviewBoard() *BoardView { + preview := NewBoardView(nil) + game := chess.NewGame(chess.UseNotation(chess.UCINotation{})) + for _, m := range []string{"e2e4", "e7e5", "g1f3", "b8c6", "f1c4", "g8f6"} { + _ = game.MoveStr(m) + } + preview.SetPosition(game.Position(), true) + preview.SetLastMove(chess.G8, chess.F6) + preview.SetSelection(chess.F3, map[chess.Square]bool{chess.G5: true, chess.E5: true, chess.H4: true, chess.D4: true}) + return preview +} + +func gotoOptions() { + optionsScreen.sub = "" + updateOptions() + Root.Switch("options") +} + +// optionsBack leaves a submenu (undoing its preview) or the screen. +func optionsBack() { + o := &optionsScreen + switch o.sub { + case "pieces": + api.SetConfig(func(c *api.UserConfig) { c.PieceSet = o.before }) + case "boards": + api.SetConfig(func(c *api.UserConfig) { c.Board = o.before }) + default: + gotoWelcome() + return + } + o.sub = "" + updateOptions() +} + +func updateOptions() { + o := &optionsScreen + switch o.sub { + case "pieces": + o.showChoices(pieceSets, currentPieceSet(), func(v string) { api.SetConfig(func(c *api.UserConfig) { c.PieceSet = v }) }) + return + case "boards": + names := make([]string, len(boardThemes)) + for i, t := range boardThemes { + names[i] = t.name + } + o.showChoices(names, currentBoard().name, func(v string) { api.SetConfig(func(c *api.UserConfig) { c.Board = v }) }) + return + } + + current := PiecesSetting() + mark := func(style string) string { + if style == current { + return "[green]●[-] " + } + return "○ " + } + sel := o.list.GetCurrentItemIndex() + o.list.SetChangedFunc(nil) + o.list.Clear() + o.list.ShowSecondaryText(true) + add := func(text, explain string, key rune, f func()) { + item := cv.NewListItem(text) + item.SetSecondaryText(" " + explain) + item.SetShortcut(key) + item.SetSelectedFunc(f) + o.list.AddItem(item) + } + add(mark(PiecesText)+"Advanced rendering", "Unicode chess symbols; big in kitty", 'c', func() { choosePieces(PiecesText) }) + add(mark(PiecesImage)+"Image rendering", "Lichess boards and piece sets", 'i', func() { choosePieces(PiecesImage) }) + if current == PiecesImage { + add(" Piece set: [::b]"+currentPieceSet()+"[::-] ›", " Choose from "+fmt.Sprint(len(pieceSets))+" sets", 'p', func() { o.openSub("pieces", currentPieceSet()) }) + add(" Board: [::b]"+currentBoard().name+"[::-] ›", " Choose the board colours", 'o', func() { o.openSub("boards", currentBoard().name) }) + } + add(mark(PiecesBasic)+"Basic rendering", "Plain symbols and colours, for any terminal", 'a', func() { choosePieces(PiecesBasic) }) + moveBox, other := "Ctrl-K only", "always shown" + if moveBoxAlways() { + moveBox, other = "always shown", "Ctrl-K only" + } + add("Move box: [::b]"+moveBox+"[::-]", "Typing moves: Enter to switch to "+other, 'm', func() { + setMoveBoxAlways(!moveBoxAlways()) + updateOptions() + }) + onOff := func(b bool) string { + if b { + return "on" + } + return "off" + } + add("Clock bar: [::b]"+onOff(clockBarsOn())+"[::-]", "Clocks with a bar beside the board, or plain in the sidebar", 'k', func() { + setClockBars(!clockBarsOn()) + updateOptions() + }) + add("Zen mode: [::b]"+onOff(zenMode())+"[::-]", "Hide names, ratings, chat and game info during games", 'z', func() { + setZen(!zenMode()) + updateOptions() + }) + keys := "arrows and hjkl" + if !vimKeys() { + keys = "arrows only" + } + add("Keys: [::b]"+keys+"[::-]", "Move with the arrow keys, or with vim's hjkl too", 'y', func() { + setVimKeys(!vimKeys()) + updateOptions() + }) + soundExplain := "Retro chiptune, Wood, or off; Enter for the next" + if !soundAvailable() { + soundExplain = "Can't play sound here: " + soundHelp() + } + add("Sound: [::b]"+soundThemeNames[soundTheme()]+"[::-]", soundExplain, 'u', func() { + next := soundThemes[0] + for i, t := range soundThemes { + if t == soundTheme() { + next = soundThemes[(i+1)%len(soundThemes)] + } + } + setSoundTheme(next) + playSound(soundMove) // a sample of the new theme + updateOptions() + }) + reset := cv.NewListItem("Reset all settings") + reset.SetSecondaryText(" Defaults, then first-run setup again (keeps login and games)") + reset.SetShortcut('r') + confirmItem(reset, "Reset all settings", "Reset all settings? Press again", resetSettings) + o.list.AddItem(reset) + add("Back", "Return to the home screen", 'b', gotoWelcome) + o.list.SetCurrentItem(sel) + + note := "[::b]Pieces[::-]\n\n" + if GraphicsSupported() { + note += "Image rendering draws Lichess's boards and piece sets as pictures, scaled to the board. Only sets with licences that allow them in chess-cli are included.\n" + } else { + note += "[yellow]This terminal can't show images[-], so image rendering falls back to advanced rendering. " + + "Images work in terminals with the kitty graphics protocol, such as kitty, Ghostty and WezTerm (not inside tmux).\n" + } + if TextSizingMode() { + note += "\nWith advanced rendering, pieces are drawn big using kitty's text sizing.\n" + } + note += "\nBasic rendering uses only the terminal's 8 standard colours and plain symbols, like the original chess-cli. Use it if the board looks wrong in your terminal.\n" + o.note.SetText(note) +} + +func (o *optionsState) openSub(sub, current string) { + o.sub, o.before = sub, current + o.list.SetCurrentItem(0) + updateOptions() +} + +// showChoices lists the values of a submenu. Moving through the list +// previews each one; Enter keeps it, Esc goes back to the previous one. +func (o *optionsState) showChoices(values []string, current string, apply func(string)) { + o.list.SetChangedFunc(nil) + o.list.Clear() + o.list.ShowSecondaryText(false) + sel := 0 + for i, v := range values { + v := v + item := cv.NewListItem(" " + v) + item.SetShortcut(numberKey(i)) + if v == current { + item.SetMainText("[green]●[-] " + v) + sel = i + } + item.SetSelectedFunc(func() { + apply(v) + _ = api.SaveConfig() + o.sub = "" + updateOptions() + }) + o.list.AddItem(item) + } + back := cv.NewListItem("Back") + back.SetShortcut('b') + back.SetSelectedFunc(optionsBack) + o.list.AddItem(back) + o.list.SetCurrentItem(sel) + o.list.SetChangedFunc(func(i int, _ *cv.ListItem) { + if i < len(values) { + apply(values[i]) + } else { + apply(o.before) + } + }) + what := "piece set" + if o.sub == "boards" { + what = "board" + } + o.note.SetText(fmt.Sprintf("[::b]Choose a %s[::-]\n\nMove through the list to preview; Enter to keep, Esc to go back.", what)) +} + +func choosePieces(style string) { + if err := SetPiecesSetting(style); err != nil { + optionsScreen.note.SetText(fmt.Sprintf("[red]Couldn't save the setting: %v[-]", err)) + return + } + updateOptions() +} diff --git a/pkg/ui_stockfish.go b/pkg/ui_stockfish.go new file mode 100644 index 0000000..2645b3c --- /dev/null +++ b/pkg/ui_stockfish.go @@ -0,0 +1,149 @@ +package pkg + +import ( + "fmt" + "math/rand" + "os" + "path/filepath" + "strings" + + cv "codeberg.org/tslocum/cview" + "github.com/nate-xyz/chess-cli/api" + "github.com/notnil/chess" +) + +// The "Play local Stockfish" menu on the home screen: level and colour, or, +// when no Stockfish is found, ways to get one. + +var ( + stockfishColor = "random" // "white", "black" or "random" + downloading bool +) + +// expandHome turns a leading ~ into the home folder. +func expandHome(p string) string { + if strings.HasPrefix(p, "~/") || p == "~" { + if home, err := os.UserHomeDir(); err == nil { + return filepath.Join(home, strings.TrimPrefix(p, "~")) + } + } + return p +} + +func stockfishLevel() int { + if l := api.UserInfo.StockfishLevel; l >= 1 && l <= 8 { + return l + } + return 3 +} + +// stockfishList fills the home menu list; back returns to the previous menu. +func stockfishList(list *cv.List, back func()) { + again := func() { stockfishList(list, back) } + cur := list.GetCurrentItemIndex() + list.Clear() + add := func(text, explain string, key rune, f func()) *cv.ListItem { + item := cv.NewListItem(text) + item.SetSecondaryText(explain) + if key != 0 { + item.SetShortcut(key) + } + item.SetSelectedFunc(f) + list.AddItem(item) + return item + } + defer list.SetCurrentItem(cur) + + path := findEngine() + if path == "" { + add("Download Stockfish for me", "Official release from GitHub (~80 MB), kept in chess-cli's folder", 'd', func() { + if !downloading { + downloadEngine(list, again) + } + }) + add("Use my Stockfish…", "Enter the path of a Stockfish you already have", 'u', func() { askEnginePath(again) }) + add("Install it yourself", installHint()+" (then come back here)", 'i', again) + add("Back", "Go back", 'b', back) + return + } + + level := stockfishLevel() + add(fmt.Sprintf("Start game · level %d · %s", level, stockfishColor), "Using "+filepath.Base(path), 's', func() { + player := chess.White + switch stockfishColor { + case "black": + player = chess.Black + case "random": + if rand.Intn(2) == 1 { + player = chess.Black + } + } + startEngineGame(path, level, player) + }) + add(fmt.Sprintf("Level: %d", level), "1 (beginner) to 8 (full strength); Enter for the next", 'l', func() { + _ = api.UpdateConfig(func(c *api.UserConfig) { c.StockfishLevel = level%8 + 1 }) + again() + }) + add("Colour: "+stockfishColor, "Play white, black or random; Enter to change", 'c', func() { + stockfishColor = map[string]string{"random": "white", "white": "black", "black": "random"}[stockfishColor] + again() + }) + add("Clock: "+localClockName(localClockIndex()), "Time control; Enter for the next", 'k', func() { + nextLocalClock() + again() + }) + add("Use a different Stockfish…", path, 'u', func() { askEnginePath(again) }) + add("Back", "Go back", 'b', back) +} + +// askEnginePath asks where Stockfish is, checks it, and remembers it. +func askEnginePath(then func()) { + const q = "Where is Stockfish? Enter the full path of the program." + askText(q, "Path: ", func(text string) { + p, err := filepath.Abs(expandHome(text)) + if err == nil { + err = checkEngine(p) + } + if err != nil { + promptError(q, "That didn't work: "+err.Error()) + return + } + _ = api.UpdateConfig(func(c *api.UserConfig) { c.StockfishPath = p }) + gotoWelcome() + then() + }) +} + +// downloadEngine downloads Stockfish, showing progress in the menu item. +func downloadEngine(list *cv.List, then func()) { + downloading = true + item := list.GetItem(list.GetCurrentItemIndex()) + item.SetSecondaryText("Starting download…") + go func() { + last := -1 + path, err := DownloadStockfish(func(done, total int64) { + if total <= 0 { + return + } + pct := int(done * 100 / total) + if pct == last { + return + } + last = pct + Root.App.QueueUpdateDraw(func() { + item.SetSecondaryText(fmt.Sprintf("Downloading… %d%% of %d MB", pct, total>>20)) + }) + }) + if err == nil { + err = checkEngine(path) + } + Root.App.QueueUpdateDraw(func() { + downloading = false + if err != nil { + item.SetSecondaryText(fmt.Sprintf("[red]Download failed: %v[-]", err)) + return + } + then() + }) + }() +} diff --git a/pkg/ui_types.go b/pkg/ui_types.go index 8b8cb5e..eb41236 100644 --- a/pkg/ui_types.go +++ b/pkg/ui_types.go @@ -1,12 +1,16 @@ package pkg import ( - cv "code.rocketnine.space/tslocum/cview" + "context" + "time" + + cv "codeberg.org/tslocum/cview" "github.com/nate-xyz/chess-cli/api" + "github.com/notnil/chess" ) type GameScreen struct { - Board *cv.Table + Board *BoardView Status *cv.TextView History *cv.TextView UserInfo *cv.TextView @@ -14,17 +18,22 @@ type GameScreen struct { OppInfo *cv.TextView OppTimer *cv.TextView List *cv.List + Move *moveBox + + engine *Engine // set when playing a local Stockfish + engineColor chess.Color + engineLevel int + engineGen int // bumped when an engine game starts or stops + clock localClock } type PostGameScreen struct { - Board *cv.Table - Result *cv.TextView - History *cv.TextView + *postGame } type SavedGames struct { List *cv.List - Preview *cv.Table + Preview *BoardView } type WelcomeOnline struct { @@ -37,8 +46,9 @@ type Loader struct { } type OnlineGame struct { - Grid *cv.Grid - Board *cv.Table + Side *cv.Flex + Move *moveBox + Board *BoardView Status *cv.TextView History *cv.TextView List *cv.List @@ -47,24 +57,33 @@ type OnlineGame struct { OppInfo *cv.TextView OppTimer *cv.TextView PopUp *cv.Flex + Chat *cv.TextView + ChatInput *cv.InputField - Full api.StreamBoardGameFull - State api.StreamBoardGameState - Resign api.StreamBoardResign + Full api.StreamBoardGameFull + State api.StreamBoardGameState + Gone api.StreamOpponentGone + + // per-game state, reset by startNewOnlineGame; UI goroutine only + ctx context.Context + cancel context.CancelFunc + ended bool + popupKind string // which offer the popup is showing, if any + goneSince time.Time // when the opponent-gone event arrived + canClaim bool // opponent gone long enough to claim + clockW int64 // clocks (ms) as of clockAt + clockB int64 + clockAt time.Time + lowWarned bool // the low-time sound has played this game } type OnlinePostGame struct { - Grid *cv.Grid - - Board *cv.Table - Result *cv.TextView - History *cv.TextView - PopUp *cv.Flex + *postGame } type Ongoing struct { List *cv.List - Preview *cv.Table + Preview *BoardView } type Challenges struct { diff --git a/pkg/ui_update_local.go b/pkg/ui_update_local.go index 1cd775c..8a8c750 100644 --- a/pkg/ui_update_local.go +++ b/pkg/ui_update_local.go @@ -4,7 +4,7 @@ import ( "fmt" "strings" - cv "code.rocketnine.space/tslocum/cview" + cv "codeberg.org/tslocum/cview" "github.com/notnil/chess" ) @@ -12,13 +12,13 @@ func (g *GameScreen) UpdateStatus() { var status string = Root.gameState.Status Root.gameState.Status = "" if Root.gameState.Game.Position().Turn() == chess.White { - status += "White's turn. \n\n" + status = "White to move. " + status } else { - status += "Black's turn. \n\n" + status = "Black to move. " + status + } + if g.engineTurn() { + status += "\n[#a0a0a0]Stockfish is thinking…[-]" } - - Root.gameState.UpdateLegalMoves() - status += "Valid Moves: [green]" + strings.Join(Root.gameState.LegalMoves, ", ") + "[white]\n" g.Status.SetText(status) } @@ -26,8 +26,10 @@ func (g *GameScreen) DoMove(m string) error { gClone := Root.gameState.Game.Clone() move, _ := GetMoveType(m, Root.gameState.Game) //store move p := GetPiece(m[2:], gClone).String() //get piece - err := Root.gameState.Game.MoveStr(m) //do the move + mover := Root.gameState.Game.Position().Turn() + err := Root.gameState.Game.MoveStr(m) //do the move if err == nil { + g.clockMoved(mover) if move.HasTag(chess.Check) { Root.gameState.Status += "Check!" } @@ -40,7 +42,7 @@ func (g *GameScreen) DoMove(m string) error { } Root.gameState.MoveHistoryArray = append(Root.gameState.MoveHistoryArray, m) DrawMoveHistory(g.History) - DrawBoard(g.Board, Root.gameState.Game.Position().Turn() == chess.White) + DrawBoard(g.Board, g.whiteAtBottom()) Root.gameState.NextMove = "" //clear the next move g.UpdateStatus() g.UpdateUserInfo() @@ -48,6 +50,8 @@ func (g *GameScreen) DoMove(m string) error { Root.App.GetScreen().Beep() if Root.gameState.Game.Outcome() != chess.NoOutcome { //check if game is done gotoPostLocal() + } else if g.engineTurn() { + g.engineMove() } return nil } @@ -79,36 +83,29 @@ func (g *GameScreen) UpdateUserInfo() { OppString = fmt.Sprintf("%v\n%v", WhiteCapture, OppString) } + if g.vsEngine() { + you, sf := WhiteCapture, BlackCapture + youName, sfName := "White", "Black" + if g.engineColor == chess.White { + you, sf, youName, sfName = BlackCapture, WhiteCapture, "Black", "White" + } + UserString = fmt.Sprintf("[blue]You (%s)[white]\n%v", youName, you) + OppString = fmt.Sprintf("%v\n[red]Stockfish level %d (%s)[white]", sf, g.engineLevel, sfName) + } g.UserInfo.SetText(UserString) g.OppInfo.SetText(OppString) } -func LocalTableHandler(row, col int) { - selectedCell := translateSelectedCell(row, col, Root.gameState.Game.Position().Turn() == chess.White) - if LastSelectedCell.Alg == selectedCell { - //toggle selected status of this cell - Root.lgame.Board.Select(100, 100) - LastSelectedCell = PiecePosition{-1, -1, "", true, ""} - } else { - //try to do move - todoMove := LastSelectedCell.Alg + selectedCell - if contains(Root.gameState.LegalMoves, todoMove) { - err := Root.lgame.DoMove(todoMove) - if err != nil { - Root.gameState.Status += fmt.Sprintf("%v", err) - Root.lgame.UpdateStatus() - } +// LocalSquareHandler handles a click (or Enter) on a board square in a local game. +func LocalSquareHandler(sq chess.Square) { + g := Root.lgame + g.Board.HandleSquare(Root.gameState.Game, sq, !g.engineTurn(), func(uci string) { + if err := g.DoMove(uci); err != nil { + Root.gameState.Status += fmt.Sprintf("%v", err) + g.UpdateStatus() } - //check if select is empty for updateBoard - symbol := Root.lgame.Board.GetCell(row, col).GetText() - LastSelectedCell = PiecePosition{row, col, selectedCell, (symbol == EmptyChar), symbol} - } - DrawBoard(Root.lgame.Board, Root.gameState.Game.Position().Turn() == chess.White) -} - -func (g *PostGameScreen) UpdateResult() { - g.Result.SetText(Root.gameState.Status) - Root.gameState.Status = "" + }) + DrawBoard(g.Board, g.whiteAtBottom()) } func (sg *SavedGames) UpdateList() { @@ -130,7 +127,7 @@ func (sg *SavedGames) UpdateList() { item := cv.NewListItem(text) item.SetSecondaryText(game.FEN) - item.SetShortcut(rune('a' + i)) + item.SetShortcut(numberKey(i)) sg.List.AddItem(item) } } diff --git a/pkg/ui_update_online.go b/pkg/ui_update_online.go index b9e220d..c28fbf7 100644 --- a/pkg/ui_update_online.go +++ b/pkg/ui_update_online.go @@ -4,8 +4,9 @@ import ( "fmt" "math" "strings" + "time" - cv "code.rocketnine.space/tslocum/cview" + cv "codeberg.org/tslocum/cview" tc "github.com/gdamore/tcell/v3" "github.com/nate-xyz/chess-cli/api" "github.com/notnil/chess" @@ -14,61 +15,77 @@ import ( func (og *OnlineGame) UpdateAll() { Root.gameState.UpdateLegalMoves() DrawMoveHistory(og.History) - DrawBoard(og.Board, og.Full.White.Name == Root.User.Name) + DrawBoard(og.Board, og.IsWhite()) og.UpdateStatus() og.UpdateUserInfo() og.UpdateList() - Root.RefreshAll() } func (og *OnlineGame) UpdateList() { list := og.List list.Clear() - optionsList := []string{"Back", "Quit"} - optionsExplain := []string{"Go back Home", "Close chess-cli"} + optionsList := []string{"Leave game", "Quit"} + optionsExplain := []string{"Back to the Lichess menu (the game keeps going)", "Close chess-cli"} optionsFunc := []ListSelectedFunc{gotoLichessFromGame, Root.App.Stop} + keys := []rune{'x', 'q'} for i, opt := range optionsList { item := cv.NewListItem(opt) item.SetSecondaryText(optionsExplain[i]) item.SetSelectedFunc(optionsFunc[i]) + item.SetShortcut(keys[i]) list.AddItem(item) } - optionsList = []string{"Takeback", "Abort", "Offer Draw", "Resign"} - optionsExplain = []string{"Propose a takeback", "Abort the current game", "Offer a draw to your opponent", "Resign from the current game"} - optionsFunc = []ListSelectedFunc{og.doProposeTakeBack, og.doAbort, og.doOfferDraw, og.doResign} + optionsList = []string{"Takeback", "Abort", "Offer Draw", "Resign", "Claim Draw", "Claim Victory"} + optionsExplain = []string{"Propose a takeback", "Abort the current game", "Offer a draw to your opponent", "Resign from the current game", + "Opponent left: end the game as a draw", "Opponent left: claim the win"} + optionsFunc = []ListSelectedFunc{og.doProposeTakeBack, og.doAbort, og.doOfferDraw, og.doResign, og.doClaimDraw, og.doClaimVictory} + keys = []rune{'t', 'a', 'd', 'g', 'c', 'v'} // g: give up (r picks a rook when promoting) for i, opt := range optionsList { if opt == "Takeback" && Root.gameState.MoveCount == 0 { continue } + if opt == "Abort" && Root.gameState.MoveCount >= 2 { + continue // Lichess only allows aborting before both sides have moved + } if (opt == "Offer Draw" || opt == "Resign") && Root.gameState.MoveCount < 2 { continue } + if (opt == "Claim Draw" || opt == "Claim Victory") && !(og.Gone.Gone && og.canClaim) { + continue + } item := cv.NewListItem(opt) item.SetSecondaryText(optionsExplain[i]) - item.SetSelectedFunc(optionsFunc[i]) + item.SetShortcut(keys[i]) + if opt == "Abort" || opt == "Resign" { // press twice: a stray key shouldn't end the game + confirmItem(item, opt, opt+"? Press again", optionsFunc[i]) + } else { + item.SetSelectedFunc(optionsFunc[i]) + } list.InsertItem(1, item) } - + og.Side.ResizeItem(list, list.GetItemCount(), 0) } func (w *WelcomeOnline) UpdateTitle(msg string) { var titlestr string = LichessTitle - if api.Online { + if api.IsOnline() { titlestr += " 🟢" } else { titlestr += " ⚪" } - if api.UserInfo.ApiToken == "" { - titlestr += "[red]\nNot logged into lichess.[blue]\nPlease login through your browser.[white]\nLink should open automatically." + if Root.User == nil || Root.User.Name == "" { + titlestr += "[red]\nNot logged in to Lichess.[white]" + if loginURL != "" { + titlestr += "\n[blue]Log in through your browser; it should open by itself.[white]\nIf it didn't, open this link:\n" + cv.Escape(loginURL) + } } else { - titlestr += fmt.Sprintf("\n[green]Logged in[white] as: [blue]%s, %s[white]\n", Root.User.Name, Root.User.Email) + titlestr += fmt.Sprintf("\n[green]Logged in[white] as: [blue]%s[white]\n", cv.Escape(Root.User.Name)) } if msg != "" { titlestr += msg } w.Title.SetText(titlestr) - Root.App.QueueUpdateDraw(func() {}, w.Title) } func (og *OnlineGame) UpdateStatus() { @@ -82,7 +99,9 @@ func (og *OnlineGame) UpdateStatus() { ratestr = "Casual" } - if og.Full.Speed == "correspondence" { + if zenMode() { + // zen: no game info + } else if og.Full.Speed == "correspondence" { status += fmt.Sprintf("\n%v • %v %v\n", ratestr, caser.String(og.Full.Speed), @@ -97,58 +116,54 @@ func (og *OnlineGame) UpdateStatus() { } if Root.gameState.Game.Position().Turn() == chess.White { - status += "White's turn. \n\n" + status += "White to move.\n" } else { - status += "Black's turn. \n\n" + status += "Black to move.\n" + } + if og.Gone.Gone { + if og.canClaim { + status += "[yellow]Your opponent left. You can claim victory or a draw from the menu.[-]\n" + } else { + status += fmt.Sprintf("[yellow]Your opponent left. You can claim the game in %ds if they don't return.[-]\n", og.Gone.ClaimWinInSeconds) + } } og.Status.SetText(status) } func (og *OnlineGame) UpdateUserInfo() { - var ( - OppName string = "%s" - You string = "%s" - UserString string = "\n[blue]%v[white]" - OppString string = "\n[red]%v[white]" - BlackCapture string = strings.Join(Root.gameState.BlackCaptured, "") + " \t" - WhiteCapture string = strings.Join(Root.gameState.WhiteCaptured, "") + " \t" - ) - - if og.Full.White.Name == Root.User.Name { - if og.Full.Rated { - OppName = fmt.Sprintf("%s (%d)", og.Full.Black.Name, og.Full.Black.Rating) - You = fmt.Sprintf("%s (%d)", Root.User.Name, og.Full.White.Rating) - } else { - OppName = og.Full.Black.Name - You = Root.User.Name + describe := func(p api.GamePlayer) string { + if p.AiLevel > 0 { + return fmt.Sprintf("🤖 Stockfish level %d", p.AiLevel) } - UserString = UserString + " (white)\n" - UserString += WhiteCapture - OppString = OppString + " (black)\n" - OppString = BlackCapture + OppString - } else { - if og.Full.Rated { - OppName = fmt.Sprintf("%s (%d)", og.Full.White.Name, og.Full.White.Rating) - You = fmt.Sprintf("%s (%d)", Root.User.Name, og.Full.Black.Rating) - } else { - OppName = og.Full.White.Name - You = Root.User.Name + name := p.Name + if p.Title != "" { + name = p.Title + " " + name + } + name = cv.Escape(name) + if og.Full.Rated && p.Rating > 0 { + name += fmt.Sprintf(" (%d", p.Rating) + if p.Provisional { + name += "?" + } + name += ")" } - OppString = OppString + " (white)\n" - OppString = WhiteCapture + OppString - UserString = UserString + " (black)\n" - UserString += BlackCapture + return name } - - if CurrentChallenge.Type == 2 { - OppName = "🤖" + whiteCaptured := strings.Join(Root.gameState.WhiteCaptured, "") + " \t" + blackCaptured := strings.Join(Root.gameState.BlackCaptured, "") + " \t" + white := og.IsWhite() + me, opp := og.Full.White, og.Full.Black + myColor, oppColor, myCaptured, oppCaptured := "white", "black", whiteCaptured, blackCaptured + if !white { + me, opp = opp, me + myColor, oppColor, myCaptured, oppCaptured = oppColor, myColor, oppCaptured, myCaptured } - - UserString = fmt.Sprintf(UserString, You) - OppString = fmt.Sprintf(OppString, OppName) - - og.UserInfo.SetText(UserString) - og.OppInfo.SetText(OppString) + meName, oppName := describe(me), describe(opp) + if zenMode() { + meName, oppName = "You", "Opponent" + } + og.UserInfo.SetText(fmt.Sprintf("\n[blue]%s[white] (%s)\n%s", meName, myColor, myCaptured)) + og.OppInfo.SetText(fmt.Sprintf("%s\n[red]%s[white] (%s)\n", oppCaptured, oppName, oppColor)) } func (l *Loader) DrawIcon(i int) int { @@ -161,50 +176,50 @@ func (l *Loader) DrawIcon(i int) int { if i > 7 { i = 0 } - Root.RefreshAll() return i } -func (l *Loader) DrawMessage(msg string) { - l.Message.SetText(msg) - Root.RefreshAll() -} - +// DoMove plays a move: it's shown straight away, then sent to Lichess in the +// background. If Lichess rejects it, the board goes back to the last position +// Lichess confirmed. UI goroutine only. func (og *OnlineGame) DoMove(move string) error { - go func() { - err := Root.gameState.Game.MoveStr(move) - if err == nil { - DrawBoard(og.Board, og.Full.White.Name == Root.User.Name) - Root.App.QueueUpdateDraw(func() {}, og.Board) - } - }() - - err := api.MakeMove(currentGameID, move) //do the move - if err != nil { + if err := Root.gameState.Game.MoveStr(move); err != nil { return err } - Root.App.GetScreen().Beep() - - DrawBoard(og.Board, og.Full.White.Name == Root.User.Name) - - Root.gameState.NextMove = "" //clear the next move + Root.gameState.NextMove = "" + DrawBoard(og.Board, og.IsWhite()) og.UpdateStatus() + Root.App.GetScreen().Beep() + gameID := currentGameID + go func() { + err := api.MakeMove(gameID, move) + if err == nil { + return + } + Root.App.QueueUpdateDraw(func() { + if og.ended || currentGameID != gameID { + return + } + Root.gameState.Status += fmt.Sprintf("[red]Move %s rejected: %v[-]\n", move, err) + og.applyState(og.State) // back to the last confirmed position + }) + }() return nil } -func (og *OnlineGame) InitTimeView() { - b := int64(og.Full.State.Btime) - w := int64(og.Full.State.Wtime) - og.LiveUpdateTime(b, w) -} - func (og *OnlineGame) LiveUpdateTime(b int64, w int64) { //MoveCount - if og.Full.State.Btime == math.MaxInt32 { + if og.Full.State.Btime == math.MaxInt32 { // unlimited: no clocks + if clockBarsOn() { + og.Board.SetClockBars(clockBar{label: "∞", frac: -1, right: "Unlimited"}, clockBar{label: "∞", frac: -1, right: "Unlimited"}) + } else { + og.UserTimer.SetText("∞") + og.OppTimer.SetText("∞ Unlimited") + } return } - var White bool = og.Full.White.Name == Root.User.Name + var White bool = og.IsWhite() var UserStr string var OppoStr string @@ -254,30 +269,64 @@ func (og *OnlineGame) LiveUpdateTime(b int64, w int64) { //MoveCount og.UserTimer.SetText(UserStr) og.OppTimer.SetText(OppoStr) + mine := w + if !og.IsWhite() { + mine = b + } + myTurn := (Root.gameState.Game.Position().Turn() == chess.White) == og.IsWhite() + if !og.lowWarned && !og.ended && myTurn && og.Full.Speed != "correspondence" && + lowTime(time.Duration(mine)*time.Millisecond, time.Duration(og.Full.Clock.Initial)*time.Millisecond) { + og.lowWarned = true + playSound(soundLowTime) + } + if clockBarsOn() { + og.updateClockBars(b, w) + } } -func (online *OnlineGame) OnlineTableHandler(row, col int) { - selectedCell := translateSelectedCell(row, col, online.Full.White.Name == Root.User.Name) - - if LastSelectedCell.Alg == selectedCell { //toggle selected status of this cell +// timeControl describes the game's time control, e.g. "10+5". +func (og *OnlineGame) timeControl() string { + return timeControlText(og.Full.Clock.Initial/1000, og.Full.Clock.Increment/1000, og.Full.Speed, og.Full.DaysPerTurn) +} - online.Board.Select(100, 100) - LastSelectedCell = PiecePosition{-1, -1, "", true, ""} - } else { //try to do move +// updateClockBars shows the clocks beside the board: you at the bottom. +// b and w are milliseconds. +func (og *OnlineGame) updateClockBars(b, w int64) { + initial := int64(og.Full.Clock.Initial) + running := Root.gameState.MoveCount >= 2 && !og.ended + whiteToMove := Root.gameState.Game.Position().Turn() == chess.White + bar := func(ms int64, active bool) clockBar { + c := clockBar{label: clockLabel(int(ms / 1000)), frac: -1, active: active && running} + if og.Full.Speed != "correspondence" && initial > 0 { + c.frac = float64(ms) / float64(initial) + } + return c + } + wc, bc := bar(w, whiteToMove), bar(b, !whiteToMove) + top, bottom := bc, wc + if !og.IsWhite() { + top, bottom = wc, bc + } + top.right, bottom.right = og.timeControl(), og.timeControl() + og.Board.SetClockBars(top, bottom) +} - todoMove := LastSelectedCell.Alg + selectedCell - if contains(Root.gameState.LegalMoves, todoMove) { - err := online.DoMove(todoMove) - if err != nil { +// OnlineSquareHandler handles a click (or Enter) on a board square in an online game. +// Only your own pieces can be selected, and only on your turn. +func (online *OnlineGame) OnlineSquareHandler(sq chess.Square) { + white := online.IsWhite() + myTurn := (Root.gameState.Game.Position().Turn() == chess.White) == white + if !myTurn { + online.Board.ClearSelection() + } else { + online.Board.HandleSquare(Root.gameState.Game, sq, true, func(uci string) { + if err := online.DoMove(uci); err != nil { Root.gameState.Status += fmt.Sprintf("%v", err) online.UpdateStatus() } - } - //check if select is empty for updateBoard - symbol := online.Board.GetCell(row, col).GetText() - LastSelectedCell = PiecePosition{row, col, selectedCell, (symbol == EmptyChar), symbol} + }) } - DrawBoard(online.Board, online.Full.White.Name == Root.User.Name) + DrawBoard(online.Board, white) } func (ongoing *Ongoing) UpdateList() { @@ -288,8 +337,8 @@ func (ongoing *Ongoing) UpdateList() { continue } GameListIDArr = append(GameListIDArr, game.FullID) - variant := game.Variant.Name - opp := game.Opponent.Username + variant := cv.Escape(game.Variant.Name) + opp := cv.Escape(game.Opponent.Username) oppRating := game.Opponent.Rating perf := caser.String(game.Perf) listString := fmt.Sprintf("%v vs %v", perf, opp) @@ -316,17 +365,17 @@ func (ongoing *Ongoing) UpdateList() { } else { text += " White to play, " } - text += fmt.Sprintf("(%v)", Root.User.Name) + text += fmt.Sprintf("(%v)", cv.Escape(Root.User.Name)) } else { if game.Color == "black" { text += "White to play, " } else { text += "Black to play, " } - text += fmt.Sprintf("(%v)", game.Opponent.ID) + text += fmt.Sprintf("(%v)", cv.Escape(game.Opponent.ID)) } item.SetSecondaryText(text) - item.SetShortcut(rune('a' + i)) + item.SetShortcut(numberKey(i)) ongoing.List.AddItem(item) } @@ -335,16 +384,18 @@ func (ongoing *Ongoing) UpdateList() { func (c *Challenges) UpdateList() { c.In.Clear() c.Out.Clear() + InChallengeGameID = nil + OutChallengeGameID = nil for i, challenge := range Root.User.IncomingChallenges { if contains(InChallengeGameID, challenge.ID) { continue } InChallengeGameID = append(InChallengeGameID, challenge.ID) - variant := challenge.Variant.Name - opp := challenge.Challenger.Name + variant := cv.Escape(challenge.Variant.Name) + opp := cv.Escape(challenge.Challenger.Name) oppRating := challenge.Challenger.Rating - perf := caser.String(challenge.Perf.Name) + perf := cv.Escape(caser.String(challenge.Perf.Name)) listString := fmt.Sprintf("%v challenge from %v", perf, opp) if oppRating > 0 { listString += fmt.Sprintf(" (%v) ", oppRating) @@ -357,9 +408,9 @@ func (c *Challenges) UpdateList() { } else { text += " • Casual • " } - text += fmt.Sprintf("%v plays %v", challenge.Challenger.Name, challenge.Color) + text += fmt.Sprintf("%v plays %v", cv.Escape(challenge.Challenger.Name), cv.Escape(challenge.Color)) item.SetSecondaryText(text) - item.SetShortcut(rune('a' + i)) + item.SetShortcut(numberKey(i)) c.In.AddItem(item) } for i, challenge := range Root.User.OutgoingChallenges { @@ -368,7 +419,7 @@ func (c *Challenges) UpdateList() { } OutChallengeGameID = append(OutChallengeGameID, challenge.ID) variant := challenge.Variant.Name - opp := challenge.DestUser.Name + opp := cv.Escape(challenge.DestUser.Name) oppRating := challenge.DestUser.Rating perf := caser.String(challenge.Perf.Name) listString := fmt.Sprintf("%v challenge to %v", perf, opp) @@ -385,13 +436,8 @@ func (c *Challenges) UpdateList() { } text += fmt.Sprintf("%v plays %v", challenge.Challenger.Name, challenge.Color) item.SetSecondaryText(text) - item.SetShortcut(rune('a' + i)) + item.SetShortcut(numberKey(i)) c.Out.AddItem(item) } } - -func (pg *OnlinePostGame) UpdateResult() { - pg.Result.SetText(Root.gameState.Status) - Root.gameState.Status = "" -} diff --git a/pkg/ui_update_shared.go b/pkg/ui_update_shared.go index 88b9b00..a80aad8 100644 --- a/pkg/ui_update_shared.go +++ b/pkg/ui_update_shared.go @@ -2,174 +2,75 @@ package pkg import ( "fmt" - "log" - "os" - "strconv" - "unicode" + "strings" - cv "code.rocketnine.space/tslocum/cview" - tc "github.com/gdamore/tcell/v3" + cv "codeberg.org/tslocum/cview" "github.com/notnil/chess" ) func DrawMoveHistory(win *cv.TextView) { - var text string - moveArr := Root.gameState.MoveHistoryArray - if moveArr == nil { - return - } - pieceArr, err := GetPieceArr(moveArr) - if err != nil { - text += fmt.Sprintf("%v", err) - return - } - if pieceArr == nil { - return - } - for i := len(moveArr) - 1; i >= 0; i-- { - move := moveArr[i] - text += fmt.Sprintf("\t%v: %v %v", i, pieceArr[i], move) - if i%2 == 0 { - text += " ⬜\n" - } else { - text += " ⬛\n" - } - } - win.SetText(text) + win.SetText(moveListText(Root.gameState.Game)) + win.ScrollToEnd() } -func DrawBoard(table *cv.Table, white bool) { - var FEN string - if white { - FEN = Root.gameState.Game.Position().String() - for i := 0; i < 8; i++ { - rank := cv.NewTableCell(fmt.Sprintf("%v", i+1)) - file := cv.NewTableCell(string(rune('a' + i))) - rank.SetAlign(cv.AlignRight) - file.SetAlign(cv.AlignRight) - rank.SetSelectable(false) - file.SetSelectable(false) - table.SetCell(8-i, 0, rank) - table.SetCell(8-i, 9, rank) - table.SetCell(0, i+1, file) - table.SetCell(9, i+1, file) - } - } else { - FEN = Root.gameState.Game.Position().Board().Flip(chess.UpDown).Flip(chess.LeftRight).String() - for i := 0; i < 8; i++ { - rank := cv.NewTableCell(fmt.Sprintf("%v", 8-i)) - file := cv.NewTableCell(string(rune('h' - i))) - rank.SetAlign(cv.AlignRight) - file.SetAlign(cv.AlignRight) - rank.SetSelectable(false) - file.SetSelectable(false) - table.SetCell(8-i, 0, rank) - table.SetCell(8-i, 9, rank) - table.SetCell(0, i+1, file) - table.SetCell(9, i+1, file) - } - } - - empty := cv.NewTableCell(EmptyChar) - empty.SetSelectable(false) - empty.SetTextColor(tc.ColorBlack.TrueColor()) - table.SetCell(0, 0, empty) - table.SetCell(0, 9, empty) - table.SetCell(9, 0, empty) - table.SetCell(9, 9, empty) - - //loop through current FEN and print to board - square := 0 - col, row := 1, 1 - for _, current_piece := range FEN { //loop to parse the FEN string - - if current_piece == ' ' { - break - } else if current_piece == '/' { - col = 1 - row++ - square++ - continue - } else if unicode.IsDigit(current_piece) { //nothing - int_, _ := strconv.Atoi(string(current_piece)) - for i := 1; i <= int_; i++ { - cell := cv.NewTableCell(EmptyChar) - cell.SetSelectable(true) - cell.SetAlign(cv.AlignRight) +// moveListText is a game's moves in standard notation, numbered in pairs. +func moveListText(game *chess.Game) string { + return moveListFrom(game.Positions(), game.Moves(), nil) +} - if square%2 == 0 { - cell.SetTextColor(tc.NewRGBColor(145, 130, 109)) - cell.SetBackgroundColor(tc.NewRGBColor(145, 130, 109)) - } else { - cell.SetTextColor(tc.NewRGBColor(108, 81, 59)) - cell.SetBackgroundColor(tc.NewRGBColor(108, 81, 59)) - } - table.SetCell(row, col, cell) - col++ - square++ - } - if col > 8 { - col = 1 - } - continue - } else if !unicode.IsDigit(current_piece) { - cell := cv.NewTableCell(PiecesMap[unicode.ToLower(current_piece)] + " ") - cell.SetSelectable(true) - cell.SetAlign(cv.AlignRight) - if unicode.IsUpper(current_piece) { - cell.SetTextColor(tc.NewRGBColor(255, 248, 220)) - } else { - cell.SetTextColor(tc.NewRGBColor(18, 18, 18)) - } - if square%2 == 0 { - cell.SetBackgroundColor(tc.NewRGBColor(145, 130, 109)) - } else { - cell.SetBackgroundColor(tc.NewRGBColor(108, 81, 59)) - } - table.SetCell(row, col, cell) - square++ - col++ +// moveListFrom is moveListText for positions and moves, with an optional +// mark after each move (a coloured ?! from the analysis): marks[i] is shown +// after move i+1, as text and its visible width. +func moveListFrom(positions []*chess.Position, moves []*chess.Move, marks []moveMark) string { + var text strings.Builder + text.WriteString("[::b]Moves[::-]\n") + for i, m := range moves { + san := chess.AlgebraicNotation{}.Encode(positions[i], m) + width := len([]rune(san)) + // each move is a region, m, so it can be clicked (linkMoveList) + tagged := fmt.Sprintf(`["m%d"]%s[""]`, i+1, san) + if i < len(marks) && marks[i].width > 0 { + tagged += marks[i].text + width += marks[i].width + } + if positions[i].Turn() == chess.White { + fmt.Fprintf(&text, "%3d. %s%s", moveNumber(positions[i]), tagged, strings.Repeat(" ", max(1, 8-width))) } else { - log.Fatal("error parsing starting FEN") + if i == 0 { // game started with black to move + fmt.Fprintf(&text, "%3d. %-8s", moveNumber(positions[0]), "…") + } + text.WriteString(tagged + "\n") } } + return text.String() +} - //check if piece is selected - if !LastSelectedCell.Empty { - FEN = Root.gameState.Game.Position().String() - fen, err := chess.FEN(FEN) - if err != nil { - log.Fatal(err) - os.Exit(10) - } - NewChessGame = chess.NewGame(fen) - destArr := []string{} - for _, m := range NewChessGame.ValidMoves() { - move := m.String() - if move[0:2] == LastSelectedCell.Alg { - destArr = append(destArr, move[2:]) - - } - - } - for _, d := range destArr { - r, c := translateAlgtoCell(d, white) - cell := table.GetCell(r, c) - if cell.GetText() == EmptyChar { - if white { - cell.SetTextColor(tc.NewRGBColor(255, 248, 220)) - } else { - cell.SetTextColor(tc.NewRGBColor(18, 18, 18)) - } - cell.SetText("•") - } else { - t := cell.GetText() - cell.SetAttributes(tc.AttrItalic | tc.AttrBlink) - cell.SetText(t) - } +// moveMark is something shown after a move in the move list. +type moveMark struct { + text string + width int +} - } +// moveNumber is a position's full move number (the FEN's last field). +func moveNumber(pos *chess.Position) int { + n := 1 + if f := strings.Fields(pos.String()); len(f) == 6 { + fmt.Sscan(f[5], &n) } + return n +} - Root.App.QueueUpdateDraw(func() {}, table) +// DrawBoard shows the current game position on a board, with white at the +// bottom if white is true, and highlights the last move played. +func DrawBoard(board *BoardView, white bool) { + game := Root.gameState.Game + board.SetPosition(game.Position(), white) + board.SetHistory(game.Positions(), game.Moves()) + from, to := chess.NoSquare, chess.NoSquare + if moves := game.Moves(); len(moves) > 0 { + last := moves[len(moves)-1] + from, to = last.S1(), last.S2() + } + board.SetLastMove(from, to) + Root.App.QueueUpdateDraw(func() {}) // full draw, so big pieces are flushed too } diff --git a/pkg/util.go b/pkg/util.go index ed083f5..716f24c 100644 --- a/pkg/util.go +++ b/pkg/util.go @@ -2,16 +2,9 @@ package pkg import ( "fmt" - "log" "math/rand" - "os" - "strconv" "strings" - "time" - "unicode" - cv "code.rocketnine.space/tslocum/cview" - tc "github.com/gdamore/tcell/v3" "github.com/notnil/chess" ) @@ -24,30 +17,9 @@ func contains(s []string, str string) bool { return false } +// GetRandomQuote picks one of the quotes (keys 0..n-1) at random. func GetRandomQuote() string { - rand.Seed(time.Now().UnixNano()) - minrand := 0 - maxrand := 56 - rand_quote_int := rand.Intn(maxrand-minrand+1) + minrand - var rand_quote string = RandQuoteMap[rand_quote_int] - return rand_quote -} - -//writes to a local text file -func WriteLocal(title string, payload string) { - f, err := os.Create(fmt.Sprintf("%s.txt", title)) - - if err != nil { - log.Fatal(err) - } - - defer f.Close() - - _, err2 := f.WriteString(payload) - - if err2 != nil { - log.Fatal(err2) - } + return RandQuoteMap[rand.Intn(len(RandQuoteMap))] } func timeFormat(time int64) string { @@ -76,34 +48,6 @@ func timeFormat(time int64) string { } } -func translateSelectedCell(row, col int, white bool) string { - var rank string - var file string - if white { - rank = fmt.Sprintf("%v", 8-(row-1)) - file = string(rune('a' + (col - 1))) - } else { - rank = fmt.Sprintf("%v", (row)) - file = string(rune('h' - (col - 1))) - } - return file + rank -} - -func translateAlgtoCell(alg string, white bool) (r, c int) { - file := alg[0] - rank := alg[1] - var row int - var col int - if white { - row = -int(rank) + 57 - col = int(file) - 96 - } else { - row = int(rank) - 48 - col = -int(file) + 105 - } - return row, col -} - func GetPiece(p string, g *chess.Game) chess.Piece { getFile := map[string]chess.File{ "a": chess.FileA, @@ -195,99 +139,16 @@ func GetMoveType(movestr string, g *chess.Game) (*chess.Move, error) { return new(chess.Move), fmt.Errorf("unable to decode move string") } -func FENtoBoard(table *cv.Table, FEN string, white bool) { - if white { - for i := 0; i < 8; i++ { - rank := cv.NewTableCell(fmt.Sprintf("%v", i+1)) - file := cv.NewTableCell(string(rune('a' + i))) - rank.SetAlign(cv.AlignRight) - file.SetAlign(cv.AlignRight) - rank.SetSelectable(false) - file.SetSelectable(false) - table.SetCell(8-i, 0, rank) - table.SetCell(8-i, 9, rank) - table.SetCell(0, i+1, file) - table.SetCell(9, i+1, file) - } - } else { - for i := 0; i < 8; i++ { - rank := cv.NewTableCell(fmt.Sprintf("%v", 8-i)) - file := cv.NewTableCell(string(rune('h' - i))) - rank.SetAlign(cv.AlignRight) - file.SetAlign(cv.AlignRight) - rank.SetSelectable(false) - file.SetSelectable(false) - table.SetCell(8-i, 0, rank) - table.SetCell(8-i, 9, rank) - table.SetCell(0, i+1, file) - table.SetCell(9, i+1, file) - } - } - - empty := cv.NewTableCell(EmptyChar) - empty.SetSelectable(false) - empty.SetTextColor(tc.ColorBlack.TrueColor()) - table.SetCell(0, 0, empty) - table.SetCell(0, 9, empty) - table.SetCell(9, 0, empty) - table.SetCell(9, 9, empty) - - //loop through current FEN and print to board - square := 0 - col, row := 1, 1 - for _, current_piece := range FEN { //loop to parse the FEN string - - if current_piece == ' ' { - break - } else if current_piece == '/' { - col = 1 - row++ - square++ - continue - } else if unicode.IsDigit(current_piece) { //nothing - int_, _ := strconv.Atoi(string(current_piece)) - for i := 1; i <= int_; i++ { - cell := cv.NewTableCell(EmptyChar) - cell.SetSelectable(true) - cell.SetAlign(cv.AlignRight) - - if square%2 == 0 { - cell.SetTextColor(tc.NewRGBColor(145, 130, 109)) - cell.SetBackgroundColor(tc.NewRGBColor(145, 130, 109)) - } else { - cell.SetTextColor(tc.NewRGBColor(108, 81, 59)) - cell.SetBackgroundColor(tc.NewRGBColor(108, 81, 59)) - } - table.SetCell(row, col, cell) - col++ - square++ - } - if col > 8 { - col = 1 - } - continue - } else if !unicode.IsDigit(current_piece) { - cell := cv.NewTableCell(PiecesMap[unicode.ToLower(current_piece)] + " ") - cell.SetSelectable(true) - cell.SetAlign(cv.AlignRight) - if unicode.IsUpper(current_piece) { - cell.SetTextColor(tc.NewRGBColor(255, 248, 220)) - } else { - cell.SetTextColor(tc.NewRGBColor(18, 18, 18)) - } - if square%2 == 0 { - cell.SetBackgroundColor(tc.NewRGBColor(145, 130, 109)) - } else { - cell.SetBackgroundColor(tc.NewRGBColor(108, 81, 59)) - } - table.SetCell(row, col, cell) - square++ - col++ - } else { - log.Fatal("error parsing starting FEN") - } +// FENtoBoard shows a position given as FEN on a board (used for previews). +func FENtoBoard(board *BoardView, FEN string, white bool) { + opt, err := chess.FEN(FEN) + if err != nil { + return } - Root.App.QueueUpdateDraw(func() {}, table) + board.SetPosition(chess.NewGame(opt).Position(), white) + board.SetLastMove(chess.NoSquare, chess.NoSquare) + board.ClearSelection() + Root.App.QueueUpdateDraw(func() {}) // full draw, so big pieces are flushed too } // func containedInOngoingGames(a []api.OngoingGameInfo, gameid string) bool { @@ -298,3 +159,50 @@ func FENtoBoard(table *cv.Table, FEN string, white bool) { // } // return false // } + +// parseMoveInput turns a typed move into UCI. It accepts UCI ("e2e4", +// "e7e8q"), UCI with a promotion marker ("e7e8=N", "e7e8N"), standard +// algebraic notation ("Nf3", "exd5", "e8=Q", "O-O", "0-0") and long algebraic +// ("Ng1f3"). Only legal moves are returned. +func parseMoveInput(g *chess.Game, in string) (string, error) { + in = strings.TrimSpace(in) + if in == "" { + return "", fmt.Errorf("empty move") + } + pos := g.Position() + legal := map[string]bool{} + for _, m := range g.ValidMoves() { + legal[chess.UCINotation{}.Encode(pos, m)] = true + } + try := func(n chess.Notation, s string) (string, bool) { + m, err := n.Decode(pos, s) + if err != nil { + return "", false + } + uci := chess.UCINotation{}.Encode(pos, m) + return uci, legal[uci] + } + uciForm := strings.ToLower(strings.NewReplacer("=", "", "-", "", "+", "", "#", "", " ", "").Replace(in)) + if uci, ok := try(chess.UCINotation{}, uciForm); ok { + return uci, nil + } + san := strings.NewReplacer("0-0-0", "O-O-O", "0-0", "O-O").Replace(in) + for _, n := range []chess.Notation{chess.AlgebraicNotation{}, chess.LongAlgebraicNotation{}} { + if uci, ok := try(n, san); ok { + return uci, nil + } + } + return "", fmt.Errorf("not a legal move: %s", in) +} + +// invalidMoveHint explains why a typed move was rejected, with a nudge for the +// common case of a promotion typed without its piece. +// It also plays the error sound, since it's shown for every rejected move. +func invalidMoveHint(move string) string { + playSound(soundError) + m := strings.ToLower(strings.TrimSpace(move)) + if len(m) == 4 && contains(Root.gameState.LegalMoves, m+"q") { + return fmt.Sprintf("[yellow]%s is a promotion: add the piece, e.g. %s=Q (Q, R, B or N).[white]\n", move, move) + } + return fmt.Sprintf("[red]%q isn't a legal move.[white] Try e2e4, Nf3 or e8=Q.\n", move) +} diff --git a/pkg/watch.go b/pkg/watch.go new file mode 100644 index 0000000..8d39db1 --- /dev/null +++ b/pkg/watch.go @@ -0,0 +1,619 @@ +package pkg + +import ( + "context" + "fmt" + "strings" + "time" + + cv "codeberg.org/tslocum/cview" + tc "github.com/gdamore/tcell/v3" + "github.com/nate-xyz/chess-cli/api" + "github.com/notnil/chess" +) + +// Watching games: Lichess TV channels, a player's current game, or a game by +// link/ID. The board follows the game live; history stepping and drawing +// work as in games. + +type WatchScreen struct { + Board *BoardView + Side *cv.Flex + Top *cv.TextView // player at the top of the board, and their clock + TopClock *cv.TextView // clocks as text, when the clock bar is off + BotClock *cv.TextView + Status *cv.TextView + Result *cv.TextView // the result, right beside the board, once it's over + History *cv.TextView + Bottom *cv.TextView + List *cv.List + + cancel context.CancelFunc + gen int + title string // what's being watched + tv string // TV channel key, if watching TV + game *api.WatchGame + chess *chess.Game // the game as followed (history from when we joined, or all of it) + white bool // white at the bottom + clockW int // seconds, as of clockAt; -1 = unknown + clockB int + clockAt time.Time + clockMax int // seconds each side started with (or the most seen, until known) + tc string // time control, e.g. "3+2", once known + over string +} + +func (ws *WatchScreen) Init() cv.Primitive { + ws.Board = NewBoardView(func(chess.Square) {}) // clicks: drawing and history only + ws.Board.viewOnly = true + ws.Board.EnableSounds() + ws.Top = textBox(cv.AlignLeft) + ws.TopClock = textBox(cv.AlignLeft) + ws.BotClock = textBox(cv.AlignLeft) + ws.Status = textBox(cv.AlignLeft) + ws.Result = textBox(cv.AlignRight) + ws.History = textBox(cv.AlignLeft) + linkMoveList(ws.History, ws.Board) + ws.Bottom = textBox(cv.AlignLeft) + ws.List = menuList() + ws.List.AddItem(menuItem("Flip board", 'f', ws.flip)) + ws.List.AddItem(menuItem("Leave", 'x', ws.leave)) + + side := cv.NewFlex() + side.SetDirection(cv.FlexRow) + side.AddItem(ws.Top, 1, 0, false) + side.AddItem(ws.TopClock, 0, 0, false) + side.AddItem(ws.Status, 0, 1, false) + side.AddItem(ws.Result, 0, 0, false) + side.AddItem(ws.History, 0, 2, false) + side.AddItem(ws.List, 2, 0, false) + side.AddItem(ws.BotClock, 0, 0, false) + side.AddItem(ws.Bottom, 1, 0, false) + ws.Side = side + + ws.Board.SetTabFunc(func() { Root.App.SetFocus(ws.List) }) + ws.List.SetInputCapture(func(event *tc.EventKey) *tc.EventKey { + if event.Key() == tc.KeyTab || event.Key() == tc.KeyEscape { + Root.App.SetFocus(ws.Board) + return nil + } + return event + }) + go ws.ticker() + registerMenus("watch", false, ws.List) + return newGameLayout(ws.Board, side, " chess-cli · watching │ scroll or [ ] to step through moves │ right-drag to draw │ f flip │ Tab menu │ Ctrl-C quit") +} + +// start stops whatever was being watched and resets the screen. +func (ws *WatchScreen) start(title string) context.Context { + if ws.cancel != nil { + ws.cancel() + } + ws.gen++ + ctx, cancel := context.WithCancel(context.Background()) + ws.cancel = cancel + ws.title, ws.tv, ws.game, ws.chess, ws.over = title, "", nil, nil, "" + ws.clockW, ws.clockB, ws.clockMax, ws.tc = -1, -1, 0, "" + ws.Board.HideClockBars() + ws.white = true + ws.Top.SetText("") + ws.Bottom.SetText("") + ws.History.SetText("") + ws.showResult(chess.NoColor, "") + ws.Board.SetPosition(chess.StartingPosition(), true) + ws.Board.SetHistory(nil, nil) + ws.Board.SetLastMove(chess.NoSquare, chess.NoSquare) + ws.setStatus("[#a0a0a0]Connecting…[-]") + Root.Switch("watch") + return ctx +} + +func (ws *WatchScreen) leave() { + if ws.cancel != nil { + ws.cancel() + ws.cancel = nil + } + gotoWelcome() +} + +func (ws *WatchScreen) flip() { + ws.white = !ws.white + ws.redraw() +} + +// WatchTv follows a TV channel; when its game ends, TV moves on to the next. +func WatchTv(key, name string) { + ws := Root.watch + ctx := ws.start("Lichess TV · " + name) + ws.tv = key + gen := ws.gen + go func() { + for ctx.Err() == nil { + err := api.StreamTv(ctx, key, func(u api.WatchUpdate) { ws.post(gen, u) }) + if ctx.Err() != nil { + return + } + msg := "[yellow]Connection lost, reconnecting…[-]" + if err != nil { + msg = fmt.Sprintf("[yellow]%v; reconnecting…[-]", err) + } + Root.App.QueueUpdateDraw(func() { + if gen == ws.gen { + ws.setStatus(msg) + } + }) + select { + case <-ctx.Done(): + case <-time.After(3 * time.Second): + } + } + }() +} + +// WatchGameByID follows one game (from a link or ID, or a player's current +// game when player is set). +func WatchGameByID(id, player string) { + ws := Root.watch + title := "Game " + id + if player != "" { + title = player + "'s game" + } + ctx := ws.start(title) + gen := ws.gen + go func() { + var g *api.WatchGame + var err error + if player != "" { + g, err = api.GetCurrentGame(player) + } else { + g, err = api.GetGame(id) + } + if err != nil { + Root.App.QueueUpdateDraw(func() { + if gen == ws.gen { + ws.setStatus(fmt.Sprintf("[red]Couldn't find the game: %v[-]", err)) + } + }) + return + } + ws.post(gen, api.WatchUpdate{Game: g, WhiteClock: -1, BlackClock: -1}) + err = api.StreamGame(ctx, g.ID, func(u api.WatchUpdate) { ws.post(gen, u) }) + if ctx.Err() == nil && err != nil { + Root.App.QueueUpdateDraw(func() { + if gen == ws.gen && ws.over == "" { + ws.setStatus(fmt.Sprintf("[yellow]Stream ended: %v[-]", err)) + } + }) + } + }() +} + +// post hands an update to the UI goroutine, unless something else is being +// watched by then. +func (ws *WatchScreen) post(gen int, u api.WatchUpdate) { + Root.App.QueueUpdateDraw(func() { + if gen == ws.gen { + ws.apply(u) + } + }) +} + +func (ws *WatchScreen) apply(u api.WatchUpdate) { + if u.Game != nil { + ws.newGame(u.Game) + } + if u.FEN != "" { + ws.follow(u.FEN, u.LastMove) + } + if u.WhiteClock >= 0 || u.BlackClock >= 0 { + ws.clockW, ws.clockB, ws.clockAt = u.WhiteClock, u.BlackClock, time.Now() + ws.clockMax = max(ws.clockMax, u.WhiteClock, u.BlackClock) + } + if u.Status != "" { + ws.over = gameOverText(u.Status, u.Winner) + } + ws.updateInfo() + ws.redraw() + // the result: from Lichess, or seen on the board (TV doesn't send results) + switch { + case u.Status != "" && u.Status != "aborted" && u.Status != "noStart": + ws.showResult(colorFromName(u.Winner), u.Status) + case ws.chess != nil && ws.chess.Outcome() != chess.NoOutcome && ws.over == "": + winner, method := winnerOf(ws.chess.Outcome()), gameMethod(ws.chess) + ws.over = strings.SplitN(strings.TrimPrefix(resultText(winner, method), "[::b]"), "\n", 2)[1] + ws.updateInfo() + ws.showResult(winner, method) + case u.Game != nil && ws.over == "": + ws.showResult(chess.NoColor, "") // a new game + } +} + +// showResult puts the result beside the board and on the kings; method "" +// clears it. +func (ws *WatchScreen) showResult(winner chess.Color, method string) { + if method == "" { + ws.Result.SetText("") + ws.Side.ResizeItem(ws.Result, 0, 0) + return + } + ws.Result.SetText(resultText(winner, method)) + ws.Side.ResizeItem(ws.Result, 3, 0) + ws.Board.SetResult(winner, method) +} + +// newGame starts following a game, replaying its moves if they're known. +func (ws *WatchScreen) newGame(g *api.WatchGame) { + same := ws.game != nil && ws.game.ID == g.ID + if !same { + ws.clockMax = 0 + } + ws.game, ws.over = g, "" + if !same { + ws.tc = "" + } + if g.ClockInitial > 0 { + ws.clockMax = g.ClockInitial + } + if g.ClockInitial > 0 || g.ClockIncrement > 0 || g.DaysPerTurn > 0 || g.Speed != "" { + ws.tc = timeControlText(g.ClockInitial, g.ClockIncrement, g.Speed, g.DaysPerTurn) + } + if same && ws.chess != nil { + return + } + ws.white = g.Orientation != "black" + ws.chess = nil + if g.Moves != "" || g.InitialFEN != "" { + game, err := gameFromSAN(g.InitialFEN, g.Moves) + if err == nil { + ws.chess = game + } + } else if ws.tv != "" { + go ws.fetchEarlierMoves(ws.gen, g.ID) + } +} + +// fetchEarlierMoves fills in a TV game's moves from before we joined. TV +// only sends positions, and Lichess's export of an ongoing game runs a few +// moves behind, so it retries until the export reaches a position we've +// seen live, then joins the two. +func (ws *WatchScreen) fetchEarlierMoves(gen int, id string) { + for try := 0; try < 18; try++ { + if try > 0 { + time.Sleep(10 * time.Second) + } + g, err := api.GetGame(id) + if err != nil { + continue + } + earlier, err := gameFromSAN(g.InitialFEN, g.Moves) + if err != nil { + return + } + if g.ClockInitial > 0 { + Root.App.QueueUpdateDraw(func() { + if gen == ws.gen && ws.game != nil && ws.game.ID == id { + ws.clockMax = g.ClockInitial // for the clock bars + ws.tc = timeControlText(g.ClockInitial, g.ClockIncrement, g.Speed, g.DaysPerTurn) + ws.updateInfo() + } + }) + } + done := make(chan bool, 1) + Root.App.QueueUpdateDraw(func() { + if gen != ws.gen || ws.game == nil || ws.game.ID != id { + done <- true // watching something else now + return + } + if ws.chess == nil { + done <- false + return + } + if merged := joinGames(earlier, ws.chess); merged != nil { + ws.chess = merged + ws.redraw() + done <- true + return + } + done <- false + }) + if <-done { + return + } + } +} + +// joinGames combines an earlier record of a game (from the start) with the +// game as followed live (from when we joined): it finds the latest live +// position the earlier record reaches and continues from there with the live +// moves. Returns nil if they don't meet. +func joinGames(earlier, live *chess.Game) *chess.Game { + key := func(p *chess.Position) string { + f := strings.Fields(p.String()) + return f[0] + " " + f[1] + } + at := map[string]int{} + for i, p := range earlier.Positions() { + at[key(p)] = i + } + livePos, liveMoves := live.Positions(), live.Moves() + for j := len(livePos) - 1; j >= 0; j-- { + k, ok := at[key(livePos[j])] + if !ok { + continue + } + // replay the earlier record up to k, then the live moves after j + game := chess.NewGame() + if start := earlier.Positions()[0]; key(start) != key(chess.StartingPosition()) { + if fen, err := chess.FEN(start.String()); err == nil { + game = chess.NewGame(fen) + } + } + for _, m := range earlier.Moves()[:k] { + if game.Move(m) != nil { + return nil + } + } + for i, m := range liveMoves[j:] { + uci := chess.UCINotation{}.Encode(livePos[j+i], m) + next, err := chess.UCINotation{}.Decode(game.Position(), uci) + if err != nil || game.Move(next) != nil { + return nil + } + } + return game + } + return nil +} + +// gameFromSAN replays SAN moves from a start position ("" or "startpos" for +// the usual one). +func gameFromSAN(initialFEN, moves string) (*chess.Game, error) { + game := chess.NewGame() + if initialFEN != "" && initialFEN != "startpos" { + fen, err := chess.FEN(initialFEN) + if err != nil { + return nil, err + } + game = chess.NewGame(fen) + } + for _, san := range strings.Fields(moves) { + if err := game.MoveStr(san); err != nil { + return nil, err + } + } + return game, nil +} + +// follow moves the game on to a new position: by playing the last move if +// it leads there, otherwise starting over from the position. +func (ws *WatchScreen) follow(fen, lm string) { + full := completeFEN(fen, lm) + if ws.chess != nil { + if samePlacement(ws.chess.Position(), full) { + return + } + if lm != "" { + if m, err := (chess.UCINotation{}).Decode(ws.chess.Position(), lm); err == nil { + next := ws.chess.Clone() + if next.Move(m) == nil && samePlacement(next.Position(), full) { + ws.chess = next + return + } + } + } + } + f, err := chess.FEN(full) + if err != nil { + ws.setStatus("[red]Can't show this position (variant?)[-]") + return + } + ws.chess = chess.NewGame(f) +} + +// samePlacement compares the piece placement of a position and a FEN. +func samePlacement(pos *chess.Position, fen string) bool { + a, b := strings.Fields(pos.String()), strings.Fields(fen) + return len(a) > 0 && len(b) > 0 && a[0] == b[0] +} + +// completeFEN fills in a FEN that has only the board (and maybe the side +// to move): the side to move is the one that didn't just move the piece now +// on the last move's destination square. +func completeFEN(fen, lm string) string { + f := strings.Fields(fen) + if len(f) >= 6 { + return fen + } + if len(f) == 2 { + return f[0] + " " + f[1] + " - - 0 1" + } + turn := "w" + if len(lm) >= 4 { + if pos, err := chess.FEN(f[0] + " w - - 0 1"); err == nil { + game := chess.NewGame(pos) + dest := chess.Square(int(lm[3]-'1')*8 + int(lm[2]-'a')) + if p := game.Position().Board().Piece(dest); p != chess.NoPiece && p.Color() == chess.White { + turn = "b" + } + } + } + return f[0] + " " + turn + " - - 0 1" +} + +func gameOverText(status, winner string) string { + text := map[string]string{ + "mate": "Checkmate", "resign": "Resignation", "stalemate": "Stalemate", "timeout": "Time out", + "draw": "Draw", "outoftime": "Time out", "aborted": "Aborted", "noStart": "Didn't start", + "cheat": "Cheat detected", "variantEnd": "Variant ending", + }[status] + if text == "" { + text = status + } + switch winner { + case "white": + text += " · White wins" + case "black": + text += " · Black wins" + } + return text +} + +func (ws *WatchScreen) setStatus(s string) { ws.Status.SetText(s) } + +func (ws *WatchScreen) updateInfo() { + g := ws.game + if g == nil { + return + } + if zenMode() { // just the result, if any + status := "" + if ws.over != "" { + status = "[yellow]" + ws.over + "[-]" + } + ws.setStatus(status) + ws.updatePlayers() + return + } + status := "[::b]" + cv.Escape(ws.title) + "[::-]\n" + if ws.tc != "" && !clockBarsOn() { + status += ws.tc + " · " + } + if g.Speed != "" { + rated := "casual" + if g.Rated { + rated = "rated" + } + status += fmt.Sprintf("%s · %s · ", caser.String(g.Speed), rated) + } + status += "[#a0a0a0]lichess.org/" + g.ID + "[-]\n" + if ws.tv == "" { + status += "[#a0a0a0]Lichess shows ongoing games 3 moves behind.[-]\n" + } + if ws.over != "" { + status += "\n[yellow]" + ws.over + "[-]" + if ws.tv != "" { + status += "\n[#a0a0a0]TV will switch to the next game.[-]" + } + } + ws.setStatus(status) + ws.updatePlayers() +} + +func (ws *WatchScreen) updatePlayers() { + g := ws.game + if g == nil { + return + } + name := func(p api.WatchPlayer, c string) string { + if zenMode() { + if c == "[::b]○[::-] " { + return c + "White" + } + return c + "Black" + } + s := cv.Escape(p.Name) + if p.Title != "" { + s = "[yellow]" + p.Title + "[-] " + s + } + if p.Rating > 0 { + s += fmt.Sprintf(" [#a0a0a0](%d)[-]", p.Rating) + } + return c + s + } + white, black := name(g.White, "[::b]○[::-] "), name(g.Black, "[::b]●[::-] ") + if ws.white { + ws.Top.SetText(black) + ws.Bottom.SetText(white) + } else { + ws.Top.SetText(white) + ws.Bottom.SetText(black) + } + ws.updateClocks() +} + +// updateClocks shows the clocks beside the board (time and bar), counting +// down the side to move. +func (ws *WatchScreen) updateClocks() { + if ws.clockW < 0 && ws.clockB < 0 { + ws.Board.HideClockBars() + return + } + w, b := ws.clockW, ws.clockB + // clocks run once both sides have moved (joining mid-game, they have) + running := ws.over == "" && ws.chess != nil && + (len(ws.chess.Moves()) >= 2 || moveNumber(ws.chess.Positions()[0]) > 1) + whiteToMove := ws.chess != nil && ws.chess.Position().Turn() == chess.White + if running { + gone := int(time.Since(ws.clockAt).Seconds()) + if whiteToMove { + w = max(0, w-gone) + } else { + b = max(0, b-gone) + } + } + frac := func(s int) float64 { + if ws.clockMax <= 0 { + return -1 + } + return float64(s) / float64(ws.clockMax) + } + wc := clockBar{label: clockLabel(w), frac: frac(w), active: running && whiteToMove} + bc := clockBar{label: clockLabel(b), frac: frac(b), active: running && !whiteToMove} + top, bottom := bc, wc + if !ws.white { + top, bottom = wc, bc + } + if !clockBarsOn() { // plain text in the sidebar instead + ws.Board.HideClockBars() + text := func(c clockBar) string { + if c.active { + return "[black:#c8c8c8] " + c.label + " [-:-]" + } + return " " + c.label + } + ws.TopClock.SetText(text(top)) + ws.BotClock.SetText(text(bottom)) + return + } + top.right, bottom.right = ws.tc, ws.tc + ws.Board.SetClockBars(top, bottom) +} + +func (ws *WatchScreen) redraw() { + if ws.chess == nil { + return + } + ws.Board.SetPosition(ws.chess.Position(), ws.white) + ws.Board.SetHistory(ws.chess.Positions(), ws.chess.Moves()) + from, to := chess.NoSquare, chess.NoSquare + if moves := ws.chess.Moves(); len(moves) > 0 { + last := moves[len(moves)-1] + from, to = last.S1(), last.S2() + } + ws.Board.SetLastMove(from, to) + ws.History.SetText(moveListText(ws.chess)) + ws.History.ScrollToEnd() + ws.updatePlayers() +} + +// ticker redraws the running clock every second. +func (ws *WatchScreen) ticker() { + for range time.Tick(time.Second) { + if !showing("watch") { + continue + } + Root.App.QueueUpdateDraw(func() { + if name, _ := Root.nav.GetFrontPanel(); name == "watch" { + ws.updateClocks() + } + }) + } +} + +func askWatch(mode string) { + if mode == "player" { + askText("Whose game?", "Lichess username: ", func(text string) { WatchGameByID("", text) }) + } else { + askText("Which game?", "Link or ID: ", func(text string) { WatchGameByID(api.GameIDFrom(text), "") }) + } +} diff --git a/pkg/watch_test.go b/pkg/watch_test.go new file mode 100644 index 0000000..611c73d --- /dev/null +++ b/pkg/watch_test.go @@ -0,0 +1,58 @@ +package pkg + +import ( + "testing" + + "github.com/nate-xyz/chess-cli/api" + "github.com/notnil/chess" +) + +func TestJoinGames(t *testing.T) { + // the export knows 1. e4 e5 2. Nf3; we joined live after 1. e4 e5 and saw Nf3 Nc6 Bc4 + earlier, _ := gameFromSAN("", "e4 e5 Nf3") + joined, _ := gameFromSAN("", "e4 e5") + fen, _ := chess.FEN(joined.Position().String()) + live := chess.NewGame(fen) + for _, san := range []string{"Nf3", "Nc6", "Bc4"} { + if err := live.MoveStr(san); err != nil { + t.Fatal(err) + } + } + got := joinGames(earlier, live) + if got == nil || len(got.Moves()) != 5 { + t.Fatalf("joined game: %v", got) + } + if want, _ := gameFromSAN("", "e4 e5 Nf3 Nc6 Bc4"); got.Position().String() != want.Position().String() { + t.Errorf("got %s", got.Position()) + } + // an export that doesn't reach anything we saw: nothing to join yet + behind, _ := gameFromSAN("", "e4") + if joinGames(behind, live) != nil { + t.Error("joined games that don't meet") + } +} + +func TestGameIDFrom(t *testing.T) { + for in, want := range map[string]string{ + "q7ZvsdUF": "q7ZvsdUF", + "https://lichess.org/q7ZvsdUF": "q7ZvsdUF", + "https://lichess.org/q7ZvsdUFab12": "q7ZvsdUF", // player's view + "lichess.org/q7ZvsdUF/black#12": "q7ZvsdUF", + " https://lichess.org/q7ZvsdUF?x=1": "q7ZvsdUF", + } { + if got := api.GameIDFrom(in); got != want { + t.Errorf("GameIDFrom(%q) = %q, want %q", in, got, want) + } + } +} + +func TestCompleteFEN(t *testing.T) { + // after 1. e4 the pawn on e4 is white's, so black is to move + if got := completeFEN("rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR", "e2e4"); got != "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b - - 0 1" { + t.Errorf("got %q", got) + } + full := "2kr3r/pp3pp1/2p1pnp1/q1npP3/8/bP1P2P1/P1PNQPBP/BK1R3R b - - 0 15" + if got := completeFEN(full, "e4e5"); got != full { + t.Errorf("full FEN changed: %q", got) + } +} diff --git a/scripts/render-pieces.sh b/scripts/render-pieces.sh new file mode 100755 index 0000000..574f0e7 --- /dev/null +++ b/scripts/render-pieces.sh @@ -0,0 +1,10 @@ +#!/bin/sh +# Render the piece SVGs in pkg/assets/pieces/*/ to the PNGs chess-cli embeds. +# Needs Inkscape (and optionally optipng to shrink the results). +set -e +cd "$(dirname "$0")/../pkg/assets/pieces" +for svg in */*.svg; do + png="${svg%.svg}.png" + inkscape "$svg" --export-type=png --export-width=384 --export-height=384 --export-filename="$png" >/dev/null 2>&1 +done +if command -v optipng >/dev/null; then optipng -quiet -o2 */*.png; fi