Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

feat(export): animated PNG/WebP and recorded move times

public

feat(export): animated PNG/WebP and recorded move times

- Export the game as animated PNG (own APNG writer, no new dependency):
  only changed tiles per frame, blended over the previous one on an opaque
  background; 1.5 s per ply, 3 s on the final position.
- Optional WebP when Pillow has libwebp: still image of the position or
  lossless animation of the game, about half the size of the APNG.
- Record thinking time per move (vs. Maia, duo, Lichess), save it as [%emt],
  derive it from Lichess [%clk]; Lichess exports now include clocks.
- New export switch "Zugzeit": [%emt] in PGN, frame durations in the
  animations, times next to each move in HTML and PDF.
- Show move times in the window's move list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Changeset3c25b2ae34730900b9f43d171ab79f94d03eee80
Author (claimed)Timo Stolz <timo.stolz@nullachtvierzehn.de>,
Parents00427af512e9
Children3c9deb297eb3
Pushlog
by timo via ssh
by timo via ssh

modified ROADMAP.md +19 −1

@@ -580,6 +580,11 @@ Zwischenablage (außer PDF):
580580
 - PGN (Partie oder Stellung mit `[FEN]`-Kopf), FEN
581581
 - Bild der Stellung: SVG oder PNG (statt WebP: PNG braucht keine neue Abhängigkeit
582582
   und lässt sich überall einfügen)
583
+- Animiertes PNG (APNG) der Partie, 640 Pixel breit, endlos (23.11.2026): ohne neue
584
+  Abhängigkeit, die PNG-Daten schreibt `export.py` selbst. Jedes Bild enthält nur die
585
+  geänderten Kacheln als Auflage, deshalb auf deckendem hellem Hintergrund. 1,5 s pro
586
+  Halbzug, 3 s am Ende, oder mit „Zugzeit“ so lange, wie der Zug gedauert hat. MNG und
587
+  animiertes SVG verworfen: MNG zeigt kein Browser, SVG-Animation kaum ein Messenger.
583588
 - LaTeX mit `xskak`: Zugfolge, Diagramm an der gezeigten Stellung
584589
 - PDF direkt mit Cairo, oder über LaTeX, wenn `pdflatex` installiert ist
585590
 - HTML als eine Datei: SVG-Brett, FEN zum Kopieren (`user-select: all`), Zugliste
@@ -587,7 +592,20 @@ Zwischenablage (außer PDF):
587592
 - ASCII-Art
588593
 
589594
 Umfang (Stellung oder Partie) und Darstellung (Zugzeichen, Gewinnchance,
590
-Spielerköpfe, letzter Zug, Drehung) sind schaltbar. Bilder nutzen dieselbe
595
+Spielerköpfe, letzter Zug, Drehung, Zugzeit) sind schaltbar.
596
+
597
+**Zugzeit** (23.11.2026): Gegen Maia, zu zweit und auf Lichess misst das Programm die
598
+Bedenkzeit jedes Zugs (`times` im Spielstand, im PGN als `[%emt]`). Lichess-Partien
599
+bringen `[%clk]` mit, daraus wird die Bedenkzeit errechnet. Exportiert wird sie mit dem
600
+Schalter „Zugzeit“: im PGN als `[%emt]`, im animierten PNG als Dauer der Bilder, in HTML
601
+und PDF klein neben jedem Zug der Zugliste („0,8 s“, „12 s“, „1:05“; im PDF dann zwei
602
+statt drei Spalten). Die Zugliste im Fenster zeigt sie immer, rechts in jeder Zeile.
603
+
604
+**WebP** (23.11.2026), nur wenn Pillow mit libwebp installiert ist, sonst fehlt das
605
+Format im Dialog (wie „PDF über LaTeX“ ohne `pdflatex`). Verlustfrei, Stellung oder Partie:
606
+- Stellung: Standbild wie das PNG (800 Pixel, durchsichtig), etwa 36 statt 92 KB.
607
+- Partie: dieselben Bilder wie das APNG, etwa halb so groß (14 Halbzüge: 99 statt 201 KB;
608
+  120 Halbzüge: 481 statt 1041 KB). Verlustbehaftet war größer und viel langsamer. Bilder nutzen dieselbe
591609
 Zeichenroutine wie das Fenster (`schach/diagram.py`, `BoardPainter`).
592610
 
593611
 ## Weitere Vorhaben (je eine Datei in `roadmap/`)

modified schach/app.py +27 −2

@@ -46,6 +46,7 @@ DEFAULT_HELPER = "maia2000"
4646
 THREAT_SOURCES = {"opponent": "wie der Gegner", "stockfish": "Stockfish"}
4747
 OPPONENT_TEMPERATURE = 1.0  # menschliche Streuung; 0 = immer der wahrscheinlichste Zug
4848
 MIN_REPLY_SECONDS = 0.6
49
+TIMED_MODES = ("maia", "duo", "online")  # hier zählt die Bedenkzeit; nicht beim Ansehen, Rätseln, Kurs
4950
 AUTOSAVE_DELAY_MS = 800
5051
 
5152
 # Übersicht für den Reiter „Tastenkürzel“ in den Einstellungen
