Files
MDHelper/mdhelper/style_dialog.py
T

490 lines
24 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,
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
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._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.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(label)
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)
form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
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", "斜体"), ("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))
self.color_combo = self._combo([("继承", None), ("自动(随主题)", "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.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_spin.setSuffix(" 字符")
form.addRow("特殊缩进", self._row(self.indent_mode_combo, self.indent_spin))
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"]))
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 is not self.font_size_preset_combo:
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 = self.rules.get('_metadata')
self.rules = result.rules
if metadata:
self.rules['_metadata'] = deepcopy(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()
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.color_combo.setCurrentIndex(2)
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
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")))
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._loading = False
self._refresh_preview()
def _store_current_rule(self) -> None:
if self._loading:
return
rule = normalize_rule(self.rules.get(self._current_target, {}))
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())
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())
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 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:
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 = number(rule["indent_value"]) * 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.setForeground(QColor("#23272f" if rule["font_color"] == "auto" 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)