Initial MDHelper implementation
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
"""MDHelper package."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
from .app import main
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from .doc_check import main as check_documents_main
|
||||
from .logging_config import setup_logging
|
||||
from .main_window import MainWindow
|
||||
|
||||
|
||||
def parse_arguments(argv: list[str]) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description="MDHelper 本地 Markdown 帮助文档阅读器")
|
||||
parser.add_argument("file", nargs="?", help="启动后打开的 Markdown、网页或本地文件")
|
||||
parser.add_argument("--check", action="store_true", help="检查 sample.md 和 docs/ 中缺失的本地链接/媒体")
|
||||
parser.add_argument("--project-root", default=None, help="项目根目录,默认使用 MDHelper 所在目录")
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = parse_arguments(list(sys.argv[1:] if argv is None else argv))
|
||||
project_root = Path(args.project_root).resolve() if args.project_root else Path(__file__).resolve().parent.parent
|
||||
if args.check:
|
||||
return check_documents_main([str(project_root)])
|
||||
|
||||
QApplication.setAttribute(Qt.ApplicationAttribute.AA_DontCreateNativeWidgetSiblings, True)
|
||||
setup_logging(project_root)
|
||||
|
||||
app = QApplication([sys.argv[0]])
|
||||
app.setApplicationName("MDHelper")
|
||||
app.setOrganizationName("MDHelper")
|
||||
|
||||
initial_path = Path(args.file).expanduser().resolve() if args.file else None
|
||||
window = MainWindow(project_root=project_root, initial_path=initial_path)
|
||||
window.resize(1280, 820)
|
||||
window.show()
|
||||
|
||||
return app.exec()
|
||||
@@ -0,0 +1,103 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog,
|
||||
QHBoxLayout,
|
||||
QInputDialog,
|
||||
QListWidget,
|
||||
QListWidgetItem,
|
||||
QPushButton,
|
||||
QVBoxLayout,
|
||||
)
|
||||
|
||||
|
||||
class BookmarkManagerDialog(QDialog):
|
||||
def __init__(self, bookmarks: list[dict[str, str]], parent: object | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("书签管理")
|
||||
self.setMinimumSize(560, 360)
|
||||
self._bookmarks = [dict(item) for item in bookmarks]
|
||||
self.selected_bookmark: dict[str, str] | None = None
|
||||
|
||||
self.list_widget = QListWidget()
|
||||
self._populate()
|
||||
|
||||
self.open_button = QPushButton("打开")
|
||||
self.open_button.clicked.connect(self._open_selected)
|
||||
|
||||
self.rename_button = QPushButton("重命名")
|
||||
self.rename_button.clicked.connect(self._rename_selected)
|
||||
|
||||
self.delete_button = QPushButton("删除")
|
||||
self.delete_button.clicked.connect(self._delete_selected)
|
||||
|
||||
self.close_button = QPushButton("关闭")
|
||||
self.close_button.clicked.connect(self.accept)
|
||||
|
||||
button_layout = QHBoxLayout()
|
||||
button_layout.addWidget(self.open_button)
|
||||
button_layout.addWidget(self.rename_button)
|
||||
button_layout.addWidget(self.delete_button)
|
||||
button_layout.addStretch(1)
|
||||
button_layout.addWidget(self.close_button)
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
layout.addWidget(self.list_widget)
|
||||
layout.addLayout(button_layout)
|
||||
|
||||
def bookmarks(self) -> list[dict[str, str]]:
|
||||
return [dict(item) for item in self._bookmarks]
|
||||
|
||||
def _populate(self) -> None:
|
||||
self.list_widget.clear()
|
||||
for index, bookmark in enumerate(self._bookmarks):
|
||||
label = bookmark.get("label") or Path(bookmark.get("path", "")).name
|
||||
path = bookmark.get("path", "")
|
||||
fragment = bookmark.get("fragment", "")
|
||||
suffix = f" #{fragment}" if fragment else ""
|
||||
item = QListWidgetItem(f"{label}{suffix}\n{path}")
|
||||
item.setData(256, index)
|
||||
self.list_widget.addItem(item)
|
||||
|
||||
def _current_index(self) -> int | None:
|
||||
item = self.list_widget.currentItem()
|
||||
if item is None:
|
||||
return None
|
||||
index = item.data(256)
|
||||
if isinstance(index, int) and 0 <= index < len(self._bookmarks):
|
||||
return index
|
||||
return None
|
||||
|
||||
def _open_selected(self) -> None:
|
||||
index = self._current_index()
|
||||
if index is None:
|
||||
return
|
||||
self.selected_bookmark = dict(self._bookmarks[index])
|
||||
self.accept()
|
||||
|
||||
def _rename_selected(self) -> None:
|
||||
index = self._current_index()
|
||||
if index is None:
|
||||
return
|
||||
|
||||
current = self._bookmarks[index].get("label", "")
|
||||
text, ok = QInputDialog.getText(self, "重命名书签", "名称", text=current)
|
||||
if not ok:
|
||||
return
|
||||
text = text.strip()
|
||||
if text:
|
||||
self._bookmarks[index]["label"] = text
|
||||
self._populate()
|
||||
self.list_widget.setCurrentRow(index)
|
||||
|
||||
def _delete_selected(self) -> None:
|
||||
index = self._current_index()
|
||||
if index is None:
|
||||
return
|
||||
del self._bookmarks[index]
|
||||
self._populate()
|
||||
if self._bookmarks:
|
||||
self.list_widget.setCurrentRow(min(index, len(self._bookmarks) - 1))
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from urllib.parse import unquote, urlsplit
|
||||
from urllib.request import url2pathname
|
||||
|
||||
|
||||
EXTERNAL_SCHEMES = {"http", "https", "mailto", "tel", "data", "qrc"}
|
||||
MARKDOWN_LINK_PATTERN = re.compile(r"!?\[[^\]]*]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)")
|
||||
HTML_LINK_PATTERN = re.compile(r"""(?:src|href)=["']([^"']+)["']""", flags=re.IGNORECASE)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LinkIssue:
|
||||
source: Path
|
||||
line_number: int
|
||||
target: str
|
||||
resolved_path: Path
|
||||
message: str
|
||||
|
||||
|
||||
def discover_markdown_files(project_root: Path) -> list[Path]:
|
||||
files: set[Path] = set()
|
||||
|
||||
for pattern in ("*.md", "*.markdown"):
|
||||
files.update(path.resolve() for path in project_root.glob(pattern) if path.is_file())
|
||||
|
||||
docs_root = project_root / "docs"
|
||||
if docs_root.exists():
|
||||
for pattern in ("*.md", "*.markdown"):
|
||||
files.update(path.resolve() for path in docs_root.rglob(pattern) if path.is_file())
|
||||
|
||||
return sorted(files)
|
||||
|
||||
|
||||
def check_documents(project_root: Path) -> list[LinkIssue]:
|
||||
root = project_root.resolve()
|
||||
issues: list[LinkIssue] = []
|
||||
|
||||
for markdown_path in discover_markdown_files(root):
|
||||
issues.extend(check_markdown_file(markdown_path))
|
||||
|
||||
return issues
|
||||
|
||||
|
||||
def check_markdown_file(markdown_path: Path) -> list[LinkIssue]:
|
||||
issues: list[LinkIssue] = []
|
||||
try:
|
||||
lines = markdown_path.read_text(encoding="utf-8").splitlines()
|
||||
except (OSError, UnicodeDecodeError) as error:
|
||||
return [
|
||||
LinkIssue(
|
||||
source=markdown_path,
|
||||
line_number=0,
|
||||
target=str(markdown_path),
|
||||
resolved_path=markdown_path,
|
||||
message=f"无法读取文件:{error}",
|
||||
)
|
||||
]
|
||||
|
||||
for line_number, line in enumerate(lines, start=1):
|
||||
for target in _extract_targets(line):
|
||||
resolved = _resolve_local_target(markdown_path, target)
|
||||
if resolved is not None and not resolved.exists():
|
||||
issues.append(
|
||||
LinkIssue(
|
||||
source=markdown_path,
|
||||
line_number=line_number,
|
||||
target=target,
|
||||
resolved_path=resolved,
|
||||
message="本地目标不存在",
|
||||
)
|
||||
)
|
||||
|
||||
return issues
|
||||
|
||||
|
||||
def _extract_targets(line: str) -> list[str]:
|
||||
targets = MARKDOWN_LINK_PATTERN.findall(line)
|
||||
targets.extend(HTML_LINK_PATTERN.findall(line))
|
||||
return [target.strip().strip("<>") for target in targets if target.strip()]
|
||||
|
||||
|
||||
def _resolve_local_target(markdown_path: Path, target: str) -> Path | None:
|
||||
parsed = urlsplit(target)
|
||||
if parsed.scheme in EXTERNAL_SCHEMES or parsed.path.startswith("#"):
|
||||
return None
|
||||
if parsed.scheme and parsed.scheme != "file":
|
||||
return None
|
||||
if not parsed.path:
|
||||
return None
|
||||
|
||||
if parsed.scheme == "file":
|
||||
return Path(url2pathname(unquote(parsed.path))).resolve()
|
||||
|
||||
return (markdown_path.parent / unquote(parsed.path)).resolve()
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="检查 MDHelper 文档中的本地链接和媒体引用。")
|
||||
parser.add_argument("project_root", nargs="?", default=".", help="项目根目录,默认使用当前目录。")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
root = Path(args.project_root).resolve()
|
||||
issues = check_documents(root)
|
||||
if not issues:
|
||||
print("文档检查通过:未发现缺失的本地链接或媒体。")
|
||||
return 0
|
||||
|
||||
print(f"发现 {len(issues)} 个文档引用问题:")
|
||||
for issue in issues:
|
||||
try:
|
||||
source = issue.source.relative_to(root)
|
||||
except ValueError:
|
||||
source = issue.source
|
||||
print(f"- {source}:{issue.line_number} {issue.message}: {issue.target}")
|
||||
print(f" -> {issue.resolved_path}")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,39 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from .markdown_utils import extract_headings
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DocumentEntry:
|
||||
path: Path
|
||||
title: str
|
||||
relative_path: str
|
||||
|
||||
|
||||
def first_heading(path: Path) -> str | None:
|
||||
headings = extract_headings(path)
|
||||
return headings[0].title if headings else None
|
||||
|
||||
|
||||
def discover_documents(project_root: Path) -> list[DocumentEntry]:
|
||||
candidates: list[Path] = []
|
||||
|
||||
sample = project_root / "sample.md"
|
||||
if sample.exists():
|
||||
candidates.append(sample)
|
||||
|
||||
docs_dir = project_root / "docs"
|
||||
if docs_dir.exists():
|
||||
candidates.extend(sorted(docs_dir.rglob("*.md")))
|
||||
|
||||
entries: list[DocumentEntry] = []
|
||||
for path in candidates:
|
||||
resolved = path.resolve()
|
||||
title = first_heading(resolved) or resolved.stem.replace("_", " ").title()
|
||||
relative_path = resolved.relative_to(project_root).as_posix()
|
||||
entries.append(DocumentEntry(path=resolved, title=title, relative_path=relative_path))
|
||||
|
||||
return entries
|
||||
@@ -0,0 +1,50 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HistoryItem:
|
||||
path: Path
|
||||
fragment: str = ""
|
||||
|
||||
|
||||
class NavigationHistory:
|
||||
def __init__(self) -> None:
|
||||
self._items: list[HistoryItem] = []
|
||||
self._index = -1
|
||||
|
||||
def push(self, item: HistoryItem) -> None:
|
||||
if self.current == item:
|
||||
return
|
||||
del self._items[self._index + 1 :]
|
||||
self._items.append(item)
|
||||
self._index = len(self._items) - 1
|
||||
|
||||
@property
|
||||
def current(self) -> HistoryItem | None:
|
||||
if 0 <= self._index < len(self._items):
|
||||
return self._items[self._index]
|
||||
return None
|
||||
|
||||
@property
|
||||
def can_go_back(self) -> bool:
|
||||
return self._index > 0
|
||||
|
||||
@property
|
||||
def can_go_forward(self) -> bool:
|
||||
return self._index + 1 < len(self._items)
|
||||
|
||||
def back(self) -> HistoryItem | None:
|
||||
if not self.can_go_back:
|
||||
return None
|
||||
self._index -= 1
|
||||
return self.current
|
||||
|
||||
def forward(self) -> HistoryItem | None:
|
||||
if not self.can_go_forward:
|
||||
return None
|
||||
self._index += 1
|
||||
return self.current
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from pathlib import Path
|
||||
from types import TracebackType
|
||||
|
||||
from PySide6.QtCore import qInstallMessageHandler
|
||||
|
||||
|
||||
def setup_logging(project_root: Path) -> Path:
|
||||
log_dir = project_root / "logs"
|
||||
log_dir.mkdir(exist_ok=True)
|
||||
log_path = log_dir / "mdhelper.log"
|
||||
|
||||
root_logger = logging.getLogger()
|
||||
root_logger.setLevel(logging.INFO)
|
||||
root_logger.handlers.clear()
|
||||
|
||||
formatter = logging.Formatter(
|
||||
fmt="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||
datefmt="%Y-%m-%d %H:%M:%S",
|
||||
)
|
||||
|
||||
file_handler = RotatingFileHandler(
|
||||
log_path,
|
||||
maxBytes=1_000_000,
|
||||
backupCount=3,
|
||||
encoding="utf-8",
|
||||
)
|
||||
file_handler.setFormatter(formatter)
|
||||
root_logger.addHandler(file_handler)
|
||||
|
||||
console_handler = logging.StreamHandler()
|
||||
console_handler.setFormatter(formatter)
|
||||
root_logger.addHandler(console_handler)
|
||||
|
||||
def handle_exception(
|
||||
exc_type: type[BaseException],
|
||||
exc_value: BaseException,
|
||||
exc_traceback: TracebackType | None,
|
||||
) -> None:
|
||||
logging.getLogger("mdhelper").exception(
|
||||
"Unhandled exception",
|
||||
exc_info=(exc_type, exc_value, exc_traceback),
|
||||
)
|
||||
sys.__excepthook__(exc_type, exc_value, exc_traceback)
|
||||
|
||||
def handle_qt_message(mode: object, context: object, message: str) -> None:
|
||||
logging.getLogger("qt").warning("%s", message)
|
||||
|
||||
sys.excepthook = handle_exception
|
||||
qInstallMessageHandler(handle_qt_message)
|
||||
|
||||
logging.getLogger("mdhelper").info("Logging initialized: %s", log_path)
|
||||
return log_path
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,381 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import unquote, urlsplit
|
||||
|
||||
from markdown_it import MarkdownIt
|
||||
from markdown_it.token import Token
|
||||
from pygments import highlight
|
||||
from pygments.formatters import HtmlFormatter
|
||||
from pygments.lexers import TextLexer, get_lexer_by_name
|
||||
from pygments.util import ClassNotFound
|
||||
|
||||
from .markdown_utils import slugify_heading
|
||||
from .media import media_kind, media_mime_type
|
||||
|
||||
|
||||
class MarkdownRenderer:
|
||||
def __init__(self, project_root: Path) -> None:
|
||||
self.project_root = project_root
|
||||
self.resources_dir = Path(__file__).resolve().parent / "resources"
|
||||
self.formatter = HtmlFormatter(nowrap=True)
|
||||
self.markdown = MarkdownIt(
|
||||
"commonmark",
|
||||
{
|
||||
"html": True,
|
||||
"typographer": False,
|
||||
"breaks": False,
|
||||
},
|
||||
).enable(["table", "strikethrough"])
|
||||
|
||||
self.markdown.renderer.rules["fence"] = self._render_fence
|
||||
self.markdown.renderer.rules["code_block"] = self._render_code_block
|
||||
self.markdown.renderer.rules["image"] = self._render_image
|
||||
self.markdown.renderer.rules["link_open"] = self._render_link_open
|
||||
self.markdown.core.ruler.push("mdhelper_heading_ids", self._add_heading_ids)
|
||||
self.markdown.core.ruler.push("mdhelper_admonitions", self._convert_admonitions)
|
||||
self.markdown.core.ruler.push("mdhelper_task_lists", self._convert_task_lists)
|
||||
|
||||
def render_file(self, markdown_path: Path, theme: str = "light", font_scale: float = 1.0) -> str:
|
||||
source = markdown_path.read_text(encoding="utf-8")
|
||||
body = self.markdown.render(source, {"path": str(markdown_path)})
|
||||
return self._wrap_html(
|
||||
body=body,
|
||||
title=markdown_path.name,
|
||||
theme=theme,
|
||||
font_scale=font_scale,
|
||||
)
|
||||
|
||||
def wrap_body_for_display(self, body: str, title: str, theme: str = "light", font_scale: float = 1.0) -> str:
|
||||
return self._wrap_html(body=body, title=title, theme=theme, font_scale=font_scale)
|
||||
|
||||
def _render_fence(
|
||||
self,
|
||||
tokens: list[Token],
|
||||
idx: int,
|
||||
options: dict[str, Any],
|
||||
env: dict[str, Any],
|
||||
) -> str:
|
||||
token = tokens[idx]
|
||||
language = token.info.strip().split(maxsplit=1)[0] if token.info else ""
|
||||
language_class = f" language-{html.escape(language)}" if language else ""
|
||||
code = self._highlight_code(token.content, language)
|
||||
label = html.escape(language or "text")
|
||||
return (
|
||||
f'<div class="code-block">'
|
||||
f'<div class="code-title">{label}</div>'
|
||||
f'<pre class="highlight{language_class}"><code>{code}</code></pre>'
|
||||
f"</div>\n"
|
||||
)
|
||||
|
||||
def _render_code_block(
|
||||
self,
|
||||
tokens: list[Token],
|
||||
idx: int,
|
||||
options: dict[str, Any],
|
||||
env: dict[str, Any],
|
||||
) -> str:
|
||||
token = tokens[idx]
|
||||
return (
|
||||
'<div class="code-block">'
|
||||
'<pre class="highlight language-text"><code>'
|
||||
f"{html.escape(token.content)}"
|
||||
"</code></pre>"
|
||||
"</div>\n"
|
||||
)
|
||||
|
||||
def _render_image(
|
||||
self,
|
||||
tokens: list[Token],
|
||||
idx: int,
|
||||
options: dict[str, Any],
|
||||
env: dict[str, Any],
|
||||
) -> str:
|
||||
token = tokens[idx]
|
||||
src = token.attrGet("src") or ""
|
||||
title = token.attrGet("title") or ""
|
||||
alt = token.content or title or Path(src).name
|
||||
kind = media_kind(src)
|
||||
resolved_src = self._resolve_local_media_src(src, env)
|
||||
|
||||
escaped_src = html.escape(resolved_src, quote=True)
|
||||
escaped_alt = html.escape(alt, quote=True)
|
||||
mime_type = media_mime_type(src)
|
||||
source_type = f' type="{html.escape(mime_type, quote=True)}"' if mime_type else ""
|
||||
caption = f"<figcaption>{html.escape(alt)}</figcaption>" if alt else ""
|
||||
|
||||
if kind == "audio":
|
||||
return (
|
||||
f'<figure class="media-block media-audio" data-media-src="{escaped_src}">'
|
||||
f'<audio controls preload="metadata">'
|
||||
f'<source src="{escaped_src}"{source_type}>'
|
||||
"当前环境无法播放此音频。"
|
||||
"</audio>"
|
||||
f"{caption}</figure>"
|
||||
)
|
||||
if kind == "video":
|
||||
return (
|
||||
f'<figure class="media-block media-video" data-media-src="{escaped_src}">'
|
||||
f'<video controls preload="metadata" playsinline>'
|
||||
f'<source src="{escaped_src}"{source_type}>'
|
||||
"当前环境无法播放此视频。"
|
||||
"</video>"
|
||||
f"{caption}</figure>"
|
||||
)
|
||||
if kind == "gif":
|
||||
return (
|
||||
'<figure class="media-block media-image media-gif">'
|
||||
f'<img src="{escaped_src}" alt="{escaped_alt}" loading="lazy">'
|
||||
f"{caption}</figure>"
|
||||
)
|
||||
return f'<img src="{escaped_src}" alt="{escaped_alt}" loading="lazy">'
|
||||
|
||||
def _render_link_open(
|
||||
self,
|
||||
tokens: list[Token],
|
||||
idx: int,
|
||||
options: dict[str, Any],
|
||||
env: dict[str, Any],
|
||||
) -> str:
|
||||
token = tokens[idx]
|
||||
href = token.attrGet("href") or ""
|
||||
resolved_href = self._resolve_local_href(href, env)
|
||||
if resolved_href != href:
|
||||
token.attrSet("href", resolved_href)
|
||||
return self.markdown.renderer.renderToken(tokens, idx, options, env)
|
||||
|
||||
def _resolve_local_media_src(self, src: str, env: dict[str, Any]) -> str:
|
||||
parsed = urlsplit(src)
|
||||
if parsed.scheme or parsed.path.startswith("#"):
|
||||
return src
|
||||
|
||||
markdown_path_value = env.get("path")
|
||||
if not markdown_path_value:
|
||||
return src
|
||||
|
||||
local_path = (Path(str(markdown_path_value)).parent / unquote(parsed.path)).resolve()
|
||||
if not local_path.exists():
|
||||
return src
|
||||
|
||||
uri = local_path.as_uri()
|
||||
if parsed.fragment:
|
||||
uri = f"{uri}#{parsed.fragment}"
|
||||
return uri
|
||||
|
||||
def _resolve_local_href(self, href: str, env: dict[str, Any]) -> str:
|
||||
parsed = urlsplit(href)
|
||||
if parsed.scheme or parsed.path.startswith("#"):
|
||||
return href
|
||||
|
||||
markdown_path_value = env.get("path")
|
||||
if not markdown_path_value:
|
||||
return href
|
||||
|
||||
local_path = (Path(str(markdown_path_value)).parent / unquote(parsed.path)).resolve()
|
||||
if not local_path.exists():
|
||||
return href
|
||||
|
||||
uri = local_path.as_uri()
|
||||
if parsed.fragment:
|
||||
uri = f"{uri}#{parsed.fragment}"
|
||||
return uri
|
||||
|
||||
def _highlight_code(self, code: str, language: str) -> str:
|
||||
normalized = language.lower()
|
||||
if normalized in {"pseudocode", "pseudo"}:
|
||||
return self._highlight_pseudocode(code)
|
||||
|
||||
try:
|
||||
lexer = get_lexer_by_name(normalized) if normalized else TextLexer()
|
||||
except ClassNotFound:
|
||||
lexer = TextLexer()
|
||||
return highlight(code, lexer, self.formatter)
|
||||
|
||||
def _highlight_pseudocode(self, code: str) -> str:
|
||||
escaped = html.escape(code)
|
||||
keywords = (
|
||||
"BEGIN",
|
||||
"END",
|
||||
"SET",
|
||||
"FOR",
|
||||
"TO",
|
||||
"DO",
|
||||
"IF",
|
||||
"THEN",
|
||||
"ELSE",
|
||||
"RETURN",
|
||||
"WHILE",
|
||||
"REPEAT",
|
||||
"UNTIL",
|
||||
)
|
||||
|
||||
def replace_keyword(match: re.Match[str]) -> str:
|
||||
return f'<span class="pseudo-keyword">{match.group(0)}</span>'
|
||||
|
||||
pattern = r"\b(" + "|".join(keywords) + r")\b"
|
||||
return re.sub(pattern, replace_keyword, escaped)
|
||||
|
||||
def _add_heading_ids(self, state: Any) -> None:
|
||||
seen: dict[str, int] = {}
|
||||
tokens = state.tokens
|
||||
|
||||
for index, token in enumerate(tokens):
|
||||
if token.type != "heading_open" or index + 1 >= len(tokens):
|
||||
continue
|
||||
|
||||
inline = tokens[index + 1]
|
||||
if inline.type != "inline":
|
||||
continue
|
||||
|
||||
slug = slugify_heading(inline.content)
|
||||
if not slug:
|
||||
continue
|
||||
|
||||
count = seen.get(slug, 0)
|
||||
seen[slug] = count + 1
|
||||
if count:
|
||||
slug = f"{slug}-{count + 1}"
|
||||
|
||||
token.attrSet("id", slug)
|
||||
|
||||
def _convert_admonitions(self, state: Any) -> None:
|
||||
labels = {
|
||||
"NOTE": "注意",
|
||||
"TIP": "提示",
|
||||
"IMPORTANT": "重要",
|
||||
"WARNING": "警告",
|
||||
"CAUTION": "小心",
|
||||
}
|
||||
tokens = state.tokens
|
||||
|
||||
for index, token in enumerate(tokens):
|
||||
if token.type != "blockquote_open":
|
||||
continue
|
||||
|
||||
inline_index = self._first_inline_in_blockquote(tokens, index)
|
||||
if inline_index is None:
|
||||
continue
|
||||
|
||||
inline = tokens[inline_index]
|
||||
marker = re.match(
|
||||
r"^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*([^\n]*)(?:\n(.*))?$",
|
||||
inline.content,
|
||||
re.DOTALL,
|
||||
)
|
||||
if not marker:
|
||||
continue
|
||||
|
||||
kind = marker.group(1)
|
||||
title = marker.group(2).strip() or labels[kind]
|
||||
rest = (marker.group(3) or "").lstrip()
|
||||
close_index = self._matching_close_index(tokens, index, "blockquote_close")
|
||||
if close_index is None:
|
||||
continue
|
||||
|
||||
token.tag = "aside"
|
||||
token.attrJoin("class", f"admonition admonition-{kind.lower()}")
|
||||
tokens[close_index].tag = "aside"
|
||||
|
||||
title_node = Token("html_inline", "", 0)
|
||||
title_node.content = f'<span class="admonition-title">{html.escape(title)}</span>'
|
||||
children = [title_node]
|
||||
if rest:
|
||||
break_node = Token("html_inline", "", 0)
|
||||
break_node.content = "<br>"
|
||||
text = Token("text", "", 0)
|
||||
text.content = rest
|
||||
children.extend([break_node, text])
|
||||
|
||||
inline.content = f"{title}\n{rest}" if rest else title
|
||||
inline.children = children
|
||||
|
||||
def _convert_task_lists(self, state: Any) -> None:
|
||||
tokens = state.tokens
|
||||
|
||||
for index, token in enumerate(tokens):
|
||||
if token.type != "inline" or not token.children:
|
||||
continue
|
||||
|
||||
first_child = token.children[0]
|
||||
if first_child.type != "text":
|
||||
continue
|
||||
|
||||
marker = re.match(r"^\[([ xX])\]\s+", first_child.content)
|
||||
if not marker:
|
||||
continue
|
||||
|
||||
list_item = self._nearest_open_token(tokens, index, "list_item_open")
|
||||
if list_item is None:
|
||||
continue
|
||||
|
||||
bullet_list = self._nearest_open_token(tokens, index, "bullet_list_open")
|
||||
if bullet_list is not None:
|
||||
bullet_list.attrJoin("class", "task-list")
|
||||
|
||||
checked = marker.group(1).lower() == "x"
|
||||
list_item.attrJoin("class", "task-list-item")
|
||||
checkbox = Token("html_inline", "", 0)
|
||||
checked_attr = " checked" if checked else ""
|
||||
checkbox.content = (
|
||||
'<input class="task-list-item-checkbox" type="checkbox"'
|
||||
f"{checked_attr} disabled> "
|
||||
)
|
||||
first_child.content = first_child.content[marker.end() :]
|
||||
token.children.insert(0, checkbox)
|
||||
|
||||
def _first_inline_in_blockquote(self, tokens: list[Token], start_index: int) -> int | None:
|
||||
start_level = tokens[start_index].level
|
||||
for index in range(start_index + 1, len(tokens)):
|
||||
token = tokens[index]
|
||||
if token.type == "blockquote_close" and token.level == start_level:
|
||||
return None
|
||||
if token.type == "inline":
|
||||
return index
|
||||
return None
|
||||
|
||||
def _matching_close_index(self, tokens: list[Token], start_index: int, close_type: str) -> int | None:
|
||||
start_level = tokens[start_index].level
|
||||
for index in range(start_index + 1, len(tokens)):
|
||||
token = tokens[index]
|
||||
if token.type == close_type and token.level == start_level:
|
||||
return index
|
||||
return None
|
||||
|
||||
def _nearest_open_token(self, tokens: list[Token], start_index: int, token_type: str) -> Token | None:
|
||||
inline_level = tokens[start_index].level
|
||||
for token in reversed(tokens[:start_index]):
|
||||
if token.type == token_type and token.level < inline_level:
|
||||
return token
|
||||
return None
|
||||
|
||||
def _wrap_html(self, body: str, title: str, theme: str, font_scale: float) -> str:
|
||||
css = (self.resources_dir / "reader.css").read_text(encoding="utf-8")
|
||||
js = (self.resources_dir / "reader.js").read_text(encoding="utf-8")
|
||||
pygments_css = HtmlFormatter().get_style_defs(".highlight")
|
||||
escaped_title = html.escape(title)
|
||||
escaped_theme = html.escape(theme, quote=True)
|
||||
font_percent = int(max(0.8, min(font_scale, 1.6)) * 100)
|
||||
|
||||
return f"""<!doctype html>
|
||||
<html lang="zh-CN" data-theme="{escaped_theme}">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>{escaped_title}</title>
|
||||
<style>
|
||||
:root {{ --reader-font-scale: {font_percent}%; }}
|
||||
{pygments_css}
|
||||
{css}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="reader">
|
||||
{body}
|
||||
</main>
|
||||
<script src="qrc:///qtwebchannel/qwebchannel.js"></script>
|
||||
<script>{js}</script>
|
||||
</body>
|
||||
</html>"""
|
||||
@@ -0,0 +1,60 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Heading:
|
||||
level: int
|
||||
title: str
|
||||
slug: str
|
||||
|
||||
|
||||
def slugify_heading(text: str) -> str:
|
||||
slug = text.strip().casefold()
|
||||
slug = re.sub(r"[^\w\s\u4e00-\u9fff-]", "", slug)
|
||||
slug = re.sub(r"[\s_]+", "-", slug)
|
||||
slug = re.sub(r"-{2,}", "-", slug)
|
||||
return slug.strip("-")
|
||||
|
||||
|
||||
def extract_headings_from_text(markdown_text: str) -> list[Heading]:
|
||||
headings: list[Heading] = []
|
||||
seen: dict[str, int] = {}
|
||||
in_fenced_block = False
|
||||
|
||||
for line in markdown_text.splitlines():
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("```") or stripped.startswith("~~~"):
|
||||
in_fenced_block = not in_fenced_block
|
||||
continue
|
||||
if in_fenced_block:
|
||||
continue
|
||||
|
||||
match = re.match(r"^(#{1,6})\s+(.+?)\s*#*\s*$", stripped)
|
||||
if not match:
|
||||
continue
|
||||
|
||||
title = match.group(2).strip()
|
||||
slug = slugify_heading(title)
|
||||
if not slug:
|
||||
continue
|
||||
|
||||
count = seen.get(slug, 0)
|
||||
seen[slug] = count + 1
|
||||
if count:
|
||||
slug = f"{slug}-{count + 1}"
|
||||
|
||||
headings.append(Heading(level=len(match.group(1)), title=title, slug=slug))
|
||||
|
||||
return headings
|
||||
|
||||
|
||||
def extract_headings(path: Path) -> list[Heading]:
|
||||
try:
|
||||
return extract_headings_from_text(path.read_text(encoding="utf-8"))
|
||||
except UnicodeDecodeError:
|
||||
return []
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import PurePosixPath
|
||||
from urllib.parse import unquote, urlsplit
|
||||
|
||||
|
||||
IMAGE_EXTENSIONS = {
|
||||
".png",
|
||||
".jpg",
|
||||
".jpeg",
|
||||
".webp",
|
||||
".bmp",
|
||||
".svg",
|
||||
}
|
||||
GIF_EXTENSIONS = {".gif"}
|
||||
AUDIO_EXTENSIONS = {
|
||||
".mp3",
|
||||
".wav",
|
||||
".ogg",
|
||||
".m4a",
|
||||
".flac",
|
||||
}
|
||||
VIDEO_EXTENSIONS = {
|
||||
".mp4",
|
||||
".webm",
|
||||
".mov",
|
||||
".avi",
|
||||
".mkv",
|
||||
}
|
||||
MARKDOWN_EXTENSIONS = {".md", ".markdown"}
|
||||
WEBPAGE_EXTENSIONS = {".html", ".htm", ".xhtml"}
|
||||
|
||||
MEDIA_MIME_TYPES = {
|
||||
".mp3": "audio/mpeg",
|
||||
".wav": "audio/wav",
|
||||
".ogg": "audio/ogg",
|
||||
".m4a": "audio/mp4",
|
||||
".flac": "audio/flac",
|
||||
".mp4": "video/mp4",
|
||||
".webm": "video/webm",
|
||||
".mov": "video/quicktime",
|
||||
".avi": "video/x-msvideo",
|
||||
".mkv": "video/x-matroska",
|
||||
}
|
||||
|
||||
|
||||
def extension_from_url(url: str) -> str:
|
||||
path = unquote(urlsplit(url).path)
|
||||
return PurePosixPath(path).suffix.lower()
|
||||
|
||||
|
||||
def media_kind(url: str) -> str | None:
|
||||
ext = extension_from_url(url)
|
||||
if ext in GIF_EXTENSIONS:
|
||||
return "gif"
|
||||
if ext in IMAGE_EXTENSIONS:
|
||||
return "image"
|
||||
if ext in AUDIO_EXTENSIONS:
|
||||
return "audio"
|
||||
if ext in VIDEO_EXTENSIONS:
|
||||
return "video"
|
||||
return None
|
||||
|
||||
|
||||
def is_markdown_url(url: str) -> bool:
|
||||
return extension_from_url(url) in MARKDOWN_EXTENSIONS
|
||||
|
||||
|
||||
def is_webpage_url(url: str) -> bool:
|
||||
return extension_from_url(url) in WEBPAGE_EXTENSIONS
|
||||
|
||||
|
||||
def media_mime_type(url: str) -> str:
|
||||
return MEDIA_MIME_TYPES.get(extension_from_url(url), "")
|
||||
@@ -0,0 +1,602 @@
|
||||
html {
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: #f6f7f9;
|
||||
color: #23272f;
|
||||
font-family: "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;
|
||||
font-size: var(--reader-font-scale);
|
||||
line-height: 1.72;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] body {
|
||||
background: #17191f;
|
||||
color: #e4e8ef;
|
||||
}
|
||||
|
||||
.reader {
|
||||
box-sizing: border-box;
|
||||
max-width: 980px;
|
||||
min-height: 100vh;
|
||||
margin: 0 auto;
|
||||
padding: 34px 42px 56px;
|
||||
background: #ffffff;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .reader {
|
||||
background: #20242c;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3,
|
||||
h4 {
|
||||
line-height: 1.32;
|
||||
color: #121722;
|
||||
margin: 1.35em 0 0.55em;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] h1,
|
||||
html[data-theme="dark"] h2,
|
||||
html[data-theme="dark"] h3,
|
||||
html[data-theme="dark"] h4 {
|
||||
color: #f4f7fb;
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin-top: 0;
|
||||
padding-bottom: 0.34em;
|
||||
border-bottom: 1px solid #d9dee7;
|
||||
font-size: 2.05em;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 1.48em;
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: 1.2em;
|
||||
}
|
||||
|
||||
p {
|
||||
margin: 0.74em 0;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #1769aa;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] a {
|
||||
color: #79b8ff;
|
||||
}
|
||||
|
||||
blockquote {
|
||||
margin: 1em 0;
|
||||
padding: 0.55em 1em;
|
||||
border-left: 4px solid #4f8cc9;
|
||||
background: #eef5fc;
|
||||
color: #344258;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] blockquote {
|
||||
background: #26313f;
|
||||
color: #d6deeb;
|
||||
}
|
||||
|
||||
.admonition {
|
||||
margin: 1em 0;
|
||||
padding: 0.72em 1em;
|
||||
border: 1px solid #cfe0f2;
|
||||
border-left: 5px solid #3b82c4;
|
||||
border-radius: 8px;
|
||||
background: #f0f7ff;
|
||||
color: #28384f;
|
||||
}
|
||||
|
||||
.admonition-title {
|
||||
display: block;
|
||||
margin: 0 0 0.38em;
|
||||
color: #17395f;
|
||||
font-weight: 750;
|
||||
}
|
||||
|
||||
.admonition-title + p,
|
||||
.admonition p:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.admonition-tip {
|
||||
border-color: #ccebd9;
|
||||
border-left-color: #2f9e63;
|
||||
background: #f0fff6;
|
||||
}
|
||||
|
||||
.admonition-warning,
|
||||
.admonition-caution {
|
||||
border-color: #f1d7a8;
|
||||
border-left-color: #d08700;
|
||||
background: #fff8e8;
|
||||
}
|
||||
|
||||
.admonition-important {
|
||||
border-color: #e0cef3;
|
||||
border-left-color: #8b5cf6;
|
||||
background: #f8f4ff;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .admonition {
|
||||
border-color: #344e68;
|
||||
border-left-color: #5aa5e8;
|
||||
background: #1e2b38;
|
||||
color: #dce8f4;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .admonition-title {
|
||||
color: #f0f7ff;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .admonition-tip {
|
||||
border-color: #294f39;
|
||||
border-left-color: #54c07d;
|
||||
background: #1d3026;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .admonition-warning,
|
||||
html[data-theme="dark"] .admonition-caution {
|
||||
border-color: #584725;
|
||||
border-left-color: #f0b849;
|
||||
background: #332b1b;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .admonition-important {
|
||||
border-color: #4a3b66;
|
||||
border-left-color: #ad8cff;
|
||||
background: #2c253b;
|
||||
}
|
||||
|
||||
.task-list {
|
||||
padding-left: 1.1em;
|
||||
}
|
||||
|
||||
.task-list-item {
|
||||
list-style: none;
|
||||
margin-left: -1.1em;
|
||||
}
|
||||
|
||||
.task-list-item-checkbox {
|
||||
width: 1em;
|
||||
height: 1em;
|
||||
margin: 0 0.42em 0 0;
|
||||
vertical-align: -0.12em;
|
||||
accent-color: #2f7ecb;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
margin: 1.2em 0;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.96em;
|
||||
}
|
||||
|
||||
.table-wrapper {
|
||||
margin: 1.2em 0;
|
||||
overflow-x: auto;
|
||||
border: 1px solid #d5dbe5;
|
||||
border-radius: 8px;
|
||||
background: #ffffff;
|
||||
}
|
||||
|
||||
.table-wrapper table {
|
||||
min-width: 640px;
|
||||
margin: 0;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.table-wrapper th:first-child,
|
||||
.table-wrapper td:first-child {
|
||||
border-left: 0;
|
||||
}
|
||||
|
||||
.table-wrapper th:last-child,
|
||||
.table-wrapper td:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
|
||||
.table-wrapper tr:first-child th,
|
||||
.table-wrapper tr:first-child td {
|
||||
border-top: 0;
|
||||
}
|
||||
|
||||
.table-wrapper tr:last-child th,
|
||||
.table-wrapper tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
|
||||
.table-tools {
|
||||
position: sticky;
|
||||
left: 0;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 0.45em;
|
||||
padding: 0.44em 0.52em;
|
||||
border-bottom: 1px solid #d5dbe5;
|
||||
background: #f7f9fc;
|
||||
}
|
||||
|
||||
.copy-table-button {
|
||||
padding: 0.25em 0.62em;
|
||||
border: 1px solid #c8d0dc;
|
||||
border-radius: 5px;
|
||||
background: #ffffff;
|
||||
color: #354052;
|
||||
font: 600 0.78em "Segoe UI", "Microsoft YaHei UI", sans-serif;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.copy-table-button:hover {
|
||||
background: #f0f4f8;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .table-wrapper {
|
||||
border-color: #3a4352;
|
||||
background: #20242c;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .table-tools {
|
||||
border-bottom-color: #3a4352;
|
||||
background: #242b36;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .copy-table-button {
|
||||
border-color: #445063;
|
||||
background: #2d3542;
|
||||
color: #edf2f7;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .copy-table-button:hover {
|
||||
background: #364151;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
border: 1px solid #d5dbe5;
|
||||
padding: 0.62em 0.76em;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
th {
|
||||
background: #edf1f6;
|
||||
font-weight: 650;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] th,
|
||||
html[data-theme="dark"] td {
|
||||
border-color: #3a4352;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] th {
|
||||
background: #2b3340;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: "Cascadia Mono", Consolas, "Courier New", monospace;
|
||||
}
|
||||
|
||||
p code,
|
||||
li code,
|
||||
td code {
|
||||
padding: 0.12em 0.32em;
|
||||
border-radius: 4px;
|
||||
background: #eef1f5;
|
||||
color: #9b2c2c;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] p code,
|
||||
html[data-theme="dark"] li code,
|
||||
html[data-theme="dark"] td code {
|
||||
background: #303745;
|
||||
color: #f2b8b5;
|
||||
}
|
||||
|
||||
.code-block {
|
||||
position: relative;
|
||||
margin: 1.2em 0;
|
||||
border: 1px solid #d8dee8;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
background: #f7f9fc;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .code-block {
|
||||
border-color: #384252;
|
||||
background: #171b22;
|
||||
}
|
||||
|
||||
.code-title {
|
||||
padding: 0.42em 0.76em;
|
||||
border-bottom: 1px solid #d8dee8;
|
||||
background: #edf1f6;
|
||||
color: #53606f;
|
||||
font-size: 0.82em;
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .code-title {
|
||||
border-bottom-color: #384252;
|
||||
background: #242b36;
|
||||
color: #b7c0cc;
|
||||
}
|
||||
|
||||
pre.highlight {
|
||||
margin: 0;
|
||||
padding: 1em;
|
||||
overflow-x: auto;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.code-line {
|
||||
display: inline-block;
|
||||
min-width: 100%;
|
||||
padding-left: 3.4em;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.code-line::before {
|
||||
content: attr(data-line);
|
||||
position: absolute;
|
||||
left: 0;
|
||||
width: 2.5em;
|
||||
color: #8a95a5;
|
||||
text-align: right;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .code-line::before {
|
||||
color: #748094;
|
||||
}
|
||||
|
||||
.code-block.is-collapsible.is-collapsed pre.highlight {
|
||||
max-height: 18.5em;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.code-block.is-collapsible.is-collapsed::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
height: 3.2em;
|
||||
pointer-events: none;
|
||||
background: linear-gradient(rgb(247 249 252 / 0), #f7f9fc);
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .code-block.is-collapsible.is-collapsed::after {
|
||||
background: linear-gradient(rgb(23 27 34 / 0), #171b22);
|
||||
}
|
||||
|
||||
.plain-file-view {
|
||||
margin: 1em 0;
|
||||
padding: 1em;
|
||||
overflow: auto;
|
||||
border: 1px solid #d8dee8;
|
||||
border-radius: 8px;
|
||||
background: #f7f9fc;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .plain-file-view {
|
||||
border-color: #384252;
|
||||
background: #171b22;
|
||||
}
|
||||
|
||||
.copy-code-button {
|
||||
position: absolute;
|
||||
top: 6px;
|
||||
right: 8px;
|
||||
padding: 0.24em 0.58em;
|
||||
border: 1px solid #c8d0dc;
|
||||
border-radius: 5px;
|
||||
background: #ffffff;
|
||||
color: #354052;
|
||||
font: 600 0.78em "Segoe UI", "Microsoft YaHei UI", sans-serif;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.toggle-code-button {
|
||||
position: absolute;
|
||||
top: 6px;
|
||||
right: 62px;
|
||||
z-index: 2;
|
||||
padding: 0.24em 0.58em;
|
||||
border: 1px solid #c8d0dc;
|
||||
border-radius: 5px;
|
||||
background: #ffffff;
|
||||
color: #354052;
|
||||
font: 600 0.78em "Segoe UI", "Microsoft YaHei UI", sans-serif;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.toggle-code-button:hover {
|
||||
background: #f0f4f8;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .toggle-code-button {
|
||||
border-color: #445063;
|
||||
background: #2d3542;
|
||||
color: #edf2f7;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .toggle-code-button:hover {
|
||||
background: #364151;
|
||||
}
|
||||
|
||||
.copy-code-button:hover {
|
||||
background: #f0f4f8;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .copy-code-button {
|
||||
border-color: #445063;
|
||||
background: #2d3542;
|
||||
color: #edf2f7;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .copy-code-button:hover {
|
||||
background: #364151;
|
||||
}
|
||||
|
||||
.pseudo-keyword {
|
||||
color: #7b3ff2;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
img {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
.reader img {
|
||||
cursor: zoom-in;
|
||||
}
|
||||
|
||||
.media-block {
|
||||
margin: 1.25em 0;
|
||||
}
|
||||
|
||||
.media-block img,
|
||||
.media-block video {
|
||||
display: block;
|
||||
width: min(100%, 880px);
|
||||
max-height: 70vh;
|
||||
object-fit: contain;
|
||||
border: 1px solid #d8dee8;
|
||||
border-radius: 8px;
|
||||
background: #0f1115;
|
||||
}
|
||||
|
||||
.media-audio audio {
|
||||
width: min(100%, 680px);
|
||||
}
|
||||
|
||||
.media-fallback {
|
||||
display: none;
|
||||
margin-top: 0.72em;
|
||||
padding: 0.7em 0.85em;
|
||||
border: 1px solid #d8dee8;
|
||||
border-radius: 8px;
|
||||
background: #f7f9fc;
|
||||
color: #3f4a5d;
|
||||
}
|
||||
|
||||
.media-fallback.is-visible {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.media-fallback a {
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .media-fallback {
|
||||
border-color: #384252;
|
||||
background: #242b36;
|
||||
color: #dce3ec;
|
||||
}
|
||||
|
||||
figcaption {
|
||||
margin-top: 0.45em;
|
||||
color: #697586;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] figcaption {
|
||||
color: #a9b4c4;
|
||||
}
|
||||
|
||||
hr {
|
||||
border: 0;
|
||||
border-top: 1px solid #d9dee7;
|
||||
margin: 2em 0;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] hr {
|
||||
border-top-color: #384252;
|
||||
}
|
||||
|
||||
.image-lightbox {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 1000;
|
||||
display: none;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 34px;
|
||||
background: rgb(12 15 20 / 88%);
|
||||
}
|
||||
|
||||
.image-lightbox.is-open {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.image-lightbox__toolbar {
|
||||
position: fixed;
|
||||
top: 18px;
|
||||
left: 50%;
|
||||
z-index: 1001;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
transform: translateX(-50%);
|
||||
}
|
||||
|
||||
.image-lightbox__toolbar button {
|
||||
min-width: 36px;
|
||||
height: 34px;
|
||||
padding: 0 10px;
|
||||
border: 1px solid rgb(255 255 255 / 22%);
|
||||
border-radius: 6px;
|
||||
background: rgb(24 28 36 / 92%);
|
||||
color: #f5f7fb;
|
||||
font: 700 0.9em "Segoe UI", "Microsoft YaHei UI", sans-serif;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.image-lightbox__toolbar button:hover {
|
||||
background: rgb(48 56 70 / 96%);
|
||||
}
|
||||
|
||||
.image-lightbox img {
|
||||
max-width: 96vw;
|
||||
max-height: 92vh;
|
||||
object-fit: contain;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 20px 70px rgb(0 0 0 / 45%);
|
||||
cursor: grab;
|
||||
transition: transform 120ms ease-out;
|
||||
}
|
||||
|
||||
.image-lightbox__caption {
|
||||
position: fixed;
|
||||
left: 24px;
|
||||
right: 24px;
|
||||
bottom: 16px;
|
||||
color: #f5f7fb;
|
||||
font-size: 0.92em;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.reader {
|
||||
padding: 24px 20px 42px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
document.querySelectorAll("a[href]").forEach((link) => {
|
||||
link.addEventListener("mouseenter", () => {
|
||||
link.title = link.getAttribute("href") || "";
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll(".code-block").forEach((block) => {
|
||||
const code = block.querySelector("pre code");
|
||||
if (!code) {
|
||||
return;
|
||||
}
|
||||
|
||||
const rawText = code.innerText || code.textContent || "";
|
||||
const lines = rawText.replace(/\n$/, "").split("\n");
|
||||
if (lines.length > 1 && !code.dataset.lineNumbered) {
|
||||
code.dataset.lineNumbered = "true";
|
||||
const htmlLines = code.innerHTML.replace(/\n$/, "").split("\n");
|
||||
code.innerHTML = htmlLines
|
||||
.map((line, index) => `<span class="code-line" data-line="${index + 1}">${line || " "}</span>`)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
if (lines.length > 18) {
|
||||
block.classList.add("is-collapsible", "is-collapsed");
|
||||
const toggle = document.createElement("button");
|
||||
toggle.type = "button";
|
||||
toggle.className = "toggle-code-button";
|
||||
toggle.textContent = "展开";
|
||||
toggle.addEventListener("click", () => {
|
||||
const collapsed = block.classList.toggle("is-collapsed");
|
||||
toggle.textContent = collapsed ? "展开" : "收起";
|
||||
});
|
||||
block.appendChild(toggle);
|
||||
}
|
||||
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "copy-code-button";
|
||||
button.textContent = "复制";
|
||||
|
||||
button.addEventListener("click", async () => {
|
||||
const text = rawText;
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
button.textContent = "已复制";
|
||||
} catch (error) {
|
||||
const textarea = document.createElement("textarea");
|
||||
textarea.value = text;
|
||||
textarea.style.position = "fixed";
|
||||
textarea.style.left = "-9999px";
|
||||
document.body.appendChild(textarea);
|
||||
textarea.select();
|
||||
document.execCommand("copy");
|
||||
textarea.remove();
|
||||
button.textContent = "已复制";
|
||||
}
|
||||
window.setTimeout(() => {
|
||||
button.textContent = "复制";
|
||||
}, 1200);
|
||||
});
|
||||
|
||||
block.appendChild(button);
|
||||
});
|
||||
|
||||
document.querySelectorAll(".media-block audio, .media-block video").forEach((player) => {
|
||||
const figure = player.closest(".media-block");
|
||||
const source = figure?.dataset.mediaSrc || player.currentSrc || player.src || "";
|
||||
if (!figure || !source) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fallback = document.createElement("div");
|
||||
fallback.className = "media-fallback";
|
||||
fallback.innerHTML = `内置播放器无法播放此媒体。<a href="${source}">用系统播放器打开</a>`;
|
||||
figure.appendChild(fallback);
|
||||
|
||||
const showFallback = () => {
|
||||
fallback.classList.add("is-visible");
|
||||
};
|
||||
|
||||
player.addEventListener("error", showFallback);
|
||||
player.addEventListener("stalled", showFallback);
|
||||
player.addEventListener("emptied", showFallback);
|
||||
player.querySelectorAll("source").forEach((sourceElement) => {
|
||||
sourceElement.addEventListener("error", showFallback);
|
||||
});
|
||||
|
||||
window.setTimeout(() => {
|
||||
if (player.error || player.networkState === HTMLMediaElement.NETWORK_NO_SOURCE) {
|
||||
showFallback();
|
||||
}
|
||||
}, 700);
|
||||
});
|
||||
|
||||
const copyText = async (text) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} catch (error) {
|
||||
const textarea = document.createElement("textarea");
|
||||
textarea.value = text;
|
||||
textarea.style.position = "fixed";
|
||||
textarea.style.left = "-9999px";
|
||||
document.body.appendChild(textarea);
|
||||
textarea.select();
|
||||
document.execCommand("copy");
|
||||
textarea.remove();
|
||||
}
|
||||
};
|
||||
|
||||
document.querySelectorAll(".reader table").forEach((table) => {
|
||||
if (table.closest(".table-wrapper")) {
|
||||
return;
|
||||
}
|
||||
|
||||
const wrapper = document.createElement("div");
|
||||
wrapper.className = "table-wrapper";
|
||||
|
||||
const tools = document.createElement("div");
|
||||
tools.className = "table-tools";
|
||||
|
||||
const copyButton = document.createElement("button");
|
||||
copyButton.type = "button";
|
||||
copyButton.className = "copy-table-button";
|
||||
copyButton.textContent = "复制表格";
|
||||
|
||||
copyButton.addEventListener("click", async () => {
|
||||
const rows = [...table.querySelectorAll("tr")].map((row) =>
|
||||
[...row.querySelectorAll("th, td")]
|
||||
.map((cell) => (cell.innerText || cell.textContent || "").replace(/\s+/g, " ").trim())
|
||||
.join("\t")
|
||||
);
|
||||
await copyText(rows.join("\n"));
|
||||
copyButton.textContent = "已复制";
|
||||
window.setTimeout(() => {
|
||||
copyButton.textContent = "复制表格";
|
||||
}, 1200);
|
||||
});
|
||||
|
||||
tools.appendChild(copyButton);
|
||||
table.parentNode.insertBefore(wrapper, table);
|
||||
wrapper.appendChild(tools);
|
||||
wrapper.appendChild(table);
|
||||
});
|
||||
|
||||
const lightbox = document.createElement("div");
|
||||
lightbox.className = "image-lightbox";
|
||||
lightbox.innerHTML = `
|
||||
<div class="image-lightbox__toolbar">
|
||||
<button type="button" data-action="zoom-out" title="缩小">-</button>
|
||||
<button type="button" data-action="zoom-in" title="放大">+</button>
|
||||
<button type="button" data-action="rotate-left" title="向左旋转">↺</button>
|
||||
<button type="button" data-action="rotate-right" title="向右旋转">↻</button>
|
||||
<button type="button" data-action="reset" title="重置">1:1</button>
|
||||
<button type="button" data-action="close" title="关闭">×</button>
|
||||
</div>
|
||||
<img alt="">
|
||||
<div class="image-lightbox__caption"></div>
|
||||
`;
|
||||
document.body.appendChild(lightbox);
|
||||
|
||||
const preview = lightbox.querySelector("img");
|
||||
const caption = lightbox.querySelector(".image-lightbox__caption");
|
||||
const toolbar = lightbox.querySelector(".image-lightbox__toolbar");
|
||||
let scale = 1;
|
||||
let rotation = 0;
|
||||
|
||||
const updatePreviewTransform = () => {
|
||||
preview.style.transform = `scale(${scale}) rotate(${rotation}deg)`;
|
||||
};
|
||||
|
||||
const resetPreviewTransform = () => {
|
||||
scale = 1;
|
||||
rotation = 0;
|
||||
updatePreviewTransform();
|
||||
};
|
||||
|
||||
const closeLightbox = () => {
|
||||
lightbox.classList.remove("is-open");
|
||||
preview.removeAttribute("src");
|
||||
caption.textContent = "";
|
||||
resetPreviewTransform();
|
||||
};
|
||||
|
||||
document.querySelectorAll(".reader img").forEach((image) => {
|
||||
image.addEventListener("click", () => {
|
||||
preview.src = image.currentSrc || image.src;
|
||||
preview.alt = image.alt || "";
|
||||
caption.textContent = image.alt || image.title || "";
|
||||
resetPreviewTransform();
|
||||
lightbox.classList.add("is-open");
|
||||
});
|
||||
});
|
||||
|
||||
preview.addEventListener("click", (event) => {
|
||||
event.stopPropagation();
|
||||
});
|
||||
|
||||
preview.addEventListener("wheel", (event) => {
|
||||
event.preventDefault();
|
||||
scale = Math.max(0.25, Math.min(5, scale + (event.deltaY < 0 ? 0.12 : -0.12)));
|
||||
updatePreviewTransform();
|
||||
});
|
||||
|
||||
toolbar.addEventListener("click", (event) => {
|
||||
event.stopPropagation();
|
||||
const action = event.target?.dataset?.action;
|
||||
if (action === "zoom-in") {
|
||||
scale = Math.min(5, scale + 0.2);
|
||||
} else if (action === "zoom-out") {
|
||||
scale = Math.max(0.25, scale - 0.2);
|
||||
} else if (action === "rotate-left") {
|
||||
rotation -= 90;
|
||||
} else if (action === "rotate-right") {
|
||||
rotation += 90;
|
||||
} else if (action === "reset") {
|
||||
resetPreviewTransform();
|
||||
return;
|
||||
} else if (action === "close") {
|
||||
closeLightbox();
|
||||
return;
|
||||
}
|
||||
updatePreviewTransform();
|
||||
});
|
||||
|
||||
lightbox.addEventListener("click", closeLightbox);
|
||||
document.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Escape") {
|
||||
closeLightbox();
|
||||
} else if (lightbox.classList.contains("is-open") && (event.key === "+" || event.key === "=")) {
|
||||
scale = Math.min(5, scale + 0.2);
|
||||
updatePreviewTransform();
|
||||
} else if (lightbox.classList.contains("is-open") && event.key === "-") {
|
||||
scale = Math.max(0.25, scale - 0.2);
|
||||
updatePreviewTransform();
|
||||
} else if (lightbox.classList.contains("is-open") && event.key === "0") {
|
||||
resetPreviewTransform();
|
||||
}
|
||||
});
|
||||
|
||||
const headingElements = [...document.querySelectorAll("h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]")];
|
||||
let bridge = null;
|
||||
let ticking = false;
|
||||
|
||||
const reportScroll = () => {
|
||||
ticking = false;
|
||||
const documentElement = document.documentElement;
|
||||
const maxScroll = Math.max(1, documentElement.scrollHeight - window.innerHeight);
|
||||
const progress = Math.max(0, Math.min(100, (window.scrollY / maxScroll) * 100));
|
||||
|
||||
let activeId = "";
|
||||
for (const heading of headingElements) {
|
||||
if (heading.getBoundingClientRect().top <= 96) {
|
||||
activeId = heading.id;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (bridge && bridge.reportScroll) {
|
||||
bridge.reportScroll(progress, activeId);
|
||||
}
|
||||
};
|
||||
|
||||
const scheduleReport = () => {
|
||||
if (!ticking) {
|
||||
ticking = true;
|
||||
window.requestAnimationFrame(reportScroll);
|
||||
}
|
||||
};
|
||||
|
||||
if (window.qt && window.qt.webChannelTransport) {
|
||||
new QWebChannel(window.qt.webChannelTransport, (channel) => {
|
||||
bridge = channel.objects.mdhelperBridge;
|
||||
reportScroll();
|
||||
});
|
||||
}
|
||||
|
||||
window.addEventListener("scroll", scheduleReport, { passive: true });
|
||||
window.addEventListener("resize", scheduleReport);
|
||||
reportScroll();
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .document_tree import DocumentEntry
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SearchMatch:
|
||||
entry: DocumentEntry
|
||||
snippet: str
|
||||
|
||||
|
||||
class SearchIndex:
|
||||
def __init__(self, entries: list[DocumentEntry] | None = None) -> None:
|
||||
self._records: list[tuple[DocumentEntry, str]] = []
|
||||
if entries:
|
||||
self.rebuild(entries)
|
||||
|
||||
def rebuild(self, entries: list[DocumentEntry]) -> None:
|
||||
self._records = [(entry, self._haystack(entry)) for entry in entries]
|
||||
|
||||
def matches_entry(self, entry: DocumentEntry, query: str) -> bool:
|
||||
normalized = query.strip().casefold()
|
||||
if not normalized:
|
||||
return True
|
||||
|
||||
for indexed_entry, haystack in self._records:
|
||||
if indexed_entry.path == entry.path:
|
||||
return normalized in haystack.casefold()
|
||||
return normalized in self._haystack(entry).casefold()
|
||||
|
||||
def search(self, query: str, limit: int = 80) -> list[SearchMatch]:
|
||||
normalized = query.strip().casefold()
|
||||
if not normalized:
|
||||
return []
|
||||
|
||||
matches: list[SearchMatch] = []
|
||||
for entry, haystack in self._records:
|
||||
index = haystack.casefold().find(normalized)
|
||||
if index < 0:
|
||||
continue
|
||||
|
||||
matches.append(SearchMatch(entry=entry, snippet=_snippet(haystack, index, len(normalized))))
|
||||
if len(matches) >= limit:
|
||||
break
|
||||
return matches
|
||||
|
||||
def _haystack(self, entry: DocumentEntry) -> str:
|
||||
return f"{entry.title}\n{entry.relative_path}\n{_read_text(entry)}"
|
||||
|
||||
|
||||
def matches_entry(entry: DocumentEntry, query: str) -> bool:
|
||||
normalized = query.strip().casefold()
|
||||
if not normalized:
|
||||
return True
|
||||
haystack = f"{entry.title}\n{entry.relative_path}\n{_read_text(entry)}".casefold()
|
||||
return normalized in haystack
|
||||
|
||||
|
||||
def search_entries(entries: list[DocumentEntry], query: str, limit: int = 80) -> list[SearchMatch]:
|
||||
normalized = query.strip().casefold()
|
||||
if not normalized:
|
||||
return []
|
||||
|
||||
matches: list[SearchMatch] = []
|
||||
for entry in entries:
|
||||
text = _read_text(entry)
|
||||
haystack = f"{entry.title}\n{entry.relative_path}\n{text}"
|
||||
index = haystack.casefold().find(normalized)
|
||||
if index < 0:
|
||||
continue
|
||||
|
||||
matches.append(SearchMatch(entry=entry, snippet=_snippet(haystack, index, len(normalized))))
|
||||
if len(matches) >= limit:
|
||||
break
|
||||
return matches
|
||||
|
||||
|
||||
def _read_text(entry: DocumentEntry) -> str:
|
||||
try:
|
||||
return entry.path.read_text(encoding="utf-8")
|
||||
except OSError:
|
||||
return ""
|
||||
|
||||
|
||||
def _snippet(text: str, index: int, length: int) -> str:
|
||||
start = max(0, index - 42)
|
||||
end = min(len(text), index + length + 86)
|
||||
snippet = text[start:end].replace("\r", " ").replace("\n", " ")
|
||||
snippet = " ".join(snippet.split())
|
||||
if start > 0:
|
||||
snippet = "..." + snippet
|
||||
if end < len(text):
|
||||
snippet += "..."
|
||||
return snippet
|
||||
@@ -0,0 +1,71 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from PySide6.QtWidgets import (
|
||||
QCheckBox,
|
||||
QComboBox,
|
||||
QDialog,
|
||||
QDialogButtonBox,
|
||||
QDoubleSpinBox,
|
||||
QFormLayout,
|
||||
QVBoxLayout,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AppPreferences:
|
||||
theme: str
|
||||
font_scale: float
|
||||
auto_refresh: bool
|
||||
non_preview_action: str
|
||||
|
||||
|
||||
class SettingsDialog(QDialog):
|
||||
def __init__(self, preferences: AppPreferences, parent: object | None = None) -> None:
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("设置")
|
||||
self.setMinimumWidth(420)
|
||||
|
||||
self.theme_combo = QComboBox()
|
||||
self.theme_combo.addItem("浅色", "light")
|
||||
self.theme_combo.addItem("深色", "dark")
|
||||
self.theme_combo.setCurrentIndex(max(0, self.theme_combo.findData(preferences.theme)))
|
||||
|
||||
self.font_scale_spin = QDoubleSpinBox()
|
||||
self.font_scale_spin.setRange(0.8, 1.6)
|
||||
self.font_scale_spin.setSingleStep(0.1)
|
||||
self.font_scale_spin.setDecimals(1)
|
||||
self.font_scale_spin.setValue(preferences.font_scale)
|
||||
|
||||
self.auto_refresh_checkbox = QCheckBox("文件变化后自动刷新当前阅读页")
|
||||
self.auto_refresh_checkbox.setChecked(preferences.auto_refresh)
|
||||
|
||||
self.non_preview_combo = QComboBox()
|
||||
self.non_preview_combo.addItem("每次询问", "ask")
|
||||
self.non_preview_combo.addItem("直接用本地默认软件打开", "open")
|
||||
self.non_preview_combo.addItem("阻止打开,仅提示路径", "block")
|
||||
self.non_preview_combo.setCurrentIndex(max(0, self.non_preview_combo.findData(preferences.non_preview_action)))
|
||||
|
||||
form = QFormLayout()
|
||||
form.addRow("主题", self.theme_combo)
|
||||
form.addRow("正文字号倍率", self.font_scale_spin)
|
||||
form.addRow("自动刷新", self.auto_refresh_checkbox)
|
||||
form.addRow("其他本地文件", self.non_preview_combo)
|
||||
|
||||
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
|
||||
buttons.accepted.connect(self.accept)
|
||||
buttons.rejected.connect(self.reject)
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
layout.addLayout(form)
|
||||
layout.addWidget(buttons)
|
||||
|
||||
def preferences(self) -> AppPreferences:
|
||||
return AppPreferences(
|
||||
theme=str(self.theme_combo.currentData()),
|
||||
font_scale=float(self.font_scale_spin.value()),
|
||||
auto_refresh=self.auto_refresh_checkbox.isChecked(),
|
||||
non_preview_action=str(self.non_preview_combo.currentData()),
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user