Files
MDHelper/mdhelper/markdown_editor.py
T
2026-06-18 12:30:37 +08:00

849 lines
33 KiB
Python

from __future__ import annotations
import os
import json
import re
from pathlib import Path
from typing import Callable
from PySide6.QtCore import QObject, QRect, QSize, QTimer, QUrl, Qt, Signal, Slot
from PySide6.QtGui import (
QAction,
QColor,
QFont,
QKeySequence,
QPainter,
QSyntaxHighlighter,
QTextCharFormat,
QTextCursor,
QTextDocument,
QTextFormat,
)
from PySide6.QtWebChannel import QWebChannel
from PySide6.QtWebEngineCore import QWebEngineSettings
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtWidgets import (
QCheckBox,
QComboBox,
QDialog,
QFileDialog,
QHBoxLayout,
QLabel,
QLineEdit,
QMenu,
QMessageBox,
QPlainTextEdit,
QPushButton,
QSplitter,
QTextEdit,
QToolBar,
QVBoxLayout,
QWidget,
)
from shiboken6 import isValid
from .markdown_renderer import MarkdownRenderer
from .markdown_utils import slugify_heading
MAX_SYNTAX_HIGHLIGHT_CHARS = 1_000_000
class LineNumberArea(QWidget):
def __init__(self, editor: "MarkdownSourceEditor") -> None:
super().__init__(editor)
self.editor = editor
def sizeHint(self) -> QSize:
return QSize(self.editor.line_number_area_width(), 0)
def paintEvent(self, event: object) -> None:
self.editor.line_number_area_paint_event(event)
class MarkdownSourceEditor(QPlainTextEdit):
def __init__(self, parent: QWidget | None = None) -> None:
super().__init__(parent)
self.line_number_background = QColor("#f3f5f8")
self.line_number_foreground = QColor("#7a8494")
self.current_line_background = QColor("#edf4ff")
self.line_number_area = LineNumberArea(self)
self.blockCountChanged.connect(self.update_line_number_area_width)
self.updateRequest.connect(self.update_line_number_area)
self.cursorPositionChanged.connect(self.highlight_current_line)
self.update_line_number_area_width(0)
self.highlight_current_line()
def apply_theme(self, dark: bool) -> None:
if dark:
self.line_number_background = QColor("#22272e")
self.line_number_foreground = QColor("#8b949e")
self.current_line_background = QColor("#273447")
self.setStyleSheet(
"QPlainTextEdit { background: #1f242b; color: #dbe2ea; "
"selection-background-color: #2f6feb; selection-color: #ffffff; }"
)
else:
self.line_number_background = QColor("#f3f5f8")
self.line_number_foreground = QColor("#7a8494")
self.current_line_background = QColor("#edf4ff")
self.setStyleSheet("")
self.line_number_area.update()
self.highlight_current_line()
def line_number_area_width(self) -> int:
digits = max(2, len(str(max(1, self.blockCount()))))
return 12 + self.fontMetrics().horizontalAdvance("9") * digits
def update_line_number_area_width(self, new_block_count: int) -> None:
del new_block_count
self.setViewportMargins(self.line_number_area_width(), 0, 0, 0)
def update_line_number_area(self, rect: QRect, dy: int) -> None:
if dy:
self.line_number_area.scroll(0, dy)
else:
self.line_number_area.update(0, rect.y(), self.line_number_area.width(), rect.height())
if rect.contains(self.viewport().rect()):
self.update_line_number_area_width(0)
def resizeEvent(self, event: object) -> None:
super().resizeEvent(event)
content_rect = self.contentsRect()
self.line_number_area.setGeometry(
QRect(content_rect.left(), content_rect.top(), self.line_number_area_width(), content_rect.height())
)
def line_number_area_paint_event(self, event: object) -> None:
painter = QPainter(self.line_number_area)
painter.fillRect(event.rect(), self.line_number_background)
block = self.firstVisibleBlock()
block_number = block.blockNumber()
top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top())
bottom = top + int(self.blockBoundingRect(block).height())
while block.isValid() and top <= event.rect().bottom():
if block.isVisible() and bottom >= event.rect().top():
painter.setPen(self.line_number_foreground)
painter.drawText(
0,
top,
self.line_number_area.width() - 6,
self.fontMetrics().height(),
Qt.AlignmentFlag.AlignRight,
str(block_number + 1),
)
block = block.next()
top = bottom
bottom = top + int(self.blockBoundingRect(block).height())
block_number += 1
def highlight_current_line(self) -> None:
selection = QTextEdit.ExtraSelection()
selection.format.setBackground(self.current_line_background)
selection.format.setProperty(QTextFormat.Property.FullWidthSelection, True)
selection.cursor = self.textCursor()
selection.cursor.clearSelection()
self.setExtraSelections([selection])
class MarkdownSyntaxHighlighter(QSyntaxHighlighter):
def __init__(self, document: object, dark: bool = False) -> None:
super().__init__(document)
self.dark = dark
self._rebuild_rules()
def apply_theme(self, dark: bool) -> None:
self.dark = dark
self._rebuild_rules()
self.rehighlight()
def _rebuild_rules(self) -> None:
if self.dark:
heading = "#79c0ff"
link = "#58a6ff"
strong = "#f0f6fc"
accent = "#d2a8ff"
code = "#ffa657"
media = "#7ee787"
quote = "#8b949e"
fence = "#ffab70"
block_code = "#c9d1d9"
else:
heading = "#1f6feb"
link = "#0969da"
strong = "#24292f"
accent = "#8250df"
code = "#bf3989"
media = "#1a7f37"
quote = "#6e7781"
fence = "#953800"
block_code = "#57606a"
self.rules = [
(re.compile(r"^#{1,6}\s+.+$"), self._format(heading, bold=True)),
(re.compile(r"^\s*[-*+]\s+"), self._format(link)),
(re.compile(r"^\s*\d+\.\s+"), self._format(link)),
(re.compile(r"\*\*[^*]+\*\*"), self._format(strong, bold=True)),
(re.compile(r"(?<!\*)\*[^*\n]+\*(?!\*)"), self._format(accent, italic=True)),
(re.compile(r"`[^`\n]+`"), self._format(code)),
(re.compile(r"!\[[^\]]*]\([^)]+\)"), self._format(media)),
(re.compile(r"\[[^\]]+]\([^)]+\)"), self._format(link, underline=True)),
(re.compile(r"^\s{0,3}>\s?.*$"), self._format(quote, italic=True)),
(re.compile(r"^\s{0,3}---+\s*$"), self._format(quote)),
]
self.code_format = self._format(block_code)
self.fence_format = self._format(fence, bold=True)
def _format(self, color: str, bold: bool = False, italic: bool = False, underline: bool = False) -> QTextCharFormat:
text_format = QTextCharFormat()
text_format.setForeground(QColor(color))
if bold:
text_format.setFontWeight(QFont.Weight.Bold)
if italic:
text_format.setFontItalic(True)
if underline:
text_format.setFontUnderline(True)
return text_format
def highlightBlock(self, text: str) -> None:
in_fence = self.previousBlockState() == 1
if text.strip().startswith("```"):
self.setFormat(0, len(text), self.fence_format)
self.setCurrentBlockState(0 if in_fence else 1)
return
if in_fence:
self.setFormat(0, len(text), self.code_format)
self.setCurrentBlockState(1)
return
self.setCurrentBlockState(0)
for pattern, text_format in self.rules:
for match in pattern.finditer(text):
self.setFormat(match.start(), match.end() - match.start(), text_format)
class MarkdownPreviewBridge(QObject):
heading_requested = Signal(str)
@Slot(str)
def openHeading(self, slug: str) -> None:
self.heading_requested.emit(str(slug))
class MarkdownEditorDialog(QDialog):
save_requested = Signal(object, str, object)
close_requested = Signal()
title_changed = Signal(str)
def __init__(
self,
path: Path,
source: str,
renderer: MarkdownRenderer,
theme: str,
font_scale: float,
document_font_family: str,
document_font_size: int,
document_width_scale: float = 1.0,
document_style_css: str = "",
math_engine: str = "katex",
original_source: str | None = None,
file_signature: tuple[int, int] | None = None,
draft_callback: Callable[[str], None] | None = None,
embedded: bool = False,
parent: QWidget | None = None,
) -> None:
super().__init__(parent)
self.embedded = embedded
if embedded:
self.setWindowFlag(Qt.WindowType.Widget, True)
self.path = path
self.save_target_path = path
self.renderer = renderer
self.theme = theme
self.font_scale = font_scale
self.document_font_family = document_font_family
self.document_font_size = document_font_size
self.document_width_scale = document_width_scale
self.document_style_css = document_style_css
self.math_engine = math_engine
self.preview_embedded_toc = True
self.file_signature = file_signature
self.draft_callback = draft_callback
self._preview_dirty = True
self._preview_scroll_y = 0
self._preview_scroll_ratio = 0.0
self._syncing_scroll = False
self._match_positions: list[int] = []
self._current_match_index = -1
self.setWindowTitle(f"编辑 Markdown - {path.name}")
self.setMinimumSize(1120, 720)
self._original_source = source if original_source is None else original_source
layout = QVBoxLayout(self)
layout.setContentsMargins(12, 12, 12, 12)
layout.setSpacing(8)
self.path_label = QLabel(str(path))
self.path_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
if not embedded:
layout.addWidget(self.path_label)
self.insert_toolbar = QToolBar("插入")
self.insert_toolbar.setMovable(False)
self._build_insert_toolbar()
layout.addWidget(self.insert_toolbar)
control_layout = QHBoxLayout()
control_layout.setContentsMargins(0, 0, 0, 0)
control_layout.addWidget(QLabel("视图"))
self.view_mode_box = QComboBox()
self.view_mode_box.addItem("源码", "source")
self.view_mode_box.addItem("预览", "preview")
self.view_mode_box.addItem("分屏", "split")
self.view_mode_box.setCurrentIndex(2 if embedded else 0)
self.view_mode_box.currentIndexChanged.connect(self._apply_view_mode)
control_layout.addWidget(self.view_mode_box)
self.editor_find_box = QLineEdit()
self.editor_find_box.setPlaceholderText("查找源码")
self.editor_find_box.returnPressed.connect(self.find_next_in_editor)
self.editor_find_box.textChanged.connect(self._rebuild_find_matches)
self.editor_replace_box = QLineEdit()
self.editor_replace_box.setPlaceholderText("替换为")
self.match_case_checkbox = QCheckBox("区分大小写")
self.match_case_checkbox.toggled.connect(self._rebuild_find_matches)
self.whole_word_checkbox = QCheckBox("全词")
self.whole_word_checkbox.toggled.connect(self._rebuild_find_matches)
self.editor_find_previous_button = QPushButton("上一个")
self.editor_find_previous_button.clicked.connect(self.find_previous_in_editor)
self.editor_find_next_button = QPushButton("下一个")
self.editor_find_next_button.clicked.connect(self.find_next_in_editor)
self.editor_replace_button = QPushButton("替换")
self.editor_replace_button.clicked.connect(self.replace_current_in_editor)
self.editor_replace_all_button = QPushButton("全部替换")
self.editor_replace_all_button.clicked.connect(self.replace_all_in_editor)
self.find_status_label = QLabel("0/0")
control_layout.addWidget(self.editor_find_box, 2)
control_layout.addWidget(self.editor_replace_box, 2)
control_layout.addWidget(self.match_case_checkbox)
control_layout.addWidget(self.whole_word_checkbox)
control_layout.addWidget(self.editor_find_previous_button)
control_layout.addWidget(self.editor_find_next_button)
control_layout.addWidget(self.editor_replace_button)
control_layout.addWidget(self.editor_replace_all_button)
control_layout.addWidget(self.find_status_label)
layout.addLayout(control_layout)
self.preview_refresh_timer = QTimer(self)
self.preview_refresh_timer.setSingleShot(True)
self.preview_refresh_timer.setInterval(350)
self.preview_refresh_timer.timeout.connect(self._refresh_preview_with_scroll_capture)
self.draft_save_timer = QTimer(self)
self.draft_save_timer.setSingleShot(True)
self.draft_save_timer.setInterval(5000)
self.draft_save_timer.timeout.connect(self._auto_save_draft)
self.splitter = QSplitter(Qt.Orientation.Horizontal)
self.editor = MarkdownSourceEditor()
self.editor.setPlainText(source)
self.editor.setLineWrapMode(QPlainTextEdit.LineWrapMode.WidgetWidth)
editor_font = QFont("Consolas")
editor_font.setStyleHint(QFont.StyleHint.Monospace)
self.editor.setFont(editor_font)
self._apply_editor_font()
self.highlighter = (
MarkdownSyntaxHighlighter(self.editor.document())
if len(source) <= MAX_SYNTAX_HIGHLIGHT_CHARS
else None
)
self.editor.textChanged.connect(self._on_editor_text_changed)
self.editor.verticalScrollBar().valueChanged.connect(self._sync_preview_to_editor_scroll)
self.splitter.addWidget(self.editor)
self.preview = QWebEngineView()
self.preview_bridge = MarkdownPreviewBridge(self)
self.preview_bridge.heading_requested.connect(self._open_preview_heading_in_source)
self.preview_channel = QWebChannel(self.preview)
self.preview_channel.registerObject("mdhelperPreviewBridge", self.preview_bridge)
self.preview.page().setWebChannel(self.preview_channel)
self.preview.loadFinished.connect(self._restore_preview_scroll)
self._configure_preview_settings(self.preview.settings())
self.splitter.addWidget(self.preview)
self.splitter.setSizes([560, 560])
layout.addWidget(self.splitter, 1)
button_layout = QHBoxLayout()
button_layout.addStretch(1)
self.redo_button = QPushButton("前进")
self.redo_button.setShortcut(QKeySequence.StandardKey.Redo)
self.redo_button.clicked.connect(self._redo_editor)
button_layout.addWidget(self.redo_button)
self.undo_button = QPushButton("回退")
self.undo_button.setShortcut(QKeySequence.StandardKey.Undo)
self.undo_button.clicked.connect(self._undo_editor)
button_layout.addWidget(self.undo_button)
self.save_button = QPushButton("保存")
self.save_button.setShortcut("Ctrl+S")
if embedded:
self.save_button.clicked.connect(self._emit_save_requested)
else:
self.save_button.clicked.connect(self.accept)
button_layout.addWidget(self.save_button)
self.save_as_button = QPushButton("另存为")
self.save_as_button.clicked.connect(self._choose_save_as_path)
button_layout.addWidget(self.save_as_button)
self.cancel_button = QPushButton("取消")
if embedded:
self.cancel_button.clicked.connect(self.close_requested.emit)
else:
self.cancel_button.clicked.connect(self.reject)
button_layout.addWidget(self.cancel_button)
layout.addLayout(button_layout)
self._install_shortcuts()
self.apply_theme(theme == "dark")
self._update_undo_redo_actions()
self._update_dirty_title()
self._rebuild_find_matches()
self._apply_view_mode()
def source_text(self) -> str:
return self.editor.toPlainText()
def has_unsaved_changes(self) -> bool:
return self.source_text() != self._original_source
def apply_theme(self, dark: bool) -> None:
self.editor.apply_theme(dark)
if self.highlighter is not None:
self.highlighter.apply_theme(dark)
if dark:
self.setStyleSheet(
"QDialog { background: #1f242b; color: #dbe2ea; }"
"QLineEdit, QComboBox { background: #15191f; color: #dbe2ea; border: 1px solid #3a4553; padding: 4px; }"
"QToolBar { background: #22272e; border: 1px solid #3a4553; }"
"QPushButton { background: #2d333b; color: #dbe2ea; border: 1px solid #444c56; padding: 4px 8px; }"
)
else:
self.setStyleSheet("")
def _apply_editor_font(self) -> None:
font = self.editor.font()
font.setStyleHint(QFont.StyleHint.Monospace)
font.setPointSize(max(8, min(22, round(self.document_font_size * 0.75))))
self.editor.setFont(font)
self.editor.update_line_number_area_width(0)
def update_rendering_options(
self,
theme: str,
font_scale: float,
document_font_family: str,
document_font_size: int,
document_width_scale: float = 1.0,
document_style_css: str = "",
math_engine: str = "katex",
) -> None:
self.theme = theme
self.font_scale = font_scale
self.document_font_family = document_font_family
self.document_font_size = document_font_size
self.document_width_scale = document_width_scale
self.document_style_css = document_style_css
self.math_engine = math_engine
self.apply_theme(theme == "dark")
self._apply_editor_font()
self._preview_dirty = True
if self.preview.isVisible():
self._refresh_preview_with_scroll_capture()
def _install_shortcuts(self) -> None:
find_action = QAction(self)
find_action.setShortcut(QKeySequence.StandardKey.Find)
find_action.triggered.connect(self.editor_find_box.setFocus)
self.addAction(find_action)
replace_action = QAction(self)
replace_action.setShortcut(QKeySequence("Ctrl+H"))
replace_action.triggered.connect(self.editor_replace_box.setFocus)
self.addAction(replace_action)
self.editor.undoAvailable.connect(lambda available: self.undo_button.setEnabled(available))
self.editor.redoAvailable.connect(lambda available: self.redo_button.setEnabled(available))
def _build_insert_toolbar(self) -> None:
for label, template in (
("H1", "# {selection}"),
("H2", "## {selection}"),
("B", "**{selection}**"),
("I", "*{selection}*"),
("代码", "```\n{selection}\n```"),
("表格", "| 列1 | 列2 |\n| --- | --- |\n| 内容 | 内容 |"),
("链接", "[{selection}](target.md)"),
("图片", "![{selection}](media/screenshot.png)"),
("提示", "> [!NOTE]\n> {selection}"),
("Mermaid", "```mermaid\ngraph TD\n A --> B\n```"),
("公式", "$${selection}$$"),
):
action = QAction(label, self)
action.setToolTip(label)
action.triggered.connect(lambda checked=False, item=template: self.insert_template(item))
self.insert_toolbar.addAction(action)
def insert_template(self, template: str) -> None:
cursor = self.editor.textCursor()
selection = cursor.selectedText().replace("\u2029", "\n")
replacement = template.format(selection=selection or "内容")
cursor.insertText(replacement)
self.editor.setTextCursor(cursor)
self.editor.setFocus()
def scroll_to_heading(self, slug: str) -> bool:
target_line = self._heading_line_for_slug(slug)
if target_line is None:
return False
block = self.editor.document().findBlockByNumber(target_line)
if not block.isValid():
return False
cursor = QTextCursor(block)
self.editor.setTextCursor(cursor)
self.editor.centerCursor()
self.editor.setFocus()
if self.preview.isVisible():
self._scroll_preview_to_heading(slug)
return True
def _heading_line_for_slug(self, target_slug: str) -> int | None:
seen: dict[str, int] = {}
in_fenced_block = False
for line_number, line in enumerate(self.source_text().splitlines()):
stripped = line.strip()
if stripped.startswith("```") or stripped.startswith("~~~"):
in_fenced_block = not in_fenced_block
continue
if in_fenced_block:
continue
match = re.match(r"^(#{1,6})\s+(.+?)\s*#*\s*$", stripped)
if not match:
continue
slug = slugify_heading(match.group(2).strip())
if not slug:
continue
count = seen.get(slug, 0)
seen[slug] = count + 1
if count:
slug = f"{slug}-{count + 1}"
if slug == target_slug:
return line_number
return None
def _open_preview_heading_in_source(self, slug: str) -> None:
if self.scroll_to_heading(str(slug)) and hasattr(self, "find_status_label"):
self.find_status_label.setText(f"已定位标题:#{slug}")
def _scroll_preview_to_heading(self, slug: str) -> None:
if not isValid(self) or not isValid(self.preview):
return
script = (
"(() => {"
"const id = "
f"{json.dumps(slug)}"
";"
"const selector = window.CSS && CSS.escape ? `[id=\"${CSS.escape(id)}\"]` : '';"
"const target = document.getElementById(id) || (selector ? document.querySelector(selector) : null);"
"if (target) {"
" target.scrollIntoView({block: 'start', behavior: 'auto'});"
" const scroller = document.scrollingElement || document.documentElement || document.body;"
" scroller.scrollTop = Math.max(0, scroller.scrollTop - 12);"
"}"
"})();"
)
self.preview.page().runJavaScript(script)
def _on_editor_text_changed(self) -> None:
self._schedule_preview_refresh()
if self.has_unsaved_changes():
self.draft_save_timer.start()
self._update_dirty_title()
self._rebuild_find_matches()
self._update_undo_redo_actions()
def _update_undo_redo_actions(self) -> None:
self.undo_button.setEnabled(self.editor.document().isUndoAvailable())
self.redo_button.setEnabled(self.editor.document().isRedoAvailable())
def _undo_editor(self) -> None:
self.editor.undo()
self._update_undo_redo_actions()
def _redo_editor(self) -> None:
self.editor.redo()
self._update_undo_redo_actions()
def _update_dirty_title(self) -> None:
marker = "*" if self.has_unsaved_changes() else ""
title = f"{marker}编辑 Markdown - {self.save_target_path.name}"
self.setWindowTitle(title)
self.title_changed.emit(title)
self.path_label.setText(str(self.save_target_path))
def _auto_save_draft(self) -> None:
if self.has_unsaved_changes() and callable(self.draft_callback):
self.draft_callback(self.source_text())
def _find_flags(self) -> QTextDocument.FindFlag:
flags = QTextDocument.FindFlag(0)
if self.match_case_checkbox.isChecked():
flags |= QTextDocument.FindFlag.FindCaseSensitively
if self.whole_word_checkbox.isChecked():
flags |= QTextDocument.FindFlag.FindWholeWords
return flags
def _rebuild_find_matches(self) -> None:
query = self.editor_find_box.text()
self._match_positions = []
self._current_match_index = -1
if not query:
self.find_status_label.setText("0/0")
return
text = self.source_text()
flags = 0 if self.match_case_checkbox.isChecked() else re.IGNORECASE
pattern = re.escape(query)
if self.whole_word_checkbox.isChecked():
pattern = r"\b" + pattern + r"\b"
self._match_positions = [match.start() for match in re.finditer(pattern, text, flags)]
cursor_pos = self.editor.textCursor().selectionStart()
for index, position in enumerate(self._match_positions):
if position >= cursor_pos:
self._current_match_index = index - 1
break
else:
self._current_match_index = len(self._match_positions) - 1
self._update_find_status()
def _select_match(self, index: int) -> None:
if not self._match_positions:
self._update_find_status()
return
self._current_match_index = index % len(self._match_positions)
query = self.editor_find_box.text()
cursor = self.editor.textCursor()
cursor.setPosition(self._match_positions[self._current_match_index])
cursor.setPosition(cursor.position() + len(query), QTextCursor.MoveMode.KeepAnchor)
self.editor.setTextCursor(cursor)
self.editor.ensureCursorVisible()
self._update_find_status()
def _update_find_status(self) -> None:
total = len(self._match_positions)
current = self._current_match_index + 1 if total and self._current_match_index >= 0 else 0
self.find_status_label.setText(f"{current}/{total}")
def find_next_in_editor(self) -> None:
if not self.editor_find_box.text():
return
if not self._match_positions:
self._rebuild_find_matches()
if self._match_positions:
self._select_match(self._current_match_index + 1)
def find_previous_in_editor(self) -> None:
if not self.editor_find_box.text():
return
if not self._match_positions:
self._rebuild_find_matches()
if self._match_positions:
self._select_match(self._current_match_index - 1)
def replace_current_in_editor(self) -> None:
query = self.editor_find_box.text()
if not query:
return
cursor = self.editor.textCursor()
selected = cursor.selectedText().replace("\u2029", "\n")
matches = selected == query if self.match_case_checkbox.isChecked() else selected.lower() == query.lower()
if cursor.hasSelection() and matches:
cursor.insertText(self.editor_replace_box.text())
self._rebuild_find_matches()
return
self.find_next_in_editor()
def replace_all_in_editor(self) -> None:
query = self.editor_find_box.text()
if not query:
return
replacement = self.editor_replace_box.text()
flags = 0 if self.match_case_checkbox.isChecked() else re.IGNORECASE
pattern = re.escape(query)
if self.whole_word_checkbox.isChecked():
pattern = r"\b" + pattern + r"\b"
self.editor.setPlainText(re.sub(pattern, replacement, self.source_text(), flags=flags))
self._rebuild_find_matches()
def _configure_preview_settings(self, settings: QWebEngineSettings) -> None:
attributes = QWebEngineSettings.WebAttribute
settings.setAttribute(attributes.LocalContentCanAccessFileUrls, True)
settings.setAttribute(attributes.LocalContentCanAccessRemoteUrls, True)
settings.setAttribute(attributes.PlaybackRequiresUserGesture, False)
settings.setAttribute(attributes.FullScreenSupportEnabled, True)
settings.setAttribute(attributes.JavascriptEnabled, True)
def _apply_view_mode(self) -> None:
mode = str(self.view_mode_box.currentData() or "source")
self.editor.setVisible(mode in {"source", "split"})
self.preview.setVisible(mode in {"preview", "split"})
if mode in {"preview", "split"} and self._preview_dirty:
self._refresh_preview_now()
if mode == "split":
QTimer.singleShot(0, lambda: self._sync_preview_to_editor_scroll(self.editor.verticalScrollBar().value()))
def _schedule_preview_refresh(self) -> None:
self._preview_dirty = True
mode = str(self.view_mode_box.currentData() or "source")
if mode in {"preview", "split"}:
self.preview_refresh_timer.start()
def _refresh_preview_with_scroll_capture(self) -> None:
mode = str(self.view_mode_box.currentData() or "source")
if mode == "split":
self._preview_scroll_ratio = self._editor_scroll_ratio()
self._refresh_preview_now()
return
self.preview.page().runJavaScript("Math.max(0, window.scrollY || 0)", self._store_scroll_and_refresh_preview)
def _store_scroll_and_refresh_preview(self, scroll_y: object) -> None:
if not isValid(self) or not isValid(self.preview):
return
try:
self._preview_scroll_y = max(0, int(float(scroll_y or 0)))
except (TypeError, ValueError):
self._preview_scroll_y = 0
self._refresh_preview_now()
def _refresh_preview_now(self) -> None:
if not isValid(self) or not isValid(self.preview):
return
html_content = self.renderer.render_source(
self.source_text(),
self.save_target_path,
theme=self.theme,
font_scale=self.font_scale,
document_font_family=self.document_font_family,
document_font_size=self.document_font_size,
document_width_scale=self.document_width_scale,
document_style_css=self.document_style_css,
math_engine=self.math_engine,
include_reader_toc=self.preview_embedded_toc,
include_reader_progress=False,
)
base_path = str(self.save_target_path.parent.resolve()) + os.sep
self.preview.setHtml(html_content, QUrl.fromLocalFile(base_path))
self._preview_dirty = False
def _restore_preview_scroll(self, ok: bool) -> None:
if not ok:
return
if str(self.view_mode_box.currentData() or "source") == "split":
self._scroll_preview_to_ratio(self._preview_scroll_ratio)
return
if self._preview_scroll_y > 0:
script = f"(() => {{ window.scrollTo({{top: {self._preview_scroll_y}, behavior: 'instant'}}); }})();"
self.preview.page().runJavaScript(script)
def _editor_scroll_ratio(self) -> float:
maximum = max(1, self.editor.verticalScrollBar().maximum())
return max(0.0, min(1.0, self.editor.verticalScrollBar().value() / maximum))
def _sync_preview_to_editor_scroll(self, value: int) -> None:
del value
if self._syncing_scroll or str(self.view_mode_box.currentData() or "source") != "split":
return
self._preview_scroll_ratio = self._editor_scroll_ratio()
self._scroll_preview_to_ratio(self._preview_scroll_ratio)
def _scroll_preview_to_ratio(self, ratio: float) -> None:
if not isValid(self) or not isValid(self.preview):
return
script = (
"(() => {"
"const ratio = %0.6f;"
"const maxY = Math.max(0, document.documentElement.scrollHeight - window.innerHeight);"
"window.scrollTo({top: Math.round(maxY * ratio), behavior: 'instant'});"
"})();"
% ratio
)
self._syncing_scroll = True
self.preview.page().runJavaScript(script, lambda result=None: self._clear_scroll_sync())
def _clear_scroll_sync(self) -> None:
self._syncing_scroll = False
def _choose_save_as_path(self) -> None:
file_name, _ = QFileDialog.getSaveFileName(
self,
"另存为 Markdown",
str(self.save_target_path),
"Markdown Files (*.md *.markdown);;All Files (*)",
)
if not file_name:
return
target = Path(file_name)
if target.suffix.lower() not in {".md", ".markdown"}:
target = target.with_suffix(".md")
self.save_target_path = target.resolve()
self._update_dirty_title()
if self.embedded:
self._emit_save_requested()
else:
self.accept()
def accept(self) -> None:
super().accept()
def _emit_save_requested(self) -> None:
self.save_requested.emit(self.save_target_path, self.source_text(), self.file_signature)
def mark_saved(self, path: Path, source: str, file_signature: tuple[int, int] | None) -> None:
self.path = path
self.save_target_path = path
self.file_signature = file_signature
self._original_source = source
self._update_dirty_title()
def confirm_close(self) -> bool:
if not self.has_unsaved_changes():
return True
choice = QMessageBox.question(
self,
"关闭编辑标签?",
"当前编辑内容尚未保存,确定要关闭此编辑标签吗?",
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.No,
)
return choice == QMessageBox.StandardButton.Yes
def reject(self) -> None:
if not self.confirm_close():
return
super().reject()