-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmdexplore.py
More file actions
11193 lines (10321 loc) · 455 KB
/
mdexplore.py
File metadata and controls
11193 lines (10321 loc) · 455 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
#!/usr/bin/env python3
"""mdexplore: fast markdown browser/editor launcher for Ubuntu."""
from __future__ import annotations
import argparse
import base64
import fcntl
import html
import hashlib
from html.parser import HTMLParser
from io import BytesIO
import json
import math
import mimetypes
import os
import re
import shutil
import subprocess
import sys
import tempfile
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from threading import Event, Lock
import time
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
from collections import deque
from difflib import SequenceMatcher
from pathlib import Path
from typing import Callable
from markdown_it import MarkdownIt
from mdit_py_plugins.dollarmath import dollarmath_plugin
from PySide6.QtCore import (
QDir,
QEventLoop,
QMimeData,
QObject,
QPoint,
QRect,
QSize,
Qt,
QThreadPool,
QTimer,
QUrl,
Signal,
)
from PySide6.QtGui import (
QAction,
QBrush,
QClipboard,
QColor,
QFont,
QFontDatabase,
QFontMetrics,
QIcon,
QImage,
QPainter,
QPalette,
QPen,
QPixmap,
QPolygon,
)
from PySide6.QtWebEngineCore import (
QWebEnginePage,
QWebEngineProfile,
QWebEngineSettings,
)
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtWidgets import (
QApplication,
QFileDialog,
QHBoxLayout,
QInputDialog,
QLabel,
QLineEdit,
QMainWindow,
QMenu,
QMessageBox,
QPushButton,
QRadioButton,
QSizePolicy,
QSplitter,
QStyle,
QTreeView,
QVBoxLayout,
QWidget,
)
from mdexplore_app.constants import (
CONFIG_FILE_NAME,
DIAGRAM_VIEW_STATE_JSON_TOKEN,
MAX_PRINT_DIAGRAM_FONT_PT,
MERMAID_BACKEND_JS,
MERMAID_BACKEND_RUST,
MERMAID_CACHE_JSON_TOKEN,
MERMAID_CACHE_RESTORE_BATCH_SIZE,
MERMAID_SVG_CACHE_MAX_ENTRIES,
MERMAID_SVG_MAX_CHARS,
MIN_PRINT_DIAGRAM_FONT_PT,
PDF_EXPORT_PRECHECK_INTERVAL_MS,
PDF_EXPORT_PRECHECK_MAX_ATTEMPTS,
PLANTUML_RESTORE_BATCH_SIZE,
PREVIEW_HIGHLIGHT_KIND_IMPORTANT,
PREVIEW_HIGHLIGHT_KIND_NORMAL,
PREVIEW_PERSISTENT_HIGHLIGHT_COLOR,
PREVIEW_PERSISTENT_HIGHLIGHT_IMPORTANT_COLOR,
PREVIEW_PERSISTENT_HIGHLIGHT_IMPORTANT_MARKER_COLOR,
PREVIEW_PERSISTENT_HIGHLIGHT_IMPORTANT_TEXT_COLOR,
PREVIEW_PERSISTENT_HIGHLIGHT_MARKER_COLOR,
PREVIEW_SETHTML_MAX_BYTES,
PREVIEW_ZOOM_MAX,
PREVIEW_ZOOM_MIN,
PREVIEW_ZOOM_OVERLAY_TIMEOUT_MS,
PREVIEW_ZOOM_RESET,
PREVIEW_ZOOM_STEP,
RESTORE_OVERLAY_MAX_VISIBLE_SECONDS,
RESTORE_OVERLAY_SHOW_DELAY_MS,
RESTORE_OVERLAY_TIMEOUT_SECONDS,
PDF_LANDSCAPE_PAGE_TOKEN,
SEARCH_CLOSE_WORD_GAP,
)
from mdexplore_app.icons import (
build_clear_x_icon as _build_clear_x_icon,
build_markdown_icon as _build_markdown_icon,
load_png_icon_two_tone as _load_png_icon_two_tone,
load_svg_icon as _load_svg_icon,
load_svg_icon_two_tone as _load_svg_icon_two_tone,
ui_asset_path as _ui_asset_path,
)
from mdexplore_app.fast_base64 import (
b64decode_loose as _b64decode_loose,
b64encode_ascii as _b64encode_ascii,
)
from mdexplore_app.js import (
preload_js_assets as _preload_js_assets,
render_js_asset as _render_js_asset,
)
try:
import cmarkgfm as _cmarkgfm
except Exception:
_cmarkgfm = None
from mdexplore_app.templates import (
preload_template_assets as _preload_template_assets,
render_template_asset as _render_template_asset,
)
from mdexplore_app.pdf import (
extract_plantuml_error_details as _extract_plantuml_error_details,
stamp_pdf_page_numbers as _stamp_pdf_page_numbers,
)
import mdexplore_app.search as _search_query
from mdexplore_app.runtime import (
config_file_path as _config_file_path,
configure_qt_graphics_fallback as _configure_qt_graphics_fallback,
gpu_context_available as _gpu_context_available,
letter_pdf_page_layout as _letter_pdf_page_layout,
load_default_root_from_config as _load_default_root_from_config,
pdf_print_layout_knobs as _pdf_print_layout_knobs,
search_hit_count_font_family as _search_hit_count_font_family,
)
from mdexplore_app.tabs import ViewTabBar
from mdexplore_app.tree import ColorizedMarkdownModel, MarkdownTreeItemDelegate
from mdexplore_app.workers import (
InlineDataImageMaterializeWorker,
PdfExportWorker,
PlantUmlRenderWorker,
PreviewRenderWorker,
SearchScanWorker,
TreeMarkerScanWorker,
)
PREVIEW_HIGHLIGHT_OFFSET_SPACE_PREVIEW = "preview_text_v2"
PREVIEW_HIGHLIGHT_OFFSET_SPACE_SOURCE = "markdown_source_v1"
_PREVIEW_INLINE_DATA_IMAGE_SRC_RE = re.compile(
r'(<img\b[^>]*?\bsrc=)(["\'])(data:[^"\']+;base64,[^"\']+)\2',
flags=re.IGNORECASE,
)
_CMARK_SOURCEPOS_ATTR_RE = re.compile(
r'\sdata-sourcepos="(?P<start>\d+):\d+-(?P<end>\d+):\d+"',
flags=re.IGNORECASE,
)
_CMARK_CODE_BLOCK_RE = re.compile(
r"(?P<pre_open><pre\b[^>]*>)\s*<code\b(?P<code_attrs>[^>]*)>(?P<code>.*?)</code>\s*</pre>",
flags=re.IGNORECASE | re.DOTALL,
)
_PREVIEW_INLINE_DATA_IMAGE_MIME_EXTENSION_OVERRIDES = {
"image/svg+xml": ".svg",
"image/jpeg": ".jpg",
}
_PREVIEW_INLINE_IMAGE_PLACEHOLDER_DATA_URI = (
"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="
)
class _PreviewLogicalTextExtractor(HTMLParser):
"""Extract the preview's countable text stream from cached HTML."""
_SKIP_TAGS = {"script", "style", "noscript", "textarea"}
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self._inside_main = False
self._skip_depth = 0
self._chunks: list[str] = []
@staticmethod
def _countable_text(value: str) -> str:
source = value if isinstance(value, str) else ""
if not source:
return ""
parts: list[str] = []
cursor = 0
for match in re.finditer(r"\s+", source):
if match.start() > cursor:
parts.append(source[cursor : match.start()])
raw = match.group(0)
if not re.search(r"[\r\n\t]", raw):
parts.append(raw)
cursor = match.end()
if cursor < len(source):
parts.append(source[cursor:])
return "".join(parts)
def handle_starttag(self, tag: str, attrs) -> None:
normalized = str(tag or "").strip().lower()
if normalized == "main":
self._inside_main = True
if self._inside_main and normalized in self._SKIP_TAGS:
self._skip_depth += 1
def handle_endtag(self, tag: str) -> None:
normalized = str(tag or "").strip().lower()
if self._inside_main and normalized in self._SKIP_TAGS and self._skip_depth > 0:
self._skip_depth -= 1
if normalized == "main":
self._inside_main = False
self._skip_depth = 0
def handle_data(self, data: str) -> None:
if not self._inside_main or self._skip_depth > 0:
return
countable = self._countable_text(data)
if countable:
self._chunks.append(countable)
def logical_text(self) -> str:
return "".join(self._chunks)
class MarkdownRenderer:
"""Converts markdown to HTML with Mermaid, MathJax, and PlantUML support."""
def __init__(self, mermaid_backend: str = MERMAID_BACKEND_JS) -> None:
# Backend selection is resolved once per renderer so the markdown fence
# callbacks can stay simple and deterministic.
self._mermaid_backend_requested = (
str(mermaid_backend or MERMAID_BACKEND_JS).strip().lower()
)
if self._mermaid_backend_requested not in {
MERMAID_BACKEND_JS,
MERMAID_BACKEND_RUST,
}:
self._mermaid_backend_requested = MERMAID_BACKEND_JS
self._mermaid_rs_binary = self._resolve_mermaid_rs_binary()
self._mermaid_rs_setup_issue = self._mermaid_rs_setup_error()
if (
self._mermaid_backend_requested == MERMAID_BACKEND_RUST
and self._mermaid_rs_setup_issue is None
):
self._mermaid_backend = MERMAID_BACKEND_RUST
else:
self._mermaid_backend = MERMAID_BACKEND_JS
self._mermaid_svg_cache: dict[str, str] = {}
self._last_mermaid_pdf_svg_by_hash: dict[str, str] = {}
self._mathjax_local_script = self._resolve_local_mathjax_script()
self._mermaid_local_script = self._resolve_local_mermaid_script()
self._plantuml_jar_path = self._resolve_plantuml_jar_path()
self._plantuml_setup_issue = self._plantuml_setup_error()
self._plantuml_svg_cache: dict[str, str] = {}
cmark_mode_raw = os.environ.get("MDEXPLORE_MARKDOWN_ENGINE", "cmark")
cmark_mode = str(cmark_mode_raw or "cmark").strip().lower()
if cmark_mode not in {"auto", "cmark", "markdown-it"}:
cmark_mode = "auto"
self._markdown_engine_mode = cmark_mode
self._cmark_available = _cmarkgfm is not None
if self._cmark_available:
try:
self._cmark_options = int(
_cmarkgfm.Options.CMARK_OPT_UNSAFE
| _cmarkgfm.Options.CMARK_OPT_SOURCEPOS
| _cmarkgfm.Options.CMARK_OPT_SMART
| _cmarkgfm.Options.CMARK_OPT_STRIKETHROUGH_DOUBLE_TILDE
)
except Exception:
self._cmark_options = 0
else:
self._cmark_options = 0
self._md = (
MarkdownIt(
"commonmark",
{"html": True, "linkify": True, "typographer": True},
)
.enable("table")
.enable("strikethrough")
)
# Parse $...$ / $$...$$ as dedicated math tokens before markdown
# emphasis/underscore rules run, preventing TeX corruption.
self._md.use(dollarmath_plugin)
default_fence = self._md.renderer.rules["fence"]
default_render_token = self._md.renderer.renderToken
def custom_math_inline(tokens, idx, options, env):
token = tokens[idx]
# Keep TeX content raw for MathJax, only HTML-escape unsafe chars.
return f"${html.escape(token.content)}$"
def custom_math_block(tokens, idx, options, env):
token = tokens[idx]
line_attrs = ""
if token.map and len(token.map) == 2:
line_attrs = f' data-md-line-start="{token.map[0]}" data-md-line-end="{token.map[1]}"'
math_body = (token.content or "").strip("\n")
return f'<div class="mdexplore-math-block"{line_attrs}>$$\n{html.escape(math_body)}\n$$</div>\n'
def custom_fence(tokens, idx, options, env):
# Intercept known diagram fences and delegate the rest to the
# default fenced-code renderer. This is the only place where raw
# markdown fence language is turned into preview/PDF placeholders.
token = tokens[idx]
info = token.info.strip().split(maxsplit=1)[0].lower() if token.info else ""
code = token.content
line_attrs = ""
if token.map and len(token.map) == 2:
line_attrs = f' data-md-line-start="{token.map[0]}" data-md-line-end="{token.map[1]}"'
if info == "mermaid":
return self._render_mermaid_fence_html(code, line_attrs, env)
if info in {"plantuml", "puml", "uml"}:
return self._render_plantuml_fence_html(info, code, line_attrs, env)
return default_fence(tokens, idx, options, env)
def custom_render_token(tokens, idx, options, env):
# Attach source-line metadata so preview selections can map back
# to source markdown ranges for copy operations.
token = tokens[idx]
if (
token.nesting == 1
and token.type.endswith("_open")
and token.map
and len(token.map) == 2
):
token.attrSet("data-md-line-start", str(token.map[0]))
token.attrSet("data-md-line-end", str(token.map[1]))
return default_render_token(tokens, idx, options, env)
self._md.renderer.rules["fence"] = custom_fence
self._md.renderer.rules["math_inline"] = custom_math_inline
self._md.renderer.rules["math_block"] = custom_math_block
self._md.renderer.renderToken = custom_render_token
@staticmethod
def _line_attrs_from_sourcepos_match(match: re.Match[str]) -> str:
"""Convert one cmark `data-sourcepos` span to mdexplore 0-based attrs."""
try:
start_line = max(1, int(match.group("start")))
end_line = max(start_line, int(match.group("end")))
except Exception:
return match.group(0)
return (
f' data-md-line-start="{start_line - 1}" '
f'data-md-line-end="{end_line}"'
)
def _rewrite_cmark_sourcepos_attrs(self, html_body: str) -> str:
"""Map cmark source-position attrs to mdexplore line-range attrs."""
try:
return _CMARK_SOURCEPOS_ATTR_RE.sub(
self._line_attrs_from_sourcepos_match, html_body
)
except Exception:
return html_body
@staticmethod
def _extract_code_language_from_attrs(code_attrs: str) -> str:
"""Extract lower-case language suffix from one code-block class attr."""
raw = str(code_attrs or "")
class_match = re.search(
r'class\s*=\s*(?:"(?P<dq>[^"]*)"|\'(?P<sq>[^\']*)\')',
raw,
flags=re.IGNORECASE,
)
class_value = ""
if class_match is not None:
class_value = class_match.group("dq") or class_match.group("sq") or ""
for token in class_value.split():
lowered = token.strip().lower()
if lowered.startswith("language-") and len(lowered) > len("language-"):
return lowered[len("language-") :]
return ""
@staticmethod
def _extract_pre_language_from_attrs(pre_open: str) -> str:
"""Extract lower-case language from cmark `<pre ... lang=...>` attrs."""
raw = str(pre_open or "")
lang_match = re.search(
r'\blang\s*=\s*(?:"(?P<dq>[^"]*)"|\'(?P<sq>[^\']*)\')',
raw,
flags=re.IGNORECASE,
)
if lang_match is not None:
lang_value = (lang_match.group("dq") or lang_match.group("sq") or "").strip()
if lang_value:
return lang_value.lower()
class_match = re.search(
r'class\s*=\s*(?:"(?P<dq>[^"]*)"|\'(?P<sq>[^\']*)\')',
raw,
flags=re.IGNORECASE,
)
class_value = ""
if class_match is not None:
class_value = class_match.group("dq") or class_match.group("sq") or ""
for token in class_value.split():
lowered = token.strip().lower()
if lowered.startswith("language-") and len(lowered) > len("language-"):
return lowered[len("language-") :]
return ""
def _rewrite_cmark_special_fences(self, html_body: str, env: dict[str, object]) -> str:
"""Replace cmark-rendered Mermaid/PlantUML code fences with mdexplore blocks."""
def _replace(match: re.Match[str]) -> str:
pre_open = str(match.group("pre_open") or "")
start_match = re.search(
r'data-md-line-start="(?P<start>\d+)"', pre_open, flags=re.IGNORECASE
)
end_match = re.search(
r'data-md-line-end="(?P<end>\d+)"', pre_open, flags=re.IGNORECASE
)
line_attrs = ""
if start_match is not None and end_match is not None:
line_attrs = (
f' data-md-line-start="{start_match.group("start")}"'
f' data-md-line-end="{end_match.group("end")}"'
)
language = self._extract_code_language_from_attrs(match.group("code_attrs"))
if not language:
language = self._extract_pre_language_from_attrs(pre_open)
if language == "mermaid":
code_text = html.unescape(match.group("code") or "")
return self._render_mermaid_fence_html(code_text, line_attrs, env)
if language in {"plantuml", "puml", "uml"}:
code_text = html.unescape(match.group("code") or "")
return self._render_plantuml_fence_html(language, code_text, line_attrs, env)
return match.group(0)
try:
return _CMARK_CODE_BLOCK_RE.sub(_replace, html_body)
except Exception:
return html_body
def _render_body_with_cmark(
self, markdown_text: str, env: dict[str, object]
) -> str | None:
"""Render markdown via cmark-gfm, preserving mdexplore line metadata."""
if not self._cmark_available or _cmarkgfm is None:
return None
try:
body = _cmarkgfm.github_flavored_markdown_to_html(
markdown_text, options=int(self._cmark_options)
)
if not isinstance(body, str):
return None
body = self._rewrite_cmark_sourcepos_attrs(body)
body = self._rewrite_cmark_special_fences(body, env)
return body
except Exception:
return None
def _should_use_cmark_fast_path(
self, markdown_text: str, has_math_hint: bool | None = None
) -> bool:
"""Return whether cmark fast rendering should be attempted."""
if not self._cmark_available:
return False
mode = self._markdown_engine_mode
if mode in {"markdown-it", "auto"}:
return False
has_math = (
bool(has_math_hint)
if has_math_hint is not None
else (
bool(re.search(r"(?s)(?<!\\)\$\$(.+?)(?<!\\)\$\$", markdown_text))
or bool(re.search(r"(?<!\\)\$(?!\s)(.+?)(?<!\\)\$", markdown_text))
)
)
if has_math:
return False
return mode == "cmark"
def _render_mermaid_fence_html(
self, code: str, line_attrs: str, env: dict[str, object] | None
) -> str:
"""Render one Mermaid fence to mdexplore preview HTML."""
try:
prepared_source = self._prepare_mermaid_source(code)
mermaid_hash = hashlib.sha1(
prepared_source.encode("utf-8", errors="replace")
).hexdigest()
mermaid_index = int(env.get("mermaid_index", 0)) if isinstance(env, dict) else 0
if isinstance(env, dict):
env["mermaid_index"] = mermaid_index + 1
if self._mermaid_backend == MERMAID_BACKEND_RUST:
svg_markup, error_message = self._render_mermaid_svg_markup(
prepared_source, "preview"
)
if isinstance(env, dict):
pdf_svg_map = env.get("mermaid_pdf_svg_by_hash")
if isinstance(pdf_svg_map, dict) and mermaid_hash not in pdf_svg_map:
pdf_svg, _pdf_error = self._render_mermaid_svg_markup(
prepared_source, "pdf"
)
if pdf_svg:
pdf_svg_map[mermaid_hash] = pdf_svg
source_attr = html.escape(prepared_source, quote=True)
if svg_markup is not None:
return (
f'<div class="mdexplore-fence"{line_attrs}>'
f'<div class="mermaid mermaid-ready" data-mdexplore-mermaid-backend="rust" '
f'data-mdexplore-mermaid-hash="{mermaid_hash}" '
f'data-mdexplore-mermaid-index="{mermaid_index}" '
f'data-mdexplore-mermaid-source="{source_attr}">\n{svg_markup}\n</div>'
"</div>\n"
)
safe_error_attr = html.escape(
error_message or "Rust Mermaid rendering failed", quote=True
)
return (
f'<div class="mdexplore-fence"{line_attrs}>'
f'<div class="mermaid mermaid-rust-fallback" data-mdexplore-mermaid-backend="rust" '
f'data-mdexplore-mermaid-hash="{mermaid_hash}" '
f'data-mdexplore-mermaid-index="{mermaid_index}" '
f'data-mdexplore-mermaid-source="{source_attr}" '
f'data-mdexplore-rust-error="{safe_error_attr}">'
"Mermaid rendering..."
"</div>"
"</div>\n"
)
return (
f'<div class="mdexplore-fence"{line_attrs}>'
f'<div class="mermaid" data-mdexplore-mermaid-hash="{mermaid_hash}" '
f'data-mdexplore-mermaid-index="{mermaid_index}">\n{html.escape(code)}\n</div>'
"</div>\n"
)
except Exception as exc:
safe_error = html.escape(str(exc) or "unexpected Mermaid rendering error")
return (
f'<div class="mdexplore-fence mermaid-error"{line_attrs}>'
f'<div class="mermaid mermaid-error">Mermaid render failed: {safe_error}</div>'
"</div>\n"
)
def _render_plantuml_fence_html(
self,
info: str,
code: str,
line_attrs: str,
env: dict[str, object] | None,
) -> str:
"""Render one PlantUML fence to mdexplore preview HTML."""
resolver = env.get("plantuml_resolver") if isinstance(env, dict) else None
if callable(resolver) and isinstance(env, dict):
plantuml_index = int(env.get("plantuml_index", 0))
env["plantuml_index"] = plantuml_index + 1
try:
return str(resolver(code, plantuml_index, line_attrs))
except Exception:
pass
data_uri, error_message = self._render_plantuml_data_uri(code)
if data_uri is not None:
return (
f'<div class="mdexplore-fence"{line_attrs}>'
f'<img class="plantuml" src="{data_uri}" alt="PlantUML diagram"/>'
"</div>\n"
)
escaped_error = html.escape(error_message or "PlantUML rendering failed")
escaped_code = html.escape(code)
language = html.escape(info or "plantuml")
return (
f'<div class="mdexplore-fence plantuml-error"{line_attrs}>'
f'<div class="plantuml-error-message">{escaped_error}</div>'
f'<pre><code class="language-{language}">{escaped_code}</code></pre>'
"</div>\n"
)
@property
def mermaid_backend(self) -> str:
"""Return active Mermaid backend (`js` or `rust`)."""
return self._mermaid_backend
@property
def mermaid_backend_requested(self) -> str:
"""Return requested Mermaid backend from CLI/config."""
return self._mermaid_backend_requested
def mermaid_backend_warning(self) -> str | None:
"""Describe why requested Mermaid backend could not be activated."""
if (
self._mermaid_backend_requested == MERMAID_BACKEND_RUST
and self._mermaid_backend != MERMAID_BACKEND_RUST
):
return self._mermaid_rs_setup_issue or "Rust Mermaid backend unavailable"
return None
def _resolve_mermaid_rs_binary(self) -> Path | None:
"""Locate mmdr executable for Rust Mermaid rendering."""
env_value = os.environ.get("MDEXPLORE_MERMAID_RS_BIN", "").strip()
candidates: list[Path] = []
if env_value:
candidates.append(Path(env_value).expanduser())
app_dir = Path(__file__).resolve().parent
candidates.extend(
[
Path.home() / ".cargo" / "bin" / "mmdr",
app_dir
/ "vendor"
/ "mermaid-rs-renderer"
/ "target"
/ "release"
/ "mmdr",
app_dir / "vendor" / "mermaid-rs-renderer" / "mmdr",
app_dir / "vendor" / "mermaid-rs-renderer" / "bin" / "mmdr",
app_dir / "mermaid-rs-renderer" / "target" / "release" / "mmdr",
app_dir / "mmdr",
]
)
for candidate in candidates:
try:
if candidate.is_file() and os.access(candidate, os.X_OK):
return candidate.resolve()
except Exception:
continue
for name in ("mmdr", "mermaid-rs-renderer"):
found = shutil.which(name)
if found:
try:
return Path(found).resolve()
except Exception:
return Path(found)
return None
def _mermaid_rs_setup_error(self) -> str | None:
"""Return setup issue text when Rust Mermaid backend is unavailable."""
if self._mermaid_rs_binary is None:
return (
"mmdr executable not found "
"(set MDEXPLORE_MERMAID_RS_BIN or install mermaid-rs-renderer)"
)
return None
def _render_mermaid_svg_markup(
self, code: str, render_profile: str = "preview"
) -> tuple[str | None, str | None]:
"""Render Mermaid source through Rust mmdr backend and return raw SVG."""
if self._mermaid_rs_setup_issue is not None:
return None, self._mermaid_rs_setup_issue
if self._mermaid_rs_binary is None:
return None, "mmdr executable not available"
profile = str(render_profile or "preview").strip().lower()
if profile not in {"preview", "pdf"}:
profile = "preview"
prepared_source = self._prepare_mermaid_source(code)
if profile == "preview":
rust_theme_config = self._rust_mermaid_theme_config()
config_signature = json.dumps(
rust_theme_config,
sort_keys=True,
separators=(",", ":"),
ensure_ascii=False,
)
else:
# PDF-mode Rust rendering should stay vanilla/default.
rust_theme_config = None
config_signature = "__MDEXPLORE_RUST_DEFAULT_THEME__"
cache_key = hashlib.sha1(
(
profile
+ "\n__MDEXPLORE_RUST_PROFILE__\n"
+ prepared_source
+ "\n__MDEXPLORE_RUST_CFG__\n"
+ config_signature
).encode("utf-8", errors="replace")
).hexdigest()
cached = self._mermaid_svg_cache.get(cache_key)
if cached is not None:
return cached, None
tmp_input_path = None
tmp_output_path = None
tmp_config_path = None
try:
input_file = tempfile.NamedTemporaryFile(
"w", encoding="utf-8", suffix=".mmd", delete=False
)
tmp_input_path = Path(input_file.name)
input_file.write(prepared_source)
input_file.flush()
input_file.close()
output_file = tempfile.NamedTemporaryFile(
"w", encoding="utf-8", suffix=".svg", delete=False
)
tmp_output_path = Path(output_file.name)
output_file.close()
candidate_commands = []
if profile == "preview":
config_file = tempfile.NamedTemporaryFile(
"w", encoding="utf-8", suffix=".json", delete=False
)
tmp_config_path = Path(config_file.name)
config_file.write(config_signature)
config_file.flush()
config_file.close()
# `mmdr` CLI signatures vary by build. Prefer the current
# flag-based form (-i/-o/-e), then fall back to positional.
candidate_commands.extend(
[
[
str(self._mermaid_rs_binary),
"-i",
str(tmp_input_path),
"-o",
str(tmp_output_path),
"-e",
"svg",
"-c",
str(tmp_config_path),
],
[
str(self._mermaid_rs_binary),
"-i",
str(tmp_input_path),
"-o",
str(tmp_output_path),
"-e",
"svg",
],
[
str(self._mermaid_rs_binary),
str(tmp_input_path),
str(tmp_output_path),
"--output-format",
"svg",
],
]
)
else:
candidate_commands.extend(
[
[
str(self._mermaid_rs_binary),
"-i",
str(tmp_input_path),
"-o",
str(tmp_output_path),
"-e",
"svg",
],
[
str(self._mermaid_rs_binary),
str(tmp_input_path),
str(tmp_output_path),
"--output-format",
"svg",
],
]
)
result = None
for command in candidate_commands:
result = subprocess.run(
command,
text=True,
capture_output=True,
check=False,
timeout=20,
)
if result.returncode == 0:
break
if result is None or result.returncode != 0:
error_text = (
(result.stderr if result is not None else "")
or (result.stdout if result is not None else "")
or ""
).strip()
if not error_text:
code = result.returncode if result is not None else "unknown"
error_text = f"mmdr exited with code {code}"
return None, error_text
svg_markup = tmp_output_path.read_text(
encoding="utf-8", errors="replace"
).strip()
if "<svg" not in svg_markup.casefold():
return None, "mmdr did not produce SVG output"
cleaned_svg = (
self._sanitize_rust_mermaid_svg_markup(svg_markup)
if profile == "preview"
else svg_markup
)
self._mermaid_svg_cache[cache_key] = cleaned_svg
return cleaned_svg, None
except subprocess.TimeoutExpired:
return None, "mmdr render timed out"
except Exception as exc:
return None, f"Rust Mermaid render failed: {exc}"
finally:
if tmp_input_path is not None:
try:
tmp_input_path.unlink(missing_ok=True)
except Exception:
pass
if tmp_output_path is not None:
try:
tmp_output_path.unlink(missing_ok=True)
except Exception:
pass
if tmp_config_path is not None:
try:
tmp_config_path.unlink(missing_ok=True)
except Exception:
pass
@staticmethod
def _rust_mermaid_theme_config() -> dict[str, object]:
"""Dark-theme palette for Rust Mermaid output in GUI preview mode."""
return {
"theme": "base",
"themeVariables": {
"background": "#0f172a",
"primaryColor": "#1e293b",
"primaryBorderColor": "#93c5fd",
"primaryTextColor": "#e5e7eb",
"secondaryColor": "#172554",
"tertiaryColor": "#111827",
"lineColor": "#d1d5db",
"textColor": "#e5e7eb",
"edgeLabelBackground": "#0f172a",
"clusterBkg": "#1f2937",
"clusterBorder": "#94a3b8",
"actorBkg": "#1e293b",
"actorBorder": "#93c5fd",
"actorLine": "#d1d5db",
"noteBkg": "#1f2937",
"noteBorderColor": "#93c5fd",
"fontFamily": "Noto Sans, DejaVu Sans, sans-serif",
},
}
@staticmethod
def _parse_svg_length(value: str | None) -> float | None:
"""Parse numeric SVG lengths from values like '123', '123px', '123.4%'."""
if not value:
return None
match = re.search(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?", str(value))
if not match:
return None
try:
return float(match.group(0))
except Exception:
return None
@classmethod
def _sanitize_rust_mermaid_svg_markup(cls, svg_markup: str) -> str:
"""Remove opaque white canvas background from Rust Mermaid SVG output."""
if not svg_markup:
return svg_markup
try:
root = ET.fromstring(svg_markup)
except Exception:
return svg_markup
def local_name(tag: str) -> str:
return tag.rsplit("}", 1)[-1] if "}" in tag else tag
if local_name(root.tag).lower() != "svg":
return svg_markup
# Some renderers add root-level background styles; strip them for
# dark preview transparency.
style_attr = str(root.attrib.get("style", "")).strip()
if style_attr:
style_parts = [
part.strip() for part in style_attr.split(";") if part.strip()
]
kept_parts = [
part for part in style_parts if "background" not in part.casefold()
]
if kept_parts:
root.set("style", "; ".join(kept_parts))
else:
root.attrib.pop("style", None)
view_w = None
view_h = None
view_box = str(root.attrib.get("viewBox", "")).strip()
if view_box:
numbers = [
float(part)
for part in re.findall(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?", view_box)
]
if len(numbers) == 4:
view_w = numbers[2]
view_h = numbers[3]
if view_w is None or view_h is None:
view_w = cls._parse_svg_length(root.attrib.get("width"))
view_h = cls._parse_svg_length(root.attrib.get("height"))
white_fill_values = {
"#fff",
"#ffffff",
"white",
"rgb(255,255,255)",
"rgba(255,255,255,1)",
"rgba(255,255,255,1.0)",
}
# Rust output commonly injects a first full-canvas white <rect>.
# Remove only when it clearly covers the canvas.
for child in list(root):
if local_name(child.tag).lower() != "rect":
continue
fill_value = (
str(child.attrib.get("fill", "")).strip().casefold().replace(" ", "")
)
if not fill_value:
style_text = str(child.attrib.get("style", ""))
style_match = re.search(
r"(?:^|;)\s*fill\s*:\s*([^;]+)", style_text, flags=re.IGNORECASE
)
if style_match:
fill_value = (
style_match.group(1).strip().casefold().replace(" ", "")
)
if fill_value not in white_fill_values:
continue
x = cls._parse_svg_length(child.attrib.get("x")) or 0.0
y = cls._parse_svg_length(child.attrib.get("y")) or 0.0
w = cls._parse_svg_length(child.attrib.get("width"))
h = cls._parse_svg_length(child.attrib.get("height"))
if view_w and view_h and w and h:
covers_canvas = (
x <= 1.0
and y <= 1.0
and w >= (view_w * 0.97)
and h >= (view_h * 0.97)
)
else:
covers_canvas = x <= 1.0 and y <= 1.0
if not covers_canvas:
continue
root.remove(child)
break
try:
if root.tag.startswith("{") and "}" in root.tag:
namespace_uri = root.tag[1:].split("}", 1)[0]
ET.register_namespace("", namespace_uri)
return ET.tostring(root, encoding="unicode")
except Exception:
return svg_markup
def _resolve_local_mathjax_script(self) -> Path | None:
"""Locate a local MathJax bundle, preferring SVG output quality."""
env_value = os.environ.get("MDEXPLORE_MATHJAX_JS", "").strip()
candidates: list[Path] = []
if env_value:
candidates.append(Path(env_value).expanduser())
app_dir = Path(__file__).resolve().parent
candidates.extend(
[
app_dir / "mathjax" / "es5" / "tex-svg.js",
app_dir / "mathjax" / "tex-svg.js",
app_dir / "assets" / "mathjax" / "es5" / "tex-svg.js",
app_dir / "vendor" / "mathjax" / "es5" / "tex-svg.js",