@@ -160,6 +161,9 @@ class Window(OnlineMixin, PuzzleMixin, O
160161
         self.save_path = ""
161162
         self._autosave_source = 0
162163
         self.evals = {}  # Halbzug-Index -> Gewinnchance Weiß (%) nach diesem Zug
164
+        self.times = {}  # Halbzug-Index -> Bedenkzeit für diesen Zug (ms), siehe _track_time
165
+        self._times_len = 0  # Länge der Zugfolge beim letzten _track_time
166
+        self._turn_since = time.monotonic()  # seitdem ist der Spieler am Zug
163167
         self.eval_requested = set()
164168
         self.key_ply = {}  # FEN -> Halbzug-Index der Stellung
165169
         self.browse_ply = None  # in der Zugliste gewählte Stellung (nur Ansicht)
@@ -880,7 +884,25 @@ class Window(OnlineMixin, PuzzleMixin, O
880884
         n = len(self.board.move_stack)
881885
         return n >= 1 if self.human == chess.WHITE else n >= 2
882886
 
887
+    def _track_time(self):
888
+        """Bedenkzeit des eben gespielten Zugs merken (gegen Maia, zu zweit, auf Lichess).
889
+
890
+        Gemessen wird von der vorigen Änderung der Zugfolge bis zu diesem Zug. Rücknahmen
891
+        und Sprünge setzen nur den Startpunkt neu.
892
+        """
893
+        n = len(self.board.move_stack)
894
+        if n == self._times_len:
895
+            return
896
+        now = time.monotonic()
897
+        if n == self._times_len + 1 and self.mode in TIMED_MODES:
898
+            self.times[n - 1] = round((now - self._turn_since) * 1000)
899
+        for ply in [p for p in self.times if p >= n]:
900
+            del self.times[ply]
901
+        self._times_len = n
902
+        self._turn_since = now
903
+
883904
     def _changed(self):
905
+        self._track_time()
884906
         self._schedule_autosave()
885907
         self._wait_done()  # eine laufende Rechnung gehörte zur alten Stellung
886908
         self.gen += 1
@@ -1442,7 +1464,7 @@ class Window(OnlineMixin, PuzzleMixin, O
14421464
             self.stockfish.submit(annotate.fallback_job(before, move), on_result)
14431465
 
14441466
     def _truncate_extras(self, n):
1445
-        for table in (self.symbols, self.evals, self.takebacks):
1467
+        for table in (self.symbols, self.evals, self.takebacks, self.times):
14461468
             for ply in [p for p in table if p >= n]:
14471469
                 del table[ply]
14481470
         self.eval_requested = {(p, m) for p, m in self.eval_requested if p < n}
@@ -1474,7 +1496,7 @@ class Window(OnlineMixin, PuzzleMixin, O
14741496
                 top = top.parent
14751497
             selected = next((i for i, (_p, _t, n) in enumerate(self.list_variations) if n is top), None)
14761498
         self.movelist.update(self.board, self.evals, self.symbols, None if selected is not None else self._list_ply(),
1477
-                             [(p, t) for p, t, _n in self.list_variations], selected)
1499
+                             [(p, t) for p, t, _n in self.list_variations], selected, times=self.times)
14781500
 
14791501
     def _on_list_variation(self, index):
14801502
         if 0 <= index < len(getattr(self, "list_variations", ())) and not (self.demo and self.demo["busy"]):
@@ -1922,6 +1944,7 @@ class Window(OnlineMixin, PuzzleMixin, O
19221944
             names=("Weiß", "Schwarz") if self.mode == "duo" else self.names,
19231945
             variations=self._game_variations() if variations else {},
19241946
             takebacks={p: list(v) for p, v in self.takebacks.items()},
1947
+            times=dict(self.times),
19251948
         )
19261949
 
19271950
     def load_state(self, state):
@@ -1937,6 +1960,8 @@ class Window(OnlineMixin, PuzzleMixin, O
19371960
         self.eval_requested = set()
19381961
         self.symbols = dict(state.symbols)
19391962
         self.evals = dict(state.evals)
1963
+        self.times = dict(state.times)
1964
+        self._times_len, self._turn_since = len(self.board.move_stack), time.monotonic()
19401965
         self.takebacks = {p: list(v) for p, v in state.takebacks.items()}
19411966
         self._game_tree_restore(state.variations)
19421967
         self.save_name = state.name

modified schach/export.py +260 −10

@@ -1,4 +1,4 @@
1
-"""Export einer Partie oder Stellung: PGN, FEN, SVG, PNG, LaTeX, PDF, HTML, ASCII.
1
+"""Export einer Partie oder Stellung: PGN, FEN, SVG, PNG, animiertes PNG und WebP, LaTeX, PDF, HTML, ASCII.
22
 
33
 Ohne Gtk, damit es sich testen lässt; der Dialog (exportdialog.py) sammelt nur die
44
 Optionen ein und entscheidet, ob das Ergebnis in eine Datei oder in die Zwischenablage geht.
@@ -13,13 +13,17 @@ import datetime
1313
 import html as html_mod
1414
 import io
1515
 import json
16
+import math
1617
 import re
1718
 import os
1819
 import shutil
20
+import sys
1921
 import subprocess
2022
 import tempfile
2123
 import textwrap
24
+import zlib
2225
 
26
+import cairo
2327
 import chess
2428
 import chess.pgn
2529
 
@@ -46,6 +50,7 @@ class Options:
4650
     flipped: bool = False  # Schwarz unten
4751
     variations: bool = True  # Nebenvarianten vom Analysebrett (PGN, HTML)
4852
     takebacks: bool = True  # zurückgenommene Züge als Nebenvariante (PGN, HTML)
53
+    move_times: bool = False  # Bedenkzeit je Zug: [%emt] im PGN, Bildfolge im animierten PNG
4954
     theme: str = BUILTIN_THEME
5055
     scheme: str = DEFAULT_SCHEME
5156
 
@@ -64,17 +69,22 @@ class Format:
6469
 _BOARD = frozenset({"last_move", "flipped"})
6570
 FORMATS = {
6671
     "pgn": Format("PGN", "pgn", "application/vnd.chess-pgn", ("position", "game"),
67
-                  frozenset({"symbols", "evals", "variations", "takebacks"})),
72
+                  frozenset({"symbols", "evals", "variations", "takebacks", "move_times"})),
6873
     "fen": Format("FEN", "fen", "text/plain", ("position",), frozenset()),
6974
     "svg": Format("SVG-Bild", "svg", "image/svg+xml", ("position",), _BOARD | {"symbols", "evals", "players"}),
7075
     "png": Format("PNG-Bild", "png", "image/png", ("position",), _BOARD | {"symbols", "evals", "players"}, binary=True),
76
+    "apng": Format("Animiertes PNG", "png", "image/apng", ("game",),
77
+                   _BOARD | {"symbols", "evals", "players", "move_times"}, binary=True,
78
+                   clipboard=False),  # über die Zwischenablage käme nur das erste Bild an
79
+    "webp": Format("WebP", "webp", "image/webp", ("position", "game"),
80
+                   _BOARD | {"symbols", "evals", "players", "move_times"}, binary=True, clipboard=False),
7181
     "latex": Format("LaTeX (xskak)", "tex", "text/x-tex", ("position", "game"), _BOARD | {"symbols", "players"}),
7282
     "pdf": Format("PDF", "pdf", "application/pdf", ("position", "game"),
73
-                  _BOARD | {"symbols", "evals", "players"}, binary=True, clipboard=False),
83
+                  _BOARD | {"symbols", "evals", "players", "move_times"}, binary=True, clipboard=False),
7484
     "pdf-latex": Format("PDF über LaTeX", "pdf", "application/pdf", ("position", "game"),
7585
                         _BOARD | {"symbols", "players"}, binary=True, clipboard=False),
7686
     "html": Format("HTML-Seite", "html", "text/html", ("position", "game"),
77
-                   _BOARD | {"symbols", "evals", "players", "variations", "takebacks"}),
87
+                   _BOARD | {"symbols", "evals", "players", "variations", "takebacks", "move_times"}),
7888
     "ascii": Format("ASCII-Art", "txt", "text/plain", ("position", "game"), {"flipped", "symbols", "players"}),
7989
 }
8090
 
@@ -215,6 +225,12 @@ def _moves(state):
215225
     return result
216226
 
217227
 
228
+def _time(state, ply, opts):
229
+    """Bedenkzeit für Halbzug ``ply`` als Text, wenn sie exportiert wird; sonst None."""
230
+    ms = state.times.get(ply) if opts.move_times else None
231
+    return None if ms is None else notation.format_time(ms)
232
+
233
+
218234
 def move_text(state, opts, start=0, stop=None, san_style=None):
219235
     """Zugfolge „1. e4 e5 2. Sf3 …“ von Halbzug ``start`` bis vor ``stop``."""
220236
     words = []
@@ -240,7 +256,9 @@ def to_fen(state, opts):
240256
 def to_pgn(state, opts):
241257
     """PGN mit Eröffnung (Kopfzeilen ECO/Opening, Kommentar „Bis hier: …“ am letzten Buchzug)."""
242258
     state = dataclasses.replace(state, variations=state.variations if opts.variations else {},
243
-                                takebacks=state.takebacks if opts.takebacks else {})
259
+                                takebacks=state.takebacks if opts.takebacks else {},
260
+                                evals=state.evals if opts.evals else {},
261
+                                times=state.times if opts.move_times else {})
244262
     game = chess.pgn.read_game(io.StringIO(savegames.to_pgn(state)))
245263
     if opts.scope == "position":
246264
         plies = _plies(state, opts)
@@ -260,8 +278,6 @@ def to_pgn(state, opts):
260278
     for ply, node in enumerate(game.mainline()):
261279
         if not opts.symbols:
262280
             node.nags.clear()
263
-        if not opts.evals:
264
-            node.comment = ""
265281
         if ply == book_ply:
