Files

196 lines
7.8 KiB
Python

"""Reusable Markdown source widgets; no document or browser lifecycle."""
from __future__ import annotations
import re
from PySide6.QtCore import QRect, QSize, Qt
from PySide6.QtGui import QColor, QFont, QPainter, QSyntaxHighlighter, QTextCharFormat, QTextFormat
from PySide6.QtWidgets import QPlainTextEdit, QTextEdit, QWidget
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.image_handler = None
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 canInsertFromMimeData(self, source: object) -> bool:
from .editor_assets import image_files
return bool(source.hasImage() or image_files(source)) or super().canInsertFromMimeData(source)
def insertFromMimeData(self, source: object) -> None:
if callable(self.image_handler) and self.image_handler(source):
return
super().insertFromMimeData(source)
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)