Public repository: timo / schach

Reader

Ein aufgeräumtes Schach-Programm für GNOME

feat(prefs): add preferences dialog

public

feat(prefs): add preferences dialog

Engines, board colours and piece sets outgrow the main menu.
- Allgemein: default colour, Maia temperature (was a constant)
- Darstellung: piece set, moved out of the main menu
- Lichess: account with avatar, login/logout moved out of menu
Settings apply to all open windows immediately (Ctrl+,).

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

modified schach/app.py +38 −21

@@ -18,6 +18,7 @@ from gi.repository import Adw, Gio, GLib
1818
 from . import annotate, lichess, savegames  # noqa: E402
1919
 from .board import BoardView, available_themes  # noqa: E402
2020
 from .movelist import MoveList  # noqa: E402
21
+from .prefs import Preferences  # noqa: E402
2122
 from .engines import MAIA_CMD, STOCKFISH_CMD, EngineWorker, maia_candidates, maia_move  # noqa: E402
2223
 from .online import OnlineMixin  # noqa: E402
2324
 from .puzzles import PuzzleMixin  # noqa: E402
@@ -33,7 +34,10 @@ FEATURED_THEMES = [
3334
 ]
3435
 
3536
 SETTINGS_PATH = os.path.join(GLib.get_user_config_dir(), "schach", "settings.json")
36
-DEFAULTS = {"elo": 1200, "color": "white", "theme": "cburnett", "puzzle_difficulty": "normal"}
37
+DEFAULTS = {
38
+    "elo": 1200, "color": "white", "theme": "cburnett", "puzzle_difficulty": "normal",
39
+    "temperature": OPPONENT_TEMPERATURE,
40
+}
3741
 
3842
 
3943
 def load_settings():
