-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoverlay.py
More file actions
373 lines (305 loc) · 13.2 KB
/
Copy pathoverlay.py
File metadata and controls
373 lines (305 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
"""
overlay.py — PyQt6 always-on-top transparent overlay.
The overlay never steals focus from the active game window.
Public API
----------
GameOverlay(parent=None) — QWidget subclass
.show_loading()
.show_result(result: dict)
.show_error(message: str)
.toggle_minimize()
"""
from __future__ import annotations
from typing import Any, Optional
from PyQt6.QtCore import Qt, QPoint, pyqtSignal, pyqtSlot
from PyQt6.QtGui import QColor, QFont, QPainter, QPainterPath, QFontMetrics
from PyQt6.QtWidgets import (
QApplication,
QHBoxLayout,
QLabel,
QPushButton,
QSizePolicy,
QVBoxLayout,
QWidget,
)
from config import get_config
# ---------------------------------------------------------------------------
# Colour palette
# ---------------------------------------------------------------------------
BG_COLOR = QColor(20, 20, 20, 210)
BORDER_COLOR = QColor(60, 60, 60, 200)
ACCENT_COLOR = QColor(0, 200, 255) # cyan — game detected header
MOVE_COLOR = QColor(255, 215, 0) # gold — primary recommendation
REASONING_COLOR = QColor(180, 180, 180)
ERROR_COLOR = QColor(255, 80, 80)
LOADING_COLOR = QColor(140, 140, 140)
BADGE_BG = QColor(40, 40, 40, 230)
CORNER_RADIUS = 12
# ---------------------------------------------------------------------------
# Pill-shaped badge for the game label
# ---------------------------------------------------------------------------
class _Badge(QWidget):
def __init__(self, text: str, color: QColor, parent: Optional[QWidget] = None):
super().__init__(parent)
self._text = text
self._color = color
self._font = QFont("Segoe UI", 9, QFont.Weight.Bold)
fm = QFontMetrics(self._font)
self.setFixedSize(fm.horizontalAdvance(text) + 20, fm.height() + 8)
def setText(self, text: str) -> None:
self._text = text
self.update()
def setColor(self, color: QColor) -> None:
self._color = color
self.update()
def paintEvent(self, _event) -> None: # type: ignore[override]
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
path = QPainterPath()
path.addRoundedRect(0, 0, self.width(), self.height(), self.height() / 2, self.height() / 2)
p.fillPath(path, self._color)
p.setPen(QColor(0, 0, 0))
p.setFont(self._font)
p.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, self._text)
# ---------------------------------------------------------------------------
# Main overlay widget
# ---------------------------------------------------------------------------
class GameOverlay(QWidget):
"""Transparent, always-on-top floating overlay."""
# Emitted by worker threads — must be connected to slots
result_ready: pyqtSignal = pyqtSignal(dict)
error_ready: pyqtSignal = pyqtSignal(str)
loading_signal: pyqtSignal = pyqtSignal()
def __init__(self, parent: Optional[QWidget] = None) -> None:
super().__init__(parent)
cfg = get_config()
self._minimized = False
self._drag_pos: Optional[QPoint] = None
# Window flags: always on top, frameless, never steals focus
self.setWindowFlags(
Qt.WindowType.FramelessWindowHint
| Qt.WindowType.WindowStaysOnTopHint
| Qt.WindowType.Tool # excluded from taskbar
)
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
# CRITICAL: do not steal focus
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
self.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self.setGeometry(cfg.overlay_x, cfg.overlay_y, cfg.overlay_width, cfg.overlay_height)
self.setMinimumWidth(280)
self._build_ui()
# Connect cross-thread signals
self.result_ready.connect(self._on_result)
self.error_ready.connect(self._on_error)
self.loading_signal.connect(self._on_loading)
# ------------------------------------------------------------------
# UI construction
# ------------------------------------------------------------------
def _build_ui(self) -> None:
outer = QVBoxLayout(self)
outer.setContentsMargins(12, 10, 12, 12)
outer.setSpacing(6)
# --- Title bar row ---
title_row = QHBoxLayout()
title_row.setSpacing(6)
self._badge = _Badge("GAMEADVISOR", ACCENT_COLOR)
title_row.addWidget(self._badge)
self._game_label = QLabel("—")
self._game_label.setStyleSheet("color: #aaaaaa; font-size: 10px; font-family: 'Segoe UI';")
title_row.addWidget(self._game_label)
title_row.addStretch()
self._toggle_btn = QPushButton("—")
self._toggle_btn.setFixedSize(20, 20)
self._toggle_btn.setStyleSheet(
"QPushButton { color: #888; background: transparent; border: none; font-size: 14px; }"
"QPushButton:hover { color: #fff; }"
)
self._toggle_btn.setFocusPolicy(Qt.FocusPolicy.NoFocus)
self._toggle_btn.clicked.connect(self.toggle_minimize)
title_row.addWidget(self._toggle_btn)
outer.addLayout(title_row)
# --- Content area (hidden when minimised) ---
self._content = QWidget()
content_layout = QVBoxLayout(self._content)
content_layout.setContentsMargins(0, 4, 0, 0)
content_layout.setSpacing(6)
# Primary recommendation label
self._move_label = QLabel("Press F9 to analyse")
self._move_label.setWordWrap(True)
self._move_label.setStyleSheet(
"color: #FFD700; font-size: 18px; font-weight: bold; font-family: 'Segoe UI';"
)
self._move_label.setAlignment(Qt.AlignmentFlag.AlignLeft)
content_layout.addWidget(self._move_label)
# Reasoning / detail label
self._reason_label = QLabel("")
self._reason_label.setWordWrap(True)
self._reason_label.setStyleSheet(
"color: #b4b4b4; font-size: 11px; font-family: 'Segoe UI'; line-height: 1.4;"
)
self._reason_label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
content_layout.addWidget(self._reason_label)
# Confidence bar (simple text for now)
self._confidence_label = QLabel("")
self._confidence_label.setStyleSheet(
"color: #666; font-size: 10px; font-family: 'Segoe UI Mono';"
)
content_layout.addWidget(self._confidence_label)
outer.addWidget(self._content)
self.setLayout(outer)
# ------------------------------------------------------------------
# Custom painting — rounded dark card
# ------------------------------------------------------------------
def paintEvent(self, _event) -> None: # type: ignore[override]
p = QPainter(self)
p.setRenderHint(QPainter.RenderHint.Antialiasing)
path = QPainterPath()
path.addRoundedRect(0, 0, self.width(), self.height(), CORNER_RADIUS, CORNER_RADIUS)
p.fillPath(path, BG_COLOR)
p.setPen(BORDER_COLOR)
p.drawPath(path)
# ------------------------------------------------------------------
# Dragging
# ------------------------------------------------------------------
def mousePressEvent(self, event) -> None: # type: ignore[override]
if event.button() == Qt.MouseButton.LeftButton:
self._drag_pos = event.globalPosition().toPoint() - self.frameGeometry().topLeft()
def mouseMoveEvent(self, event) -> None: # type: ignore[override]
if self._drag_pos and event.buttons() & Qt.MouseButton.LeftButton:
self.move(event.globalPosition().toPoint() - self._drag_pos)
def mouseReleaseEvent(self, event) -> None: # type: ignore[override]
if event.button() == Qt.MouseButton.LeftButton:
self._drag_pos = None
# Persist new position
cfg = get_config()
pos = self.pos()
cfg.overlay_x = pos.x()
cfg.overlay_y = pos.y()
cfg.save()
# ------------------------------------------------------------------
# Public slots (safe to call from worker threads via signals)
# ------------------------------------------------------------------
@pyqtSlot()
def show_loading(self) -> None:
self.loading_signal.emit()
@pyqtSlot(dict)
def show_result(self, result: dict) -> None:
self.result_ready.emit(result)
@pyqtSlot(str)
def show_error(self, message: str) -> None:
self.error_ready.emit(message)
def toggle_minimize(self) -> None:
self._minimized = not self._minimized
self._content.setVisible(not self._minimized)
self._toggle_btn.setText("+" if self._minimized else "—")
cfg = get_config()
# Shrink/expand height
if self._minimized:
self.setFixedHeight(38)
else:
self.setFixedHeight(cfg.overlay_height)
self.setMinimumHeight(0)
self.setMaximumHeight(16777215)
self.adjustSize()
# ------------------------------------------------------------------
# Internal slots (main thread)
# ------------------------------------------------------------------
@pyqtSlot()
def _on_loading(self) -> None:
self._game_label.setText("analysing…")
self._move_label.setStyleSheet(
"color: #888888; font-size: 16px; font-weight: normal; font-family: 'Segoe UI';"
)
self._move_label.setText("Capturing & analysing…")
self._reason_label.setText("")
self._confidence_label.setText("")
if self._minimized:
self.toggle_minimize()
@pyqtSlot(dict)
def _on_result(self, result: dict) -> None:
"""
Expected keys (all optional with fallbacks):
game, recommendation, reasoning, confidence, moves (list), warning
"""
game = result.get("game", "unknown").capitalize()
self._game_label.setText(game)
# Badge colour by game
color_map = {
"Chess": QColor(100, 200, 100),
"Poker": QColor(200, 120, 50),
"Unknown": QColor(120, 120, 120),
}
self._badge.setColor(color_map.get(game, ACCENT_COLOR))
recommendation = result.get("recommendation", "")
# Chess: first of top moves
if not recommendation and result.get("moves"):
first = result["moves"][0]
recommendation = first.get("move", "")
self._move_label.setStyleSheet(
"color: #FFD700; font-size: 18px; font-weight: bold; font-family: 'Segoe UI';"
)
self._move_label.setText(recommendation or "No recommendation")
reasoning = result.get("reasoning", "")
# Chess: attach move list details
if result.get("moves"):
parts = []
for m in result["moves"][:3]:
label = m.get("score_label") or (
f"{m['score']:+d} cp" if isinstance(m.get("score"), int) else ""
)
parts.append(f"{m['move']} {label} — {m.get('reasoning', '')}")
reasoning = "\n".join(parts) if not reasoning else reasoning + "\n\n" + "\n".join(parts)
self._reason_label.setText(reasoning)
conf = result.get("confidence")
if conf is not None:
filled = int(round(float(conf) * 10))
bar = "█" * filled + "░" * (10 - filled)
self._confidence_label.setText(f"Confidence {bar} {int(float(conf)*100)}%")
else:
self._confidence_label.setText("")
warning = result.get("warning", "")
if warning:
self._reason_label.setText(
(self._reason_label.text() + f"\n⚠ {warning}").strip()
)
if self._minimized:
self.toggle_minimize()
self.adjustSize()
@pyqtSlot(str)
def _on_error(self, message: str) -> None:
self._game_label.setText("error")
self._badge.setColor(ERROR_COLOR)
self._move_label.setStyleSheet(
"color: #FF5050; font-size: 14px; font-weight: bold; font-family: 'Segoe UI';"
)
self._move_label.setText(message)
self._reason_label.setText("")
self._confidence_label.setText("")
if self._minimized:
self.toggle_minimize()
self.adjustSize()
# ---------------------------------------------------------------------------
# Standalone test
# ---------------------------------------------------------------------------
if __name__ == "__main__":
import sys, time, threading
app = QApplication(sys.argv)
ov = GameOverlay()
ov.show()
def _demo():
time.sleep(1)
ov.show_loading()
time.sleep(2)
ov.show_result({
"game": "chess",
"moves": [
{"move": "e4", "score": 30, "score_label": "Best", "reasoning": "Controls centre"},
{"move": "Nf3", "score": 15, "score_label": "Good", "reasoning": "Develops knight"},
{"move": "d4", "score": 10, "score_label": "Acceptable", "reasoning": "Solid opening"},
],
"confidence": 0.87,
})
time.sleep(4)
ov.show_error("Analysis timeout — try again")
threading.Thread(target=_demo, daemon=True).start()
sys.exit(app.exec())