266282
             node.comment = " ".join(filter(None, [book_comment(eco, name), node.comment]))
267283
     return str(game) + "\n"
@@ -486,7 +502,8 @@ def to_pdf(state, opts):
486502
 
487503
     # Zugliste: drei Spalten, je Zeile ein Zugpaar; Balken unter jedem Halbzug
488504
     y += 18
489
-    columns, gap, row_h = 3, 18, 17
505
+    timed = opts.move_times and bool(state.times)
506
+    columns, gap, row_h = (2 if timed else 3), 18, 17  # mit Zugzeit braucht jeder Zug mehr Platz
490507
     col_w = (text_width - gap * (columns - 1)) / columns
491508
     moves = _moves(state)
492509
     rows = []
@@ -508,6 +525,9 @@ def to_pdf(state, opts):
508525
             sym = state.symbols[ply]
509526
             mark += f" <span foreground='{hex_color(BADGE[sym])}' weight='heavy'>{html_mod.escape(sym)}</span>"
510527
         text(mark, x, yy, size=9)
528
+        spent = _time(state, ply, opts)
529
+        if spent:  # rechtsbündig über dem Balken, klein und grau
530
+            text(f"<span alpha='55%'>{spent}</span>", x, yy + 1.5, size=6.5, w=w - 8, align=Pango.Alignment.RIGHT)
511531
         wp = state.evals.get(ply) if opts.evals else None
512532
         if wp is not None:
513533
             bar_w, bar_h, bar_y = w - 8, 3.2, yy + row_h - 3.8
