223 lines
11 KiB
Python
223 lines
11 KiB
Python
"""One configuration schema for local settings and portable JSON files."""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import math
|
|
import re
|
|
from dataclasses import asdict, dataclass, field, fields
|
|
from pathlib import Path
|
|
|
|
from .document_tree import DEFAULT_DOCUMENT_FILE_GROUPS, normalized_document_file_groups
|
|
from .export_settings import PageSettings
|
|
from .style_presets import DOCUMENT_STYLE_PRESETS
|
|
from .style_sync import normalize_payload
|
|
|
|
THEME_COLORS = {"white", "black", "dark_gray", "colorful"}
|
|
BACKGROUNDS = {"none", "chinese_knot", "cloud", "ruyi", "brush", "peony", "bamboo", "meander"}
|
|
WIDTH_SCALES = (1.0, 1.25, 1.5, 1.75, 2.0)
|
|
REFRESH_MODES = {"off", "current", "resources", "all"}
|
|
REFRESH_DELAYS = {800, 1000, 1500}
|
|
|
|
|
|
def number(value, default, minimum, maximum):
|
|
try:
|
|
value = float(value)
|
|
return max(minimum, min(maximum, value)) if math.isfinite(value) else default
|
|
except (ValueError, TypeError, OverflowError):
|
|
return default
|
|
|
|
|
|
def boolean(value, default=True):
|
|
if isinstance(value, str):
|
|
return {"true": True, "false": False, "1": True, "0": False}.get(value.lower(), default)
|
|
return bool(value) if isinstance(value, (bool, int)) else default
|
|
|
|
|
|
def normalize_custom_styles(value, font_size=16):
|
|
if not isinstance(value, dict):
|
|
return {}
|
|
result = {}
|
|
for key, style in value.items():
|
|
if not isinstance(style, dict):
|
|
continue
|
|
normalized = normalize_payload(style, "自定义样式", font_size)
|
|
name = str(normalized.get("name", "")).strip()
|
|
if not name:
|
|
continue
|
|
key = str(key)
|
|
if not key.startswith("custom:"):
|
|
safe = re.sub(r"[^0-9A-Za-z\u4e00-\u9fff._-]+", "-", name).strip("-._") or "style"
|
|
key, suffix = "custom:" + safe, 2
|
|
while key in result:
|
|
key = f"custom:{safe}-{suffix}"
|
|
suffix += 1
|
|
result[key] = normalized
|
|
return result
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ReaderPreferences:
|
|
theme: str = "light"
|
|
theme_color: str = "colorful"
|
|
theme_background: str = "none"
|
|
font_scale: float = 1.0
|
|
wheel_scroll_speed: float = 1.0
|
|
reader_width_scale: float = 1.0
|
|
ui_font_family: str = ""
|
|
ui_font_point_size: int = 0
|
|
document_font_family: str = ""
|
|
document_font_size: int = 16
|
|
document_style_id: str = "default"
|
|
custom_document_styles: dict = field(default_factory=dict)
|
|
document_tree_label_mode: str = "title"
|
|
math_engine: str = "katex"
|
|
auto_refresh: bool = True
|
|
auto_refresh_mode: str = "all"
|
|
auto_refresh_delay_ms: int = 1000
|
|
non_preview_action: str = "ask"
|
|
document_file_groups: tuple[str, ...] = DEFAULT_DOCUMENT_FILE_GROUPS
|
|
|
|
@classmethod
|
|
def from_mapping(cls, values: dict, base: ReaderPreferences | None = None):
|
|
base = base or cls()
|
|
data = asdict(base)
|
|
data.update({key: value for key, value in values.items() if key in data})
|
|
if "theme_color" not in values and isinstance(values.get("theme"), str) and values["theme"] in {"light", "dark"}:
|
|
data["theme_color"] = "black" if values["theme"] == "dark" else "white"
|
|
def choice(name, allowed):
|
|
if not isinstance(data[name], str) or data[name] not in allowed:
|
|
data[name] = getattr(base, name)
|
|
choice("theme_color", THEME_COLORS)
|
|
data["theme"] = "dark" if data["theme_color"] in {"black", "dark_gray"} else "light"
|
|
if data["theme_color"] != "colorful" or not isinstance(data["theme_background"], str) or data["theme_background"] not in BACKGROUNDS:
|
|
data["theme_background"] = "none"
|
|
size = base.document_font_size
|
|
if "font_scale" in values and "document_font_size" not in values:
|
|
size = round(number(values["font_scale"], base.font_scale, .75, 1.75) * 16)
|
|
data["document_font_size"] = int(number(values.get("document_font_size", size), size, 12, 28))
|
|
data["font_scale"] = data["document_font_size"] / 16
|
|
data["wheel_scroll_speed"] = number(data["wheel_scroll_speed"], base.wheel_scroll_speed, .5, 3)
|
|
width = number(data["reader_width_scale"], base.reader_width_scale, 1, 2)
|
|
data["reader_width_scale"] = min(WIDTH_SCALES, key=lambda value: abs(value - width))
|
|
data["ui_font_point_size"] = int(number(data["ui_font_point_size"], base.ui_font_point_size, 0, 32))
|
|
for name in ("ui_font_family", "document_font_family"):
|
|
data[name] = str(data[name]).strip()
|
|
data["custom_document_styles"] = normalize_custom_styles(data["custom_document_styles"], data["document_font_size"])
|
|
choice("document_style_id", set(DOCUMENT_STYLE_PRESETS) | set(data["custom_document_styles"]))
|
|
if data["document_style_id"] not in DOCUMENT_STYLE_PRESETS and data["document_style_id"] not in data["custom_document_styles"]:
|
|
data["document_style_id"] = "default"
|
|
choice("document_tree_label_mode", {"title", "filename"})
|
|
choice("math_engine", {"katex", "mathjax"})
|
|
choice("auto_refresh_mode", REFRESH_MODES)
|
|
enabled = boolean(data["auto_refresh"], base.auto_refresh)
|
|
if not enabled or data["auto_refresh_mode"] == "off":
|
|
data["auto_refresh_mode"] = "off"
|
|
data["auto_refresh"] = data["auto_refresh_mode"] != "off"
|
|
delay = int(number(data["auto_refresh_delay_ms"], base.auto_refresh_delay_ms, 0, 10000))
|
|
data["auto_refresh_delay_ms"] = delay if delay in REFRESH_DELAYS else base.auto_refresh_delay_ms
|
|
choice("non_preview_action", {"ask", "open", "block"})
|
|
data["document_file_groups"] = normalized_document_file_groups(data["document_file_groups"])
|
|
return cls(**data)
|
|
|
|
|
|
@dataclass
|
|
class ApplicationConfiguration:
|
|
reader: ReaderPreferences = field(default_factory=ReaderPreferences)
|
|
project_root: str = ""
|
|
recent_files: list[str] = field(default_factory=list)
|
|
bookmarks: list[dict] = field(default_factory=list)
|
|
scroll_positions: dict[str, int] = field(default_factory=dict)
|
|
external_applications: dict[str, str] = field(default_factory=dict)
|
|
page_settings: PageSettings = field(default_factory=PageSettings)
|
|
|
|
def to_payload(self, version: str) -> dict:
|
|
result = asdict(self)
|
|
result["reader"]["document_file_groups"] = list(self.reader.document_file_groups)
|
|
result.update(app="MDHelper", version=version)
|
|
return result
|
|
|
|
@classmethod
|
|
def from_payload(cls, payload: dict, base: ApplicationConfiguration | None = None):
|
|
base = base or cls()
|
|
result = cls(**{name: getattr(base, name) for name in cls.__dataclass_fields__})
|
|
if isinstance(payload.get("reader"), dict):
|
|
result.reader = ReaderPreferences.from_mapping(payload["reader"], base.reader)
|
|
if isinstance(payload.get("project_root"), str):
|
|
result.project_root = payload["project_root"]
|
|
recent = payload.get("recent_files", base.recent_files)
|
|
if isinstance(recent, str):
|
|
recent = [recent]
|
|
if isinstance(recent, list):
|
|
result.recent_files = [str(Path(str(path)).expanduser().resolve()) for path in recent if path]
|
|
bookmarks = payload.get("bookmarks", base.bookmarks)
|
|
if isinstance(bookmarks, list):
|
|
result.bookmarks = [item for item in bookmarks if isinstance(item, dict)]
|
|
positions = payload.get("scroll_positions", base.scroll_positions)
|
|
if isinstance(positions, dict):
|
|
result.scroll_positions = {}
|
|
for path, position in positions.items():
|
|
try:
|
|
result.scroll_positions[str(path)] = int(position)
|
|
except (TypeError, ValueError, OverflowError):
|
|
pass
|
|
applications = payload.get("external_applications", base.external_applications)
|
|
if isinstance(applications, dict):
|
|
result.external_applications = {str(ext).lower(): str(program) for ext, program in applications.items()
|
|
if str(ext).startswith(".") and str(program)}
|
|
if isinstance(payload.get("page_settings"), dict):
|
|
result.page_settings = PageSettings.from_dict(payload["page_settings"]).normalized()
|
|
return result
|
|
|
|
|
|
READER_KEYS = {item.name: "reader/" + item.name for item in fields(ReaderPreferences)}
|
|
READER_KEYS.update(reader_width_scale="reader/width_scale", document_tree_label_mode="tree/markdown_label_mode")
|
|
JSON_READER_FIELDS = {"custom_document_styles", "document_file_groups"}
|
|
COLLECTION_KEYS = {"bookmarks": "bookmarks/items", "scroll_positions": "reader/scroll_positions",
|
|
"external_applications": "external_apps/by_extension"}
|
|
|
|
|
|
class ConfigurationStore:
|
|
def __init__(self, settings):
|
|
self.settings = settings
|
|
|
|
def read_json(self, key, default):
|
|
try:
|
|
value = self.settings.value(key, None)
|
|
return json.loads(str(value)) if value is not None else default
|
|
except (TypeError, ValueError):
|
|
return default
|
|
|
|
def load(self) -> ApplicationConfiguration:
|
|
reader = {}
|
|
for name, key in READER_KEYS.items():
|
|
if self.settings.contains(key):
|
|
reader[name] = self.read_json(key, None) if name in JSON_READER_FIELDS else self.settings.value(key)
|
|
payload = {"reader": reader, "recent_files": self.settings.value("recent/files", []),
|
|
"project_root": self.settings.value("project/last_root", ""),
|
|
"page_settings": asdict(self.load_page_settings())}
|
|
payload.update({name: self.read_json(key, [] if name == "bookmarks" else {}) for name, key in COLLECTION_KEYS.items()})
|
|
return ApplicationConfiguration.from_payload(payload)
|
|
|
|
def load_page_settings(self) -> PageSettings:
|
|
value = self.read_json("export/page_settings", {})
|
|
if isinstance(value, dict) and value:
|
|
return PageSettings.from_dict(value).normalized()
|
|
margins = {name: number(self.settings.value(f"pdf/{name}_margin_mm", 15), 15, 0, 50)
|
|
for name in ("top", "bottom", "left", "right")}
|
|
return PageSettings(**margins)
|
|
|
|
def save_page_settings(self, value: PageSettings) -> None:
|
|
self.settings.setValue("export/page_settings", json.dumps(asdict(value), ensure_ascii=False))
|
|
|
|
def save(self, config: ApplicationConfiguration):
|
|
for name, value in asdict(config.reader).items():
|
|
self.settings.setValue(READER_KEYS[name], json.dumps(value, ensure_ascii=False) if name in JSON_READER_FIELDS else value)
|
|
for key in ("reader/embedded_toc", "reader/external_toc", "reader/embedded_progress"):
|
|
self.settings.remove(key)
|
|
for name, key in COLLECTION_KEYS.items():
|
|
self.settings.setValue(key, json.dumps(getattr(config, name), ensure_ascii=False))
|
|
self.settings.setValue("recent/files", config.recent_files)
|
|
if config.project_root:
|
|
self.settings.setValue("project/last_root", config.project_root)
|
|
self.save_page_settings(config.page_settings)
|