From 117e6b65f196508a82eab13d4828fc7d166b1ef0 Mon Sep 17 00:00:00 2001 From: shen Date: Fri, 30 Oct 2026 10:32:56 +0800 Subject: [PATCH] feat: add on-demand semantic styles panel and reader preview --- mdhelper/main_window.py | 34 +++++++++++++++- mdhelper/style_catalog.py | 2 + mdhelper/style_dialog.py | 83 +++++++++++++++++++++++++++++++++++++-- mdhelper/style_panel.py | 78 ++++++++++++++++++++++++++++++++++++ tests/test_style_panel.py | 51 ++++++++++++++++++++++++ 5 files changed, 242 insertions(+), 6 deletions(-) create mode 100644 mdhelper/style_panel.py create mode 100644 tests/test_style_panel.py diff --git a/mdhelper/main_window.py b/mdhelper/main_window.py index 217b454..838e94e 100644 --- a/mdhelper/main_window.py +++ b/mdhelper/main_window.py @@ -692,10 +692,16 @@ class MainWindow(QMainWindow): def _build_style_menu(self) -> None: self.style_menu.clear() + if not hasattr(self, 'style_panel_action'): + self.style_panel_action = QAction('样式面板', self) + self.style_panel_action.setCheckable(True) + self.style_panel_action.triggered.connect(self.show_style_panel) + self.style_menu.addAction(self.style_panel_action) + self.style_menu.addSeparator() self.document_style_group = QActionGroup(self) self.document_style_group.setExclusive(True) - built_in_label = QAction("内置样式", self) + built_in_label = QAction("内置样式集", self) built_in_label.setEnabled(False) self.style_menu.addAction(built_in_label) for style_id, style in DOCUMENT_STYLE_PRESETS.items(): @@ -706,7 +712,7 @@ class MainWindow(QMainWindow): self.style_menu.addAction(action) self.style_menu.addSeparator() - custom_label = QAction("自定义样式", self) + custom_label = QAction("自定义样式集", self) custom_label.setEnabled(False) self.style_menu.addAction(custom_label) if self.custom_document_styles: @@ -3133,6 +3139,30 @@ class MainWindow(QMainWindow): self.refresh_all_tab_appearances() self.status_label.setText(f"自定义样式已创建:{name}") + def show_style_panel(self, checked=True): + if not hasattr(self, 'style_panel'): + if not checked: return + from .style_panel import StylePanel + self.style_panel = StylePanel(self) + self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.style_panel) + self.style_panel.visibilityChanged.connect(self.style_panel_action.setChecked) + self.style_panel.setVisible(checked) + self.style_panel_action.setChecked(checked) + + def edit_semantic_style(self, target): + style = self._style_payload_for_id(self.document_style_id) + dialog = DocumentStyleEditorDialog(style, parent=self) + dialog.select_target(target) + dialog.apply_theme(self.theme_color) + scope = '当前项目' if self.project_styles.active else '全局默认' + dialog.setWindowTitle(f'修改样式 — {scope}') + if dialog.exec() != QDialog.DialogCode.Accepted: return + payload = self._normalize_document_style_payload(dialog.style_payload()) + style_id = self.document_style_id if self.document_style_id in self.custom_document_styles else self._unique_custom_style_id(payload['name'] + '(自定义)') + self.custom_document_styles[style_id] = payload + self.document_style_id = style_id + self._build_style_menu(); self._save_preferences(); self.refresh_all_tab_appearances() + def edit_current_custom_document_style(self) -> None: style = self.custom_document_styles.get(self.document_style_id) if not style: diff --git a/mdhelper/style_catalog.py b/mdhelper/style_catalog.py index 40f3916..39f6b4e 100644 --- a/mdhelper/style_catalog.py +++ b/mdhelper/style_catalog.py @@ -83,6 +83,8 @@ def explicit_rules(rules): own = rules.get(key, {}) own = own if isinstance(own, dict) else {} inherited = dict(resolve(base)) if base else {} + if base and CATALOG[key].kind == 'character': + inherited = {**CHARACTER_DEFAULTS.get(base, {}), **inherited} if key in ('table_head', 'table_cell') and not base: inherited.update({k: v for k, v in rules.get('table', {}).items() if k not in {'border_color', 'border_width', 'cell_padding'}}) if key == 'inline_code' and not base: diff --git a/mdhelper/style_dialog.py b/mdhelper/style_dialog.py index 90168cd..98f9b5a 100644 --- a/mdhelper/style_dialog.py +++ b/mdhelper/style_dialog.py @@ -19,6 +19,7 @@ from PySide6.QtWidgets import ( QHBoxLayout, QLabel, QLineEdit, + QMessageBox, QListWidget, QListWidgetItem, QPushButton, @@ -35,7 +36,7 @@ from .document_style import (STYLE_TARGETS, normalize_rule, resolved_rules, from .document_style import build_document_style_css from .style_sync import analyze_css, source_from_payload, patch_core -from .style_catalog import CATALOG, CHARACTER_FIELDS +from .style_catalog import CATALOG, CHARACTER_FIELDS, KINDS, normalize_metadata, parent_style, style_name class DocumentStyleEditorDialog(QDialog): @@ -53,6 +54,11 @@ class DocumentStyleEditorDialog(QDialog): self.rules: dict[str, dict[str, Any]] = deepcopy(source.get("rules", {})) if isinstance(source.get("rules"), dict) else {} self._current_target = STYLE_TARGETS[0][0] self._loading = False + self.actual_preview = None + self.actual_preview_timer = QTimer(self) + self.actual_preview_timer.setSingleShot(True) + self.actual_preview_timer.setInterval(250) + self.actual_preview_timer.timeout.connect(self._render_actual_preview) self._css_dirty = False self._syncing_css = False @@ -69,7 +75,7 @@ class DocumentStyleEditorDialog(QDialog): name_row = QHBoxLayout() name_row.setContentsMargins(0, 0, 0, 0) name_row.setSpacing(8) - name_row.addWidget(QLabel("样式名称")) + name_row.addWidget(QLabel("样式集名称")) name_row.addWidget(self.name_edit) name_row.addStretch(1) @@ -77,6 +83,9 @@ class DocumentStyleEditorDialog(QDialog): self.tabs.setMinimumWidth(750) self.tabs.addTab(self._build_visual_tab(), "图形设置") self.tabs.addTab(self._build_advanced_tab(source_from_payload(source)), "高级 CSS") + self.actual_preview_container = QWidget() + self.actual_preview_layout = QVBoxLayout(self.actual_preview_container) + self.tabs.addTab(self.actual_preview_container, '实际阅读效果') self.tabs.currentChanged.connect(self._tab_changed) buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) @@ -154,7 +163,7 @@ class DocumentStyleEditorDialog(QDialog): self.target_list = QListWidget() self.target_list.setFixedWidth(115) for key, label, _ in STYLE_TARGETS: - item = QListWidgetItem(label) + item = QListWidgetItem(style_name(key, self.rules)) item.setData(Qt.ItemDataRole.UserRole, key) self.target_list.addItem(item) self.target_list.setCurrentRow(0) @@ -163,6 +172,14 @@ class DocumentStyleEditorDialog(QDialog): form = QFormLayout(panel) self.form = form form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow) + self.style_name_edit = QLineEdit() + self.style_kind_label = QLabel() + self.based_on_box = QComboBox() + form.addRow('具体样式名称', self.style_name_edit) + form.addRow('类型 / 语法', self.style_kind_label) + form.addRow('样式基准', self.based_on_box) + self.style_name_edit.editingFinished.connect(self._store_metadata) + self.based_on_box.currentIndexChanged.connect(self._store_metadata) self.font_combo = QFontComboBox() self.chinese_font_combo = self.font_combo self.english_font_combo = QFontComboBox() @@ -270,7 +287,7 @@ class DocumentStyleEditorDialog(QDialog): right.addWidget(self.preview) layout.addLayout(right, 1) for widget in panel.findChildren(QComboBox): - if widget is not self.font_size_preset_combo: + if widget not in (self.font_size_preset_combo, self.based_on_box): widget.currentIndexChanged.connect(self._store_and_refresh) if widget.isEditable(): widget.editTextChanged.connect(self._store_and_refresh) @@ -335,6 +352,54 @@ class DocumentStyleEditorDialog(QDialog): def _tab_changed(self, *_: object) -> None: if self._css_dirty: self._sync_from_css() + if self.tabs.currentIndex() == 2: + self._render_actual_preview() + + def select_target(self, key): + for index in range(self.target_list.count()): + if self.target_list.item(index).data(Qt.ItemDataRole.UserRole) == key: + self.target_list.setCurrentRow(index) + break + + def _store_metadata(self, *_): + if self._loading: return + key, base = self._current_target, self.based_on_box.currentData() or '' + ancestor, seen = base, set() + while ancestor and ancestor not in seen: + if ancestor == key: + QMessageBox.warning(self, '无法继承', '样式基准不能形成循环。') + self._load_rule_to_widgets(self.rules.get(key, {})); return + seen.add(ancestor); ancestor = parent_style(ancestor, self.rules) + metadata = deepcopy(self.rules.get('_metadata', {})) + metadata[key] = {'name': self.style_name_edit.text().strip() or CATALOG[key].name, 'based_on': base} + self.rules['_metadata'] = normalize_metadata(metadata) + self.target_list.currentItem().setText(style_name(key, self.rules)) + self._refresh_preview() + + def _render_actual_preview(self): + if self.tabs.currentIndex() != 2: return + from pathlib import Path + from PySide6.QtWebEngineWidgets import QWebEngineView + from .markdown_renderer import MarkdownRenderer + from .style_sync import render_css + if self.actual_preview is None: + self.actual_preview = QWebEngineView(self.actual_preview_container) + self.actual_preview_layout.addWidget(self.actual_preview) + if hasattr(self.parent(), '_configure_web_settings'): + self.parent()._configure_web_settings(self.actual_preview.settings()) + sample = '# 标题 1 中的 **加粗** 与 [链接](#预览)\n\n## 标题 2\n\n### 标题 3\n\n#### 标题 4\n\n##### 标题 5\n\n###### 标题 6\n\n正文段落:中文与 English,**加粗**、*强调*、~~删除线~~、`inline code`。\n\n第二段文字,用于观察段间距。\n\n> 引用段落中的 **重点**。\n\n- 无序列表\n - 第二级列表\n\n1. 有序列表\n2. 第二项\n\n- [ ] 任务列表\n\n```text\n代码块 code block\n第二行\n```\n\n| 表头 | Heading |\n|---|---|\n| 单元格 | Cell |' + parent = self.parent() + root = getattr(parent, 'project_root', Path.cwd()) + content = MarkdownRenderer(root).render_source(sample, root / '__style_preview__.md', + theme=getattr(parent, 'theme', 'light'), document_font_family=getattr(parent, 'document_font_family', ''), + document_font_size=getattr(parent, 'document_font_size', 16), + document_style_css=render_css(self.extra_css_edit.toPlainText(), self.rules)) + self.actual_preview.setHtml(content) + + def closeEvent(self, event): + self.actual_preview_timer.stop() + if self.actual_preview is not None: self.actual_preview.stop() + super().closeEvent(event) def _write_css(self, source: str) -> None: if source == self.extra_css_edit.toPlainText(): @@ -376,6 +441,14 @@ class DocumentStyleEditorDialog(QDialog): def _load_rule_to_widgets(self, rule: dict[str, Any]) -> None: self._loading = True + key = self._current_target + self.style_name_edit.setText(style_name(key, self.rules)) + self.style_kind_label.setText(f'{KINDS[CATALOG[key].kind]} · {CATALOG[key].syntax}') + self.based_on_box.clear(); self.based_on_box.addItem('文档默认 / 所在段落', '') + for candidate, definition in CATALOG.items(): + if candidate != key and definition.kind == CATALOG[key].kind: + self.based_on_box.addItem(style_name(candidate, self.rules), candidate) + self._select(self.based_on_box, parent_style(key, self.rules)) character = CATALOG[self._current_target].kind == 'character' for row in range(self.paragraph_row_start, self.paragraph_row_end): self.form.setRowVisible(row, not character) self.form.setRowVisible(self.border_row, not character) @@ -488,6 +561,8 @@ class DocumentStyleEditorDialog(QDialog): self._sync_from_css(update_widgets=False) def _refresh_preview(self) -> None: + if hasattr(self, 'tabs') and self.tabs.currentIndex() == 2: + self.actual_preview_timer.start() self.indent_spin.setEnabled(self.indent_mode_combo.currentData() in ("first", "hanging")) self.line_height_spin.setEnabled(self.line_height_mode_combo.currentData() in ("multiple", "exact", "at_least")) self.character_spacing_spin.setEnabled(self.character_spacing_combo.currentData() in (-1, 1)) diff --git a/mdhelper/style_panel.py b/mdhelper/style_panel.py new file mode 100644 index 0000000..4e3dcc8 --- /dev/null +++ b/mdhelper/style_panel.py @@ -0,0 +1,78 @@ +"""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) diff --git a/tests/test_style_panel.py b/tests/test_style_panel.py new file mode 100644 index 0000000..c36bd4e --- /dev/null +++ b/tests/test_style_panel.py @@ -0,0 +1,51 @@ +import time +from PySide6.QtCore import QSettings, Qt +from mdhelper import main_window +from mdhelper.style_dialog import DocumentStyleEditorDialog +from mdhelper.style_sync import normalize_payload + + +def test_panel_is_lazy_and_tracks_unsaved_document_and_cursor(qt_application, tmp_path, monkeypatch): + settings = QSettings(str(tmp_path / 'settings.ini'), QSettings.Format.IniFormat) + monkeypatch.setattr(main_window, 'QSettings', lambda *_: settings) + path = tmp_path / 'note.md'; path.write_text('# Heading **strong**\n\nBody [link](#heading-strong)', encoding='utf-8') + window = main_window.MainWindow(tmp_path) + try: + assert not hasattr(window, 'style_panel') + window.open_document(path); window.edit_current_markdown() + editor = window.tabs.currentWidget() + window.show_style_panel(); panel = window.style_panel + panel.filter.setCurrentIndex(1); panel.refresh(force=True) + keys = {panel.listing.item(i).data(Qt.ItemDataRole.UserRole) for i in range(panel.listing.count())} + assert keys == {'h1', 'strong', 'paragraph', 'link'} + assert '标题 1' in panel.current.text() and '加粗' in panel.current.text() + cursor = editor.editor.textCursor(); cursor.setPosition(editor.source_text().index('Body')); editor.editor.setTextCursor(cursor) + panel.refresh(); assert '正文' in panel.current.text() and '超链接' in panel.current.text() + editor.replace_source_undoable('`inline`'); panel.refresh(force=True) + assert 'inline_code' in panel.used and 'h1' not in panel.used + editor.mark_saved(path, editor.source_text(), window._file_signature(path)) + panel.hide(); assert not panel.timer.isActive() + assert path.read_text(encoding='utf-8').startswith('# Heading') + finally: window.close() + + +def test_modify_style_metadata_and_real_preview(qt_application): + dialog = DocumentStyleEditorDialog({'name': 'Test', 'rules': {'h1': {'font_size': 28, 'font_size_unit': 'pt'}}}) + try: + assert dialog.actual_preview is None + dialog.select_target('h2') + dialog.style_name_edit.setText('自定义章节'); dialog.style_name_edit.editingFinished.emit() + dialog.based_on_box.setCurrentIndex(dialog.based_on_box.findData('h1')) + payload = dialog.style_payload() + assert normalize_payload(payload)['rules']['_metadata']['h2'] == {'name': '自定义章节', 'based_on': 'h1'} + dialog.tabs.setCurrentIndex(2) + assert dialog.actual_preview is not None + values = []; deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + qt_application.processEvents() + if not dialog.actual_preview.page().isLoading(): break + time.sleep(.01) + dialog.actual_preview.page().runJavaScript("getComputedStyle(document.querySelector('h2')).fontSize", values.append) + while not values and time.monotonic() < deadline: qt_application.processEvents(); time.sleep(.01) + assert values and abs(float(values[0].removesuffix('px')) - 28*96/72) < .1 + finally: dialog.close()