@@ -701,6 +721,9 @@ button:focus-visible { outline: 2px soli
701721
   background: linear-gradient(90deg, #e9e9e4 var(--wp), #2b2b2e var(--wp)); outline: 1px solid var(--line); }
702722
 .moves .start { grid-column: 1 / -1; }
703723
 .moves b.s { font-weight: 800; margin-left: 2px; }
724
+.moves small.t { float: right; margin-left: 6px; font-size: .78em; line-height: 1.8; color: var(--muted);
725
+  font-variant-numeric: tabular-nums; }
726
+.moves button.sel small.t { color: inherit; opacity: .8; }
704727
 .result { grid-column: 1 / -1; padding: 4px 8px; font-weight: 600; }
705728
 """
706729
 
@@ -884,6 +907,9 @@ def to_html(state, opts):
884907
             if opts.symbols and ply in state.symbols:
885908
                 sym = state.symbols[ply]
886909
                 label += f'<b class="s" style="color:{hex_color(BADGE[sym])}">{esc(sym)}</b>'
910
+            spent = _time(state, ply, opts)
911
+            if spent:
912
+                label += f'<small class="t" title="Bedenkzeit">{esc(spent)}</small>'
887913
             ev = state.evals.get(ply) if opts.evals else None
888914
             if ev is not None:
889915
                 label += f'<i style="--wp:{ev:.1f}%"></i>'
@@ -913,16 +939,238 @@ def to_png(state, opts):
913939
     return diagram(state, opts).png(800)
914940
 
915941
 
942
+# --- Animiertes PNG (APNG) -----------------------------------------------------
943
+#
944
+# Cairo zeichnet jede Stellung; PNG-Daten und die Blöcke acTL, fcTL und fdAT schreiben wir
945
+# selbst (https://www.w3.org/TR/png-3/#apng-frame-control-chunk), damit alle Bilder dasselbe
946
+# Format haben – Cairo schreibt deckende Bilder als RGB, Auflagen aber als RGBA.
947
+
948
+APNG_WIDTH = 640
949
+APNG_DELAY_MS = 1500  # pro Halbzug, wenn nicht nach Zugzeit
950
+APNG_END_MS = 3000  # Schlussstellung, bevor es von vorn beginnt
951
+APNG_MIN_MS = 100  # kürzer zeigen Browser ohnehin nicht
952
+TILE = 16  # Kantenlänge der Kacheln, in denen Änderungen gesucht werden
953
+APNG_BACKGROUND = (0xFA / 255, 0xFA / 255, 0xF9 / 255)  # wie die HTML-Seite im hellen Modus
954
+
955
+
956
+def _chunk(kind, body):
957
+    return len(body).to_bytes(4, "big") + kind + body + zlib.crc32(kind + body).to_bytes(4, "big")
958
+
959
+
960
+def _delay(ms):
961
+    """(Zähler, Nenner) für fcTL; beide nur 16 Bit."""
962
+    ms = max(APNG_MIN_MS, round(ms))
963
+    if ms <= 0xFFFF:
964
+        return ms, 1000
965
+    return min(0xFFFF, round(ms / 10)), 100
966
+
967
+
968
+def _frames(state, opts):
969
+    """[(diagramm, dauer_ms)] von der Ausgangsstellung bis zum Ende der Partie.
970
+
971
+    Jedes Bild steht so lange, wie der nächste Zug gedauert hat (``move_times``), sonst
972
+    ``APNG_DELAY_MS``.
973
+    """
974
+    total = len(state.board.move_stack)
975
+    with_bar = opts.evals and bool(state.evals)
976
+    names = None
977
+    if opts.players:
978
+        i = info(state)
979
+        names = {chess.WHITE: i.white, chess.BLACK: i.black}
980
+    times = state.times if opts.move_times else {}
981
+    frames, bar = [], 50.0
982
+    for plies in range(total + 1):
983
+        board = board_at(state, plies)
984
+        if with_bar and plies:  # alle Bilder gleich groß: fehlende Werte erben den vorigen
985
+            bar = state.evals.get(plies - 1, bar)
986
+        delay = APNG_END_MS if plies == total else times.get(plies, APNG_DELAY_MS)
987
+        frames.append((Diagram(
988
+            board, theme=opts.theme, scheme=opts.scheme, flipped=opts.flipped, last_move=opts.last_move,
989
+            badge=_badge(state, board, opts), names=names, eval_bar=bar if with_bar else None,
990
+        ), delay))
991
+    return frames
992
+
993
+
994
+def _changed_tiles(old, new, stride, width, height):
995
+    """[(x, y, w, h)] der Kacheln, in denen sich Pixel geändert haben."""
996
+    tiles = []
997
+    for ty in range(0, height, TILE):
998
+        rows = range(ty, min(ty + TILE, height))
999
+        if all(old[y * stride:(y + 1) * stride] == new[y * stride:(y + 1) * stride] for y in rows):
1000
+            continue
1001
+        for tx in range(0, width, TILE):
1002
+            a, b = tx * 4, min(tx + TILE, width) * 4
1003
+            if any(old[y * stride + a:y * stride + b] != new[y * stride + a:y * stride + b] for y in rows):
1004
+                tiles.append((tx, ty, (b - a) // 4, len(rows)))
1005
+    return tiles
1006
+
1007
+
1008
+def _region(pixels, stride, box, tiles=None):
1009
+    """Die Pixel in ``box`` als zusammenhängender Puffer (4 Byte pro Pixel, Cairo-Reihenfolge).
1010
+
1011
+    Mit ``tiles`` nur diese Kacheln, der Rest durchsichtig – für blend OVER, das die
1012
+    durchsichtigen Pixel des vorigen Bilds stehen lässt.
1013
+    """
1014
+    x, y, w, h = box
1015
+    if tiles is None:
1016
+        return b"".join(pixels[row * stride + x * 4:row * stride + (x + w) * 4] for row in range(y, y + h))
1017
+    out = bytearray(w * 4 * h)
1018
+    for tx, ty, tw, th in tiles:
1019
+        for row in range(ty, ty + th):
1020
+            dst = (row - y) * w * 4 + (tx - x) * 4
1021
+            out[dst:dst + tw * 4] = pixels[row * stride + tx * 4:row * stride + (tx + tw) * 4]
1022
+    return bytes(out)
1023
+
1024
+
1025
+def _byte_minus(a, b):
1026
+    """(a − b) mod 256 für jedes Byte zweier gleich langer Puffer – in einem Rutsch über große Zahlen."""
1027
+    n = len(a)
1028
+    high, low = int.from_bytes(b"\x80" * n, "big"), int.from_bytes(b"\x7f" * n, "big")
1029
+    x, y = int.from_bytes(a, "big"), int.from_bytes(b, "big")
1030
+    # Byteweise ohne Übertrag: die oberen Bits gesetzt, damit kein Byte beim Nachbarn borgt,
1031
+    # dann das richtige oberste Bit wieder einsetzen.
1032
+    z = ((x | high) - (y & low)) ^ ((x ^ ~y) & high)
1033
+    return z.to_bytes(n, "big")
1034
+
1035
+
1036
+def _encode(pixels, width, height):
1037
+    """IDAT-Daten für Cairo-Pixel mit Alpha 255 oder 0, als 8-Bit-RGBA.
1038
+
1039
+    Je Zeile wird der PNG-Filter (keiner, Sub oder Up) genommen, der die meisten Nullbytes ergibt.
1040
+    """
1041
+    order = (2, 1, 0, 3) if sys.byteorder == "little" else (1, 2, 3, 0)  # Cairo: ARGB als 32-Bit-Zahl
1042
+    rgba = bytearray(len(pixels))
1043
+    for target, source in enumerate(order):
1044
+        rgba[target::4] = pixels[source::4]
1045
+    rgba = bytes(rgba)
1046
+    line = width * 4
1047
+    rows = [rgba[y * line:(y + 1) * line] for y in range(height)]
1048
+    left = b"".join(b"\0\0\0\0" + row[:-4] for row in rows)
1049
+    sub = _byte_minus(rgba, left)
1050
+    up = _byte_minus(rgba, b"\0" * line + rgba[:-line])
1051
+    out = []
1052
+    for y, row in enumerate(rows):
1053
+        options = (row, sub[y * line:(y + 1) * line], up[y * line:(y + 1) * line])
1054
+        kind = max(range(3), key=lambda k: options[k].count(0))
1055
+        out.append(bytes((kind,)) + options[kind])
1056
+    return zlib.compress(b"".join(out), 9)
1057
+
1058
+
1059
+def _rendered(state, opts):
1060
+    """Je Bild der Animation (Cairo-Pixel, Zeilenlänge, Breite, Höhe, Dauer in ms).
1061
+
1062
+    Deckend auf hellem Hintergrund: lesbar auf jedem Untergrund (Messenger im Dunkelmodus),
1063
+    und beim APNG bleibt die Auflage mit blend OVER exakt.
1064
+    """
1065
+    frames = _frames(state, opts)
1066
+    width = APNG_WIDTH
1067
+    height = math.ceil(width * frames[0][0].aspect())
1068
+    for diagram_, delay in frames:
1069
+        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
1070
+        cr = cairo.Context(surface)
1071
+        cr.set_source_rgb(*APNG_BACKGROUND)
1072
+        cr.paint()
1073
+        diagram_.render(cr, 0, 0, width)
1074
+        surface.flush()
1075
+        yield bytes(surface.get_data()), surface.get_stride(), width, height, delay
1076
+
1077
+
1078
+def to_apng(state, opts):
1079
+    """Die Partie als animiertes PNG, endlos wiederholt.
1080
+
1081
+    Das erste Bild ist ein gewöhnliches PNG (IDAT), das Programme ohne APNG zeigen. Danach
1082
+    enthält jedes Bild nur das Rechteck um die geänderten Kacheln, möglichst als Auflage
1083
+    (blend OVER) mit durchsichtigem Rest; das komprimiert viel besser.
1084
+    """
1085
+    previous, body = None, []  # body: [box, dauer_ms, blend, idat]
1086
+    for pixels, stride, width, height, delay in _rendered(state, opts):
1087
+        if previous is None:
1088
+            box, blend = (0, 0, width, height), 0
1089
+            data = _region(pixels, stride, box)
1090
+        else:
1091
+            tiles = _changed_tiles(previous, pixels, stride, width, height)
1092
+            if not tiles:  # nichts geändert: das vorige Bild länger zeigen
1093
+                body[-1][1] += delay
1094
+                continue
1095
+            left, top = min(t[0] for t in tiles), min(t[1] for t in tiles)
1096
+            box = (left, top, max(t[0] + t[2] for t in tiles) - left, max(t[1] + t[3] for t in tiles) - top)
1097
+            blend, data = 1, _region(pixels, stride, box, tiles)
1098
+        body.append([box, delay, blend, _encode(data, box[2], box[3])])
1099
+        previous = pixels
1100
+
1101
+    ihdr = width.to_bytes(4, "big") + height.to_bytes(4, "big") + bytes((8, 6, 0, 0, 0))  # 8 Bit RGBA
1102
+    out = [b"\x89PNG\r\n\x1a\n", _chunk(b"IHDR", ihdr),
1103
+           _chunk(b"acTL", len(body).to_bytes(4, "big") + (0).to_bytes(4, "big"))]  # 0 = endlos
1104
+    sequence = 0
1105
+    for index, ((x, y, w, h), delay, blend, idat) in enumerate(body):
1106
+        num, den = _delay(delay)
1107
+        fctl = b"".join(v.to_bytes(4, "big") for v in (sequence, w, h, x, y))
1108
+        fctl += num.to_bytes(2, "big") + den.to_bytes(2, "big") + bytes((0, blend))  # dispose none
1109
+        out.append(_chunk(b"fcTL", fctl))
1110
+        sequence += 1
1111
+        if index == 0:
1112
+            out.append(_chunk(b"IDAT", idat))
1113
+        else:
1114
+            out.append(_chunk(b"fdAT", sequence.to_bytes(4, "big") + idat))
1115
+            sequence += 1
1116
+    out.append(_chunk(b"IEND", b""))
1117
+    return b"".join(out)
1118
+
1119
+
1120
+def webp_available():
1121
+    """Pillow mit libwebp installiert? Nur dann gibt es „Animiertes WebP“."""
1122
+    try:
1123
+        from PIL import features
1124
+    except ImportError:
1125
+        return False
1126
+    return bool(features.check("webp"))
1127
+
1128
+
1129
+def to_webp(state, opts):
1130
+    """Stellung als Bild oder Partie als Animation, verlustfrei; braucht Pillow.
1131
+
1132
+    Die Animation ist etwa halb so groß wie das APNG. Verlustbehaftet wäre sie bei den
1133
+    flachen Farbflächen des Bretts größer und viel langsamer.
1134
+    """
1135
+    try:
1136
+        from PIL import Image
1137
+    except ImportError as exc:
1138
+        raise ExportError("Für WebP fehlt das Python-Paket Pillow") from exc
1139
+    if opts.scope == "position":  # wie das PNG-Bild: 800 Pixel, durchsichtiger Hintergrund
1140
+        dia = diagram(state, opts)
1141
+        width = 800
1142
+        height = math.ceil(width * dia.aspect())
1143
+        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
1144
+        dia.render(cairo.Context(surface), 0, 0, width)
1145
+        surface.flush()
1146
+        mode = "BGRa" if sys.byteorder == "little" else "aRGB"  # Cairo: vormultipliziertes Alpha
1147
+        image = Image.frombuffer("RGBA", (width, height), bytes(surface.get_data()), "raw", mode,
1148
+                                 surface.get_stride(), 1)
1149
+        out = io.BytesIO()
1150
+        image.save(out, "WEBP", lossless=True, method=4)
1151
+        return out.getvalue()
1152
+    images, delays = [], []
1153
+    for pixels, stride, width, height, delay in _rendered(state, opts):
1154
+        # Cairo speichert ARGB als 32-Bit-Zahl; deckend, also ohne Vormultiplikation
1155
+        mode = "BGRA" if sys.byteorder == "little" else "ARGB"
1156
+        images.append(Image.frombuffer("RGBA", (width, height), pixels, "raw", mode, stride, 1).convert("RGB"))
1157
+        delays.append(max(APNG_MIN_MS, round(delay)))
1158
+    out = io.BytesIO()
1159
+    images[0].save(out, "WEBP", save_all=True, append_images=images[1:], duration=delays, loop=0,
1160
+                   lossless=True, method=2)  # method 2: so klein wie 6, aber schneller
1161
+    return out.getvalue()
1162
+
1163
+
9161164
 # --- Einstieg ----------------------------------------------------------------
9171165
 
9181166
 _WRITERS = {
919
-    "pgn": to_pgn, "fen": to_fen, "svg": to_svg, "png": to_png, "latex": to_latex,
1167
+    "pgn": to_pgn, "fen": to_fen, "svg": to_svg, "png": to_png, "apng": to_apng, "webp": to_webp, "latex": to_latex,
9201168
     "pdf": to_pdf, "pdf-latex": to_pdf_latex, "html": to_html, "ascii": to_ascii,
9211169
 }
9221170
 
9231171
 
9241172
 def export(fmt, state, opts):
925
-    """Inhalt als ``str`` (Textformate) oder ``bytes`` (PNG, PDF)."""
1173
+    """Inhalt als ``str`` (Textformate) oder ``bytes`` (PNG, APNG, WebP, PDF)."""
9261174
     if fmt not in FORMATS:
9271175
         raise ExportError(f"Unbekanntes Format: {fmt}")
9281176
     if opts.scope not in FORMATS[fmt].scopes:
@@ -934,5 +1182,7 @@ def filename(fmt, state, opts):
9341182
     """Vorschlag für den Dateinamen, z. B. „partie-2026-11-20.pdf“."""
9351183
     scope = opts.scope if opts.scope in FORMATS[fmt].scopes else FORMATS[fmt].scopes[0]
9361184
     base = "partie" if scope == "game" else "stellung"
1185
+    if fmt in ("apng", "webp") and scope == "game":
1186
+        base = "partie-animiert"
9371187
     return f"{base}-{datetime.date.today():%Y-%m-%d}.{FORMATS[fmt].extension}"
9381188
 

modified schach/exportdialog.py +31 −4

@@ -17,7 +17,7 @@ from gi.repository import Adw, Gdk, GLib
1717
 from . import export  # noqa: E402
1818
 
1919
 DEFAULTS = {"format": "pgn", "scope": "game", "symbols": True, "evals": True, "players": True, "last_move": True,
20
-            "variations": True, "takebacks": True}
20
+            "variations": True, "takebacks": True, "move_times": False}
2121
 
2222
 # Schalter für die Darstellung: (Option, Titel, Untertitel)
2323
 SWITCHES = [
@@ -28,13 +28,29 @@ SWITCHES = [
2828
     ("flipped", "Schwarz unten", "Brett gedreht"),
2929
     ("variations", "Varianten", "Selbst gezogene Züge vom Analysebrett"),
3030
     ("takebacks", "Zurückgenommene Züge", "Fehlversuche und Rücknahmen als Nebenvariante"),
31
+    ("move_times", "Zugzeit", "Wie lange jeder Zug gedauert hat"),
3132
 ]
3233
 
34
+# Untertitel, die vom Format abhängen: {Schalter: {Format: Untertitel}}
35
+SWITCH_HINTS = {
36
+    "move_times": {
37
+        "pgn": "Bedenkzeit an jedem Zug, als [%emt]",
38
+        "apng": "Jede Stellung so lange zeigen, wie der nächste Zug gedauert hat – sonst 1,5 Sekunden",
39
+        "webp": "Jede Stellung so lange zeigen, wie der nächste Zug gedauert hat – sonst 1,5 Sekunden",
40
+        "html": "Bedenkzeit neben jedem Zug in der Zugliste, im PGN als [%emt]",
41
+        "pdf": "Bedenkzeit neben jedem Zug in der Zugliste",
42
+    },
43
+}
44
+
45
+SWITCHES_BY_NAME = {key: subtitle for key, _title, subtitle in SWITCHES}
46
+
3347
 FORMAT_HINTS = {
3448
     "pgn": "Partie oder Stellung für andere Schachprogramme",
3549
     "fen": "Die Stellung als eine Zeile Text",
3650
     "svg": "Vektorbild des Bretts, wie es hier aussieht",
3751
     "png": "Bild des Bretts, 800 Pixel breit",
52
+    "apng": "Die Partie als Bildfolge, 640 Pixel breit – für Browser, Messenger und Webseiten",
53
+    "webp": "Bild der Stellung oder die Partie als Bildfolge – kleiner als PNG; nicht jeder Bildbetrachter kann es",
3854
     "latex": "Quelltext mit dem Paket xskak, zum Einbinden in eigene Dokumente",
3955
     "pdf": "Druckfertig: Diagramm und Zugliste",
4056
     "pdf-latex": "Druckfertig, gesetzt mit LaTeX (dauert einige Sekunden)",
@@ -55,7 +71,9 @@ class ExportDialog(Adw.Dialog):
5571
         )
5672
         settings = {**DEFAULTS, **(saved or {})}
5773
         self.saved = settings
58
-        self.formats = [key for key in export.FORMATS if key != "pdf-latex" or export.latex_available()]
74
+        self.formats = [key for key in export.FORMATS if (key != "pdf-latex" or export.latex_available())
75
+                        and (key != "webp" or export.webp_available())
76
+                        and (key != "apng" or state.board.move_stack)]
5977
         if settings["format"] not in self.formats:
6078
             settings["format"] = DEFAULTS["format"]
6179
 
@@ -96,6 +114,11 @@ class ExportDialog(Adw.Dialog):
96114
             row.set_active(False)
97115
             row.set_sensitive(False)
98116
             row.set_subtitle("In dieser Partie wurde kein Zug zurückgenommen")
117
+        if not state.times:  # aus und gesperrt, wie bei den Rücknahmen
118
+            row = self.switches["move_times"]
119
+            row.set_active(False)
120
+            row.set_sensitive(False)
121
+            row.set_subtitle("Für diese Partie sind keine Zugzeiten bekannt")
99122
         page.add(self.look)
100123
 
101124
         self.copy_btn = Gtk.Button(label="_Kopieren", use_underline=True, hexpand=True)
@@ -152,12 +175,16 @@ class ExportDialog(Adw.Dialog):
152175
             self._updating = False
153176
         game = self.scope.get_active_name() == "game"
154177
         shown = {name for name in self.switches if name in fmt.options and
155
-                 (name != "variations" or game and bool(self.state.variations))}
178
+                 (name != "variations" or game and bool(self.state.variations)) and
179
+                 (name != "move_times" or game)}  # bei einer Stellung gibt es keine Zugzeit
156180
         for name, row in self.switches.items():
157181
             row.set_visible(name in shown)
182
+            hints = SWITCH_HINTS.get(name)
183
+            if hints and row.get_sensitive():
184
+                row.set_subtitle(hints.get(key, SWITCHES_BY_NAME[name]))
158185
         self.look.set_visible(bool(shown))
159186
         self.copy_btn.set_sensitive(fmt.clipboard)
160
-        self.copy_btn.set_tooltip_text(None if fmt.clipboard else "PDF lässt sich nur als Datei speichern")
187
+        self.copy_btn.set_tooltip_text(None if fmt.clipboard else f"{fmt.label} lässt sich nur als Datei speichern")
161188
 
162189
     def _remember(self):
163190
         values = {"format": self._format(), "scope": self.wanted_scope}

modified schach/lichess.py +2 −2

@@ -340,14 +340,14 @@ class Client:
340340
         """Eine Partie als PGN – auch ohne Anmeldung, für öffentliche Partien."""
341341
         return self._get(
342342
             f"/game/export/{urllib.parse.quote(game_id)}",
343
-            params={"clocks": "false", "evals": "false", "literate": "false"},
343
+            params={"clocks": "true", "evals": "false", "literate": "false"},  # [%clk] → Zugzeiten
344344
             headers={"Accept": "application/x-chess-pgn"},
345345
         ).text
346346
 
347347
     def games(self, username, max_games=30):
348348
         resp = self._get(
349349
             f"/api/games/user/{urllib.parse.quote(username)}",
350
-            params={"max": max_games, "pgnInJson": "true", "opening": "true", "moves": "true"},
350
+            params={"max": max_games, "pgnInJson": "true", "opening": "true", "moves": "true", "clocks": "true"},
351351
             headers={"Accept": "application/x-ndjson"},
352352
             timeout=40,
353353
         )

modified schach/movelist.py +22 −8

@@ -19,6 +19,14 @@ CSS = b"""
1919
   font-feature-settings: "tnum";
2020
 }
2121
 .move-pill.selected-move { background: @accent_bg_color; color: @accent_fg_color; }
22
+.move-time {
23
+  background: alpha(white, 0.78);
24
+  color: alpha(#1e1e1e, 0.75);
25
+  border-radius: 6px;
26
+  padding: 0 6px;
27
+  font-size: smaller;
28
+  font-feature-settings: "tnum";
29
+}
2230
 .move-row-buttons button { min-height: 22px; min-width: 22px; padding: 1px; }
2331
 .variation-row { padding: 2px 8px 2px 30px; }
2432
 .variation-pill {
@@ -75,20 +83,23 @@ class MoveList(Gtk.Box):
7583
 
7684
     # --- Aufbau ------------------------------------------------------------
7785
 
78
-    def update(self, board, evals, symbols, selected, variations=(), selected_variation=None):
79
-        """Baut die Liste neu, wenn sich Züge, Bewertungen, Zeichen oder Varianten geändert haben.
86
+    def update(self, board, evals, symbols, selected, variations=(), selected_variation=None, times=None):
87
+        """Baut die Liste neu, wenn sich Züge, Bewertungen, Zeichen, Zugzeiten oder Varianten geändert haben.
8088
 
8189
         ``variations``: [(Halbzug, Text)] – Nebenvarianten vom Analysebrett, eingerückt unter dem Zug,
82
-        nach dem sie abzweigen (-1: vor dem ersten Zug). ``selected_variation``: Nummer darin."""
90
+        nach dem sie abzweigen (-1: vor dem ersten Zug). ``selected_variation``: Nummer darin.
91
+        ``times``: {Halbzug: ms} – Bedenkzeit, rechts in der Zeile."""
8392
         moves = list(board.move_stack)
93
+        times = times or {}
8494
         signature = (tuple(moves), tuple(sorted(evals.items())), tuple(sorted(symbols.items())), self.notation,
85
-                     tuple(variations))
95
+                     tuple(variations), tuple(sorted(times.items())))
8696
         if signature != self._signature:
8797
             self._signature = signature
88
-            self._rebuild(board, moves, evals, symbols, variations)
98
+            self._rebuild(board, moves, evals, symbols, variations, times)
8999
         self._apply_selection(selected, selected_variation)
90100
 
91
-    def _rebuild(self, board, moves, evals, symbols, variations=()):
101
+    def _rebuild(self, board, moves, evals, symbols, variations=(), times=None):
102
+        times = times or {}
92103
         self._updating = True
93104
         self.listbox.remove_all()
94105
         self._rows = []
@@ -103,7 +114,7 @@ class MoveList(Gtk.Box):
103114
             prefix = f"{number}." if replay.turn == chess.WHITE else f"{number}…"
104115
             san = notation.move(replay, move, self.notation)
105116
             replay.push(move)
106
-            self._rows.append(self._make_row(ply, prefix, san, symbols.get(ply), evals.get(ply)))
117
+            self._rows.append(self._make_row(ply, prefix, san, symbols.get(ply), evals.get(ply), times.get(ply)))
107118
             ordered.append(self._rows[-1][0])
108119
             ordered += [self._make_variation_row(i, t) for i, t in after.get(ply, [])]
109120
         for row in ordered:
@@ -118,7 +129,7 @@ class MoveList(Gtk.Box):
118129
         if self.listbox.get_selected_row() is None:
119130
             adj.set_value(adj.get_upper() - adj.get_page_size())
120131
 
121
-    def _make_row(self, ply, prefix, san, symbol, white_pct):
132
+    def _make_row(self, ply, prefix, san, symbol, white_pct, ms=None):
122133
         bar = Gtk.DrawingArea(content_height=30, hexpand=True)
123134
         bar.set_draw_func(self._draw_bar, white_pct)
124135
 
@@ -148,6 +159,9 @@ class MoveList(Gtk.Box):
148159
         content = Gtk.Box(spacing=6, margin_start=8, margin_end=8)
149160
         content.append(pill)
150161
         content.append(Gtk.Box(hexpand=True))
162
+        if ms is not None:
163
+            content.append(Gtk.Label(label=notation.format_time(ms), css_classes=["move-time"],
164
+                                     valign=Gtk.Align.CENTER, tooltip_text="Bedenkzeit"))
151165
         content.append(buttons)
152166
 
153167
         overlay = Gtk.Overlay(child=bar)

modified schach/notation.py +15 −0

@@ -42,3 +42,18 @@ def text(german_text, style=DEFAULT):
4242
         return f"{m.group(5)}={m.group(6).translate(_TO_EN)}"
4343
 
4444
     return _GERMAN_MOVE.sub(english, german_text)
45
+
46
+
47
+def format_time(ms):
48
+    """Bedenkzeit kurz: „0,8 s“, „12 s“, „1:05“, „1:02:03“."""
49
+    seconds = ms / 1000
50
+    if seconds < 9.95:
51
+        return f"{seconds:.1f} s".replace(".", ",")
52
+    seconds = round(seconds)
53
+    if seconds < 60:
54
+        return f"{seconds} s"
55
+    minutes, seconds = divmod(seconds, 60)
56
+    if minutes < 60:
57
+        return f"{minutes}:{seconds:02d}"
58
+    hours, minutes = divmod(minutes, 60)
59
+    return f"{hours}:{minutes:02d}:{seconds:02d}"

modified schach/savegames.py +33 −0

@@ -46,6 +46,7 @@ class GameState:
4646
     # Zurückgenommene Züge (vom Kurs oder selbst), gleiches Format wie ``variations``. Im PGN eine
4747
     # Nebenvariante mit [%zurueck kurs] bzw. [%zurueck selbst] im Kommentar des ersten Zugs.
4848
     takebacks: dict = dataclasses.field(default_factory=dict)
49
+    times: dict = dataclasses.field(default_factory=dict)  # Halbzug-Index -> Bedenkzeit für diesen Zug (ms)
4950
 
5051
     def truncated(self, ply):
5152
         """Kopie bis einschließlich Halbzug ``ply`` (für Abzweigungen)."""
@@ -61,6 +62,7 @@ class GameState:
6162
             evals={p: e for p, e in self.evals.items() if p < n},
6263
             variations={p: v for p, v in self.variations.items() if p < n},
6364
             takebacks={p: v for p, v in self.takebacks.items() if p < n},
65
+            times={p: t for p, t in self.times.items() if p < n},
6466
         )
6567
 
6668
 
@@ -101,6 +103,8 @@ def to_pgn(state):
101103
             node.nags.add(NAG[state.symbols[ply]])
102104
         if ply in state.evals:
103105
             node.comment = f"[%wp {state.evals[ply]:.1f}]"
106
+        if ply in state.times:
107
+            node.set_emt(round(state.times[ply] / 1000, 1))  # [%emt 0:00:03.5]
104108
     for table in (state.variations, state.takebacks):
105109
         for ply, variations in sorted(table.items()):
106110
             if ply in played:
@@ -182,6 +186,33 @@ def _add_variation(parent, variation):
182186
         _add_variation(node, child)
183187
 
184188
 
189
+def _time_control(headers):
190
+    """(Grundzeit, Zuschlag) in Sekunden aus „180+2“; None ohne Uhr oder bei anderen Formen."""
191
+    match = re.fullmatch(r"(\d+)(?:\+(\d+))?", headers.get("TimeControl", ""))
192
+    return (int(match.group(1)), int(match.group(2) or 0)) if match else None
193
+
194
+
195
+def read_times(game):
196
+    """{Halbzug: ms} aus [%emt] (Bedenkzeit) oder, wie bei Lichess, aus [%clk] (Restzeit)."""
197
+    times = {}
198
+    control = _time_control(game.headers)
199
+    last = {}  # Farbe -> Restzeit nach ihrem vorigen Zug
200
+    board = game.board()
201
+    for ply, node in enumerate(game.mainline()):
202
+        color = board.turn
203
+        board.push(node.move)
204
+        emt, clock = node.emt(), node.clock()
205
+        if emt is not None:
206
+            times[ply] = round(emt * 1000)
207
+        elif clock is not None and (color in last or control):
208
+            before = last.get(color, control[0] if control else clock)
209
+            increment = control[1] if control else 0
210
+            times[ply] = max(0, round((before - clock + increment) * 1000))
211
+        if clock is not None:
212
+            last[color] = clock
213
+    return times
214
+
215
+
185216
 def from_pgn(text, path=""):
186217
     game = chess.pgn.read_game(io.StringIO(text))
187218
     if game is None:
@@ -189,6 +220,7 @@ def from_pgn(text, path=""):
189220
     headers = game.headers
190221
     board = game.board()
191222
     symbols, evals = {}, {}
223
+    times = read_times(game)
192224
     for ply, node in enumerate(game.mainline()):
193225
         board.push(node.move)
194226
         for nag in node.nags:
@@ -212,6 +244,7 @@ def from_pgn(text, path=""):
212244
         names=(headers.get("White", "?"), headers.get("Black", "?")) if headers.get("SchachForeign") else (),
213245
         variations=variations,
214246
         takebacks=takebacks,
247
+        times=times,
215248
     )
