Files
MDHelper/mdhelper/style_panel.py
T

79 lines
5.3 KiB
Python

"""Lazy style inspector. Parsing is cached; hidden panels have no timer or browser."""
from __future__ import annotations
from PySide6.QtCore import Qt, QTimer
from PySide6.QtGui import QFont, QColor
from PySide6.QtWidgets import QDockWidget, QWidget, QVBoxLayout, QLabel, QComboBox, QListWidget, QListWidgetItem, QPushButton
from .style_catalog import CATALOG, KINDS, document_styles, style_name
from .document_style import resolved_rules, font_points
from .markdown_editor import MarkdownEditorDialog
class StylePanel(QDockWidget):
def __init__(self, window):
super().__init__('样式', window)
self.window = window
self.setObjectName('semanticStylePanel')
self.setAllowedAreas(Qt.DockWidgetArea.LeftDockWidgetArea | Qt.DockWidgetArea.RightDockWidgetArea)
content = QWidget(); layout = QVBoxLayout(content)
self.scope = QLabel(); self.scope.setWordWrap(True); layout.addWidget(self.scope)
self.current = QLabel(); self.current.setWordWrap(True); layout.addWidget(self.current)
self.filter = QComboBox(); self.filter.addItems(['全部样式', '当前文档使用的样式']); layout.addWidget(self.filter)
self.listing = QListWidget(); self.listing.itemDoubleClicked.connect(self.edit_selected); layout.addWidget(self.listing)
button = QPushButton('修改选中样式…'); button.clicked.connect(self.edit_selected); layout.addWidget(button)
scope_button = QPushButton('项目范围与预设…'); scope_button.clicked.connect(window.show_project_presets); layout.addWidget(scope_button)
self.setWidget(content); self.setMinimumWidth(260)
self.timer = QTimer(self); self.timer.setInterval(300); self.timer.timeout.connect(self.refresh)
self.visibilityChanged.connect(self.visibility_changed)
self.filter.currentIndexChanged.connect(lambda: self.refresh(force=True))
self.cache_key = self.list_key = None
self.regions, self.used = [], set()
def visibility_changed(self, visible):
if visible: self.refresh(force=True); self.timer.start()
else: self.timer.stop()
def refresh(self, force=False):
window = self.window; widget = window.tabs.currentWidget(); path = window.current_file
editor = widget if isinstance(widget, MarkdownEditorDialog) else None
key = (path, editor.editor.document().revision() if editor else window._file_signature(path) if path else None, bool(editor))
if key != self.cache_key:
try:
source = editor.source_text() if editor else path.read_text(encoding='utf-8-sig') if path and path.suffix.lower() in ('.md', '.markdown') else ''
self.regions, self.used = document_styles(source)
except (OSError, UnicodeError): self.regions, self.used = [], set()
self.cache_key = key
rules = window.custom_document_styles.get(window.document_style_id, {}).get('rules', {})
self.scope.setText(f'样式集:{window._document_style_label()}\n范围:' +
(f'当前项目 {window.project_root.name}' if window.project_styles.active else '全局默认'))
active = None
if editor:
line = editor.editor.textCursor().blockNumber()
active = next((region for region in reversed(self.regions) if region.start <= line < region.end), None)
self.current.setText(('当前段落:' + style_name(active.style, rules) +
('\n包含:' + '、'.join(style_name(k, rules) for k in active.characters) if active.characters else '')) if active else '阅读模式:双击条目修改统一外观。')
listing_key = (key, repr(rules), window.document_font_size, window.document_font_family, self.filter.currentIndex())
if force or listing_key != self.list_key:
selected = self.listing.currentItem().data(Qt.ItemDataRole.UserRole) if self.listing.currentItem() else None
self.listing.clear()
effective = resolved_rules(rules, window.document_font_family, window.document_font_size, window.document_style_id)
for target, definition in CATALOG.items():
if self.filter.currentIndex() and target not in self.used: continue
item = QListWidgetItem(f'{style_name(target, rules)} · {KINDS[definition.kind]}')
item.setData(Qt.ItemDataRole.UserRole, target); item.setToolTip(definition.syntax)
rule = effective[target]; font = QFont(rule['chinese_font_family']); font.setPointSizeF(min(18, max(9, font_points(rule))))
font.setBold(rule['bold']); font.setItalic(rule['italic']); item.setFont(font)
if str(rule['font_color']).startswith('#'): item.setForeground(QColor(rule['font_color']))
self.listing.addItem(item)
if target == selected: self.listing.setCurrentItem(item)
self.list_key = listing_key
if active:
for index in range(self.listing.count()):
item = self.listing.item(index)
item.setBackground(QColor('#dceaf8') if item.data(Qt.ItemDataRole.UserRole) in (active.style, *active.characters) else QColor('transparent'))
def edit_selected(self, *_):
item = self.listing.currentItem()
if item:
self.window.edit_semantic_style(item.data(Qt.ItemDataRole.UserRole))
self.refresh(force=True)