@@ -102,6 +106,7 @@ class Window(OnlineMixin, PuzzleMixin, A
102106
         self.opponent = ""  # Gegnername, wenn nicht Maia
103107
         self.final_text = None  # Partie-Ende, das nicht am Brett ablesbar ist (Aufgabe, Zeit, Rätsel gelöst)
104108
         self.puzzle = None
109
+        self.prefs_dialog = None
105110
         self.review_requested = set()
106111
         self._online_init()
107112
 
@@ -164,15 +169,9 @@ class Window(OnlineMixin, PuzzleMixin, A
164169
         menu.append_section("Lichess", self.lichess_section)
165170
         view = Gio.Menu()
166171
         view.append("Brett _drehen", "win.flip")
167
-        themes = Gio.Menu()
168
-        installed = set(available_themes())
169
-        for name in FEATURED_THEMES:
170
-            if name in installed:
171
-                label = "Eingebaut" if name == "python-chess" else name.capitalize()
172
-                themes.append(label, f"win.theme::{name}")
173
-        view.append_submenu("_Figuren", themes)
174172
         menu.append_section(None, view)
175173
         about = Gio.Menu()
174
+        about.append("_Einstellungen", "win.preferences")
176175
         about.append("_Tastenkürzel", "win.shortcuts")
177176
         about.append("_Info zu Schach", "win.about")
178177
         menu.append_section(None, about)
@@ -288,17 +287,13 @@ class Window(OnlineMixin, PuzzleMixin, A
288287
             ("resign", self._resign),
289288
             ("open-lichess-game", self._open_lichess_game),
290289
             ("shortcuts", self._shortcuts_dialog),
290
+            ("preferences", self._preferences_dialog),
291291
             ("about", self._about_dialog),
292292
         ]:
293293
             action = Gio.SimpleAction.new(name, None)
294294
             action.connect("activate", handler)
295295
             self.add_action(action)
296296
 
297
-        theme = Gio.SimpleAction.new_stateful(
298
-            "theme", GLib.VariantType.new("s"), GLib.Variant.new_string(self.settings["theme"])
299
-        )
300
-        theme.connect("activate", self._on_theme)
301
-        self.add_action(theme)
302297
         difficulty = Gio.SimpleAction.new_stateful(
303298
             "puzzle-difficulty", GLib.VariantType.new("s"),
304299
             GLib.Variant.new_string(self.settings.get("puzzle_difficulty", "normal")),
@@ -318,6 +313,7 @@ class Window(OnlineMixin, PuzzleMixin, A
318313
         app.set_accels_for_action("win.end-browse", ["Escape"])
319314
         app.set_accels_for_action("win.puzzle", ["r"])
320315
         app.set_accels_for_action("win.shortcuts", ["<Control>question"])
316
+        app.set_accels_for_action("win.preferences", ["<Control>comma"])
321317
 
322318
     def _action(self, name):
323319
         return self.lookup_action(name)
@@ -331,10 +327,11 @@ class Window(OnlineMixin, PuzzleMixin, A
331327
         else:
332328
             label = f"Lichess · {user.get('username', '')}"
333329
             self.lichess_section.append("Meine Lichess-_Partien …", "win.lichess-games")
334
-            self.lichess_section.append(f"Abmelden ({user.get('username', '')})", "win.lichess-logout")
335330
         # Abschnittsüberschrift zeigt den Anmeldestatus; dafür den Abschnitt neu einhängen
336331
         self.primary_menu.remove(1)
337332
         self.primary_menu.insert_section(1, label, self.lichess_section)
333
+        if self.prefs_dialog is not None:
334
+            self.prefs_dialog.refresh_lichess()
338335
 
339336
     # --- Zustand → Anzeige -------------------------------------------------
340337
 
@@ -636,7 +633,8 @@ class Window(OnlineMixin, PuzzleMixin, A
636633
             else:
637634
                 apply(move)
638635
 
639
-        self.maia.submit(maia_move(self.board, self.elo, OPPONENT_TEMPERATURE), on_move)
636
+        temperature = float(self.settings.get("temperature", OPPONENT_TEMPERATURE))
637
+        self.maia.submit(maia_move(self.board, self.elo, temperature), on_move)
640638
 
641639
     def _on_maia_ready(self, error):
642640
         if error:
@@ -858,11 +856,23 @@ class Window(OnlineMixin, PuzzleMixin, A
858856
         self.view.flipped = not self.view.flipped
859857
         self.view.queue_draw()
860858
 
861
-    def _on_theme(self, action, value):
862
-        action.set_state(value)
863
-        self.settings["theme"] = value.get_string()
864
-        save_settings(self.settings)
865
-        self.view.set_theme(value.get_string())
859
+    def apply_setting(self, key, value):
860
+        """Von den Einstellungen gerufen (für jedes Fenster)."""
861
+        self.settings[key] = value
862
+        if key == "theme":
863
+            self.view.set_theme(value)
864
+
865
+    def _preferences_dialog(self, *_):
866
+        if self.prefs_dialog is not None:
867
+            return
868
+        installed = set(available_themes())
869
+        themes = [
870
+            (name, "Eingebaut" if name == "python-chess" else name.capitalize())
871
+            for name in FEATURED_THEMES if name in installed
872
+        ]
873
+        dialog = self.prefs_dialog = Preferences(self, themes)
874
+        dialog.connect("closed", lambda *_: setattr(self, "prefs_dialog", None))
875
+        dialog.present(self)
866876
 
867877
     # --- Dialoge -----------------------------------------------------------
868878
 
@@ -939,7 +949,7 @@ class Window(OnlineMixin, PuzzleMixin, A
939949
                 ("Spielstand speichern", "<Control>s"), ("Spielstände öffnen", "<Control>o"),
940950
                 ("Als PGN exportieren", "<Control><Shift>s"),
941951
             ]),
942
-            ("Allgemein", [("Tastenkürzel", "<Control>question")]),
952
+            ("Allgemein", [("Einstellungen", "<Control>comma"), ("Tastenkürzel", "<Control>question")]),
943953
         ]:
944954
             section = Adw.ShortcutsSection(title=title)
945955
             for label, accel in items:
@@ -1261,6 +1271,13 @@ class SchachApp(Adw.Application):
12611271
             win._refresh()
12621272
         self._toast(Adw.Toast(title="Von Lichess abgemeldet", timeout=2))
12631273
 
1274
+    def update_setting(self, key, value):
1275
+        settings = load_settings()
1276
+        settings[key] = value
1277
+        save_settings(settings)
1278
+        for win in self._windows():
1279
+            win.apply_setting(key, value)
1280
+
12641281
     def _free_window(self):
12651282
         win = self.get_active_window()
12661283
         if isinstance(win, Window) and not win._busy():

added schach/prefs.py +114 −0

@@ -0,0 +1,114 @@
1
+"""Einstellungen (Adw.PreferencesDialog): gilt sofort, ohne Speichern-Knopf."""
2
+
3
+import gi
4
+
5
+gi.require_version("Gtk", "4.0")
6
+gi.require_version("Adw", "1")
7
+from gi.repository import Adw, Gtk  # noqa: E402
8
+
9
+COLORS = [("white", "Weiß"), ("black", "Schwarz"), ("random", "Zufällig")]
10
+
11
+
12
+class Preferences(Adw.PreferencesDialog):
13
+    def __init__(self, win, themes):
14
+        super().__init__(title="Einstellungen", search_enabled=False)
15
+        self.win = win
16
+        self.app = win.get_application()
17
+        self._themes = themes  # [(name, label)]
18
+        self.add(self._general_page())
19
+        self.add(self._appearance_page())
20
+        self.add(self._lichess_page())
21
+        self.refresh_lichess()
22
+
23
+    def _set(self, key, value):
24
+        """Wert in allen Fenstern übernehmen und speichern."""
25
+        self.app.update_setting(key, value)
26
+
27
+    # --- Allgemein ---------------------------------------------------------
28
+
29
+    def _general_page(self):
30
+        page = Adw.PreferencesPage(title="Allgemein", icon_name="preferences-system-symbolic")
31
+        settings = self.win.settings
32
+
33
+        game = Adw.PreferencesGroup(title="Neue Partie")
34
+        color = Adw.ComboRow(
35
+            title="Deine Farbe", subtitle="Vorauswahl im Dialog „Neue Partie“",
36
+            model=Gtk.StringList.new([label for _, label in COLORS]),
37
+        )
38
+        keys = [key for key, _ in COLORS]
39
+        color.set_selected(keys.index(settings.get("color", "white")) if settings.get("color") in keys else 0)
40
+        color.connect("notify::selected", lambda row, _p: self._set("color", keys[row.get_selected()]))
41
+        game.add(color)
42
+        page.add(game)
43
+
44
+        opponent = Adw.PreferencesGroup(title="Gegner")
45
+        spread = Adw.SpinRow(
46
+            title="Streuung von Maia",
47
+            subtitle="0 = immer der wahrscheinlichste Zug, 1 = menschlich, darüber wilder",
48
+            digits=1,
49
+            adjustment=Gtk.Adjustment(lower=0.0, upper=2.0, step_increment=0.1, page_increment=0.5),
50
+        )
51
+        spread.set_value(float(settings.get("temperature", 1.0)))
52
+        spread.connect("notify::value", lambda row, _p: self._set("temperature", round(row.get_value(), 1)))
53
+        opponent.add(spread)
54
+        page.add(opponent)
55
+        return page
56
+
57
+    # --- Darstellung -------------------------------------------------------
58
+
59
+    def _appearance_page(self):
60
+        page = Adw.PreferencesPage(title="Darstellung", icon_name="preferences-desktop-appearance-symbolic")
61
+        self.appearance_page = page
62
+        pieces = Adw.PreferencesGroup(title="Figuren")
63
+        names = [name for name, _ in self._themes]
64
+        row = Adw.ComboRow(
65
+            title="Figurensatz", model=Gtk.StringList.new([label for _, label in self._themes]),
66
+        )
67
+        current = self.win.settings.get("theme")
68
+        if current in names:
69
+            row.set_selected(names.index(current))
70
+        row.connect("notify::selected", lambda r, _p: self._set("theme", names[r.get_selected()]))
71
+        pieces.add(row)
72
+        page.add(pieces)
73
+        return page
74
+
75
+    # --- Lichess -----------------------------------------------------------
76
+
77
+    def _lichess_page(self):
78
+        page = Adw.PreferencesPage(title="Lichess", icon_name="avatar-default-symbolic")
79
+        self.lichess_group = Adw.PreferencesGroup(
80
+            title="Konto",
81
+            description="Anmeldung über den Browser – das Programm sieht kein Passwort. "
82
+                        "Der Zugriffsschlüssel liegt im GNOME-Schlüsselbund.",
83
+        )
84
+        self.lichess_row = Adw.ActionRow()
85
+        self.lichess_avatar = Adw.Avatar(size=40, show_initials=True)
86
+        self.lichess_row.add_prefix(self.lichess_avatar)
87
+        self.lichess_button = Gtk.Button(valign=Gtk.Align.CENTER)
88
+        self.lichess_button.connect("clicked", self._on_lichess_button)
89
+        self.lichess_row.add_suffix(self.lichess_button)
90
+        self.lichess_group.add(self.lichess_row)
91
+        page.add(self.lichess_group)
92
+        return page
93
+
94
+    def refresh_lichess(self):
95
+        user = self.app.lichess_user
96
+        if user is None:
97
+            self.lichess_row.set_title("Nicht angemeldet")
98
+            self.lichess_row.set_subtitle("Für Online-Partien, Rätselwertung und deine Lichess-Partien")
99
+            self.lichess_avatar.set_text("")
100
+            self.lichess_button.set_label("Anmelden …")
101
+            self.lichess_button.set_css_classes(["suggested-action"])
102
+        else:
103
+            name = user.get("username", "")
104
+            self.lichess_row.set_title(name)
105
+            self.lichess_row.set_subtitle("Angemeldet bei lichess.org")
106
+            self.lichess_avatar.set_text(name)
107
+            self.lichess_button.set_label("Abmelden")
108
+            self.lichess_button.set_css_classes([])
109
+
110
+    def _on_lichess_button(self, _button):
111
+        if self.app.lichess_user is None:
112
+            self.app.lichess_login(self.win)
113
+        else:
114
+            self.app.lichess_logout()