feat(export): export dialog for PGN, FEN, SVG, PNG, LaTeX, PDF, HTML and ASCII
public
feat(export): export dialog for PGN, FEN, SVG, PNG, LaTeX, PDF, HTML and ASCII Board drawing moves into diagram.py (BoardPainter), so exported images match the board in the window. HTML is a single file with an SVG board and a clickable move list that opens at the exported position. PDF is rendered with Cairo, or via pdflatex/xskak when available. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| Changeset | 1c86dc9e9a1e10acc2de2d076ee8a2fc34a306a4 |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@nullachtvierzehn.de>, |
| Parents | e0b0611680a2 |
| Children | eddd4f2e0afc |
| Pushlog | by timo via ssh by timo via ssh |
modified README.md +12 −2
| @@ -62,6 +62,15 @@ Schlichtes GNOME-Schachprogramm (Python, | ||
| 62 | 62 | Brett). Eine `.pgn`-Datei aufs Brett ziehen geht genauso. Läuft im Fenster schon eine |
| 63 | 63 | Partie, öffnet sich ein neues. Fremde Partien zeigen die Namen und werden für beide |
| 64 | 64 | Seiten analysiert. Während einer Online-Partie ist Einfügen gesperrt. |
| 65 | +- **Exportieren** (Strg+Umschalt+S, Hauptmenü): ein Dialog für alle Formate – PGN, FEN, | |
| 66 | + SVG- und PNG-Bild, LaTeX (Paket `xskak`), PDF (direkt oder, wenn `pdflatex` da ist, über | |
| 67 | + LaTeX), HTML und ASCII-Art. Umfang: die gezeigte Stellung oder die ganze Partie. Zugzeichen, | |
| 68 | + Gewinnchance-Balken, Spielerköpfe, Markierung des letzten Zugs und Drehung sind schaltbar; | |
| 69 | + die Auswahl merkt sich das Programm. Bilder sehen aus wie das Brett im Fenster (Farben, | |
| 70 | + Figurensatz). Die HTML-Seite ist eine einzelne Datei: Brett als SVG, Zugliste zum | |
| 71 | + Durchklicken (Pfeiltasten, F dreht), sie öffnet bei der Stellung, die beim Export gezeigt | |
| 72 | + war, und die FEN markiert sich mit einem Klick. Alles außer PDF geht auch in die | |
| 73 | + Zwischenablage – Bilder als Bild, HTML als formatierter Text. | |
| 65 | 74 | - **Einstellungen** (Strg+,): Standardfarbe, Streuung von Maia, Brettfarben (Holz, |
| 66 | 75 | Schiefer, Grün), Notation (deutsch Sf3 oder englisch Nf3 – gilt für Zugliste und |
| 67 | 76 | Erklärungen; PGN-Dateien bleiben international), Figurensätze aus PyChess (`/usr/share/pychess/pieces`), Lichess-Konto. |
| @@ -72,6 +81,7 @@ Schlichtes GNOME-Schachprogramm (Python, | ||
| 72 | 81 | |
| 73 | 82 | Abhängigkeiten: `python-gobject`, `libadwaita`, `librsvg`, `python-chess`, |
| 74 | 83 | `stockfish`, `maia3-git` (AUR), `python-requests`, `libsecret`. |
| 84 | +Optional für „PDF über LaTeX“: `texlive-games` (`xskak`) und `pdflatex`. | |
| 75 | 85 | |
| 76 | 86 | Tests: |
| 77 | 87 | |
| @@ -94,7 +104,7 @@ Ins App-Menü aufnehmen: | ||
| 94 | 104 | | R | Neues Rätsel | |
| 95 | 105 | | Strg+S | Spielstand speichern | |
| 96 | 106 | | Strg+O | Spielstände | |
| 97 | -| Strg+Umschalt+S | Als PGN exportieren | | |
| 107 | +| Strg+Umschalt+S | Exportieren (PGN, Bild, PDF, HTML …) | | |
| 98 | 108 | | Strg+C | Partie als PGN kopieren | |
| 99 | 109 | | Strg+Umschalt+C | Stellung als FEN kopieren | |
| 100 | 110 | | Strg+V | Partie, Stellung oder Lichess-Link einfügen | |
| @@ -106,7 +116,7 @@ Ins App-Menü aufnehmen: | ||
| 106 | 116 | - `schach/app.py`: `HELPERS` (Hinweis-Helfer), `MIN_REPLY_SECONDS` |
| 107 | 117 | - `schach/threat.py`: `THREAT_GAIN` (ab wann eine Drohung zählt), `THREAT_LIMIT` |
| 108 | 118 | - `schach/annotate.py`: Schwellen für `?!`/`?`/`??` und für „einziger Zug“ (`!`) |
| 109 | -- Brettfarben: `SCHEMES` in `schach/board.py` | |
| 119 | +- Brettfarben: `SCHEMES` in `schach/diagram.py` | |
| 110 | 120 | - Eröffnungskurse: `schach/kurse/*.pgn` – normale PGN-Dateien. Hauptvariante = Plan, |
| 111 | 121 | Varianten = weitere Antworten, Kommentare = Erklärung. Kopf: `[Event "Name"]`, |
| 112 | 122 | `[SchachColor "white"]`, `[SchachIntro "…"]`. Neue Datei hinlegen genügt. |
modified ROADMAP.md +17 −9
| @@ -542,18 +542,26 @@ Springer, ohne Turm oder ohne Dame. Im Dialog „Freund herausfordern“: Vorgabe und | ||
| 542 | 542 | wer vorgibt. „Gewertet“ ist dann ausgegraut. Möglich wäre dasselbe später auch für |
| 543 | 543 | lokale Partien (gegen Maia, zu zweit). |
| 544 | 544 | |
| 545 | -## 11. Export (Idee) | |
| 545 | +## 11. Export | |
| 546 | 546 | |
| 547 | -Export als Datei oder in die Zwischenablage: | |
| 547 | +**Status:** umgesetzt (20.11.2026). Hauptmenü „Exportieren …“, Strg+Umschalt+S. | |
| 548 | + | |
| 549 | +Ein Dialog (`schach/exportdialog.py`) für alle Formate, als Datei oder in die | |
| 550 | +Zwischenablage (außer PDF): | |
| 548 | 551 | |
| 549 | -- PGN (gibt es schon), EPD/FEN der Stellung | |
| 550 | -- Bild der Stellung: SVG oder WebP | |
| 551 | -- LaTeX (Stellung oder ganze Partie, z. B. mit `xskak`/`chessboard`) | |
| 552 | -- PDF (Stellung oder ganze Partie) | |
| 553 | -- HTML: SVG-Brett, aktuelle Stellung als FEN zum Kopieren (`user-select: all`), | |
| 554 | - Zugliste zum Durchklicken, die mit dem beim Export gewählten Zug beginnt | |
| 552 | +- PGN (Partie oder Stellung mit `[FEN]`-Kopf), FEN | |
| 553 | +- Bild der Stellung: SVG oder PNG (statt WebP: PNG braucht keine neue Abhängigkeit | |
| 554 | + und lässt sich überall einfügen) | |
| 555 | +- LaTeX mit `xskak`: Zugfolge, Diagramm an der gezeigten Stellung | |
| 556 | +- PDF direkt mit Cairo, oder über LaTeX, wenn `pdflatex` installiert ist | |
| 557 | +- HTML als eine Datei: SVG-Brett, FEN zum Kopieren (`user-select: all`), Zugliste | |
| 558 | + zum Durchklicken, die mit der beim Export gezeigten Stellung beginnt | |
| 555 | 559 | - ASCII-Art |
| 556 | 560 | |
| 561 | +Umfang (Stellung oder Partie) und Darstellung (Zugzeichen, Gewinnchance, | |
| 562 | +Spielerköpfe, letzter Zug, Drehung) sind schaltbar. Bilder nutzen dieselbe | |
| 563 | +Zeichenroutine wie das Fenster (`schach/diagram.py`, `BoardPainter`). | |
| 564 | + | |
| 557 | 565 | ## Reihenfolge |
| 558 | 566 | |
| 559 | 567 | | # | Paket | Warum an dieser Stelle | |
| @@ -567,7 +575,7 @@ Export als Datei oder in die Zwischenabl | ||
| 567 | 575 | | 7 | Zwei Spieler an einem Rechner (7) | klein, sobald Spieler-Zeilen und Hilfe-Gruppe stehen. Legt das Partie-Modell für 8 an | |
| 568 | 576 | | 8 | Vorgabe-Partie auf Lichess (10) | klein; Handicap übers Internet ohne Fair-Play-Probleme | |
| 569 | 577 | | – | LAN mit Browser-Gast (8) | nur bei Bedarf | |
| 570 | -| – | Export (11) | Idee | | |
| 578 | +| ✓ | Export (11) | umgesetzt | | |
| 571 | 579 | | 9 | Internationalisierung (9) | Idee, ohne festen Platz | |
| 572 | 580 | |
| 573 | 581 | ## Offene Fragen |
modified schach/app.py +11 −16
| @@ -198,7 +198,7 @@ class Window(OnlineMixin, PuzzleMixin, O | ||
| 198 | 198 | files = Gio.Menu() |
| 199 | 199 | files.append("Spielstand _speichern …", "win.save-game") |
| 200 | 200 | files.append("Spielstände _öffnen …", "win.open-saves") |
| 201 | - files.append("Als PGN _exportieren …", "win.save-pgn") | |
| 201 | + files.append("_Exportieren …", "win.export") | |
| 202 | 202 | menu.append_section(None, files) |
| 203 | 203 | self.lichess_section = Gio.Menu() |
| 204 | 204 | menu.append_section("Lichess", self.lichess_section) |
| @@ -337,7 +337,7 @@ class Window(OnlineMixin, PuzzleMixin, O | ||
| 337 | 337 | ("hint", self.hint), |
| 338 | 338 | ("threat", self.threat), |
| 339 | 339 | ("flip", self.flip), |
| 340 | - ("save-pgn", self._save_pgn), | |
| 340 | + ("export", self._export_dialog), | |
| 341 | 341 | ("save-game", self._save_game_dialog), |
| 342 | 342 | ("open-saves", self._saves_dialog), |
| 343 | 343 | ("end-browse", self._end_browse), |
| @@ -392,7 +392,7 @@ class Window(OnlineMixin, PuzzleMixin, O | ||
| 392 | 392 | app.set_accels_for_action("win.flip", ["f"]) |
| 393 | 393 | app.set_accels_for_action("win.save-game", ["<Control>s"]) |
| 394 | 394 | app.set_accels_for_action("win.open-saves", ["<Control>o"]) |
| 395 | - app.set_accels_for_action("win.save-pgn", ["<Control><Shift>s"]) | |
| 395 | + app.set_accels_for_action("win.export", ["<Control><Shift>s"]) | |
| 396 | 396 | app.set_accels_for_action("win.toggle-list", ["a"]) |
| 397 | 397 | app.set_accels_for_action("win.end-browse", ["Escape"]) |
| 398 | 398 | app.set_accels_for_action("win.puzzle", ["r"]) |
| @@ -1464,7 +1464,7 @@ class Window(OnlineMixin, PuzzleMixin, O | ||
| 1464 | 1464 | ]), |
| 1465 | 1465 | ("Spielstände", [ |
| 1466 | 1466 | ("Spielstand speichern", "<Control>s"), ("Spielstände öffnen", "<Control>o"), |
| 1467 | - ("Als PGN exportieren", "<Control><Shift>s"), | |
| 1467 | + ("Exportieren (PGN, Bild, PDF, HTML …)", "<Control><Shift>s"), | |
| 1468 | 1468 | ]), |
| 1469 | 1469 | ("Zwischenablage", [ |
| 1470 | 1470 | ("Partie als PGN kopieren", "<Control>c"), |
| @@ -1665,19 +1665,14 @@ class Window(OnlineMixin, PuzzleMixin, O | ||
| 1665 | 1665 | def _pgn(self): |
| 1666 | 1666 | return savegames.to_pgn(self.state()) |
| 1667 | 1667 | |
| 1668 | - def _save_pgn(self, *_): | |
| 1669 | - dialog = Gtk.FileDialog(initial_name=f"partie-{datetime.date.today():%Y-%m-%d}.pgn") | |
| 1668 | + def _export_dialog(self, *_): | |
| 1669 | + from .exportdialog import ExportDialog | |
| 1670 | 1670 | |
| 1671 | - def on_done(d, result): | |
| 1672 | - try: | |
| 1673 | - file = d.save_finish(result) | |
| 1674 | - except GLib.Error: | |
| 1675 | - return | |
| 1676 | - with open(file.get_path(), "w") as fh: | |
| 1677 | - fh.write(self._pgn()) | |
| 1678 | - self.toasts.add_toast(Adw.Toast(title="Partie gespeichert")) | |
| 1679 | - | |
| 1680 | - dialog.save(self, None, on_done) | |
| 1671 | + plies = self.browse_ply + 1 if self._browsing() else len(self.board.move_stack) | |
| 1672 | + ExportDialog( | |
| 1673 | + self, self.state(), plies, self.settings.get("export"), flipped=self.view.flipped, | |
| 1674 | + theme=self.settings["theme"], scheme=self.settings["scheme"], style=self._notation(), | |
| 1675 | + ).present(self) | |
| 1681 | 1676 | |
| 1682 | 1677 | def _on_active_changed(self, *_): |
| 1683 | 1678 | if self.is_active(): |
modified schach/board.py +22 −431
| @@ -1,129 +1,41 @@ | ||
| 1 | -"""Das Schachbrett als GTK4-Widget (Cairo + librsvg).""" | |
| 1 | +"""Das Schachbrett als GTK4-Widget: Maus, Animation, Systemstil. Gezeichnet wird in diagram.py.""" | |
| 2 | 2 | |
| 3 | 3 | import math |
| 4 | -import os | |
| 5 | 4 | |
| 6 | -import cairo | |
| 7 | 5 | import chess |
| 8 | -import chess.svg | |
| 9 | 6 | import gi |
| 10 | 7 | |
| 11 | 8 | gi.require_version("Gtk", "4.0") |
| 12 | -gi.require_version("Rsvg", "2.0") | |
| 13 | 9 | gi.require_version("Adw", "1") |
| 14 | -from gi.repository import Adw, GLib, Gtk, Rsvg # noqa: E402 | |
| 10 | +from gi.repository import Adw, GLib, Gtk # noqa: E402 | |
| 11 | + | |
| 12 | +from .diagram import ( # noqa: E402,F401 – Namen bleiben hier importierbar | |
| 13 | + BADGE, BUILTIN_THEME, CLOCK_LOW, CLOCK_RUNNING, DEFAULT_SCHEME, LOW_TIME_MS, PYCHESS_PIECES, SCHEMES, | |
| 14 | + STRIP, VALUE, BoardPainter, available_themes, clock_parts, load_pieces, | |
| 15 | +) | |
| 16 | +from . import diagram # noqa: E402 | |
| 15 | 17 | |
| 16 | 18 | ANIM_SECONDS = 0.22 |
| 17 | -STRIP = 0.5 # Höhe der Streifen für geschlagene Figuren, in Feldgrößen | |
| 18 | -VALUE = {chess.PAWN: 1, chess.KNIGHT: 3, chess.BISHOP: 3, chess.ROOK: 5, chess.QUEEN: 9, chess.KING: 0} | |
| 19 | - | |
| 20 | -PYCHESS_PIECES = "/usr/share/pychess/pieces" | |
| 21 | -BUILTIN_THEME = "python-chess" | |
| 22 | - | |
| 23 | - | |
| 24 | - | |
| 25 | -def _rgb(hex_color): | |
| 26 | - return tuple(int(hex_color[i:i + 2], 16) / 255 for i in (1, 3, 5)) | |
| 27 | - | |
| 28 | - | |
| 29 | -# Brettfarben. "night" (optional): Variante für den dunklen Systemstil, damit das Brett nicht blendet. | |
| 30 | -SCHEMES = { | |
| 31 | - "holz": { | |
| 32 | - "label": "Holz", "light": _rgb("#f0d9b5"), "dark": _rgb("#b58863"), | |
| 33 | - "last": (0.80, 0.82, 0.25, 0.42), "selected": (0.08, 0.50, 0.20, 0.45), | |
| 34 | - }, | |
| 35 | - "schiefer": { | |
| 36 | - "label": "Schiefer", "light": _rgb("#e9ecef"), "dark": _rgb("#8b95a1"), | |
| 37 | - "night": {"light": _rgb("#c9ced4"), "dark": _rgb("#6f7a86")}, | |
| 38 | - "last": (0.98, 0.80, 0.30, 0.45), "selected": (0.08, 0.50, 0.20, 0.42), | |
| 39 | - }, | |
| 40 | - "gruen": { | |
| 41 | - "label": "Grün", "light": _rgb("#eeeed2"), "dark": _rgb("#769656"), | |
| 42 | - "last": (0.96, 0.92, 0.30, 0.50), "selected": (0.20, 0.45, 0.85, 0.45), | |
| 43 | - }, | |
| 44 | -} | |
| 45 | -DEFAULT_SCHEME = "holz" | |
| 46 | 19 | |
| 47 | 20 | |
| 48 | 21 | def scheme_colors(name): |
| 49 | 22 | """(hell, dunkel, letzter Zug, Auswahl) – berücksichtigt den dunklen Systemstil.""" |
| 50 | - scheme = SCHEMES.get(name) or SCHEMES[DEFAULT_SCHEME] | |
| 51 | - light, dark = scheme["light"], scheme["dark"] | |
| 52 | - if "night" in scheme and Adw.StyleManager.get_default().get_dark(): | |
| 53 | - light, dark = scheme["night"]["light"], scheme["night"]["dark"] | |
| 54 | - return light, dark, scheme["last"], scheme["selected"] | |
| 55 | - | |
| 56 | -HINT = (0.21, 0.52, 0.89) | |
| 57 | -THREAT = (0.91, 0.36, 0.11) | |
| 58 | -CHECK = (0.88, 0.11, 0.14) | |
| 59 | -BADGE = { | |
| 60 | - "!!": (0.10, 0.62, 0.55), | |
| 61 | - "!": (0.30, 0.52, 0.80), | |
| 62 | - "?!": (0.86, 0.66, 0.08), | |
| 63 | - "?": (0.90, 0.45, 0.10), | |
| 64 | - "??": (0.82, 0.13, 0.13), | |
| 65 | -} | |
| 23 | + return diagram.scheme_colors(name, Adw.StyleManager.get_default().get_dark()) | |
| 66 | 24 | |
| 67 | 25 | |
| 68 | -def available_themes(): | |
| 69 | - themes = [] | |
| 70 | - if os.path.isdir(PYCHESS_PIECES): | |
| 71 | - for name in sorted(os.listdir(PYCHESS_PIECES)): | |
| 72 | - if os.path.isfile(os.path.join(PYCHESS_PIECES, name, "wk.svg")): | |
| 73 | - themes.append(name) | |
| 74 | - return [BUILTIN_THEME] + themes | |
| 75 | - | |
| 76 | - | |
| 77 | -def load_pieces(theme): | |
| 78 | - handles = {} | |
| 79 | - for symbol in "PNBRQKpnbrqk": | |
| 80 | - piece = chess.Piece.from_symbol(symbol) | |
| 81 | - path = os.path.join( | |
| 82 | - PYCHESS_PIECES, theme, ("w" if piece.color else "b") + symbol.lower() + ".svg" | |
| 83 | - ) | |
| 84 | - if theme != BUILTIN_THEME and os.path.isfile(path): | |
| 85 | - handles[symbol] = Rsvg.Handle.new_from_file(path) | |
| 86 | - else: | |
| 87 | - handles[symbol] = Rsvg.Handle.new_from_data(chess.svg.piece(piece).encode()) | |
| 88 | - return handles | |
| 89 | - | |
| 90 | - | |
| 91 | -class BoardView(Gtk.DrawingArea): | |
| 26 | +class BoardView(Gtk.DrawingArea, BoardPainter): | |
| 92 | 27 | def __init__(self, theme="cburnett", scheme=DEFAULT_SCHEME): |
| 93 | 28 | super().__init__(hexpand=True, vexpand=True) |
| 94 | - self.scheme = scheme | |
| 95 | 29 | Adw.StyleManager.get_default().connect("notify::dark", lambda *_: self.queue_draw()) |
| 96 | 30 | self.set_size_request(320, 320) |
| 97 | 31 | |
| 98 | - self.board = chess.Board() | |
| 99 | - self.human = chess.WHITE | |
| 100 | - self.flipped = False | |
| 101 | - self.interactive = False | |
| 102 | - self.last_move = None | |
| 103 | - self.hint_from = None | |
| 104 | - self.hint_to = None | |
| 105 | - self.threat_from = None # Bedrohung: drohende Figur (Stufe 2) … | |
| 106 | - self.threat_to = None # … und bedrohtes Feld (Stufe 1) | |
| 107 | - self.badge = None # (feld, symbol) | |
| 108 | - self.selected = None | |
| 32 | + self._painter_init(theme, scheme) | |
| 109 | 33 | self.on_move = None # callback(von, nach) |
| 110 | 34 | self.on_inactive_click = None # callback() – Klick, während das Brett gesperrt ist |
| 111 | - self.names = None # {Farbe: "Name (1500)"} – Online-Partien | |
| 112 | - self.clocks = None # {Farbe: Millisekunden} | |
| 113 | - self.clock_running = None # Farbe, deren Uhr gerade läuft | |
| 114 | - self.turn_marker = None # Farbe, deren Name fett steht (wer am Zug ist, bei zwei Spielern) | |
| 115 | - | |
| 116 | - self._drag_sq = None | |
| 117 | - self._drag_pos = None | |
| 118 | - self._drag_moved = False | |
| 119 | 35 | self._was_selected = False |
| 120 | 36 | self._dropped = None # (von, nach) des letzten per Maus gezogenen Zugs |
| 121 | - self._anim = None | |
| 122 | - self._captures_key = None | |
| 123 | - self._captures = None | |
| 124 | - self.set_theme(theme) | |
| 125 | 37 | |
| 126 | - self.set_draw_func(self._draw) | |
| 38 | + self.set_draw_func(lambda _area, cr, _w, _h: self.paint(cr)) | |
| 127 | 39 | drag = Gtk.GestureDrag() |
| 128 | 40 | drag.connect("drag-begin", self._on_begin) |
| 129 | 41 | drag.connect("drag-update", self._on_update) |
| @@ -140,10 +52,16 @@ class BoardView(Gtk.DrawingArea): | ||
| 140 | 52 | |
| 141 | 53 | # --- Geometrie --------------------------------------------------------- |
| 142 | 54 | |
| 143 | - def _geometry(self): | |
| 144 | - w, h = self.get_width(), self.get_height() | |
| 145 | - size = max(min(w - 24, (h - 24) / (1 + 2 * STRIP / 8)), 8) | |
| 146 | - return (w - size) / 2, (h - size) / 2, size / 8 | |
| 55 | + def _size(self): | |
| 56 | + return self.get_width(), self.get_height() | |
| 57 | + | |
| 58 | + def _fg(self): | |
| 59 | + fg = self.get_color() # folgt hellem/dunklem Stil | |
| 60 | + return fg.red, fg.green, fg.blue | |
| 61 | + | |
| 62 | + @property | |
| 63 | + def dark_style(self): | |
| 64 | + return Adw.StyleManager.get_default().get_dark() | |
| 147 | 65 | |
| 148 | 66 | # --- Animation --------------------------------------------------------- |
| 149 | 67 | |
| @@ -193,38 +111,6 @@ class BoardView(Gtk.DrawingArea): | ||
| 193 | 111 | self.queue_draw() |
| 194 | 112 | return GLib.SOURCE_CONTINUE |
| 195 | 113 | |
| 196 | - # --- Geschlagene Figuren ----------------------------------------------- | |
| 197 | - | |
| 198 | - def _captured_by(self): | |
| 199 | - """{Farbe: [geschlagene gegnerische Figuren]} aus dem Partieverlauf.""" | |
| 200 | - key = (id(self.board), tuple(self.board.move_stack)) | |
| 201 | - if key != self._captures_key: | |
| 202 | - result = {chess.WHITE: [], chess.BLACK: []} | |
| 203 | - replay = self.board.root() | |
| 204 | - for move in self.board.move_stack: | |
| 205 | - if replay.is_en_passant(move): | |
| 206 | - result[replay.turn].append(chess.Piece(chess.PAWN, not replay.turn)) | |
| 207 | - elif replay.is_capture(move) and not replay.is_castling(move): | |
| 208 | - result[replay.turn].append(replay.piece_at(move.to_square)) | |
| 209 | - replay.push(move) | |
| 210 | - self._captures_key, self._captures = key, result | |
| 211 | - captured = {c: list(p) for c, p in self._captures.items()} | |
| 212 | - # Die gerade verblassende Figur erscheint erst nach der Animation im Streifen | |
| 213 | - if self._anim and self._anim["captured"]: | |
| 214 | - piece = self._anim["captured"][0] | |
| 215 | - if piece in captured[not piece.color]: | |
| 216 | - captured[not piece.color].remove(piece) | |
| 217 | - return captured | |
| 218 | - | |
| 219 | - def _material(self, color): | |
| 220 | - return sum(VALUE[p.piece_type] for p in self.board.piece_map().values() if p.color == color) | |
| 221 | - | |
| 222 | - def _square_origin(self, square): | |
| 223 | - ox, oy, sq = self._geometry() | |
| 224 | - f, r = chess.square_file(square), chess.square_rank(square) | |
| 225 | - col, row = (7 - f, r) if self.flipped else (f, 7 - r) | |
| 226 | - return ox + col * sq, oy + row * sq | |
| 227 | - | |
| 228 | 114 | def _square_at(self, x, y): |
| 229 | 115 | ox, oy, sq = self._geometry() |
| 230 | 116 | col, row = math.floor((x - ox) / sq), math.floor((y - oy) / sq) |
| @@ -232,9 +118,6 @@ class BoardView(Gtk.DrawingArea): | ||
| 232 | 118 | return None |
| 233 | 119 | return chess.square(7 - col, row) if self.flipped else chess.square(col, 7 - row) |
| 234 | 120 | |
| 235 | - def _targets(self, src): | |
| 236 | - return {m.to_square for m in self.board.legal_moves if m.from_square == src} | |
| 237 | - | |
| 238 | 121 | # --- Eingabe ----------------------------------------------------------- |
| 239 | 122 | |
| 240 | 123 | def _on_begin(self, gesture, x, y): |
| @@ -288,295 +171,3 @@ class BoardView(Gtk.DrawingArea): | ||
| 288 | 171 | self.queue_draw() |
| 289 | 172 | if self.on_move: |
| 290 | 173 | self.on_move(src, dst) |
| 291 | - | |
| 292 | - # --- Zeichnen ---------------------------------------------------------- | |
| 293 | - | |
| 294 | - def _draw(self, area, cr, width, height): | |
| 295 | - ox, oy, sq = self._geometry() | |
| 296 | - light_rgb, dark_rgb, last_rgba, selected_rgba = scheme_colors(self.scheme) | |
| 297 | - self._square_colors = (light_rgb, dark_rgb) | |
| 298 | - | |
| 299 | - for square in chess.SQUARES: | |
| 300 | - x, y = self._square_origin(square) | |
| 301 | - light = (chess.square_file(square) + chess.square_rank(square)) % 2 == 1 | |
| 302 | - cr.set_source_rgb(*(light_rgb if light else dark_rgb)) | |
| 303 | - cr.rectangle(x, y, sq, sq) | |
| 304 | - cr.fill() | |
| 305 | - | |
| 306 | - if self.last_move: | |
| 307 | - for s in (self.last_move.from_square, self.last_move.to_square): | |
| 308 | - self._fill_square(cr, s, sq, last_rgba) | |
| 309 | - if self.selected is not None: | |
| 310 | - self._fill_square(cr, self.selected, sq, selected_rgba) | |
| 311 | - if self.board.is_check(): | |
| 312 | - king = self.board.king(self.board.turn) | |
| 313 | - if king is not None: | |
| 314 | - self._glow(cr, king, sq, CHECK, 0.85) | |
| 315 | - for s in (self.hint_from, self.hint_to): | |
| 316 | - if s is not None: | |
| 317 | - self._mark(cr, s, sq, HINT) | |
| 318 | - for s in (self.threat_from, self.threat_to): | |
| 319 | - if s is not None: | |
| 320 | - self._mark(cr, s, sq, THREAT) | |
| 321 | - | |
| 322 | - self._draw_coordinates(cr, sq) | |
| 323 | - | |
| 324 | - dragging = self._drag_sq is not None and self._drag_moved | |
| 325 | - anim = self._anim | |
| 326 | - hidden = {to for _, _, to in anim["movers"]} if anim else set() | |
| 327 | - if anim and anim["captured"]: | |
| 328 | - piece, square = anim["captured"] | |
| 329 | - p = anim["progress"] | |
| 330 | - scale = 1 - 0.35 * p | |
| 331 | - x, y = self._square_origin(square) | |
| 332 | - off = sq * (1 - scale) / 2 | |
| 333 | - cr.push_group() | |
| 334 | - self._draw_piece(cr, piece, x + off, y + off, sq * scale) | |
| 335 | - cr.pop_group_to_source() | |
| 336 | - cr.paint_with_alpha(1 - p) | |
| 337 | - for square, piece in self.board.piece_map().items(): | |
| 338 | - if (dragging and square == self._drag_sq) or square in hidden: | |
| 339 | - continue | |
| 340 | - x, y = self._square_origin(square) | |
| 341 | - self._draw_piece(cr, piece, x, y, sq) | |
| 342 | - if anim: | |
| 343 | - p = anim["progress"] | |
| 344 | - for piece, src, dst in anim["movers"]: | |
| 345 | - x0, y0 = self._square_origin(src) | |
| 346 | - x1, y1 = self._square_origin(dst) | |
| 347 | - self._draw_piece(cr, piece, x0 + (x1 - x0) * p, y0 + (y1 - y0) * p, sq) | |
| 348 | - | |
| 349 | - if self.threat_from is not None and self.threat_to is not None: | |
| 350 | - self._draw_arrow(cr, self.threat_from, self.threat_to, sq, THREAT) | |
| 351 | - | |
| 352 | - self._draw_captures(cr, ox, oy, sq) | |
| 353 | - self._draw_players(cr, ox, oy, sq) | |
| 354 | - | |
| 355 | - if self.selected is not None and self.interactive: | |
| 356 | - for t in self._targets(self.selected): | |
| 357 | - x, y = self._square_origin(t) | |
| 358 | - cr.new_path() # show_text hinterlässt einen Current Point; arc() zöge sonst eine Linie von dort | |
| 359 | - cr.set_source_rgba(0, 0, 0, 0.2) | |
| 360 | - if self.board.piece_at(t): | |
| 361 | - cr.set_line_width(sq * 0.07) | |
| 362 | - cr.arc(x + sq / 2, y + sq / 2, sq * 0.45, 0, 2 * math.pi) | |
| 363 | - cr.stroke() | |
| 364 | - else: | |
| 365 | - cr.arc(x + sq / 2, y + sq / 2, sq * 0.15, 0, 2 * math.pi) | |
| 366 | - cr.fill() | |
| 367 | - | |
| 368 | - if self.badge: | |
| 369 | - self._draw_badge(cr, *self.badge, sq) | |
| 370 | - | |
| 371 | - if dragging: | |
| 372 | - piece = self.board.piece_at(self._drag_sq) | |
| 373 | - if piece: | |
| 374 | - px, py = self._drag_pos | |
| 375 | - s = sq * 1.1 | |
| 376 | - self._draw_piece(cr, piece, px - s / 2, py - s / 2, s) | |
| 377 | - | |
| 378 | - def _mark(self, cr, square, sq, rgb): | |
| 379 | - """Leuchtendes Feld mit Rahmen (Hinweis blau, Bedrohung orange).""" | |
| 380 | - self._glow(cr, square, sq, rgb, 0.9) | |
| 381 | - x, y = self._square_origin(square) | |
| 382 | - cr.set_source_rgba(*rgb, 0.95) | |
| 383 | - cr.set_line_width(max(sq * 0.05, 2)) | |
| 384 | - inset = sq * 0.04 | |
| 385 | - cr.rectangle(x + inset, y + inset, sq - 2 * inset, sq - 2 * inset) | |
| 386 | - cr.stroke() | |
| 387 | - | |
| 388 | - def _draw_arrow(self, cr, src, dst, sq, rgb): | |
| 389 | - x0, y0 = self._square_origin(src) | |
| 390 | - x1, y1 = self._square_origin(dst) | |
| 391 | - x0, y0, x1, y1 = x0 + sq / 2, y0 + sq / 2, x1 + sq / 2, y1 + sq / 2 | |
| 392 | - angle = math.atan2(y1 - y0, x1 - x0) | |
| 393 | - head = sq * 0.38 | |
| 394 | - tip_x, tip_y = x1 - math.cos(angle) * sq * 0.12, y1 - math.sin(angle) * sq * 0.12 | |
| 395 | - base_x, base_y = tip_x - math.cos(angle) * head * 0.8, tip_y - math.sin(angle) * head * 0.8 | |
| 396 | - cr.new_path() | |
| 397 | - cr.set_source_rgba(*rgb, 0.8) | |
| 398 | - cr.set_line_width(sq * 0.13) | |
| 399 | - cr.set_line_cap(cairo.LINE_CAP_ROUND) | |
| 400 | - cr.move_to(x0 + math.cos(angle) * sq * 0.2, y0 + math.sin(angle) * sq * 0.2) | |
| 401 | - cr.line_to(base_x, base_y) | |
| 402 | - cr.stroke() | |
| 403 | - cr.move_to(tip_x, tip_y) | |
| 404 | - for side in (-0.5, 0.5): | |
| 405 | - cr.line_to(tip_x - head * math.cos(angle + side), tip_y - head * math.sin(angle + side)) | |
| 406 | - cr.close_path() | |
| 407 | - cr.fill() | |
| 408 | - cr.set_line_cap(cairo.LINE_CAP_BUTT) | |
| 409 | - | |
| 410 | - def _fill_square(self, cr, square, sq, rgba): | |
| 411 | - x, y = self._square_origin(square) | |
| 412 | - cr.set_source_rgba(*rgba) | |
| 413 | - cr.rectangle(x, y, sq, sq) | |
| 414 | - cr.fill() | |
| 415 | - | |
| 416 | - def _glow(self, cr, square, sq, rgb, alpha): | |
| 417 | - x, y = self._square_origin(square) | |
| 418 | - cx, cy = x + sq / 2, y + sq / 2 | |
| 419 | - grad = cairo.RadialGradient(cx, cy, sq * 0.05, cx, cy, sq * 0.72) | |
| 420 | - grad.add_color_stop_rgba(0, *rgb, alpha) | |
| 421 | - grad.add_color_stop_rgba(0.6, *rgb, alpha * 0.5) | |
| 422 | - grad.add_color_stop_rgba(1, *rgb, 0) | |
| 423 | - cr.save() | |
| 424 | - cr.rectangle(x, y, sq, sq) | |
| 425 | - cr.clip() | |
| 426 | - cr.set_source(grad) | |
| 427 | - cr.paint() | |
| 428 | - cr.restore() | |
| 429 | - | |
| 430 | - def _draw_piece(self, cr, piece, x, y, size): | |
| 431 | - rect = Rsvg.Rectangle() | |
| 432 | - rect.x, rect.y, rect.width, rect.height = x, y, size, size | |
| 433 | - self._pieces[piece.symbol()].render_document(cr, rect) | |
| 434 | - | |
| 435 | - def _draw_coordinates(self, cr, sq): | |
| 436 | - light_rgb, dark_rgb = self._square_colors # Beschriftung in der Gegenfarbe des Felds | |
| 437 | - cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) | |
| 438 | - cr.set_font_size(sq * 0.16) | |
| 439 | - bottom_rank = 7 if self.flipped else 0 | |
| 440 | - left_file = 7 if self.flipped else 0 | |
| 441 | - for f in range(8): | |
| 442 | - square = chess.square(f, bottom_rank) | |
| 443 | - x, y = self._square_origin(square) | |
| 444 | - light = (f + bottom_rank) % 2 == 1 | |
| 445 | - cr.set_source_rgb(*(dark_rgb if light else light_rgb)) | |
| 446 | - cr.move_to(x + sq * 0.80, y + sq * 0.94) | |
| 447 | - cr.show_text(chess.FILE_NAMES[f]) | |
| 448 | - for r in range(8): | |
| 449 | - square = chess.square(left_file, r) | |
| 450 | - x, y = self._square_origin(square) | |
| 451 | - light = (left_file + r) % 2 == 1 | |
| 452 | - cr.set_source_rgb(*(dark_rgb if light else light_rgb)) | |
| 453 | - cr.move_to(x + sq * 0.05, y + sq * 0.2) | |
| 454 | - cr.show_text(chess.RANK_NAMES[r]) | |
| 455 | - | |
| 456 | - def _draw_captures(self, cr, ox, oy, sq): | |
| 457 | - captured = self._captured_by() | |
| 458 | - bottom = chess.BLACK if self.flipped else chess.WHITE | |
| 459 | - diff = self._material(chess.WHITE) - self._material(chess.BLACK) | |
| 460 | - size = sq * STRIP * 0.9 | |
| 461 | - for color in (chess.WHITE, chess.BLACK): | |
| 462 | - if color == bottom: | |
| 463 | - y = oy + 8 * sq + sq * STRIP * 0.05 | |
| 464 | - else: | |
| 465 | - y = oy - sq * STRIP * 0.95 | |
| 466 | - x = ox | |
| 467 | - pieces = sorted(captured[color], key=lambda p: (VALUE[p.piece_type], p.piece_type)) | |
| 468 | - previous = None | |
| 469 | - for piece in pieces: | |
| 470 | - if previous is not None: | |
| 471 | - x += size * (0.45 if piece.piece_type == previous else 0.85) | |
| 472 | - self._draw_piece(cr, piece, x, y, size) | |
| 473 | - previous = piece.piece_type | |
| 474 | - advantage = diff if color == chess.WHITE else -diff | |
| 475 | - if advantage > 0: | |
| 476 | - x += size * (1.0 if pieces else 0.0) | |
| 477 | - cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) | |
| 478 | - cr.set_font_size(size * 0.55) | |
| 479 | - fg = self.get_color() # folgt hellem/dunklem Stil | |
| 480 | - cr.set_source_rgba(fg.red, fg.green, fg.blue, 0.7) | |
| 481 | - cr.move_to(x + size * 0.1, y + size * 0.72) | |
| 482 | - cr.show_text(f"+{advantage}") | |
| 483 | - | |
| 484 | - def _draw_players(self, cr, ox, oy, sq): | |
| 485 | - """Name und Uhr rechts in den Streifen über und unter dem Brett.""" | |
| 486 | - if not self.names and not self.clocks: | |
| 487 | - return | |
| 488 | - bottom = chess.BLACK if self.flipped else chess.WHITE | |
| 489 | - h = sq * STRIP | |
| 490 | - fg = self.get_color() | |
| 491 | - for color in (chess.WHITE, chess.BLACK): | |
| 492 | - y = oy + 8 * sq if color == bottom else oy - h | |
| 493 | - right = ox + 8 * sq | |
| 494 | - if self.clocks and color in self.clocks: | |
| 495 | - right = self._draw_clock(cr, right, y, h, self.clocks[color], self.clock_running == color, fg) | |
| 496 | - if self.names and color in self.names: | |
| 497 | - bold = self.turn_marker == color | |
| 498 | - cr.select_font_face( | |
| 499 | - "Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD if bold else cairo.FONT_WEIGHT_NORMAL) | |
| 500 | - cr.set_font_size(h * 0.45) | |
| 501 | - text = self.names[color] | |
| 502 | - ext = cr.text_extents(text) | |
| 503 | - cr.set_source_rgba(fg.red, fg.green, fg.blue, 0.75) | |
| 504 | - cr.move_to(right - ext.x_advance, y + h / 2 + ext.height / 2) | |
| 505 | - cr.show_text(text) | |
| 506 | - | |
| 507 | - def _draw_clock(self, cr, right, y, h, ms, running, fg): | |
| 508 | - """Uhr als zwei zusammengewachsene Felder: Minuten | Sekunden. Gibt die linke Kante zurück.""" | |
| 509 | - minutes, seconds = clock_parts(ms) | |
| 510 | - low = ms < LOW_TIME_MS | |
| 511 | - cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) | |
| 512 | - cr.set_font_size(h * 0.52) | |
| 513 | - pad = h * 0.22 | |
| 514 | - # feste Mindestbreiten, damit die Uhr beim Ticken nicht springt | |
| 515 | - left_w = max(cr.text_extents("00").x_advance, cr.text_extents(minutes).x_advance) + 2 * pad | |
| 516 | - right_w = max(cr.text_extents("00").x_advance, cr.text_extents(seconds).x_advance) + 2 * pad | |
| 517 | - bh = h * 0.78 | |
| 518 | - by = y + (h - bh) / 2 | |
| 519 | - bx = right - left_w - right_w | |
| 520 | - radius = bh * 0.3 | |
| 521 | - | |
| 522 | - if running: | |
| 523 | - cr.set_source_rgb(*(CLOCK_LOW if low else CLOCK_RUNNING)) | |
| 524 | - else: | |
| 525 | - cr.set_source_rgba(fg.red, fg.green, fg.blue, 0.10) | |
| 526 | - _rounded(cr, bx, by, left_w + right_w, bh, radius) | |
| 527 | - cr.fill() | |
| 528 | - # Naht zwischen Minuten und Sekunden | |
| 529 | - cr.set_source_rgba(1, 1, 1, 0.35) if running else cr.set_source_rgba(fg.red, fg.green, fg.blue, 0.18) | |
| 530 | - cr.rectangle(bx + left_w - 0.75, by + bh * 0.18, 1.5, bh * 0.64) | |
| 531 | - cr.fill() | |
| 532 | - | |
| 533 | - if running: | |
| 534 | - cr.set_source_rgb(1, 1, 1) | |
| 535 | - else: | |
| 536 | - cr.set_source_rgba(fg.red, fg.green, fg.blue, 0.85) | |
| 537 | - digits = cr.text_extents("0") | |
| 538 | - baseline = by + bh / 2 + digits.height / 2 | |
| 539 | - for text, x0, width in ((minutes, bx, left_w), (seconds, bx + left_w, right_w)): | |
| 540 | - ext = cr.text_extents(text) | |
| 541 | - cr.move_to(x0 + (width - ext.x_advance) / 2, baseline) | |
| 542 | - cr.show_text(text) | |
| 543 | - return bx - h * 0.3 | |
| 544 | - | |
| 545 | - def _draw_badge(self, cr, square, text, sq): | |
| 546 | - x, y = self._square_origin(square) | |
| 547 | - r = sq * 0.19 | |
| 548 | - cx, cy = x + sq - r * 0.9, y + r * 0.9 | |
| 549 | - cr.set_source_rgba(0, 0, 0, 0.3) | |
| 550 | - cr.arc(cx + 1.5, cy + 1.5, r, 0, 2 * math.pi) | |
| 551 | - cr.fill() | |
| 552 | - cr.set_source_rgb(*BADGE.get(text, (0.4, 0.4, 0.4))) | |
| 553 | - cr.arc(cx, cy, r, 0, 2 * math.pi) | |
| 554 | - cr.fill() | |
| 555 | - cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) | |
| 556 | - cr.set_font_size(r * (1.05 if len(text) == 1 else 0.95)) | |
| 557 | - ext = cr.text_extents(text) | |
| 558 | - cr.set_source_rgb(1, 1, 1) | |
| 559 | - cr.move_to(cx - ext.width / 2 - ext.x_bearing, cy - ext.height / 2 - ext.y_bearing) | |
| 560 | - cr.show_text(text) | |
| 561 | - | |
| 562 | - | |
| 563 | -LOW_TIME_MS = 20000 # darunter wird die laufende Uhr rot | |
| 564 | -CLOCK_RUNNING = (0.18, 0.55, 0.34) | |
| 565 | -CLOCK_LOW = (0.80, 0.20, 0.18) | |
| 566 | - | |
| 567 | - | |
| 568 | -def clock_parts(ms): | |
| 569 | - """Minuten- und Sekundenfeld, beide zweistellig: ("04", "37"); ab einer Stunde ("1:02", "37").""" | |
| 570 | - secs = max(0, int(ms)) // 1000 | |
| 571 | - if secs >= 3600: | |
| 572 | - return f"{secs // 3600}:{secs // 60 % 60:02d}", f"{secs % 60:02d}" | |
| 573 | - return f"{secs // 60:02d}", f"{secs % 60:02d}" | |
| 574 | - | |
| 575 | - | |
| 576 | -def _rounded(cr, x, y, w, h, r): | |
| 577 | - cr.new_sub_path() | |
| 578 | - cr.arc(x + w - r, y + r, r, -math.pi / 2, 0) | |
| 579 | - cr.arc(x + w - r, y + h - r, r, 0, math.pi / 2) | |
| 580 | - cr.arc(x + r, y + h - r, r, math.pi / 2, math.pi) | |
| 581 | - cr.arc(x + r, y + r, r, math.pi, 3 * math.pi / 2) | |
| 582 | - cr.close_path() | |
added schach/diagram.py +556 −0
| @@ -0,0 +1,556 @@ | ||
| 1 | +"""Das Brett zeichnen – auf jede Cairo-Fläche: Fenster, SVG, PNG, PDF. | |
| 2 | + | |
| 3 | +``BoardPainter`` enthält alles, was ein Bild des Bretts braucht. ``BoardView`` (board.py) | |
| 4 | +ergänzt Maus und Animation; ``Diagram`` zeichnet eine feste Stellung für den Export. | |
| 5 | +Ohne Gtk, damit Export und Tests auch ohne Fenster laufen. | |
| 6 | +""" | |
| 7 | + | |
| 8 | +import io | |
| 9 | +import math | |
| 10 | +import os | |
| 11 | + | |
| 12 | +import cairo | |
| 13 | +import chess | |
| 14 | +import chess.svg | |
| 15 | +import gi | |
| 16 | + | |
| 17 | +gi.require_version("Rsvg", "2.0") | |
| 18 | +from gi.repository import Rsvg # noqa: E402 | |
| 19 | + | |
| 20 | +STRIP = 0.5 # Höhe der Streifen für geschlagene Figuren, in Feldgrößen | |
| 21 | +BAR = 0.32 # Breite des Gewinnchance-Balkens neben dem Brett, in Feldgrößen | |
| 22 | +VALUE = {chess.PAWN: 1, chess.KNIGHT: 3, chess.BISHOP: 3, chess.ROOK: 5, chess.QUEEN: 9, chess.KING: 0} | |
| 23 | + | |
| 24 | +PYCHESS_PIECES = "/usr/share/pychess/pieces" | |
| 25 | +BUILTIN_THEME = "python-chess" | |
| 26 | + | |
| 27 | + | |
| 28 | +def _rgb(hex_color): | |
| 29 | + return tuple(int(hex_color[i:i + 2], 16) / 255 for i in (1, 3, 5)) | |
| 30 | + | |
| 31 | + | |
| 32 | +# Brettfarben. "night" (optional): Variante für den dunklen Systemstil, damit das Brett nicht blendet. | |
| 33 | +SCHEMES = { | |
| 34 | + "holz": { | |
| 35 | + "label": "Holz", "light": _rgb("#f0d9b5"), "dark": _rgb("#b58863"), | |
| 36 | + "last": (0.80, 0.82, 0.25, 0.42), "selected": (0.08, 0.50, 0.20, 0.45), | |
| 37 | + }, | |
| 38 | + "schiefer": { | |
| 39 | + "label": "Schiefer", "light": _rgb("#e9ecef"), "dark": _rgb("#8b95a1"), | |
| 40 | + "night": {"light": _rgb("#c9ced4"), "dark": _rgb("#6f7a86")}, | |
| 41 | + "last": (0.98, 0.80, 0.30, 0.45), "selected": (0.08, 0.50, 0.20, 0.42), | |
| 42 | + }, | |
| 43 | + "gruen": { | |
| 44 | + "label": "Grün", "light": _rgb("#eeeed2"), "dark": _rgb("#769656"), | |
| 45 | + "last": (0.96, 0.92, 0.30, 0.50), "selected": (0.20, 0.45, 0.85, 0.45), | |
| 46 | + }, | |
| 47 | +} | |
| 48 | +DEFAULT_SCHEME = "holz" | |
| 49 | + | |
| 50 | +HINT = (0.21, 0.52, 0.89) | |
| 51 | +THREAT = (0.91, 0.36, 0.11) | |
| 52 | +CHECK = (0.88, 0.11, 0.14) | |
| 53 | +BADGE = { | |
| 54 | + "!!": (0.10, 0.62, 0.55), | |
| 55 | + "!": (0.30, 0.52, 0.80), | |
| 56 | + "?!": (0.86, 0.66, 0.08), | |
| 57 | + "?": (0.90, 0.45, 0.10), | |
| 58 | + "??": (0.82, 0.13, 0.13), | |
| 59 | +} | |
| 60 | +BAR_WHITE = (0.95, 0.95, 0.93) | |
| 61 | +BAR_BLACK = (0.17, 0.17, 0.18) | |
| 62 | + | |
| 63 | + | |
| 64 | +def scheme_colors(name, dark=False): | |
| 65 | + """(hell, dunkel, letzter Zug, Auswahl); ``dark``: Variante für den dunklen Systemstil.""" | |
| 66 | + scheme = SCHEMES.get(name) or SCHEMES[DEFAULT_SCHEME] | |
| 67 | + light, darker = scheme["light"], scheme["dark"] | |
| 68 | + if dark and "night" in scheme: | |
| 69 | + light, darker = scheme["night"]["light"], scheme["night"]["dark"] | |
| 70 | + return light, darker, scheme["last"], scheme["selected"] | |
| 71 | + | |
| 72 | + | |
| 73 | +def hex_color(rgb): | |
| 74 | + return "#" + "".join(f"{round(c * 255):02x}" for c in rgb[:3]) | |
| 75 | + | |
| 76 | + | |
| 77 | +def available_themes(): | |
| 78 | + themes = [] | |
| 79 | + if os.path.isdir(PYCHESS_PIECES): | |
| 80 | + for name in sorted(os.listdir(PYCHESS_PIECES)): | |
| 81 | + if os.path.isfile(os.path.join(PYCHESS_PIECES, name, "wk.svg")): | |
| 82 | + themes.append(name) | |
| 83 | + return [BUILTIN_THEME] + themes | |
| 84 | + | |
| 85 | + | |
| 86 | +def piece_svg(theme, symbol): | |
| 87 | + """SVG-Quelltext einer Figur (``symbol`` wie in FEN: K, q …) aus dem Figurensatz.""" | |
| 88 | + piece = chess.Piece.from_symbol(symbol) | |
| 89 | + path = os.path.join(PYCHESS_PIECES, theme, ("w" if piece.color else "b") + symbol.lower() + ".svg") | |
| 90 | + if theme != BUILTIN_THEME and os.path.isfile(path): | |
| 91 | + with open(path, "rb") as fh: | |
| 92 | + return fh.read() | |
| 93 | + return chess.svg.piece(piece).encode() | |
| 94 | + | |
| 95 | + | |
| 96 | +def load_pieces(theme): | |
| 97 | + return {symbol: Rsvg.Handle.new_from_data(piece_svg(theme, symbol)) for symbol in "PNBRQKpnbrqk"} | |
| 98 | + | |
| 99 | + | |
| 100 | +class BoardPainter: | |
| 101 | + """Zeichnet Brett, Markierungen, Figuren und die Streifen darüber und darunter. | |
| 102 | + | |
| 103 | + Unterklassen liefern die Fläche (``_size``) und die Textfarbe (``_fg``). | |
| 104 | + """ | |
| 105 | + | |
| 106 | + margin = 12 # Rand um Brett und Streifen | |
| 107 | + strips = True # Streifen für geschlagene Figuren und Namen | |
| 108 | + dark_style = False # Brettfarben für den dunklen Systemstil | |
| 109 | + | |
| 110 | + def _painter_init(self, theme, scheme): | |
| 111 | + self.scheme = scheme | |
| 112 | + self.board = chess.Board() | |
| 113 | + self.human = chess.WHITE | |
| 114 | + self.flipped = False | |
| 115 | + self.interactive = False | |
| 116 | + self.last_move = None | |
| 117 | + self.hint_from = None | |
| 118 | + self.hint_to = None | |
| 119 | + self.threat_from = None # Bedrohung: drohende Figur (Stufe 2) … | |
| 120 | + self.threat_to = None # … und bedrohtes Feld (Stufe 1) | |
| 121 | + self.badge = None # (feld, symbol) | |
| 122 | + self.selected = None | |
| 123 | + self.names = None # {Farbe: "Name (1500)"} | |
| 124 | + self.clocks = None # {Farbe: Millisekunden} | |
| 125 | + self.clock_running = None # Farbe, deren Uhr gerade läuft | |
| 126 | + self.turn_marker = None # Farbe, deren Name fett steht (wer am Zug ist, bei zwei Spielern) | |
| 127 | + self.eval_bar = None # Gewinnchance Weiß in Prozent: Balken links neben dem Brett | |
| 128 | + self._drag_sq = None | |
| 129 | + self._drag_pos = None | |
| 130 | + self._drag_moved = False | |
| 131 | + self._anim = None | |
| 132 | + self._captures_key = None | |
| 133 | + self._captures = None | |
| 134 | + self._pieces = load_pieces(theme) | |
| 135 | + | |
| 136 | + def _size(self): | |
| 137 | + raise NotImplementedError | |
| 138 | + | |
| 139 | + def _fg(self): | |
| 140 | + return (0.2, 0.2, 0.2) | |
| 141 | + | |
| 142 | + # --- Geometrie --------------------------------------------------------- | |
| 143 | + | |
| 144 | + def _geometry(self): | |
| 145 | + w, h = self._size() | |
| 146 | + strip = 2 * STRIP / 8 if self.strips else 0 | |
| 147 | + bar = BAR / 8 if self.eval_bar is not None else 0 | |
| 148 | + size = max(min((w - 2 * self.margin) / (1 + bar), (h - 2 * self.margin) / (1 + strip)), 8) | |
| 149 | + ox = (w - size * (1 + bar)) / 2 + size * bar | |
| 150 | + return ox, (h - size) / 2, size / 8 | |
| 151 | + | |
| 152 | + def _square_origin(self, square): | |
| 153 | + ox, oy, sq = self._geometry() | |
| 154 | + f, r = chess.square_file(square), chess.square_rank(square) | |
| 155 | + col, row = (7 - f, r) if self.flipped else (f, 7 - r) | |
| 156 | + return ox + col * sq, oy + row * sq | |
| 157 | + | |
| 158 | + def _targets(self, src): | |
| 159 | + return {m.to_square for m in self.board.legal_moves if m.from_square == src} | |
| 160 | + | |
| 161 | + # --- Geschlagene Figuren ----------------------------------------------- | |
| 162 | + | |
| 163 | + def _captured_by(self): | |
| 164 | + """{Farbe: [geschlagene gegnerische Figuren]} aus dem Partieverlauf.""" | |
| 165 | + key = (id(self.board), tuple(self.board.move_stack)) | |
| 166 | + if key != self._captures_key: | |
| 167 | + result = {chess.WHITE: [], chess.BLACK: []} | |
| 168 | + replay = self.board.root() | |
| 169 | + for move in self.board.move_stack: | |
| 170 | + if replay.is_en_passant(move): | |
| 171 | + result[replay.turn].append(chess.Piece(chess.PAWN, not replay.turn)) | |
| 172 | + elif replay.is_capture(move) and not replay.is_castling(move): | |
| 173 | + result[replay.turn].append(replay.piece_at(move.to_square)) | |
| 174 | + replay.push(move) | |
| 175 | + self._captures_key, self._captures = key, result | |
| 176 | + captured = {c: list(p) for c, p in self._captures.items()} | |
| 177 | + # Die gerade verblassende Figur erscheint erst nach der Animation im Streifen | |
| 178 | + if self._anim and self._anim["captured"]: | |
| 179 | + piece = self._anim["captured"][0] | |
| 180 | + if piece in captured[not piece.color]: | |
| 181 | + captured[not piece.color].remove(piece) | |
| 182 | + return captured | |
| 183 | + | |
| 184 | + def _material(self, color): | |
| 185 | + return sum(VALUE[p.piece_type] for p in self.board.piece_map().values() if p.color == color) | |
| 186 | + | |
| 187 | + # --- Zeichnen ---------------------------------------------------------- | |
| 188 | + | |
| 189 | + def paint(self, cr): | |
| 190 | + ox, oy, sq = self._geometry() | |
| 191 | + light_rgb, dark_rgb, last_rgba, selected_rgba = scheme_colors(self.scheme, self.dark_style) | |
| 192 | + self._square_colors = (light_rgb, dark_rgb) | |
| 193 | + | |
| 194 | + for square in chess.SQUARES: | |
| 195 | + x, y = self._square_origin(square) | |
| 196 | + light = (chess.square_file(square) + chess.square_rank(square)) % 2 == 1 | |
| 197 | + cr.set_source_rgb(*(light_rgb if light else dark_rgb)) | |
| 198 | + cr.rectangle(x, y, sq, sq) | |
| 199 | + cr.fill() | |
| 200 | + | |
| 201 | + if self.last_move: | |
| 202 | + for s in (self.last_move.from_square, self.last_move.to_square): | |
| 203 | + self._fill_square(cr, s, sq, last_rgba) | |
| 204 | + if self.selected is not None: | |
| 205 | + self._fill_square(cr, self.selected, sq, selected_rgba) | |
| 206 | + if self.board.is_check(): | |
| 207 | + king = self.board.king(self.board.turn) | |
| 208 | + if king is not None: | |
| 209 | + self._glow(cr, king, sq, CHECK, 0.85) | |
| 210 | + for s in (self.hint_from, self.hint_to): | |
| 211 | + if s is not None: | |
| 212 | + self._mark(cr, s, sq, HINT) | |
| 213 | + for s in (self.threat_from, self.threat_to): | |
| 214 | + if s is not None: | |
| 215 | + self._mark(cr, s, sq, THREAT) | |
| 216 | + | |
| 217 | + self._draw_coordinates(cr, sq) | |
| 218 | + | |
| 219 | + dragging = self._drag_sq is not None and self._drag_moved | |
| 220 | + anim = self._anim | |
| 221 | + hidden = {to for _, _, to in anim["movers"]} if anim else set() | |
| 222 | + if anim and anim["captured"]: | |
| 223 | + piece, square = anim["captured"] | |
| 224 | + p = anim["progress"] | |
| 225 | + scale = 1 - 0.35 * p | |
| 226 | + x, y = self._square_origin(square) | |
| 227 | + off = sq * (1 - scale) / 2 | |
| 228 | + cr.push_group() | |
| 229 | + self._draw_piece(cr, piece, x + off, y + off, sq * scale) | |
| 230 | + cr.pop_group_to_source() | |
| 231 | + cr.paint_with_alpha(1 - p) | |
| 232 | + for square, piece in self.board.piece_map().items(): | |
| 233 | + if (dragging and square == self._drag_sq) or square in hidden: | |
| 234 | + continue | |
| 235 | + x, y = self._square_origin(square) | |
| 236 | + self._draw_piece(cr, piece, x, y, sq) | |
| 237 | + if anim: | |
| 238 | + p = anim["progress"] | |
| 239 | + for piece, src, dst in anim["movers"]: | |
| 240 | + x0, y0 = self._square_origin(src) | |
| 241 | + x1, y1 = self._square_origin(dst) | |
| 242 | + self._draw_piece(cr, piece, x0 + (x1 - x0) * p, y0 + (y1 - y0) * p, sq) | |
| 243 | + | |
| 244 | + if self.threat_from is not None and self.threat_to is not None: | |
| 245 | + self._draw_arrow(cr, self.threat_from, self.threat_to, sq, THREAT) | |
| 246 | + | |
| 247 | + if self.strips: | |
| 248 | + self._draw_captures(cr, ox, oy, sq) | |
| 249 | + self._draw_players(cr, ox, oy, sq) | |
| 250 | + if self.eval_bar is not None: | |
| 251 | + self._draw_eval_bar(cr, ox, oy, sq) | |
| 252 | + | |
| 253 | + if self.selected is not None and self.interactive: | |
| 254 | + for t in self._targets(self.selected): | |
| 255 | + x, y = self._square_origin(t) | |
| 256 | + cr.new_path() # show_text hinterlässt einen Current Point; arc() zöge sonst eine Linie von dort | |
| 257 | + cr.set_source_rgba(0, 0, 0, 0.2) | |
| 258 | + if self.board.piece_at(t): | |
| 259 | + cr.set_line_width(sq * 0.07) | |
| 260 | + cr.arc(x + sq / 2, y + sq / 2, sq * 0.45, 0, 2 * math.pi) | |
| 261 | + cr.stroke() | |
| 262 | + else: | |
| 263 | + cr.arc(x + sq / 2, y + sq / 2, sq * 0.15, 0, 2 * math.pi) | |
| 264 | + cr.fill() | |
| 265 | + | |
| 266 | + if self.badge: | |
| 267 | + self._draw_badge(cr, *self.badge, sq) | |
| 268 | + | |
| 269 | + if dragging: | |
| 270 | + piece = self.board.piece_at(self._drag_sq) | |
| 271 | + if piece: | |
| 272 | + px, py = self._drag_pos | |
| 273 | + s = sq * 1.1 | |
| 274 | + self._draw_piece(cr, piece, px - s / 2, py - s / 2, s) | |
| 275 | + | |
| 276 | + def _mark(self, cr, square, sq, rgb): | |
| 277 | + """Leuchtendes Feld mit Rahmen (Hinweis blau, Bedrohung orange).""" | |
| 278 | + self._glow(cr, square, sq, rgb, 0.9) | |
| 279 | + x, y = self._square_origin(square) | |
| 280 | + cr.set_source_rgba(*rgb, 0.95) | |
| 281 | + cr.set_line_width(max(sq * 0.05, 2)) | |
| 282 | + inset = sq * 0.04 | |
| 283 | + cr.rectangle(x + inset, y + inset, sq - 2 * inset, sq - 2 * inset) | |
| 284 | + cr.stroke() | |
| 285 | + | |
| 286 | + def _draw_arrow(self, cr, src, dst, sq, rgb): | |
| 287 | + x0, y0 = self._square_origin(src) | |
| 288 | + x1, y1 = self._square_origin(dst) | |
| 289 | + x0, y0, x1, y1 = x0 + sq / 2, y0 + sq / 2, x1 + sq / 2, y1 + sq / 2 | |
| 290 | + angle = math.atan2(y1 - y0, x1 - x0) | |
| 291 | + head = sq * 0.38 | |
| 292 | + tip_x, tip_y = x1 - math.cos(angle) * sq * 0.12, y1 - math.sin(angle) * sq * 0.12 | |
| 293 | + base_x, base_y = tip_x - math.cos(angle) * head * 0.8, tip_y - math.sin(angle) * head * 0.8 | |
| 294 | + cr.new_path() | |
| 295 | + cr.set_source_rgba(*rgb, 0.8) | |
| 296 | + cr.set_line_width(sq * 0.13) | |
| 297 | + cr.set_line_cap(cairo.LINE_CAP_ROUND) | |
| 298 | + cr.move_to(x0 + math.cos(angle) * sq * 0.2, y0 + math.sin(angle) * sq * 0.2) | |
| 299 | + cr.line_to(base_x, base_y) | |
| 300 | + cr.stroke() | |
| 301 | + cr.move_to(tip_x, tip_y) | |
| 302 | + for side in (-0.5, 0.5): | |
| 303 | + cr.line_to(tip_x - head * math.cos(angle + side), tip_y - head * math.sin(angle + side)) | |
| 304 | + cr.close_path() | |
| 305 | + cr.fill() | |
| 306 | + cr.set_line_cap(cairo.LINE_CAP_BUTT) | |
| 307 | + | |
| 308 | + def _fill_square(self, cr, square, sq, rgba): | |
| 309 | + x, y = self._square_origin(square) | |
| 310 | + cr.set_source_rgba(*rgba) | |
| 311 | + cr.rectangle(x, y, sq, sq) | |
| 312 | + cr.fill() | |
| 313 | + | |
| 314 | + def _glow(self, cr, square, sq, rgb, alpha): | |
| 315 | + x, y = self._square_origin(square) | |
| 316 | + cx, cy = x + sq / 2, y + sq / 2 | |
| 317 | + grad = cairo.RadialGradient(cx, cy, sq * 0.05, cx, cy, sq * 0.72) | |
| 318 | + grad.add_color_stop_rgba(0, *rgb, alpha) | |
| 319 | + grad.add_color_stop_rgba(0.6, *rgb, alpha * 0.5) | |
| 320 | + grad.add_color_stop_rgba(1, *rgb, 0) | |
| 321 | + cr.save() | |
| 322 | + cr.rectangle(x, y, sq, sq) | |
| 323 | + cr.clip() | |
| 324 | + cr.set_source(grad) | |
| 325 | + cr.paint() | |
| 326 | + cr.restore() | |
| 327 | + | |
| 328 | + def _draw_piece(self, cr, piece, x, y, size): | |
| 329 | + rect = Rsvg.Rectangle() | |
| 330 | + rect.x, rect.y, rect.width, rect.height = x, y, size, size | |
| 331 | + self._pieces[piece.symbol()].render_document(cr, rect) | |
| 332 | + | |
| 333 | + def _draw_coordinates(self, cr, sq): | |
| 334 | + light_rgb, dark_rgb = self._square_colors # Beschriftung in der Gegenfarbe des Felds | |
| 335 | + cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) | |
| 336 | + cr.set_font_size(sq * 0.16) | |
| 337 | + bottom_rank = 7 if self.flipped else 0 | |
| 338 | + left_file = 7 if self.flipped else 0 | |
| 339 | + for f in range(8): | |
| 340 | + square = chess.square(f, bottom_rank) | |
| 341 | + x, y = self._square_origin(square) | |
| 342 | + light = (f + bottom_rank) % 2 == 1 | |
| 343 | + cr.set_source_rgb(*(dark_rgb if light else light_rgb)) | |
| 344 | + cr.move_to(x + sq * 0.80, y + sq * 0.94) | |
| 345 | + cr.show_text(chess.FILE_NAMES[f]) | |
| 346 | + for r in range(8): | |
| 347 | + square = chess.square(left_file, r) | |
| 348 | + x, y = self._square_origin(square) | |
| 349 | + light = (left_file + r) % 2 == 1 | |
| 350 | + cr.set_source_rgb(*(dark_rgb if light else light_rgb)) | |
| 351 | + cr.move_to(x + sq * 0.05, y + sq * 0.2) | |
| 352 | + cr.show_text(chess.RANK_NAMES[r]) | |
| 353 | + | |
| 354 | + def _draw_captures(self, cr, ox, oy, sq): | |
| 355 | + captured = self._captured_by() | |
| 356 | + bottom = chess.BLACK if self.flipped else chess.WHITE | |
| 357 | + diff = self._material(chess.WHITE) - self._material(chess.BLACK) | |
| 358 | + size = sq * STRIP * 0.9 | |
| 359 | + for color in (chess.WHITE, chess.BLACK): | |
| 360 | + if color == bottom: | |
| 361 | + y = oy + 8 * sq + sq * STRIP * 0.05 | |
| 362 | + else: | |
| 363 | + y = oy - sq * STRIP * 0.95 | |
| 364 | + x = ox | |
| 365 | + pieces = sorted(captured[color], key=lambda p: (VALUE[p.piece_type], p.piece_type)) | |
| 366 | + previous = None | |
| 367 | + for piece in pieces: | |
| 368 | + if previous is not None: | |
| 369 | + x += size * (0.45 if piece.piece_type == previous else 0.85) | |
| 370 | + self._draw_piece(cr, piece, x, y, size) | |
| 371 | + previous = piece.piece_type | |
| 372 | + advantage = diff if color == chess.WHITE else -diff | |
| 373 | + if advantage > 0: | |
| 374 | + x += size * (1.0 if pieces else 0.0) | |
| 375 | + cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) | |
| 376 | + cr.set_font_size(size * 0.55) | |
| 377 | + cr.set_source_rgba(*self._fg(), 0.7) | |
| 378 | + cr.move_to(x + size * 0.1, y + size * 0.72) | |
| 379 | + cr.show_text(f"+{advantage}") | |
| 380 | + | |
| 381 | + def _draw_players(self, cr, ox, oy, sq): | |
| 382 | + """Name und Uhr rechts in den Streifen über und unter dem Brett.""" | |
| 383 | + if not self.names and not self.clocks: | |
| 384 | + return | |
| 385 | + bottom = chess.BLACK if self.flipped else chess.WHITE | |
| 386 | + h = sq * STRIP | |
| 387 | + fg = self._fg() | |
| 388 | + for color in (chess.WHITE, chess.BLACK): | |
| 389 | + y = oy + 8 * sq if color == bottom else oy - h | |
| 390 | + right = ox + 8 * sq | |
| 391 | + if self.clocks and color in self.clocks: | |
| 392 | + right = self._draw_clock(cr, right, y, h, self.clocks[color], self.clock_running == color, fg) | |
| 393 | + if self.names and color in self.names: | |
| 394 | + bold = self.turn_marker == color | |
| 395 | + cr.select_font_face( | |
| 396 | + "Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD if bold else cairo.FONT_WEIGHT_NORMAL) | |
| 397 | + cr.set_font_size(h * 0.45) | |
| 398 | + text = self.names[color] | |
| 399 | + ext = cr.text_extents(text) | |
| 400 | + cr.set_source_rgba(*fg, 0.75) | |
| 401 | + cr.move_to(right - ext.x_advance, y + h / 2 + ext.height / 2) | |
| 402 | + cr.show_text(text) | |
| 403 | + | |
| 404 | + def _draw_clock(self, cr, right, y, h, ms, running, fg): | |
| 405 | + """Uhr als zwei zusammengewachsene Felder: Minuten | Sekunden. Gibt die linke Kante zurück.""" | |
| 406 | + minutes, seconds = clock_parts(ms) | |
| 407 | + low = ms < LOW_TIME_MS | |
| 408 | + cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) | |
| 409 | + cr.set_font_size(h * 0.52) | |
| 410 | + pad = h * 0.22 | |
| 411 | + # feste Mindestbreiten, damit die Uhr beim Ticken nicht springt | |
| 412 | + left_w = max(cr.text_extents("00").x_advance, cr.text_extents(minutes).x_advance) + 2 * pad | |
| 413 | + right_w = max(cr.text_extents("00").x_advance, cr.text_extents(seconds).x_advance) + 2 * pad | |
| 414 | + bh = h * 0.78 | |
| 415 | + by = y + (h - bh) / 2 | |
| 416 | + bx = right - left_w - right_w | |
| 417 | + radius = bh * 0.3 | |
| 418 | + | |
| 419 | + if running: | |
| 420 | + cr.set_source_rgb(*(CLOCK_LOW if low else CLOCK_RUNNING)) | |
| 421 | + else: | |
| 422 | + cr.set_source_rgba(*fg, 0.10) | |
| 423 | + _rounded(cr, bx, by, left_w + right_w, bh, radius) | |
| 424 | + cr.fill() | |
| 425 | + # Naht zwischen Minuten und Sekunden | |
| 426 | + cr.set_source_rgba(1, 1, 1, 0.35) if running else cr.set_source_rgba(*fg, 0.18) | |
| 427 | + cr.rectangle(bx + left_w - 0.75, by + bh * 0.18, 1.5, bh * 0.64) | |
| 428 | + cr.fill() | |
| 429 | + | |
| 430 | + if running: | |
| 431 | + cr.set_source_rgb(1, 1, 1) | |
| 432 | + else: | |
| 433 | + cr.set_source_rgba(*fg, 0.85) | |
| 434 | + digits = cr.text_extents("0") | |
| 435 | + baseline = by + bh / 2 + digits.height / 2 | |
| 436 | + for text, x0, width in ((minutes, bx, left_w), (seconds, bx + left_w, right_w)): | |
| 437 | + ext = cr.text_extents(text) | |
| 438 | + cr.move_to(x0 + (width - ext.x_advance) / 2, baseline) | |
| 439 | + cr.show_text(text) | |
| 440 | + return bx - h * 0.3 | |
| 441 | + | |
| 442 | + def _draw_eval_bar(self, cr, ox, oy, sq): | |
| 443 | + """Senkrechter Weiß/Schwarz-Balken links: Weiß wächst von der eigenen Seite her.""" | |
| 444 | + width = sq * BAR * 0.75 | |
| 445 | + x = ox - sq * BAR | |
| 446 | + height = 8 * sq | |
| 447 | + white = height * max(0.0, min(100.0, self.eval_bar)) / 100.0 | |
| 448 | + split = oy + white if self.flipped else oy + height - white | |
| 449 | + cr.set_source_rgb(*BAR_BLACK) | |
| 450 | + cr.rectangle(x, oy, width, height) | |
| 451 | + cr.fill() | |
| 452 | + cr.set_source_rgb(*BAR_WHITE) | |
| 453 | + cr.rectangle(x, oy if self.flipped else split, width, white) | |
| 454 | + cr.fill() | |
| 455 | + cr.set_source_rgba(0.5, 0.5, 0.5, 0.8) | |
| 456 | + cr.rectangle(x, oy + height / 2 - 0.5, width, 1) | |
| 457 | + cr.fill() | |
| 458 | + | |
| 459 | + def _draw_badge(self, cr, square, text, sq): | |
| 460 | + x, y = self._square_origin(square) | |
| 461 | + r = sq * 0.19 | |
| 462 | + cx, cy = x + sq - r * 0.9, y + r * 0.9 | |
| 463 | + cr.new_path() | |
| 464 | + cr.set_source_rgba(0, 0, 0, 0.3) | |
| 465 | + cr.arc(cx + 1.5, cy + 1.5, r, 0, 2 * math.pi) | |
| 466 | + cr.fill() | |
| 467 | + cr.set_source_rgb(*BADGE.get(text, (0.4, 0.4, 0.4))) | |
| 468 | + cr.arc(cx, cy, r, 0, 2 * math.pi) | |
| 469 | + cr.fill() | |
| 470 | + cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) | |
| 471 | + cr.set_font_size(r * (1.05 if len(text) == 1 else 0.95)) | |
| 472 | + ext = cr.text_extents(text) | |
| 473 | + cr.set_source_rgb(1, 1, 1) | |
| 474 | + cr.move_to(cx - ext.width / 2 - ext.x_bearing, cy - ext.height / 2 - ext.y_bearing) | |
| 475 | + cr.show_text(text) | |
| 476 | + | |
| 477 | + | |
| 478 | +class Diagram(BoardPainter): | |
| 479 | + """Feste Stellung als Bild – für SVG, PNG und PDF. | |
| 480 | + | |
| 481 | + ``names`` (Spielerköpfe) blendet die Streifen mit Namen und geschlagenen Figuren ein, | |
| 482 | + ``eval_bar`` den Gewinnchance-Balken. | |
| 483 | + """ | |
| 484 | + | |
| 485 | + margin = 0 | |
| 486 | + | |
| 487 | + def __init__(self, board, theme=BUILTIN_THEME, scheme=DEFAULT_SCHEME, flipped=False, | |
| 488 | + last_move=True, badge=None, names=None, eval_bar=None): | |
| 489 | + self._painter_init(theme, scheme) | |
| 490 | + self.board = board | |
| 491 | + self.flipped = flipped | |
| 492 | + self.last_move = board.peek() if last_move and board.move_stack else None | |
| 493 | + self.badge = badge | |
| 494 | + self.names = names | |
| 495 | + self.strips = bool(names) | |
| 496 | + self.eval_bar = eval_bar | |
| 497 | + self._area = (400, 400) | |
| 498 | + | |
| 499 | + def _size(self): | |
| 500 | + return self._area | |
| 501 | + | |
| 502 | + def aspect(self): | |
| 503 | + """Höhe / Breite des Bilds.""" | |
| 504 | + strip = 2 * STRIP / 8 if self.strips else 0 | |
| 505 | + bar = BAR / 8 if self.eval_bar is not None else 0 | |
| 506 | + return (1 + strip) / (1 + bar) | |
| 507 | + | |
| 508 | + def render(self, cr, x, y, width): | |
| 509 | + """Zeichnet das Diagramm mit der Breite ``width`` an (x, y); gibt die Höhe zurück.""" | |
| 510 | + height = width * self.aspect() | |
| 511 | + self._area = (width, height) | |
| 512 | + cr.save() | |
| 513 | + cr.translate(x, y) | |
| 514 | + self.paint(cr) | |
| 515 | + cr.restore() | |
| 516 | + return height | |
| 517 | + | |
| 518 | + def svg(self, width=360): | |
| 519 | + out = io.BytesIO() | |
| 520 | + surface = cairo.SVGSurface(out, width, width * self.aspect()) | |
| 521 | + surface.set_document_unit(cairo.SVGUnit.PX) | |
| 522 | + cr = cairo.Context(surface) | |
| 523 | + self.render(cr, 0, 0, width) | |
| 524 | + surface.finish() | |
| 525 | + return out.getvalue() | |
| 526 | + | |
| 527 | + def png(self, width=800): | |
| 528 | + height = math.ceil(width * self.aspect()) | |
| 529 | + surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) | |
| 530 | + cr = cairo.Context(surface) | |
| 531 | + self.render(cr, 0, 0, width) | |
| 532 | + out = io.BytesIO() | |
| 533 | + surface.write_to_png(out) | |
| 534 | + return out.getvalue() | |
| 535 | + | |
| 536 | + | |
| 537 | +LOW_TIME_MS = 20000 # darunter wird die laufende Uhr rot | |
| 538 | +CLOCK_RUNNING = (0.18, 0.55, 0.34) | |
| 539 | +CLOCK_LOW = (0.80, 0.20, 0.18) | |
| 540 | + | |
| 541 | + | |
| 542 | +def clock_parts(ms): | |
| 543 | + """Minuten- und Sekundenfeld, beide zweistellig: ("04", "37"); ab einer Stunde ("1:02", "37").""" | |
| 544 | + secs = max(0, int(ms)) // 1000 | |
| 545 | + if secs >= 3600: | |
| 546 | + return f"{secs // 3600}:{secs // 60 % 60:02d}", f"{secs % 60:02d}" | |
| 547 | + return f"{secs // 60:02d}", f"{secs % 60:02d}" | |
| 548 | + | |
| 549 | + | |
| 550 | +def _rounded(cr, x, y, w, h, r): | |
| 551 | + cr.new_sub_path() | |
| 552 | + cr.arc(x + w - r, y + r, r, -math.pi / 2, 0) | |
| 553 | + cr.arc(x + w - r, y + h - r, r, 0, math.pi / 2) | |
| 554 | + cr.arc(x + r, y + h - r, r, math.pi / 2, math.pi) | |
| 555 | + cr.arc(x + r, y + r, r, math.pi, 3 * math.pi / 2) | |
| 556 | + cr.close_path() | |
added schach/export.py +777 −0
| @@ -0,0 +1,777 @@ | ||
| 1 | +"""Export einer Partie oder Stellung: PGN, FEN, SVG, PNG, LaTeX, PDF, HTML, ASCII. | |
| 2 | + | |
| 3 | +Ohne Gtk, damit es sich testen lässt; der Dialog (exportdialog.py) sammelt nur die | |
| 4 | +Optionen ein und entscheidet, ob das Ergebnis in eine Datei oder in die Zwischenablage geht. | |
| 5 | + | |
| 6 | +Stellungen werden über ``plies`` angegeben: die Zahl der gespielten Halbzüge | |
| 7 | +(0 = Ausgangsstellung, len(move_stack) = aktuelle Stellung). | |
| 8 | +""" | |
| 9 | + | |
| 10 | +import base64 | |
| 11 | +import dataclasses | |
| 12 | +import datetime | |
| 13 | +import html as html_mod | |
| 14 | +import io | |
| 15 | +import json | |
| 16 | +import os | |
| 17 | +import shutil | |
| 18 | +import subprocess | |
| 19 | +import tempfile | |
| 20 | +import textwrap | |
| 21 | + | |
| 22 | +import chess | |
| 23 | +import chess.pgn | |
| 24 | + | |
| 25 | +from . import notation, savegames | |
| 26 | +from .diagram import ( | |
| 27 | + BADGE, BAR_BLACK, BAR_WHITE, BUILTIN_THEME, CHECK, DEFAULT_SCHEME, Diagram, hex_color, piece_svg, | |
| 28 | + scheme_colors, | |
| 29 | +) | |
| 30 | + | |
| 31 | + | |
| 32 | +class ExportError(Exception): | |
| 33 | + """Export nicht möglich; die Meldung ist für Menschen gedacht.""" | |
| 34 | + | |
| 35 | + | |
| 36 | +@dataclasses.dataclass | |
| 37 | +class Options: | |
| 38 | + scope: str = "position" # "position" oder "game" | |
| 39 | + plies: int | None = None # gezeigte Stellung; None = aktuelle | |
| 40 | + notation: str = notation.DEFAULT | |
| 41 | + symbols: bool = True # Zugzeichen !! ! ?! ? ?? | |
| 42 | + evals: bool = True # Gewinnchance-Balken | |
| 43 | + players: bool = True # Spielerköpfe: Namen, Datum, Ergebnis | |
| 44 | + last_move: bool = True # letzten Zug markieren | |
| 45 | + flipped: bool = False # Schwarz unten | |
| 46 | + theme: str = BUILTIN_THEME | |
| 47 | + scheme: str = DEFAULT_SCHEME | |
| 48 | + | |
| 49 | + | |
| 50 | +@dataclasses.dataclass(frozen=True) | |
| 51 | +class Format: | |
| 52 | + label: str | |
| 53 | + extension: str | |
| 54 | + mime: str | |
| 55 | + scopes: tuple # ("position", "game") | |
| 56 | + options: frozenset # welche Schalter aus Options hier wirken | |
| 57 | + binary: bool = False | |
| 58 | + clipboard: bool = True | |
| 59 | + | |
| 60 | + | |
| 61 | +_BOARD = frozenset({"last_move", "flipped"}) | |
| 62 | +FORMATS = { | |
| 63 | + "pgn": Format("PGN", "pgn", "application/vnd.chess-pgn", ("position", "game"), frozenset({"symbols", "evals"})), | |
| 64 | + "fen": Format("FEN", "fen", "text/plain", ("position",), frozenset()), | |
| 65 | + "svg": Format("SVG-Bild", "svg", "image/svg+xml", ("position",), _BOARD | {"symbols", "evals", "players"}), | |
| 66 | + "png": Format("PNG-Bild", "png", "image/png", ("position",), _BOARD | {"symbols", "evals", "players"}, binary=True), | |
| 67 | + "latex": Format("LaTeX (xskak)", "tex", "text/x-tex", ("position", "game"), _BOARD | {"symbols", "players"}), | |
| 68 | + "pdf": Format("PDF", "pdf", "application/pdf", ("position", "game"), | |
| 69 | + _BOARD | {"symbols", "evals", "players"}, binary=True, clipboard=False), | |
| 70 | + "pdf-latex": Format("PDF über LaTeX", "pdf", "application/pdf", ("position", "game"), | |
| 71 | + _BOARD | {"symbols", "players"}, binary=True, clipboard=False), | |
| 72 | + "html": Format("HTML-Seite", "html", "text/html", ("position", "game"), _BOARD | {"symbols", "evals", "players"}), | |
| 73 | + "ascii": Format("ASCII-Art", "txt", "text/plain", ("position", "game"), {"flipped", "symbols", "players"}), | |
| 74 | +} | |
| 75 | + | |
| 76 | + | |
| 77 | +def latex_available(): | |
| 78 | + return shutil.which("pdflatex") is not None | |
| 79 | + | |
| 80 | + | |
| 81 | +# --- Grundlagen ------------------------------------------------------------- | |
| 82 | + | |
| 83 | + | |
| 84 | +def _plies(state, opts): | |
| 85 | + n = len(state.board.move_stack) | |
| 86 | + return n if opts.plies is None else max(0, min(n, opts.plies)) | |
| 87 | + | |
| 88 | + | |
| 89 | +def board_at(state, plies): | |
| 90 | + board = state.board.copy() | |
| 91 | + while len(board.move_stack) > plies: | |
| 92 | + board.pop() | |
| 93 | + return board | |
| 94 | + | |
| 95 | + | |
| 96 | +@dataclasses.dataclass | |
| 97 | +class Info: | |
| 98 | + white: str | |
| 99 | + black: str | |
| 100 | + event: str | |
| 101 | + date: str # TT.MM.JJJJ | |
| 102 | + result: str # "1-0", "0-1", "1/2-1/2", "*" | |
| 103 | + end_text: str # z. B. "Schwarz hat aufgegeben." | |
| 104 | + | |
| 105 | + @property | |
| 106 | + def title(self): | |
| 107 | + return f"{self.white} – {self.black}" | |
| 108 | + | |
| 109 | + | |
| 110 | +def info(state): | |
| 111 | + """Namen, Anlass, Datum und Ergebnis – dieselben Angaben wie im PGN-Kopf.""" | |
| 112 | + headers = chess.pgn.read_headers(io.StringIO(savegames.to_pgn(state))) | |
| 113 | + date = datetime.date.today().strftime("%d.%m.%Y") | |
| 114 | + return Info( | |
| 115 | + white=headers.get("White", "?"), black=headers.get("Black", "?"), | |
| 116 | + event=headers.get("Event", ""), date=date, result=headers.get("Result", "*"), | |
| 117 | + end_text=state.final_text or "", | |
| 118 | + ) | |
| 119 | + | |
| 120 | + | |
| 121 | +RESULT_TEXT = {"1-0": "1–0", "0-1": "0–1", "1/2-1/2": "½–½", "*": ""} | |
| 122 | + | |
| 123 | + | |
| 124 | +def caption(board, style=notation.DEFAULT): | |
| 125 | + """„Stellung nach 12… Sf6 · Weiß am Zug“.""" | |
| 126 | + turn = "Weiß am Zug" if board.turn == chess.WHITE else "Schwarz am Zug" | |
| 127 | + if board.is_checkmate(): | |
| 128 | + turn = "Schwarz ist matt" if board.turn == chess.BLACK else "Weiß ist matt" | |
| 129 | + elif board.is_stalemate(): | |
| 130 | + turn = "Patt" | |
| 131 | + if not board.move_stack: | |
| 132 | + return f"Ausgangsstellung · {turn}" | |
| 133 | + before = board.copy() | |
| 134 | + last = before.pop() | |
| 135 | + return f"Stellung nach {notation.label(before, last, style)} · {turn}" | |
| 136 | + | |
| 137 | + | |
| 138 | +def _badge(state, board, opts): | |
| 139 | + if not (opts.symbols and board.move_stack): | |
| 140 | + return None | |
| 141 | + symbol = state.symbols.get(len(board.move_stack) - 1) | |
| 142 | + return (board.peek().to_square, symbol) if symbol else None | |
| 143 | + | |
| 144 | + | |
| 145 | +def _eval(state, plies, opts): | |
| 146 | + if not opts.evals or plies == 0: | |
| 147 | + return None | |
| 148 | + return state.evals.get(plies - 1) | |
| 149 | + | |
| 150 | + | |
| 151 | +def diagram(state, opts, plies=None, players=None): | |
| 152 | + plies = _plies(state, opts) if plies is None else plies | |
| 153 | + board = board_at(state, plies) | |
| 154 | + names = None | |
| 155 | + if opts.players if players is None else players: | |
| 156 | + i = info(state) | |
| 157 | + names = {chess.WHITE: i.white, chess.BLACK: i.black} | |
| 158 | + return Diagram( | |
| 159 | + board, theme=opts.theme, scheme=opts.scheme, flipped=opts.flipped, last_move=opts.last_move, | |
| 160 | + badge=_badge(state, board, opts), names=names, eval_bar=_eval(state, plies, opts), | |
| 161 | + ) | |
| 162 | + | |
| 163 | + | |
| 164 | +def _moves(state): | |
| 165 | + """[(halbzug, brett vor dem zug, zug)] der ganzen Partie.""" | |
| 166 | + replay = state.board.root() | |
| 167 | + result = [] | |
| 168 | + for ply, move in enumerate(state.board.move_stack): | |
| 169 | + result.append((ply, replay.copy(stack=False), move)) | |
| 170 | + replay.push(move) | |
| 171 | + return result | |
| 172 | + | |
| 173 | + | |
| 174 | +def move_text(state, opts, start=0, stop=None, san_style=None): | |
| 175 | + """Zugfolge „1. e4 e5 2. Sf3 …“ von Halbzug ``start`` bis vor ``stop``.""" | |
| 176 | + words = [] | |
| 177 | + for ply, before, move in _moves(state)[start:stop]: | |
| 178 | + if before.turn == chess.WHITE: | |
| 179 | + words.append(f"{before.fullmove_number}.") | |
| 180 | + elif not words: | |
| 181 | + words.append(f"{before.fullmove_number}...") | |
| 182 | + san = before.san(move) if san_style == "pgn" else notation.move(before, move, opts.notation) | |
| 183 | + if opts.symbols and ply in state.symbols: | |
| 184 | + san += state.symbols[ply] | |
| 185 | + words.append(san) | |
| 186 | + return " ".join(words) | |
| 187 | + | |
| 188 | + | |
| 189 | +# --- Textformate ------------------------------------------------------------- | |
| 190 | + | |
| 191 | + | |
| 192 | +def to_fen(state, opts): | |
| 193 | + return board_at(state, _plies(state, opts)).fen() + "\n" | |
| 194 | + | |
| 195 | + | |
| 196 | +def to_pgn(state, opts): | |
| 197 | + game = chess.pgn.read_game(io.StringIO(savegames.to_pgn(state))) | |
| 198 | + if opts.scope == "position": | |
| 199 | + board = board_at(state, _plies(state, opts)) | |
| 200 | + position = chess.pgn.Game() | |
| 201 | + for key in ("Event", "Date", "White", "Black"): | |
| 202 | + position.headers[key] = game.headers.get(key, "?") | |
| 203 | + position.headers["Result"] = "*" | |
| 204 | + position.setup(board) | |
| 205 | + return str(position) + "\n" | |
| 206 | + for node in game.mainline(): | |
| 207 | + if not opts.symbols: | |
| 208 | + node.nags.clear() | |
| 209 | + if not opts.evals: | |
| 210 | + node.comment = "" | |
| 211 | + return str(game) + "\n" | |
| 212 | + | |
| 213 | + | |
| 214 | +_ASCII_DE = {"K": "K", "Q": "D", "R": "T", "B": "L", "N": "S", "P": "B"} | |
| 215 | + | |
| 216 | + | |
| 217 | +def _ascii_board(board, opts): | |
| 218 | + rows = [" +-----------------+"] | |
| 219 | + ranks = range(8) if opts.flipped else range(7, -1, -1) | |
| 220 | + files = list(range(7, -1, -1)) if opts.flipped else list(range(8)) | |
| 221 | + for rank in ranks: | |
| 222 | + cells = [] | |
| 223 | + for f in files: | |
| 224 | + piece = board.piece_at(chess.square(f, rank)) | |
| 225 | + if piece is None: | |
| 226 | + cells.append(".") | |
| 227 | + else: | |
| 228 | + letter = piece.symbol().upper() | |
| 229 | + if opts.notation == "de": | |
| 230 | + letter = _ASCII_DE[letter] | |
| 231 | + cells.append(letter if piece.color == chess.WHITE else letter.lower()) | |
| 232 | + rows.append(f"{rank + 1} | {' '.join(cells)} |") | |
| 233 | + rows.append(" +-----------------+") | |
| 234 | + rows.append(" " + " ".join(chess.FILE_NAMES[f] for f in files)) | |
| 235 | + return rows | |
| 236 | + | |
| 237 | + | |
| 238 | +def to_ascii(state, opts): | |
| 239 | + plies = _plies(state, opts) | |
| 240 | + board = board_at(state, plies) | |
| 241 | + lines = [] | |
| 242 | + i = info(state) | |
| 243 | + if opts.players: | |
| 244 | + result = RESULT_TEXT.get(i.result, "") | |
| 245 | + lines += [f"{i.title}{' ' + result if result else ''}", i.date, ""] | |
| 246 | + lines += _ascii_board(board, opts) | |
| 247 | + lines += ["", caption(board, opts.notation), "FEN: " + board.fen()] | |
| 248 | + if opts.scope == "game" and state.board.move_stack: | |
| 249 | + text = move_text(state, opts) | |
| 250 | + if i.result != "*": | |
| 251 | + text += " " + RESULT_TEXT[i.result] | |
| 252 | + lines += [""] + textwrap.wrap(text, 72, break_on_hyphens=False) | |
| 253 | + if i.end_text: | |
| 254 | + lines.append(i.end_text) | |
| 255 | + return "\n".join(lines) + "\n" | |
| 256 | + | |
| 257 | + | |
| 258 | +# --- LaTeX ------------------------------------------------------------------- | |
| 259 | + | |
| 260 | +_TEX_ESCAPE = { | |
| 261 | + "\\": r"\textbackslash{}", "&": r"\&", "%": r"\%", "$": r"\$", "#": r"\#", "_": r"\_", | |
| 262 | + "{": r"\{", "}": r"\}", "~": r"\textasciitilde{}", "^": r"\textasciicircum{}", | |
| 263 | +} | |
| 264 | + | |
| 265 | + | |
| 266 | +def _tex(text): | |
| 267 | + return "".join(_TEX_ESCAPE.get(c, c) for c in text) | |
| 268 | + | |
| 269 | + | |
| 270 | +def _tex_board(board, opts, with_fen): | |
| 271 | + keys = ["showmover=true"] | |
| 272 | + if with_fen: | |
| 273 | + keys.insert(0, f"setfen={board.fen()}") | |
| 274 | + if opts.flipped: | |
| 275 | + keys.append("inverse") | |
| 276 | + if opts.last_move and board.move_stack: | |
| 277 | + last = board.peek() | |
| 278 | + keys.append("pgfstyle=color,color=yellow!45") | |
| 279 | + keys.append(f"markfields={{{chess.square_name(last.from_square)},{chess.square_name(last.to_square)}}}") | |
| 280 | + return "\\begin{center}\n\\chessboard[" + ",\n ".join(keys) + "]\n\\end{center}\n" | |
| 281 | + | |
| 282 | + | |
| 283 | +def to_latex(state, opts): | |
| 284 | + plies = _plies(state, opts) | |
| 285 | + board = board_at(state, plies) | |
| 286 | + i = info(state) | |
| 287 | + out = [ | |
| 288 | + "\\documentclass[a4paper]{article}", | |
| 289 | + "\\usepackage[T1]{fontenc}", | |
| 290 | + "\\usepackage[utf8]{inputenc}", | |
| 291 | + "\\usepackage{xskak}", | |
| 292 | + "\\xskakset{style=UF}", | |
| 293 | + "\\begin{document}", | |
| 294 | + "", | |
| 295 | + ] | |
| 296 | + if opts.players: | |
| 297 | + out.append(f"\\section*{{{_tex(i.white)} -- {_tex(i.black)}}}") | |
| 298 | + meta = [m for m in (i.event, i.date) if m and m != "?"] | |
| 299 | + out.append("\\noindent " + _tex(" · ".join(meta)).replace("·", "\\textperiodcentered{}") + "\n") | |
| 300 | + root = state.board.root() | |
| 301 | + setfen = "" if root.fen() == chess.STARTING_FEN else f"[setfen={root.fen()}]" | |
| 302 | + if opts.scope == "game" and state.board.move_stack: | |
| 303 | + out.append(f"\\newchessgame{setfen}") | |
| 304 | + before = move_text(state, _pgn_opts(opts), 0, plies, san_style="pgn") | |
| 305 | + after = move_text(state, _pgn_opts(opts), plies, None, san_style="pgn") | |
| 306 | + if before: | |
| 307 | + out.append(f"\\noindent\\mainline{{{before}}}\n") | |
| 308 | + out.append(_tex_board(board, opts, with_fen=False)) | |
| 309 | + out.append(f"\\noindent {_tex(caption(board, opts.notation))}\n") | |
| 310 | + if after: | |
| 311 | + out.append(f"\\noindent\\mainline{{{after}}}\n") | |
| 312 | + if i.result != "*" or i.end_text: | |
| 313 | + out.append("\\noindent\\textbf{" + _tex(" ".join(filter(None, [RESULT_TEXT[i.result], i.end_text]))) + "}\n") | |
| 314 | + else: | |
| 315 | + out.append(_tex_board(board, opts, with_fen=True)) | |
| 316 | + out.append(f"\\noindent {_tex(caption(board, opts.notation))}\n") | |
| 317 | + out.append(f"\\noindent\\texttt{{\\small {_tex(board.fen())}}}\n") | |
| 318 | + out += ["\\end{document}", ""] | |
| 319 | + return "\n".join(out) | |
| 320 | + | |
| 321 | + | |
| 322 | +def _pgn_opts(opts): | |
| 323 | + """xskak liest englische Züge; die Anzeige setzt es selbst als Figurinen.""" | |
| 324 | + return dataclasses.replace(opts, notation="en") | |
| 325 | + | |
| 326 | + | |
| 327 | +def to_pdf_latex(state, opts): | |
| 328 | + if not latex_available(): | |
| 329 | + raise ExportError("pdflatex ist nicht installiert.") | |
| 330 | + source = to_latex(state, opts) | |
| 331 | + with tempfile.TemporaryDirectory(prefix="schach-") as tmp: | |
| 332 | + with open(os.path.join(tmp, "partie.tex"), "w") as fh: | |
| 333 | + fh.write(source) | |
| 334 | + try: | |
| 335 | + run = subprocess.run( | |
| 336 | + ["pdflatex", "-interaction=nonstopmode", "-halt-on-error", "-no-shell-escape", "partie.tex"], | |
| 337 | + cwd=tmp, capture_output=True, text=True, timeout=90, | |
| 338 | + ) | |
| 339 | + except subprocess.TimeoutExpired: | |
| 340 | + raise ExportError("pdflatex hat zu lange gebraucht.") from None | |
| 341 | + pdf = os.path.join(tmp, "partie.pdf") | |
| 342 | + if run.returncode != 0 or not os.path.exists(pdf): | |
| 343 | + errors = [line for line in run.stdout.splitlines() if line.startswith("!")] | |
| 344 | + detail = errors[0][1:].strip() if errors else "unbekannter Fehler" | |
| 345 | + if "xskak.sty" in run.stdout and "not found" in run.stdout: | |
| 346 | + detail = "Das LaTeX-Paket xskak fehlt." | |
| 347 | + raise ExportError(f"pdflatex: {detail}") | |
| 348 | + with open(pdf, "rb") as fh: | |
| 349 | + return fh.read() | |
| 350 | + | |
| 351 | + | |
| 352 | +# --- PDF mit Cairo ------------------------------------------------------------- | |
| 353 | + | |
| 354 | +A4 = (595.28, 841.89) | |
| 355 | +PDF_MARGIN = 50 | |
| 356 | + | |
| 357 | + | |
| 358 | +def to_pdf(state, opts): | |
| 359 | + import cairo | |
| 360 | + import gi | |
| 361 | + | |
| 362 | + gi.require_version("Pango", "1.0") | |
| 363 | + gi.require_version("PangoCairo", "1.0") | |
| 364 | + from gi.repository import Pango, PangoCairo | |
| 365 | + | |
| 366 | + out = io.BytesIO() | |
| 367 | + width, height = A4 | |
| 368 | + surface = cairo.PDFSurface(out, width, height) | |
| 369 | + i = info(state) | |
| 370 | + surface.set_metadata(cairo.PDF_METADATA_TITLE, i.title if opts.players else "Schach") | |
| 371 | + surface.set_metadata(cairo.PDF_METADATA_CREATOR, "Schach") | |
| 372 | + cr = cairo.Context(surface) | |
| 373 | + left, right = PDF_MARGIN, width - PDF_MARGIN | |
| 374 | + text_width = right - left | |
| 375 | + | |
| 376 | + def text(markup, x, y, size=10, w=None, bold=False, family="Sans", align=Pango.Alignment.LEFT): | |
| 377 | + layout = PangoCairo.create_layout(cr) | |
| 378 | + desc = Pango.FontDescription.from_string(f"{family} {'Bold ' if bold else ''}{size}") | |
| 379 | + layout.set_font_description(desc) | |
| 380 | + if w is not None: | |
| 381 | + layout.set_width(int(w * Pango.SCALE)) | |
| 382 | + layout.set_wrap(Pango.WrapMode.WORD_CHAR) | |
| 383 | + layout.set_alignment(align) | |
| 384 | + layout.set_markup(markup, -1) | |
| 385 | + cr.set_source_rgb(0.1, 0.1, 0.1) | |
| 386 | + cr.move_to(x, y) | |
| 387 | + PangoCairo.show_layout(cr, layout) | |
| 388 | + return layout.get_pixel_extents()[1].height | |
| 389 | + | |
| 390 | + y = PDF_MARGIN | |
| 391 | + if opts.players: | |
| 392 | + y += text(html_mod.escape(i.title), left, y, size=18, bold=True, w=text_width) | |
| 393 | + meta = [m for m in (i.event, i.date, RESULT_TEXT.get(i.result, ""), i.end_text) if m and m != "?"] | |
| 394 | + y += text(html_mod.escape(" · ".join(meta)), left, y + 2, size=10, w=text_width) + 14 | |
| 395 | + | |
| 396 | + plies = _plies(state, opts) | |
| 397 | + board = board_at(state, plies) | |
| 398 | + game = opts.scope == "game" and state.board.move_stack | |
| 399 | + dia = diagram(state, opts, plies) | |
| 400 | + dia_width = 300 if game else 420 | |
| 401 | + if dia.aspect() * dia_width > height - y - PDF_MARGIN - 60: | |
| 402 | + dia_width = (height - y - PDF_MARGIN - 60) / dia.aspect() | |
| 403 | + y += dia.render(cr, left + (text_width - dia_width) / 2, y, dia_width) + 8 | |
| 404 | + y += text(html_mod.escape(caption(board, opts.notation)), left, y, size=10, w=text_width, | |
| 405 | + align=Pango.Alignment.CENTER) + 4 | |
| 406 | + if not game: | |
| 407 | + text(html_mod.escape(board.fen()), left, y, size=9, w=text_width, family="Monospace", | |
| 408 | + align=Pango.Alignment.CENTER) | |
| 409 | + surface.finish() | |
| 410 | + return out.getvalue() | |
| 411 | + | |
| 412 | + # Zugliste: drei Spalten, je Zeile ein Zugpaar; Balken unter jedem Halbzug | |
| 413 | + y += 18 | |
| 414 | + columns, gap, row_h = 3, 18, 17 | |
| 415 | + col_w = (text_width - gap * (columns - 1)) / columns | |
| 416 | + moves = _moves(state) | |
| 417 | + rows = [] | |
| 418 | + for ply, before, move in moves: | |
| 419 | + if before.turn == chess.WHITE or not rows: | |
| 420 | + rows.append([before.fullmove_number, None, None]) | |
| 421 | + rows[-1][1 if before.turn == chess.WHITE else 2] = (ply, notation.move(before, move, opts.notation)) | |
| 422 | + col, top = 0, y | |
| 423 | + | |
| 424 | + def cell(entry, x, yy, w): | |
| 425 | + if entry is None: | |
| 426 | + text("…", x, yy, size=9) | |
| 427 | + return | |
| 428 | + ply, san = entry | |
| 429 | + mark = html_mod.escape(san) | |
| 430 | + if ply + 1 == plies: | |
| 431 | + mark = f"<b>{mark}</b>" | |
| 432 | + if opts.symbols and ply in state.symbols: | |
| 433 | + sym = state.symbols[ply] | |
| 434 | + mark += f" <span foreground='{hex_color(BADGE[sym])}' weight='heavy'>{html_mod.escape(sym)}</span>" | |
| 435 | + text(mark, x, yy, size=9) | |
| 436 | + wp = state.evals.get(ply) if opts.evals else None | |
| 437 | + if wp is not None: | |
| 438 | + bar_w, bar_h, bar_y = w - 8, 3.2, yy + row_h - 3.8 | |
| 439 | + split = bar_w * max(0.0, min(100.0, wp)) / 100 | |
| 440 | + cr.set_source_rgb(*BAR_BLACK) | |
| 441 | + cr.rectangle(x, bar_y, bar_w, bar_h) | |
| 442 | + cr.fill() | |
| 443 | + cr.set_source_rgb(*BAR_WHITE) | |
| 444 | + cr.rectangle(x, bar_y, split, bar_h) | |
| 445 | + cr.fill() | |
| 446 | + cr.set_source_rgb(0.55, 0.55, 0.55) | |
| 447 | + cr.set_line_width(0.4) | |
| 448 | + cr.rectangle(x, bar_y, bar_w, bar_h) | |
| 449 | + cr.stroke() | |
| 450 | + | |
| 451 | + for number, white, black in rows: | |
| 452 | + if y + row_h > height - PDF_MARGIN: | |
| 453 | + col += 1 | |
| 454 | + if col == columns: | |
| 455 | + surface.show_page() | |
| 456 | + col, top = 0, PDF_MARGIN | |
| 457 | + y = top | |
| 458 | + x = left + col * (col_w + gap) | |
| 459 | + num_w = 24 | |
| 460 | + text(f"<span alpha='60%'>{number}.</span>", x, y, size=9) | |
| 461 | + half = (col_w - num_w) / 2 | |
| 462 | + cell(white, x + num_w, y, half) | |
| 463 | + if black is not None or white is None: | |
| 464 | + cell(black, x + num_w + half, y, half) | |
| 465 | + y += row_h | |
| 466 | + if i.result != "*": | |
| 467 | + if y + row_h > height - PDF_MARGIN: | |
| 468 | + col += 1 | |
| 469 | + if col == columns: | |
| 470 | + surface.show_page() | |
| 471 | + col, top = 0, PDF_MARGIN | |
| 472 | + y = top | |
| 473 | + text(f"<b>{RESULT_TEXT[i.result]}</b>", left + col * (col_w + gap), y + 2, size=10) | |
| 474 | + surface.finish() | |
| 475 | + return out.getvalue() | |
| 476 | + | |
| 477 | + | |
| 478 | +# --- HTML -------------------------------------------------------------------- | |
| 479 | + | |
| 480 | +def _square_xy(square): | |
| 481 | + return chess.square_file(square), 7 - chess.square_rank(square) | |
| 482 | + | |
| 483 | + | |
| 484 | +def _html_ply_group(state, board, plies, opts, light_dark): | |
| 485 | + last_rgba = light_dark[2] | |
| 486 | + parts = [] | |
| 487 | + if opts.last_move and board.move_stack: | |
| 488 | + last = board.peek() | |
| 489 | + for s in (last.from_square, last.to_square): | |
| 490 | + x, y = _square_xy(s) | |
| 491 | + parts.append( | |
| 492 | + f'<rect class="m" data-x="{x}" data-y="{y}" x="{x}" y="{y}" width="1" height="1" ' | |
| 493 | + f'fill="{hex_color(last_rgba)}" fill-opacity="{last_rgba[3]}"/>' | |
| 494 | + ) | |
| 495 | + if board.is_check(): | |
| 496 | + king = board.king(board.turn) | |
| 497 | + if king is not None: | |
| 498 | + x, y = _square_xy(king) | |
| 499 | + parts.append(f'<rect class="m" data-x="{x}" data-y="{y}" x="{x}" y="{y}" width="1" height="1" fill="url(#check)"/>') | |
| 500 | + for square, piece in sorted(board.piece_map().items()): | |
| 501 | + x, y = _square_xy(square) | |
| 502 | + parts.append(f'<use class="m" data-x="{x}" data-y="{y}" href="#p{piece.symbol()}" x="{x}" y="{y}" width="1" height="1"/>') | |
| 503 | + badge = _badge(state, board, opts) | |
| 504 | + if badge: | |
| 505 | + x, y = _square_xy(badge[0]) | |
| 506 | + sym = badge[1] | |
| 507 | + parts.append( | |
| 508 | + f'<use class="m" data-x="{x}" data-y="{y}" href="#{_badge_id(sym)}" x="{x}" y="{y}" width="1" height="1"/>' | |
| 509 | + ) | |
| 510 | + hidden = "" if plies == _plies(state, opts) else ' style="display:none"' | |
| 511 | + return f'<g class="ply" data-ply="{plies}"{hidden}>' + "".join(parts) + "</g>" | |
| 512 | + | |
| 513 | + | |
| 514 | +def _badge_id(sym): | |
| 515 | + """Gültige SVG-ID für ein Zugzeichen: !! → b-gg, ?! → b-qg …""" | |
| 516 | + return "b-" + sym.replace("!", "g").replace("?", "q") | |
| 517 | + | |
| 518 | + | |
| 519 | +def _badge_symbols(): | |
| 520 | + out = [] | |
| 521 | + for sym, rgb in BADGE.items(): | |
| 522 | + sid = _badge_id(sym) | |
| 523 | + size = 0.2 if len(sym) == 1 else 0.17 | |
| 524 | + out.append( | |
| 525 | + f'<symbol id="{sid}" viewBox="0 0 1 1"><rect width="1" height="1" fill="none"/>' | |
| 526 | + f'<circle cx="0.83" cy="0.17" r="0.17" fill="{hex_color(rgb)}"/>' | |
| 527 | + f'<text x="0.83" y="0.17" dy="0.07" font-size="{size}" text-anchor="middle" ' | |
| 528 | + f'font-family="sans-serif" font-weight="bold" fill="#fff">{html_mod.escape(sym)}</text></symbol>' | |
| 529 | + ) | |
| 530 | + return out | |
| 531 | + | |
| 532 | + | |
| 533 | +def _html_board(state, opts, plies_list): | |
| 534 | + light, dark, last, _sel = scheme_colors(opts.scheme) | |
| 535 | + defs = [] | |
| 536 | + for symbol in "PNBRQKpnbrqk": | |
| 537 | + data = base64.b64encode(piece_svg(opts.theme, symbol)).decode() | |
| 538 | + defs.append( | |
| 539 | + f'<symbol id="p{symbol}" viewBox="0 0 1 1">' | |
| 540 | + f'<image href="data:image/svg+xml;base64,{data}" width="1" height="1"/></symbol>' | |
| 541 | + ) | |
| 542 | + defs += _badge_symbols() | |
| 543 | + defs.append( | |
| 544 | + f'<radialGradient id="check"><stop offset="0" stop-color="{hex_color(CHECK)}" stop-opacity="0.85"/>' | |
| 545 | + f'<stop offset="0.6" stop-color="{hex_color(CHECK)}" stop-opacity="0.42"/>' | |
| 546 | + f'<stop offset="1" stop-color="{hex_color(CHECK)}" stop-opacity="0"/></radialGradient>' | |
| 547 | + ) | |
| 548 | + squares = [] | |
| 549 | + for square in chess.SQUARES: | |
| 550 | + x, y = _square_xy(square) | |
| 551 | + color = light if (chess.square_file(square) + chess.square_rank(square)) % 2 else dark | |
| 552 | + squares.append(f'<rect class="m" data-x="{x}" data-y="{y}" x="{x}" y="{y}" width="1" height="1" fill="{hex_color(color)}"/>') | |
| 553 | + labels = [] | |
| 554 | + for flipped in (False, True): | |
| 555 | + bottom_rank = 7 if flipped else 0 | |
| 556 | + left_file = 7 if flipped else 0 | |
| 557 | + items = [] | |
| 558 | + for f in range(8): | |
| 559 | + col = 7 - f if flipped else f | |
| 560 | + on_light = (f + bottom_rank) % 2 == 1 | |
| 561 | + items.append(f'<text x="{col + 0.95}" y="7.94" text-anchor="end" fill="{hex_color(dark if on_light else light)}">{chess.FILE_NAMES[f]}</text>') | |
| 562 | + for r in range(8): | |
| 563 | + row = r if flipped else 7 - r | |
| 564 | + on_light = (left_file + r) % 2 == 1 | |
| 565 | + items.append(f'<text x="0.05" y="{row + 0.2}" fill="{hex_color(dark if on_light else light)}">{r + 1}</text>') | |
| 566 | + labels.append(f'<g class="labels {"flip" if flipped else "normal"}">' + "".join(items) + "</g>") | |
| 567 | + groups = [_html_ply_group(state, board_at(state, p), p, opts, (light, dark, last)) for p in plies_list] | |
| 568 | + return ( | |
| 569 | + '<svg id="board" viewBox="0 0 8 8" xmlns="http://www.w3.org/2000/svg" role="img" ' | |
| 570 | + 'aria-label="Schachbrett">' | |
| 571 | + f'<defs>{"".join(defs)}</defs>{"".join(squares)}' | |
| 572 | + f'<g font-family="sans-serif" font-weight="bold" font-size="0.16">{"".join(labels)}</g>' | |
| 573 | + f'{"".join(groups)}</svg>' | |
| 574 | + ) | |
| 575 | + | |
| 576 | + | |
| 577 | +_HTML_CSS = """ | |
| 578 | +:root { color-scheme: light dark; --bg: #fafaf9; --fg: #1e1e1e; --muted: #6b6b6b; --card: #fff; | |
| 579 | + --line: #ddd; --accent: #3584e4; --accent-fg: #fff; } | |
| 580 | +@media (prefers-color-scheme: dark) { :root { --bg: #1e1e20; --fg: #eee; --muted: #9a9a9a; --card: #2a2a2d; | |
| 581 | + --line: #3a3a3d; } } | |
| 582 | +* { box-sizing: border-box; } | |
| 583 | +body { margin: 0; padding: 16px; background: var(--bg); color: var(--fg); | |
| 584 | + font: 15px/1.4 system-ui, "Cantarell", sans-serif; } | |
| 585 | +main { max-width: 980px; margin: 0 auto; display: grid; gap: 16px 24px; grid-template-columns: minmax(0, 1fr); } | |
| 586 | +@media (min-width: 760px) { main.game { grid-template-columns: minmax(0, 1.1fr) minmax(260px, 1fr); } } | |
| 587 | +header { grid-column: 1 / -1; } | |
| 588 | +h1 { font-size: 1.4em; margin: 0 0 2px; } | |
| 589 | +.meta { color: var(--muted); margin: 0; } | |
| 590 | +.boardwrap { display: flex; gap: 6px; align-items: stretch; } | |
| 591 | +#board { width: 100%; height: auto; display: block; border-radius: 4px; user-select: none; } | |
| 592 | +#bar { width: 12px; flex: none; background: #2b2b2e; border-radius: 3px; display: flex; | |
| 593 | + flex-direction: column-reverse; overflow: hidden; } | |
| 594 | +#bar.flip { flex-direction: column; } | |
| 595 | +#bar span { display: block; background: #f2f2ee; transition: height .2s; } | |
| 596 | +.labels.flip, .flipped .labels.normal { display: none; } | |
| 597 | +.flipped .labels.flip { display: inline; } | |
| 598 | +.caption { margin: 8px 0 4px; } | |
| 599 | +.fenrow { display: flex; gap: 6px; align-items: center; } | |
| 600 | +.fen { flex: 1; min-width: 0; overflow-wrap: anywhere; user-select: all; -webkit-user-select: all; | |
| 601 | + font: 13px/1.3 ui-monospace, monospace; background: var(--card); border: 1px solid var(--line); | |
| 602 | + border-radius: 6px; padding: 6px 8px; } | |
| 603 | +button { font: inherit; color: inherit; background: var(--card); border: 1px solid var(--line); | |
| 604 | + border-radius: 6px; padding: 4px 10px; cursor: pointer; } | |
| 605 | +button:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; } | |
| 606 | +.nav { display: flex; gap: 6px; margin-top: 8px; flex-wrap: wrap; } | |
| 607 | +.moves { background: var(--card); border: 1px solid var(--line); border-radius: 8px; padding: 6px; | |
| 608 | + max-height: 70vh; overflow-y: auto; display: grid; grid-template-columns: auto 1fr 1fr; gap: 3px 4px; | |
| 609 | + align-content: start; } | |
| 610 | +.moves .n { color: var(--muted); text-align: right; padding: 3px 2px 0 4px; font-variant-numeric: tabular-nums; } | |
| 611 | +.moves button { text-align: left; border: 0; padding: 3px 7px 6px; position: relative; background: transparent; } | |
| 612 | +.moves button:hover { background: color-mix(in srgb, var(--fg) 8%, transparent); } | |
| 613 | +.moves button.sel { background: var(--accent); color: var(--accent-fg); } | |
| 614 | +.moves button i { position: absolute; left: 7px; right: 7px; bottom: 2px; height: 3px; border-radius: 2px; | |
| 615 | + background: linear-gradient(90deg, #e9e9e4 var(--wp), #2b2b2e var(--wp)); outline: 1px solid var(--line); } | |
| 616 | +.moves .start { grid-column: 1 / -1; } | |
| 617 | +.moves b.s { font-weight: 800; margin-left: 2px; } | |
| 618 | +.result { grid-column: 1 / -1; padding: 4px 8px; font-weight: 600; } | |
| 619 | +""" | |
| 620 | + | |
| 621 | +_HTML_JS = """ | |
| 622 | +(() => { | |
| 623 | + const data = JSON.parse(document.getElementById('data').textContent); | |
| 624 | + const svg = document.getElementById('board'); | |
| 625 | + const groups = [...svg.querySelectorAll('g.ply')]; | |
| 626 | + const buttons = [...document.querySelectorAll('.moves button[data-ply]')]; | |
| 627 | + const fen = document.getElementById('fen'); | |
| 628 | + const cap = document.getElementById('caption'); | |
| 629 | + const bar = document.getElementById('bar'); | |
| 630 | + let cur = data.start, flipped = data.flipped; | |
| 631 | + function place() { | |
| 632 | + svg.classList.toggle('flipped', flipped); | |
| 633 | + for (const el of svg.querySelectorAll('.m')) { | |
| 634 | + const x = +el.dataset.x, y = +el.dataset.y; | |
| 635 | + el.setAttribute('x', flipped ? 7 - x : x); | |
| 636 | + el.setAttribute('y', flipped ? 7 - y : y); | |
| 637 | + } | |
| 638 | + if (bar) bar.classList.toggle('flip', flipped); | |
| 639 | + } | |
| 640 | + function show(p) { | |
| 641 | + cur = Math.max(0, Math.min(data.plies.length - 1, p)); | |
| 642 | + const info = data.plies[cur]; | |
| 643 | + for (const g of groups) g.style.display = +g.dataset.ply === info.p ? '' : 'none'; | |
| 644 | + for (const b of buttons) b.classList.toggle('sel', +b.dataset.ply === info.p); | |
| 645 | + const sel = buttons.find(b => +b.dataset.ply === info.p); | |
| 646 | + if (sel) sel.scrollIntoView({block: 'nearest'}); | |
| 647 | + fen.textContent = info.fen; | |
| 648 | + cap.textContent = info.caption; | |
| 649 | + if (bar) bar.firstElementChild.style.height = (info.wp == null ? 50 : info.wp) + '%'; | |
| 650 | + } | |
| 651 | + for (const b of buttons) b.addEventListener('click', () => show(data.plies.findIndex(i => i.p === +b.dataset.ply))); | |
| 652 | + const act = {first: () => show(0), prev: () => show(cur - 1), next: () => show(cur + 1), | |
| 653 | + last: () => show(data.plies.length - 1), flip: () => { flipped = !flipped; place(); }, | |
| 654 | + copy: () => navigator.clipboard && navigator.clipboard.writeText(fen.textContent)}; | |
| 655 | + for (const b of document.querySelectorAll('[data-act]')) b.addEventListener('click', () => act[b.dataset.act]()); | |
| 656 | + document.addEventListener('keydown', e => { | |
| 657 | + if (e.altKey || e.ctrlKey || e.metaKey) return; | |
| 658 | + const k = {ArrowLeft: 'prev', ArrowRight: 'next', Home: 'first', End: 'last', f: 'flip'}[e.key]; | |
| 659 | + if (k) { act[k](); e.preventDefault(); } | |
| 660 | + }); | |
| 661 | + document.querySelector('.nav').hidden = false; | |
| 662 | + place(); show(cur); | |
| 663 | +})(); | |
| 664 | +""" | |
| 665 | + | |
| 666 | + | |
| 667 | +def to_html(state, opts): | |
| 668 | + plies = _plies(state, opts) | |
| 669 | + game = opts.scope == "game" and bool(state.board.move_stack) | |
| 670 | + plies_list = list(range(len(state.board.move_stack) + 1)) if game else [plies] | |
| 671 | + i = info(state) | |
| 672 | + board = board_at(state, plies) | |
| 673 | + esc = html_mod.escape | |
| 674 | + | |
| 675 | + entries = [] | |
| 676 | + for p in plies_list: | |
| 677 | + b = board_at(state, p) | |
| 678 | + entries.append({"p": p, "fen": b.fen(), "caption": caption(b, opts.notation), | |
| 679 | + "wp": _eval(state, p, opts)}) | |
| 680 | + data = {"plies": entries, "start": plies_list.index(plies), "flipped": opts.flipped} | |
| 681 | + data_json = json.dumps(data, ensure_ascii=False).replace("</", "<\\/") | |
| 682 | + | |
| 683 | + title = i.title if opts.players else "Schachstellung" if not game else "Schachpartie" | |
| 684 | + head = "" | |
| 685 | + if opts.players: | |
| 686 | + meta = [m for m in (i.event, i.date, RESULT_TEXT.get(i.result, ""), i.end_text) if m and m != "?"] | |
| 687 | + head = f'<header><h1>{esc(i.title)}</h1><p class="meta">{esc(" · ".join(meta))}</p></header>' | |
| 688 | + | |
| 689 | + bar = "" | |
| 690 | + wp = _eval(state, plies, opts) | |
| 691 | + if opts.evals and (game and state.evals or wp is not None): | |
| 692 | + height = 50 if wp is None else wp | |
| 693 | + bar = f'<div id="bar" class="{"flip" if opts.flipped else ""}" title="Gewinnchance Weiß"><span style="height:{height}%"></span></div>' | |
| 694 | + | |
| 695 | + svg = _html_board(state, opts, plies_list) | |
| 696 | + nav = "" | |
| 697 | + if game: | |
| 698 | + nav = ( | |
| 699 | + '<div class="nav" hidden><button data-act="first" title="Anfang (Pos1)">⏮</button>' | |
| 700 | + '<button data-act="prev" title="Zurück (←)">◀</button>' | |
| 701 | + '<button data-act="next" title="Vor (→)">▶</button>' | |
| 702 | + '<button data-act="last" title="Ende (Ende)">⏭</button>' | |
| 703 | + '<button data-act="flip" title="Brett drehen (F)">⇅</button></div>' | |
| 704 | + ) | |
| 705 | + else: | |
| 706 | + nav = '<div class="nav" hidden><button data-act="flip" title="Brett drehen (F)">⇅</button></div>' | |
| 707 | + left = ( | |
| 708 | + f'<section><div class="boardwrap">{bar}{svg}</div>{nav}' | |
| 709 | + f'<p class="caption" id="caption">{esc(caption(board, opts.notation))}</p>' | |
| 710 | + f'<div class="fenrow"><code class="fen" id="fen" title="FEN – Klick markiert alles">{esc(board.fen())}</code>' | |
| 711 | + f'<button data-act="copy" title="FEN kopieren">Kopieren</button></div></section>' | |
| 712 | + ) | |
| 713 | + | |
| 714 | + right = "" | |
| 715 | + if game: | |
| 716 | + cells = ['<button class="start" data-ply="0">Ausgangsstellung</button>'] | |
| 717 | + for ply, before, move in _moves(state): | |
| 718 | + if before.turn == chess.WHITE: | |
| 719 | + cells.append(f'<span class="n">{before.fullmove_number}.</span>') | |
| 720 | + elif ply == 0: | |
| 721 | + cells.append(f'<span class="n">{before.fullmove_number}.</span><span></span>') | |
| 722 | + label = esc(notation.move(before, move, opts.notation)) | |
| 723 | + if opts.symbols and ply in state.symbols: | |
| 724 | + sym = state.symbols[ply] | |
| 725 | + label += f'<b class="s" style="color:{hex_color(BADGE[sym])}">{esc(sym)}</b>' | |
| 726 | + ev = state.evals.get(ply) if opts.evals else None | |
| 727 | + if ev is not None: | |
| 728 | + label += f'<i style="--wp:{ev:.1f}%"></i>' | |
| 729 | + cells.append(f'<button data-ply="{ply + 1}">{label}</button>') | |
| 730 | + result = " ".join(filter(None, [RESULT_TEXT.get(i.result, ""), i.end_text])) | |
| 731 | + if result: | |
| 732 | + cells.append(f'<div class="result">{esc(result)}</div>') | |
| 733 | + right = f'<nav class="moves" aria-label="Züge">{"".join(cells)}</nav>' | |
| 734 | + | |
| 735 | + return ( | |
| 736 | + "<!doctype html>\n<html lang=\"de\">\n<head>\n<meta charset=\"utf-8\">\n" | |
| 737 | + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n" | |
| 738 | + f"<title>{esc(title)}</title>\n<style>{_HTML_CSS}</style>\n</head>\n<body>\n" | |
| 739 | + f'<main class="{"game" if game else "position"}">{head}{left}{right}</main>\n' | |
| 740 | + f'<script type="application/json" id="data">{data_json}</script>\n' | |
| 741 | + f"<script>{_HTML_JS}</script>\n</body>\n</html>\n" | |
| 742 | + ) | |
| 743 | + | |
| 744 | + | |
| 745 | +# --- Bilder ------------------------------------------------------------------ | |
| 746 | + | |
| 747 | +def to_svg(state, opts): | |
| 748 | + return diagram(state, opts).svg().decode() | |
| 749 | + | |
| 750 | + | |
| 751 | +def to_png(state, opts): | |
| 752 | + return diagram(state, opts).png(800) | |
| 753 | + | |
| 754 | + | |
| 755 | +# --- Einstieg ---------------------------------------------------------------- | |
| 756 | + | |
| 757 | +_WRITERS = { | |
| 758 | + "pgn": to_pgn, "fen": to_fen, "svg": to_svg, "png": to_png, "latex": to_latex, | |
| 759 | + "pdf": to_pdf, "pdf-latex": to_pdf_latex, "html": to_html, "ascii": to_ascii, | |
| 760 | +} | |
| 761 | + | |
| 762 | + | |
| 763 | +def export(fmt, state, opts): | |
| 764 | + """Inhalt als ``str`` (Textformate) oder ``bytes`` (PNG, PDF).""" | |
| 765 | + if fmt not in FORMATS: | |
| 766 | + raise ExportError(f"Unbekanntes Format: {fmt}") | |
| 767 | + if opts.scope not in FORMATS[fmt].scopes: | |
| 768 | + opts = dataclasses.replace(opts, scope=FORMATS[fmt].scopes[0]) | |
| 769 | + return _WRITERS[fmt](state, opts) | |
| 770 | + | |
| 771 | + | |
| 772 | +def filename(fmt, state, opts): | |
| 773 | + """Vorschlag für den Dateinamen, z. B. „partie-2026-11-20.pdf“.""" | |
| 774 | + scope = opts.scope if opts.scope in FORMATS[fmt].scopes else FORMATS[fmt].scopes[0] | |
| 775 | + base = "partie" if scope == "game" else "stellung" | |
| 776 | + return f"{base}-{datetime.date.today():%Y-%m-%d}.{FORMATS[fmt].extension}" | |
| 777 | + | |
added schach/exportdialog.py +241 −0
| @@ -0,0 +1,241 @@ | ||
| 1 | +"""Dialog „Exportieren“: Format, Umfang und Darstellung wählen, dann speichern oder kopieren. | |
| 2 | + | |
| 3 | +Die Arbeit macht export.py; hier werden nur Optionen eingesammelt. Die Auswahl merkt sich | |
| 4 | +das Programm (Einstellung ``export``), außer der Drehung – die folgt dem Brett im Fenster. | |
| 5 | +""" | |
| 6 | + | |
| 7 | +import dataclasses | |
| 8 | +import threading | |
| 9 | + | |
| 10 | +import gi | |
| 11 | + | |
| 12 | +gi.require_version("Gtk", "4.0") | |
| 13 | +gi.require_version("Gdk", "4.0") | |
| 14 | +gi.require_version("Adw", "1") | |
| 15 | +from gi.repository import Adw, Gdk, GLib, Gtk # noqa: E402 | |
| 16 | + | |
| 17 | +from . import export # noqa: E402 | |
| 18 | + | |
| 19 | +DEFAULTS = {"format": "pgn", "scope": "game", "symbols": True, "evals": True, "players": True, "last_move": True} | |
| 20 | + | |
| 21 | +# Schalter für die Darstellung: (Option, Titel, Untertitel) | |
| 22 | +SWITCHES = [ | |
| 23 | + ("symbols", "Zugzeichen", "!! ! ?! ? ?? an Zügen und Figur"), | |
| 24 | + ("evals", "Gewinnchance", "Weiß/Schwarz-Balken aus der Analyse"), | |
| 25 | + ("players", "Spielerköpfe", "Namen, Datum und Ergebnis"), | |
| 26 | + ("last_move", "Letzten Zug markieren", "Felder des letzten Zugs hervorheben"), | |
| 27 | + ("flipped", "Schwarz unten", "Brett gedreht"), | |
| 28 | +] | |
| 29 | + | |
| 30 | +FORMAT_HINTS = { | |
| 31 | + "pgn": "Partie oder Stellung für andere Schachprogramme", | |
| 32 | + "fen": "Die Stellung als eine Zeile Text", | |
| 33 | + "svg": "Vektorbild des Bretts, wie es hier aussieht", | |
| 34 | + "png": "Bild des Bretts, 800 Pixel breit", | |
| 35 | + "latex": "Quelltext mit dem Paket xskak, zum Einbinden in eigene Dokumente", | |
| 36 | + "pdf": "Druckfertig: Diagramm und Zugliste", | |
| 37 | + "pdf-latex": "Druckfertig, gesetzt mit LaTeX (dauert einige Sekunden)", | |
| 38 | + "html": "Eine Datei zum Ansehen im Browser – mit Zugliste zum Durchklicken", | |
| 39 | + "ascii": "Brett aus Buchstaben, z. B. für E-Mails oder Foren", | |
| 40 | +} | |
| 41 | + | |
| 42 | + | |
| 43 | +class ExportDialog(Adw.Dialog): | |
| 44 | + def __init__(self, win, state, plies, saved, flipped, theme, scheme, style): | |
| 45 | + """``plies``: gezeigte Stellung (Zahl der Halbzüge), ``saved``: gemerkte Auswahl.""" | |
| 46 | + super().__init__(title="Exportieren", content_width=440) | |
| 47 | + self.win = win | |
| 48 | + self.state = state | |
| 49 | + self.plies = plies | |
| 50 | + self.base = export.Options( | |
| 51 | + plies=plies, notation=style, flipped=flipped, theme=theme, scheme=scheme, | |
| 52 | + ) | |
| 53 | + settings = {**DEFAULTS, **(saved or {})} | |
| 54 | + self.formats = [key for key in export.FORMATS if key != "pdf-latex" or export.latex_available()] | |
| 55 | + if settings["format"] not in self.formats: | |
| 56 | + settings["format"] = DEFAULTS["format"] | |
| 57 | + | |
| 58 | + page = Adw.PreferencesPage() | |
| 59 | + | |
| 60 | + what = Adw.PreferencesGroup() | |
| 61 | + self.format_row = Adw.ComboRow( | |
| 62 | + title="Format", model=Gtk.StringList.new([export.FORMATS[k].label for k in self.formats]), | |
| 63 | + ) | |
| 64 | + self.format_row.set_selected(self.formats.index(settings["format"])) | |
| 65 | + self.format_row.connect("notify::selected", lambda *_: self._update()) | |
| 66 | + what.add(self.format_row) | |
| 67 | + | |
| 68 | + self.scope = Adw.ToggleGroup(valign=Gtk.Align.CENTER) | |
| 69 | + self.scope.add(Adw.Toggle(name="position", label="Stellung")) | |
| 70 | + self.scope.add(Adw.Toggle(name="game", label="Partie")) | |
| 71 | + self.wanted_scope = settings["scope"] if settings["scope"] in ("position", "game") else "game" | |
| 72 | + self._updating = False | |
| 73 | + self.scope.set_active_name(self.wanted_scope) | |
| 74 | + self.scope.connect("notify::active-name", self._on_scope) | |
| 75 | + board = export.board_at(state, plies) | |
| 76 | + self.scope_row = Adw.ActionRow(title="Umfang", subtitle=export.caption(board, style)) | |
| 77 | + self.scope_row.add_suffix(self.scope) | |
| 78 | + what.add(self.scope_row) | |
| 79 | + page.add(what) | |
| 80 | + | |
| 81 | + self.look = Adw.PreferencesGroup(title="Darstellung") | |
| 82 | + self.switches = {} | |
| 83 | + for key, title, subtitle in SWITCHES: | |
| 84 | + row = Adw.SwitchRow(title=title, subtitle=subtitle) | |
| 85 | + row.set_active(flipped if key == "flipped" else bool(settings[key])) | |
| 86 | + self.look.add(row) | |
| 87 | + self.switches[key] = row | |
| 88 | + if not state.evals: | |
| 89 | + self.switches["evals"].set_subtitle("Für diese Partie gibt es noch keine Bewertung") | |
| 90 | + page.add(self.look) | |
| 91 | + | |
| 92 | + self.copy_btn = Gtk.Button(label="_Kopieren", use_underline=True, hexpand=True) | |
| 93 | + self.copy_btn.connect("clicked", lambda *_: self._run(self._to_clipboard)) | |
| 94 | + self.save_btn = Gtk.Button(label="_Speichern …", use_underline=True, hexpand=True, | |
| 95 | + css_classes=["suggested-action"]) | |
| 96 | + self.save_btn.connect("clicked", lambda *_: self._save()) | |
| 97 | + self.spinner = Adw.Spinner(visible=False) | |
| 98 | + buttons = Gtk.Box(spacing=12, margin_start=12, margin_end=12, margin_top=6, margin_bottom=12, | |
| 99 | + homogeneous=False) | |
| 100 | + buttons.append(self.copy_btn) | |
| 101 | + buttons.append(self.spinner) | |
| 102 | + buttons.append(self.save_btn) | |
| 103 | + | |
| 104 | + view = Adw.ToolbarView(content=page) | |
| 105 | + view.add_top_bar(Adw.HeaderBar()) | |
| 106 | + view.add_bottom_bar(buttons) | |
| 107 | + self.set_child(view) | |
| 108 | + self.set_default_widget(self.save_btn) | |
| 109 | + self._update() | |
| 110 | + | |
| 111 | + # --- Zustand ------------------------------------------------------------- | |
| 112 | + | |
| 113 | + def _format(self): | |
| 114 | + return self.formats[self.format_row.get_selected()] | |
| 115 | + | |
| 116 | + def _options(self): | |
| 117 | + fmt = export.FORMATS[self._format()] | |
| 118 | + scope = self.scope.get_active_name() | |
| 119 | + if scope not in fmt.scopes: | |
| 120 | + scope = fmt.scopes[0] | |
| 121 | + values = {key: row.get_active() for key, row in self.switches.items()} | |
| 122 | + return dataclasses.replace(self.base, scope=scope, **values) | |
| 123 | + | |
| 124 | + def _on_scope(self, *_): | |
| 125 | + if not self._updating: | |
| 126 | + self.wanted_scope = self.scope.get_active_name() # Wahl merken, auch wenn ein Format sie kurz sperrt | |
| 127 | + self._update() | |
| 128 | + | |
| 129 | + def _update(self): | |
| 130 | + key = self._format() | |
| 131 | + fmt = export.FORMATS[key] | |
| 132 | + self.format_row.set_subtitle(FORMAT_HINTS.get(key, "")) | |
| 133 | + has_game = bool(self.state.board.move_stack) | |
| 134 | + scope = self.wanted_scope if self.wanted_scope in fmt.scopes and has_game else fmt.scopes[0] | |
| 135 | + if not self._updating: | |
| 136 | + # Sperren und Umschalten löst notify::active-name aus – das ist keine Wahl des Nutzers | |
| 137 | + self._updating = True | |
| 138 | + for name in ("position", "game"): | |
| 139 | + enabled = name in fmt.scopes and (name == "position" or has_game) | |
| 140 | + self.scope.get_toggle_by_name(name).set_enabled(enabled) | |
| 141 | + if self.scope.get_active_name() != scope: | |
| 142 | + self.scope.set_active_name(scope) | |
| 143 | + self._updating = False | |
| 144 | + for name, row in self.switches.items(): | |
| 145 | + row.set_visible(name in fmt.options) | |
| 146 | + self.look.set_visible(any(name in fmt.options for name in self.switches)) | |
| 147 | + self.copy_btn.set_sensitive(fmt.clipboard) | |
| 148 | + self.copy_btn.set_tooltip_text(None if fmt.clipboard else "PDF lässt sich nur als Datei speichern") | |
| 149 | + | |
| 150 | + def _remember(self): | |
| 151 | + values = {"format": self._format(), "scope": self.wanted_scope} | |
| 152 | + values.update({k: self.switches[k].get_active() for k in DEFAULTS if k in self.switches}) | |
| 153 | + self.win.get_application().update_setting("export", values) | |
| 154 | + | |
| 155 | + # --- Ausführen ------------------------------------------------------------- | |
| 156 | + | |
| 157 | + def _run(self, done): | |
| 158 | + """Export im Hintergrund (pdflatex braucht Sekunden), dann ``done(inhalt)`` im GTK-Thread.""" | |
| 159 | + fmt, opts, state = self._format(), self._options(), self.state | |
| 160 | + self._busy(True) | |
| 161 | + | |
| 162 | + def work(): | |
| 163 | + try: | |
| 164 | + result, error = export.export(fmt, state, opts), None | |
| 165 | + except export.ExportError as exc: | |
| 166 | + result, error = None, str(exc) | |
| 167 | + except Exception as exc: # noqa: BLE001 – soll als Meldung ankommen, nicht den Dialog hängen lassen | |
| 168 | + result, error = None, f"Export fehlgeschlagen: {exc}" | |
| 169 | + GLib.idle_add(finish, result, error) | |
| 170 | + | |
| 171 | + def finish(result, error): | |
| 172 | + self._busy(False) | |
| 173 | + if error: | |
| 174 | + self.win.toasts.add_toast(Adw.Toast(title=error)) | |
| 175 | + return | |
| 176 | + self._remember() | |
| 177 | + done(fmt, result) | |
| 178 | + | |
| 179 | + threading.Thread(target=work, daemon=True).start() | |
| 180 | + | |
| 181 | + def _busy(self, busy): | |
| 182 | + self.spinner.set_visible(busy) | |
| 183 | + self.copy_btn.set_sensitive(not busy and export.FORMATS[self._format()].clipboard) | |
| 184 | + self.save_btn.set_sensitive(not busy) | |
| 185 | + | |
| 186 | + def _to_clipboard(self, fmt, content): | |
| 187 | + clipboard = self.win.get_clipboard() | |
| 188 | + if fmt == "png": | |
| 189 | + clipboard.set_texture(Gdk.Texture.new_from_bytes(GLib.Bytes.new(content))) | |
| 190 | + title = "Bild kopiert" | |
| 191 | + elif fmt == "svg": | |
| 192 | + data = content.encode() | |
| 193 | + png = export.diagram(self.state, self._options()).png(800) | |
| 194 | + clipboard.set_content(Gdk.ContentProvider.new_union([ | |
| 195 | + Gdk.ContentProvider.new_for_bytes("image/svg+xml", GLib.Bytes.new(data)), | |
| 196 | + Gdk.ContentProvider.new_for_value(Gdk.Texture.new_from_bytes(GLib.Bytes.new(png))), | |
| 197 | + Gdk.ContentProvider.new_for_bytes("text/plain;charset=utf-8", GLib.Bytes.new(data)), | |
| 198 | + ])) | |
| 199 | + title = "Bild kopiert" | |
| 200 | + elif fmt == "html": | |
| 201 | + data = GLib.Bytes.new(content.encode()) | |
| 202 | + clipboard.set_content(Gdk.ContentProvider.new_union([ | |
| 203 | + Gdk.ContentProvider.new_for_bytes("text/html", data), | |
| 204 | + Gdk.ContentProvider.new_for_bytes("text/plain;charset=utf-8", data), | |
| 205 | + ])) | |
| 206 | + title = "HTML kopiert" | |
| 207 | + else: | |
| 208 | + clipboard.set(content) | |
| 209 | + title = f"{export.FORMATS[fmt].label} kopiert" | |
| 210 | + self.win.toasts.add_toast(Adw.Toast(title=title, timeout=2)) | |
| 211 | + self.close() | |
| 212 | + | |
| 213 | + def _save(self): | |
| 214 | + fmt = self._format() | |
| 215 | + opts = self._options() | |
| 216 | + dialog = Gtk.FileDialog(initial_name=export.filename(fmt, self.state, opts)) | |
| 217 | + | |
| 218 | + def chosen(d, result): | |
| 219 | + try: | |
| 220 | + file = d.save_finish(result) | |
| 221 | + except GLib.Error: | |
| 222 | + return # abgebrochen | |
| 223 | + path = file.get_path() | |
| 224 | + | |
| 225 | + def write(_fmt, content): | |
| 226 | + try: | |
| 227 | + if isinstance(content, bytes): | |
| 228 | + with open(path, "wb") as fh: | |
| 229 | + fh.write(content) | |
| 230 | + else: | |
| 231 | + with open(path, "w", encoding="utf-8") as fh: | |
| 232 | + fh.write(content) | |
| 233 | + except OSError as exc: | |
| 234 | + self.win.toasts.add_toast(Adw.Toast(title=f"Nicht gespeichert: {exc.strerror}")) | |
| 235 | + return | |
| 236 | + self.win.toasts.add_toast(Adw.Toast(title=f"Gespeichert: {file.get_basename()}", timeout=3)) | |
| 237 | + self.close() | |
| 238 | + | |
| 239 | + self._run(write) | |
| 240 | + | |
| 241 | + dialog.save(self.win, None, chosen) | |
added tests/test_export.py +170 −0
| @@ -0,0 +1,170 @@ | ||
| 1 | +import io | |
| 2 | +import re | |
| 3 | +import shutil | |
| 4 | +import subprocess | |
| 5 | +import tempfile | |
| 6 | +import unittest | |
| 7 | + | |
| 8 | +import chess | |
| 9 | +import chess.pgn | |
| 10 | + | |
| 11 | +from schach import export, savegames | |
| 12 | + | |
| 13 | +MOVES = "e4 e5 Nf3 Nc6 Bc4 Nd4 Nxe5 Qg5 Nxf7 Qxg2 Rf1 Qxe4+ Be2 Nf3#".split() | |
| 14 | + | |
| 15 | + | |
| 16 | +def sample(): | |
| 17 | + board = chess.Board() | |
| 18 | + for san in MOVES: | |
| 19 | + board.push_san(san) | |
| 20 | + return savegames.GameState( | |
| 21 | + board=board, human=chess.WHITE, elo=1500, symbols={5: "!", 6: "??", 13: "!!"}, | |
| 22 | + evals={i: 50.0 + i for i in range(len(MOVES))}, names=("Florian", "Max"), mode="review", | |
| 23 | + name="Vereinsabend", | |
| 24 | + ) | |
| 25 | + | |
| 26 | + | |
| 27 | +def opts(**kw): | |
| 28 | + kw.setdefault("theme", "python-chess") | |
| 29 | + return export.Options(**kw) | |
| 30 | + | |
| 31 | + | |
| 32 | +class TextFormatsTest(unittest.TestCase): | |
| 33 | + def test_fen_of_shown_position(self): | |
| 34 | + fen = export.export("fen", sample(), opts(plies=2)) | |
| 35 | + self.assertEqual(fen.strip(), "rnbqkbnr/pppp1ppp/8/4p3/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2") | |
| 36 | + | |
| 37 | + def test_fen_ignores_game_scope(self): | |
| 38 | + self.assertEqual(export.export("fen", sample(), opts(scope="game", plies=0)).strip(), chess.STARTING_FEN) | |
| 39 | + | |
| 40 | + def test_pgn_game_keeps_or_drops_annotations(self): | |
| 41 | + full = export.export("pgn", sample(), opts(scope="game")) | |
| 42 | + self.assertIn("$4", full) | |
| 43 | + self.assertIn("[%wp", full) | |
| 44 | + bare = export.export("pgn", sample(), opts(scope="game", symbols=False, evals=False)) | |
| 45 | + self.assertNotIn("$", bare.split("\n\n", 1)[1]) | |
| 46 | + self.assertNotIn("[%wp", bare) | |
| 47 | + game = chess.pgn.read_game(io.StringIO(bare)) | |
| 48 | + self.assertEqual(len(list(game.mainline_moves())), len(MOVES)) | |
| 49 | + | |
| 50 | + def test_pgn_position_is_setup_without_moves(self): | |
| 51 | + text = export.export("pgn", sample(), opts(plies=4)) | |
| 52 | + game = chess.pgn.read_game(io.StringIO(text)) | |
| 53 | + self.assertEqual(game.headers["White"], "Florian") | |
| 54 | + self.assertEqual(list(game.mainline_moves()), []) | |
| 55 | + self.assertEqual(game.board().fen(), export.board_at(sample(), 4).fen()) | |
| 56 | + self.assertNotIn("SchachHuman", text) | |
| 57 | + | |
| 58 | + def test_ascii_board_and_moves(self): | |
| 59 | + text = export.export("ascii", sample(), opts(scope="game", plies=0, notation="de")) | |
| 60 | + self.assertIn("8 | t s l d k l s t |", text) | |
| 61 | + self.assertIn("1 | T S L D K L S T |", text) | |
| 62 | + self.assertIn("2. Sf3 Sc6 3. Lc4 Sd4!", text) | |
| 63 | + self.assertIn("Florian – Max", text) | |
| 64 | + self.assertIn("0–1", text) | |
| 65 | + self.assertTrue(text.isascii() is False) # Gedankenstrich im Kopf | |
| 66 | + | |
| 67 | + def test_ascii_flipped_and_english(self): | |
| 68 | + text = export.export("ascii", sample(), opts(plies=0, flipped=True, notation="en", players=False)) | |
| 69 | + lines = text.splitlines() | |
| 70 | + self.assertEqual(lines[1], "1 | R N B K Q B N R |") | |
| 71 | + self.assertEqual(lines[-4].strip(), "h g f e d c b a") | |
| 72 | + self.assertNotIn("Florian", text) | |
| 73 | + | |
| 74 | + def test_caption(self): | |
| 75 | + board = export.board_at(sample(), 8) | |
| 76 | + self.assertEqual(export.caption(board, "de"), "Stellung nach 4… Dg5 · Weiß am Zug") | |
| 77 | + self.assertTrue(export.caption(sample().board).endswith("Weiß ist matt")) | |
| 78 | + self.assertTrue(export.caption(chess.Board()).startswith("Ausgangsstellung")) | |
| 79 | + | |
| 80 | + | |
| 81 | +class LatexTest(unittest.TestCase): | |
| 82 | + def test_game_splits_mainline_at_diagram(self): | |
| 83 | + tex = export.export("latex", sample(), opts(scope="game", plies=8, flipped=True)) | |
| 84 | + self.assertIn("\\mainline{1. e4 e5 2. Nf3 Nc6 3. Bc4 Nd4! 4. Nxe5?? Qg5}", tex) | |
| 85 | + self.assertIn("\\mainline{5. Nxf7", tex) | |
| 86 | + self.assertIn("inverse", tex) | |
| 87 | + self.assertIn("markfields={d8,g5}", tex) | |
| 88 | + self.assertLess(tex.index("\\chessboard"), tex.index("\\mainline{5.")) | |
| 89 | + | |
| 90 | + def test_position_sets_fen_and_escapes_names(self): | |
| 91 | + state = sample() | |
| 92 | + state.names = ("A & B", "50%") | |
| 93 | + tex = export.export("latex", state, opts(plies=4, last_move=False)) | |
| 94 | + self.assertIn("setfen=" + export.board_at(state, 4).fen(), tex) | |
| 95 | + self.assertIn("A \\& B -- 50\\%", tex) | |
| 96 | + self.assertNotIn("markfields", tex) | |
| 97 | + | |
| 98 | + @unittest.skipUnless(export.latex_available(), "pdflatex fehlt") | |
| 99 | + def test_pdf_via_latex(self): | |
| 100 | + pdf = export.export("pdf-latex", sample(), opts(scope="game", plies=8)) | |
| 101 | + self.assertTrue(pdf.startswith(b"%PDF")) | |
| 102 | + | |
| 103 | + | |
| 104 | +class ImageAndPageTest(unittest.TestCase): | |
| 105 | + def test_svg_and_png(self): | |
| 106 | + svg = export.export("svg", sample(), opts(scope="game", plies=8)) | |
| 107 | + self.assertIn("<svg", svg) | |
| 108 | + png = export.export("png", sample(), opts(plies=8, players=False, evals=False)) | |
| 109 | + self.assertTrue(png.startswith(b"\x89PNG")) | |
| 110 | + width, height = int.from_bytes(png[16:20], "big"), int.from_bytes(png[20:24], "big") | |
| 111 | + self.assertEqual((width, height), (800, 800)) # ohne Köpfe und Balken: quadratisch | |
| 112 | + | |
| 113 | + def test_pdf(self): | |
| 114 | + for scope in ("position", "game"): | |
| 115 | + pdf = export.export("pdf", sample(), opts(scope=scope, plies=8)) | |
| 116 | + self.assertTrue(pdf.startswith(b"%PDF")) | |
| 117 | + | |
| 118 | + @unittest.skipUnless(shutil.which("pdfinfo"), "pdfinfo fehlt") | |
| 119 | + def test_long_game_pdf_gets_more_pages(self): | |
| 120 | + state = sample() | |
| 121 | + board = chess.Board() | |
| 122 | + for _ in range(60): # Springer hin und her: 120 Züge | |
| 123 | + for san in ("Nf3", "Nf6", "Ng1", "Ng8"): | |
| 124 | + board.push_san(san) | |
| 125 | + state.board, state.symbols, state.evals = board, {}, {} | |
| 126 | + pdf = export.export("pdf", state, opts(scope="game")) | |
| 127 | + with tempfile.NamedTemporaryFile(suffix=".pdf") as fh: | |
| 128 | + fh.write(pdf) | |
| 129 | + fh.flush() | |
| 130 | + info = subprocess.run(["pdfinfo", fh.name], capture_output=True, text=True).stdout | |
| 131 | + self.assertEqual(int(re.search(r"Pages:\s+(\d+)", info).group(1)), 2) | |
| 132 | + | |
| 133 | + def test_html_game_has_one_group_per_position(self): | |
| 134 | + page = export.export("html", sample(), opts(scope="game", plies=8)) | |
| 135 | + groups = re.findall(r'<g class="ply" data-ply="(\d+)"( style="display:none")?>', page) | |
| 136 | + self.assertEqual(len(groups), len(MOVES) + 1) | |
| 137 | + visible = [ply for ply, hidden in groups if not hidden] | |
| 138 | + self.assertEqual(visible, ["8"]) | |
| 139 | + self.assertIn('"start": 8', page) | |
| 140 | + self.assertIn("user-select: all", page) | |
| 141 | + self.assertIn("Sxe5", page) | |
| 142 | + | |
| 143 | + def test_html_position_only(self): | |
| 144 | + page = export.export("html", sample(), opts(plies=3, players=False)) | |
| 145 | + self.assertEqual(len(re.findall(r'<g class="ply"', page)), 1) | |
| 146 | + self.assertNotIn('class="moves"', page) | |
| 147 | + self.assertNotIn("Florian", page) | |
| 148 | + | |
| 149 | + def test_html_escapes_script_end(self): | |
| 150 | + state = sample() | |
| 151 | + state.names = ("</script><b>", "Max") | |
| 152 | + page = export.export("html", state, opts(scope="game")) | |
| 153 | + self.assertEqual(page.count("</script>"), 2) | |
| 154 | + | |
| 155 | + | |
| 156 | +class MetaTest(unittest.TestCase): | |
| 157 | + def test_filename(self): | |
| 158 | + self.assertRegex(export.filename("pdf", sample(), opts(scope="game")), r"^partie-\d{4}-\d\d-\d\d\.pdf$") | |
| 159 | + self.assertRegex(export.filename("png", sample(), opts(scope="game")), r"^stellung-.*\.png$") | |
| 160 | + | |
| 161 | + def test_every_format_has_writer(self): | |
| 162 | + for fmt in export.FORMATS: | |
| 163 | + if fmt == "pdf-latex": | |
| 164 | + continue | |
| 165 | + for scope in export.FORMATS[fmt].scopes: | |
| 166 | + self.assertTrue(export.export(fmt, sample(), opts(scope=scope, plies=5))) | |
| 167 | + | |
| 168 | + | |
| 169 | +if __name__ == "__main__": | |
| 170 | + unittest.main() | |