Repository navigation
Expand file tree
/
Copy pathplugin.py
More file actions
287 lines (244 loc) · 11.6 KB
/
Copy pathplugin.py
File metadata and controls
287 lines (244 loc) · 11.6 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
"""IPluginPreview implementation: diff view for conflicting text files."""
from __future__ import annotations
import os
import mobase
from PyQt6.QtCore import QByteArray, QCoreApplication, QSize, qInfo, qWarning
from PyQt6.QtWidgets import (
QFrame, QLabel, QMessageBox, QPlainTextEdit, QVBoxLayout, QWidget,
)
from .diffview import DiffPreviewWidget, mono_font
from .extensions import TEXT_TAKEOVER, build_extension_set, parse_extension_list
from .highlight import highlighter_for
from .resolve import resolve_variants
from .settings import SettingsProxy
from .textio import from_bytes, read_text
PLUGIN_NAME = "Preview Text Files"
PREVIEW_BASE = "Preview Base"
BLACKLIST_KEY = "blacklisted_extensions"
#: Single source of truth for the version; dev/build_release.py
#: reads this straight out of the AST, so it needs no imports.
VERSION = (1, 1, 0)
# Toolbar state, stored via persistent() rather than as settings.
REMEMBERED_KEYS = ("view_mode", "winner_left", "diff_engine",
"git_diff_algorithm", "only_differences",
"ignore_whitespace")
class _PlainPreview(QWidget):
"""Fallback view: the file as-is, highlighted but not diffed."""
def __init__(self):
super().__init__()
self.highlighter = None
def _plain_widget(text: str, extension: str = "", monospace: bool = True) -> QWidget:
widget = _PlainPreview()
layout = QVBoxLayout(widget)
layout.setContentsMargins(6, 6, 6, 6)
editor = QPlainTextEdit(widget)
editor.setReadOnly(True)
editor.setFrameShape(QFrame.Shape.NoFrame)
editor.setLineWrapMode(QPlainTextEdit.LineWrapMode.NoWrap)
if monospace:
editor.setFont(mono_font())
editor.setPlainText(text)
layout.addWidget(editor)
if extension:
dark = widget.palette().base().color().lightness() < 128
# Keep a reference so the highlighter is not garbage collected.
widget.highlighter = highlighter_for(extension, editor.document(), dark)
return widget
def _message_widget(message: str) -> QWidget:
widget = QWidget()
layout = QVBoxLayout(widget)
label = QLabel(message, widget)
label.setWordWrap(True)
layout.addWidget(label)
layout.addStretch(1)
return widget
class ConflictDiffPreview(mobase.IPluginPreview):
def __init__(self):
super().__init__()
self.__organizer = None
self.__settings: SettingsProxy | None = None
self.__extensions: set[str] = set()
self.__restart_notice = ""
# ------------------------------------------------------------- metadata
def name(self) -> str:
return PLUGIN_NAME
def author(self) -> str:
return "Langmans"
def description(self) -> str:
return self.__tr(
"Previews conflicting text files as a diff against the mod that wins "
"(or loses) the conflict, with syntax highlighting and a button to open "
"the same pair in WinMerge or any other compare tool."
)
def version(self) -> mobase.VersionInfo:
# Four ints: the release type defaults to FINAL. Avoids depending on the
# ReleaseType enum member spelling, which is FINAL (not 'final') in 2.5.
return mobase.VersionInfo(*VERSION, 0)
def __tr(self, txt: str) -> str:
# The context must match the class name for pylupdate6 to line up.
return QCoreApplication.translate("ConflictDiffPreview", txt)
def settings(self) -> list[mobase.PluginSetting]:
return [
mobase.PluginSetting(
"extra_extensions",
self.__tr("Extra file extensions to preview as a diff, comma separated "
"(e.g. 'dsd, def_i'). Requires a restart."),
""),
mobase.PluginSetting(
"excluded_extensions",
self.__tr("Extensions to drop from the defaults, comma separated. Accepts "
"whole groups: config, scripts, shaders, frameworks, docs. "
"Requires a restart."),
""),
mobase.PluginSetting(
"take_over_text_extensions",
self.__tr("Also handle txt/ini/json/log/cfg/psc by adding them to the "
"'Preview Base' plugin's blacklist. Requires a restart."),
True),
mobase.PluginSetting(
"theme",
self.__tr("Colour scheme: 'auto' measures the background MO2's "
"stylesheet actually paints; 'dark' or 'light' force it."),
"auto"),
mobase.PluginSetting(
"mo2_conflict_colors",
self.__tr("Use MO2's own conflict colours for the diff rows: "
"'normal' (removed = overwriting, added = overwritten), "
"'swapped', or 'off' for the built-in green/red."),
"normal"),
mobase.PluginSetting(
"git_path",
self.__tr("Path to git.exe. Leave empty to search PATH."),
""),
mobase.PluginSetting(
"word_diff",
self.__tr("Highlight the changed characters within changed lines."),
True),
mobase.PluginSetting(
"context_lines",
self.__tr("Unchanged lines kept around each change."),
3),
mobase.PluginSetting(
"external_tools",
self.__tr("JSON list of external compare tools. Leave empty to "
"auto-detect WinMerge / VS Code / Beyond Compare / KDiff3 / "
"Meld. Edit it from the preview via 'Compare in > Configure "
"tools'."),
""),
mobase.PluginSetting(
"max_diff_lines",
self.__tr("Files with more lines than this are shown but not "
"diffed; comparing them locks the interface for "
"seconds. 0 disables the limit."),
20000),
mobase.PluginSetting(
"max_file_size_kb",
self.__tr("Files larger than this are not diffed inline; the external "
"compare tools still work."),
2048),
]
# ----------------------------------------------------------------- init
#: Settings and remembered toolbar state are keyed on the plugin name, so a
#: rename would silently orphan them. Anything found under the old name is
#: carried over once.
FORMER_NAMES = ("Conflict Diff Preview", "Preview Source Code")
def init(self, organizer: mobase.IOrganizer) -> bool:
self.__organizer = organizer
self.__settings = SettingsProxy(organizer, PLUGIN_NAME)
try:
keys = [s.key for s in self.settings()]
for former in self.FORMER_NAMES:
self.__settings.adopt_from(former, keys, REMEMBERED_KEYS)
except Exception as exc:
qWarning(f"[{PLUGIN_NAME}] could not carry over old settings: {exc}")
try:
self.__extensions = build_extension_set(
extra=self.__settings.string("extra_extensions", ""),
excluded=self.__settings.string("excluded_extensions", ""),
take_over_text=self.__settings.boolean("take_over_text_extensions", True),
)
qInfo(f"[{PLUGIN_NAME}] handling: "
f"{', '.join(sorted(self.__extensions))}")
except Exception as exc: # never let a bad setting stop MO2 from starting
qWarning(f"[{PLUGIN_NAME}] failed to build extension set: {exc}")
self.__extensions = build_extension_set()
try:
self.__sync_preview_base()
except Exception as exc:
qWarning(f"[{PLUGIN_NAME}] could not update {PREVIEW_BASE}: {exc}")
try:
organizer.onUserInterfaceInitialized(self.__on_ui_initialized)
except Exception:
pass
return True
def __sync_preview_base(self) -> None:
"""Add/remove our text extensions in preview_base's blacklist.
preview_base builds its extension map in init() and skips blacklisted
entries, and the first preview plugin that claims an extension wins the
lookup -- with DLLs loading before Python plugins, that would always be
preview_base. Blacklisting is the supported way to hand them over.
"""
take_over = self.__settings.boolean("take_over_text_extensions", True)
raw = self.__settings.foreign(PREVIEW_BASE, BLACKLIST_KEY, None)
if raw is None:
qInfo(f"[{PLUGIN_NAME}] '{PREVIEW_BASE}' not found; leaving its settings "
f"alone")
return
current = parse_extension_list(str(raw))
updated = (current | TEXT_TAKEOVER) if take_over else (current - TEXT_TAKEOVER)
if updated == current:
return
value = ",".join(sorted(updated))
if not self.__settings.set_foreign(PREVIEW_BASE, BLACKLIST_KEY, value):
return
extensions = ", ".join(sorted(TEXT_TAKEOVER))
if take_over:
headline = self.__tr("{plugin} updated the '{other}' plugin so that "
"{extensions} are handed over to the diff preview.")
else:
headline = self.__tr("{plugin} updated the '{other}' plugin so that "
"{extensions} are returned to it.")
self.__restart_notice = (
headline.format(plugin=PLUGIN_NAME, other=PREVIEW_BASE, extensions=extensions)
+ "\n\n"
+ self.__tr("Restart Mod Organizer for this to take effect.")
)
qInfo(f"[{PLUGIN_NAME}] {PREVIEW_BASE}/{BLACKLIST_KEY} = "
f"{value}")
def __on_ui_initialized(self, window) -> None:
if self.__restart_notice:
QMessageBox.information(window, PLUGIN_NAME, self.__restart_notice)
self.__restart_notice = ""
# -------------------------------------------------------------- preview
def supportedExtensions(self) -> set[str]: # noqa: N802 (Qt/MO2 naming)
if not self.__extensions:
self.__extensions = build_extension_set()
return set(self.__extensions)
def supportsArchives(self) -> bool: # noqa: N802
return True
def genFilePreview(self, fileName: str, maxSize: QSize) -> QWidget: # noqa: N802
try:
resolution = resolve_variants(self.__organizer, fileName)
return DiffPreviewWidget(self.__settings, resolution)
except Exception as exc:
qWarning(f"[{PLUGIN_NAME}] diff preview failed for {fileName}: "
f"{exc}")
handle = read_text(fileName, self.__max_bytes())
if handle.error:
return _message_widget(
self.__tr("Could not read {path}:").format(path=fileName)
+ "\n" + handle.error)
return _plain_widget(handle.text, os.path.splitext(fileName)[1])
def genDataPreview(self, fileData: QByteArray, fileName: str, # noqa: N802
maxSize: QSize) -> QWidget:
# Archive contents have no second copy on disk to diff against, so this
# is a plain highlighted view.
try:
handle = from_bytes(fileData.data())
return _plain_widget(handle.text, os.path.splitext(fileName)[1])
except Exception as exc:
return _message_widget(
self.__tr("Could not decode {path}:").format(path=fileName)
+ "\n" + str(exc))
def __max_bytes(self) -> int:
return max(0, self.__settings.integer("max_file_size_kb", 2048)) * 1024