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.
@@ -0,0 +1,457 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import chess
5
+ import chess.engine
6
+ import chess.pgn
7
+ import chess.polyglot
8
+ import chess.svg
9
+ from PySide6.QtCore import (
10
+ QPointF,
11
+ QRectF,
12
+ Qt,
13
+ Signal,
14
+ )
15
+ from PySide6.QtGui import (
16
+ QColor,
17
+ QFontMetrics,
18
+ QPainter,
19
+ QPen,
20
+ QPolygonF,
21
+ QIcon,
22
+ QPixmap,
23
+ )
24
+ from PySide6.QtWidgets import (
25
+ QFrame,
26
+ QGridLayout,
27
+ QScrollArea,
28
+ QHBoxLayout,
29
+ QLabel,
30
+ QPlainTextEdit,
31
+ QStyledItemDelegate,
32
+ QVBoxLayout,
33
+ QWidget,
34
+ QListWidget,
35
+ QListWidgetItem,
36
+ )
37
+
38
+ from silentengine.review import CATEGORIES
39
+
40
+
41
+ def nav_icon(kind: str, color: str = "#cfcfcf", size: int = 20) -> QIcon:
42
+ """Crisp triangle icons for the move controls (first / prev / next / last / menu)."""
43
+ pm = QPixmap(size, size)
44
+ pm.fill(Qt.transparent)
45
+ p = QPainter(pm)
46
+ p.setRenderHint(QPainter.Antialiasing)
47
+ p.setPen(Qt.NoPen)
48
+ p.setBrush(QColor(color))
49
+ s = float(size)
50
+
51
+ if kind == "prev":
52
+ p.drawPolygon(
53
+ QPolygonF(
54
+ [
55
+ QPointF(0.68 * s, 0.2 * s),
56
+ QPointF(0.68 * s, 0.8 * s),
57
+ QPointF(0.28 * s, 0.5 * s),
58
+ ]
59
+ )
60
+ )
61
+ elif kind == "next":
62
+ p.drawPolygon(
63
+ QPolygonF(
64
+ [
65
+ QPointF(0.32 * s, 0.2 * s),
66
+ QPointF(0.32 * s, 0.8 * s),
67
+ QPointF(0.72 * s, 0.5 * s),
68
+ ]
69
+ )
70
+ )
71
+ elif kind == "first":
72
+ p.drawRect(QRectF(0.2 * s, 0.2 * s, 0.1 * s, 0.6 * s))
73
+ p.drawPolygon(
74
+ QPolygonF(
75
+ [
76
+ QPointF(0.75 * s, 0.2 * s),
77
+ QPointF(0.75 * s, 0.8 * s),
78
+ QPointF(0.35 * s, 0.5 * s),
79
+ ]
80
+ )
81
+ )
82
+ elif kind == "last":
83
+ p.drawPolygon(
84
+ QPolygonF(
85
+ [
86
+ QPointF(0.25 * s, 0.2 * s),
87
+ QPointF(0.25 * s, 0.8 * s),
88
+ QPointF(0.65 * s, 0.5 * s),
89
+ ]
90
+ )
91
+ )
92
+ p.drawRect(QRectF(0.7 * s, 0.2 * s, 0.1 * s, 0.6 * s))
93
+ else: # menu: three bars
94
+ for y in (0.25, 0.46, 0.67):
95
+ p.drawRoundedRect(QRectF(0.2 * s, y * s, 0.6 * s, 0.09 * s), 1, 1)
96
+ p.end()
97
+ return QIcon(pm)
98
+
99
+
100
+ class EvalBar(QWidget):
101
+ def __init__(self) -> None:
102
+ super().__init__()
103
+ self.frac = 0.5
104
+ self.text = "0.0"
105
+ self.flipped = False
106
+
107
+ def set_eval(self, frac: float, text: str) -> None:
108
+ self.frac, self.text = frac, text
109
+ self.update()
110
+
111
+ def set_flipped(self, flipped: bool) -> None:
112
+ self.flipped = flipped
113
+ self.update()
114
+
115
+ def paintEvent(self, _event) -> None:
116
+ p = QPainter(self)
117
+ p.setRenderHint(QPainter.Antialiasing)
118
+ w, h = self.width(), self.height()
119
+ p.fillRect(0, 0, w, h, QColor("#2b2b2b"))
120
+ white_h = h * self.frac
121
+ if self.flipped:
122
+ p.fillRect(QRectF(0, 0, w, white_h), QColor("#f2f2f2"))
123
+ else:
124
+ p.fillRect(QRectF(0, h - white_h, w, white_h), QColor("#f2f2f2"))
125
+ font = p.font()
126
+ font.setBold(True)
127
+ size = 10
128
+ while size > 6: # shrink until the text fits the bar width
129
+ font.setPixelSize(size)
130
+ if QFontMetrics(font).horizontalAdvance(self.text) <= w - 2:
131
+ break
132
+ size -= 1
133
+ p.setFont(font)
134
+ white_side_bottom = not self.flipped
135
+ white_winning = self.frac >= 0.5
136
+ # put the label at the end of the larger side, in a contrasting color
137
+ at_bottom = white_side_bottom == white_winning
138
+ p.setPen(QColor("#222") if white_winning else QColor("#ddd"))
139
+ rect = QRectF(0, h - 20 if at_bottom else 2, w, 18)
140
+ p.drawText(rect, Qt.AlignCenter, self.text)
141
+
142
+
143
+ class PgnEdit(QPlainTextEdit):
144
+ pasted = Signal()
145
+
146
+ def insertFromMimeData(self, source) -> None:
147
+ super().insertFromMimeData(source)
148
+ self.pasted.emit()
149
+
150
+
151
+ class ResultBarDelegate(QStyledItemDelegate):
152
+ """Draws a white / draw / black result bar from (w, d, b) stored in UserRole."""
153
+
154
+ def paint(self, painter, option, index) -> None:
155
+ data = index.data(Qt.UserRole)
156
+ if not data:
157
+ return super().paint(painter, option, index)
158
+ total = sum(data) or 1
159
+ r = option.rect.adjusted(4, 4, -4, -4)
160
+ painter.save()
161
+ x = float(r.x())
162
+ for count, fill, ink in zip(
163
+ data, ("#e8e8e8", "#8a8a8a", "#303030"), ("#222222", "#ffffff", "#ffffff")
164
+ ):
165
+ w = r.width() * count / total
166
+ seg = QRectF(x, r.y(), w, r.height())
167
+ painter.fillRect(seg, QColor(fill))
168
+ if w >= 30:
169
+ painter.setPen(QColor(ink))
170
+ painter.drawText(seg, Qt.AlignCenter, f"{count * 100 / total:.0f}%")
171
+ x += w
172
+ painter.restore()
173
+
174
+
175
+ class TimeGraph(QWidget):
176
+ """Time spent per move: one bar per ply, light for White, grey for Black."""
177
+
178
+ plySelected = Signal(int)
179
+
180
+ def __init__(self) -> None:
181
+ super().__init__()
182
+ self.setFixedHeight(46)
183
+ self.data: list[tuple[float | None, bool]] = [] # (seconds, mover is White)
184
+ self.current: int | None = None
185
+
186
+ def set_data(self, data: list) -> None:
187
+ self.data = data
188
+ self.setVisible(any(t is not None for t, _w in data))
189
+ self.update()
190
+
191
+ def set_current(self, ply: int | None) -> None:
192
+ self.current = ply
193
+ self.update()
194
+
195
+ def paintEvent(self, _event) -> None:
196
+ p = QPainter(self)
197
+ w, h = self.width(), self.height()
198
+ p.fillRect(0, 0, w, h, QColor("#2b2b2b"))
199
+ vals = [t for t, _w in self.data if t is not None]
200
+ if not vals:
201
+ return
202
+ top = max(max(vals), 1.0)
203
+ step = (w - 6) / len(self.data)
204
+ p.setPen(Qt.NoPen)
205
+ for i, (t, white) in enumerate(self.data):
206
+ if t is None:
207
+ continue
208
+ bar = max(
209
+ 1.5, math.sqrt(t / top) * (h - 4)
210
+ ) # sqrt so one long think doesn't flatten the rest
211
+ p.setBrush(QColor("#dcdcdc" if white else "#7a7a7a"))
212
+ p.drawRect(QRectF(3 + i * step, h - bar, max(1.0, step - 1), bar))
213
+ if self.current:
214
+ x = 3 + (self.current - 1) * step + step / 2
215
+ p.setPen(QPen(QColor("#3b82f6"), 2))
216
+ p.drawLine(QPointF(x, 0), QPointF(x, h))
217
+
218
+ def _pick(self, e) -> None:
219
+ if not self.data:
220
+ return
221
+ idx = int((e.position().x() - 3) / max(1, self.width() - 6) * len(self.data))
222
+ self.plySelected.emit(max(1, min(len(self.data), idx + 1)))
223
+
224
+ def mousePressEvent(self, e) -> None:
225
+ self._pick(e)
226
+
227
+ def mouseMoveEvent(self, e) -> None:
228
+ self._pick(e)
229
+
230
+
231
+ class EvalGraph(QWidget):
232
+ plySelected = Signal(int)
233
+
234
+ def __init__(self) -> None:
235
+ super().__init__()
236
+ self.setFixedHeight(84)
237
+ self.fracs: list[float] = []
238
+ self.marks: dict[int, str] = {} # ply -> color
239
+ self.current: int | None = None
240
+
241
+ def set_data(self, fracs: list[float], marks: dict[int, str]) -> None:
242
+ self.fracs, self.marks = fracs, marks
243
+ self.update()
244
+
245
+ def set_current(self, ply: int | None) -> None:
246
+ self.current = ply
247
+ self.update()
248
+
249
+ def _x(self, i: int) -> float:
250
+ n = max(1, len(self.fracs) - 1)
251
+ return 3 + i * (self.width() - 6) / n
252
+
253
+ def paintEvent(self, _event) -> None:
254
+ p = QPainter(self)
255
+ p.setRenderHint(QPainter.Antialiasing)
256
+ w, h = self.width(), self.height()
257
+ p.fillRect(0, 0, w, h, QColor("#2b2b2b"))
258
+ if len(self.fracs) < 2:
259
+ return
260
+ poly = [QPointF(self._x(0), h)]
261
+ poly += [QPointF(self._x(i), h - f * h) for i, f in enumerate(self.fracs)]
262
+ poly.append(QPointF(self._x(len(self.fracs) - 1), h))
263
+ p.setPen(Qt.NoPen)
264
+ p.setBrush(QColor("#dcdcdc"))
265
+ p.drawPolygon(QPolygonF(poly))
266
+ p.setPen(QPen(QColor(120, 120, 120, 180), 1, Qt.DashLine))
267
+ p.drawLine(0, h // 2, w, h // 2)
268
+ for ply, color in self.marks.items():
269
+ p.setPen(Qt.NoPen)
270
+ p.setBrush(QColor(color))
271
+ p.drawEllipse(QPointF(self._x(ply), h - self.fracs[ply] * h), 3.2, 3.2)
272
+ if self.current is not None and 0 <= self.current < len(self.fracs):
273
+ p.setPen(QPen(QColor("#3b82f6"), 2))
274
+ x = self._x(self.current)
275
+ p.drawLine(QPointF(x, 0), QPointF(x, h))
276
+
277
+ def _pick(self, e) -> None:
278
+ if len(self.fracs) < 2:
279
+ return
280
+ n = len(self.fracs) - 1
281
+ idx = round((e.position().x() - 3) / max(1, self.width() - 6) * n)
282
+ self.plySelected.emit(max(0, min(n, idx)))
283
+
284
+ def mousePressEvent(self, e) -> None:
285
+ self._pick(e)
286
+
287
+ def mouseMoveEvent(self, e) -> None:
288
+ self._pick(e)
289
+
290
+
291
+ class ReviewPanel(QWidget):
292
+ """Accuracy boxes, eval graph, move-rating counts and the selected move's details."""
293
+
294
+ plySelected = Signal(int)
295
+
296
+ def __init__(self) -> None:
297
+ super().__init__()
298
+ outer = QVBoxLayout(self)
299
+ outer.setContentsMargins(0, 0, 0, 0)
300
+ self.empty = QLabel(
301
+ "Press Review (R) to analyse the line you're viewing.\n"
302
+ "Accuracy, move ratings and the eval graph appear here."
303
+ )
304
+ self.empty.setAlignment(Qt.AlignCenter)
305
+ self.empty.setWordWrap(True)
306
+ self.empty.setStyleSheet("color:#777;")
307
+
308
+ content = QWidget()
309
+ lay = QVBoxLayout(content)
310
+ lay.setContentsMargins(6, 6, 6, 6)
311
+ lay.setSpacing(8)
312
+
313
+ row = QHBoxLayout()
314
+ box_w, self.acc_w = self._acc_box("#f2f2f2", "#1a1a1a")
315
+ box_b, self.acc_b = self._acc_box("#3a3a3a", "#f2f2f2")
316
+ self.result_lbl = QLabel("")
317
+ self.result_lbl.setAlignment(Qt.AlignCenter)
318
+ self.result_lbl.setStyleSheet("color:#aaa;")
319
+ row.addWidget(box_w, 1)
320
+ row.addWidget(self.result_lbl)
321
+ row.addWidget(box_b, 1)
322
+ lay.addLayout(row)
323
+
324
+ self.graph = EvalGraph()
325
+ self.graph.plySelected.connect(self.plySelected)
326
+ lay.addWidget(self.graph)
327
+
328
+ self.time_graph = TimeGraph()
329
+ self.time_graph.plySelected.connect(self.plySelected)
330
+ lay.addWidget(self.time_graph)
331
+
332
+ grid = QGridLayout()
333
+ grid.setHorizontalSpacing(6)
334
+ grid.setVerticalSpacing(4)
335
+ grid.setColumnMinimumWidth(4, 10)
336
+ self.counts: dict[tuple[str, bool], QLabel] = {}
337
+ for block, cats in enumerate((CATEGORIES[:5], CATEGORIES[5:])):
338
+ base = block * 5
339
+ for col, text in ((2, "W"), (3, "B")):
340
+ h = QLabel(text)
341
+ h.setAlignment(Qt.AlignCenter)
342
+ h.setStyleSheet("color:#777; font-size:11px;")
343
+ grid.addWidget(h, 0, base + col)
344
+ for r, (label, badge, color) in enumerate(cats, start=1):
345
+ b = QLabel(badge)
346
+ b.setFixedSize(24, 18)
347
+ b.setAlignment(Qt.AlignCenter)
348
+ b.setStyleSheet(
349
+ f"background:{color}; color:#fff; border-radius:9px; font-weight:700; font-size:10px;"
350
+ )
351
+ grid.addWidget(b, r, base)
352
+ grid.addWidget(QLabel(label), r, base + 1)
353
+ for col, color_side in ((2, chess.WHITE), (3, chess.BLACK)):
354
+ c = QLabel("0")
355
+ c.setAlignment(Qt.AlignCenter)
356
+ self.counts[(label, color_side)] = c
357
+ grid.addWidget(c, r, base + col)
358
+ grid.setColumnStretch(base + 1, 1)
359
+ lay.addLayout(grid)
360
+
361
+ self.info = QLabel()
362
+ self.info.setTextFormat(Qt.RichText)
363
+ self.info.setWordWrap(True)
364
+ lay.addWidget(self.info)
365
+ self.moments_hdr = QLabel()
366
+ self.moments_hdr.setStyleSheet("color:#888; font-size:11px;")
367
+ lay.addWidget(self.moments_hdr)
368
+ self.moments = QListWidget()
369
+ self.moments.setMaximumHeight(150)
370
+ self.moments.setStyleSheet(
371
+ "QListWidget::item { padding:3px 4px; }"
372
+ "QListWidget::item:selected { background:#2e4a7a; }"
373
+ )
374
+ self.moments.itemClicked.connect(
375
+ lambda it: self.plySelected.emit(it.data(Qt.UserRole))
376
+ )
377
+ lay.addWidget(self.moments)
378
+ lay.addStretch(1)
379
+
380
+ self.scroll = QScrollArea()
381
+ self.scroll.setWidgetResizable(True)
382
+ self.scroll.setFrameShape(QFrame.NoFrame)
383
+ self.scroll.setWidget(content)
384
+ outer.addWidget(self.empty, 1)
385
+ outer.addWidget(self.scroll, 1)
386
+ self.clear()
387
+
388
+ @staticmethod
389
+ def _acc_box(bg: str, fg: str):
390
+ frame = QFrame()
391
+ frame.setStyleSheet(
392
+ f"QFrame {{ background:{bg}; border-radius:4px; }} QLabel {{ background:transparent; color:{fg}; }}"
393
+ )
394
+ v = QVBoxLayout(frame)
395
+ v.setContentsMargins(6, 4, 6, 4)
396
+ v.setSpacing(0)
397
+ num = QLabel("–")
398
+ num.setAlignment(Qt.AlignCenter)
399
+ num.setStyleSheet("font-size:22px; font-weight:700;")
400
+ sub = QLabel("Accuracy")
401
+ sub.setAlignment(Qt.AlignCenter)
402
+ sub.setStyleSheet("font-size:10px;")
403
+ v.addWidget(num)
404
+ v.addWidget(sub)
405
+ return frame, num
406
+
407
+ def clear(self) -> None:
408
+ self.empty.show()
409
+ self.scroll.hide()
410
+ self.info.setText("")
411
+
412
+ def populate(
413
+ self,
414
+ acc_w: str,
415
+ acc_b: str,
416
+ result: str,
417
+ counts: dict,
418
+ mark_colors: dict,
419
+ fracs: list,
420
+ times: list | None = None,
421
+ moments: list | None = None,
422
+ ) -> None:
423
+ self.acc_w.setText(acc_w)
424
+ self.acc_b.setText(acc_b)
425
+ self.result_lbl.setText(result)
426
+ for (label, color), widget in self.counts.items():
427
+ widget.setText(str(counts[color].get(label, 0)))
428
+ self.graph.set_data(fracs, mark_colors)
429
+ self.time_graph.set_data(times or [])
430
+ moments = moments or []
431
+ self.moments_hdr.setText(f"Critical moments ({len(moments)})")
432
+ self.moments.clear()
433
+ for ply, text, color in moments:
434
+ item = QListWidgetItem(text)
435
+ item.setData(Qt.UserRole, ply)
436
+ item.setForeground(QColor(color))
437
+ self.moments.addItem(item)
438
+ self.moments.setVisible(bool(moments))
439
+ self.empty.hide()
440
+ self.scroll.show()
441
+
442
+ def set_current(self, ply: int | None) -> None:
443
+ self.graph.set_current(ply)
444
+ self.time_graph.set_current(ply)
445
+ self.moments.blockSignals(
446
+ True
447
+ ) # keeps the list highlight in sync with N/P and the graphs
448
+ self.moments.clearSelection()
449
+ for r in range(self.moments.count()):
450
+ it = self.moments.item(r)
451
+ if it.data(Qt.UserRole) == ply:
452
+ self.moments.setCurrentItem(it)
453
+ break
454
+ self.moments.blockSignals(False)
455
+
456
+ def set_info(self, html: str) -> None:
457
+ self.info.setText(html)