silentengine 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
silentengine/board.py ADDED
@@ -0,0 +1,606 @@
1
+ from __future__ import annotations
2
+ import math
3
+
4
+ import chess
5
+ import chess.engine
6
+ import chess.pgn
7
+ import chess.polyglot
8
+ import chess.svg
9
+ from PySide6.QtCore import QByteArray, QPointF, QRectF, Qt, Signal, QMimeData, QPoint
10
+ from PySide6.QtGui import (
11
+ QBrush,
12
+ QColor,
13
+ QIcon,
14
+ QPainter,
15
+ QPen,
16
+ QPixmap,
17
+ QPolygonF,
18
+ QDrag,
19
+ QPainterPath,
20
+ )
21
+ from PySide6.QtSvg import QSvgRenderer
22
+ from PySide6.QtWidgets import (
23
+ QDialog,
24
+ QToolButton,
25
+ QVBoxLayout,
26
+ QWidget,
27
+ QApplication,
28
+ QLabel,
29
+ )
30
+
31
+ from silentengine.theme import (
32
+ LIGHT_SQ,
33
+ DARK_SQ,
34
+ LAST_MOVE,
35
+ SELECT,
36
+ ARROW,
37
+ MARK,
38
+ MARK_ALT,
39
+ HINT,
40
+ )
41
+ from silentengine.widgets import EvalBar
42
+
43
+ PIECE_MIME = "application/x-silentengine-piece"
44
+
45
+
46
+ class PieceChip(QLabel):
47
+ """A piece in the free-move palette: drag it onto the board."""
48
+
49
+ def __init__(self, piece: chess.Piece, pixmap: QPixmap) -> None:
50
+ super().__init__()
51
+ self.piece, self._pm = piece, pixmap
52
+ self.setPixmap(pixmap)
53
+ self.setFixedSize(pixmap.width() + 8, pixmap.height() + 8)
54
+ self.setAlignment(Qt.AlignCenter)
55
+ self.setCursor(Qt.OpenHandCursor)
56
+ self.setToolTip(
57
+ f"{'White' if piece.color else 'Black'} {chess.piece_name(piece.piece_type)}: drag onto the board"
58
+ )
59
+ self._press: QPoint | None = None
60
+
61
+ def mousePressEvent(self, e) -> None:
62
+ if e.button() == Qt.LeftButton:
63
+ self._press = e.position().toPoint()
64
+
65
+ def mouseMoveEvent(self, e) -> None:
66
+ if self._press is None or not (e.buttons() & Qt.LeftButton):
67
+ return
68
+ if (
69
+ e.position().toPoint() - self._press
70
+ ).manhattanLength() < QApplication.startDragDistance():
71
+ return
72
+ self._press = None
73
+ drag = QDrag(self)
74
+ mime = QMimeData()
75
+ mime.setData(PIECE_MIME, QByteArray(self.piece.symbol().encode()))
76
+ drag.setMimeData(mime)
77
+ drag.setPixmap(self._pm)
78
+ drag.setHotSpot(QPoint(self._pm.width() // 2, self._pm.height() // 2))
79
+ drag.exec(Qt.CopyAction)
80
+
81
+ def mouseReleaseEvent(self, e) -> None:
82
+ self._press = None
83
+
84
+
85
+ class BoardWidget(QWidget):
86
+ moveMade = Signal(object)
87
+ freeMoved = Signal(int, int)
88
+ freePlaced = Signal(int, int, bool) # square, piece type, color
89
+ freeRemoved = Signal(int)
90
+
91
+ def __init__(self) -> None:
92
+ super().__init__()
93
+ self.free = False
94
+ # self.brush: chess.Piece | None = None
95
+ self.board = chess.Board()
96
+ self.last_move: chess.Move | None = None
97
+ self.flipped = False
98
+ self.arrows: list[tuple[int, int]] = []
99
+ self.selected: int | None = None
100
+ self.drag_from: int | None = None
101
+ self.drag_pos = QPointF()
102
+ self._renderers: dict[str, QSvgRenderer] = {}
103
+ self.setMinimumSize(360, 360)
104
+ self.badge: tuple[str, str] | None = (
105
+ None # (text, color) on last move's target square
106
+ )
107
+ self.marks: list[tuple[int, int, bool]] = (
108
+ []
109
+ ) # (from, to, alt); from == to is a circle
110
+ self.right_from: int | None = None
111
+ self.right_to: int | None = None
112
+ self.right_alt = False
113
+ self.hint: tuple[int, int] | None = None
114
+
115
+ # state -------------------------------------------------------------- #
116
+ def set_position(self, board: chess.Board, last_move: chess.Move | None) -> None:
117
+ self.board = board.copy()
118
+ self.last_move = last_move
119
+ self.selected = None
120
+ self.drag_from = None
121
+ self.badge = None
122
+ self.hint = None
123
+ self.marks = []
124
+ self.right_from = self.right_to = None
125
+ self.update()
126
+
127
+ def set_badge(self, text: str | None, color: str = "") -> None:
128
+ self.badge = (text, color) if text else None
129
+ self.update()
130
+
131
+ def set_arrows(self, arrows: list[tuple[int, int]]) -> None:
132
+ self.arrows = arrows
133
+ self.update()
134
+
135
+ def set_hint(self, a: int | None, b: int | None = None) -> None:
136
+ self.hint = (a, b) if a is not None else None
137
+ self.update()
138
+
139
+ def set_flipped(self, flipped: bool) -> None:
140
+ self.flipped = flipped
141
+ self.update()
142
+
143
+ # geometry ----------------------------------------------------------- #
144
+ def _sq_size(self) -> float:
145
+ return min(self.width(), self.height()) / 8
146
+
147
+ def _rect(self, square: int) -> QRectF:
148
+ f, r = chess.square_file(square), chess.square_rank(square)
149
+ col = 7 - f if self.flipped else f
150
+ row = r if self.flipped else 7 - r
151
+ s = self._sq_size()
152
+ return QRectF(col * s, row * s, s, s)
153
+
154
+ def _square_at(self, pos: QPointF) -> int | None:
155
+ s = self._sq_size()
156
+ col, row = int(pos.x() // s), int(pos.y() // s)
157
+ if not (0 <= col < 8 and 0 <= row < 8):
158
+ return None
159
+ f = 7 - col if self.flipped else col
160
+ r = row if self.flipped else 7 - row
161
+ return chess.square(f, r)
162
+
163
+ def _renderer(self, piece: chess.Piece) -> QSvgRenderer:
164
+ key = piece.symbol()
165
+ if key not in self._renderers:
166
+ data = QByteArray(chess.svg.piece(piece).encode("utf-8"))
167
+ self._renderers[key] = QSvgRenderer(data)
168
+ return self._renderers[key]
169
+
170
+ # painting ----------------------------------------------------------- #
171
+
172
+ def _moves_from(self, src: int) -> list[chess.Move]:
173
+ """Legal destinations for the piece on src (one entry per square)."""
174
+ piece = self.board.piece_at(src)
175
+ if piece is None:
176
+ return []
177
+ b = self.board
178
+ if self.free: # in free mode any color can move, whatever the turn is
179
+ b = self.board.copy(stack=False)
180
+ b.turn = piece.color
181
+ b.ep_square = None
182
+ out, seen = [], set()
183
+ for m in b.legal_moves:
184
+ if m.from_square != src or m.to_square in seen:
185
+ continue
186
+ if self.free:
187
+ target = self.board.piece_at(m.to_square)
188
+ if b.is_castling(m) or (target and target.piece_type == chess.KING):
189
+ continue
190
+ seen.add(m.to_square)
191
+ out.append(m)
192
+ return out
193
+
194
+ def paintEvent(self, _event) -> None:
195
+ p = QPainter(self)
196
+ p.setRenderHint(QPainter.Antialiasing)
197
+ s = self._sq_size()
198
+
199
+ for sq in chess.SQUARES:
200
+ light = (chess.square_file(sq) + chess.square_rank(sq)) % 2 == 1
201
+ p.fillRect(self._rect(sq), LIGHT_SQ if light else DARK_SQ)
202
+
203
+ if self.last_move:
204
+ for sq in (self.last_move.from_square, self.last_move.to_square):
205
+ p.fillRect(self._rect(sq), LAST_MOVE)
206
+ if self.selected is not None:
207
+ p.fillRect(self._rect(self.selected), SELECT)
208
+ if self.board.is_check():
209
+ king = self.board.king(self.board.turn)
210
+ if king is not None:
211
+ p.fillRect(self._rect(king), QColor(220, 40, 40, 140))
212
+
213
+ # coordinates
214
+ font = p.font()
215
+ font.setPixelSize(max(9, int(s * 0.16)))
216
+ font.setBold(True)
217
+ p.setFont(font)
218
+ for i in range(8):
219
+ f = 7 - i if self.flipped else i
220
+ r = i if self.flipped else 7 - i
221
+ bottom_sq = chess.square(f, 0 if not self.flipped else 7)
222
+ left_sq = chess.square(0 if not self.flipped else 7, r)
223
+ for sq, label, align in (
224
+ (bottom_sq, chess.FILE_NAMES[f], Qt.AlignRight | Qt.AlignBottom),
225
+ (left_sq, str(r + 1), Qt.AlignLeft | Qt.AlignTop),
226
+ ):
227
+ light = (chess.square_file(sq) + chess.square_rank(sq)) % 2 == 1
228
+ p.setPen(DARK_SQ if light else LIGHT_SQ)
229
+ p.drawText(self._rect(sq).adjusted(3, 2, -3, -2), align, label)
230
+
231
+ # legal-move hints
232
+ src = self.drag_from if self.drag_from is not None else self.selected
233
+ if src is not None and not (self.free and self.drag_from is not None):
234
+ p.setPen(Qt.NoPen)
235
+ p.setBrush(QColor(0, 0, 0, 60))
236
+ for move in self._moves_from(src):
237
+ r = self._rect(move.to_square)
238
+ if self.board.piece_at(move.to_square) or self.board.is_en_passant(
239
+ move
240
+ ):
241
+ p.setBrush(Qt.NoBrush)
242
+ p.setPen(QPen(QColor(0, 0, 0, 60), s * 0.08))
243
+ p.drawEllipse(r.adjusted(s * 0.06, s * 0.06, -s * 0.06, -s * 0.06))
244
+ p.setPen(Qt.NoPen)
245
+ p.setBrush(QColor(0, 0, 0, 60))
246
+ else:
247
+ p.drawEllipse(r.center(), s * 0.15, s * 0.15)
248
+
249
+ # pieces
250
+ for sq, piece in self.board.piece_map().items():
251
+ if sq == self.drag_from:
252
+ continue
253
+ self._renderer(piece).render(p, self._rect(sq))
254
+
255
+ # move-quality badge (top-right corner of the destination square)
256
+ if self.badge and self.last_move:
257
+ text, color = self.badge
258
+ r = self._rect(self.last_move.to_square)
259
+ d = s * 0.38
260
+ c = QPointF(r.right() - d * 0.5, r.top() + d * 0.5)
261
+ p.setPen(QPen(QColor("#ffffff"), max(1.0, s * 0.025)))
262
+ p.setBrush(QColor(color))
263
+ p.drawEllipse(c, d / 2, d / 2)
264
+ f = p.font()
265
+ f.setPixelSize(max(8, int(d * 0.5)))
266
+ f.setBold(True)
267
+ p.setFont(f)
268
+ p.setPen(QColor("#ffffff"))
269
+ p.drawText(QRectF(c.x() - d / 2, c.y() - d / 2, d, d), Qt.AlignCenter, text)
270
+
271
+ # engine arrows
272
+ for a, b in self.arrows:
273
+ self._draw_arrow(p, a, b, s)
274
+
275
+ if self.hint:
276
+ self._draw_move_arrow(p, self.hint[0], self.hint[1], s, HINT)
277
+
278
+ # user annotations (right-click)
279
+ def draw_mark(a: int, b: int, alt: bool) -> None:
280
+ col = MARK_ALT if alt else MARK
281
+ df = abs(chess.square_file(a) - chess.square_file(b))
282
+ dr = abs(chess.square_rank(a) - chess.square_rank(b))
283
+ if a == b:
284
+ p.setBrush(Qt.NoBrush)
285
+ p.setPen(QPen(col, s * 0.07))
286
+ p.drawEllipse(
287
+ self._rect(a).adjusted(s * 0.06, s * 0.06, -s * 0.06, -s * 0.06)
288
+ )
289
+ elif {df, dr} == {1, 2}:
290
+ self._draw_knight_arrow(p, a, b, s, col)
291
+ else:
292
+ self._draw_arrow(p, a, b, s, col)
293
+
294
+ for a, b, alt in self.marks:
295
+ draw_mark(a, b, alt)
296
+ if self.right_from is not None and self.right_to is not None:
297
+ draw_mark(self.right_from, self.right_to, self.right_alt)
298
+
299
+ # dragged piece
300
+ if self.drag_from is not None:
301
+ piece = self.board.piece_at(self.drag_from)
302
+ if piece:
303
+ r = QRectF(self.drag_pos.x() - s / 2, self.drag_pos.y() - s / 2, s, s)
304
+ self._renderer(piece).render(p, r)
305
+
306
+ def _draw_arrow(self, p: QPainter, a: int, b: int, s: float, color=ARROW) -> None:
307
+ p1, p2 = self._rect(a).center(), self._rect(b).center()
308
+ dx, dy = p2.x() - p1.x(), p2.y() - p1.y()
309
+ length = math.hypot(dx, dy)
310
+ if length < 1:
311
+ return
312
+ ux, uy = dx / length, dy / length
313
+ head_len, head_w = s * 0.36, s * 0.36
314
+ start = QPointF(p1.x() + ux * s * 0.22, p1.y() + uy * s * 0.22)
315
+ base = QPointF(
316
+ p2.x() - ux * (head_len + s * 0.08), p2.y() - uy * (head_len + s * 0.08)
317
+ )
318
+ tip = QPointF(p2.x() - ux * s * 0.08, p2.y() - uy * s * 0.08)
319
+ px, py = -uy, ux
320
+ p.setPen(QPen(color, s * 0.14, Qt.SolidLine, Qt.FlatCap))
321
+ p.drawLine(start, base)
322
+ p.setPen(Qt.NoPen)
323
+ p.setBrush(QBrush(color))
324
+ p.drawPolygon(
325
+ QPolygonF(
326
+ [
327
+ tip,
328
+ QPointF(base.x() + px * head_w / 2, base.y() + py * head_w / 2),
329
+ QPointF(base.x() - px * head_w / 2, base.y() - py * head_w / 2),
330
+ ]
331
+ )
332
+ )
333
+
334
+ def _draw_knight_arrow(
335
+ self, p: QPainter, a: int, b: int, s: float, color=ARROW
336
+ ) -> None:
337
+ p1, p2 = self._rect(a).center(), self._rect(b).center()
338
+ dx, dy = p2.x() - p1.x(), p2.y() - p1.y()
339
+ sx, sy = (1 if dx > 0 else -1), (1 if dy > 0 else -1)
340
+ if abs(dx) > abs(dy): # long leg horizontal, short leg vertical
341
+ corner = QPointF(p2.x(), p1.y())
342
+ first, last = (sx, 0), (0, sy)
343
+ else: # long leg vertical, short leg horizontal
344
+ corner = QPointF(p1.x(), p2.y())
345
+ first, last = (0, sy), (sx, 0)
346
+ head_len, head_w = s * 0.36, s * 0.36
347
+ start = QPointF(p1.x() + first[0] * s * 0.22, p1.y() + first[1] * s * 0.22)
348
+ base = QPointF(
349
+ p2.x() - last[0] * (head_len + s * 0.08),
350
+ p2.y() - last[1] * (head_len + s * 0.08),
351
+ )
352
+ tip = QPointF(p2.x() - last[0] * s * 0.08, p2.y() - last[1] * s * 0.08)
353
+ px, py = -last[1], last[0] # perpendicular to the last leg
354
+
355
+ path = QPainterPath(start)
356
+ path.lineTo(corner)
357
+ path.lineTo(base)
358
+ p.setBrush(Qt.NoBrush)
359
+ p.setPen(QPen(color, s * 0.14, Qt.SolidLine, Qt.FlatCap, Qt.MiterJoin))
360
+ p.drawPath(path)
361
+ p.setPen(Qt.NoPen)
362
+ p.setBrush(QBrush(color))
363
+ p.drawPolygon(
364
+ QPolygonF(
365
+ [
366
+ tip,
367
+ QPointF(base.x() + px * head_w / 2, base.y() + py * head_w / 2),
368
+ QPointF(base.x() - px * head_w / 2, base.y() - py * head_w / 2),
369
+ ]
370
+ )
371
+ )
372
+
373
+ def _draw_move_arrow(self, p: QPainter, a: int, b: int, s: float, color) -> None:
374
+ df = abs(chess.square_file(a) - chess.square_file(b))
375
+ dr = abs(chess.square_rank(a) - chess.square_rank(b))
376
+ if {df, dr} == {1, 2}:
377
+ self._draw_knight_arrow(p, a, b, s, color)
378
+ else:
379
+ self._draw_arrow(p, a, b, s, color)
380
+
381
+ # input -------------------------------------------------------------- #
382
+ def mousePressEvent(self, e) -> None:
383
+ if e.button() == Qt.RightButton:
384
+ sq = self._square_at(e.position())
385
+ if sq is not None:
386
+ self.right_from = self.right_to = sq
387
+ self.right_alt = bool(e.modifiers() & Qt.ControlModifier)
388
+ self.update()
389
+ return
390
+ if e.button() != Qt.LeftButton:
391
+ return
392
+ if self.marks:
393
+ self.marks = []
394
+ if e.button() != Qt.LeftButton:
395
+ return
396
+ sq = self._square_at(e.position())
397
+ if sq is None:
398
+ self.selected = None
399
+ self.update()
400
+ return
401
+ # if self.free and self.brush is not None:
402
+ # self.freePlaced.emit(sq, self.brush.piece_type, self.brush.color)
403
+ # return
404
+ if (
405
+ self.selected is not None
406
+ and sq != self.selected
407
+ and self._try_move(self.selected, sq)
408
+ ):
409
+ return
410
+ piece = self.board.piece_at(sq)
411
+ if piece and (self.free or piece.color == self.board.turn):
412
+ self.selected = sq
413
+ self.drag_from = sq
414
+ self.drag_pos = e.position()
415
+ else:
416
+ self.selected = None
417
+ self.update()
418
+
419
+ def mouseMoveEvent(self, e) -> None:
420
+ if self.right_from is not None:
421
+ self.right_to = self._square_at(e.position())
422
+ self.update()
423
+ return
424
+ if self.drag_from is not None:
425
+ self.drag_pos = e.position()
426
+ self.update()
427
+
428
+ def mouseReleaseEvent(self, e) -> None:
429
+ if e.button() == Qt.RightButton and self.right_from is not None:
430
+ dst = self._square_at(e.position())
431
+ if dst is not None:
432
+ key = (self.right_from, dst, self.right_alt)
433
+ if key in self.marks:
434
+ self.marks.remove(key) # drawing the same one again erases it
435
+ else:
436
+ self.marks.append(key)
437
+ self.right_from = self.right_to = None
438
+ self.update()
439
+ return
440
+ if self.drag_from is None:
441
+ return
442
+ src, self.drag_from = self.drag_from, None
443
+ dst = self._square_at(e.position())
444
+ if self.free and dst is None: # dropped outside the board: delete the piece
445
+ self.selected = None
446
+ self.freeRemoved.emit(src)
447
+ return
448
+ if dst is not None and dst != src:
449
+ if self._try_move(src, dst, drag=True):
450
+ return
451
+ self.selected = None
452
+ self.update()
453
+
454
+ def dragEnterEvent(self, e) -> None:
455
+ if self.free and e.mimeData().hasFormat(PIECE_MIME):
456
+ e.acceptProposedAction()
457
+
458
+ def dragMoveEvent(self, e) -> None:
459
+ if self.free and e.mimeData().hasFormat(PIECE_MIME):
460
+ e.acceptProposedAction()
461
+
462
+ def dropEvent(self, e) -> None:
463
+ if not (self.free and e.mimeData().hasFormat(PIECE_MIME)):
464
+ return
465
+ sq = self._square_at(e.position())
466
+ if sq is None:
467
+ return
468
+ piece = chess.Piece.from_symbol(bytes(e.mimeData().data(PIECE_MIME)).decode())
469
+ self.freePlaced.emit(sq, piece.piece_type, piece.color)
470
+ e.acceptProposedAction()
471
+
472
+ def _try_move(self, src: int, dst: int, drag: bool = False) -> bool:
473
+ if self.free:
474
+ piece, target = self.board.piece_at(src), self.board.piece_at(dst)
475
+ if piece is None:
476
+ return False
477
+ if drag:
478
+ if target and (
479
+ target.color == piece.color or target.piece_type == chess.KING
480
+ ):
481
+ return False
482
+ elif dst not in {m.to_square for m in self._moves_from(src)}:
483
+ return False
484
+ self.selected = None
485
+ self.freeMoved.emit(src, dst)
486
+ return True
487
+ piece = self.board.piece_at(src)
488
+ move = chess.Move(src, dst)
489
+
490
+ if self.free:
491
+ piece, target = self.board.piece_at(src), self.board.piece_at(dst)
492
+ if piece is None or (
493
+ target
494
+ and (target.color == piece.color or target.piece_type == chess.KING)
495
+ ):
496
+ return False # can't land on your own piece or capture a king
497
+ self.selected = None
498
+ self.freeMoved.emit(src, dst)
499
+ return True
500
+
501
+ if (
502
+ piece
503
+ and piece.piece_type == chess.PAWN
504
+ and chess.square_rank(dst) in (0, 7)
505
+ ):
506
+ if chess.Move(src, dst, chess.QUEEN) not in self.board.legal_moves:
507
+ return False
508
+ choice = self._ask_promotion(dst, piece.color)
509
+ if choice is None: # popup dismissed: cancel the move
510
+ self.selected = None
511
+ self.update()
512
+ return False
513
+ move.promotion = choice
514
+ if move not in self.board.legal_moves:
515
+ return False
516
+ self.selected = None
517
+ self.moveMade.emit(move)
518
+ return True
519
+
520
+ def _piece_pixmap(self, piece: chess.Piece, size: int) -> QPixmap:
521
+ pm = QPixmap(size, size)
522
+ pm.fill(Qt.transparent)
523
+ painter = QPainter(pm)
524
+ self._renderer(piece).render(painter, QRectF(0, 0, size, size))
525
+ painter.end()
526
+ return pm
527
+
528
+ def _ask_promotion(self, dst: int, color: bool) -> int | None:
529
+ size = max(44, int(self._sq_size()))
530
+ rect = self._rect(dst)
531
+ at_top = rect.center().y() < self.height() / 2
532
+ order = (chess.QUEEN, chess.ROOK, chess.BISHOP, chess.KNIGHT)
533
+ picker = PromotionPicker(
534
+ [(pt, self._piece_pixmap(chess.Piece(pt, color), size)) for pt in order],
535
+ size,
536
+ at_top,
537
+ self,
538
+ )
539
+ g = self.mapToGlobal(rect.topLeft().toPoint())
540
+ picker.move(g.x(), g.y() if at_top else g.y() + size - picker.height())
541
+ picker.exec()
542
+ return picker.choice
543
+
544
+
545
+ class PromotionPicker(QDialog):
546
+ """Popup with the four real piece images, shown on the promotion square."""
547
+
548
+ def __init__(self, options: list, size: int, at_top: bool, parent=None) -> None:
549
+ super().__init__(parent, Qt.Popup | Qt.FramelessWindowHint)
550
+ self.choice: int | None = None
551
+ self.setFixedSize(size, size * len(options))
552
+ self.setStyleSheet(
553
+ "QDialog { background:#f2f2f2; border:1px solid #888; }"
554
+ "QToolButton { background:#f2f2f2; border:none; padding:0; }"
555
+ "QToolButton:hover { background:#bcd7ff; }"
556
+ )
557
+ lay = QVBoxLayout(self)
558
+ lay.setContentsMargins(0, 0, 0, 0)
559
+ lay.setSpacing(0)
560
+ # queen always sits on the promotion square, the rest extend inward
561
+ for piece_type, pixmap in (options if at_top else list(reversed(options))):
562
+ btn = QToolButton()
563
+ btn.setIcon(QIcon(pixmap))
564
+ btn.setIconSize(pixmap.size())
565
+ btn.setFixedSize(size, size)
566
+ btn.setToolTip(chess.piece_name(piece_type).capitalize())
567
+ btn.clicked.connect(lambda _c=False, pt=piece_type: self._pick(pt))
568
+ lay.addWidget(btn)
569
+
570
+ def _pick(self, piece_type: int) -> None:
571
+ self.choice = piece_type
572
+ self.accept()
573
+
574
+
575
+ class BoardArea(QWidget):
576
+ """Keeps the eval bar and the square board aligned and the board square."""
577
+
578
+ BAR_W = 32
579
+ GAP = 8
580
+
581
+ def __init__(self, bar: EvalBar, board: BoardWidget) -> None:
582
+ super().__init__()
583
+ self.bar, self.board = bar, board
584
+ bar.setParent(self)
585
+ board.setParent(self)
586
+ self.setMinimumSize(360 + self.BAR_W + self.GAP, 360)
587
+
588
+ def resizeEvent(self, _event) -> None:
589
+ bar_w = 0 if self.bar.isHidden() else self.BAR_W
590
+ side = max(1, min(self.width() - bar_w - self.GAP, self.height()))
591
+ total = bar_w + (self.GAP if bar_w else 0) + side
592
+ x0, y0 = (self.width() - total) // 2, (self.height() - side) // 2
593
+ self.bar.setGeometry(x0, y0, bar_w, side)
594
+ self.board.setGeometry(x0 + total - side, y0, side, side)
595
+
596
+
597
+ class PreviewBoard(BoardWidget):
598
+ """Small read-only board shown while hovering an engine line."""
599
+
600
+ def __init__(self) -> None:
601
+ super().__init__()
602
+ self.setMinimumSize(0, 0)
603
+ self.setFixedSize(220, 220)
604
+ self.setWindowFlags(Qt.ToolTip | Qt.FramelessWindowHint)
605
+ self.setAttribute(Qt.WA_ShowWithoutActivating)
606
+ self.setAttribute(Qt.WA_TransparentForMouseEvents)
silentengine/config.py ADDED
@@ -0,0 +1,91 @@
1
+ from __future__ import annotations
2
+ import json
3
+ import os
4
+ import shutil
5
+ from pathlib import Path
6
+
7
+ from PySide6.QtCore import (
8
+ QSettings,
9
+ )
10
+
11
+ ROOT = Path(__file__).resolve().parent.parent
12
+ from silentengine.constants import APP_NAME, CPU_COUNT, DATA_DIR
13
+
14
+ DEFAULTS = {
15
+ "engines": [],
16
+ "engine": "",
17
+ "search_time": 10, # seconds, 0 = infinite
18
+ "multipv": 3,
19
+ "threads": max(1, CPU_COUNT // 2),
20
+ "hash": 256, # MB
21
+ "review_ms": 500, # per position when reviewing a full game
22
+ "show_arrows": True,
23
+ "show_eval": True,
24
+ "last_dir": "",
25
+ "username": "",
26
+ }
27
+
28
+
29
+ def load_config() -> dict:
30
+ s = QSettings(APP_NAME, APP_NAME)
31
+ cfg = dict(DEFAULTS)
32
+ try:
33
+ cfg["engines"] = list(json.loads(s.value("engines", "[]")))
34
+ except (ValueError, TypeError):
35
+ cfg["engines"] = []
36
+ cfg["engine"] = str(s.value("engine", ""))
37
+ cfg["last_dir"] = str(s.value("last_dir", ""))
38
+ cfg["username"] = str(s.value("username", ""))
39
+ for key in ("search_time", "multipv", "threads", "hash", "review_ms"):
40
+ try:
41
+ cfg[key] = int(s.value(key, DEFAULTS[key]))
42
+ except (ValueError, TypeError):
43
+ cfg[key] = DEFAULTS[key]
44
+ for key in ("show_arrows", "show_eval"):
45
+ cfg[key] = s.value(key, DEFAULTS[key], type=bool)
46
+ cfg["threads"] = min(max(1, cfg["threads"]), CPU_COUNT)
47
+ cfg["multipv"] = min(max(1, cfg["multipv"]), 5)
48
+
49
+ for path in discover_engines():
50
+ if path not in cfg["engines"]:
51
+ cfg["engines"].append(path)
52
+ cfg["engines"] = [p for p in cfg["engines"] if os.path.isfile(p)]
53
+ if cfg["engine"] not in cfg["engines"]:
54
+ cfg["engine"] = cfg["engines"][0] if cfg["engines"] else ""
55
+ return cfg
56
+
57
+
58
+ def save_config(cfg: dict) -> None:
59
+ s = QSettings(APP_NAME, APP_NAME)
60
+ s.setValue("engines", json.dumps(cfg["engines"]))
61
+ for key in (
62
+ "engine",
63
+ "search_time",
64
+ "multipv",
65
+ "threads",
66
+ "hash",
67
+ "review_ms",
68
+ "show_arrows",
69
+ "show_eval",
70
+ ):
71
+ s.setValue(key, cfg[key])
72
+ s.setValue("last_dir", cfg["last_dir"])
73
+ s.setValue("username", cfg["username"])
74
+
75
+
76
+ def discover_engines() -> list[str]:
77
+ found: list[str] = []
78
+ on_path = shutil.which("stockfish")
79
+ if on_path:
80
+ found.append(on_path)
81
+ folder = DATA_DIR / "engines"
82
+ folder.mkdir(exist_ok=True)
83
+ if folder.is_dir():
84
+ for p in sorted(folder.iterdir()):
85
+ if (
86
+ p.is_file()
87
+ and "stockfish" in p.name.lower()
88
+ and p.suffix.lower() in ("", ".exe")
89
+ ):
90
+ found.append(str(p))
91
+ return found