prism-code-workspace 1.0.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.
- prism_code_workspace-1.0.0.dist-info/METADATA +272 -0
- prism_code_workspace-1.0.0.dist-info/RECORD +30 -0
- prism_code_workspace-1.0.0.dist-info/WHEEL +4 -0
- prism_code_workspace-1.0.0.dist-info/entry_points.txt +3 -0
- prism_code_workspace-1.0.0.dist-info/licenses/LICENSE +21 -0
- python_app/__init__.py +3 -0
- python_app/ai.py +225 -0
- python_app/analysis.py +953 -0
- python_app/compare.py +685 -0
- python_app/compare_engine.py +284 -0
- python_app/compiled_analysis.py +727 -0
- python_app/desktop.py +181 -0
- python_app/function_pov/__init__.py +16 -0
- python_app/function_pov/analyzer.py +464 -0
- python_app/function_pov/graph.py +50 -0
- python_app/function_pov/models.py +53 -0
- python_app/function_pov/pov/__init__.py +17 -0
- python_app/function_pov/pov/engine.py +1630 -0
- python_app/function_pov/pov/exercises.py +1263 -0
- python_app/function_pov_ui.py +1749 -0
- python_app/i18n.py +570 -0
- python_app/installer.nsi +70 -0
- python_app/installer_runtime.nsi +70 -0
- python_app/js_analysis.py +709 -0
- python_app/launch.py +6 -0
- python_app/launch_native.py +14 -0
- python_app/metrics_advisor.py +79 -0
- python_app/native_app.py +1709 -0
- python_app/requirements.txt +7 -0
- python_app/server.py +453 -0
python_app/native_app.py
ADDED
|
@@ -0,0 +1,1709 @@
|
|
|
1
|
+
"""Prism Native — a pure-Python desktop code analysis workspace.
|
|
2
|
+
|
|
3
|
+
This is the Python-first edition. The UI, editor, four analysis views, guide,
|
|
4
|
+
trace playback and file handling are implemented with PySide6. There is no
|
|
5
|
+
HTML, CSS or JavaScript application code.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import html
|
|
11
|
+
import math
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from PySide6.QtCore import (
|
|
16
|
+
QEasingCurve, QParallelAnimationGroup, QPauseAnimation, QPoint,
|
|
17
|
+
QPropertyAnimation, QRegularExpression, QSettings, Qt, QThread, QTimer,
|
|
18
|
+
QVariantAnimation, Signal,
|
|
19
|
+
)
|
|
20
|
+
from PySide6.QtGui import (
|
|
21
|
+
QAction, QColor, QFont, QFontDatabase, QIcon, QPainter, QPen, QRadialGradient,
|
|
22
|
+
QResizeEvent, QShowEvent, QSyntaxHighlighter, QTextCharFormat,
|
|
23
|
+
)
|
|
24
|
+
from PySide6.QtWidgets import (
|
|
25
|
+
QApplication, QCheckBox, QComboBox, QDialog, QDialogButtonBox, QFileDialog,
|
|
26
|
+
QFormLayout, QFrame, QGraphicsOpacityEffect, QGraphicsScene, QGraphicsView,
|
|
27
|
+
QHBoxLayout, QLabel, QLineEdit, QListWidget, QListWidgetItem, QMainWindow,
|
|
28
|
+
QMenu, QMessageBox, QPlainTextEdit, QPushButton, QSplitter, QStackedWidget,
|
|
29
|
+
QStatusBar, QTabWidget, QTableWidget, QTableWidgetItem, QTextBrowser,
|
|
30
|
+
QTreeWidget, QTreeWidgetItem, QVBoxLayout, QWidget,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
try:
|
|
34
|
+
from python_app.ai import AIError, AISettings, PROVIDERS, complete, test_connection
|
|
35
|
+
except ImportError: # direct script execution
|
|
36
|
+
from ai import AIError, AISettings, PROVIDERS, complete, test_connection
|
|
37
|
+
|
|
38
|
+
try:
|
|
39
|
+
from python_app.analysis import analyze_python
|
|
40
|
+
from python_app.js_analysis import analyze_javascript
|
|
41
|
+
from python_app.compiled_analysis import analyze_compiled
|
|
42
|
+
from python_app.compare import ComparePage
|
|
43
|
+
from python_app.function_pov_ui import FunctionPOVPage
|
|
44
|
+
from python_app.i18n import LANGUAGES as UI_LANGUAGES, set_language as _apply_ui_language, tr
|
|
45
|
+
except ImportError: # running the file directly
|
|
46
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
47
|
+
from python_app.analysis import analyze_python
|
|
48
|
+
from python_app.js_analysis import analyze_javascript
|
|
49
|
+
from python_app.compiled_analysis import analyze_compiled
|
|
50
|
+
from python_app.compare import ComparePage
|
|
51
|
+
from python_app.function_pov_ui import FunctionPOVPage
|
|
52
|
+
from python_app.i18n import LANGUAGES as UI_LANGUAGES, set_language as _apply_ui_language, tr
|
|
53
|
+
|
|
54
|
+
APP_NAME = "Prism"
|
|
55
|
+
APP_TAGLINE = "Code, made clear."
|
|
56
|
+
LANGUAGE_LABELS = [
|
|
57
|
+
("python", "Python"), ("javascript", "JavaScript"), ("typescript", "TypeScript"),
|
|
58
|
+
("java", "Java"), ("cpp", "C++"), ("c", "C"),
|
|
59
|
+
]
|
|
60
|
+
FILE_EXTENSIONS = {
|
|
61
|
+
"python": ".py", "javascript": ".js", "typescript": ".ts",
|
|
62
|
+
"java": ".java", "cpp": ".cpp", "c": ".c",
|
|
63
|
+
}
|
|
64
|
+
LANGUAGE_NAMES = dict(LANGUAGE_LABELS)
|
|
65
|
+
MAX_SOURCE = 60_000
|
|
66
|
+
CASES = {
|
|
67
|
+
"Loop and total": """prices = [12, 8, 25]
|
|
68
|
+
total = 0
|
|
69
|
+
for price in prices:
|
|
70
|
+
if price >= 10:
|
|
71
|
+
total += price
|
|
72
|
+
print(total)
|
|
73
|
+
""",
|
|
74
|
+
"Discount helper": """def apply_discount(price, is_member):
|
|
75
|
+
if is_member:
|
|
76
|
+
return price * 0.9
|
|
77
|
+
return price
|
|
78
|
+
|
|
79
|
+
prices = [12, 8, 25]
|
|
80
|
+
total = 0
|
|
81
|
+
for price in prices:
|
|
82
|
+
total += apply_discount(price, True)
|
|
83
|
+
print("Total:", total)
|
|
84
|
+
""",
|
|
85
|
+
"Scores and counters": """scores = [72, 88, 91, 65]
|
|
86
|
+
passed = 0
|
|
87
|
+
for score in scores:
|
|
88
|
+
if score >= 70:
|
|
89
|
+
passed += 1
|
|
90
|
+
print(f"Passed: {passed}")
|
|
91
|
+
""",
|
|
92
|
+
}
|
|
93
|
+
JS_CASES = {
|
|
94
|
+
"Loop and total": """const prices = [12, 8, 25];
|
|
95
|
+
let total = 0;
|
|
96
|
+
for (const price of prices) {
|
|
97
|
+
if (price >= 10) {
|
|
98
|
+
total += price;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
console.log(total);
|
|
102
|
+
""",
|
|
103
|
+
"Discount helper": """function applyDiscount(price, isMember) {
|
|
104
|
+
if (isMember) {
|
|
105
|
+
return price * 0.9;
|
|
106
|
+
}
|
|
107
|
+
return price;
|
|
108
|
+
}
|
|
109
|
+
const total = applyDiscount(40, true);
|
|
110
|
+
console.log("Total:", total);
|
|
111
|
+
""",
|
|
112
|
+
"Scores and counters": """const scores = [72, 88, 91, 65];
|
|
113
|
+
let passed = 0;
|
|
114
|
+
for (const score of scores) {
|
|
115
|
+
if (score >= 70) {
|
|
116
|
+
passed += 1;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
console.log("Passed:", passed);
|
|
120
|
+
""",
|
|
121
|
+
}
|
|
122
|
+
COMPILED_CASES = {
|
|
123
|
+
"java": {
|
|
124
|
+
"Loop and total": """public class Main {
|
|
125
|
+
public static void main(String[] args) {
|
|
126
|
+
int[] prices = {12, 8, 25};
|
|
127
|
+
int total = 0;
|
|
128
|
+
for (int price : prices) {
|
|
129
|
+
if (price >= 10) {
|
|
130
|
+
total += price;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
System.out.println(total);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
""",
|
|
137
|
+
},
|
|
138
|
+
"cpp": {
|
|
139
|
+
"Loop and total": """#include <iostream>
|
|
140
|
+
using namespace std;
|
|
141
|
+
|
|
142
|
+
int main() {
|
|
143
|
+
int prices[] = {12, 8, 25};
|
|
144
|
+
int total = 0;
|
|
145
|
+
for (int price : prices) {
|
|
146
|
+
if (price >= 10) {
|
|
147
|
+
total += price;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
cout << total << endl;
|
|
151
|
+
return 0;
|
|
152
|
+
}
|
|
153
|
+
""",
|
|
154
|
+
},
|
|
155
|
+
"c": {
|
|
156
|
+
"Loop and total": """#include <stdio.h>
|
|
157
|
+
|
|
158
|
+
int main() {
|
|
159
|
+
int prices[] = {12, 8, 25};
|
|
160
|
+
int total = 0;
|
|
161
|
+
for (int i = 0; i < 3; i++) {
|
|
162
|
+
if (prices[i] >= 10) {
|
|
163
|
+
total += prices[i];
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
printf("%d\\n", total);
|
|
167
|
+
return 0;
|
|
168
|
+
}
|
|
169
|
+
""",
|
|
170
|
+
},
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
STYLE = """
|
|
174
|
+
* { font-family: "Segoe UI", "Noto Sans", sans-serif; font-size: 10pt; }
|
|
175
|
+
QWidget { background: #1b1d21; color: #e5e8ec; }
|
|
176
|
+
QLabel { background: transparent; }
|
|
177
|
+
QFrame#TopBar { background: #202227; border-bottom: 1px solid #34383f; }
|
|
178
|
+
QFrame#Card { background: #23262b; border: 1px solid #363a41; border-radius: 10px; }
|
|
179
|
+
QLabel#Brand { font-size: 15pt; font-weight: 700; color: #ffffff; }
|
|
180
|
+
QLabel#Muted { color: #9aa2ad; }
|
|
181
|
+
QLabel#Tiny { color: #8d96a1; font-size: 9pt; }
|
|
182
|
+
QLabel#Title { font-size: 29pt; font-weight: 700; color: #f4f5f6; }
|
|
183
|
+
QLabel#Subtitle { color: #aab2bd; font-size: 11pt; }
|
|
184
|
+
QLabel#CardTitle { font-size: 13pt; font-weight: 600; color: #f2f3f5; }
|
|
185
|
+
QLabel#Kicker { color: #ff8d6f; font-size: 8pt; font-weight: 700; letter-spacing: 1px; }
|
|
186
|
+
QLabel#Feature { color: #c4cad2; padding: 5px 0; }
|
|
187
|
+
QLabel#Step { color: #ff8d6f; font-weight: 700; font-size: 9pt; }
|
|
188
|
+
QPushButton {
|
|
189
|
+
background: #2b2f36; border: 1px solid #41464f; border-radius: 6px;
|
|
190
|
+
color: #e9ecf0; padding: 7px 14px;
|
|
191
|
+
}
|
|
192
|
+
QPushButton:hover { background: #343941; border-color: #59606b; }
|
|
193
|
+
QPushButton:pressed { background: #262a31; }
|
|
194
|
+
QPushButton#Primary {
|
|
195
|
+
background: #ff7852; border-color: #ff7852; color: #201310; font-weight: 600;
|
|
196
|
+
}
|
|
197
|
+
QPushButton#Primary:hover { background: #ff8d6c; }
|
|
198
|
+
QPushButton#Ghost { background: transparent; border-color: transparent; color: #b8c0ca; }
|
|
199
|
+
QPushButton#Ghost:hover { background: #2b2f36; color: #fff; }
|
|
200
|
+
QPushButton#Chip { background: #252930; border-color: #353a42; color: #b8c0ca; padding: 6px 10px; }
|
|
201
|
+
QPushButton#Chip:hover { border-color: #ff7852; color: #fff; }
|
|
202
|
+
QPlainTextEdit {
|
|
203
|
+
background: #17191d; border: 1px solid #34383f; border-radius: 7px;
|
|
204
|
+
color: #dfe4ea; selection-background-color: #5a3529;
|
|
205
|
+
font-family: "Cascadia Code", "Consolas", monospace; font-size: 10.5pt;
|
|
206
|
+
}
|
|
207
|
+
QPlainTextEdit#ReadOnly { background: #181a1e; }
|
|
208
|
+
QTextBrowser { background: #1c1f24; border: 1px solid #34383f; border-radius: 7px; padding: 7px; }
|
|
209
|
+
QTabWidget::pane { border: 1px solid #34383f; border-radius: 7px; background: #1c1f24; top: -1px; }
|
|
210
|
+
QTabBar::tab {
|
|
211
|
+
background: transparent; color: #98a1ac; padding: 8px 14px;
|
|
212
|
+
border-bottom: 2px solid transparent;
|
|
213
|
+
}
|
|
214
|
+
QTabBar::tab:selected { color: #fff; border-bottom-color: #ff7852; }
|
|
215
|
+
QTabBar::tab:hover { color: #e8ecf1; }
|
|
216
|
+
QTreeWidget, QTableWidget, QListWidget {
|
|
217
|
+
background: #1c1f24; border: 1px solid #34383f; border-radius: 7px;
|
|
218
|
+
alternate-background-color: #202329; color: #dfe4ea;
|
|
219
|
+
}
|
|
220
|
+
QTreeWidget::item, QListWidget::item { padding: 5px; }
|
|
221
|
+
QTreeWidget::item:selected, QListWidget::item:selected { background: #493027; color: #fff; }
|
|
222
|
+
QHeaderView::section { background: #24272d; color: #9ea7b2; border: 0; padding: 6px; }
|
|
223
|
+
QScrollBar:vertical { background: #1b1d21; width: 10px; }
|
|
224
|
+
QScrollBar::handle:vertical { background: #424750; border-radius: 5px; min-height: 24px; }
|
|
225
|
+
QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { height: 0; }
|
|
226
|
+
QSplitter::handle { background: #2b2e34; width: 2px; }
|
|
227
|
+
QStatusBar { background: #202227; color: #98a1ac; border-top: 1px solid #34383f; }
|
|
228
|
+
QMenuBar { background: #202227; color: #dfe4ea; }
|
|
229
|
+
QMenuBar::item:selected { background: #343941; }
|
|
230
|
+
QMenu { background: #25282e; border: 1px solid #3b4048; color: #e7eaee; }
|
|
231
|
+
QMenu::item:selected { background: #493027; }
|
|
232
|
+
QMessageBox { background: #23262b; }
|
|
233
|
+
"""
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def fade_in(widget: QWidget, duration: int = 220) -> None:
|
|
237
|
+
"""Fade a widget without changing its layout or visibility."""
|
|
238
|
+
effect = QGraphicsOpacityEffect(widget)
|
|
239
|
+
widget.setGraphicsEffect(effect)
|
|
240
|
+
animation = QPropertyAnimation(effect, b"opacity", widget)
|
|
241
|
+
animation.setDuration(duration)
|
|
242
|
+
animation.setStartValue(0.0)
|
|
243
|
+
animation.setEndValue(1.0)
|
|
244
|
+
animation.setEasingCurve(QEasingCurve.Type.OutCubic)
|
|
245
|
+
def cleanup() -> None:
|
|
246
|
+
if widget.graphicsEffect() is effect:
|
|
247
|
+
widget.setGraphicsEffect(None)
|
|
248
|
+
animation.finished.connect(cleanup)
|
|
249
|
+
widget._prism_fade_animation = animation
|
|
250
|
+
animation.start()
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
class PreviewArt(QWidget):
|
|
254
|
+
"""Small living illustration for the welcome page."""
|
|
255
|
+
|
|
256
|
+
def __init__(self, parent=None):
|
|
257
|
+
super().__init__(parent)
|
|
258
|
+
self.setFixedSize(360, 166)
|
|
259
|
+
self.phase = 0.0
|
|
260
|
+
self.timer = QTimer(self)
|
|
261
|
+
self.timer.setInterval(45)
|
|
262
|
+
self.timer.timeout.connect(self._tick)
|
|
263
|
+
self.timer.start()
|
|
264
|
+
|
|
265
|
+
def _tick(self) -> None:
|
|
266
|
+
self.phase = (self.phase + 0.045) % 6.283
|
|
267
|
+
self.update()
|
|
268
|
+
|
|
269
|
+
def paintEvent(self, event) -> None:
|
|
270
|
+
painter = QPainter(self)
|
|
271
|
+
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
|
272
|
+
painter.setPen(QPen(QColor("#363b43"), 1))
|
|
273
|
+
painter.setBrush(QColor("#1f2227"))
|
|
274
|
+
painter.drawRoundedRect(self.rect().adjusted(1, 1, -1, -1), 10, 10)
|
|
275
|
+
glow = QRadialGradient(300, 20, 170)
|
|
276
|
+
glow.setColorAt(0.0, QColor(255, 120, 82, 42))
|
|
277
|
+
glow.setColorAt(1.0, QColor(255, 120, 82, 0))
|
|
278
|
+
painter.setPen(Qt.PenStyle.NoPen)
|
|
279
|
+
painter.setBrush(glow)
|
|
280
|
+
painter.drawRoundedRect(self.rect().adjusted(1, 1, -1, -1), 10, 10)
|
|
281
|
+
|
|
282
|
+
painter.setPen(QColor("#8d96a1"))
|
|
283
|
+
painter.setFont(QFont("Segoe UI", 7, QFont.Weight.DemiBold))
|
|
284
|
+
painter.drawText(18, 22, "LIVE STRUCTURE")
|
|
285
|
+
|
|
286
|
+
nodes = [
|
|
287
|
+
("FLOW", 30, 54, "#ff8d6f"),
|
|
288
|
+
("TREE", 180, 40, "#c49a63"),
|
|
289
|
+
("TRACE", 232, 104, "#6ca7c9"),
|
|
290
|
+
("DATA", 64, 108, "#a9c68c"),
|
|
291
|
+
]
|
|
292
|
+
for i in range(len(nodes) - 1):
|
|
293
|
+
x1, y1 = nodes[i][1] + 42, nodes[i][2] + 15
|
|
294
|
+
x2, y2 = nodes[i + 1][1] + 42, nodes[i + 1][2] + 15
|
|
295
|
+
painter.setPen(QPen(QColor(255, 120, 82, 55), 1))
|
|
296
|
+
painter.drawLine(x1, y1, x2, y2)
|
|
297
|
+
for index, (label, x, y, color) in enumerate(nodes):
|
|
298
|
+
float_y = int(3 * math.sin(self.phase + index * 1.7))
|
|
299
|
+
painter.setPen(QPen(QColor(color), 1))
|
|
300
|
+
painter.setBrush(QColor("#20242a"))
|
|
301
|
+
painter.drawRoundedRect(x, y + float_y, 86, 30, 5, 5)
|
|
302
|
+
painter.setPen(QColor(color))
|
|
303
|
+
painter.setFont(QFont("Segoe UI", 7, QFont.Weight.DemiBold))
|
|
304
|
+
painter.drawText(x + 10, y + 19 + float_y, label)
|
|
305
|
+
painter.setBrush(QColor(color))
|
|
306
|
+
painter.setPen(Qt.PenStyle.NoPen)
|
|
307
|
+
painter.drawEllipse(x + 69, y + 12 + float_y, 5, 5)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
class CodeHighlighter(QSyntaxHighlighter):
|
|
311
|
+
def __init__(self, document, language: str = "python"):
|
|
312
|
+
super().__init__(document)
|
|
313
|
+
self.language = language
|
|
314
|
+
self.rules: list[tuple[QRegularExpression, QTextCharFormat]] = []
|
|
315
|
+
keyword = QTextCharFormat()
|
|
316
|
+
keyword.setForeground(QColor("#ff9a7d"))
|
|
317
|
+
keyword.setFontWeight(QFont.Weight.DemiBold)
|
|
318
|
+
python_words = (
|
|
319
|
+
"False", "None", "True", "and", "as", "assert", "async", "await",
|
|
320
|
+
"break", "class", "continue", "def", "del", "elif", "else", "except",
|
|
321
|
+
"finally", "for", "from", "global", "if", "import", "in", "is",
|
|
322
|
+
"lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try",
|
|
323
|
+
"while", "with", "yield",
|
|
324
|
+
)
|
|
325
|
+
js_words = (
|
|
326
|
+
"async", "await", "break", "case", "catch", "class", "const",
|
|
327
|
+
"continue", "default", "delete", "do", "else", "export", "extends",
|
|
328
|
+
"false", "finally", "for", "from", "function", "if", "import", "in",
|
|
329
|
+
"instanceof", "let", "new", "null", "of", "return", "static", "super",
|
|
330
|
+
"switch", "this", "throw", "true", "try", "typeof", "undefined", "var",
|
|
331
|
+
"void", "while", "yield", "interface", "type", "implements", "private",
|
|
332
|
+
"public", "protected", "readonly", "as", "enum", "namespace", "declare",
|
|
333
|
+
)
|
|
334
|
+
for word in (python_words if language == "python" else js_words):
|
|
335
|
+
self.rules.append((QRegularExpression(rf"\b{word}\b"), keyword))
|
|
336
|
+
if language in {"java", "cpp", "c"}:
|
|
337
|
+
for word in ("abstract", "boolean", "char", "double", "float", "int", "long",
|
|
338
|
+
"short", "void", "volatile", "transient", "native", "synchronized",
|
|
339
|
+
"include", "define", "struct", "union", "typedef", "sizeof"):
|
|
340
|
+
self.rules.append((QRegularExpression(rf"\b{word}\b"), keyword))
|
|
341
|
+
number = QTextCharFormat()
|
|
342
|
+
number.setForeground(QColor("#d8b87a"))
|
|
343
|
+
self.rules.append((QRegularExpression(r"\b\d+(\.\d+)?\b"), number))
|
|
344
|
+
string = QTextCharFormat()
|
|
345
|
+
string.setForeground(QColor("#a8c68f"))
|
|
346
|
+
self.rules.append((QRegularExpression(r'"[^"\\]*(\\.[^"\\]*)*"'), string))
|
|
347
|
+
self.rules.append((QRegularExpression(r"'[^'\\]*(\\.[^'\\]*)*'"), string))
|
|
348
|
+
comment = QTextCharFormat()
|
|
349
|
+
comment.setForeground(QColor("#75808c"))
|
|
350
|
+
comment.setFontItalic(True)
|
|
351
|
+
comment_pattern = r"#[^\n]*" if language == "python" else r"//[^\n]*"
|
|
352
|
+
self.rules.append((QRegularExpression(comment_pattern), comment))
|
|
353
|
+
builtin = QTextCharFormat()
|
|
354
|
+
builtin.setForeground(QColor("#82b7d8"))
|
|
355
|
+
builtins = ("print", "len", "range", "int", "str", "float", "list", "dict", "sum", "min", "max") if language == "python" else ("console", "Math", "JSON", "parseInt", "parseFloat", "String", "Number", "Array", "Object")
|
|
356
|
+
for word in builtins:
|
|
357
|
+
self.rules.append((QRegularExpression(rf"\b{word}\b"), builtin))
|
|
358
|
+
|
|
359
|
+
def highlightBlock(self, text: str) -> None:
|
|
360
|
+
for expression, fmt in self.rules:
|
|
361
|
+
iterator = expression.globalMatch(text)
|
|
362
|
+
while iterator.hasNext():
|
|
363
|
+
match = iterator.next()
|
|
364
|
+
self.setFormat(match.capturedStart(), match.capturedLength(), fmt)
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
class CodeEditor(QPlainTextEdit):
|
|
368
|
+
def __init__(self, parent=None, language: str = "python"):
|
|
369
|
+
super().__init__(parent)
|
|
370
|
+
font = QFontDatabase.systemFont(QFontDatabase.SystemFont.FixedFont)
|
|
371
|
+
font.setPointSize(10)
|
|
372
|
+
self.setFont(font)
|
|
373
|
+
self.setTabStopDistance(self.fontMetrics().horizontalAdvance(" ") * 4)
|
|
374
|
+
self.language = language
|
|
375
|
+
self.highlighter = CodeHighlighter(self.document(), language)
|
|
376
|
+
self.setPlaceholderText("Write code here…")
|
|
377
|
+
|
|
378
|
+
def set_language(self, language: str) -> None:
|
|
379
|
+
if language == self.language:
|
|
380
|
+
return
|
|
381
|
+
self.language = language
|
|
382
|
+
self.highlighter = CodeHighlighter(self.document(), language)
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def format_value(value) -> str:
|
|
386
|
+
text = str(value)
|
|
387
|
+
return text if len(text) <= 90 else text[:87] + "…"
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def guide_html(guide: dict, analysis: dict, ai_text: str | None = None) -> str:
|
|
391
|
+
def esc(text):
|
|
392
|
+
return html.escape(str(text)).replace("`", "").replace("**", "")
|
|
393
|
+
|
|
394
|
+
parts = [f"<h1>{esc(guide.get('headline', 'How this program works'))}</h1>"]
|
|
395
|
+
parts.append(f"<p style='color:#b9c1cb'>{esc(guide.get('summary', ''))}</p>")
|
|
396
|
+
mental = guide.get("overview", {}).get("mentalModel", {})
|
|
397
|
+
if mental:
|
|
398
|
+
parts.append(f"<h2>Mental model</h2><p><b>{esc(mental.get('title', ''))}</b><br>{esc(mental.get('body', ''))}</p>")
|
|
399
|
+
parts.append("<h2>Overview</h2>")
|
|
400
|
+
for paragraph in guide.get("overview", {}).get("paragraphs", []):
|
|
401
|
+
parts.append(f"<p>{esc(paragraph)}</p>")
|
|
402
|
+
walkthrough = guide.get("walkthrough", [])
|
|
403
|
+
if walkthrough:
|
|
404
|
+
parts.append("<h2>How it runs</h2>")
|
|
405
|
+
for item in walkthrough:
|
|
406
|
+
points = "".join(f"<li>{esc(point)}</li>" for point in item.get("points", []))
|
|
407
|
+
parts.append(
|
|
408
|
+
f"<h3>{esc(item.get('title', ''))}</h3>"
|
|
409
|
+
f"<p>{esc(item.get('body', ''))}</p>"
|
|
410
|
+
+ (f"<ul>{points}</ul>" if points else "")
|
|
411
|
+
)
|
|
412
|
+
notes = guide.get("lineNotes", [])
|
|
413
|
+
if notes:
|
|
414
|
+
parts.append("<h2>Line by line</h2>")
|
|
415
|
+
for note in notes:
|
|
416
|
+
parts.append(
|
|
417
|
+
f"<p><b>Line {note.get('line', '?')}</b> "
|
|
418
|
+
f"<code style='color:#ffb59f'>{esc(note.get('code', ''))}</code><br>"
|
|
419
|
+
f"{esc(note.get('note', ''))}</p>"
|
|
420
|
+
)
|
|
421
|
+
concepts = guide.get("concepts", [])
|
|
422
|
+
if concepts:
|
|
423
|
+
parts.append("<h2>Concepts</h2>")
|
|
424
|
+
for concept in concepts:
|
|
425
|
+
parts.append(
|
|
426
|
+
f"<p><b>{esc(concept.get('term', ''))}</b><br>"
|
|
427
|
+
f"{esc(concept.get('definition', ''))}<br>"
|
|
428
|
+
f"<span style='color:#aab3be'>{esc(concept.get('inThisCode', ''))}</span></p>"
|
|
429
|
+
)
|
|
430
|
+
watch_outs = guide.get("watchOuts", [])
|
|
431
|
+
if watch_outs:
|
|
432
|
+
parts.append("<h2>Watch out for</h2>")
|
|
433
|
+
for item in watch_outs:
|
|
434
|
+
parts.append(f"<p><b>{esc(item.get('title', ''))}</b><br>{esc(item.get('body', ''))}</p>")
|
|
435
|
+
quiz = guide.get("quiz", [])
|
|
436
|
+
if quiz:
|
|
437
|
+
parts.append("<h2>Quick check</h2>")
|
|
438
|
+
for item in quiz:
|
|
439
|
+
parts.append(f"<p><b>{esc(item.get('question', ''))}</b><br>{esc(item.get('answer', ''))}</p>")
|
|
440
|
+
if ai_text:
|
|
441
|
+
parts.append("<h2>AI explanation</h2>")
|
|
442
|
+
for paragraph in str(ai_text).split("\n\n"):
|
|
443
|
+
if paragraph.strip():
|
|
444
|
+
parts.append(f"<p>{esc(paragraph.strip())}</p>")
|
|
445
|
+
parts.append("<hr><p style='color:#8d96a1'>Generated locally by the Python analysis engine.</p>")
|
|
446
|
+
return "".join(parts)
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
class FlowchartView(QGraphicsView):
|
|
450
|
+
"""A readable top-down flow outline rendered entirely with QPainter."""
|
|
451
|
+
|
|
452
|
+
def __init__(self, parent=None):
|
|
453
|
+
super().__init__(parent)
|
|
454
|
+
self.setRenderHints(QPainter.RenderHint.Antialiasing | QPainter.RenderHint.TextAntialiasing)
|
|
455
|
+
self.setBackgroundBrush(QColor("#1c1f24"))
|
|
456
|
+
self.setFrameShape(QFrame.Shape.NoFrame)
|
|
457
|
+
self._scene = QGraphicsScene(self)
|
|
458
|
+
self.setScene(self._scene)
|
|
459
|
+
self._fit_timer = QTimer(self)
|
|
460
|
+
self._fit_timer.setSingleShot(True)
|
|
461
|
+
self._fit_timer.timeout.connect(self._fit_scene)
|
|
462
|
+
|
|
463
|
+
def set_analysis(self, analysis: dict, trace: dict | None = None) -> None:
|
|
464
|
+
self._scene.clear()
|
|
465
|
+
self._trace = trace
|
|
466
|
+
self._animation_groups = []
|
|
467
|
+
y = 18
|
|
468
|
+
x = 18
|
|
469
|
+
entry = analysis.get("entry") or {}
|
|
470
|
+
focus = entry.get("node") if entry.get("kind") == "function" and entry.get("node") else analysis.get("root")
|
|
471
|
+
self._column(x, y, analysis, focus)
|
|
472
|
+
self._schedule_fit()
|
|
473
|
+
QTimer.singleShot(20, self._animate_items)
|
|
474
|
+
|
|
475
|
+
def showEvent(self, event: QShowEvent) -> None:
|
|
476
|
+
super().showEvent(event)
|
|
477
|
+
self._schedule_fit()
|
|
478
|
+
|
|
479
|
+
def resizeEvent(self, event: QResizeEvent) -> None:
|
|
480
|
+
super().resizeEvent(event)
|
|
481
|
+
self._schedule_fit()
|
|
482
|
+
|
|
483
|
+
def _schedule_fit(self) -> None:
|
|
484
|
+
if self.isVisible() and self.viewport().width() > 0 and self.viewport().height() > 0:
|
|
485
|
+
self._fit_timer.start(0)
|
|
486
|
+
|
|
487
|
+
def _fit_scene(self) -> None:
|
|
488
|
+
if not self.isVisible() or self.viewport().width() <= 0 or self.viewport().height() <= 0:
|
|
489
|
+
return
|
|
490
|
+
bounds = self._scene.itemsBoundingRect()
|
|
491
|
+
if bounds.isEmpty():
|
|
492
|
+
return
|
|
493
|
+
self.fitInView(
|
|
494
|
+
bounds.adjusted(-20, -20, 20, 20),
|
|
495
|
+
Qt.AspectRatioMode.KeepAspectRatio,
|
|
496
|
+
)
|
|
497
|
+
|
|
498
|
+
def _animate_items(self) -> None:
|
|
499
|
+
items = sorted(self._scene.items(), key=lambda item: item.sceneBoundingRect().top())
|
|
500
|
+
for index, item in enumerate(items[:70]):
|
|
501
|
+
effect = QGraphicsOpacityEffect(self)
|
|
502
|
+
effect.setOpacity(0.0)
|
|
503
|
+
item.setGraphicsEffect(effect)
|
|
504
|
+
fade = QPropertyAnimation(effect, b"opacity", self)
|
|
505
|
+
fade.setDuration(260)
|
|
506
|
+
fade.setStartValue(0.0)
|
|
507
|
+
fade.setEndValue(1.0)
|
|
508
|
+
fade.setEasingCurve(QEasingCurve.Type.OutCubic)
|
|
509
|
+
group = QParallelAnimationGroup(self)
|
|
510
|
+
group.addAnimation(QPauseAnimation(index * 22))
|
|
511
|
+
group.addAnimation(fade)
|
|
512
|
+
group.start()
|
|
513
|
+
self._animation_groups.append(group)
|
|
514
|
+
|
|
515
|
+
def _text(self, text: str, max_len: int = 56) -> str:
|
|
516
|
+
text = " ".join(str(text).split())
|
|
517
|
+
return text if len(text) <= max_len else text[: max_len - 1] + "…"
|
|
518
|
+
|
|
519
|
+
def _box(self, x, y, width, height, title, body="", accent="#ff7852", dashed=False):
|
|
520
|
+
pen = QPen(QColor(accent if dashed else "#464c56"))
|
|
521
|
+
pen.setWidthF(1.2)
|
|
522
|
+
if dashed:
|
|
523
|
+
pen.setStyle(Qt.PenStyle.DashLine)
|
|
524
|
+
rect = self._scene.addRect(x, y, width, height, pen, QColor("#252930"))
|
|
525
|
+
rect.setZValue(1)
|
|
526
|
+
tag = self._scene.addSimpleText(self._text(title, 34))
|
|
527
|
+
tag.setBrush(QColor(accent if dashed else "#aeb7c1"))
|
|
528
|
+
tag.setFont(QFont("Segoe UI", 7, QFont.Weight.DemiBold))
|
|
529
|
+
tag.setPos(x + 14, y + 10)
|
|
530
|
+
tag.setZValue(2)
|
|
531
|
+
if body:
|
|
532
|
+
line = self._scene.addSimpleText(self._text(body))
|
|
533
|
+
line.setBrush(QColor("#e9edf2"))
|
|
534
|
+
line.setFont(QFont("Cascadia Code", 9))
|
|
535
|
+
line.setPos(x + 14, y + 29)
|
|
536
|
+
line.setZValue(2)
|
|
537
|
+
return (x + width / 2, y + height)
|
|
538
|
+
|
|
539
|
+
def _arrow(self, start, end, dashed=False):
|
|
540
|
+
pen = QPen(QColor("#5d6672"))
|
|
541
|
+
pen.setWidthF(1.3)
|
|
542
|
+
if dashed:
|
|
543
|
+
pen.setStyle(Qt.PenStyle.DashLine)
|
|
544
|
+
self._scene.addLine(start[0], start[1], end[0], end[1], pen)
|
|
545
|
+
self._scene.addEllipse(end[0] - 2, end[1] - 2, 4, 4, pen, QColor("#5d6672"))
|
|
546
|
+
|
|
547
|
+
def _column(self, x: int, y: int, analysis: dict, focus: dict | None = None) -> int:
|
|
548
|
+
width = 370
|
|
549
|
+
language_name = analysis.get("language", {}).get("name", "Program")
|
|
550
|
+
body = (focus or {}).get("body") if focus and focus.get("type") == "function" else analysis["root"].get("body")
|
|
551
|
+
self._box(x, y, width, 48, "START", f"{language_name} program", "#ff7852")
|
|
552
|
+
previous_exit = (x + width / 2, y + 48)
|
|
553
|
+
y += 68
|
|
554
|
+
y = self._sequence((body or {}).get("children", []), x, y, width, previous_exit)
|
|
555
|
+
if (body or {}).get("children"):
|
|
556
|
+
previous_exit = (x + width / 2, y - 25)
|
|
557
|
+
trace = self._trace
|
|
558
|
+
messages = []
|
|
559
|
+
if trace is None:
|
|
560
|
+
messages.append("Program finished")
|
|
561
|
+
elif not trace.get("complete"):
|
|
562
|
+
messages.append(tr("Simulation incomplete"))
|
|
563
|
+
messages.append(str((trace.get("warnings") or [trace.get("stoppedReason", "")])[-1]))
|
|
564
|
+
elif not trace.get("output") and not trace.get("lastTopLevelReturn"):
|
|
565
|
+
messages.append(tr("Completed · no output"))
|
|
566
|
+
output = trace.get("output", "") if trace else ""
|
|
567
|
+
if output:
|
|
568
|
+
label = tr("Output") if trace.get("complete") else tr("Partial output")
|
|
569
|
+
lines = output.splitlines() or [output]
|
|
570
|
+
messages.append(label + ": " + lines[0])
|
|
571
|
+
if len(lines) > 1:
|
|
572
|
+
messages.append(lines[1] + (" …" if len(lines) > 2 else ""))
|
|
573
|
+
result = trace.get("lastTopLevelReturn") if trace and trace.get("complete") else None
|
|
574
|
+
if result:
|
|
575
|
+
lines = str(result["value"]).splitlines() or [""]
|
|
576
|
+
messages.append(tr("Return") + ": " + result["name"] + " → " + lines[0])
|
|
577
|
+
if len(lines) > 1:
|
|
578
|
+
messages.append(lines[1] + (" …" if len(lines) > 2 else ""))
|
|
579
|
+
height = 40 + len(messages) * 17
|
|
580
|
+
self._arrow(previous_exit, (x + width / 2, y))
|
|
581
|
+
self._box(x, y, width, height, "END", "", "#ff7852")
|
|
582
|
+
for index, message in enumerate(messages):
|
|
583
|
+
line = self._scene.addSimpleText(self._text(message, 48))
|
|
584
|
+
line.setBrush(QColor("#e9edf2"))
|
|
585
|
+
line.setFont(QFont("Cascadia Code", 9))
|
|
586
|
+
line.setPos(x + 14, y + 29 + index * 17)
|
|
587
|
+
line.setZValue(2)
|
|
588
|
+
return y + height
|
|
589
|
+
|
|
590
|
+
def _sequence(self, nodes, x, y, width, previous_exit):
|
|
591
|
+
for node in nodes:
|
|
592
|
+
kind = node.get("type")
|
|
593
|
+
if kind in {"function", "class"}:
|
|
594
|
+
continue
|
|
595
|
+
before = y
|
|
596
|
+
self._arrow(previous_exit, (x + width / 2, y))
|
|
597
|
+
if kind in {"for", "while"}:
|
|
598
|
+
previous_exit = self._box(x, y, width, 48, "LOOP", node.get("header", "loop"), "#d7a84d")
|
|
599
|
+
y = previous_exit[1] + 18
|
|
600
|
+
y = self._sequence(node.get("body", {}).get("children", []), x + 34, y, width - 34, previous_exit)
|
|
601
|
+
if node.get("alternate"):
|
|
602
|
+
y = self._sequence(node["alternate"].get("children", []), x + 34, y, width - 34, (x + width / 2, y))
|
|
603
|
+
y += 22
|
|
604
|
+
previous_exit = (x + width / 2, y)
|
|
605
|
+
elif kind == "if":
|
|
606
|
+
previous_exit = self._box(x, y, width, 48, "IF", node.get("condition", "condition"), "#d7a84d")
|
|
607
|
+
y = previous_exit[1] + 16
|
|
608
|
+
y = self._sequence(node.get("consequent", {}).get("children", []), x + 34, y, width - 34, previous_exit)
|
|
609
|
+
alternate = node.get("alternate")
|
|
610
|
+
if alternate and alternate.get("children"):
|
|
611
|
+
self._arrow((x + width / 2, y), (x + width / 2 + 22, y))
|
|
612
|
+
y = self._sequence(alternate.get("children", []), x + 56, y + 18, width - 56, (x + width / 2, y))
|
|
613
|
+
y += 12
|
|
614
|
+
previous_exit = (x + width / 2, y)
|
|
615
|
+
elif kind == "action":
|
|
616
|
+
action = node.get("action") or {}
|
|
617
|
+
subtype = action.get("subtype", "statement")
|
|
618
|
+
accent = "#ff8d6f" if subtype in {"return", "break", "continue"} else "#5d6672"
|
|
619
|
+
previous_exit = self._box(x, y, width, 54, subtype.upper(), node.get("text", ""), accent)
|
|
620
|
+
y = previous_exit[1]
|
|
621
|
+
else:
|
|
622
|
+
previous_exit = self._box(x, y, width, 50, str(kind).upper(), node.get("header", ""))
|
|
623
|
+
y = previous_exit[1]
|
|
624
|
+
y += 25
|
|
625
|
+
if y <= before:
|
|
626
|
+
break
|
|
627
|
+
return y
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
class SyntaxTreeView(QTreeWidget):
|
|
631
|
+
def __init__(self, parent=None):
|
|
632
|
+
super().__init__(parent)
|
|
633
|
+
self.setHeaderLabels(["Structure", "Line"])
|
|
634
|
+
self.setAlternatingRowColors(True)
|
|
635
|
+
self.setColumnWidth(0, 350)
|
|
636
|
+
self.setAnimated(True)
|
|
637
|
+
|
|
638
|
+
def set_analysis(self, analysis: dict) -> None:
|
|
639
|
+
self.clear()
|
|
640
|
+
root = QTreeWidgetItem(["Program", str(analysis.get("lineCount", ""))])
|
|
641
|
+
self.addTopLevelItem(root)
|
|
642
|
+
self._add_nodes(analysis["root"]["body"].get("children", []), root)
|
|
643
|
+
root.setExpanded(True)
|
|
644
|
+
|
|
645
|
+
def _add_nodes(self, nodes, parent):
|
|
646
|
+
for node in nodes:
|
|
647
|
+
kind = node.get("type")
|
|
648
|
+
label = node.get("name") or node.get("header") or node.get("text") or kind
|
|
649
|
+
item = QTreeWidgetItem([str(kind).title(), str(node.get("startLine", ""))])
|
|
650
|
+
item.setToolTip(0, str(label))
|
|
651
|
+
parent.addChild(item)
|
|
652
|
+
if kind in {"function", "class", "if", "for", "while"}:
|
|
653
|
+
body = node.get("body") or node.get("consequent")
|
|
654
|
+
if body:
|
|
655
|
+
self._add_nodes(body.get("children", []), item)
|
|
656
|
+
alternate = node.get("alternate")
|
|
657
|
+
if alternate:
|
|
658
|
+
alt = QTreeWidgetItem(["Else", str(alternate.get("startLine", ""))])
|
|
659
|
+
item.addChild(alt)
|
|
660
|
+
self._add_nodes(alternate.get("children", []), alt)
|
|
661
|
+
item.setExpanded(True)
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
class TraceView(QWidget):
|
|
665
|
+
def __init__(self, parent=None):
|
|
666
|
+
super().__init__(parent)
|
|
667
|
+
layout = QVBoxLayout(self)
|
|
668
|
+
layout.setContentsMargins(0, 0, 0, 0)
|
|
669
|
+
split = QSplitter(Qt.Orientation.Horizontal)
|
|
670
|
+
self.steps = QListWidget()
|
|
671
|
+
self.steps.setMinimumWidth(220)
|
|
672
|
+
self.steps.currentRowChanged.connect(self.show_step)
|
|
673
|
+
split.addWidget(self.steps)
|
|
674
|
+
self.detail = QTextBrowser()
|
|
675
|
+
split.addWidget(self.detail)
|
|
676
|
+
split.setSizes([260, 620])
|
|
677
|
+
layout.addWidget(split, 1)
|
|
678
|
+
controls = QHBoxLayout()
|
|
679
|
+
self.prev = QPushButton("Previous")
|
|
680
|
+
self.next = QPushButton("Next")
|
|
681
|
+
self.play = QPushButton("Play")
|
|
682
|
+
self.prev.clicked.connect(lambda: self.move(-1))
|
|
683
|
+
self.next.clicked.connect(lambda: self.move(1))
|
|
684
|
+
self.play.clicked.connect(self.toggle_play)
|
|
685
|
+
controls.addWidget(self.prev)
|
|
686
|
+
controls.addWidget(self.next)
|
|
687
|
+
controls.addWidget(self.play)
|
|
688
|
+
controls.addStretch(1)
|
|
689
|
+
layout.addLayout(controls)
|
|
690
|
+
self.timer = QTimer(self)
|
|
691
|
+
self.timer.setInterval(750)
|
|
692
|
+
self.timer.timeout.connect(lambda: self.move(1))
|
|
693
|
+
self.items: list[dict] = []
|
|
694
|
+
self.trace = {}
|
|
695
|
+
|
|
696
|
+
def set_trace(self, trace: dict) -> None:
|
|
697
|
+
self.trace = trace
|
|
698
|
+
self.timer.stop()
|
|
699
|
+
self.play.setText("Play")
|
|
700
|
+
self.steps.clear()
|
|
701
|
+
self.items = trace.get("steps", [])
|
|
702
|
+
self.play.setEnabled(len(self.items) > 1)
|
|
703
|
+
for step in self.items:
|
|
704
|
+
item = QListWidgetItem(f"L{step.get('line', '?')} · {step.get('title', 'Step')}")
|
|
705
|
+
self.steps.addItem(item)
|
|
706
|
+
if self.items:
|
|
707
|
+
self.steps.setCurrentRow(0)
|
|
708
|
+
else:
|
|
709
|
+
self.detail.setHtml("<p style='color:#9aa2ad'>No trace steps were recorded.</p>")
|
|
710
|
+
|
|
711
|
+
def show_step(self, index: int) -> None:
|
|
712
|
+
if index < 0 or index >= len(self.items):
|
|
713
|
+
return
|
|
714
|
+
step = self.items[index]
|
|
715
|
+
variables = "".join(
|
|
716
|
+
f"<tr><td style='color:#b8c0ca'>{html.escape(str(v.get('name', '')))}</td>"
|
|
717
|
+
f"<td style='color:#f0c48a'>{html.escape(format_value(v.get('display', '')))}</td></tr>"
|
|
718
|
+
for v in step.get("vars", [])
|
|
719
|
+
)
|
|
720
|
+
output = html.escape(step.get("output", "")).replace("\n", "<br>") or "—"
|
|
721
|
+
self.detail.setHtml(
|
|
722
|
+
f"<h2 style='color:#f1f3f5'>{html.escape(step.get('title', 'Step'))}</h2>"
|
|
723
|
+
f"<p style='color:#aab2bd'>Line {step.get('line', '?')} · {html.escape(step.get('scope', 'Global'))}</p>"
|
|
724
|
+
f"<p>{html.escape(step.get('detail', ''))}</p>"
|
|
725
|
+
f"<h3>Variables</h3><table>{variables or '<tr><td>No variables yet.</td></tr>'}</table>"
|
|
726
|
+
f"<h3>Output</h3><pre style='color:#c8d2b5'>{output}</pre>"
|
|
727
|
+
+ ("<p>" + html.escape("; ".join(self.trace.get("warnings", []))) + "</p>" if not self.trace.get("complete", True) else "")
|
|
728
|
+
)
|
|
729
|
+
self.prev.setEnabled(index > 0)
|
|
730
|
+
self.next.setEnabled(index + 1 < len(self.items))
|
|
731
|
+
fade_in(self.detail, 160)
|
|
732
|
+
|
|
733
|
+
def move(self, delta: int) -> None:
|
|
734
|
+
index = self.steps.currentRow() + delta
|
|
735
|
+
if 0 <= index < len(self.items):
|
|
736
|
+
self.steps.setCurrentRow(index)
|
|
737
|
+
if self.steps.currentRow() >= len(self.items) - 1:
|
|
738
|
+
self.timer.stop()
|
|
739
|
+
self.play.setText("Play")
|
|
740
|
+
|
|
741
|
+
def toggle_play(self) -> None:
|
|
742
|
+
if self.timer.isActive():
|
|
743
|
+
self.timer.stop()
|
|
744
|
+
self.play.setText("Play")
|
|
745
|
+
else:
|
|
746
|
+
if self.steps.currentRow() >= len(self.items) - 1:
|
|
747
|
+
self.steps.setCurrentRow(0)
|
|
748
|
+
self.timer.start()
|
|
749
|
+
self.play.setText("Pause")
|
|
750
|
+
|
|
751
|
+
|
|
752
|
+
class DataFlowView(QTableWidget):
|
|
753
|
+
def __init__(self, parent=None):
|
|
754
|
+
super().__init__(parent)
|
|
755
|
+
self.setColumnCount(5)
|
|
756
|
+
self.setHorizontalHeaderLabels(["Line", "Target", "Expression / value", "Depends on", "Scope"])
|
|
757
|
+
self.horizontalHeader().setStretchLastSection(True)
|
|
758
|
+
self.setColumnWidth(0, 60)
|
|
759
|
+
self.setColumnWidth(1, 140)
|
|
760
|
+
self.setColumnWidth(2, 260)
|
|
761
|
+
self.setColumnWidth(3, 180)
|
|
762
|
+
self.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
|
|
763
|
+
|
|
764
|
+
def set_analysis(self, analysis: dict, trace: dict) -> None:
|
|
765
|
+
rows = []
|
|
766
|
+
seen = set()
|
|
767
|
+
for event in trace.get("events", []):
|
|
768
|
+
if event.get("kind") != "assignment":
|
|
769
|
+
continue
|
|
770
|
+
key = (event.get("line"), event.get("target"))
|
|
771
|
+
if key in seen:
|
|
772
|
+
continue
|
|
773
|
+
seen.add(key)
|
|
774
|
+
rows.append((
|
|
775
|
+
event.get("line", ""), event.get("target", ""),
|
|
776
|
+
f"{event.get('expressionText') or ''} → {event.get('value', '')}",
|
|
777
|
+
", ".join(event.get("dependencies", []) or []),
|
|
778
|
+
event.get("scope", "Global"),
|
|
779
|
+
))
|
|
780
|
+
if not rows:
|
|
781
|
+
for assignment in analysis.get("assignments", []):
|
|
782
|
+
rows.append((
|
|
783
|
+
assignment.get("line", ""), assignment.get("target", ""),
|
|
784
|
+
f"{assignment.get('expressionText', '')}",
|
|
785
|
+
", ".join(assignment.get("dependencies", []) or []),
|
|
786
|
+
assignment.get("scope", "Global"),
|
|
787
|
+
))
|
|
788
|
+
self.setRowCount(len(rows))
|
|
789
|
+
for row, values in enumerate(rows):
|
|
790
|
+
for column, value in enumerate(values):
|
|
791
|
+
self.setItem(row, column, QTableWidgetItem(format_value(value)))
|
|
792
|
+
self.resizeRowsToContents()
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
class AIWorker(QThread):
|
|
796
|
+
succeeded = Signal(str)
|
|
797
|
+
failed = Signal(str)
|
|
798
|
+
|
|
799
|
+
def __init__(self, job, parent=None):
|
|
800
|
+
super().__init__(parent)
|
|
801
|
+
self.job = job
|
|
802
|
+
|
|
803
|
+
def run(self) -> None:
|
|
804
|
+
try:
|
|
805
|
+
self.succeeded.emit(self.job())
|
|
806
|
+
except AIError as error:
|
|
807
|
+
self.failed.emit(str(error))
|
|
808
|
+
except Exception as error: # pragma: no cover - network boundary
|
|
809
|
+
self.failed.emit(str(error))
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
class AISettingsDialog(QDialog):
|
|
813
|
+
def __init__(self, settings: AISettings, remember: bool, parent=None):
|
|
814
|
+
super().__init__(parent)
|
|
815
|
+
self.setWindowTitle("Connect AI")
|
|
816
|
+
self.setMinimumWidth(540)
|
|
817
|
+
self.settings = settings
|
|
818
|
+
self.remember_value = remember
|
|
819
|
+
self.worker = None
|
|
820
|
+
layout = QVBoxLayout(self)
|
|
821
|
+
title = QLabel("Connect your AI")
|
|
822
|
+
title.setObjectName("Title")
|
|
823
|
+
title.setStyleSheet("font-size: 20pt;")
|
|
824
|
+
layout.addWidget(title)
|
|
825
|
+
description = QLabel(
|
|
826
|
+
"Optional. The local guide always works without AI. A request is sent only when you test or enhance."
|
|
827
|
+
)
|
|
828
|
+
description.setObjectName("Muted")
|
|
829
|
+
description.setWordWrap(True)
|
|
830
|
+
layout.addWidget(description)
|
|
831
|
+
|
|
832
|
+
form = QFormLayout()
|
|
833
|
+
self.provider = QComboBox()
|
|
834
|
+
for key, item in PROVIDERS.items():
|
|
835
|
+
self.provider.addItem(item["name"], key)
|
|
836
|
+
self.provider.setCurrentIndex(max(0, self.provider.findData(settings.provider)))
|
|
837
|
+
form.addRow("Provider", self.provider)
|
|
838
|
+
self.base_url = QLineEdit(settings.base_url)
|
|
839
|
+
form.addRow("Base URL", self.base_url)
|
|
840
|
+
self.model = QLineEdit(settings.model)
|
|
841
|
+
form.addRow("Model", self.model)
|
|
842
|
+
self.api_key = QLineEdit(settings.api_key)
|
|
843
|
+
self.api_key.setEchoMode(QLineEdit.EchoMode.Password)
|
|
844
|
+
self.api_key.setPlaceholderText("Optional for local compatible servers")
|
|
845
|
+
form.addRow("API key", self.api_key)
|
|
846
|
+
layout.addLayout(form)
|
|
847
|
+
|
|
848
|
+
self.remember = QCheckBox("Remember the key on this device")
|
|
849
|
+
self.remember.setChecked(remember)
|
|
850
|
+
layout.addWidget(self.remember)
|
|
851
|
+
note = QLabel("The key is sent only to the provider for the request you start. It is never logged.")
|
|
852
|
+
note.setObjectName("Tiny")
|
|
853
|
+
note.setWordWrap(True)
|
|
854
|
+
layout.addWidget(note)
|
|
855
|
+
|
|
856
|
+
self.status = QLabel("")
|
|
857
|
+
self.status.setObjectName("Muted")
|
|
858
|
+
self.status.setWordWrap(True)
|
|
859
|
+
layout.addWidget(self.status)
|
|
860
|
+
|
|
861
|
+
buttons = QHBoxLayout()
|
|
862
|
+
self.test = QPushButton("Test connection")
|
|
863
|
+
self.test.clicked.connect(self.test_ai)
|
|
864
|
+
buttons.addWidget(self.test)
|
|
865
|
+
buttons.addStretch(1)
|
|
866
|
+
box = QDialogButtonBox(QDialogButtonBox.StandardButton.Save | QDialogButtonBox.StandardButton.Cancel)
|
|
867
|
+
box.accepted.connect(self.save)
|
|
868
|
+
box.rejected.connect(self.reject)
|
|
869
|
+
buttons.addWidget(box)
|
|
870
|
+
layout.addLayout(buttons)
|
|
871
|
+
self.provider.currentIndexChanged.connect(self.provider_changed)
|
|
872
|
+
|
|
873
|
+
def provider_changed(self) -> None:
|
|
874
|
+
key = self.provider.currentData()
|
|
875
|
+
defaults = PROVIDERS.get(key)
|
|
876
|
+
if not defaults:
|
|
877
|
+
return
|
|
878
|
+
if not self.base_url.text().strip() or self.base_url.text().strip() in {
|
|
879
|
+
item["base"] for item in PROVIDERS.values()
|
|
880
|
+
}:
|
|
881
|
+
self.base_url.setText(defaults["base"])
|
|
882
|
+
if not self.model.text().strip() or self.model.text().strip() in {
|
|
883
|
+
item["model"] for item in PROVIDERS.values()
|
|
884
|
+
}:
|
|
885
|
+
self.model.setText(defaults["model"])
|
|
886
|
+
|
|
887
|
+
def current_settings(self) -> AISettings:
|
|
888
|
+
return AISettings(
|
|
889
|
+
provider=self.provider.currentData(),
|
|
890
|
+
base_url=self.base_url.text().strip(),
|
|
891
|
+
model=self.model.text().strip(),
|
|
892
|
+
api_key=self.api_key.text(),
|
|
893
|
+
)
|
|
894
|
+
|
|
895
|
+
def test_ai(self) -> None:
|
|
896
|
+
settings = self.current_settings()
|
|
897
|
+
self.test.setEnabled(False)
|
|
898
|
+
self.status.setText("Testing connection…")
|
|
899
|
+
self.worker = AIWorker(lambda: test_connection(settings), self)
|
|
900
|
+
self.worker.succeeded.connect(lambda text: self._test_done(text, None))
|
|
901
|
+
self.worker.failed.connect(lambda error: self._test_done("", error))
|
|
902
|
+
self.worker.start()
|
|
903
|
+
|
|
904
|
+
def _test_done(self, text: str, error: str | None) -> None:
|
|
905
|
+
self.test.setEnabled(True)
|
|
906
|
+
if error:
|
|
907
|
+
self.status.setText(f"Connection failed: {error}")
|
|
908
|
+
else:
|
|
909
|
+
self.status.setText(f"Connected. Provider replied: {text.strip()[:80]}")
|
|
910
|
+
|
|
911
|
+
def save(self) -> None:
|
|
912
|
+
settings = self.current_settings()
|
|
913
|
+
if not settings.base_url or not settings.model:
|
|
914
|
+
self.status.setText("Base URL and model are required.")
|
|
915
|
+
return
|
|
916
|
+
self.settings = settings
|
|
917
|
+
self.remember_value = self.remember.isChecked()
|
|
918
|
+
self.accept()
|
|
919
|
+
|
|
920
|
+
|
|
921
|
+
class WelcomePage(QWidget):
|
|
922
|
+
def __init__(self, parent=None):
|
|
923
|
+
super().__init__(parent)
|
|
924
|
+
outer = QVBoxLayout(self)
|
|
925
|
+
outer.setContentsMargins(70, 36, 70, 36)
|
|
926
|
+
outer.setSpacing(18)
|
|
927
|
+
intro_row = QHBoxLayout()
|
|
928
|
+
intro_row.setSpacing(24)
|
|
929
|
+
intro_copy = QVBoxLayout()
|
|
930
|
+
intro_copy.setSpacing(8)
|
|
931
|
+
kicker = QLabel(tr("LOCAL CODE WORKSPACE"))
|
|
932
|
+
kicker.setObjectName("Kicker")
|
|
933
|
+
intro_copy.addWidget(kicker)
|
|
934
|
+
title = QLabel(tr(APP_TAGLINE))
|
|
935
|
+
title.setObjectName("Title")
|
|
936
|
+
intro_copy.addWidget(title)
|
|
937
|
+
subtitle = QLabel(
|
|
938
|
+
tr("Write or import code. Prism explains the flow, structure, execution, "
|
|
939
|
+
"and data without leaving this window.")
|
|
940
|
+
)
|
|
941
|
+
subtitle.setObjectName("Subtitle")
|
|
942
|
+
subtitle.setWordWrap(True)
|
|
943
|
+
subtitle.setMaximumWidth(720)
|
|
944
|
+
intro_copy.addWidget(subtitle)
|
|
945
|
+
intro_row.addLayout(intro_copy, 1)
|
|
946
|
+
self.preview = PreviewArt()
|
|
947
|
+
intro_row.addWidget(self.preview, 0, Qt.AlignmentFlag.AlignTop)
|
|
948
|
+
outer.addLayout(intro_row)
|
|
949
|
+
self.intro_widgets = [kicker, title, subtitle, self.preview]
|
|
950
|
+
self.kicker = kicker
|
|
951
|
+
self.title = title
|
|
952
|
+
self.subtitle = subtitle
|
|
953
|
+
|
|
954
|
+
card = QFrame()
|
|
955
|
+
card.setObjectName("Card")
|
|
956
|
+
card_layout = QVBoxLayout(card)
|
|
957
|
+
card_layout.setContentsMargins(28, 24, 28, 24)
|
|
958
|
+
card_layout.setSpacing(14)
|
|
959
|
+
card_title = QLabel(tr("Start an analysis"))
|
|
960
|
+
card_title.setObjectName("CardTitle")
|
|
961
|
+
card_layout.addWidget(card_title)
|
|
962
|
+
card_sub = QLabel(
|
|
963
|
+
tr("The document starts blank. Open the editor, import a source file, or try a case.")
|
|
964
|
+
)
|
|
965
|
+
card_sub.setObjectName("Muted")
|
|
966
|
+
card_sub.setWordWrap(True)
|
|
967
|
+
card_layout.addWidget(card_sub)
|
|
968
|
+
language_row = QHBoxLayout()
|
|
969
|
+
language_label = QLabel(tr("Language"))
|
|
970
|
+
language_label.setObjectName("Muted")
|
|
971
|
+
self.language = QComboBox()
|
|
972
|
+
for language_id, name in LANGUAGE_LABELS:
|
|
973
|
+
self.language.addItem(name, language_id)
|
|
974
|
+
language_row.addWidget(language_label)
|
|
975
|
+
language_row.addWidget(self.language)
|
|
976
|
+
language_row.addStretch(1)
|
|
977
|
+
card_layout.addLayout(language_row)
|
|
978
|
+
buttons = QHBoxLayout()
|
|
979
|
+
self.editor_button = QPushButton(tr("Open editor"))
|
|
980
|
+
self.editor_button.setObjectName("Primary")
|
|
981
|
+
self.import_button = QPushButton(tr("Import file"))
|
|
982
|
+
self.example_button = QPushButton(tr("Try a case"))
|
|
983
|
+
self.compare_button = QPushButton(tr("Compare versions"))
|
|
984
|
+
buttons.addWidget(self.editor_button)
|
|
985
|
+
buttons.addWidget(self.import_button)
|
|
986
|
+
buttons.addWidget(self.example_button)
|
|
987
|
+
buttons.addWidget(self.compare_button)
|
|
988
|
+
buttons.addStretch(1)
|
|
989
|
+
card_layout.addLayout(buttons)
|
|
990
|
+
features = QLabel(
|
|
991
|
+
tr("FLOWCHART Trace decisions and loops\n"
|
|
992
|
+
"SYNTAX TREE Inspect the AST structure\n"
|
|
993
|
+
"LIVE TRACE Step through the safe run\n"
|
|
994
|
+
"DATA FLOW Follow values to their use\n"
|
|
995
|
+
"GUIDE Read the explanation beside the code")
|
|
996
|
+
)
|
|
997
|
+
features.setObjectName("Feature")
|
|
998
|
+
features.setWordWrap(True)
|
|
999
|
+
card_layout.addWidget(features)
|
|
1000
|
+
outer.addWidget(card)
|
|
1001
|
+
outer.addStretch(1)
|
|
1002
|
+
|
|
1003
|
+
self.card_title = card_title
|
|
1004
|
+
self.card_sub = card_sub
|
|
1005
|
+
self.language_label = language_label
|
|
1006
|
+
self.features = features
|
|
1007
|
+
|
|
1008
|
+
def retranslate(self) -> None:
|
|
1009
|
+
self.kicker.setText(tr("LOCAL CODE WORKSPACE"))
|
|
1010
|
+
self.title.setText(tr(APP_TAGLINE))
|
|
1011
|
+
self.subtitle.setText(
|
|
1012
|
+
tr("Write or import code. Prism explains the flow, structure, execution, "
|
|
1013
|
+
"and data without leaving this window.")
|
|
1014
|
+
)
|
|
1015
|
+
self.card_title.setText(tr("Start an analysis"))
|
|
1016
|
+
self.card_sub.setText(
|
|
1017
|
+
tr("The document starts blank. Open the editor, import a source file, or try a case.")
|
|
1018
|
+
)
|
|
1019
|
+
self.language_label.setText(tr("Language"))
|
|
1020
|
+
self.editor_button.setText(tr("Open editor"))
|
|
1021
|
+
self.import_button.setText(tr("Import file"))
|
|
1022
|
+
self.example_button.setText(tr("Try a case"))
|
|
1023
|
+
self.compare_button.setText(tr("Compare versions"))
|
|
1024
|
+
self.features.setText(
|
|
1025
|
+
tr("FLOWCHART Trace decisions and loops\n"
|
|
1026
|
+
"SYNTAX TREE Inspect the AST structure\n"
|
|
1027
|
+
"LIVE TRACE Step through the safe run\n"
|
|
1028
|
+
"DATA FLOW Follow values to their use\n"
|
|
1029
|
+
"GUIDE Read the explanation beside the code")
|
|
1030
|
+
)
|
|
1031
|
+
|
|
1032
|
+
def play_intro(self) -> None:
|
|
1033
|
+
for index, widget in enumerate(self.intro_widgets):
|
|
1034
|
+
QTimer.singleShot(index * 55, lambda w=widget: fade_in(w, 360))
|
|
1035
|
+
|
|
1036
|
+
|
|
1037
|
+
class EditorPage(QWidget):
|
|
1038
|
+
def __init__(self, parent=None):
|
|
1039
|
+
super().__init__(parent)
|
|
1040
|
+
layout = QVBoxLayout(self)
|
|
1041
|
+
layout.setContentsMargins(24, 18, 24, 18)
|
|
1042
|
+
layout.setSpacing(12)
|
|
1043
|
+
head = QHBoxLayout()
|
|
1044
|
+
self.back = QPushButton(tr("← Welcome"))
|
|
1045
|
+
self.back.setObjectName("Ghost")
|
|
1046
|
+
head.addWidget(self.back)
|
|
1047
|
+
self.file_label = QLabel("main.py")
|
|
1048
|
+
self.file_label.setObjectName("CardTitle")
|
|
1049
|
+
head.addWidget(self.file_label)
|
|
1050
|
+
head.addStretch(1)
|
|
1051
|
+
self.import_button = QPushButton(tr("Import"))
|
|
1052
|
+
self.clear_button = QPushButton(tr("Clear"))
|
|
1053
|
+
head.addWidget(self.import_button)
|
|
1054
|
+
head.addWidget(self.clear_button)
|
|
1055
|
+
layout.addLayout(head)
|
|
1056
|
+
self.editor = CodeEditor()
|
|
1057
|
+
self.editor.setPlaceholderText(tr("Write Python code here…"))
|
|
1058
|
+
layout.addWidget(self.editor, 1)
|
|
1059
|
+
foot = QHBoxLayout()
|
|
1060
|
+
self.meta = QLabel(tr("Blank document"))
|
|
1061
|
+
self.meta.setObjectName("Tiny")
|
|
1062
|
+
foot.addWidget(self.meta)
|
|
1063
|
+
foot.addStretch(1)
|
|
1064
|
+
self.analyze = QPushButton(tr("Visualize & explain"))
|
|
1065
|
+
self.analyze.setObjectName("Primary")
|
|
1066
|
+
foot.addWidget(self.analyze)
|
|
1067
|
+
layout.addLayout(foot)
|
|
1068
|
+
|
|
1069
|
+
def retranslate(self) -> None:
|
|
1070
|
+
self.back.setText(tr("← Welcome"))
|
|
1071
|
+
self.import_button.setText(tr("Import"))
|
|
1072
|
+
self.clear_button.setText(tr("Clear"))
|
|
1073
|
+
self.editor.setPlaceholderText(tr("Write Python code here…"))
|
|
1074
|
+
if self.meta.text().strip() in ("Blank document", ""):
|
|
1075
|
+
self.meta.setText(tr("Blank document"))
|
|
1076
|
+
self.analyze.setText(tr("Visualize & explain"))
|
|
1077
|
+
|
|
1078
|
+
|
|
1079
|
+
class ResultsPage(QWidget):
|
|
1080
|
+
def __init__(self, parent=None):
|
|
1081
|
+
super().__init__(parent)
|
|
1082
|
+
self.guide = None
|
|
1083
|
+
self.trace = None
|
|
1084
|
+
self.analysis = None
|
|
1085
|
+
self.language = "python"
|
|
1086
|
+
self.function_pov_supported = False
|
|
1087
|
+
layout = QVBoxLayout(self)
|
|
1088
|
+
layout.setContentsMargins(16, 12, 16, 12)
|
|
1089
|
+
layout.setSpacing(10)
|
|
1090
|
+
head = QHBoxLayout()
|
|
1091
|
+
self.back = QPushButton(tr("← Welcome"))
|
|
1092
|
+
self.back.setObjectName("Ghost")
|
|
1093
|
+
head.addWidget(self.back)
|
|
1094
|
+
self.file_label = QLabel("main.py")
|
|
1095
|
+
self.file_label.setObjectName("CardTitle")
|
|
1096
|
+
head.addWidget(self.file_label)
|
|
1097
|
+
self.summary = QLabel("")
|
|
1098
|
+
self.summary.setObjectName("Tiny")
|
|
1099
|
+
head.addWidget(self.summary)
|
|
1100
|
+
head.addStretch(1)
|
|
1101
|
+
self.ai_button = QPushButton(tr("Enhance guide"))
|
|
1102
|
+
self.edit = QPushButton(tr("Edit code"))
|
|
1103
|
+
self.export = QPushButton(tr("Save guide"))
|
|
1104
|
+
self.function_pov_button = QPushButton(tr("Function POV"))
|
|
1105
|
+
self.function_pov_button.setEnabled(False)
|
|
1106
|
+
self.function_pov_button.setVisible(False)
|
|
1107
|
+
self.function_pov_button.setToolTip(tr("Function POV currently supports Python only."))
|
|
1108
|
+
head.addWidget(self.function_pov_button)
|
|
1109
|
+
head.addWidget(self.ai_button)
|
|
1110
|
+
head.addWidget(self.edit)
|
|
1111
|
+
head.addWidget(self.export)
|
|
1112
|
+
layout.addLayout(head)
|
|
1113
|
+
split = QSplitter(Qt.Orientation.Horizontal)
|
|
1114
|
+
self.source = QPlainTextEdit()
|
|
1115
|
+
self.source.setReadOnly(True)
|
|
1116
|
+
self.source.setObjectName("ReadOnly")
|
|
1117
|
+
self.source.setMinimumWidth(260)
|
|
1118
|
+
self.source_highlighter = CodeHighlighter(self.source.document(), "python")
|
|
1119
|
+
split.addWidget(self.source)
|
|
1120
|
+
self.tabs = QTabWidget()
|
|
1121
|
+
self.flow = FlowchartView()
|
|
1122
|
+
self.tree = SyntaxTreeView()
|
|
1123
|
+
self.trace_view = TraceView()
|
|
1124
|
+
self.data = DataFlowView()
|
|
1125
|
+
self.guide_view = QTextBrowser()
|
|
1126
|
+
self.tabs.addTab(self.flow, tr("Flowchart"))
|
|
1127
|
+
self.tabs.addTab(self.tree, tr("Syntax Tree"))
|
|
1128
|
+
self.tabs.addTab(self.trace_view, tr("Live Trace"))
|
|
1129
|
+
self.tabs.addTab(self.data, tr("Data Flow"))
|
|
1130
|
+
self.tabs.addTab(self.guide_view, tr("Guide"))
|
|
1131
|
+
self.tabs.currentChanged.connect(self._tab_changed)
|
|
1132
|
+
split.addWidget(self.tabs)
|
|
1133
|
+
split.setSizes([320, 940])
|
|
1134
|
+
layout.addWidget(split, 1)
|
|
1135
|
+
|
|
1136
|
+
def retranslate(self) -> None:
|
|
1137
|
+
self.back.setText(tr("← Welcome"))
|
|
1138
|
+
self.ai_button.setText(tr("Enhance guide"))
|
|
1139
|
+
self.edit.setText(tr("Edit code"))
|
|
1140
|
+
self.export.setText(tr("Save guide"))
|
|
1141
|
+
self.function_pov_button.setText(tr("Function POV"))
|
|
1142
|
+
self.function_pov_button.setToolTip(
|
|
1143
|
+
tr("Function POV is available for this Python analysis.")
|
|
1144
|
+
if self.function_pov_supported
|
|
1145
|
+
else tr("Open Function POV to see language support.")
|
|
1146
|
+
)
|
|
1147
|
+
self.tabs.setTabText(0, tr("Flowchart"))
|
|
1148
|
+
self.tabs.setTabText(1, tr("Syntax Tree"))
|
|
1149
|
+
self.tabs.setTabText(2, tr("Live Trace"))
|
|
1150
|
+
self.tabs.setTabText(3, tr("Data Flow"))
|
|
1151
|
+
self.tabs.setTabText(4, tr("Guide"))
|
|
1152
|
+
if self.analysis:
|
|
1153
|
+
self.flow.set_analysis(self.analysis, self.trace if self.language == "python" else None)
|
|
1154
|
+
|
|
1155
|
+
def _tab_changed(self, index: int) -> None:
|
|
1156
|
+
widget = self.tabs.widget(index)
|
|
1157
|
+
if widget is not None:
|
|
1158
|
+
fade_in(widget, 180)
|
|
1159
|
+
|
|
1160
|
+
def set_result(self, result: dict, filename: str, language: str = "python") -> None:
|
|
1161
|
+
self.analysis = result["analysis"]
|
|
1162
|
+
self.trace = result["trace"]
|
|
1163
|
+
self.guide = result["guide"]
|
|
1164
|
+
self.ai_text = ""
|
|
1165
|
+
self.language = language
|
|
1166
|
+
self.function_pov_supported = language == "python"
|
|
1167
|
+
self.function_pov_button.setVisible(self.function_pov_supported)
|
|
1168
|
+
self.function_pov_button.setEnabled(self.function_pov_supported)
|
|
1169
|
+
self.function_pov_button.setToolTip(
|
|
1170
|
+
tr("Function POV is available for this Python analysis.")
|
|
1171
|
+
if self.function_pov_supported
|
|
1172
|
+
else tr("Open Function POV to see language support.")
|
|
1173
|
+
)
|
|
1174
|
+
self.file_label.setText(filename)
|
|
1175
|
+
language_name = LANGUAGE_NAMES.get(language, language.title())
|
|
1176
|
+
self.summary.setText(
|
|
1177
|
+
f"{language_name} · {self.analysis['lineCount']} lines · "
|
|
1178
|
+
f"{len(self.trace.get('steps', []))} trace steps"
|
|
1179
|
+
)
|
|
1180
|
+
self.source_highlighter = CodeHighlighter(self.source.document(), language)
|
|
1181
|
+
self.source.setPlainText(self.analysis.get("source", ""))
|
|
1182
|
+
self.flow.set_analysis(self.analysis, self.trace if language == "python" else None)
|
|
1183
|
+
self.tree.set_analysis(self.analysis)
|
|
1184
|
+
self.trace_view.set_trace(self.trace)
|
|
1185
|
+
self.data.set_analysis(self.analysis, self.trace)
|
|
1186
|
+
self.guide_view.setHtml(guide_html(self.guide, self.analysis, self.ai_text))
|
|
1187
|
+
self.tabs.setCurrentIndex(0)
|
|
1188
|
+
|
|
1189
|
+
def set_ai_text(self, text: str) -> None:
|
|
1190
|
+
self.ai_text = text
|
|
1191
|
+
if self.guide:
|
|
1192
|
+
self.guide_view.setHtml(guide_html(self.guide, self.analysis, self.ai_text))
|
|
1193
|
+
self.tabs.setCurrentIndex(4)
|
|
1194
|
+
|
|
1195
|
+
|
|
1196
|
+
class MainWindow(QMainWindow):
|
|
1197
|
+
def __init__(self):
|
|
1198
|
+
super().__init__()
|
|
1199
|
+
self.settings = QSettings("Prism", "Prism Native")
|
|
1200
|
+
saved_language = str(self.settings.value("ui/language", "en"))
|
|
1201
|
+
_apply_ui_language(saved_language)
|
|
1202
|
+
|
|
1203
|
+
self.setWindowTitle(tr("Prism — code analysis workspace"))
|
|
1204
|
+
self.resize(1400, 900)
|
|
1205
|
+
self.setMinimumSize(980, 680)
|
|
1206
|
+
icon = Path(__file__).resolve().parent.parent / "assets" / "icon.ico"
|
|
1207
|
+
if icon.exists():
|
|
1208
|
+
self.setWindowIcon(QIcon(str(icon)))
|
|
1209
|
+
|
|
1210
|
+
top = QFrame()
|
|
1211
|
+
top.setObjectName("TopBar")
|
|
1212
|
+
top_layout = QHBoxLayout(top)
|
|
1213
|
+
top_layout.setContentsMargins(18, 9, 18, 9)
|
|
1214
|
+
brand = QLabel("prism")
|
|
1215
|
+
brand.setObjectName("Brand")
|
|
1216
|
+
top_layout.addWidget(brand)
|
|
1217
|
+
self.activity = QLabel(tr("CODE WORKSPACE"))
|
|
1218
|
+
self.activity.setObjectName("Tiny")
|
|
1219
|
+
top_layout.addWidget(self.activity)
|
|
1220
|
+
language_label = QLabel(tr("UI language"))
|
|
1221
|
+
language_label.setObjectName("Tiny")
|
|
1222
|
+
top_layout.addWidget(language_label)
|
|
1223
|
+
self.ui_language = QComboBox()
|
|
1224
|
+
for code, name in UI_LANGUAGES:
|
|
1225
|
+
self.ui_language.addItem(name, code)
|
|
1226
|
+
index = self.ui_language.findData(saved_language)
|
|
1227
|
+
self.ui_language.setCurrentIndex(index if index >= 0 else 0)
|
|
1228
|
+
self.ui_language.currentIndexChanged.connect(
|
|
1229
|
+
lambda _index: self.set_ui_language(self.ui_language.currentData())
|
|
1230
|
+
)
|
|
1231
|
+
top_layout.addWidget(self.ui_language)
|
|
1232
|
+
top_layout.addStretch(1)
|
|
1233
|
+
self.ai_button = QPushButton(tr("Connect AI"))
|
|
1234
|
+
self.ai_button.setObjectName("Chip")
|
|
1235
|
+
top_layout.addWidget(self.ai_button)
|
|
1236
|
+
self.language_label = language_label
|
|
1237
|
+
|
|
1238
|
+
container = QWidget()
|
|
1239
|
+
root = QVBoxLayout(container)
|
|
1240
|
+
root.setContentsMargins(0, 0, 0, 0)
|
|
1241
|
+
root.setSpacing(0)
|
|
1242
|
+
root.addWidget(top)
|
|
1243
|
+
self.stack = QStackedWidget()
|
|
1244
|
+
self.welcome = WelcomePage()
|
|
1245
|
+
self.editor_page = EditorPage()
|
|
1246
|
+
self.results = ResultsPage()
|
|
1247
|
+
self.function_pov_page = FunctionPOVPage()
|
|
1248
|
+
self.compare_page = ComparePage()
|
|
1249
|
+
self.stack.addWidget(self.welcome)
|
|
1250
|
+
self.stack.addWidget(self.editor_page)
|
|
1251
|
+
self.stack.addWidget(self.results)
|
|
1252
|
+
self.stack.addWidget(self.function_pov_page)
|
|
1253
|
+
self.stack.addWidget(self.compare_page)
|
|
1254
|
+
root.addWidget(self.stack, 1)
|
|
1255
|
+
self.setCentralWidget(container)
|
|
1256
|
+
self.setStatusBar(QStatusBar())
|
|
1257
|
+
self.statusBar().showMessage(tr("Local · Python"))
|
|
1258
|
+
|
|
1259
|
+
self.current_file = "main.py"
|
|
1260
|
+
self.language_id = "python"
|
|
1261
|
+
self.ai_settings, self.remember_key, self.ai_saved = self._load_ai_settings()
|
|
1262
|
+
self.ai_worker = None
|
|
1263
|
+
self.ai_busy = False
|
|
1264
|
+
self._wire()
|
|
1265
|
+
self._menu()
|
|
1266
|
+
self._update_ai_button()
|
|
1267
|
+
self.show_welcome()
|
|
1268
|
+
|
|
1269
|
+
def _wire(self):
|
|
1270
|
+
self.welcome.editor_button.clicked.connect(self.show_editor)
|
|
1271
|
+
self.welcome.import_button.clicked.connect(self.import_file)
|
|
1272
|
+
self.welcome.example_button.clicked.connect(self.choose_case)
|
|
1273
|
+
self.welcome.compare_button.clicked.connect(self.show_compare)
|
|
1274
|
+
self.welcome.language.currentIndexChanged.connect(
|
|
1275
|
+
lambda _index: self.set_language(self.welcome.language.currentData())
|
|
1276
|
+
)
|
|
1277
|
+
self.editor_page.back.clicked.connect(self.show_welcome)
|
|
1278
|
+
self.editor_page.import_button.clicked.connect(self.import_file)
|
|
1279
|
+
self.editor_page.clear_button.clicked.connect(self.clear_code)
|
|
1280
|
+
self.editor_page.analyze.clicked.connect(self.analyze)
|
|
1281
|
+
self.results.back.clicked.connect(self.show_welcome)
|
|
1282
|
+
self.results.edit.clicked.connect(self.show_editor)
|
|
1283
|
+
self.results.export.clicked.connect(self.save_guide)
|
|
1284
|
+
self.results.ai_button.clicked.connect(self.enhance_guide)
|
|
1285
|
+
self.results.function_pov_button.clicked.connect(self.open_function_pov)
|
|
1286
|
+
self.function_pov_page.backRequested.connect(self.show_results)
|
|
1287
|
+
self.compare_page.back.connect(self.show_welcome)
|
|
1288
|
+
self.ai_button.clicked.connect(self.open_ai_settings)
|
|
1289
|
+
|
|
1290
|
+
def _menu(self):
|
|
1291
|
+
menu = self.menuBar().addMenu(tr("&File"))
|
|
1292
|
+
new_action = QAction(tr("New analysis"), self)
|
|
1293
|
+
new_action.setShortcut("Ctrl+N")
|
|
1294
|
+
new_action.triggered.connect(self.show_editor)
|
|
1295
|
+
open_action = QAction(tr("Open Python file…"), self)
|
|
1296
|
+
open_action.setShortcut("Ctrl+O")
|
|
1297
|
+
open_action.triggered.connect(self.import_file)
|
|
1298
|
+
save_action = QAction(tr("Save guide…"), self)
|
|
1299
|
+
save_action.setShortcut("Ctrl+S")
|
|
1300
|
+
save_action.triggered.connect(self.save_guide)
|
|
1301
|
+
quit_action = QAction(tr("Quit"), self)
|
|
1302
|
+
quit_action.setShortcut("Ctrl+Q")
|
|
1303
|
+
quit_action.triggered.connect(self.close)
|
|
1304
|
+
menu.addActions([new_action, open_action, save_action])
|
|
1305
|
+
menu.addSeparator()
|
|
1306
|
+
menu.addAction(quit_action)
|
|
1307
|
+
view = self.menuBar().addMenu(tr("&View"))
|
|
1308
|
+
full = QAction(tr("Toggle full screen"), self)
|
|
1309
|
+
full.setShortcut("F11")
|
|
1310
|
+
full.triggered.connect(self.toggle_fullscreen)
|
|
1311
|
+
view.addAction(full)
|
|
1312
|
+
tools = self.menuBar().addMenu(tr("&Tools"))
|
|
1313
|
+
compare_action = QAction(tr("Compare two versions…"), self)
|
|
1314
|
+
compare_action.setShortcut("Ctrl+D")
|
|
1315
|
+
compare_action.triggered.connect(self.show_compare)
|
|
1316
|
+
tools.addAction(compare_action)
|
|
1317
|
+
tools.addSeparator()
|
|
1318
|
+
ai_action = QAction(tr("Connect AI…"), self)
|
|
1319
|
+
ai_action.triggered.connect(self.open_ai_settings)
|
|
1320
|
+
tools.addAction(ai_action)
|
|
1321
|
+
enhance_action = QAction(tr("Enhance current guide…"), self)
|
|
1322
|
+
enhance_action.setShortcut("Ctrl+E")
|
|
1323
|
+
enhance_action.triggered.connect(self.enhance_guide)
|
|
1324
|
+
tools.addAction(enhance_action)
|
|
1325
|
+
help_menu = self.menuBar().addMenu(tr("&Help"))
|
|
1326
|
+
about_action = QAction(tr("About Prism"), self)
|
|
1327
|
+
about_action.triggered.connect(self.about)
|
|
1328
|
+
help_menu.addAction(about_action)
|
|
1329
|
+
|
|
1330
|
+
self.menus = {
|
|
1331
|
+
"file": (menu, "&File"),
|
|
1332
|
+
"view": (view, "&View"),
|
|
1333
|
+
"tools": (tools, "&Tools"),
|
|
1334
|
+
"help": (help_menu, "&Help"),
|
|
1335
|
+
}
|
|
1336
|
+
self.actions = {
|
|
1337
|
+
"new": (new_action, "New analysis"),
|
|
1338
|
+
"open": (open_action, "Open Python file…"),
|
|
1339
|
+
"save": (save_action, "Save guide…"),
|
|
1340
|
+
"quit": (quit_action, "Quit"),
|
|
1341
|
+
"full": (full, "Toggle full screen"),
|
|
1342
|
+
"compare": (compare_action, "Compare two versions…"),
|
|
1343
|
+
"ai": (ai_action, "Connect AI…"),
|
|
1344
|
+
"enhance": (enhance_action, "Enhance current guide…"),
|
|
1345
|
+
"about": (about_action, "About Prism"),
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
def retranslate(self) -> None:
|
|
1349
|
+
"""Re-apply every string after the interface language changed."""
|
|
1350
|
+
self.setWindowTitle(tr("Prism — code analysis workspace"))
|
|
1351
|
+
self.activity.setText(tr("CODE WORKSPACE"))
|
|
1352
|
+
self.language_label.setText(tr("UI language"))
|
|
1353
|
+
self.ai_button.setText(tr("Connect AI"))
|
|
1354
|
+
for widget, key in self.menus.values():
|
|
1355
|
+
widget.setTitle(tr(key))
|
|
1356
|
+
for widget, key in self.actions.values():
|
|
1357
|
+
widget.setText(tr(key))
|
|
1358
|
+
self.welcome.retranslate()
|
|
1359
|
+
self.editor_page.retranslate()
|
|
1360
|
+
self.results.retranslate()
|
|
1361
|
+
self.function_pov_page.retranslate()
|
|
1362
|
+
self.compare_page.retranslate()
|
|
1363
|
+
self.statusBar().showMessage(tr("Local · Python"))
|
|
1364
|
+
|
|
1365
|
+
def set_ui_language(self, code: str) -> None:
|
|
1366
|
+
code = code or "en"
|
|
1367
|
+
_apply_ui_language(code)
|
|
1368
|
+
self.settings.setValue("ui/language", code)
|
|
1369
|
+
index = self.ui_language.findData(code)
|
|
1370
|
+
if index >= 0 and self.ui_language.currentIndex() != index:
|
|
1371
|
+
self.ui_language.blockSignals(True)
|
|
1372
|
+
self.ui_language.setCurrentIndex(index)
|
|
1373
|
+
self.ui_language.blockSignals(False)
|
|
1374
|
+
self.retranslate()
|
|
1375
|
+
|
|
1376
|
+
def show_welcome(self):
|
|
1377
|
+
self.stack.setCurrentWidget(self.welcome)
|
|
1378
|
+
fade_in(self.welcome, 220)
|
|
1379
|
+
self.welcome.play_intro()
|
|
1380
|
+
self.statusBar().showMessage(tr("Local · Python / JavaScript / TypeScript / Java / C++ / C"))
|
|
1381
|
+
|
|
1382
|
+
def show_editor(self):
|
|
1383
|
+
self.stack.setCurrentWidget(self.editor_page)
|
|
1384
|
+
fade_in(self.editor_page, 200)
|
|
1385
|
+
self.editor_page.editor.setFocus()
|
|
1386
|
+
self.statusBar().showMessage(f"{self.current_file} · {LANGUAGE_NAMES[self.language_id]}")
|
|
1387
|
+
|
|
1388
|
+
def show_compare(self):
|
|
1389
|
+
index = self.compare_page.language_box.findData(self.language_id)
|
|
1390
|
+
if index >= 0 and self.compare_page.language_box.currentIndex() != index:
|
|
1391
|
+
self.compare_page.language_box.blockSignals(True)
|
|
1392
|
+
self.compare_page.language_box.setCurrentIndex(index)
|
|
1393
|
+
self.compare_page.language_box.blockSignals(False)
|
|
1394
|
+
self.compare_page.language = self.language_id
|
|
1395
|
+
self.stack.setCurrentWidget(self.compare_page)
|
|
1396
|
+
fade_in(self.compare_page, 200)
|
|
1397
|
+
self.statusBar().showMessage(tr("Compare · structural diff between two versions"))
|
|
1398
|
+
|
|
1399
|
+
def open_function_pov(self) -> None:
|
|
1400
|
+
if not self.results.analysis:
|
|
1401
|
+
return
|
|
1402
|
+
if self.results.function_pov_supported:
|
|
1403
|
+
self.function_pov_page.set_source(
|
|
1404
|
+
self.results.analysis.get("source", ""),
|
|
1405
|
+
self.results.file_label.text(),
|
|
1406
|
+
)
|
|
1407
|
+
else:
|
|
1408
|
+
language = LANGUAGE_NAMES.get(self.results.language, self.results.language.title())
|
|
1409
|
+
self.function_pov_page.set_unsupported_language(language)
|
|
1410
|
+
self.stack.setCurrentWidget(self.function_pov_page)
|
|
1411
|
+
fade_in(self.function_pov_page, 220)
|
|
1412
|
+
self.statusBar().showMessage(tr("Function POV · safe Python simulation"))
|
|
1413
|
+
|
|
1414
|
+
def show_results(self) -> None:
|
|
1415
|
+
if not self.results.analysis:
|
|
1416
|
+
self.show_welcome()
|
|
1417
|
+
return
|
|
1418
|
+
self.stack.setCurrentWidget(self.results)
|
|
1419
|
+
fade_in(self.results, 180)
|
|
1420
|
+
self.statusBar().showMessage(
|
|
1421
|
+
f"{self.results.file_label.text()} · "
|
|
1422
|
+
f"{LANGUAGE_NAMES.get(self.results.language, self.results.language.title())}"
|
|
1423
|
+
)
|
|
1424
|
+
|
|
1425
|
+
def set_language(self, language_id: str) -> None:
|
|
1426
|
+
if language_id not in LANGUAGE_NAMES:
|
|
1427
|
+
language_id = "python"
|
|
1428
|
+
self.language_id = language_id
|
|
1429
|
+
index = self.welcome.language.findData(language_id)
|
|
1430
|
+
if index >= 0 and self.welcome.language.currentIndex() != index:
|
|
1431
|
+
self.welcome.language.blockSignals(True)
|
|
1432
|
+
self.welcome.language.setCurrentIndex(index)
|
|
1433
|
+
self.welcome.language.blockSignals(False)
|
|
1434
|
+
ext = FILE_EXTENSIONS.get(language_id, ".txt")
|
|
1435
|
+
if not self.current_file or self.current_file in {"main.py", "main.js", "main.ts", "main.java", "main.cpp", "main.c"}:
|
|
1436
|
+
self.current_file = "main" + ext
|
|
1437
|
+
self.editor_page.file_label.setText(self.current_file)
|
|
1438
|
+
self.editor_page.editor.set_language(language_id)
|
|
1439
|
+
self.statusBar().showMessage(f"{self.current_file} · {LANGUAGE_NAMES[language_id]}")
|
|
1440
|
+
|
|
1441
|
+
def _cases(self) -> dict[str, str]:
|
|
1442
|
+
if self.language_id == "python":
|
|
1443
|
+
return CASES
|
|
1444
|
+
if self.language_id in {"javascript", "typescript"}:
|
|
1445
|
+
return JS_CASES
|
|
1446
|
+
return COMPILED_CASES.get(self.language_id, {})
|
|
1447
|
+
|
|
1448
|
+
def choose_case(self):
|
|
1449
|
+
menu = QMenu(self)
|
|
1450
|
+
for name in self._cases():
|
|
1451
|
+
action = menu.addAction(name)
|
|
1452
|
+
action.triggered.connect(lambda _=False, n=name: self.load_case(n))
|
|
1453
|
+
menu.exec(self.welcome.example_button.mapToGlobal(self.welcome.example_button.rect().bottomLeft()))
|
|
1454
|
+
|
|
1455
|
+
def load_case(self, name: str) -> None:
|
|
1456
|
+
cases = self._cases()
|
|
1457
|
+
if name not in cases:
|
|
1458
|
+
return
|
|
1459
|
+
ext = FILE_EXTENSIONS.get(self.language_id, ".py")
|
|
1460
|
+
self.current_file = name.lower().replace(" ", "-") + ext
|
|
1461
|
+
self.editor_page.editor.set_language(self.language_id)
|
|
1462
|
+
self.editor_page.editor.setPlainText(cases[name])
|
|
1463
|
+
self.editor_page.file_label.setText(self.current_file)
|
|
1464
|
+
self.show_editor()
|
|
1465
|
+
|
|
1466
|
+
def clear_code(self):
|
|
1467
|
+
self.editor_page.editor.clear()
|
|
1468
|
+
self.current_file = "main.py"
|
|
1469
|
+
self.editor_page.file_label.setText("main.py")
|
|
1470
|
+
self.editor_page.meta.setText(tr("Blank document"))
|
|
1471
|
+
|
|
1472
|
+
def import_file(self):
|
|
1473
|
+
path, _ = QFileDialog.getOpenFileName(
|
|
1474
|
+
self, tr("Import source file"), "",
|
|
1475
|
+
tr("Code files") + " (*.py *.js *.jsx *.ts *.tsx *.java *.cpp *.cc *.cxx *.c *.h *.hpp);;"
|
|
1476
|
+
"Python (*.py);;JavaScript (*.js *.jsx);;TypeScript (*.ts *.tsx);;"
|
|
1477
|
+
"Java (*.java);;C/C++ (*.c *.h *.cpp *.cc *.cxx *.hpp);;" + tr("All files") + " (*)"
|
|
1478
|
+
)
|
|
1479
|
+
if not path:
|
|
1480
|
+
return
|
|
1481
|
+
try:
|
|
1482
|
+
data = Path(path).read_text(encoding="utf-8", errors="replace")
|
|
1483
|
+
except OSError as error:
|
|
1484
|
+
QMessageBox.warning(self, tr("Could not read file"), str(error))
|
|
1485
|
+
return
|
|
1486
|
+
if len(data) > MAX_SOURCE:
|
|
1487
|
+
QMessageBox.warning(
|
|
1488
|
+
self, tr("File too large"),
|
|
1489
|
+
tr("Source files must stay under 60,000 characters."),
|
|
1490
|
+
)
|
|
1491
|
+
return
|
|
1492
|
+
suffix = Path(path).suffix.lower()
|
|
1493
|
+
if suffix in {".js", ".jsx", ".mjs", ".cjs"}:
|
|
1494
|
+
self.set_language("javascript")
|
|
1495
|
+
elif suffix in {".ts", ".tsx"}:
|
|
1496
|
+
self.set_language("typescript")
|
|
1497
|
+
elif suffix == ".py":
|
|
1498
|
+
self.set_language("python")
|
|
1499
|
+
elif suffix == ".java":
|
|
1500
|
+
self.set_language("java")
|
|
1501
|
+
elif suffix in {".cpp", ".cc", ".cxx", ".hpp", ".h"}:
|
|
1502
|
+
self.set_language("cpp")
|
|
1503
|
+
elif suffix == ".c":
|
|
1504
|
+
self.set_language("c")
|
|
1505
|
+
self.current_file = Path(path).name
|
|
1506
|
+
self.editor_page.file_label.setText(self.current_file)
|
|
1507
|
+
self.editor_page.editor.setPlainText(data)
|
|
1508
|
+
self.editor_page.meta.setText(f"{self.current_file} · {len(data.splitlines())} lines")
|
|
1509
|
+
self.show_editor()
|
|
1510
|
+
|
|
1511
|
+
def analyze(self):
|
|
1512
|
+
source = self.editor_page.editor.toPlainText()
|
|
1513
|
+
if not source.strip():
|
|
1514
|
+
QMessageBox.information(self, "Add some code", "Write or import Python code first.")
|
|
1515
|
+
return
|
|
1516
|
+
if len(source) > MAX_SOURCE:
|
|
1517
|
+
QMessageBox.warning(self, "Too large", "Keep the snippet under 60,000 characters.")
|
|
1518
|
+
return
|
|
1519
|
+
QApplication.setOverrideCursor(Qt.CursorShape.WaitCursor)
|
|
1520
|
+
try:
|
|
1521
|
+
if self.language_id == "python":
|
|
1522
|
+
result = analyze_python(source)
|
|
1523
|
+
elif self.language_id in {"javascript", "typescript"}:
|
|
1524
|
+
result = analyze_javascript(source, self.language_id)
|
|
1525
|
+
else:
|
|
1526
|
+
result = analyze_compiled(source, self.language_id)
|
|
1527
|
+
except ValueError as error:
|
|
1528
|
+
QMessageBox.warning(self, "Syntax error", str(error))
|
|
1529
|
+
return
|
|
1530
|
+
except Exception as error:
|
|
1531
|
+
QMessageBox.critical(self, "Analysis failed", str(error))
|
|
1532
|
+
return
|
|
1533
|
+
finally:
|
|
1534
|
+
QApplication.restoreOverrideCursor()
|
|
1535
|
+
self.results.set_result(result, self.current_file, self.language_id)
|
|
1536
|
+
self.stack.setCurrentWidget(self.results)
|
|
1537
|
+
fade_in(self.results, 220)
|
|
1538
|
+
self.statusBar().showMessage(
|
|
1539
|
+
f"{self.current_file} · {LANGUAGE_NAMES[self.language_id]} · "
|
|
1540
|
+
f"{result['analysis']['metrics']['codeLines']} code lines"
|
|
1541
|
+
)
|
|
1542
|
+
|
|
1543
|
+
def _load_ai_settings(self) -> tuple[AISettings, bool, bool]:
|
|
1544
|
+
provider = str(self.settings.value("ai/provider", "openai"))
|
|
1545
|
+
if provider not in PROVIDERS:
|
|
1546
|
+
provider = "openai"
|
|
1547
|
+
remember = str(self.settings.value("ai/remember", "false")).lower() == "true"
|
|
1548
|
+
saved = str(self.settings.value("ai/saved", "false")).lower() == "true"
|
|
1549
|
+
defaults = PROVIDERS[provider]
|
|
1550
|
+
return (
|
|
1551
|
+
AISettings(
|
|
1552
|
+
provider=provider,
|
|
1553
|
+
base_url=str(self.settings.value("ai/base", defaults["base"])),
|
|
1554
|
+
model=str(self.settings.value("ai/model", defaults["model"])),
|
|
1555
|
+
api_key=str(self.settings.value("ai/key", "")) if remember else "",
|
|
1556
|
+
),
|
|
1557
|
+
remember,
|
|
1558
|
+
saved,
|
|
1559
|
+
)
|
|
1560
|
+
|
|
1561
|
+
def _save_ai_settings(self) -> None:
|
|
1562
|
+
settings = self.ai_settings
|
|
1563
|
+
self.settings.setValue("ai/provider", settings.provider)
|
|
1564
|
+
self.settings.setValue("ai/base", settings.base_url)
|
|
1565
|
+
self.settings.setValue("ai/model", settings.model)
|
|
1566
|
+
self.settings.setValue("ai/saved", "true")
|
|
1567
|
+
self.settings.setValue("ai/remember", "true" if self.remember_key else "false")
|
|
1568
|
+
if self.remember_key:
|
|
1569
|
+
self.settings.setValue("ai/key", settings.api_key)
|
|
1570
|
+
else:
|
|
1571
|
+
self.settings.remove("ai/key")
|
|
1572
|
+
self.settings.sync()
|
|
1573
|
+
|
|
1574
|
+
def _update_ai_button(self) -> None:
|
|
1575
|
+
configured = self.ai_saved and self.ai_settings.configured
|
|
1576
|
+
self.ai_button.setText("AI ready" if configured else "Connect AI")
|
|
1577
|
+
self.ai_button.setToolTip(
|
|
1578
|
+
f"{self.ai_settings.provider_name()} · {self.ai_settings.model}"
|
|
1579
|
+
if configured else "Configure an optional AI provider"
|
|
1580
|
+
)
|
|
1581
|
+
|
|
1582
|
+
def open_ai_settings(self) -> None:
|
|
1583
|
+
dialog = AISettingsDialog(self.ai_settings, self.remember_key, self)
|
|
1584
|
+
if dialog.exec() != QDialog.DialogCode.Accepted:
|
|
1585
|
+
return
|
|
1586
|
+
self.ai_settings = dialog.settings
|
|
1587
|
+
self.remember_key = dialog.remember_value
|
|
1588
|
+
self.ai_saved = True
|
|
1589
|
+
self._save_ai_settings()
|
|
1590
|
+
self._update_ai_button()
|
|
1591
|
+
self.statusBar().showMessage(
|
|
1592
|
+
f"AI configured · {self.ai_settings.provider_name()} · {self.ai_settings.model}"
|
|
1593
|
+
)
|
|
1594
|
+
|
|
1595
|
+
def _ai_prompt(self) -> tuple[str, list[dict[str, str]]]:
|
|
1596
|
+
result = self.results
|
|
1597
|
+
analysis = result.analysis or {}
|
|
1598
|
+
guide = result.guide or {}
|
|
1599
|
+
trace = result.trace or {}
|
|
1600
|
+
source = analysis.get("source", "")
|
|
1601
|
+
guide_summary = guide.get("summary", "")
|
|
1602
|
+
concepts = ", ".join(item.get("term", "") for item in guide.get("concepts", []))
|
|
1603
|
+
trace_summary = "\n".join(
|
|
1604
|
+
f"L{step.get('line')}: {step.get('title')}" for step in trace.get("steps", [])[:18]
|
|
1605
|
+
)
|
|
1606
|
+
language_name = LANGUAGE_NAMES.get(self.language_id, "programming")
|
|
1607
|
+
system = (
|
|
1608
|
+
f"You are a patient {language_name} tutor. Explain code for a complete beginner. "
|
|
1609
|
+
"Be concrete, refer to line numbers, and do not invent execution values."
|
|
1610
|
+
)
|
|
1611
|
+
user = (
|
|
1612
|
+
f"Explain this {language_name} program in 3-5 short paragraphs for a beginner.\n"
|
|
1613
|
+
"Cover: what it does, the key control flow, and one likely mistake.\n\n"
|
|
1614
|
+
f"Source:\n```{self.language_id}\n{source}\n```\n\n"
|
|
1615
|
+
f"Local summary: {guide_summary}\n"
|
|
1616
|
+
f"Concepts: {concepts}\n"
|
|
1617
|
+
f"Trace (selected):\n{trace_summary}\n\n"
|
|
1618
|
+
"Return plain prose with no code fences."
|
|
1619
|
+
)
|
|
1620
|
+
return system, [{"role": "user", "content": user}]
|
|
1621
|
+
|
|
1622
|
+
def enhance_guide(self) -> None:
|
|
1623
|
+
if not self.results.guide:
|
|
1624
|
+
QMessageBox.information(self, "No guide yet", "Run an analysis first.")
|
|
1625
|
+
return
|
|
1626
|
+
if not self.ai_saved or not self.ai_settings.configured:
|
|
1627
|
+
self.open_ai_settings()
|
|
1628
|
+
if not self.ai_saved or not self.ai_settings.configured:
|
|
1629
|
+
return
|
|
1630
|
+
if self.ai_busy:
|
|
1631
|
+
return
|
|
1632
|
+
self.ai_busy = True
|
|
1633
|
+
self.results.ai_button.setEnabled(False)
|
|
1634
|
+
self.results.ai_button.setText("Enhancing…")
|
|
1635
|
+
system, messages = self._ai_prompt()
|
|
1636
|
+
settings = self.ai_settings
|
|
1637
|
+
self.ai_worker = AIWorker(lambda: complete(settings, system, messages), self)
|
|
1638
|
+
self.ai_worker.succeeded.connect(self._ai_done)
|
|
1639
|
+
self.ai_worker.failed.connect(self._ai_failed)
|
|
1640
|
+
self.ai_worker.finished.connect(self._ai_finished)
|
|
1641
|
+
self.ai_worker.start()
|
|
1642
|
+
self.statusBar().showMessage("Asking the configured AI for a second explanation…")
|
|
1643
|
+
|
|
1644
|
+
def _ai_done(self, text: str) -> None:
|
|
1645
|
+
self.results.set_ai_text(text)
|
|
1646
|
+
self.statusBar().showMessage("AI explanation added to the guide.")
|
|
1647
|
+
|
|
1648
|
+
def _ai_failed(self, error: str) -> None:
|
|
1649
|
+
QMessageBox.warning(self, "AI request failed", error)
|
|
1650
|
+
self.statusBar().showMessage("AI request failed; the local guide is unchanged.")
|
|
1651
|
+
|
|
1652
|
+
def _ai_finished(self) -> None:
|
|
1653
|
+
self.ai_busy = False
|
|
1654
|
+
self.results.ai_button.setEnabled(True)
|
|
1655
|
+
self.results.ai_button.setText("Enhance guide")
|
|
1656
|
+
|
|
1657
|
+
def save_guide(self):
|
|
1658
|
+
if not self.results.guide:
|
|
1659
|
+
QMessageBox.information(self, "No guide yet", "Run an analysis first.")
|
|
1660
|
+
return
|
|
1661
|
+
path, _ = QFileDialog.getSaveFileName(self, "Save guide", "prism-guide.md", "Markdown (*.md)")
|
|
1662
|
+
if not path:
|
|
1663
|
+
return
|
|
1664
|
+
guide = self.results.guide
|
|
1665
|
+
lines = [f"# {guide.get('headline', 'Prism guide')}", "", guide.get("summary", ""), "", "## Overview"]
|
|
1666
|
+
lines += guide.get("overview", {}).get("paragraphs", [])
|
|
1667
|
+
lines += ["", "## Walkthrough"]
|
|
1668
|
+
for item in guide.get("walkthrough", []):
|
|
1669
|
+
lines += [f"### {item.get('title', '')}", item.get("body", "")]
|
|
1670
|
+
lines += ["", "## Line by line"]
|
|
1671
|
+
lines += [f"- **Line {n.get('line')}** `{n.get('code', '')}` — {n.get('note', '')}" for n in guide.get("lineNotes", [])]
|
|
1672
|
+
if getattr(self.results, "ai_text", ""):
|
|
1673
|
+
lines += ["", "## AI explanation", self.results.ai_text]
|
|
1674
|
+
Path(path).write_text("\n".join(lines), encoding="utf-8")
|
|
1675
|
+
self.statusBar().showMessage(f"Guide saved to {path}")
|
|
1676
|
+
|
|
1677
|
+
def toggle_fullscreen(self):
|
|
1678
|
+
self.showNormal() if self.isFullScreen() else self.showFullScreen()
|
|
1679
|
+
|
|
1680
|
+
def about(self):
|
|
1681
|
+
QMessageBox.about(
|
|
1682
|
+
self, "About Prism",
|
|
1683
|
+
"Prism 2.0 — pure Python edition\n\n"
|
|
1684
|
+
"A local-first code analysis workspace for Python, JavaScript and TypeScript.\n"
|
|
1685
|
+
"Built with PySide6. No HTML, CSS or JavaScript application code is used.",
|
|
1686
|
+
)
|
|
1687
|
+
|
|
1688
|
+
|
|
1689
|
+
def main() -> int:
|
|
1690
|
+
app = QApplication(sys.argv)
|
|
1691
|
+
app.setApplicationName(APP_NAME)
|
|
1692
|
+
app.setStyleSheet(STYLE)
|
|
1693
|
+
window = MainWindow()
|
|
1694
|
+
window.show()
|
|
1695
|
+
if "--demo" in sys.argv:
|
|
1696
|
+
window.load_case("Loop and total")
|
|
1697
|
+
window.analyze()
|
|
1698
|
+
if "--capture" in sys.argv:
|
|
1699
|
+
index = sys.argv.index("--capture")
|
|
1700
|
+
target = Path(sys.argv[index + 1]) if len(sys.argv) > index + 1 else Path("prism-native.png")
|
|
1701
|
+
def capture() -> None:
|
|
1702
|
+
window.grab().save(str(target))
|
|
1703
|
+
app.quit()
|
|
1704
|
+
QTimer.singleShot(900, capture)
|
|
1705
|
+
return app.exec()
|
|
1706
|
+
|
|
1707
|
+
|
|
1708
|
+
if __name__ == "__main__":
|
|
1709
|
+
raise SystemExit(main())
|