feat(clipboard): copy and paste games as PGN, FEN or Lichess link
public
feat(clipboard): copy and paste games as PGN, FEN or Lichess link - Ctrl+C copies PGN, Ctrl+Shift+C the shown position as FEN - Ctrl+V and dropping a .pgn file set up PGN, FEN or a Lichess link - empty window takes the game, otherwise a new window opens - foreign games keep both names, neutral result, both sides analysed - blocked while an online game runs (fair play) - text fields keep normal copy and paste Board gets initial focus: the move list grabbed it in new windows and selected its first move. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| Changeset | 4cc840e11522977e08903c4e468b724403caf3ae |
|---|---|
| Author (claimed) | Timo Stolz <timo.stolz@nullachtvierzehn.de>, |
| Parents | c10008d09c9c |
| Children | ef0d7c95c61b |
| Pushlog | by timo via ssh by timo via ssh |
modified README.md +13 −0
| @@ -28,6 +28,12 @@ Schlichtes GNOME-Schachprogramm (Python, | ||
| 28 | 28 | Hinweis, in Lichess-Partien dein Konto mit Remis, Aufgeben und „auf lichess.org ansehen“. |
| 29 | 29 | Über und unter dem Brett steht, wer gegen wen spielt. In schmalen Fenstern wandert der |
| 30 | 30 | Hinweis in eine Leiste unter dem Brett. |
| 31 | +- **Zwischenablage:** Strg+C kopiert die Partie als PGN, Strg+Umschalt+C die gezeigte | |
| 32 | + Stellung als FEN. Strg+V stellt auf, was in der Zwischenablage steht: PGN, FEN (auch nur | |
| 33 | + die Figurenstellung) oder ein Lichess-Link (die Partie wird geholt, `/black` dreht das | |
| 34 | + Brett). Eine `.pgn`-Datei aufs Brett ziehen geht genauso. Läuft im Fenster schon eine | |
| 35 | + Partie, öffnet sich ein neues. Fremde Partien zeigen die Namen und werden für beide | |
| 36 | + Seiten analysiert. Während einer Online-Partie ist Einfügen gesperrt. | |
| 31 | 37 | - **Einstellungen** (Strg+,): Standardfarbe, Streuung von Maia, Brettfarben (Holz, |
| 32 | 38 | Schiefer, Grün), Figurensätze aus PyChess (`/usr/share/pychess/pieces`), Lichess-Konto. |
| 33 | 39 | |
| @@ -38,6 +44,10 @@ Schlichtes GNOME-Schachprogramm (Python, | ||
| 38 | 44 | Abhängigkeiten: `python-gobject`, `libadwaita`, `librsvg`, `python-chess`, |
| 39 | 45 | `stockfish`, `maia3-git` (AUR), `python-requests`, `libsecret`. |
| 40 | 46 | |
| 47 | +Tests: | |
| 48 | + | |
| 49 | + python -m unittest discover -s tests -t . | |
| 50 | + | |
| 41 | 51 | Ins App-Menü aufnehmen: |
| 42 | 52 | |
| 43 | 53 | cp schach.desktop ~/.local/share/applications/ |
| @@ -55,6 +65,9 @@ Ins App-Menü aufnehmen: | ||
| 55 | 65 | | Strg+S | Spielstand speichern | |
| 56 | 66 | | Strg+O | Spielstände | |
| 57 | 67 | | Strg+Umschalt+S | Als PGN exportieren | |
| 68 | +| Strg+C | Partie als PGN kopieren | | |
| 69 | +| Strg+Umschalt+C | Stellung als FEN kopieren | | |
| 70 | +| Strg+V | Partie, Stellung oder Lichess-Link einfügen | | |
| 58 | 71 | | Strg+, | Einstellungen | |
| 59 | 72 | | Strg+? | Tastenkürzel | |
| 60 | 73 | |
modified ROADMAP.md +4 −0
| @@ -209,6 +209,10 @@ mit `uci` anzusprechen ist riskant und l | ||
| 209 | 209 | |
| 210 | 210 | ## 4. PGN per Zwischenablage |
| 211 | 211 | |
| 212 | +**Status:** umgesetzt (20.11.2026), außer „Stellung aufbauen“. Fremde Partien | |
| 213 | +speichern dazu die Namen von Weiß und Schwarz (PGN-Kopf `SchachForeign`) und | |
| 214 | +werden für beide Seiten analysiert. | |
| 215 | + | |
| 212 | 216 | | Taste | Aktion | |
| 213 | 217 | | --- | --- | |
| 214 | 218 | | Strg+C | Partie als PGN kopieren (mit Kopfzeilen, Zugzeichen und Hinweis-Kommentaren) | |
modified schach/app.py +161 −5
| @@ -13,9 +13,9 @@ import gi | ||
| 13 | 13 | |
| 14 | 14 | gi.require_version("Gtk", "4.0") |
| 15 | 15 | gi.require_version("Adw", "1") |
| 16 | -from gi.repository import Adw, Gio, GLib, GObject, Gtk # noqa: E402 | |
| 16 | +from gi.repository import Adw, Gdk, Gio, GLib, GObject, Gtk # noqa: E402 | |
| 17 | 17 | |
| 18 | -from . import annotate, lichess, savegames # noqa: E402 | |
| 18 | +from . import annotate, clipboard, lichess, savegames # noqa: E402 | |
| 19 | 19 | from .board import BoardView, available_themes # noqa: E402 |
| 20 | 20 | from .movelist import MoveList # noqa: E402 |
| 21 | 21 | from .prefs import Preferences # noqa: E402 |
| @@ -55,9 +55,12 @@ def save_settings(settings): | ||
| 55 | 55 | |
| 56 | 56 | |
| 57 | 57 | def outcome_text(board, human, opponent="Maia"): |
| 58 | + """Partie-Ende in Worten; ``human=None`` für fremde Partien (neutral formuliert).""" | |
| 58 | 59 | outcome = board.outcome(claim_draw=True) |
| 59 | 60 | if outcome is None: |
| 60 | 61 | return None |
| 62 | + if outcome.winner is not None and human is None: | |
| 63 | + return f"Schachmatt – {'Weiß' if outcome.winner == chess.WHITE else 'Schwarz'} gewinnt." | |
| 61 | 64 | if outcome.winner is not None: |
| 62 | 65 | return "Schachmatt – du hast gewonnen!" if outcome.winner == human else f"Schachmatt – {opponent} gewinnt." |
| 63 | 66 | return { |
| @@ -104,6 +107,7 @@ class Window(OnlineMixin, PuzzleMixin, A | ||
| 104 | 107 | self.end_shown = False |
| 105 | 108 | self.mode = "maia" |
| 106 | 109 | self.opponent = "" # Gegnername, wenn nicht Maia |
| 110 | + self.names = () # (Weiß, Schwarz) bei fremden Partien | |
| 107 | 111 | self.final_text = None # Partie-Ende, das nicht am Brett ablesbar ist (Aufgabe, Zeit, Rätsel gelöst) |
| 108 | 112 | self.puzzle = None |
| 109 | 113 | self.prefs_dialog = None |
| @@ -142,6 +146,7 @@ class Window(OnlineMixin, PuzzleMixin, A | ||
| 142 | 146 | games.append("Partie gegen _Maia …", "win.new-game") |
| 143 | 147 | games.append("_Rätsel", "win.puzzle") |
| 144 | 148 | games.append_submenu("Rätsel-_Schwierigkeit", difficulty) |
| 149 | + games.append("Aus der _Zwischenablage", "win.paste") | |
| 145 | 150 | online = Gio.Menu() |
| 146 | 151 | online.append("Freund auf _Lichess herausfordern …", "win.challenge") |
| 147 | 152 | new_menu = Gio.Menu() |
| @@ -221,6 +226,10 @@ class Window(OnlineMixin, PuzzleMixin, A | ||
| 221 | 226 | self.view = BoardView(theme=self.settings["theme"], scheme=self.settings["scheme"]) |
| 222 | 227 | self.view.on_move = self._on_board_move |
| 223 | 228 | self.view.on_inactive_click = self._on_inactive_board_click |
| 229 | + drop = Gtk.DropTarget.new(GObject.TYPE_NONE, Gdk.DragAction.COPY) | |
| 230 | + drop.set_gtypes([Gdk.FileList, GObject.TYPE_STRING]) | |
| 231 | + drop.connect("drop", self._on_drop) | |
| 232 | + self.view.add_controller(drop) | |
| 224 | 233 | |
| 225 | 234 | box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL) |
| 226 | 235 | box.append(self.banner) |
| @@ -248,6 +257,10 @@ class Window(OnlineMixin, PuzzleMixin, A | ||
| 248 | 257 | self.toolbar = toolbar |
| 249 | 258 | self.set_content(toolbar) |
| 250 | 259 | |
| 260 | + # Startfokus aufs Brett: sonst landet er in der Zugliste, und die wählt dabei den ersten Zug aus | |
| 261 | + self.view.set_focusable(True) | |
| 262 | + self.set_focus(self.view) | |
| 263 | + | |
| 251 | 264 | self.set_size_request(360, 480) |
| 252 | 265 | breakpoint = Adw.Breakpoint.new(Adw.BreakpointCondition.parse("max-width: 560sp")) |
| 253 | 266 | breakpoint.connect("apply", lambda *_: self._set_narrow(True)) |
| @@ -288,6 +301,9 @@ class Window(OnlineMixin, PuzzleMixin, A | ||
| 288 | 301 | ("open-lichess-game", self._open_lichess_game), |
| 289 | 302 | ("shortcuts", self._shortcuts_dialog), |
| 290 | 303 | ("preferences", self._preferences_dialog), |
| 304 | + ("copy-pgn", self._copy_pgn), | |
| 305 | + ("copy-fen", self._copy_shown_fen), | |
| 306 | + ("paste", self._paste), | |
| 291 | 307 | ("about", self._about_dialog), |
| 292 | 308 | ]: |
| 293 | 309 | action = Gio.SimpleAction.new(name, None) |
| @@ -314,6 +330,9 @@ class Window(OnlineMixin, PuzzleMixin, A | ||
| 314 | 330 | app.set_accels_for_action("win.puzzle", ["r"]) |
| 315 | 331 | app.set_accels_for_action("win.shortcuts", ["<Control>question"]) |
| 316 | 332 | app.set_accels_for_action("win.preferences", ["<Control>comma"]) |
| 333 | + app.set_accels_for_action("win.copy-pgn", ["<Control>c"]) | |
| 334 | + app.set_accels_for_action("win.copy-fen", ["<Control><Shift>c"]) | |
| 335 | + app.set_accels_for_action("win.paste", ["<Control>v"]) | |
| 317 | 336 | |
| 318 | 337 | def _action(self, name): |
| 319 | 338 | return self.lookup_action(name) |
| @@ -340,6 +359,8 @@ class Window(OnlineMixin, PuzzleMixin, A | ||
| 340 | 359 | return self.final_text |
| 341 | 360 | if self.mode in ("online", "puzzle"): |
| 342 | 361 | return None # das Ende meldet Lichess bzw. die Rätsel-Lösung |
| 362 | + if self.names: | |
| 363 | + return outcome_text(self.board, None) | |
| 343 | 364 | name = "Maia" if self.mode == "maia" else (self.opponent.split(" (")[0] or "Gegner") |
| 344 | 365 | return outcome_text(self.board, self.human, name) |
| 345 | 366 | |
| @@ -367,6 +388,7 @@ class Window(OnlineMixin, PuzzleMixin, A | ||
| 367 | 388 | self._puzzle_leave() |
| 368 | 389 | self.mode = "maia" |
| 369 | 390 | self.opponent = "" |
| 391 | + self.names = () | |
| 370 | 392 | self.final_text = None |
| 371 | 393 | |
| 372 | 394 | def _reset_game_tables(self): |
| @@ -448,6 +470,8 @@ class Window(OnlineMixin, PuzzleMixin, A | ||
| 448 | 470 | else time_control_text({"type": "correspondence", "daysPerTurn": full.get("daysPerTurn", 1)})) |
| 449 | 471 | rated = "gewertet" if full.get("rated") else "ungewertet" |
| 450 | 472 | self.title.set_subtitle(f"gegen {self.opponent} · {tc} · {rated}") |
| 473 | + elif self.mode == "review" and self.names: | |
| 474 | + self.title.set_subtitle("Analyse") | |
| 451 | 475 | elif self.mode == "review": |
| 452 | 476 | self.title.set_subtitle(f"gegen {self.opponent} · du warst {side}" if self.opponent else "Analyse") |
| 453 | 477 | elif not self.maia_ready: |
| @@ -510,6 +534,9 @@ class Window(OnlineMixin, PuzzleMixin, A | ||
| 510 | 534 | """Spieler-Zeilen über und unter dem Brett: wer spielt hier gegen wen?""" |
| 511 | 535 | if self.mode == "online": |
| 512 | 536 | return # Namen und Uhren setzt die Lichess-Verbindung |
| 537 | + if self.names: | |
| 538 | + self.view.names = {chess.WHITE: self.names[0], chess.BLACK: self.names[1]} | |
| 539 | + return | |
| 513 | 540 | if self.mode == "maia": |
| 514 | 541 | other = f"Maia-3 · {self.elo}" |
| 515 | 542 | elif self.mode == "review" and self.opponent: |
| @@ -793,7 +820,9 @@ class Window(OnlineMixin, PuzzleMixin, A | ||
| 793 | 820 | gen = self.gen |
| 794 | 821 | for ply, move in enumerate(self.board.move_stack): |
| 795 | 822 | before = self._board_at(ply - 1) |
| 796 | - if before.turn != self.human or ply in self.symbols or ply in self.review_requested: | |
| 823 | + if ply in self.symbols or ply in self.review_requested: | |
| 824 | + continue | |
| 825 | + if before.turn != self.human and not self.names: # fremde Partie: beide Seiten | |
| 797 | 826 | continue |
| 798 | 827 | self.review_requested.add(ply) |
| 799 | 828 | |
| @@ -834,6 +863,122 @@ class Window(OnlineMixin, PuzzleMixin, A | ||
| 834 | 863 | self.get_clipboard().set(fen) |
| 835 | 864 | self.toasts.add_toast(Adw.Toast(title="FEN kopiert", timeout=2)) |
| 836 | 865 | |
| 866 | + # --- Zwischenablage ---------------------------------------------------- | |
| 867 | + | |
| 868 | + def _forward_clipboard(self, name): | |
| 869 | + """In Textfeldern (z. B. im Speichern-Dialog) bleiben Strg+C/V normales Kopieren.""" | |
| 870 | + focus = self.get_focus() | |
| 871 | + return focus is not None and focus is not self.view and focus.activate_action(f"clipboard.{name}", None) | |
| 872 | + | |
| 873 | + def _copy_pgn(self, *_): | |
| 874 | + if self._forward_clipboard("copy"): | |
| 875 | + return | |
| 876 | + if not self.board.move_stack: | |
| 877 | + self._copy_fen(-1) # noch keine Züge: wenigstens die Stellung | |
| 878 | + return | |
| 879 | + self.get_clipboard().set(self._pgn()) | |
| 880 | + self.toasts.add_toast(Adw.Toast(title="Partie als PGN kopiert", timeout=2)) | |
| 881 | + | |
| 882 | + def _copy_shown_fen(self, *_): | |
| 883 | + self._copy_fen(self.browse_ply if self._browsing() else len(self.board.move_stack) - 1) | |
| 884 | + | |
| 885 | + def _paste(self, *_): | |
| 886 | + if self._forward_clipboard("paste"): | |
| 887 | + return | |
| 888 | + self.get_clipboard().read_text_async(None, self._on_clipboard_text) | |
| 889 | + | |
| 890 | + def _on_clipboard_text(self, clip, result): | |
| 891 | + try: | |
| 892 | + text = clip.read_text_finish(result) | |
| 893 | + except GLib.Error: | |
| 894 | + text = None | |
| 895 | + self.import_text(text) | |
| 896 | + | |
| 897 | + def _on_drop(self, _target, value, _x, _y): | |
| 898 | + if isinstance(value, Gdk.FileList): | |
| 899 | + files = value.get_files() | |
| 900 | + if not files: | |
| 901 | + return False | |
| 902 | + try: | |
| 903 | + _ok, data, _etag = files[0].load_contents(None) | |
| 904 | + except GLib.Error as exc: | |
| 905 | + self.toasts.add_toast(Adw.Toast(title=f"Datei nicht lesbar: {exc.message}")) | |
| 906 | + return False | |
| 907 | + self.import_text(data.decode("utf-8", "replace"), source="file") | |
| 908 | + else: | |
| 909 | + self.import_text(value) | |
| 910 | + return True | |
| 911 | + | |
| 912 | + def _username(self): | |
| 913 | + return (self.get_application().lichess_user or {}).get("username", "") | |
| 914 | + | |
| 915 | + def import_text(self, text, source="clipboard"): | |
| 916 | + """PGN, FEN oder Lichess-Link aufstellen – im leeren Fenster, sonst in einem neuen.""" | |
| 917 | + if any(w._online_running() for w in self.get_application()._windows()): | |
| 918 | + self.toasts.add_toast(Adw.Toast(title="Während einer Online-Partie ist Einfügen gesperrt (Fair Play)")) | |
| 919 | + return | |
| 920 | + pasted = clipboard.parse(text, elo=self.elo or int(self.settings["elo"]), username=self._username()) | |
| 921 | + if pasted is None: | |
| 922 | + where = "in der Datei" if source == "file" else "in der Zwischenablage" | |
| 923 | + self.toasts.add_toast(Adw.Toast(title=f"Keine Partie und keine Stellung {where}", timeout=3)) | |
| 924 | + elif pasted.kind == "lichess": | |
| 925 | + self._fetch_lichess(pasted) | |
| 926 | + else: | |
| 927 | + self._place(pasted) | |
| 928 | + | |
| 929 | + def _fetch_lichess(self, link): | |
| 930 | + app = self.get_application() | |
| 931 | + client = app.lichess_client or lichess.Client() | |
| 932 | + loading = Adw.Toast(title="Partie wird von Lichess geholt …", timeout=0) | |
| 933 | + self.toasts.add_toast(loading) | |
| 934 | + | |
| 935 | + def done(text, error): | |
| 936 | + loading.dismiss() | |
| 937 | + if error: | |
| 938 | + self.toasts.add_toast(Adw.Toast(title=f"Partie nicht geladen: {error}")) | |
| 939 | + return | |
| 940 | + pasted = clipboard.parse(text, elo=self.elo or int(self.settings["elo"]), username=self._username()) | |
| 941 | + if pasted is None or pasted.kind != "pgn": | |
| 942 | + self.toasts.add_toast(Adw.Toast(title="Lichess hat keine lesbare Partie geliefert")) | |
| 943 | + return | |
| 944 | + state = pasted.state | |
| 945 | + if state.names: | |
| 946 | + state.name = f"Lichess: {state.names[0]} – {state.names[1]}" | |
| 947 | + elif state.opponent: | |
| 948 | + state.name = f"Lichess gegen {state.opponent}" | |
| 949 | + pasted.orientation = link.orientation | |
| 950 | + self._place(pasted) | |
| 951 | + | |
| 952 | + lichess._background(lambda: client.export_game(link.game_id), done) | |
| 953 | + | |
| 954 | + def _empty(self): | |
| 955 | + """Noch nichts passiert? Dann darf eine eingefügte Partie dieses Fenster übernehmen.""" | |
| 956 | + return ( | |
| 957 | + self.mode == "maia" and not self.board.move_stack and self.final_text is None | |
| 958 | + and self.board.root().fen() == chess.STARTING_FEN | |
| 959 | + ) | |
| 960 | + | |
| 961 | + def _place(self, pasted): | |
| 962 | + state = pasted.state | |
| 963 | + if self._empty(): | |
| 964 | + self.load_state(state) | |
| 965 | + target = self | |
| 966 | + else: | |
| 967 | + target = self.get_application().open_window(state) | |
| 968 | + if pasted.orientation is not None: | |
| 969 | + target.view.flipped = pasted.orientation == chess.BLACK | |
| 970 | + target.view.queue_draw() | |
| 971 | + if state.board.move_stack: | |
| 972 | + target.list_btn.set_active(True) # eingefügte Partie: gleich mit Zugliste und Bewertung | |
| 973 | + if not state.board.move_stack: | |
| 974 | + side = "Weiß" if state.board.turn == chess.WHITE else "Schwarz" | |
| 975 | + text = f"Stellung eingefügt – du spielst {side} gegen Maia" | |
| 976 | + else: | |
| 977 | + text = "Partie eingefügt" | |
| 978 | + if pasted.more_games: | |
| 979 | + text += " (nur die erste Partie)" | |
| 980 | + target.toasts.add_toast(Adw.Toast(title=text, timeout=3)) | |
| 981 | + | |
| 837 | 982 | def _continue_from(self, ply): |
| 838 | 983 | """Abzweigung: die Partie ab dieser Stellung in einem neuen Fenster, das Original bleibt.""" |
| 839 | 984 | state = self.state().truncated(ply) |
| @@ -951,6 +1096,11 @@ class Window(OnlineMixin, PuzzleMixin, A | ||
| 951 | 1096 | ("Spielstand speichern", "<Control>s"), ("Spielstände öffnen", "<Control>o"), |
| 952 | 1097 | ("Als PGN exportieren", "<Control><Shift>s"), |
| 953 | 1098 | ]), |
| 1099 | + ("Zwischenablage", [ | |
| 1100 | + ("Partie als PGN kopieren", "<Control>c"), | |
| 1101 | + ("Stellung als FEN kopieren", "<Control><Shift>c"), | |
| 1102 | + ("Partie, Stellung oder Lichess-Link einfügen", "<Control>v"), | |
| 1103 | + ]), | |
| 954 | 1104 | ("Allgemein", [("Einstellungen", "<Control>comma"), ("Tastenkürzel", "<Control>question")]), |
| 955 | 1105 | ]: |
| 956 | 1106 | section = Adw.ShortcutsSection(title=title) |
| @@ -995,12 +1145,14 @@ class Window(OnlineMixin, PuzzleMixin, A | ||
| 995 | 1145 | mode="maia" if self.mode == "maia" else "review", |
| 996 | 1146 | opponent=self.opponent, |
| 997 | 1147 | final_text=self.final_text or "", |
| 1148 | + names=self.names, | |
| 998 | 1149 | ) |
| 999 | 1150 | |
| 1000 | 1151 | def load_state(self, state): |
| 1001 | 1152 | self._leave_special() |
| 1002 | 1153 | self.mode = state.mode if state.mode in ("maia", "review") else "review" |
| 1003 | 1154 | self.opponent = state.opponent |
| 1155 | + self.names = tuple(state.names) | |
| 1004 | 1156 | self.final_text = state.final_text or None |
| 1005 | 1157 | self.human = state.human |
| 1006 | 1158 | self.elo = state.elo or int(self.settings["elo"]) |
| @@ -1091,12 +1243,16 @@ class Window(OnlineMixin, PuzzleMixin, A | ||
| 1091 | 1243 | for path, state, when in saves: |
| 1092 | 1244 | moves = len(state.board.move_stack) |
| 1093 | 1245 | side = "Weiß" if state.human == chess.WHITE else "Schwarz" |
| 1094 | - result = outcome_text(state.board, state.human) | |
| 1246 | + result = outcome_text(state.board, None if state.names else state.human) | |
| 1095 | 1247 | status = state.final_text or result or f"Zug {state.board.fullmove_number}" |
| 1096 | 1248 | against = state.opponent or f"Maia {state.elo}" |
| 1249 | + if state.names: | |
| 1250 | + against, side = f"{state.names[0]} – {state.names[1]}", None | |
| 1097 | 1251 | row = Adw.ActionRow( |
| 1098 | 1252 | title=state.name or "Ohne Namen", |
| 1099 | - subtitle=f"{status} · {moves} Halbzüge · {against} · du {side} · {when:%d.%m.%Y %H:%M}", | |
| 1253 | + subtitle=" · ".join(x for x in ( | |
| 1254 | + status, f"{moves} Halbzüge", against, side and f"du {side}", f"{when:%d.%m.%Y %H:%M}", | |
| 1255 | + ) if x), | |
| 1100 | 1256 | use_markup=False, |
| 1101 | 1257 | activatable=True, |
| 1102 | 1258 | ) |
added schach/clipboard.py +124 −0
| @@ -0,0 +1,124 @@ | ||
| 1 | +"""Partien und Stellungen aus Text erkennen: PGN, FEN oder Lichess-Link. | |
| 2 | + | |
| 3 | +Reine Logik ohne GTK, damit sie sich testen lässt. Das Fenster entscheidet, | |
| 4 | +wo das Ergebnis landet (aktuelles oder neues Fenster). | |
| 5 | +""" | |
| 6 | + | |
| 7 | +import dataclasses | |
| 8 | +import io | |
| 9 | +import re | |
| 10 | + | |
| 11 | +import chess | |
| 12 | +import chess.pgn | |
| 13 | + | |
| 14 | +from . import savegames | |
| 15 | + | |
| 16 | +LICHESS_RE = re.compile( | |
| 17 | + r"^(?:https?://)?(?:www\.)?lichess\.org/([A-Za-z0-9]{8})(?:[A-Za-z0-9]{4})?" | |
| 18 | + r"(?:/(white|black))?(?:[/?#].*)?$" | |
| 19 | +) | |
| 20 | +# Lichess-Seiten, deren Name zufällig wie eine Partie-ID aussieht (8 Zeichen) | |
| 21 | +LICHESS_PAGES = { | |
| 22 | + "training", "analysis", "practice", "streamer", "tutorial", "features", "insights", | |
| 23 | + "settings", "password", "calendar", "contacts", | |
| 24 | +} | |
| 25 | +RESULT_TEXT = {"1-0": "Weiß hat gewonnen.", "0-1": "Schwarz hat gewonnen.", "1/2-1/2": "Remis."} | |
| 26 | + | |
| 27 | + | |
| 28 | +@dataclasses.dataclass | |
| 29 | +class Pasted: | |
| 30 | + kind: str # "pgn", "fen" oder "lichess" | |
| 31 | + state: savegames.GameState | None = None | |
| 32 | + game_id: str = "" # nur "lichess": Partie muss erst geholt werden | |
| 33 | + orientation: bool | None = None # nur "lichess": /black im Link | |
| 34 | + more_games: bool = False # PGN enthielt mehr als eine Partie | |
| 35 | + | |
| 36 | + | |
| 37 | +def lichess_id(text): | |
| 38 | + """(Partie-ID, Blickrichtung) aus einem Lichess-Link oder None.""" | |
| 39 | + match = LICHESS_RE.match(text.strip()) | |
| 40 | + if not match or match.group(1).lower() in LICHESS_PAGES: | |
| 41 | + return None | |
| 42 | + color = {"white": chess.WHITE, "black": chess.BLACK}.get(match.group(2)) | |
| 43 | + return match.group(1), color | |
| 44 | + | |
| 45 | + | |
| 46 | +def parse(text, elo=1200, username=""): | |
| 47 | + """Erkennt den Text; None, wenn weder Partie noch Stellung darin steht.""" | |
| 48 | + text = (text or "").strip() | |
| 49 | + if not text: | |
| 50 | + return None | |
| 51 | + found = lichess_id(text) | |
| 52 | + if found: | |
| 53 | + return Pasted("lichess", game_id=found[0], orientation=found[1]) | |
| 54 | + board = _fen(text) | |
| 55 | + if board is not None: | |
| 56 | + state = savegames.GameState(board=board, human=board.turn, elo=elo, name="Stellung aus der Zwischenablage") | |
| 57 | + return Pasted("fen", state=state) | |
| 58 | + return _pgn(text, elo, username) | |
| 59 | + | |
| 60 | + | |
| 61 | +def _fen(text): | |
| 62 | + if "\n" in text or text.count("/") != 7: | |
| 63 | + return None | |
| 64 | + fields = text.split() | |
| 65 | + if len(fields) == 1: | |
| 66 | + fields += ["w", "-", "-", "0", "1"] # nur Figurenstellung, z. B. abgetippt: Weiß am Zug | |
| 67 | + try: | |
| 68 | + board = chess.Board(" ".join(fields)) | |
| 69 | + except ValueError: | |
| 70 | + return None | |
| 71 | + return board if board.is_valid() else None | |
| 72 | + | |
| 73 | + | |
| 74 | +def _pgn(text, elo, username): | |
| 75 | + stream = io.StringIO(text) | |
| 76 | + game = chess.pgn.read_game(stream) | |
| 77 | + if game is None: | |
| 78 | + return None | |
| 79 | + moves = list(game.mainline_moves()) | |
| 80 | + if game.errors and not moves: | |
| 81 | + return None | |
| 82 | + if not moves and "FEN" not in game.headers: | |
| 83 | + return None | |
| 84 | + more = chess.pgn.read_game(stream) is not None | |
| 85 | + headers = game.headers | |
| 86 | + | |
| 87 | + if "SchachHuman" in headers: | |
| 88 | + # aus diesem Programm kopiert: Zeichen, Bewertung und Seite bleiben erhalten | |
| 89 | + state = savegames.from_pgn(text) | |
| 90 | + state.path = "" | |
| 91 | + return Pasted("pgn", state=state, more_games=more) | |
| 92 | + | |
| 93 | + board = game.board() | |
| 94 | + for move in moves: | |
| 95 | + board.push(move) | |
| 96 | + white, black = headers.get("White", "?"), headers.get("Black", "?") | |
| 97 | + final = "" | |
| 98 | + if not board.is_game_over(claim_draw=True): | |
| 99 | + final = RESULT_TEXT.get(headers.get("Result", "*"), "") | |
| 100 | + me = username.lower() | |
| 101 | + if me and me in (white.lower(), black.lower()): | |
| 102 | + human = chess.WHITE if white.lower() == me else chess.BLACK | |
| 103 | + opponent = black if human == chess.WHITE else white | |
| 104 | + state = savegames.GameState( | |
| 105 | + board=board, human=human, elo=elo, mode="review", opponent=opponent, final_text=final, | |
| 106 | + name=headers.get("Event", "") if headers.get("Event", "?") != "?" else "", | |
| 107 | + ) | |
| 108 | + else: | |
| 109 | + state = savegames.GameState( | |
| 110 | + board=board, human=chess.WHITE, elo=elo, mode="review", final_text=final, | |
| 111 | + names=(white, black), name=_title(headers), | |
| 112 | + ) | |
| 113 | + if not moves: | |
| 114 | + # nur eine Stellung (PGN mit FEN-Kopf): gegen Maia weiterspielen | |
| 115 | + state = savegames.GameState(board=board, human=board.turn, elo=elo, name=_title(headers)) | |
| 116 | + return Pasted("pgn", state=state, more_games=more) | |
| 117 | + | |
| 118 | + | |
| 119 | +def _title(headers): | |
| 120 | + white, black = headers.get("White", "?"), headers.get("Black", "?") | |
| 121 | + if white != "?" or black != "?": | |
| 122 | + return f"{white} – {black}" | |
| 123 | + event = headers.get("Event", "?") | |
| 124 | + return event if event != "?" else "Partie aus der Zwischenablage" | |
modified schach/lichess.py +8 −0
| @@ -276,6 +276,14 @@ class Client: | ||
| 276 | 276 | return rounds[0].get("ratingDiff") if rounds else None |
| 277 | 277 | |
| 278 | 278 | # Partien |
| 279 | + def export_game(self, game_id): | |
| 280 | + """Eine Partie als PGN – auch ohne Anmeldung, für öffentliche Partien.""" | |
| 281 | + return self._get( | |
| 282 | + f"/game/export/{urllib.parse.quote(game_id)}", | |
| 283 | + params={"clocks": "false", "evals": "false", "literate": "false"}, | |
| 284 | + headers={"Accept": "application/x-chess-pgn"}, | |
| 285 | + ).text | |
| 286 | + | |
| 279 | 287 | def games(self, username, max_games=30): |
| 280 | 288 | resp = self._get( |
| 281 | 289 | f"/api/games/user/{urllib.parse.quote(username)}", |
modified schach/savegames.py +9 −3
| @@ -37,6 +37,7 @@ class GameState: | ||
| 37 | 37 | mode: str = "maia" # "maia" = gegen Maia weiterspielbar, "review" = nur ansehen (Lichess-Partie) |
| 38 | 38 | opponent: str = "" # Gegnername, wenn nicht Maia |
| 39 | 39 | final_text: str = "" # Partie-Ende, das nicht am Brett ablesbar ist (Aufgabe, Zeit …) |
| 40 | + names: tuple = () # (Weiß, Schwarz) bei fremden Partien, an denen man selbst nicht beteiligt war | |
| 40 | 41 | |
| 41 | 42 | def truncated(self, ply): |
| 42 | 43 | """Kopie bis einschließlich Halbzug ``ply`` (für Abzweigungen).""" |
| @@ -59,9 +60,13 @@ def to_pgn(state): | ||
| 59 | 60 | game.headers["Event"] = state.name or "Partie gegen Maia-3" |
| 60 | 61 | game.headers["Date"] = now.strftime("%Y.%m.%d") |
| 61 | 62 | maia = state.opponent or f"Maia-3 ({state.elo})" |
| 62 | - game.headers["White"], game.headers["Black"] = ( | |
| 63 | - ("Spieler", maia) if state.human == chess.WHITE else (maia, "Spieler") | |
| 64 | - ) | |
| 63 | + if state.names: | |
| 64 | + game.headers["White"], game.headers["Black"] = state.names | |
| 65 | + game.headers["SchachForeign"] = "1" | |
| 66 | + else: | |
| 67 | + game.headers["White"], game.headers["Black"] = ( | |
| 68 | + ("Spieler", maia) if state.human == chess.WHITE else (maia, "Spieler") | |
| 69 | + ) | |
| 65 | 70 | game.headers["Result"] = state.board.result(claim_draw=True) |
| 66 | 71 | if state.final_text and game.headers["Result"] == "*": |
| 67 | 72 | game.headers["Termination"] = state.final_text |
| @@ -113,6 +118,7 @@ def from_pgn(text, path=""): | ||
| 113 | 118 | mode=headers.get("SchachMode", "maia"), |
| 114 | 119 | opponent=headers.get("SchachOpponent", ""), |
| 115 | 120 | final_text=headers.get("SchachEnd", ""), |
| 121 | + names=(headers.get("White", "?"), headers.get("Black", "?")) if headers.get("SchachForeign") else (), | |
| 116 | 122 | ) |
| 117 | 123 | |
| 118 | 124 | |
added tests/__init__.py +0 −0
added tests/test_clipboard.py +91 −0
| @@ -0,0 +1,91 @@ | ||
| 1 | +import unittest | |
| 2 | + | |
| 3 | +import chess | |
| 4 | + | |
| 5 | +from schach import clipboard, savegames | |
| 6 | + | |
| 7 | +ITALIAN = """[Event "Club"] | |
| 8 | +[White "Florian"] | |
| 9 | +[Black "Max"] | |
| 10 | +[Result "1-0"] | |
| 11 | + | |
| 12 | +1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 1-0 | |
| 13 | +""" | |
| 14 | + | |
| 15 | + | |
| 16 | +class ParseTest(unittest.TestCase): | |
| 17 | + def test_empty_and_noise(self): | |
| 18 | + self.assertIsNone(clipboard.parse("")) | |
| 19 | + self.assertIsNone(clipboard.parse("Hallo Welt")) | |
| 20 | + self.assertIsNone(clipboard.parse("https://lichess.org/training")) | |
| 21 | + | |
| 22 | + def test_fen(self): | |
| 23 | + fen = "r1bqkbnr/pppp1ppp/2n5/4p3/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 2 3" | |
| 24 | + pasted = clipboard.parse(fen) | |
| 25 | + self.assertEqual(pasted.kind, "fen") | |
| 26 | + self.assertEqual(pasted.state.board.fen(), fen) | |
| 27 | + self.assertEqual(pasted.state.human, chess.WHITE) | |
| 28 | + self.assertEqual(pasted.state.mode, "maia") | |
| 29 | + | |
| 30 | + def test_placement_only_fen_means_white_to_move(self): | |
| 31 | + pasted = clipboard.parse("rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR") | |
| 32 | + self.assertEqual(pasted.kind, "fen") | |
| 33 | + self.assertEqual(pasted.state.board.turn, chess.WHITE) | |
| 34 | + | |
| 35 | + def test_invalid_fen_is_rejected(self): | |
| 36 | + self.assertIsNone(clipboard.parse("8/8/8/8/8/8/8/8 w - - 0 1")) # keine Könige | |
| 37 | + | |
| 38 | + def test_foreign_pgn_keeps_names(self): | |
| 39 | + pasted = clipboard.parse(ITALIAN) | |
| 40 | + self.assertEqual(pasted.kind, "pgn") | |
| 41 | + state = pasted.state | |
| 42 | + self.assertEqual(state.mode, "review") | |
| 43 | + self.assertEqual(state.names, ("Florian", "Max")) | |
| 44 | + self.assertEqual(len(state.board.move_stack), 6) | |
| 45 | + self.assertEqual(state.final_text, "Weiß hat gewonnen.") | |
| 46 | + self.assertFalse(pasted.more_games) | |
| 47 | + | |
| 48 | + def test_own_lichess_name_picks_side(self): | |
| 49 | + state = clipboard.parse(ITALIAN, username="max").state | |
| 50 | + self.assertEqual(state.human, chess.BLACK) | |
| 51 | + self.assertEqual(state.opponent, "Florian") | |
| 52 | + self.assertEqual(state.names, ()) | |
| 53 | + | |
| 54 | + def test_bare_movetext(self): | |
| 55 | + pasted = clipboard.parse("1. d4 d5 2. c4") | |
| 56 | + self.assertEqual(pasted.kind, "pgn") | |
| 57 | + self.assertEqual(len(pasted.state.board.move_stack), 3) | |
| 58 | + | |
| 59 | + def test_multiple_games(self): | |
| 60 | + self.assertTrue(clipboard.parse(ITALIAN + "\n" + ITALIAN).more_games) | |
| 61 | + | |
| 62 | + def test_roundtrip_own_pgn(self): | |
| 63 | + board = chess.Board() | |
| 64 | + for san in ("e4", "e5", "Qh5", "Nc6"): | |
| 65 | + board.push_san(san) | |
| 66 | + state = savegames.GameState(board=board, human=chess.BLACK, elo=900, symbols={2: "?!"}, evals={3: 61.0}) | |
| 67 | + pasted = clipboard.parse(savegames.to_pgn(state)) | |
| 68 | + self.assertEqual(pasted.state.human, chess.BLACK) | |
| 69 | + self.assertEqual(pasted.state.symbols, {2: "?!"}) | |
| 70 | + self.assertEqual(pasted.state.evals, {3: 61.0}) | |
| 71 | + self.assertEqual(pasted.state.mode, "maia") | |
| 72 | + | |
| 73 | + def test_foreign_names_roundtrip(self): | |
| 74 | + state = clipboard.parse(ITALIAN).state | |
| 75 | + again = savegames.from_pgn(savegames.to_pgn(state)) | |
| 76 | + self.assertEqual(again.names, ("Florian", "Max")) | |
| 77 | + | |
| 78 | + def test_lichess_links(self): | |
| 79 | + for text, expected in [ | |
| 80 | + ("https://lichess.org/abcd1234", ("abcd1234", None)), | |
| 81 | + ("lichess.org/abcd1234/black", ("abcd1234", chess.BLACK)), | |
| 82 | + ("https://lichess.org/abcd1234wxyz", ("abcd1234", None)), | |
| 83 | + ("https://lichess.org/abcd1234#12", ("abcd1234", None)), | |
| 84 | + ]: | |
| 85 | + pasted = clipboard.parse(text) | |
| 86 | + self.assertEqual(pasted.kind, "lichess", text) | |
| 87 | + self.assertEqual((pasted.game_id, pasted.orientation), expected, text) | |
| 88 | + | |
| 89 | + | |
| 90 | +if __name__ == "__main__": | |
| 91 | + unittest.main() | |