Repository navigation
Expand file tree
/
Copy pathdiffview.py
More file actions
1218 lines (1051 loc) · 51.8 KB
/
Copy pathdiffview.py
File metadata and controls
1218 lines (1051 loc) · 51.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""The widget MO2 shows for one variant of a conflicting file."""
from __future__ import annotations
import os
from datetime import datetime
from PyQt6.QtCore import QFileInfo, QRect, QSize, Qt, QTimer
from PyQt6.QtGui import (
QFont, QFontDatabase, QIcon, QPainter, QTextCursor, QTextFormat,
)
from PyQt6.QtWidgets import (
QApplication, QCheckBox, QComboBox, QFileIconProvider, QFrame, QHBoxLayout,
QLabel, QMenu,
QMessageBox, QPlainTextEdit, QSizePolicy, QSplitter, QStackedWidget, QStyle,
QPushButton, QTextEdit, QVBoxLayout, QWidget,
)
from . import engines, theme as theming, tools
from .engines import DELETE, EQUAL, INSERT, REPLACE, DiffRow
from .highlight import highlighter_for, state_after as highlight_state
from .resolve import Resolution, Variant
from .textio import TextFile, read_text
from .theme import Theme
SEPARATOR = "separator"
# QFontDatabase.systemFont(FixedFont) yields Courier New on Windows, which is
# hard to read for config files; prefer a modern console font when installed.
_MONO_PREFERENCES = ("Cascadia Mono", "Consolas", "Segoe UI Mono", "DejaVu Sans Mono")
def mono_font() -> QFont:
available = set(QFontDatabase.families())
for family in _MONO_PREFERENCES:
if family in available:
font = QFont(family)
break
else:
font = QFontDatabase.systemFont(QFontDatabase.SystemFont.FixedFont)
font.setStyleHint(QFont.StyleHint.Monospace)
font.setFixedPitch(True)
return font
class _Gutter(QWidget):
def __init__(self, pane: "DiffPane"):
super().__init__(pane)
self._pane = pane
def sizeHint(self) -> QSize: # noqa: N802 (Qt naming)
return QSize(self._pane.gutter_width(), 0)
def paintEvent(self, event) -> None: # noqa: N802
self._pane.paint_gutter(self, event)
class DiffPane(QPlainTextEdit):
"""Read-only text pane with a gutter showing the *original* line numbers.
Padding rows make block numbers and file line numbers diverge, so the
numbers are supplied explicitly instead of derived from the document.
"""
def __init__(self, theme: Theme, parent: QWidget | None = None):
super().__init__(parent)
self._theme = theme
self.line_numbers: list[int | None] = []
# Cached because gutter_width() is called on every paint and every
# highlight pass; rescanning 14k line numbers each time turned a large
# .osp into a 90-second freeze.
self._widest_number = 1
self._gutter_span = 0
self.setReadOnly(True)
self.setLineWrapMode(QPlainTextEdit.LineWrapMode.NoWrap)
self.setFrameShape(QFrame.Shape.NoFrame)
self.setFont(mono_font())
self.setTabStopDistance(4 * self.fontMetrics().horizontalAdvance(" "))
self._gutter = _Gutter(self)
self.blockCountChanged.connect(lambda _: self._update_gutter_width())
self.updateRequest.connect(self._on_update_request)
self._update_gutter_width()
def gutter_width(self) -> int:
digits = max(3, len(str(self._widest_number)))
return 12 + self.fontMetrics().horizontalAdvance("9") * digits
def _update_gutter_width(self) -> None:
# Qt asks for this on every update request, so only touch the layout
# when the width has actually moved.
width = self.gutter_width()
if width != self._gutter_span:
self._gutter_span = width
self.setViewportMargins(width, 0, 0, 0)
def _on_update_request(self, rect: QRect, dy: int) -> None:
if dy:
self._gutter.scroll(0, dy)
else:
self._gutter.update(0, rect.y(), self._gutter.width(), rect.height())
if rect.contains(self.viewport().rect()):
self._update_gutter_width()
def resizeEvent(self, event) -> None: # noqa: N802
super().resizeEvent(event)
area = self.contentsRect()
self._gutter.setGeometry(QRect(area.left(), area.top(),
self.gutter_width(), area.height()))
def paint_gutter(self, gutter: QWidget, event) -> None:
painter = QPainter(gutter)
painter.fillRect(event.rect(), self._theme.gutter)
painter.setPen(self._theme.gutter_text)
block = self.firstVisibleBlock()
top = round(self.blockBoundingGeometry(block).translated(self.contentOffset()).top())
height = round(self.blockBoundingRect(block).height())
while block.isValid() and top <= event.rect().bottom():
if block.isVisible() and top + height >= event.rect().top():
index = block.blockNumber()
if index < len(self.line_numbers) and self.line_numbers[index] is not None:
painter.drawText(0, top, gutter.width() - 6, height,
int(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter),
str(self.line_numbers[index]))
block = block.next()
top += height
height = round(self.blockBoundingRect(block).height())
def set_content(self, lines: list[str], numbers: list[int | None]) -> None:
self.line_numbers = numbers
self._widest_number = max((n for n in numbers if n), default=1)
self.setPlainText("\n".join(lines))
self._update_gutter_width()
self._gutter.update()
def set_theme(self, theme: Theme) -> None:
self._theme = theme
self._gutter.update()
class DiffPreviewWidget(QWidget):
"""Side-by-side / unified diff of one conflicting file against another mod."""
MAX_DECORATED_ROWS = 12000
#: Width of an icon-only pane button; a push button would otherwise reserve
#: room for a label that is not there.
FIXED_ICON_WIDTH = 28
def __tr(self, txt: str) -> str:
# The context must match the class name for pylupdate6 to line up.
return QApplication.translate("DiffPreviewWidget", txt)
def __init__(self, settings, resolution: Resolution, parent: QWidget | None = None):
super().__init__(parent)
self._settings = settings
self._resolution = resolution
self._extension = os.path.splitext(resolution.relative_path)[1].lstrip(".")
# Both sides are selectable: with three mods providing the file you may
# well want to compare the two you are *not* previewing.
self._left_index = resolution.current_index
self._partner_index = resolution.default_partner_index()
self._mo2_colours = theming.mo2_conflict_colours(settings.organizer)
self._themed = False
self._theme = self._build_theme()
self._syncing = False
self._result: engines.DiffResult | None = None
self._display_rows: list = []
self._left_file: TextFile | None = None
self._right_file: TextFile | None = None
self._build_ui()
self._winner_left.blockSignals(True)
self._winner_left.setChecked(
self._settings.remembered_boolean("winner_left", False))
self._winner_left.blockSignals(False)
self._apply_winner_side()
self.reload()
# --------------------------------------------------------------- theming
def _build_theme(self, measured=None) -> Theme:
mode = self._settings.string("mo2_conflict_colors", "normal").strip().lower()
overwriting, overwritten = self._mo2_colours
if mode == "swapped":
colours = (overwritten, overwriting)
elif mode == "off":
colours = (None, None)
else:
colours = (overwriting, overwritten)
return theming.build(self, self._settings.string("theme", "auto"),
measured, colours)
def showEvent(self, event) -> None: # noqa: N802 (Qt naming)
super().showEvent(event)
# Only now is there something painted to measure. Deferred by a tick so
# the stylesheet has definitely been applied to the panes.
if not self._themed:
self._themed = True
QTimer.singleShot(0, self._retheme)
def _retheme(self) -> None:
try:
measured = theming.sample_background(self._left_pane)
except RuntimeError: # widget already destroyed
return
if measured is None:
return
updated = self._build_theme(measured)
changed = not updated.matches(self._theme)
# Adopt the measured theme either way, so `source` reflects reality even
# when the palette happened to agree; only redraw when it actually moved.
self._theme = updated
for pane in (self._left_pane, self._right_pane, self._unified_pane):
pane.set_theme(updated)
if changed:
self._install_highlighters()
self._render()
# ------------------------------------------------------------------ UI
def _build_ui(self) -> None:
layout = QVBoxLayout(self)
layout.setContentsMargins(6, 6, 6, 6)
layout.setSpacing(6)
self._header = QLabel(self)
self._header.setTextFormat(Qt.TextFormat.RichText)
self._header.setWordWrap(True)
layout.addWidget(self._header)
layout.addLayout(self._build_toolbar())
self._stack = QStackedWidget(self)
self._splitter = QSplitter(Qt.Orientation.Horizontal, self)
self._left_pane = DiffPane(self._theme, self)
self._right_pane = DiffPane(self._theme, self)
self._arrows: dict = {}
self._spacers: dict = {}
self._left_box = QComboBox(self)
self._left_box.setToolTip(self.__tr("Mod shown on the left"))
self._left_box.currentIndexChanged.connect(self._on_left_changed)
self._right_box = QComboBox(self)
self._right_box.setToolTip(self.__tr("Mod shown on the right"))
self._right_box.currentIndexChanged.connect(self._on_partner_changed)
self._left_reveal = QPushButton(self)
self._right_reveal = QPushButton(self)
self._left_open = QPushButton(self)
self._right_open = QPushButton(self)
self._left_status = QLabel(self)
self._right_status = QLabel(self)
self._left_side = self._pane_header(
self._left_box, self._left_pane, self._left_reveal,
lambda: self._reveal("left"), self._left_status,
self._left_open, lambda: self._open("left"))
self._right_side = self._pane_header(
self._right_box, self._right_pane, self._right_reveal,
lambda: self._reveal("right"), self._right_status,
self._right_open, lambda: self._open("right"))
self._splitter.addWidget(self._left_side)
self._splitter.addWidget(self._right_side)
self._splitter.setSizes([1, 1])
self._stack.addWidget(self._splitter)
self._unified_pane = DiffPane(self._theme, self)
self._stack.addWidget(self._unified_pane)
layout.addWidget(self._stack, 1)
self._highlighters: list = []
self._install_highlighters()
self._link_scrollbars()
self._status = QLabel(self)
self._status.setWordWrap(True)
self._status.setTextFormat(Qt.TextFormat.RichText)
layout.addWidget(self._status)
self._apply_view_mode(
self._settings.remembered_string("view_mode", "side-by-side"))
def _build_toolbar(self) -> QHBoxLayout:
bar = QHBoxLayout()
bar.setSpacing(6)
self._view_check = QCheckBox(self.__tr("Side by side"), self)
self._view_check.setToolTip(
self.__tr("Switch between side-by-side and unified view"))
self._view_check.toggled.connect(self._on_view_toggled)
bar.addWidget(self._view_check)
self._winner_left = QCheckBox(self.__tr("Winner left"), self)
self._winner_left.setToolTip(self.__tr(
"Put the winning mod in the left pane. Off means load order, so the "
"mod the game actually uses sits on the right."))
self._winner_left.toggled.connect(self._on_winner_side_toggled)
bar.addWidget(self._winner_left)
self._engine_box = QComboBox(self)
self._engine_box.addItem(self.__tr("built-in diff"), "builtin")
self._engine_box.addItem(self.__tr("git diff"), "git")
# Without git that option could only ever fall back, so it is offered
# but disabled rather than silently doing nothing. The built-in engine
# needs nothing at all, so the diff itself always works.
self._git_exe = engines.find_git(self._settings.string("git_path", ""))
if not self._git_exe:
item = self._engine_box.model().item(1)
if item is not None:
item.setEnabled(False)
item.setToolTip(self.__tr("git was not found on this system"))
current = self._settings.remembered_string("diff_engine", "builtin")
self._engine_box.setCurrentIndex(1 if current == "git" and self._git_exe else 0)
self._engine_box.setToolTip(
self.__tr("Diff engine: Python difflib, or 'git diff --no-index'"))
self._engine_box.currentIndexChanged.connect(self._on_engine_changed)
bar.addWidget(self._engine_box)
self._algo_box = QComboBox(self)
for algorithm in engines.ALGORITHMS:
self._algo_box.addItem(algorithm, algorithm)
wanted = self._settings.remembered_string("git_diff_algorithm", "histogram")
self._algo_box.setCurrentIndex(max(0, self._algo_box.findData(wanted)))
self._algo_box.setToolTip(self.__tr(
"Which algorithm git uses. 'histogram' and 'patience' usually give "
"the most readable result on config files."))
self._algo_box.currentIndexChanged.connect(self._on_algorithm_changed)
bar.addWidget(self._algo_box)
self._only_diff = QCheckBox(self.__tr("Only differences"), self)
self._only_diff.setChecked(
self._settings.remembered_boolean("only_differences", False))
self._only_diff.toggled.connect(self._on_only_differences)
bar.addWidget(self._only_diff)
self._ignore_ws = QCheckBox(self.__tr("Ignore whitespace"), self)
self._ignore_ws.setChecked(
self._settings.remembered_boolean("ignore_whitespace", False))
self._ignore_ws.toggled.connect(self._on_ignore_whitespace)
bar.addWidget(self._ignore_ws)
bar.addStretch(1)
# Side-by-side has a reveal button per pane; unified has no panes to hang
# them off, so this one opens both folders at once.
self._reveal_button = QPushButton(self)
self._reveal_button.setIcon(
self.style().standardIcon(QStyle.StandardPixmap.SP_DirOpenIcon))
self._reveal_button.setText(self.__tr("Show both in Explorer"))
self._reveal_button.clicked.connect(self._reveal_both)
bar.addWidget(self._reveal_button)
self._copy_button = QPushButton(self)
self._copy_button.setIcon(self._icon("edit-copy",
QStyle.StandardPixmap.SP_FileDialogContentsView))
self._copy_button.setText(self.__tr("Copy diff"))
self._copy_button.clicked.connect(self._copy_diff)
bar.addWidget(self._copy_button)
self._compare_button = QPushButton(self)
self._compare_button.setText(self.__tr("Compare in") + " ")
self._compare_menu = QMenu(self._compare_button)
self._compare_button.setMenu(self._compare_menu)
bar.addWidget(self._compare_button)
return bar
def _pane_header(self, box: QComboBox, pane: DiffPane, reveal: QPushButton,
on_reveal, status: QLabel, opener: QPushButton,
on_open) -> QWidget:
"""Mod picker + reveal button sitting directly above a pane.
The same shape MO2's own NIF preview uses: each pane owns the control
that chooses what it shows, rather than a shared row of pickers.
"""
container = QWidget()
outer = QVBoxLayout(container)
outer.setContentsMargins(0, 0, 0, 0)
outer.setSpacing(2)
row = QHBoxLayout()
row.setContentsMargins(0, 0, 0, 0)
row.setSpacing(2)
previous = QPushButton(container)
previous.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_ArrowLeft))
previous.setFixedWidth(self.FIXED_ICON_WIDTH)
previous.clicked.connect(lambda: self._step(box, -1))
row.addWidget(previous)
box.setParent(container)
box.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
row.addWidget(box, 1)
following = QPushButton(container)
following.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_ArrowRight))
following.setFixedWidth(self.FIXED_ICON_WIDTH)
following.clicked.connect(lambda: self._step(box, 1))
row.addWidget(following)
opener.setParent(container)
opener.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_FileIcon))
opener.clicked.connect(on_open)
row.addWidget(opener)
reveal.setParent(container)
reveal.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_DirOpenIcon))
reveal.clicked.connect(on_reveal)
row.addWidget(reveal)
# The picker normally takes the slack. With it hidden the buttons would
# drift apart, so this takes over and keeps them left-aligned.
spacer = QWidget(container)
spacer.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Ignored)
row.addWidget(spacer)
self._spacers[box] = spacer
self._arrows.setdefault(box, (previous, following))
outer.addLayout(row)
outer.addWidget(pane, 1)
status.setTextFormat(Qt.TextFormat.RichText)
status.setContentsMargins(4, 0, 4, 0)
outer.addWidget(status)
return container
def _associated_icon(self, path: str) -> QIcon:
"""Windows' own icon for this file type: the program that opens it.
QFileIconProvider goes through SHGetFileInfo on Windows, so this is the
same icon Explorer shows -- it tells you what the Open button will
actually launch, instead of a generic page.
"""
if path:
icon = QFileIconProvider().icon(QFileInfo(path))
if not icon.isNull() and icon.availableSizes():
return icon
return self.style().standardIcon(QStyle.StandardPixmap.SP_FileIcon)
def _icon(self, theme_name: str, fallback: QStyle.StandardPixmap) -> QIcon:
"""Prefer the desktop theme's icon; Qt has no standard one for copy."""
icon = QIcon.fromTheme(theme_name)
return icon if not icon.isNull() else self.style().standardIcon(fallback)
def _step(self, box: QComboBox, delta: int) -> None:
"""Walk a pane picker to the next/previous mod, wrapping around."""
if box.count() < 2:
return
box.setCurrentIndex((box.currentIndex() + delta) % box.count())
def _reveal_tooltip(self, variant: Variant | None) -> str:
"""'Show in Explorer' plus the folder it will actually open."""
if variant is None:
return self.__tr("Show in Explorer")
folder = os.path.dirname(variant.path)
return (f"{self.__tr('Show in Explorer')}: {os.path.basename(folder)}"
f"\n{folder}")
def _open(self, side: str) -> None:
variant = self._current() if side == "left" else self._partner()
if variant is not None and not tools.open_with_default(variant.path):
QMessageBox.warning(
self, self.__tr("Open"),
self.__tr("Windows has nothing associated with this file type."))
def _reveal(self, side: str) -> None:
variant = self._current() if side == "left" else self._partner()
if variant is not None:
tools.reveal(variant.path)
def _reveal_both(self) -> None:
# Two windows, since the two copies live in different mod folders.
for variant in (self._current(), self._partner()):
if variant is not None:
tools.reveal(variant.path)
def _resync_highlighters(self) -> None:
"""Tell each highlighter the real comment state where a fold ended.
The rendered panes skip lines, so a `-->` (or `*/`) can end up in the
hidden part. Without this the block-comment machine never closes and
paints the rest of the file as comment.
"""
if not self._highlighters:
return
rules = self._highlighters[0].rules
rows = self._result.rows if self._result else []
def resync_for(side: str) -> dict[int, int]:
if not rules.block_comments:
return {}
marks: dict[int, int] = {}
state = 0
consumed = 0
for index, row in enumerate(self._display_rows):
if isinstance(row, tuple):
# Run the hidden lines through purely for their state.
hidden = rows[consumed:consumed + row[1]]
state = highlight_state(rules, [
(r.left if side == "left" else r.right) or "" for r in hidden
], state)
consumed += row[1]
marks[index + 1] = state
continue
consumed += 1
text = (row.left if side == "left" else row.right) or ""
state = highlight_state(rules, [text], state)
return marks
# Only worth computing when something was actually folded away; without
# a fold the highlighter's own state machine is already correct.
folded = any(isinstance(row, tuple) for row in self._display_rows)
self._highlighters[0].set_resync(resync_for("left") if folded else {})
self._highlighters[1].set_resync(resync_for("right") if folded else {})
def _install_highlighters(self) -> None:
"""(Re)attach syntax highlighters, e.g. after the theme is re-measured."""
for highlighter in self._highlighters:
highlighter.setDocument(None)
# Unified lines carry a leading ' ', '+' or '-'. Context lines (the bulk)
# start with a space and highlight normally; changed lines lose their
# line-anchored rules, which the row colouring more than makes up for.
self._highlighters = [
highlighter_for(self._extension, pane.document(), self._theme.dark)
for pane in (self._left_pane, self._right_pane, self._unified_pane)
]
def _link_scrollbars(self) -> None:
pairs = (
(self._left_pane.verticalScrollBar(), self._right_pane.verticalScrollBar()),
(self._left_pane.horizontalScrollBar(), self._right_pane.horizontalScrollBar()),
)
for first, second in pairs:
first.valueChanged.connect(lambda value, target=second: self._sync(target, value))
second.valueChanged.connect(lambda value, target=first: self._sync(target, value))
def _sync(self, target, value: int) -> None:
if self._syncing:
return
self._syncing = True
try:
target.setValue(value)
finally:
self._syncing = False
# ------------------------------------------------------------- handlers
def _on_view_toggled(self) -> None:
mode = "side-by-side" if self._view_check.isChecked() else "unified"
self._settings.remember("view_mode", mode)
self._apply_view_mode(mode)
self._render()
def _on_winner_side_toggled(self, checked: bool) -> None:
self._settings.remember("winner_left", checked)
self._apply_winner_side()
self.reload()
def _apply_winner_side(self) -> None:
"""Arrange the two sides so the winner lands where the user asked."""
left, right = self._variant(self._left_index), self._variant(self._partner_index)
if left is None or right is None or left.is_winner == right.is_winner:
return
winner_is_left = left.is_winner
if winner_is_left != self._winner_left.isChecked():
self._left_index, self._partner_index = self._partner_index, self._left_index
def _apply_view_mode(self, mode: str) -> None:
unified = mode == "unified"
self._view_check.blockSignals(True)
self._view_check.setChecked(not unified)
self._view_check.blockSignals(False)
self._stack.setCurrentIndex(1 if unified else 0)
self._only_diff.setEnabled(not unified)
# Redundant while the per-pane buttons are on screen.
self._reveal_button.setVisible(unified)
def _on_engine_changed(self) -> None:
self._settings.remember("diff_engine", self._engine_box.currentData())
self._apply_engine_mode()
self.reload()
def _on_algorithm_changed(self) -> None:
self._settings.remember("git_diff_algorithm", self._algo_box.currentData())
self.reload()
def _apply_engine_mode(self) -> None:
"""The algorithm picker only means anything for the git engine."""
self._algo_box.setVisible(self._engine_box.currentData() == "git")
def _on_only_differences(self, checked: bool) -> None:
self._settings.remember("only_differences", checked)
self._render()
def _on_ignore_whitespace(self, checked: bool) -> None:
self._settings.remember("ignore_whitespace", checked)
self.reload()
def _on_left_changed(self, index: int) -> None:
data = self._left_box.itemData(index)
if data is None or data == self._left_index:
return
self._left_index = data
if self._left_index == self._partner_index:
# Never compare a file with itself; step the other side along.
others = [i for i in range(len(self._resolution.variants))
if i != self._left_index]
self._partner_index = others[0] if others else -1
self.reload()
def _on_partner_changed(self, index: int) -> None:
data = self._right_box.itemData(index)
if data is None or data == self._partner_index:
return
self._partner_index = data
if self._partner_index == self._left_index:
others = [i for i in range(len(self._resolution.variants))
if i != self._partner_index]
self._left_index = others[0] if others else -1
self.reload()
def _copy_diff(self) -> None:
# With no partner there is no diff to copy, so hand over the file itself.
if self._partner() is None:
text = self._left_file.text if self._left_file else ""
else:
text = "\n".join(self._unified_lines()[0])
QApplication.clipboard().setText(text)
# ---------------------------------------------------------------- data
def _variant(self, index: int) -> Variant | None:
if 0 <= index < len(self._resolution.variants):
return self._resolution.variants[index]
return None
def _current(self) -> Variant | None:
return self._variant(self._left_index)
def __too_long_to_diff(self) -> bool:
limit = self._settings.integer("max_diff_lines", 20000)
if limit <= 0 or self._left_file is None or self._right_file is None:
return False
return max(len(self._left_file.lines), len(self._right_file.lines)) > limit
def _partner(self) -> Variant | None:
return self._variant(self._partner_index)
def reload(self) -> None:
current = self._current()
partner = self._partner()
max_bytes = max(0, self._settings.integer("max_file_size_kb", 2048)) * 1024
self._left_file = read_text(current.path, max_bytes) if current else None
self._right_file = read_text(partner.path, max_bytes) if partner else None
self._refresh_partner_box()
self._refresh_compare_menu()
self._apply_conflict_mode(partner is not None)
if self._left_file is None:
self._result = None
elif self._right_file is None:
self._result = engines.DiffResult(
rows=[DiffRow(EQUAL, index + 1, text, index + 1, text)
for index, text in enumerate(self._left_file.lines)],
engine="builtin",
)
elif self.__too_long_to_diff():
# Big generated files (BodySlide .osp runs to tens of thousands of
# lines) would freeze the UI for seconds. Show them, skip the diff,
# and leave the external tools -- which diff out of process -- as
# the way to compare them.
self._result = engines.DiffResult(
rows=[DiffRow(EQUAL, index + 1, text, index + 1, text)
for index, text in enumerate(self._left_file.lines)],
engine="builtin",
note_key="too_long",
)
else:
self._result = engines.compute_diff(
self._left_file,
self._right_file,
current.path,
partner.path,
engine=self._engine_box.currentData(),
git_exe=self._git_exe,
algorithm=self._algo_box.currentData(),
ignore_whitespace=self._ignore_ws.isChecked(),
word_diff=self._settings.boolean("word_diff", True),
)
self._render()
def _apply_conflict_mode(self, has_conflict: bool) -> None:
"""Hide every comparison control when only one mod provides the file."""
for widget in (self._view_check, self._winner_left, self._engine_box,
self._only_diff, self._ignore_ws, self._compare_button,
self._right_side):
widget.setVisible(has_conflict)
self._algo_box.setVisible(has_conflict
and self._engine_box.currentData() == "git")
self._left_box.setVisible(has_conflict)
for arrow in self._arrows.get(self._left_box, ()):
arrow.setVisible(has_conflict)
if not has_conflict:
self._left_box.setStyleSheet("")
# Unified-only as well, so re-apply that rule rather than override it.
self._reveal_button.setVisible(
has_conflict and not self._view_check.isChecked())
self._copy_button.setText(
self.__tr("Copy diff") if has_conflict else self.__tr("Copy text"))
if not has_conflict:
# Force the single file into the side-by-side page; the unified page
# would only render a diff against nothing.
self._stack.setCurrentIndex(0)
def _variant_label(self, variant: Variant) -> str:
return variant.mod_name + (" " + self.__tr("(winner)") if variant.is_winner else "")
def _refresh_partner_box(self) -> None:
several = len(self._resolution.variants) > 2
for box, selected in ((self._left_box, self._left_index),
(self._right_box, self._partner_index)):
box.blockSignals(True)
box.clear()
for index, variant in enumerate(self._resolution.variants):
box.addItem(self._variant_label(variant), index)
position = box.findData(selected)
if position >= 0:
box.setCurrentIndex(position)
box.blockSignals(False)
# Arrows are pointless with a single choice.
for arrow in self._arrows.get(box, ()):
arrow.setEnabled(several)
def _refresh_compare_menu(self) -> None:
self._compare_menu.clear()
context = self._tool_context()
available = tools.load_tools(self._settings.string("external_tools", ""))
for tool in available:
if not tool.enabled:
continue
action = self._compare_menu.addAction(tool.label)
action.setEnabled(bool(context))
action.triggered.connect(lambda _checked=False, t=tool: self._launch_tool(t))
if not self._compare_menu.actions():
self._compare_menu.addAction(self.__tr("No tools enabled")).setEnabled(False)
self._compare_menu.addSeparator()
self._compare_menu.addAction(self.__tr("Configure tools…"), self._configure_tools)
def _tool_context(self) -> dict[str, str]:
current, partner = self._current(), self._partner()
if not current or not partner:
return {}
return {
"{left}": current.path,
"{right}": partner.path,
"{leftlabel}": current.mod_name,
"{rightlabel}": partner.mod_name,
"{leftdir}": os.path.dirname(current.path),
"{rightdir}": os.path.dirname(partner.path),
"{relpath}": self._resolution.relative_path,
}
def _launch_tool(self, tool: tools.Tool) -> None:
reason, detail = tools.launch(tool, self._tool_context())
if reason == "not_found":
QMessageBox.warning(
self, self.__tr("Compare"),
self.__tr("Could not find '{executable}'.").format(executable=detail)
+ "\n\n"
+ self.__tr("Set the correct path via Compare in > Configure tools."))
elif reason:
QMessageBox.warning(self, self.__tr("Compare"),
self.__tr("Failed to start:") + "\n" + detail)
def _configure_tools(self) -> None:
current = tools.load_tools(self._settings.string("external_tools", ""))
dialog = tools.ToolsDialog(current, self._tool_context(), self)
if dialog.exec():
self._settings.set("external_tools", tools.dump_tools(dialog.tools()))
self._refresh_compare_menu()
# --------------------------------------------------------------- render
def _collapse(self, rows: list[DiffRow]) -> list:
"""Fold long runs of unchanged rows into a single separator entry."""
context = max(0, self._settings.integer("context_lines", 3))
output: list = []
run: list[DiffRow] = []
def flush() -> None:
if not run:
return
if len(run) <= context * 2 + 1:
output.extend(run)
else:
output.extend(run[:context])
output.append((SEPARATOR, len(run) - context * 2))
output.extend(run[-context:])
run.clear()
for row in rows:
if row.tag == EQUAL:
run.append(row)
else:
flush()
output.append(row)
flush()
return output
def _render(self) -> None:
self._update_header()
if not self._result:
unreadable = self.__tr("<file could not be read>")
self._left_pane.set_content([unreadable], [None])
self._right_pane.set_content([], [])
self._unified_pane.set_content([unreadable], [None])
self._update_status()
return
rows = self._result.rows
# Folding is a side-by-side affair (unified always uses context_lines),
# and never applies with nothing to compare against: the toggle may
# still be on from an earlier session even though it is hidden, and
# "4 unchanged lines" is nonsense when every line is unchanged.
if (self._partner() is not None
and self._only_diff.isChecked()
and self._view_check.isChecked()):
self._display_rows = self._collapse(rows)
else:
self._display_rows = list(rows)
if not self._view_check.isChecked():
self._render_unified()
else:
self._render_side_by_side()
self._update_status()
def _render_side_by_side(self) -> None:
left_lines: list[str] = []
right_lines: list[str] = []
left_numbers: list[int | None] = []
right_numbers: list[int | None] = []
decorations: list[tuple[int, str, str, list[tuple[int, int]]]] = []
for index, row in enumerate(self._display_rows):
if isinstance(row, tuple):
text = " " + self.__tr("... {count} unchanged lines ...").format(
count=row[1])
left_lines.append(text)
right_lines.append(text)
left_numbers.append(None)
right_numbers.append(None)
decorations.append((index, SEPARATOR, "both", []))
continue
left_lines.append(row.left if row.left is not None else "")
right_lines.append(row.right if row.right is not None else "")
left_numbers.append(row.left_no)
right_numbers.append(row.right_no)
if row.tag != EQUAL:
decorations.append((index, row.tag, "left", row.left_spans))
decorations.append((index, row.tag, "right", row.right_spans))
self._left_pane.set_content(left_lines, left_numbers)
self._right_pane.set_content(right_lines, right_numbers)
self._resync_highlighters()
self._decorate(decorations)
def _decorate(self, decorations: list) -> None:
if len(self._display_rows) > self.MAX_DECORATED_ROWS:
self._left_pane.setExtraSelections([])
self._right_pane.setExtraSelections([])
return
by_pane: dict[str, list] = {"left": [], "right": []}
panes = {"left": self._left_pane, "right": self._right_pane}
colors = {
REPLACE: self._theme.changed,
DELETE: self._theme.removed,
INSERT: self._theme.added,
SEPARATOR: self._theme.separator,
}
strong = {"left": self._theme.removed_strong, "right": self._theme.added_strong}
for index, tag, side, spans in decorations:
targets = ("left", "right") if side == "both" else (side,)
for target in targets:
pane = panes[target]
block = pane.document().findBlockByNumber(index)
if not block.isValid():
continue
# An empty padding row on the losing side gets a flat filler colour
# so it reads as "nothing here" rather than "changed".
is_filler = (
(tag == DELETE and target == "right") or (tag == INSERT and target == "left")
)
selection = QTextEdit.ExtraSelection()
selection.format.setBackground(
self._theme.filler if is_filler else colors.get(tag, self._theme.changed))
selection.format.setProperty(QTextFormat.Property.FullWidthSelection, True)
cursor = QTextCursor(block)
cursor.clearSelection()
selection.cursor = cursor
by_pane[target].append(selection)
if tag != REPLACE or not spans:
continue
for start, end in spans:
if start >= end or start > block.length() - 1:
continue
span = QTextEdit.ExtraSelection()
span.format.setBackground(strong[target])
span_cursor = QTextCursor(block)
span_cursor.setPosition(block.position() + start)
span_cursor.setPosition(
block.position() + min(end, block.length() - 1),
QTextCursor.MoveMode.KeepAnchor)
span.cursor = span_cursor
by_pane[target].append(span)
for name, pane in panes.items():
pane.setExtraSelections(by_pane[name])
def _unified_lines(self) -> tuple[list[str], list[int | None], list[tuple[int, str]]]:
context = max(0, self._settings.integer("context_lines", 3))
rows = self._result.rows if self._result else []
keep = [False] * len(rows)
for index, row in enumerate(rows):
if row.tag != EQUAL:
for offset in range(max(0, index - context), min(len(rows), index + context + 1)):
keep[offset] = True
lines: list[str] = []
numbers: list[int | None] = []
marks: list[tuple[int, str]] = []
skipped = 0
def flush_skip() -> None:
nonlocal skipped
if skipped:
marks.append((len(lines), SEPARATOR))
lines.append(self.__tr("@@ {count} unchanged lines @@").format(
count=skipped))
numbers.append(None)
skipped = 0
for index, row in enumerate(rows):
if not keep[index]:
skipped += 1
continue
flush_skip()
if row.tag == EQUAL:
lines.append(f" {row.left}")
numbers.append(row.left_no)
elif row.tag == REPLACE:
marks.append((len(lines), DELETE))
lines.append(f"-{row.left}")
numbers.append(row.left_no)
marks.append((len(lines), INSERT))
lines.append(f"+{row.right}")
numbers.append(row.right_no)
elif row.tag == DELETE:
marks.append((len(lines), DELETE))
lines.append(f"-{row.left}")
numbers.append(row.left_no)
else:
marks.append((len(lines), INSERT))
lines.append(f"+{row.right}")
numbers.append(row.right_no)
flush_skip()
if not lines:
lines = [self.__tr("(no differences)")]
numbers = [None]
return lines, numbers, marks
def _render_unified(self) -> None:
lines, numbers, marks = self._unified_lines()
self._unified_pane.set_content(lines, numbers)
if len(lines) > self.MAX_DECORATED_ROWS:
self._unified_pane.setExtraSelections([])
return
colors = {
DELETE: self._theme.removed,
INSERT: self._theme.added,
SEPARATOR: self._theme.separator,