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.
python_app/compare.py ADDED
@@ -0,0 +1,685 @@
1
+ """Compare page: two versions of one file, side by side, structure by structure.
2
+
3
+ This is the UI half; the diff itself lives in :mod:`python_app.compare_engine`,
4
+ which adapts Prism's analysis trees into the ``structscope`` symbol model.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import sys
10
+ from pathlib import Path
11
+ from typing import Any, Callable, Dict, List, Optional
12
+
13
+ from PySide6.QtCore import (
14
+ QEasingCurve,
15
+ QPointF,
16
+ QRectF,
17
+ QVariantAnimation,
18
+ Qt,
19
+ Signal,
20
+ )
21
+ from PySide6.QtGui import QColor, QFont, QPainter, QPainterPath, QPen
22
+ from PySide6.QtWidgets import (
23
+ QAbstractItemView,
24
+ QComboBox,
25
+ QFileDialog,
26
+ QFrame,
27
+ QGraphicsDropShadowEffect,
28
+ QGraphicsPathItem,
29
+ QGraphicsScene,
30
+ QGraphicsSimpleTextItem,
31
+ QGraphicsView,
32
+ QHBoxLayout,
33
+ QHeaderView,
34
+ QLabel,
35
+ QPushButton,
36
+ QSplitter,
37
+ QTableWidget,
38
+ QTableWidgetItem,
39
+ QVBoxLayout,
40
+ QWidget,
41
+ )
42
+
43
+ try:
44
+ from python_app.compare_engine import (
45
+ ENGINE_ERROR,
46
+ FILE_EXTENSIONS,
47
+ LANGUAGE_LABELS,
48
+ STATUS_COLORS,
49
+ STATUS_FILL,
50
+ aligned_rows,
51
+ compare_sources,
52
+ describe,
53
+ )
54
+ from python_app.i18n import tr
55
+ except ImportError: # direct script execution
56
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
57
+ from python_app.compare_engine import (
58
+ ENGINE_ERROR,
59
+ FILE_EXTENSIONS,
60
+ LANGUAGE_LABELS,
61
+ STATUS_COLORS,
62
+ STATUS_FILL,
63
+ aligned_rows,
64
+ compare_sources,
65
+ describe,
66
+ )
67
+ from python_app.i18n import tr
68
+
69
+ DIM_OPACITY = 0.22
70
+ HOVER_DIM_OPACITY = 0.42
71
+ ENGINE_HINT = (
72
+ "structscope is not installed \u2014 see README, section \u201cCompare two versions\u201d"
73
+ )
74
+ FILTERS = [
75
+ ("all", "All symbols"),
76
+ ("added", "Added"),
77
+ ("removed", "Removed"),
78
+ ("modified", "Modified"),
79
+ ("moved", "Moved"),
80
+ ("unchanged", "Unchanged"),
81
+ ]
82
+
83
+
84
+ class NodeCard(QGraphicsPathItem):
85
+ """One symbol card. Hovering lifts it and gives it a coloured glow.
86
+
87
+ QGraphicsPathItem is not a QObject, so it cannot declare Qt signals; the
88
+ view installs plain callables instead.
89
+ """
90
+
91
+ HOVER_SCALE = 1.08
92
+
93
+ def __init__(
94
+ self, width: float, height: float, fill: QColor, border: QColor, pair_id: str
95
+ ):
96
+ super().__init__()
97
+ self.pair_id = pair_id
98
+ self.on_enter: Optional[Callable[["NodeCard"], None]] = None
99
+ self.on_leave: Optional[Callable[["NodeCard"], None]] = None
100
+ self._fill = QColor(fill)
101
+ self._border = QColor(border)
102
+ self._glow: Optional[QGraphicsDropShadowEffect] = None
103
+ path = QPainterPath()
104
+ path.addRoundedRect(QRectF(0, 0, width, height), 5, 5)
105
+ self.setPath(path)
106
+ self.setBrush(QColor(fill))
107
+ self.setPen(QPen(QColor(border), 1.0))
108
+ self.setTransformOriginPoint(width / 2, height / 2)
109
+ self.setAcceptHoverEvents(True)
110
+ self.setCursor(Qt.CursorShape.PointingHandCursor)
111
+ self.setData(0, pair_id)
112
+ # QGraphicsItem is not a QObject, so the animation cannot be parented to
113
+ # the card; the card holds the only reference and stops it when dropped.
114
+ self._animation = QVariantAnimation()
115
+ self._animation.setDuration(140)
116
+ self._animation.setEasingCurve(QEasingCurve(QEasingCurve.Type.OutCubic))
117
+ self._animation.valueChanged.connect(self._animate_scale)
118
+
119
+ def hoverEnterEvent(self, event) -> None:
120
+ self._zoom(self.HOVER_SCALE)
121
+ if self.on_enter is not None:
122
+ self.on_enter(self)
123
+ super().hoverEnterEvent(event)
124
+
125
+ def hoverLeaveEvent(self, event) -> None:
126
+ self._zoom(1.0)
127
+ if self.on_leave is not None:
128
+ self.on_leave(self)
129
+ super().hoverLeaveEvent(event)
130
+
131
+ def _zoom(self, target: float) -> None:
132
+ self._animation.stop()
133
+ self._animation.setStartValue(self.scale())
134
+ self._animation.setEndValue(target)
135
+ self._animation.start()
136
+
137
+ def stop_animation(self) -> None:
138
+ self._animation.stop()
139
+ self._animation.deleteLater()
140
+
141
+ def _animate_scale(self, value) -> None:
142
+ try:
143
+ self.setScale(float(value))
144
+ except RuntimeError: # the card was deleted while the tick was queued
145
+ self._animation.stop()
146
+
147
+ def apply_glow(self, enabled: bool) -> None:
148
+ border = QColor(self._border)
149
+ if enabled:
150
+ border.setAlpha(255)
151
+ self.setPen(QPen(border, 2.0))
152
+ self.setBrush(self._fill.lighter(128))
153
+ self.setZValue(4)
154
+ halo = QGraphicsDropShadowEffect()
155
+ halo.setBlurRadius(28)
156
+ glow = QColor(self._border)
157
+ glow.setAlpha(210)
158
+ halo.setColor(glow)
159
+ halo.setOffset(0, 0)
160
+ self.setGraphicsEffect(halo)
161
+ self._glow = halo
162
+ else:
163
+ self.setPen(QPen(border, 1.0))
164
+ self.setBrush(QColor(self._fill))
165
+ self.setZValue(0)
166
+ if self._glow is not None:
167
+ self.setGraphicsEffect(None)
168
+ self._glow = None
169
+
170
+ def child(self, item):
171
+ """Parent a label to the card so it scales and fades with it."""
172
+ item.setParentItem(self)
173
+ item.setData(0, self.pair_id)
174
+ return item
175
+
176
+
177
+ class CompareView(QGraphicsView):
178
+ """Two columns of cards, one per symbol, joined wherever a symbol matched."""
179
+
180
+ pairSelected = Signal(object)
181
+
182
+ def __init__(self, parent: Optional[QWidget] = None):
183
+ super().__init__(parent)
184
+ self.setRenderHints(
185
+ QPainter.RenderHint.Antialiasing | QPainter.RenderHint.TextAntialiasing
186
+ )
187
+ self.setBackgroundBrush(QColor("#1c1f24"))
188
+ self.setFrameShape(QFrame.Shape.NoFrame)
189
+ self.setDragMode(QGraphicsView.DragMode.ScrollHandDrag)
190
+ self.setMouseTracking(True)
191
+ self._scene = QGraphicsScene(self)
192
+ self.setScene(self._scene)
193
+ self._cards: Dict[str, List[NodeCard]] = {}
194
+ self._links: Dict[str, QGraphicsPathItem] = {}
195
+ self._hovered: Optional[NodeCard] = None
196
+ self._result = None
197
+ self._geometry: Dict[str, Any] = {}
198
+ self._filter = "all"
199
+ self.show_placeholder()
200
+
201
+ # -- content -----------------------------------------------------------
202
+
203
+ def _release_cards(self) -> None:
204
+ """Stop hover animations before their cards are deleted with the scene."""
205
+ for cards in self._cards.values():
206
+ for card in cards:
207
+ card.stop_animation()
208
+ self._cards = {}
209
+ self._links = {}
210
+ self._hovered = None
211
+
212
+ def show_placeholder(self) -> None:
213
+ self._release_cards()
214
+ self._scene.clear()
215
+ self._result = None
216
+ self._geometry = {}
217
+ self._scene.setSceneRect(QRectF(0, 0, 980, 460))
218
+ hint = self._scene.addSimpleText(
219
+ "Choose a language, then a before file and an after file."
220
+ )
221
+ hint.setBrush(QColor("#6f7885"))
222
+ hint.setFont(QFont("Segoe UI", 12))
223
+ hint.setPos(44, 200)
224
+ sub = self._scene.addSimpleText(
225
+ "Prism compares the symbols it finds \u2014 classes, functions and methods."
226
+ )
227
+ sub.setBrush(QColor("#59606b"))
228
+ sub.setFont(QFont("Segoe UI", 9))
229
+ sub.setPos(44, 238)
230
+
231
+ def set_result(self, result: Any) -> None:
232
+ self._result = result
233
+ self._release_cards()
234
+ self._scene.clear()
235
+ # Imported lazily: the layout engine is part of structscope.
236
+ from structscope.layout import compute as layout_diff
237
+
238
+ geometry = layout_diff(result)
239
+ self._geometry = geometry
240
+ self._scene.setSceneRect(QRectF(0, 0, geometry["width"], geometry["height"]))
241
+
242
+ for node in geometry["old_nodes"]:
243
+ self._draw_node(node, "left")
244
+ for node in geometry["new_nodes"]:
245
+ self._draw_node(node, "right")
246
+
247
+ for pair in result.pairs:
248
+ box = geometry["boxes"].get(pair.id or "")
249
+ if not box or "old" not in box or "new" not in box:
250
+ continue
251
+ self._draw_link(box["old"], box["new"], pair)
252
+
253
+ self._label(6, "BEFORE")
254
+ self._label(geometry["new_x"] + 6, "AFTER")
255
+ self.fitInView(
256
+ self._scene.itemsBoundingRect().adjusted(-20, -20, 24, 24),
257
+ Qt.AspectRatioMode.KeepAspectRatio,
258
+ )
259
+ self._apply_visuals()
260
+
261
+ def apply_filter(self, mode: str) -> None:
262
+ self._filter = mode
263
+ self._apply_visuals()
264
+
265
+ def _apply_visuals(self) -> None:
266
+ """Dim what the filter or the hover hides; glow the pair under the cursor."""
267
+ if self._result is None:
268
+ return
269
+ hover_id = self._hovered.pair_id if self._hovered is not None else None
270
+ for pair in self._result.pairs:
271
+ pair_id = pair.id or ""
272
+ matched = self._filter == "all" or pair.status.value == self._filter
273
+ related = hover_id is None or pair_id == hover_id
274
+ opacity = 1.0
275
+ if not matched:
276
+ opacity = DIM_OPACITY
277
+ elif not related:
278
+ opacity = HOVER_DIM_OPACITY
279
+ for card in self._cards.get(pair_id, []):
280
+ card.setOpacity(opacity)
281
+ card.apply_glow(matched and hover_id is not None and pair_id == hover_id)
282
+ link = self._links.get(pair_id)
283
+ if link is not None:
284
+ strong = matched and hover_id is not None and pair_id == hover_id
285
+ link.setPen(self._link_pen(pair, strong))
286
+ link.setOpacity(1.0 if matched and related else HOVER_DIM_OPACITY)
287
+
288
+ @staticmethod
289
+ def _link_pen(pair: Any, strong: bool = False) -> QPen:
290
+ color = QColor(STATUS_COLORS[pair.status.value])
291
+ color.setAlpha(255 if strong else 150)
292
+ pen = QPen(color, 2.2 if strong else 1.2)
293
+ if pair.status.value == "modified":
294
+ pen.setStyle(Qt.PenStyle.DashLine)
295
+ return pen
296
+
297
+ def _card_hover_entered(self, card: NodeCard) -> None:
298
+ self._hovered = card
299
+ self._apply_visuals()
300
+
301
+ def _card_hover_left(self, card: NodeCard) -> None:
302
+ if self._hovered is card:
303
+ self._hovered = None
304
+ self._apply_visuals()
305
+
306
+ # -- painting ----------------------------------------------------------
307
+
308
+ def _label(self, x: float, text: str) -> None:
309
+ label = self._scene.addSimpleText(text)
310
+ label.setBrush(QColor("#8d96a1"))
311
+ label.setFont(QFont("Segoe UI", 8, QFont.Weight.DemiBold))
312
+ label.setPos(x, 36)
313
+
314
+ def _draw_node(self, node: Dict[str, Any], side: str) -> None:
315
+ symbol = node["sym"]
316
+ status = symbol.status.value
317
+ color = QColor(STATUS_COLORS[status])
318
+ x, y, width, height = node["x"], node["y"], node["w"], node["h"]
319
+
320
+ border = QColor(color)
321
+ border.setAlpha(130)
322
+ card = NodeCard(
323
+ width, height, QColor(STATUS_FILL[status]), border, symbol.pair_id or ""
324
+ )
325
+ card.setPos(x, y)
326
+ card.setToolTip(
327
+ f"{symbol.qualname}\n{status} \u00b7 lines {symbol.lineno}-{symbol.end_lineno}"
328
+ f"\ncomplexity {symbol.complexity} \u00b7 {symbol.loc} code lines"
329
+ )
330
+ card.on_enter = self._card_hover_entered
331
+ card.on_leave = self._card_hover_left
332
+ self._scene.addItem(card)
333
+
334
+ accent = QGraphicsPathItem()
335
+ accent_path = QPainterPath()
336
+ accent_path.addRoundedRect(QRectF(0, 0, 3, height), 1.5, 1.5)
337
+ accent.setPath(accent_path)
338
+ accent.setBrush(color)
339
+ accent.setPen(QPen(Qt.PenStyle.NoPen))
340
+ card.child(accent)
341
+
342
+ name = card.child(QGraphicsSimpleTextItem(symbol.label))
343
+ name.setBrush(QColor("#e9edf2"))
344
+ name.setFont(QFont("Cascadia Code", 8))
345
+ name.setPos(11, 4)
346
+
347
+ span = card.child(QGraphicsSimpleTextItem(str(symbol.lineno)))
348
+ span.setBrush(QColor("#7d8794"))
349
+ span.setFont(QFont("Cascadia Code", 7))
350
+ span.setPos(width - 30, 5)
351
+
352
+ box = self._geometry["boxes"].get(symbol.pair_id or "", {})
353
+ other = box.get("new" if side == "left" else "old")
354
+ if other is not None and other["sym"].complexity != symbol.complexity:
355
+ badge = card.child(QGraphicsSimpleTextItem(str(symbol.complexity)))
356
+ badge.setBrush(QColor(STATUS_COLORS["modified"]))
357
+ badge.setFont(QFont("Cascadia Code", 7))
358
+ badge.setPos(width - 54, 5)
359
+
360
+ self._cards.setdefault(symbol.pair_id or "", []).append(card)
361
+
362
+ def _draw_link(self, old_node: Dict[str, Any], new_node: Dict[str, Any], pair: Any) -> None:
363
+ start = QPointF(old_node["x"] + old_node["w"], old_node["y"] + old_node["h"] / 2)
364
+ end = QPointF(new_node["x"], new_node["y"] + new_node["h"] / 2)
365
+ path = QPainterPath(start)
366
+ reach = max(40.0, (end.x() - start.x()) * 0.45)
367
+ path.cubicTo(
368
+ QPointF(start.x() + reach, start.y()),
369
+ QPointF(end.x() - reach, end.y()),
370
+ end,
371
+ )
372
+ link = QGraphicsPathItem(path)
373
+ link.setPen(self._link_pen(pair))
374
+ link.setZValue(-1)
375
+ link.setData(0, pair.id)
376
+ self._scene.addItem(link)
377
+ self._links[pair.id or ""] = link
378
+
379
+ # -- interaction -------------------------------------------------------
380
+
381
+ def mousePressEvent(self, event) -> None:
382
+ item = self.itemAt(event.position().toPoint())
383
+ pair_id = None
384
+ while item is not None and pair_id is None:
385
+ pair_id = item.data(0)
386
+ item = item.parentItem()
387
+ if pair_id and self._result is not None:
388
+ for pair in self._result.pairs:
389
+ if pair.id == pair_id:
390
+ self.pairSelected.emit(pair)
391
+ break
392
+ super().mousePressEvent(event)
393
+
394
+
395
+ class ComparePage(QWidget):
396
+ """Pick two versions of a file; see what changed in the code's structure."""
397
+
398
+ back = Signal()
399
+
400
+ def __init__(self, parent: Optional[QWidget] = None):
401
+ super().__init__(parent)
402
+ self.language = "python"
403
+ self.old_source = ""
404
+ self.new_source = ""
405
+ self.old_label = ""
406
+ self.new_label = ""
407
+ self.result = None
408
+
409
+ layout = QVBoxLayout(self)
410
+ layout.setContentsMargins(16, 12, 16, 12)
411
+ layout.setSpacing(10)
412
+
413
+ head = QHBoxLayout()
414
+ self.back_button = QPushButton(tr("\u2190 Welcome"))
415
+ self.back_button.setObjectName("Ghost")
416
+ head.addWidget(self.back_button)
417
+ self.title_label = QLabel(tr("Compare versions"))
418
+ self.title_label.setObjectName("CardTitle")
419
+ head.addWidget(self.title_label)
420
+
421
+ self.language_box = QComboBox()
422
+ for language_id, label in LANGUAGE_LABELS:
423
+ self.language_box.addItem(label, language_id)
424
+ head.addWidget(self.language_box)
425
+
426
+ self.filter_box = QComboBox()
427
+ for key, label in FILTERS:
428
+ self.filter_box.addItem(tr(label), key)
429
+ head.addWidget(self.filter_box)
430
+ head.addStretch(1)
431
+
432
+ self.old_button = QPushButton(tr("Before file\u2026"))
433
+ self.new_button = QPushButton(tr("After file\u2026"))
434
+ self.sample_button = QPushButton(tr("Sample pair"))
435
+ self.sample_button.setObjectName("Chip")
436
+ self.swap_button = QPushButton(tr("Swap"))
437
+ self.swap_button.setObjectName("Chip")
438
+ self.compare_button = QPushButton(tr("Compare"))
439
+ self.compare_button.setObjectName("Primary")
440
+ head.addWidget(self.old_button)
441
+ head.addWidget(self.new_button)
442
+ head.addWidget(self.sample_button)
443
+ head.addWidget(self.swap_button)
444
+ head.addWidget(self.compare_button)
445
+ layout.addLayout(head)
446
+
447
+ self.status = QLabel(
448
+ tr("Pick two versions of the same file to see the structural diff.")
449
+ )
450
+ self.status.setObjectName("Tiny")
451
+ self.status.setWordWrap(True)
452
+ layout.addWidget(self.status)
453
+
454
+ split = QSplitter(Qt.Orientation.Horizontal)
455
+ self.view = CompareView()
456
+ split.addWidget(self.view)
457
+
458
+ detail = QWidget()
459
+ detail_layout = QVBoxLayout(detail)
460
+ detail_layout.setContentsMargins(0, 0, 0, 0)
461
+ detail_layout.setSpacing(6)
462
+ self.detail_title = QLabel(tr("Select a symbol"))
463
+ self.detail_title.setObjectName("Tiny")
464
+ detail_layout.addWidget(self.detail_title)
465
+ self.table = QTableWidget(0, 4)
466
+ self.table.setHorizontalHeaderLabels(["#", tr("Before"), "#", tr("After")])
467
+ self.table.verticalHeader().setVisible(False)
468
+ self.table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
469
+ self.table.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection)
470
+ header = self.table.horizontalHeader()
471
+ header.setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
472
+ header.setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)
473
+ header.setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents)
474
+ header.setSectionResizeMode(3, QHeaderView.ResizeMode.Stretch)
475
+ detail_layout.addWidget(self.table, 1)
476
+ split.addWidget(detail)
477
+ split.setSizes([780, 460])
478
+ layout.addWidget(split, 1)
479
+
480
+ if ENGINE_ERROR:
481
+ self.status.setText(
482
+ tr(ENGINE_HINT)
483
+ )
484
+
485
+ self.back_button.clicked.connect(self.back.emit)
486
+ self.language_box.currentIndexChanged.connect(self._language_changed)
487
+ self.filter_box.currentIndexChanged.connect(
488
+ lambda _index: self.view.apply_filter(self.filter_box.currentData())
489
+ )
490
+ self.old_button.clicked.connect(lambda: self._load("old"))
491
+ self.new_button.clicked.connect(lambda: self._load("new"))
492
+ self.sample_button.clicked.connect(self._load_sample)
493
+ self.swap_button.clicked.connect(self._swap)
494
+ self.compare_button.clicked.connect(self.run_compare)
495
+ self.view.pairSelected.connect(self.show_pair)
496
+
497
+ def retranslate(self) -> None:
498
+ """Re-apply interface strings after the UI language changed."""
499
+ self.back_button.setText(tr("\u2190 Welcome"))
500
+ self.title_label.setText(tr("Compare versions"))
501
+ for index, (_key, label) in enumerate(FILTERS):
502
+ self.filter_box.setItemText(index, tr(label))
503
+ if not self.old_label:
504
+ self.old_button.setText(tr("Before file\u2026"))
505
+ if not self.new_label:
506
+ self.new_button.setText(tr("After file\u2026"))
507
+ self.sample_button.setText(tr("Sample pair"))
508
+ self.swap_button.setText(tr("Swap"))
509
+ self.compare_button.setText(tr("Compare"))
510
+ self.table.setHorizontalHeaderLabels(["#", tr("Before"), "#", tr("After")])
511
+ if self.detail_title.text() in ("Select a symbol", ""):
512
+ self.detail_title.setText(tr("Select a symbol"))
513
+ if ENGINE_ERROR:
514
+ self.status.setText(tr(ENGINE_HINT))
515
+ elif self.result is None:
516
+ self.status.setText(
517
+ tr("Pick two versions of the same file to see the structural diff.")
518
+ )
519
+
520
+ # -- files -------------------------------------------------------------
521
+
522
+ def _language_changed(self, _index: int) -> None:
523
+ self.language = self.language_box.currentData()
524
+ name = self.language_box.currentText()
525
+ self.status.setText(tr("{name}: pick a before file and an after file.", name=name))
526
+
527
+ def _patterns(self) -> str:
528
+ extensions = FILE_EXTENSIONS.get(self.language, [])
529
+ if not extensions:
530
+ return "*"
531
+ return " ".join(f"*.{extension}" for extension in extensions)
532
+
533
+ def _load(self, side: str) -> None:
534
+ title = tr("Choose the before file") if side == "old" else tr("Choose the after file")
535
+ path, _filter = QFileDialog.getOpenFileName(
536
+ self, title, "", f"{tr('Source files')} ({self._patterns()});;{tr('All files')} (*)"
537
+ )
538
+ if not path:
539
+ return
540
+ try:
541
+ text = self._read(path)
542
+ except OSError as error:
543
+ self.status.setText(
544
+ tr("Could not read {name}: {error}", name=Path(path).name, error=error)
545
+ )
546
+ return
547
+ name = Path(path).name
548
+ if side == "old":
549
+ self.old_source, self.old_label = text, name
550
+ else:
551
+ self.new_source, self.new_label = text, name
552
+ self.old_button.setText(self.old_label or tr("Before file\u2026"))
553
+ self.new_button.setText(self.new_label or tr("After file\u2026"))
554
+ self.status.setText(
555
+ f"{self.old_label or tr('(no before file)')} \u2192 "
556
+ f"{self.new_label or tr('(no after file)')}"
557
+ )
558
+
559
+ @staticmethod
560
+ def _read(path: str) -> str:
561
+ data = Path(path).read_bytes()
562
+ for encoding in ("utf-8-sig", "utf-8", "gb18030", "cp1252", "latin-1"):
563
+ try:
564
+ return data.decode(encoding)
565
+ except UnicodeDecodeError:
566
+ continue
567
+ return data.decode("utf-8", errors="replace")
568
+
569
+ def _load_sample(self) -> None:
570
+ """Fill both sides from the bundled samples so the page can be tried at once."""
571
+ bundled = {
572
+ "python": ("report_before.py", "report_after.py"),
573
+ "java": ("Shape.java", "ShapeRefactored.java"),
574
+ }
575
+ pair = bundled.get(self.language)
576
+ if pair is None:
577
+ self.status.setText(
578
+ tr("No bundled sample for {name} yet \u2014 pick two files.",
579
+ name=self.language_box.currentText())
580
+ )
581
+ return
582
+ folder = Path(__file__).resolve().parent.parent / "samples"
583
+ try:
584
+ self.old_source = self._read(str(folder / pair[0]))
585
+ self.new_source = self._read(str(folder / pair[1]))
586
+ except OSError as error:
587
+ self.status.setText(tr("Sample files are missing: {error}", error=error))
588
+ return
589
+ self.old_label, self.new_label = pair
590
+ self.old_button.setText(self.old_label)
591
+ self.new_button.setText(self.new_label)
592
+ self.status.setText(tr("Sample: {old} \u2192 {new}", old=pair[0], new=pair[1]))
593
+ self.run_compare()
594
+
595
+ def _swap(self) -> None:
596
+ self.old_source, self.new_source = self.new_source, self.old_source
597
+ self.old_label, self.new_label = self.new_label, self.old_label
598
+ self.old_button.setText(self.old_label or tr("Before file\u2026"))
599
+ self.new_button.setText(self.new_label or tr("After file\u2026"))
600
+
601
+ # -- diff --------------------------------------------------------------
602
+
603
+ def run_compare(self) -> None:
604
+ if ENGINE_ERROR:
605
+ self.status.setText(
606
+ tr(ENGINE_HINT)
607
+ )
608
+ return
609
+ if not self.old_source or not self.new_source:
610
+ self.status.setText(tr("Choose both files first."))
611
+ return
612
+ self.status.setText(tr("Comparing\u2026"))
613
+ self.repaint()
614
+ try:
615
+ result = compare_sources(
616
+ self.language,
617
+ self.old_source,
618
+ self.new_source,
619
+ self.old_label or "before",
620
+ self.new_label or "after",
621
+ )
622
+ except Exception as error: # parse errors carry a readable message
623
+ self.view.show_placeholder()
624
+ self.table.setRowCount(0)
625
+ self.detail_title.setText(tr("Select a symbol"))
626
+ self.status.setText(tr("Could not compare: {error}", error=error))
627
+ return
628
+
629
+ self.result = result
630
+ summary = result.summary()
631
+ self.status.setText(describe(summary))
632
+ if not result.pairs:
633
+ self.view.show_placeholder()
634
+ self.status.setText(tr("No classes or functions found in either file."))
635
+ return
636
+ self.view.set_result(result)
637
+ first_changed = next(
638
+ (pair for pair in result.pairs if pair.status.value != "unchanged"), None
639
+ )
640
+ self.show_pair(first_changed or result.pairs[0])
641
+
642
+ # -- detail table ------------------------------------------------------
643
+
644
+ def show_pair(self, pair: Any) -> None:
645
+ if pair is None or self.result is None:
646
+ return
647
+ symbol = pair.symbol
648
+ self.detail_title.setText(
649
+ f"{symbol.qualname} \u00b7 {symbol.kind} \u00b7 {pair.status.value.upper()}"
650
+ )
651
+ old_symbol, new_symbol = pair.old, pair.new
652
+ old_lines: List[str] = []
653
+ new_lines: List[str] = []
654
+ old_start = new_start = 1
655
+ if old_symbol is not None:
656
+ old_lines = self.result.old.lines[old_symbol.lineno - 1:old_symbol.end_lineno]
657
+ old_start = old_symbol.lineno
658
+ if new_symbol is not None:
659
+ new_lines = self.result.new.lines[new_symbol.lineno - 1:new_symbol.end_lineno]
660
+ new_start = new_symbol.lineno
661
+
662
+ rows = aligned_rows(old_lines, new_lines, old_start, new_start)
663
+ self.table.setRowCount(len(rows))
664
+ tones = {
665
+ "eq": ("#1d2025", "#1d2025"),
666
+ "del": ("#331f1e", "#1d2025"),
667
+ "ins": ("#1d2025", "#1c2b23"),
668
+ "rep": ("#332a1c", "#332a1c"),
669
+ }
670
+ for row_index, (tag, old_no, old_text, new_no, new_text) in enumerate(rows):
671
+ left_tone, right_tone = tones[tag]
672
+ self._cell(row_index, 0, str(old_no or ""), "#6f7885", left_tone)
673
+ self._cell(row_index, 1, old_text, "#dfe4ea", left_tone)
674
+ self._cell(row_index, 2, str(new_no or ""), "#6f7885", right_tone)
675
+ self._cell(row_index, 3, new_text, "#dfe4ea", right_tone)
676
+
677
+ def _cell(self, row: int, column: int, text: str, ink: str, background: str) -> None:
678
+ item = QTableWidgetItem(text)
679
+ item.setForeground(QColor(ink))
680
+ item.setBackground(QColor(background))
681
+ if column in (0, 2):
682
+ item.setTextAlignment(
683
+ Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter
684
+ )
685
+ self.table.setItem(row, column, item)