216249
 
217250
 

modified tests/test_export.py +172 −2

@@ -9,7 +9,7 @@ import unittest
99
 import chess
1010
 import chess.pgn
1111
 
12
-from schach import export, savegames
12
+from schach import export, notation, savegames
1313
 
1414
 MOVES = "e4 e5 Nf3 Nc6 Bc4 Nd4 Nxe5 Qg5 Nxf7 Qxg2 Rf1 Qxe4+ Be2 Nf3#".split()
1515
 
@@ -245,14 +245,184 @@ class OpeningTest(unittest.TestCase):
245245
         self.assertIn("Bis hier:", page)
246246
 
247247
 
248
+def png_chunks(data):
249
+    """[(typ, inhalt)] einer PNG-Datei."""
250
+    chunks, pos = [], 8
251
+    while pos < len(data):
252
+        length = int.from_bytes(data[pos:pos + 4], "big")
253
+        chunks.append((data[pos + 4:pos + 8], data[pos + 8:pos + 8 + length]))
254
+        pos += 12 + length
255
+    return chunks
256
+
257
+
258
+def frame_delays(data):
259
+    """Dauer jedes Bilds in ms aus den fcTL-Blöcken."""
260
+    return [round(int.from_bytes(body[20:22], "big") * 1000 / int.from_bytes(body[22:24], "big"))
261
+            for kind, body in png_chunks(data) if kind == b"fcTL"]
262
+
263
+
264
+class AnimationTest(unittest.TestCase):
265
+    def test_apng_structure(self):
266
+        data = export.export("apng", sample(), opts(scope="game"))
267
+        self.assertTrue(data.startswith(b"\x89PNG\r\n\x1a\n"))
268
+        chunks = png_chunks(data)
269
+        kinds = [kind for kind, _ in chunks]
270
+        self.assertEqual(kinds[:4], [b"IHDR", b"acTL", b"fcTL", b"IDAT"])  # erstes Bild auch ohne APNG sichtbar
271
+        self.assertEqual(kinds[-1], b"IEND")
272
+        frames = int.from_bytes(chunks[1][1][:4], "big")
273
+        self.assertEqual(frames, len(MOVES) + 1)  # Ausgangsstellung + jeder Halbzug
274
+        self.assertEqual(kinds.count(b"fcTL"), frames)
275
+        # Folgenummern über fcTL und fdAT lückenlos ab 0
276
+        numbers = [int.from_bytes(body[:4], "big") for kind, body in chunks if kind in (b"fcTL", b"fdAT")]
277
+        self.assertEqual(numbers, list(range(len(numbers))))
278
+        width = int.from_bytes(chunks[0][1][:4], "big")
279
+        self.assertEqual(width, export.APNG_WIDTH)
280
+
281
+    def test_frames_match_single_images(self):
282
+        """Die Auflagen setzen sich genau zu den einzelnen Stellungen zusammen."""
283
+        import cairo
284
+        import io as io_mod
285
+        try:
286
+            from PIL import Image
287
+        except ImportError:
288
+            self.skipTest("Pillow fehlt")
289
+        o = opts(scope="game", plies=6)
290
+        state = sample()
291
+        state.board = export.board_at(state, 6)
292
+        animation = Image.open(io_mod.BytesIO(export.export("apng", state, o)))
293
+        for index, (diagram, _delay) in enumerate(export._frames(state, o)):
294
+            width = export.APNG_WIDTH
295
+            surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, animation.size[1])
296
+            cr = cairo.Context(surface)
297
+            cr.set_source_rgb(*export.APNG_BACKGROUND)
298
+            cr.paint()
299
+            diagram.render(cr, 0, 0, width)
300
+            out = io_mod.BytesIO()
301
+            surface.write_to_png(out)
302
+            animation.seek(index)
303
+            self.assertEqual(animation.convert("RGBA").tobytes(),
304
+                             Image.open(out).convert("RGBA").tobytes(), f"Bild {index}")
305
+
306
+    def test_delays_fixed_or_from_move_times(self):
307
+        state = sample()
308
+        state.times = {ply: 500 * (ply + 1) for ply in range(len(MOVES))}
309
+        fixed = frame_delays(export.export("apng", state, opts(scope="game")))
310
+        self.assertEqual(fixed, [export.APNG_DELAY_MS] * len(MOVES) + [export.APNG_END_MS])
311
+        timed = frame_delays(export.export("apng", state, opts(scope="game", move_times=True)))
312
+        # Bild n steht, bis Halbzug n gespielt ist
313
+        self.assertEqual(timed, [500 * (ply + 1) for ply in range(len(MOVES))] + [export.APNG_END_MS])
314
+
315
+    def test_long_think_time_fits_into_frame_control(self):
316
+        self.assertEqual(export._delay(90_000), (9000, 100))
317
+        self.assertEqual(export._delay(10), (export.APNG_MIN_MS, 1000))
318
+
319
+    def test_pgn_move_times_optional(self):
320
+        state = sample()
321
+        state.times = {0: 3500, 1: 61000}
322
+        with_times = export.export("pgn", state, opts(scope="game", move_times=True))
323
+        self.assertIn("[%emt 0:00:03.5]", with_times)
324
+        self.assertIn("[%emt 0:01:01]", with_times)
325
+        self.assertNotIn("%emt", export.export("pgn", state, opts(scope="game")))
326
+        without_evals = export.export("pgn", state, opts(scope="game", move_times=True, evals=False))
327
+        self.assertNotIn("%wp", without_evals)
328
+        self.assertIn("%emt", without_evals)
329
+
330
+
331
+@unittest.skipUnless(export.webp_available(), "Pillow mit WebP fehlt")
332
+class WebpTest(unittest.TestCase):
333
+    def open(self, data):
334
+        from PIL import Image
335
+        return Image.open(io.BytesIO(data))
336
+
337
+    def test_position_is_still_image_like_png(self):
338
+        image = self.open(export.export("webp", sample(), opts(plies=8)))
339
+        self.assertEqual(image.format, "WEBP")
340
+        self.assertFalse(getattr(image, "is_animated", False))
341
+        png = self.open(export.export("png", sample(), opts(plies=8)))
342
+        self.assertEqual(image.size, png.size)
343
+        self.assertEqual(image.mode, "RGBA")  # durchsichtiger Rand bleibt durchsichtig
344
+
345
+    def test_game_is_animation_with_same_frames_as_apng(self):
346
+        state = sample()
347
+        state.times = {ply: 300 * (ply + 1) for ply in range(len(MOVES))}
348
+        o = opts(scope="game", move_times=True)
349
+        webp = self.open(export.export("webp", state, o))
350
+        apng = self.open(export.export("apng", state, o))
351
+        self.assertEqual(webp.n_frames, len(MOVES) + 1)
352
+        delays = []
353
+        for index in range(webp.n_frames):
354
+            webp.seek(index)
355
+            webp.load()
356
+            apng.seek(index)
357
+            delays.append(webp.info["duration"])
358
+            self.assertEqual(webp.convert("RGB").tobytes(), apng.convert("RGB").tobytes(), f"Bild {index}")
359
+        self.assertEqual(delays, [300 * (ply + 1) for ply in range(len(MOVES))] + [export.APNG_END_MS])
360
+
361
+    def test_filename_by_scope(self):
362
+        self.assertRegex(export.filename("webp", sample(), opts()), r"^stellung-.*\.webp$")
363
+        self.assertRegex(export.filename("webp", sample(), opts(scope="game")), r"^partie-animiert-.*\.webp$")
364
+
365
+
366
+class MoveTimesTest(unittest.TestCase):
367
+    def test_format_time(self):
368
+        self.assertEqual([notation.format_time(ms) for ms in (800, 9940, 9960, 42000, 65000, 3725000)],
369
+                         ["0,8 s", "9,9 s", "10 s", "42 s", "1:05", "1:02:05"])
370
+
371
+    def test_html_shows_times_only_when_asked(self):
372
+        state = sample()
373
+        state.times = {0: 3500, 3: 65000}
374
+        page = export.export("html", state, opts(scope="game", move_times=True))
375
+        self.assertIn('<small class="t" title="Bedenkzeit">3,5 s</small>', page)
376
+        self.assertIn(">1:05</small>", page)
377
+        self.assertEqual(page.count('class="t"'), 2)  # nur Züge mit bekannter Zeit
378
+        self.assertNotIn('class="t"', export.export("html", state, opts(scope="game")))
379
+
380
+    @unittest.skipUnless(shutil.which("pdftotext"), "pdftotext fehlt")
381
+    def test_pdf_shows_times_only_when_asked(self):
382
+        state = sample()
383
+        state.times = {0: 3500, 3: 65000}
384
+
385
+        def text(**kw):
386
+            with tempfile.NamedTemporaryFile(suffix=".pdf") as fh:
387
+                fh.write(export.export("pdf", state, opts(scope="game", **kw)))
388
+                fh.flush()
389
+                return subprocess.run(["pdftotext", fh.name, "-"], capture_output=True, text=True).stdout
390
+
391
+        self.assertIn("3,5 s", text(move_times=True))
392
+        self.assertIn("1:05", text(move_times=True))
393
+        self.assertNotIn("3,5 s", text())
394
+
395
+    def test_saved_times_come_back(self):
396
+        state = sample()
397
+        state.times = {0: 1200, 3: 45600}
398
+        self.assertEqual(savegames.from_pgn(savegames.to_pgn(state)).times, {0: 1200, 3: 45600})
399
+        self.assertEqual(state.truncated(1).times, {0: 1200})
400
+
401
+    def test_times_from_lichess_clock(self):
402
+        pgn = ('[TimeControl "180+2"]\n\n'
403
+               "1. e4 { [%clk 0:03:00] } e5 { [%clk 0:03:00] } "
404
+               "2. Nf3 { [%clk 0:02:55] } Nc6 { [%clk 0:02:51.5] } *")
405
+        times = savegames.from_pgn(pgn).times
406
+        # Restzeit davor − Restzeit danach + Zuschlag
407
+        self.assertEqual(times, {0: 2000, 1: 2000, 2: 7000, 3: 10500})
408
+
409
+    def test_emt_wins_over_clock(self):
410
+        pgn = '1. e4 { [%clk 0:03:00] [%emt 0:00:04] } *'
411
+        self.assertEqual(savegames.from_pgn(pgn).times, {0: 4000})
412
+
413
+    def test_no_clock_no_times(self):
414
+        self.assertEqual(savegames.from_pgn("1. e4 e5 *").times, {})
415
+
416
+
248417
 class MetaTest(unittest.TestCase):
249418
     def test_filename(self):
250419
         self.assertRegex(export.filename("pdf", sample(), opts(scope="game")), r"^partie-\d{4}-\d\d-\d\d\.pdf$")
251420
         self.assertRegex(export.filename("png", sample(), opts(scope="game")), r"^stellung-.*\.png$")
421
+        self.assertRegex(export.filename("apng", sample(), opts()), r"^partie-animiert-.*\.png$")
252422
 
253423
     def test_every_format_has_writer(self):
254424
         for fmt in export.FORMATS:
255
-            if fmt == "pdf-latex":
425
+            if fmt == "pdf-latex" or fmt == "webp" and not export.webp_available():
256426
                 continue
257427
             for scope in export.FORMATS[fmt].scopes:
258428
                 self.assertTrue(export.export(fmt, sample(), opts(scope=scope, plies=5)))