Improve MDHelper themes and packaging
This commit is contained in:
+25
-2
@@ -1,12 +1,14 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from . import __version__
|
||||
from .doc_check import main as check_documents_main
|
||||
from .logging_config import setup_logging
|
||||
from .main_window import MainWindow
|
||||
@@ -20,17 +22,38 @@ def parse_arguments(argv: list[str]) -> argparse.Namespace:
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def runtime_paths(project_root_arg: str | None = None) -> tuple[Path, Path]:
|
||||
if project_root_arg:
|
||||
root = Path(project_root_arg).resolve()
|
||||
return root, root
|
||||
|
||||
if getattr(sys, "frozen", False):
|
||||
content_root = Path(getattr(sys, "_MEIPASS")).resolve()
|
||||
log_root = Path(sys.executable).resolve().parent
|
||||
return content_root, log_root
|
||||
|
||||
root = Path(__file__).resolve().parent.parent
|
||||
return root, root
|
||||
|
||||
|
||||
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
|
||||
project_root, log_root = runtime_paths(args.project_root)
|
||||
if args.check:
|
||||
return check_documents_main([str(project_root)])
|
||||
|
||||
QApplication.setAttribute(Qt.ApplicationAttribute.AA_DontCreateNativeWidgetSiblings, True)
|
||||
setup_logging(project_root)
|
||||
setup_logging(log_root)
|
||||
logging.getLogger(__name__).info(
|
||||
"Starting MDHelper %s with project_root=%s log_root=%s",
|
||||
__version__,
|
||||
project_root,
|
||||
log_root,
|
||||
)
|
||||
|
||||
app = QApplication([sys.argv[0]])
|
||||
app.setApplicationName("MDHelper")
|
||||
app.setApplicationVersion(__version__)
|
||||
app.setOrganizationName("MDHelper")
|
||||
|
||||
initial_path = Path(args.file).expanduser().resolve() if args.file else None
|
||||
|
||||
+5
-1
@@ -8,6 +8,7 @@ from pathlib import Path
|
||||
class HistoryItem:
|
||||
path: Path
|
||||
fragment: str = ""
|
||||
scroll_y: int = 0
|
||||
|
||||
|
||||
class NavigationHistory:
|
||||
@@ -22,6 +23,10 @@ class NavigationHistory:
|
||||
self._items.append(item)
|
||||
self._index = len(self._items) - 1
|
||||
|
||||
def replace_current(self, item: HistoryItem) -> None:
|
||||
if 0 <= self._index < len(self._items):
|
||||
self._items[self._index] = item
|
||||
|
||||
@property
|
||||
def current(self) -> HistoryItem | None:
|
||||
if 0 <= self._index < len(self._items):
|
||||
@@ -47,4 +52,3 @@ class NavigationHistory:
|
||||
return None
|
||||
self._index += 1
|
||||
return self.current
|
||||
|
||||
|
||||
+1039
-41
File diff suppressed because it is too large
Load Diff
@@ -39,7 +39,15 @@ class MarkdownRenderer:
|
||||
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:
|
||||
def render_file(
|
||||
self,
|
||||
markdown_path: Path,
|
||||
theme: str = "light",
|
||||
font_scale: float = 1.0,
|
||||
document_font_family: str = "",
|
||||
document_font_size: int | None = None,
|
||||
math_engine: str = "katex",
|
||||
) -> str:
|
||||
source = markdown_path.read_text(encoding="utf-8")
|
||||
body = self.markdown.render(source, {"path": str(markdown_path)})
|
||||
return self._wrap_html(
|
||||
@@ -47,10 +55,30 @@ class MarkdownRenderer:
|
||||
title=markdown_path.name,
|
||||
theme=theme,
|
||||
font_scale=font_scale,
|
||||
document_font_family=document_font_family,
|
||||
document_font_size=document_font_size,
|
||||
math_engine=math_engine,
|
||||
)
|
||||
|
||||
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 wrap_body_for_display(
|
||||
self,
|
||||
body: str,
|
||||
title: str,
|
||||
theme: str = "light",
|
||||
font_scale: float = 1.0,
|
||||
document_font_family: str = "",
|
||||
document_font_size: int | None = None,
|
||||
math_engine: str = "katex",
|
||||
) -> str:
|
||||
return self._wrap_html(
|
||||
body=body,
|
||||
title=title,
|
||||
theme=theme,
|
||||
font_scale=font_scale,
|
||||
document_font_family=document_font_family,
|
||||
document_font_size=document_font_size,
|
||||
math_engine=math_engine,
|
||||
)
|
||||
|
||||
def _render_fence(
|
||||
self,
|
||||
@@ -61,6 +89,17 @@ class MarkdownRenderer:
|
||||
) -> str:
|
||||
token = tokens[idx]
|
||||
language = token.info.strip().split(maxsplit=1)[0] if token.info else ""
|
||||
normalized_language = language.lower()
|
||||
if normalized_language == "mermaid":
|
||||
return (
|
||||
'<div class="diagram-block">'
|
||||
'<div class="diagram-title">mermaid</div>'
|
||||
f'<pre class="mermaid">{html.escape(token.content)}</pre>'
|
||||
"</div>\n"
|
||||
)
|
||||
if normalized_language in {"math", "tex", "latex"}:
|
||||
return f'<div class="math-block">$$\n{html.escape(token.content)}\n$$</div>\n'
|
||||
|
||||
language_class = f" language-{html.escape(language)}" if language else ""
|
||||
code = self._highlight_code(token.content, language)
|
||||
label = html.escape(language or "text")
|
||||
@@ -148,8 +187,11 @@ class MarkdownRenderer:
|
||||
return self.markdown.renderer.renderToken(tokens, idx, options, env)
|
||||
|
||||
def _resolve_local_media_src(self, src: str, env: dict[str, Any]) -> str:
|
||||
if src.startswith("#"):
|
||||
return src
|
||||
|
||||
parsed = urlsplit(src)
|
||||
if parsed.scheme or parsed.path.startswith("#"):
|
||||
if parsed.scheme:
|
||||
return src
|
||||
|
||||
markdown_path_value = env.get("path")
|
||||
@@ -166,8 +208,11 @@ class MarkdownRenderer:
|
||||
return uri
|
||||
|
||||
def _resolve_local_href(self, href: str, env: dict[str, Any]) -> str:
|
||||
if href.startswith("#"):
|
||||
return href
|
||||
|
||||
parsed = urlsplit(href)
|
||||
if parsed.scheme or parsed.path.startswith("#"):
|
||||
if parsed.scheme:
|
||||
return href
|
||||
|
||||
markdown_path_value = env.get("path")
|
||||
@@ -351,31 +396,106 @@ class MarkdownRenderer:
|
||||
return token
|
||||
return None
|
||||
|
||||
def _wrap_html(self, body: str, title: str, theme: str, font_scale: float) -> str:
|
||||
def _wrap_html(
|
||||
self,
|
||||
body: str,
|
||||
title: str,
|
||||
theme: str,
|
||||
font_scale: float,
|
||||
document_font_family: str,
|
||||
document_font_size: int | None,
|
||||
math_engine: str,
|
||||
) -> str:
|
||||
css = (self.resources_dir / "reader.css").read_text(encoding="utf-8")
|
||||
js = (self.resources_dir / "reader.js").read_text(encoding="utf-8")
|
||||
math_assets = self._math_assets(math_engine)
|
||||
mermaid_script = self._script_tag(self._resource_uri("vendor/mermaid/mermaid.min.js"))
|
||||
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)
|
||||
escaped_math_engine = html.escape(self._normalized_math_engine(math_engine), quote=True)
|
||||
fallback_font_size = int(round(max(0.8, min(font_scale, 1.6)) * 16))
|
||||
font_size = max(12, min(int(document_font_size or fallback_font_size), 28))
|
||||
font_family = self._css_font_family(document_font_family)
|
||||
escaped_font_family = html.escape(font_family, quote=False)
|
||||
|
||||
return f"""<!doctype html>
|
||||
<html lang="zh-CN" data-theme="{escaped_theme}">
|
||||
<html lang="zh-CN" data-theme="{escaped_theme}" data-math-engine="{escaped_math_engine}">
|
||||
<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}%; }}
|
||||
:root {{
|
||||
--reader-font-family: {escaped_font_family};
|
||||
--reader-font-size: {font_size}px;
|
||||
}}
|
||||
{pygments_css}
|
||||
{css}
|
||||
</style>
|
||||
{math_assets["css"]}
|
||||
</head>
|
||||
<body>
|
||||
<main class="reader">
|
||||
{body}
|
||||
</main>
|
||||
<script src="qrc:///qtwebchannel/qwebchannel.js"></script>
|
||||
<script>{math_assets["config"]}</script>
|
||||
{math_assets["js"]}
|
||||
{mermaid_script}
|
||||
<script>{js}</script>
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
def _resource_uri(self, relative_path: str) -> str:
|
||||
path = self.resources_dir / relative_path
|
||||
if not path.exists():
|
||||
return ""
|
||||
return path.as_uri()
|
||||
|
||||
def _script_tag(self, uri: str) -> str:
|
||||
if not uri:
|
||||
return ""
|
||||
return f'<script src="{html.escape(uri, quote=True)}"></script>'
|
||||
|
||||
def _stylesheet_tag(self, uri: str) -> str:
|
||||
if not uri:
|
||||
return ""
|
||||
return f'<link rel="stylesheet" href="{html.escape(uri, quote=True)}">'
|
||||
|
||||
def _css_font_family(self, font_family: str) -> str:
|
||||
name = font_family.strip()
|
||||
if not name:
|
||||
return '"Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif'
|
||||
escaped_name = name.replace("\\", "\\\\").replace('"', '\\"')
|
||||
return f'"{escaped_name}", "Microsoft YaHei UI", Arial, sans-serif'
|
||||
|
||||
def _math_assets(self, math_engine: str) -> dict[str, str]:
|
||||
normalized = self._normalized_math_engine(math_engine)
|
||||
if normalized == "mathjax":
|
||||
config = (
|
||||
"window.MathJax = {"
|
||||
"tex: {inlineMath: [['$', '$'], ['\\\\(', '\\\\)']], "
|
||||
"displayMath: [['$$', '$$'], ['\\\\[', '\\\\]']], processEscapes: true},"
|
||||
"svg: {fontCache: 'none'}"
|
||||
"};"
|
||||
)
|
||||
return {
|
||||
"css": "",
|
||||
"config": config,
|
||||
"js": self._script_tag(self._resource_uri("vendor/mathjax/tex-svg-full.js")),
|
||||
}
|
||||
|
||||
return {
|
||||
"css": self._stylesheet_tag(self._resource_uri("vendor/katex/katex.min.css")),
|
||||
"config": "",
|
||||
"js": "\n".join(
|
||||
[
|
||||
self._script_tag(self._resource_uri("vendor/katex/katex.min.js")),
|
||||
self._script_tag(self._resource_uri("vendor/katex/auto-render.min.js")),
|
||||
]
|
||||
),
|
||||
}
|
||||
|
||||
def _normalized_math_engine(self, math_engine: str) -> str:
|
||||
return "mathjax" if str(math_engine).lower() == "mathjax" else "katex"
|
||||
|
||||
@@ -10,8 +10,8 @@ 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);
|
||||
font-family: var(--reader-font-family);
|
||||
font-size: var(--reader-font-size);
|
||||
line-height: 1.72;
|
||||
}
|
||||
|
||||
@@ -122,6 +122,12 @@ html[data-theme="dark"] blockquote {
|
||||
background: #f0fff6;
|
||||
}
|
||||
|
||||
.admonition-note {
|
||||
border-color: #cfe0f2;
|
||||
border-left-color: #3b82c4;
|
||||
background: #f0f7ff;
|
||||
}
|
||||
|
||||
.admonition-warning,
|
||||
.admonition-caution {
|
||||
border-color: #f1d7a8;
|
||||
@@ -152,6 +158,12 @@ html[data-theme="dark"] .admonition-tip {
|
||||
background: #1d3026;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .admonition-note {
|
||||
border-color: #344e68;
|
||||
border-left-color: #5aa5e8;
|
||||
background: #1e2b38;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .admonition-warning,
|
||||
html[data-theme="dark"] .admonition-caution {
|
||||
border-color: #584725;
|
||||
@@ -402,6 +414,62 @@ html[data-theme="dark"] .plain-file-view {
|
||||
background: #171b22;
|
||||
}
|
||||
|
||||
.diagram-block,
|
||||
.math-block {
|
||||
margin: 1.2em 0;
|
||||
border: 1px solid #d8dee8;
|
||||
border-radius: 8px;
|
||||
overflow: auto;
|
||||
background: #f7f9fc;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .diagram-block,
|
||||
html[data-theme="dark"] .math-block {
|
||||
border-color: #384252;
|
||||
background: #171b22;
|
||||
}
|
||||
|
||||
.diagram-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"] .diagram-title {
|
||||
border-bottom-color: #384252;
|
||||
background: #242b36;
|
||||
color: #b7c0cc;
|
||||
}
|
||||
|
||||
.mermaid,
|
||||
.math-block {
|
||||
padding: 1em;
|
||||
}
|
||||
|
||||
.diagram-missing-runtime::before {
|
||||
content: "Mermaid 本地资源未加载,下面显示原始图表代码。";
|
||||
display: block;
|
||||
margin-bottom: 0.75em;
|
||||
color: #9b2c2c;
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
.diagram-render-error::before {
|
||||
content: "Mermaid 图表渲染失败,下面显示原始图表代码。";
|
||||
display: block;
|
||||
margin-bottom: 0.75em;
|
||||
color: #9b2c2c;
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] .diagram-missing-runtime::before,
|
||||
html[data-theme="dark"] .diagram-render-error::before {
|
||||
color: #f2b8b5;
|
||||
}
|
||||
|
||||
.copy-code-button {
|
||||
position: absolute;
|
||||
top: 6px;
|
||||
@@ -555,7 +623,10 @@ html[data-theme="dark"] hr {
|
||||
left: 50%;
|
||||
z-index: 1001;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
max-width: min(92vw, 760px);
|
||||
transform: translateX(-50%);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,60 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
});
|
||||
});
|
||||
|
||||
const renderMermaidDiagrams = async () => {
|
||||
const diagrams = [...document.querySelectorAll(".mermaid")];
|
||||
if (!diagrams.length) {
|
||||
return;
|
||||
}
|
||||
if (!window.mermaid) {
|
||||
diagrams.forEach((diagram) => {
|
||||
diagram.classList.add("diagram-missing-runtime");
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const theme = document.documentElement.dataset.theme === "dark" ? "dark" : "default";
|
||||
window.mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
securityLevel: "loose",
|
||||
theme,
|
||||
});
|
||||
try {
|
||||
await window.mermaid.run({ nodes: diagrams });
|
||||
} catch (error) {
|
||||
diagrams.forEach((diagram) => {
|
||||
diagram.classList.add("diagram-render-error");
|
||||
diagram.title = String(error);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const renderMath = () => {
|
||||
const reader = document.querySelector(".reader");
|
||||
const engine = document.documentElement.dataset.mathEngine || "katex";
|
||||
if (!reader) {
|
||||
return;
|
||||
}
|
||||
if (engine === "mathjax" && window.MathJax && window.MathJax.typesetPromise) {
|
||||
window.MathJax.typesetPromise([reader]).catch(() => {});
|
||||
return;
|
||||
}
|
||||
if (engine === "katex" && window.renderMathInElement) {
|
||||
window.renderMathInElement(reader, {
|
||||
delimiters: [
|
||||
{ left: "$$", right: "$$", display: true },
|
||||
{ left: "\\[", right: "\\]", display: true },
|
||||
{ left: "\\(", right: "\\)", display: false },
|
||||
{ left: "$", right: "$", display: false },
|
||||
],
|
||||
throwOnError: false,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
renderMermaidDiagrams();
|
||||
renderMath();
|
||||
|
||||
document.querySelectorAll(".code-block").forEach((block) => {
|
||||
const code = block.querySelector("pre code");
|
||||
if (!code) {
|
||||
@@ -151,6 +205,10 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
<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="fit" title="适应窗口">适应</button>
|
||||
<button type="button" data-action="actual-size" title="原始大小">原始</button>
|
||||
<button type="button" data-action="save" title="保存图片">保存</button>
|
||||
<button type="button" data-action="reveal" title="在文件夹中显示">定位</button>
|
||||
<button type="button" data-action="reset" title="重置">1:1</button>
|
||||
<button type="button" data-action="close" title="关闭">×</button>
|
||||
</div>
|
||||
@@ -164,6 +222,7 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
const toolbar = lightbox.querySelector(".image-lightbox__toolbar");
|
||||
let scale = 1;
|
||||
let rotation = 0;
|
||||
let currentImageUrl = "";
|
||||
|
||||
const updatePreviewTransform = () => {
|
||||
preview.style.transform = `scale(${scale}) rotate(${rotation}deg)`;
|
||||
@@ -175,16 +234,30 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
updatePreviewTransform();
|
||||
};
|
||||
|
||||
const fitPreviewToWindow = () => {
|
||||
scale = 1;
|
||||
updatePreviewTransform();
|
||||
};
|
||||
|
||||
const showPreviewActualSize = () => {
|
||||
const renderedWidth = Math.max(1, preview.getBoundingClientRect().width);
|
||||
const naturalWidth = Math.max(1, preview.naturalWidth || renderedWidth);
|
||||
scale = Math.max(0.25, Math.min(5, naturalWidth / renderedWidth));
|
||||
updatePreviewTransform();
|
||||
};
|
||||
|
||||
const closeLightbox = () => {
|
||||
lightbox.classList.remove("is-open");
|
||||
preview.removeAttribute("src");
|
||||
currentImageUrl = "";
|
||||
caption.textContent = "";
|
||||
resetPreviewTransform();
|
||||
};
|
||||
|
||||
document.querySelectorAll(".reader img").forEach((image) => {
|
||||
image.addEventListener("click", () => {
|
||||
preview.src = image.currentSrc || image.src;
|
||||
currentImageUrl = image.currentSrc || image.src;
|
||||
preview.src = currentImageUrl;
|
||||
preview.alt = image.alt || "";
|
||||
caption.textContent = image.alt || image.title || "";
|
||||
resetPreviewTransform();
|
||||
@@ -213,6 +286,22 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
rotation -= 90;
|
||||
} else if (action === "rotate-right") {
|
||||
rotation += 90;
|
||||
} else if (action === "fit") {
|
||||
fitPreviewToWindow();
|
||||
return;
|
||||
} else if (action === "actual-size") {
|
||||
showPreviewActualSize();
|
||||
return;
|
||||
} else if (action === "save") {
|
||||
if (bridge && bridge.saveImage && currentImageUrl) {
|
||||
bridge.saveImage(currentImageUrl);
|
||||
}
|
||||
return;
|
||||
} else if (action === "reveal") {
|
||||
if (bridge && bridge.revealImage && currentImageUrl) {
|
||||
bridge.revealImage(currentImageUrl);
|
||||
}
|
||||
return;
|
||||
} else if (action === "reset") {
|
||||
resetPreviewTransform();
|
||||
return;
|
||||
@@ -258,7 +347,7 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
}
|
||||
|
||||
if (bridge && bridge.reportScroll) {
|
||||
bridge.reportScroll(progress, activeId);
|
||||
bridge.reportScroll(progress, activeId, Math.max(0, Math.round(window.scrollY || 0)));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
# Vendor Assets
|
||||
|
||||
These files are bundled so MDHelper can render diagrams and formulas without network access.
|
||||
|
||||
- Mermaid 10.9.1: `mermaid/mermaid.min.js`
|
||||
- KaTeX 0.16.9: `katex/katex.min.js`, `katex/auto-render.min.js`, `katex/katex.min.css`, `katex/fonts/*.woff2`
|
||||
- MathJax 3.2.2: `mathjax/tex-svg-full.js`
|
||||
@@ -0,0 +1 @@
|
||||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("katex")):"function"==typeof define&&define.amd?define(["katex"],t):"object"==typeof exports?exports.renderMathInElement=t(require("katex")):e.renderMathInElement=t(e.katex)}("undefined"!=typeof self?self:this,(function(e){return function(){"use strict";var t={771:function(t){t.exports=e}},r={};function n(e){var i=r[e];if(void 0!==i)return i.exports;var a=r[e]={exports:{}};return t[e](a,a.exports,n),a.exports}n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,{a:t}),t},n.d=function(e,t){for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)};var i={};return function(){n.d(i,{default:function(){return s}});var e=n(771),t=n.n(e),r=function(e,t,r){for(var n=r,i=0,a=e.length;n<t.length;){var o=t[n];if(i<=0&&t.slice(n,n+a)===e)return n;"\\"===o?n++:"{"===o?i++:"}"===o&&i--,n++}return-1},a=/^\\begin{/,o=function(e,t){for(var n,i=[],o=new RegExp("("+t.map((function(e){return e.left.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")})).join("|")+")");-1!==(n=e.search(o));){n>0&&(i.push({type:"text",data:e.slice(0,n)}),e=e.slice(n));var l=t.findIndex((function(t){return e.startsWith(t.left)}));if(-1===(n=r(t[l].right,e,t[l].left.length)))break;var d=e.slice(0,n+t[l].right.length),s=a.test(d)?d:e.slice(t[l].left.length,n);i.push({type:"math",data:s,rawData:d,display:t[l].display}),e=e.slice(n+t[l].right.length)}return""!==e&&i.push({type:"text",data:e}),i},l=function(e,r){var n=o(e,r.delimiters);if(1===n.length&&"text"===n[0].type)return null;for(var i=document.createDocumentFragment(),a=0;a<n.length;a++)if("text"===n[a].type)i.appendChild(document.createTextNode(n[a].data));else{var l=document.createElement("span"),d=n[a].data;r.displayMode=n[a].display;try{r.preProcess&&(d=r.preProcess(d)),t().render(d,l,r)}catch(e){if(!(e instanceof t().ParseError))throw e;r.errorCallback("KaTeX auto-render: Failed to parse `"+n[a].data+"` with ",e),i.appendChild(document.createTextNode(n[a].rawData));continue}i.appendChild(l)}return i},d=function e(t,r){for(var n=0;n<t.childNodes.length;n++){var i=t.childNodes[n];if(3===i.nodeType){for(var a=i.textContent,o=i.nextSibling,d=0;o&&o.nodeType===Node.TEXT_NODE;)a+=o.textContent,o=o.nextSibling,d++;var s=l(a,r);if(s){for(var f=0;f<d;f++)i.nextSibling.remove();n+=s.childNodes.length-1,t.replaceChild(s,i)}else n+=d}else 1===i.nodeType&&function(){var t=" "+i.className+" ";-1===r.ignoredTags.indexOf(i.nodeName.toLowerCase())&&r.ignoredClasses.every((function(e){return-1===t.indexOf(" "+e+" ")}))&&e(i,r)}()}},s=function(e,t){if(!e)throw new Error("No element provided to render");var r={};for(var n in t)t.hasOwnProperty(n)&&(r[n]=t[n]);r.delimiters=r.delimiters||[{left:"$$",right:"$$",display:!0},{left:"\\(",right:"\\)",display:!1},{left:"\\begin{equation}",right:"\\end{equation}",display:!0},{left:"\\begin{align}",right:"\\end{align}",display:!0},{left:"\\begin{alignat}",right:"\\end{alignat}",display:!0},{left:"\\begin{gather}",right:"\\end{gather}",display:!0},{left:"\\begin{CD}",right:"\\end{CD}",display:!0},{left:"\\[",right:"\\]",display:!0}],r.ignoredTags=r.ignoredTags||["script","noscript","style","textarea","pre","code","option"],r.ignoredClasses=r.ignoredClasses||[],r.errorCallback=r.errorCallback||console.error,r.macros=r.macros||{},d(e,r)}}(),i=i.default}()}));
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+2029
File diff suppressed because one or more lines are too long
+56
-14
@@ -9,26 +9,29 @@ from .document_tree import DocumentEntry
|
||||
class SearchMatch:
|
||||
entry: DocumentEntry
|
||||
snippet: str
|
||||
match_count: int = 0
|
||||
match_kind: str = "正文"
|
||||
|
||||
|
||||
class SearchIndex:
|
||||
def __init__(self, entries: list[DocumentEntry] | None = None) -> None:
|
||||
self._records: list[tuple[DocumentEntry, str]] = []
|
||||
self._records: list[tuple[DocumentEntry, str, str, str]] = []
|
||||
if entries:
|
||||
self.rebuild(entries)
|
||||
|
||||
def rebuild(self, entries: list[DocumentEntry]) -> None:
|
||||
self._records = [(entry, self._haystack(entry)) for entry in entries]
|
||||
self._records = [(entry, entry.title, entry.relative_path, _read_text(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:
|
||||
for indexed_entry, title, relative_path, body in self._records:
|
||||
if indexed_entry.path == entry.path:
|
||||
haystack = self._haystack(title, relative_path, body)
|
||||
return normalized in haystack.casefold()
|
||||
return normalized in self._haystack(entry).casefold()
|
||||
return normalized in self._haystack(entry.title, entry.relative_path, _read_text(entry)).casefold()
|
||||
|
||||
def search(self, query: str, limit: int = 80) -> list[SearchMatch]:
|
||||
normalized = query.strip().casefold()
|
||||
@@ -36,18 +39,26 @@ class SearchIndex:
|
||||
return []
|
||||
|
||||
matches: list[SearchMatch] = []
|
||||
for entry, haystack in self._records:
|
||||
index = haystack.casefold().find(normalized)
|
||||
if index < 0:
|
||||
for entry, title, relative_path, body in self._records:
|
||||
result = _match_details(title, relative_path, body, normalized)
|
||||
if result is None:
|
||||
continue
|
||||
|
||||
matches.append(SearchMatch(entry=entry, snippet=_snippet(haystack, index, len(normalized))))
|
||||
snippet, match_count, match_kind = result
|
||||
matches.append(
|
||||
SearchMatch(
|
||||
entry=entry,
|
||||
snippet=snippet,
|
||||
match_count=match_count,
|
||||
match_kind=match_kind,
|
||||
)
|
||||
)
|
||||
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 _haystack(self, title: str, relative_path: str, body: str) -> str:
|
||||
return f"{title}\n{relative_path}\n{body}"
|
||||
|
||||
|
||||
def matches_entry(entry: DocumentEntry, query: str) -> bool:
|
||||
@@ -66,12 +77,19 @@ def search_entries(entries: list[DocumentEntry], query: str, limit: int = 80) ->
|
||||
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:
|
||||
result = _match_details(entry.title, entry.relative_path, text, normalized)
|
||||
if result is None:
|
||||
continue
|
||||
|
||||
matches.append(SearchMatch(entry=entry, snippet=_snippet(haystack, index, len(normalized))))
|
||||
snippet, match_count, match_kind = result
|
||||
matches.append(
|
||||
SearchMatch(
|
||||
entry=entry,
|
||||
snippet=snippet,
|
||||
match_count=match_count,
|
||||
match_kind=match_kind,
|
||||
)
|
||||
)
|
||||
if len(matches) >= limit:
|
||||
break
|
||||
return matches
|
||||
@@ -94,3 +112,27 @@ def _snippet(text: str, index: int, length: int) -> str:
|
||||
if end < len(text):
|
||||
snippet += "..."
|
||||
return snippet
|
||||
|
||||
|
||||
def _match_details(title: str, relative_path: str, body: str, normalized_query: str) -> tuple[str, int, str] | None:
|
||||
fields = (
|
||||
("标题", title),
|
||||
("路径", relative_path),
|
||||
("正文", body),
|
||||
)
|
||||
total = sum(_count_matches(text, normalized_query) for _, text in fields)
|
||||
if total <= 0:
|
||||
return None
|
||||
|
||||
for kind, text in fields:
|
||||
index = text.casefold().find(normalized_query)
|
||||
if index >= 0:
|
||||
return _snippet(text, index, len(normalized_query)), total, kind
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _count_matches(text: str, normalized_query: str) -> int:
|
||||
if not normalized_query:
|
||||
return 0
|
||||
return text.casefold().count(normalized_query)
|
||||
|
||||
@@ -16,6 +16,8 @@ from PySide6.QtWidgets import (
|
||||
@dataclass(frozen=True)
|
||||
class AppPreferences:
|
||||
theme: str
|
||||
theme_color: str
|
||||
theme_background: str
|
||||
font_scale: float
|
||||
auto_refresh: bool
|
||||
non_preview_action: str
|
||||
@@ -27,10 +29,25 @@ class SettingsDialog(QDialog):
|
||||
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.theme_color_combo = QComboBox()
|
||||
self.theme_color_combo.addItem("白色", "white")
|
||||
self.theme_color_combo.addItem("黑色", "black")
|
||||
self.theme_color_combo.addItem("深灰色", "dark_gray")
|
||||
self.theme_color_combo.addItem("彩色", "colorful")
|
||||
self.theme_color_combo.setCurrentIndex(max(0, self.theme_color_combo.findData(preferences.theme_color)))
|
||||
|
||||
self.theme_background_combo = QComboBox()
|
||||
self.theme_background_combo.addItem("无", "none")
|
||||
self.theme_background_combo.addItem("春天", "spring")
|
||||
self.theme_background_combo.addItem("稻草", "straw")
|
||||
self.theme_background_combo.addItem("电路", "circuit")
|
||||
self.theme_background_combo.addItem("年轮", "tree_rings")
|
||||
self.theme_background_combo.addItem("几何图形", "geometry")
|
||||
self.theme_background_combo.addItem("书法", "calligraphy")
|
||||
self.theme_background_combo.addItem("水下", "underwater")
|
||||
self.theme_background_combo.setCurrentIndex(
|
||||
max(0, self.theme_background_combo.findData(preferences.theme_background))
|
||||
)
|
||||
|
||||
self.font_scale_spin = QDoubleSpinBox()
|
||||
self.font_scale_spin.setRange(0.8, 1.6)
|
||||
@@ -48,7 +65,8 @@ class SettingsDialog(QDialog):
|
||||
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.theme_color_combo)
|
||||
form.addRow("主题背景", self.theme_background_combo)
|
||||
form.addRow("正文字号倍率", self.font_scale_spin)
|
||||
form.addRow("自动刷新", self.auto_refresh_checkbox)
|
||||
form.addRow("其他本地文件", self.non_preview_combo)
|
||||
@@ -62,10 +80,12 @@ class SettingsDialog(QDialog):
|
||||
layout.addWidget(buttons)
|
||||
|
||||
def preferences(self) -> AppPreferences:
|
||||
theme_color = str(self.theme_color_combo.currentData())
|
||||
return AppPreferences(
|
||||
theme=str(self.theme_combo.currentData()),
|
||||
theme="dark" if theme_color in {"black", "dark_gray"} else "light",
|
||||
theme_color=theme_color,
|
||||
theme_background=str(self.theme_background_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