Files
MDHelper/mdhelper/style_dialog.py
T

638 lines
35 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
from .ui_theme import style_dialog_theme, apply_title_bar_style
import re
from copy import deepcopy
from typing import Any
from PySide6.QtCore import Qt, QTimer, QSignalBlocker
from PySide6.QtGui import QFont, QColor, QTextBlockFormat, QTextCharFormat, QTextCursor
from PySide6.QtWidgets import (
QCheckBox,
QComboBox,
QColorDialog,
QDialog,
QDialogButtonBox,
QDoubleSpinBox,
QFontComboBox,
QFormLayout,
QHBoxLayout,
QLabel,
QLineEdit,
QMessageBox,
QListWidget,
QListWidgetItem,
QPushButton,
QScrollArea,
QTabWidget,
QTextEdit,
QVBoxLayout,
QWidget,
)
from .document_style import (STYLE_TARGETS, normalize_rule, resolved_rules,
font_points, length_points, line_points, number)
from .document_style import build_document_style_css
from .style_sync import analyze_css, source_from_payload, patch_core, GROUPS
from .style_catalog import CATALOG, CHARACTER_FIELDS, KINDS, normalize_metadata, parent_style, style_name, legacy_base
class DocumentStyleEditorDialog(QDialog):
def __init__(
self,
style: dict[str, Any] | None = None,
default_name: str = "自定义样式",
parent: QWidget | None = None,
) -> None:
super().__init__(parent)
self.setWindowTitle("文档样式")
self.setMinimumSize(800, 640)
self.resize(960, 780)
source = style or {}
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
self._css_timer = QTimer(self)
self._css_timer.setSingleShot(True)
self._css_timer.setInterval(350)
self._css_timer.timeout.connect(self._sync_from_css)
self.name_edit = QLineEdit(str(source.get("name") or default_name))
self.name_edit.setObjectName("styleNameEdit")
self.name_edit.setPlaceholderText("样式名称")
self.name_edit.setMaximumWidth(420)
name_row = QHBoxLayout()
name_row.setContentsMargins(0, 0, 0, 0)
name_row.setSpacing(8)
name_row.addWidget(QLabel("样式集名称"))
name_row.addWidget(self.name_edit)
name_row.addStretch(1)
self.tabs = QTabWidget()
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)
self.button_box = buttons
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
button_row = QWidget()
button_row.setMinimumWidth(750)
button_layout = QHBoxLayout(button_row)
button_layout.setContentsMargins(0, 0, 0, 0)
button_layout.addStretch(1)
button_layout.addWidget(buttons)
layout = QVBoxLayout(self)
layout.setContentsMargins(16, 14, 16, 16)
layout.setSpacing(12)
layout.addLayout(name_row)
layout.addWidget(self.tabs)
layout.addWidget(button_row)
self._load_rule_to_widgets(self.rules.get(self._current_target, {}))
self._sync_from_css()
def apply_theme(self, theme_color: str) -> None:
stylesheet, chrome, text = style_dialog_theme(theme_color)
self.setStyleSheet(stylesheet)
self._apply_window_title_bar_style(chrome, text, theme_color in {"black", "dark_gray"})
def _apply_window_title_bar_style(self, background: str, foreground: str, dark: bool) -> None:
apply_title_bar_style(self, background, foreground, dark)
def style_payload(self) -> dict[str, object]:
if not self._sync_from_css():
raise ValueError("CSS 尚未完成,请先修正提示的错误。")
return {
"name": self.name_edit.text().strip() or "自定义样式",
"rules": deepcopy(self.rules),
"css_sync_version": 1,
"css": self.extra_css_edit.toPlainText(),
}
def accept(self) -> None:
if self._sync_from_css():
super().accept()
@staticmethod
def _combo(items: list[tuple[str, object]]) -> QComboBox:
box = QComboBox()
for label, value in items:
box.addItem(label, value)
return box
@staticmethod
def _spin(maximum: float = 200, inherit: bool = True) -> QDoubleSpinBox:
box = QDoubleSpinBox()
box.setDecimals(2)
box.setRange(-1 if inherit else 0, maximum)
box.setSingleStep(0.5)
if inherit:
box.setSpecialValueText("继承")
box.setValue(-1)
return box
@staticmethod
def _row(*widgets: QWidget) -> QWidget:
row = QWidget()
layout = QHBoxLayout(row)
layout.setContentsMargins(0, 0, 0, 0)
for widget in widgets:
layout.addWidget(widget)
return row
def _build_visual_tab(self) -> QWidget:
page = QWidget()
layout = QHBoxLayout(page)
self.target_list = QListWidget()
self.target_list.setFixedWidth(115)
for key, label, _ in STYLE_TARGETS:
item = QListWidgetItem(style_name(key, self.rules))
item.setData(Qt.ItemDataRole.UserRole, key)
self.target_list.addItem(item)
self.target_list.setCurrentRow(0)
layout.addWidget(self.target_list)
panel = QWidget()
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()
for box in (self.font_combo, self.english_font_combo):
box.insertItem(0, "继承")
box.setMaximumWidth(315)
form.addRow("中文字体", self.font_combo)
form.addRow("西文字体", self.english_font_combo)
self.font_size_spin = self._spin(200)
self.font_size_unit_combo = self._combo([("磅(pt)", "pt"), ("像素(px)", "px")])
self.font_size_preset_combo = self._combo([("常用字号…", None), ("初号 42 磅", 42), ("小初 36 磅", 36),
("一号 26 磅", 26), ("小一 24 磅", 24), ("二号 22 磅", 22), ("小二 18 磅", 18),
("三号 16 磅", 16), ("小三 15 磅", 15), ("四号 14 磅", 14), ("小四 12 磅", 12),
("五号 10.5 磅", 10.5), ("小五 9 磅", 9), ("六号 7.5 磅", 7.5)])
form.addRow("字号", self._row(self.font_size_spin, self.font_size_unit_combo, self.font_size_preset_combo))
self.bool_boxes = {}
for key, label in [("bold", "加粗"), ("italic", "斜体"), ('underline', '下划线'), ('strike', '删除线'), ("contextual_spacing", "同样式段落间不添加间距"),
("keep_with_next", "与下段同页"), ("keep_lines_together", "段中不分页"),
("page_break_before", "段前分页"), ("widow_control", "孤行控制")]:
box = QCheckBox(label)
box.setTristate(True)
box.setToolTip("方块:继承;勾选:开启;空白:关闭")
self.bool_boxes[key] = box
self.bold_checkbox = self.bool_boxes["bold"]
self.italic_checkbox = self.bool_boxes["italic"]
form.addRow("字形", self._row(self.bold_checkbox, self.italic_checkbox))
form.addRow('文字修饰', self._row(self.bool_boxes['underline'], self.bool_boxes['strike']))
self.background_edit = QLineEdit()
self.background_edit.setPlaceholderText('继承 / transparent / #RRGGBB')
form.addRow('底色', self.background_edit)
self.border_color_edit = QLineEdit()
self.border_color_edit.setPlaceholderText('继承 / #RRGGBB')
self.border_width_spin = self._spin(20)
self.border_width_spin.setSuffix(' 磅')
self.border_style_combo = self._combo([('继承',None),('无边框','none'),('隐藏','hidden'),('实线','solid'),('点线','dotted'),('虚线','dashed'),('双线','double'),('凹槽','groove'),('凸脊','ridge'),('内嵌','inset'),('外凸','outset')])
self.cell_padding_spin = self._spin(100)
self.cell_padding_spin.setSuffix(' 磅')
self.border_row = form.rowCount()
form.addRow('边框颜色 / 宽度 / 样式', self._row(self.border_color_edit, self.border_width_spin, self.border_style_combo))
self.padding_row = form.rowCount()
form.addRow('内边距', self.cell_padding_spin)
self.list_marker_box = self._combo([('继承', None), ('圆点', 'disc'), ('空心圆', 'circle'), ('方块', 'square'),
('数字', 'decimal'), ('小写字母', 'lower-alpha'), ('大写字母', 'upper-alpha'), ('小写罗马', 'lower-roman'), ('大写罗马', 'upper-roman'), ('无', 'none')])
self.marker_row = form.rowCount()
form.addRow('列表标记', self.list_marker_box)
self.level_indent_spin = self._spin(200); self.level_indent_spin.setSuffix(' 磅')
self.level_row = form.rowCount()
form.addRow('每级列表缩进', self.level_indent_spin)
for edit in (self.background_edit, self.border_color_edit):
edit.editingFinished.connect(self._store_and_refresh)
self.color_combo = self._combo([("继承", None), ("随所在文字颜色", "inherit"), ("自动(随主题)", "auto"), ("自定义…", "custom")])
self.color_button = QPushButton("#23272f")
self.color_button.clicked.connect(self._choose_color)
form.addRow("字体颜色", self._row(self.color_combo, self.color_button))
self.character_spacing_combo = self._combo([("继承", None), ("标准", 0), ("加宽", 1), ("紧缩", -1)])
self.character_spacing_spin = self._spin(100, False)
self.character_spacing_spin.setSuffix(" 磅")
form.addRow("字符间距", self._row(self.character_spacing_combo, self.character_spacing_spin))
self.paragraph_row_start = form.rowCount()
self.alignment_combo = self._combo([("继承", None), ("左对齐", "left"), ("居中", "center"), ("右对齐", "right"), ("两端对齐", "justify")])
form.addRow("对齐方式", self.alignment_combo)
for side, label in (("left", "左缩进"), ("right", "右缩进")):
spin = self._spin()
unit = self._combo([("字符", "em"), ("磅", "pt"), ("厘米", "cm")])
setattr(self, f"{side}_indent_spin", spin)
setattr(self, f"{side}_indent_unit_combo", unit)
form.addRow(label, self._row(spin, unit))
self.indent_mode_combo = self._combo([("继承", None), ("无", "none"), ("首行缩进", "first"), ("悬挂缩进", "hanging")])
self.indent_spin = self._spin(100, False)
self.indent_unit_combo = self._combo([('字符', 'em'), ('磅', 'pt'), ('像素', 'px')])
form.addRow("特殊缩进", self._row(self.indent_mode_combo, self.indent_spin, self.indent_unit_combo))
self.line_height_mode_combo = self._combo([("继承", None), ("单倍", "single"), ("1.5 倍", "one_half"),
("双倍", "double"), ("多倍", "multiple"), ("固定值(磅)", "exact"), ("最小值(磅)", "at_least")])
self.line_height_spin = self._spin(500, False)
self.line_height_spin.setMinimum(0.1)
form.addRow("行距", self._row(self.line_height_mode_combo, self.line_height_spin))
for side, label in (("before", "段前间距"), ("after", "段后间距")):
spin = self._spin(1000)
unit = self._combo([("磅", "pt"), ("字符(em)", "em"), ("行", "line")])
setattr(self, f"space_{side}_spin", spin)
setattr(self, f"space_{side}_unit_combo", unit)
form.addRow(label, self._row(spin, unit))
form.addRow("段落间距", self.bool_boxes["contextual_spacing"])
form.addRow("换行与分页", self._row(self.bool_boxes["keep_with_next"], self.bool_boxes["keep_lines_together"]))
form.addRow("", self._row(self.bool_boxes["page_break_before"], self.bool_boxes["widow_control"]))
self.paragraph_row_end = form.rowCount()
note = QLabel("“继承”沿用文档默认样式;0 表示清零。复选框方块表示继承。")
note.setWordWrap(True)
form.addRow(note)
reset = QPushButton("重置当前对象")
reset.setObjectName("styleResetButton")
reset.setMaximumWidth(128)
reset.clicked.connect(self._reset_current_rule)
form.addRow(reset)
scroll = QScrollArea()
scroll.setWidgetResizable(True)
scroll.setWidget(panel)
right = QVBoxLayout()
right.addWidget(scroll, 1)
right.addWidget(QLabel("字体与段落预览(扩展 CSS 应用后查看;分页以 Word 为准)"))
self.preview = QTextEdit()
self.preview.setReadOnly(True)
self.preview.setMinimumHeight(125)
self.preview.setMaximumHeight(165)
self.preview.setStyleSheet("QTextEdit { background: white; color: #23272f; }")
right.addWidget(self.preview)
layout.addLayout(right, 1)
for widget in panel.findChildren(QComboBox):
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)
for widget in panel.findChildren(QDoubleSpinBox):
widget.valueChanged.connect(self._store_and_refresh)
for widget in self.bool_boxes.values():
widget.checkStateChanged.connect(self._store_and_refresh)
self.font_size_preset_combo.currentIndexChanged.connect(self._apply_size_preset)
self.target_list.currentItemChanged.connect(self._change_target)
return page
def _build_advanced_tab(self, css: str) -> QWidget:
page = QWidget()
layout = QVBoxLayout(page)
label = QLabel("这里是完整样式集。已支持的字体、段落、文字修饰及底色/边框属性会同步到图形设置和 Word;复杂选择器、条件规则等保留为 CSS,并显示适用范围提示。")
label.setWordWrap(True)
layout.addWidget(label)
self.extra_css_edit = QTextEdit()
self.extra_css_edit.setAcceptRichText(False)
self.extra_css_edit.setPlaceholderText("可以先调整图形设置,再编辑这里生成的 CSS。\n例如:.reader p { font-size: 14pt; color: #24558a; }")
self.extra_css_edit.setPlainText(css)
self.extra_css_edit.setFont(QFont("Consolas", 10))
self.extra_css_edit.textChanged.connect(self._css_changed)
layout.addWidget(self.extra_css_edit)
self.css_status_label = QLabel()
self.css_status_label.setWordWrap(True)
self.css_status_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
layout.addWidget(self.css_status_label)
return page
def _css_changed(self) -> None:
if not self._syncing_css:
self._css_dirty = True
self.css_status_label.setText("正在编辑,停止输入后同步核心设置…")
self._css_timer.start()
def _sync_from_css(self, update_widgets: bool = True) -> bool:
self._css_timer.stop()
result = analyze_css(self.extra_css_edit.toPlainText(), getattr(self.parent(), "document_font_size", 16))
valid = not result.errors
self.tabs.setTabEnabled(0, valid)
self.button_box.button(QDialogButtonBox.StandardButton.Ok).setEnabled(valid)
if not valid:
self.css_status_label.setText("尚未同步:" + ";".join(result.errors[:3]))
return False
self._css_dirty = False
metadata = {key: deepcopy(self.rules[key]) for key in ('_metadata', '_preset') if key in self.rules}
self.rules = result.rules
self.rules.update(metadata)
if update_widgets:
self._load_rule_to_widgets(self.rules.get(self._current_target, {}))
else:
self._refresh_preview()
summary = "可识别的核心设置已同步,并用于 Word 导出。"
if result.notes:
summary += "\n" + ";".join(result.notes[:4]) + (";更多说明见悬停提示。" if len(result.notes) > 4 else "")
self.css_status_label.setText(summary)
self.css_status_label.setToolTip("\n".join(result.notes))
return True
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 = '' if base == '__legacy__' else 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}
if base != '__legacy__': metadata[key]['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,
getattr(parent, 'document_font_family', ''), getattr(parent, 'document_font_size', 16)))
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():
return
self._syncing_css = True
blocker = QSignalBlocker(self.extra_css_edit)
cursor = self.extra_css_edit.textCursor()
position = cursor.position()
cursor.beginEditBlock()
cursor.select(QTextCursor.SelectionType.Document)
cursor.insertText(source)
cursor.endEditBlock()
cursor.setPosition(min(position, len(source)))
self.extra_css_edit.setTextCursor(cursor)
del blocker
self._syncing_css = False
def _choose_color(self) -> None:
color = QColorDialog.getColor(QColor(self.color_button.text()), self, "字体颜色")
if color.isValid():
self.color_button.setText(color.name())
self._select(self.color_combo, 'custom')
self._store_and_refresh()
def _apply_size_preset(self, *_: object) -> None:
value = self.font_size_preset_combo.currentData()
if value is not None:
self._loading = True
self.font_size_spin.setValue(value)
self.font_size_unit_combo.setCurrentIndex(0)
self.font_size_preset_combo.setCurrentIndex(0)
self._loading = False
self._store_and_refresh()
@staticmethod
def _select(box: QComboBox, value: object) -> None:
index = box.findData(value)
box.setCurrentIndex(max(0, index))
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('文档默认 / 所在段落', '')
compatibility = {'inline_code':'code','table_head':'table','table_cell':'table'}.get(key)
if compatibility: self.based_on_box.addItem('兼容:' + style_name(compatibility, self.rules), '__legacy__')
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, '__legacy__' if legacy_base(key, self.rules) else 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, self._current_target == 'table')
self.form.setRowVisible(self.padding_row, self._current_target == 'table')
self.form.setRowVisible(self.marker_row, self._current_target.startswith('list'))
self.form.setRowVisible(self.level_row, self._current_target.startswith('list'))
self.background_edit.setText(rule.get('background_color', ''))
self.border_color_edit.setText(rule.get('border_color', ''))
self.border_width_spin.setValue(number(rule.get('border_width'), -1))
self._select(self.border_style_combo, rule.get('border_style'))
self.cell_padding_spin.setValue(number(rule.get('cell_padding'), -1))
self.level_indent_spin.setValue(number(rule.get('level_indent'), -1))
self._select(self.list_marker_box, rule.get('list_marker'))
rule = normalize_rule(rule)
for key, box in (("chinese_font_family", self.font_combo), ("english_font_family", self.english_font_combo)):
box.setCurrentText(str(rule.get(key) or "继承"))
self.font_size_spin.setValue(number(rule.get("font_size"), -1))
self._select(self.font_size_unit_combo, rule.get("font_size_unit", "px" if "font_size" in rule else "pt"))
for key, box in self.bool_boxes.items():
box.setCheckState(Qt.CheckState.PartiallyChecked if key not in rule else
Qt.CheckState.Checked if rule[key] else Qt.CheckState.Unchecked)
color = rule.get("font_color")
self._select(self.color_combo, "custom" if str(color).startswith("#") else color)
self.color_button.setText(str(color) if str(color).startswith("#") else "#23272f")
spacing = rule.get("letter_spacing")
self._select(self.character_spacing_combo, None if spacing is None else (1 if number(spacing) > 0 else -1 if number(spacing) < 0 else 0))
self.character_spacing_spin.setValue(abs(number(spacing)))
self._select(self.alignment_combo, rule.get("alignment"))
for side in ("left", "right"):
getattr(self, f"{side}_indent_spin").setValue(number(rule.get(f"{side}_indent_value"), -1))
self._select(getattr(self, f"{side}_indent_unit_combo"), rule.get(f"{side}_indent_unit", "em"))
self._select(self.indent_mode_combo, rule.get("indent_mode"))
self.indent_spin.setValue(number(rule.get("indent_value")))
self._select(self.indent_unit_combo, rule.get('indent_unit', 'em'))
mode, value = rule.get("line_spacing_mode"), number(rule.get("line_height_value"), 1)
if mode == "multiple":
mode = {1: "single", 1.5: "one_half", 2: "double"}.get(value, "multiple")
self._select(self.line_height_mode_combo, mode)
self.line_height_spin.setValue(value)
for side in ("before", "after"):
getattr(self, f"space_{side}_spin").setValue(number(rule.get(f"space_{side}_value"), -1))
self._select(getattr(self, f"space_{side}_unit_combo"), rule.get(f"space_{side}_unit", "pt"))
self._loaded_widget_rule = self._read_widget_rule()
self._loading = False
self._refresh_preview()
def _read_widget_rule(self) -> dict:
rule = {}
def put(key: str, value: object) -> None:
if value is None:
rule.pop(key, None)
else:
rule[key] = value
for key, box in (("chinese_font_family", self.font_combo), ("english_font_family", self.english_font_combo)):
put(key, box.currentText() if box.currentText() != "继承" else None)
size = self.font_size_spin.value()
put("font_size", size if size > 0 else None)
put("font_size_unit", self.font_size_unit_combo.currentData() if size > 0 else None)
for key, box in self.bool_boxes.items():
put(key, None if box.checkState() == Qt.CheckState.PartiallyChecked else box.isChecked())
for key, widget in (('background_color', self.background_edit), ('border_color', self.border_color_edit)):
text = widget.text().strip()
put(key, text if re.fullmatch(r'#[0-9a-fA-F]{6}|transparent', text) else None)
for key, widget in (('border_width', self.border_width_spin), ('cell_padding', self.cell_padding_spin), ('level_indent', self.level_indent_spin)):
put(key, widget.value() if widget.value() >= 0 else None)
put('list_marker', self.list_marker_box.currentData())
put('border_style', self.border_style_combo.currentData())
color = self.color_combo.currentData()
put("font_color", self.color_button.text() if color == "custom" else color)
direction = self.character_spacing_combo.currentData()
put("letter_spacing", None if direction is None else direction * self.character_spacing_spin.value())
put("alignment", self.alignment_combo.currentData())
for side in ("left", "right", "space_before", "space_after"):
prefix = f"{side}_indent" if side in ("left", "right") else side
value = getattr(self, f"{prefix}_spin").value()
put(f"{prefix}_value", value if value >= 0 else None)
put(f"{prefix}_unit", getattr(self, f"{prefix}_unit_combo").currentData() if value >= 0 else None)
mode = self.indent_mode_combo.currentData()
put("indent_mode", mode)
put("indent_value", None if mode is None else 0 if mode == "none" else self.indent_spin.value())
put('indent_unit', self.indent_unit_combo.currentData() if mode in ('first', 'hanging') and self.indent_unit_combo.currentData() != 'em' else None)
mode = self.line_height_mode_combo.currentData()
preset = {"single": 1, "one_half": 1.5, "double": 2}
put("line_spacing_mode", "multiple" if mode in preset else mode)
put("line_height_value", None if mode is None else preset.get(mode, self.line_height_spin.value()))
rule.pop("line_height_unit", None)
if CATALOG[self._current_target].kind == 'character':
rule = {key: value for key, value in rule.items() if key in CHARACTER_FIELDS}
return rule
def _store_current_rule(self) -> None:
if self._loading:
return
rule = normalize_rule(self.rules.get(self._current_target, {}))
current = self._read_widget_rule()
previous = self._loaded_widget_rule
# A spin box can round or clamp imported CSS. Only changed controls
# may write back; changing italic must not rewrite an untouched length.
for keys in GROUPS.values():
if any(current.get(key) != previous.get(key) for key in keys):
for key in keys:
if key in current: rule[key] = current[key]
else: rule.pop(key, None)
self._loaded_widget_rule = current
if rule:
self.rules[self._current_target] = rule
else:
self.rules.pop(self._current_target, None)
def _change_target(self, current: QListWidgetItem, previous: QListWidgetItem | None) -> None:
if self._css_dirty:
self._sync_from_css()
self._current_target = current.data(Qt.ItemDataRole.UserRole)
self._load_rule_to_widgets(self.rules.get(self._current_target, {}))
def _reset_current_rule(self) -> None:
before = self.rules.get(self._current_target, {})
self._write_css(patch_core(self.extra_css_edit.toPlainText(), self._current_target, before, {}, reset=True))
self._sync_from_css()
def _store_and_refresh(self, *_: object) -> None:
if not self._loading:
if self._css_dirty and not self._sync_from_css():
return
before = deepcopy(self.rules.get(self._current_target, {}))
self._store_current_rule()
after = self.rules.get(self._current_target, {})
self._write_css(patch_core(self.extra_css_edit.toPlainText(), self._current_target, before, after))
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))
self.color_button.setEnabled(self.color_combo.currentData() == "custom")
parent = self.parent()
rule = resolved_rules(self.rules, getattr(parent, "document_font_family", ""),
getattr(parent, "document_font_size", 16))[self._current_target]
points = font_points(rule)
block = QTextBlockFormat()
block.setAlignment({"left": Qt.AlignmentFlag.AlignLeft, "center": Qt.AlignmentFlag.AlignHCenter,
"right": Qt.AlignmentFlag.AlignRight, "justify": Qt.AlignmentFlag.AlignJustify}[rule["alignment"]])
# QTextDocument distances are logical pixels; Word values are points.
scale = 96 / 72
for side, setter in (("left", block.setLeftMargin), ("right", block.setRightMargin)):
setter(length_points(rule[f"{side}_indent_value"], rule[f"{side}_indent_unit"], points) * scale)
indent = length_points(rule['indent_value'], rule.get('indent_unit', 'em'), points) * scale
block.setTextIndent(indent if rule["indent_mode"] == "first" else -indent if rule["indent_mode"] == "hanging" else 0)
mode = rule["line_spacing_mode"]
block.setLineHeight(number(rule["line_height_value"]) * (100 if mode == "multiple" else scale),
{"multiple": 1, "exact": 2, "at_least": 3}[mode])
for side, setter in (("before", block.setTopMargin), ("after", block.setBottomMargin)):
setter(length_points(rule[f"space_{side}_value"], rule[f"space_{side}_unit"], points, line_points(rule, points)) * scale)
self.preview.clear()
cursor = self.preview.textCursor()
for index, sample in enumerate(("中文段落预览:字体、缩进与行距会实时更新。English text 123. 这段示例用于查看排版效果。", "第二段示例:观察段落之间的间距。Preview the next paragraph.")):
current = QTextBlockFormat(block)
if rule["contextual_spacing"]:
if index == 0:
current.setBottomMargin(0)
else:
current.setTopMargin(0)
if index:
cursor.insertBlock(current)
else:
cursor.setBlockFormat(current)
for part in re.findall(r"[\x00-\x7f]+|[^\x00-\x7f]+", sample):
char = QTextCharFormat()
char.setFontFamilies([str(rule["english_font_family"] if part.isascii() else rule["chinese_font_family"])])
char.setFontPointSize(points)
char.setFontWeight(QFont.Weight.Bold if rule["bold"] else QFont.Weight.Normal)
char.setFontItalic(rule["italic"])
char.setFontUnderline(rule.get('underline', False))
char.setFontStrikeOut(rule.get('strike', False))
if str(rule.get('background_color', '')).startswith('#'): char.setBackground(QColor(rule['background_color']))
char.setForeground(QColor("#23272f" if rule["font_color"] in ('auto', 'inherit') else rule["font_color"]))
char.setFontLetterSpacingType(QFont.SpacingType.AbsoluteSpacing)
char.setFontLetterSpacing(number(rule["letter_spacing"]) * scale)
cursor.insertText(part, char)
self.preview.moveCursor(QTextCursor.MoveOperation.Start)