Skip to main content

nagisa_render/
theme.rs

1//! 主题与渲染配置。`RenderOptions` 是 `render_*` 的入参;`Theme` 是配色 / 字族 / 字号等
2//! 视觉口径,带亮 / 暗预设。所有尺寸是**逻辑值**,layout 前统一乘 `scale` 换设备像素。
3
4use std::collections::HashMap;
5
6use crate::build::ParaBuilder;
7use crate::font::FontHandle;
8use crate::model::{Align, Color, Inline, TextStyle};
9
10/// 四边内边距(逻辑像素)。
11#[derive(Clone, Copy, Debug)]
12pub struct Insets {
13    /// 上。
14    pub top: f32,
15    /// 右。
16    pub right: f32,
17    /// 下。
18    pub bottom: f32,
19    /// 左。
20    pub left: f32,
21}
22
23impl Insets {
24    /// 四边相等。
25    pub const fn all(v: f32) -> Self {
26        Self { top: v, right: v, bottom: v, left: v }
27    }
28    /// `v` = 上下,`h` = 左右。
29    pub const fn symmetric(v: f32, h: f32) -> Self {
30        Self { top: v, right: h, bottom: v, left: h }
31    }
32}
33
34/// 视觉主题:配色 + 字族 + 字号体系。预设见 [`Theme::light`] / [`Theme::dark`]。
35#[derive(Clone, Debug)]
36pub struct Theme {
37    /// 画布背景色。
38    pub background: Color,
39    /// 正文文字色。
40    pub text: Color,
41    /// 引用条 / 序号 / 链接等强调色。
42    pub accent: Color,
43    /// 图注 / 次要文字。
44    pub muted: Color,
45    /// 代码块 / 行内代码底色。
46    pub code_bg: Color,
47    /// 代码文字色。
48    pub code_text: Color,
49    /// `==高亮==` 的默认底色。
50    pub highlight: Color,
51    /// 表格 / 网格的边框线色(比 `muted` 更淡)。
52    pub border: Color,
53    /// 无衬线字族名。
54    pub font_sans: String,
55    /// 衬线字族名。
56    pub font_serif: String,
57    /// 等宽字族名。
58    pub font_mono: String,
59    /// 楷体字族名。
60    pub font_kai: String,
61    /// 基准字号(逻辑像素)。
62    pub base_size: f32,
63    /// 行高倍率。
64    pub line_height: f32,
65    /// h1..h6 相对基准字号的倍率。
66    pub heading_scale: [f32; 6],
67}
68
69impl Theme {
70    /// 亮色预设。
71    pub fn light() -> Self {
72        Self {
73            background: Color::rgb(0xff, 0xff, 0xff),
74            text: Color::rgb(0x1f, 0x23, 0x28),
75            accent: Color::rgb(0x25, 0x63, 0xeb),
76            muted: Color::rgb(0x6e, 0x77, 0x81),
77            code_bg: Color::rgb(0xf3, 0xf4, 0xf6),
78            code_text: Color::rgb(0x1f, 0x23, 0x28),
79            highlight: Color::rgb(0xff, 0xf1, 0xa8),
80            border: Color::rgb(0xe5, 0xe7, 0xeb),
81            ..Self::common()
82        }
83    }
84
85    /// 暗色预设。
86    pub fn dark() -> Self {
87        Self {
88            background: Color::rgb(0x0d, 0x11, 0x17),
89            text: Color::rgb(0xe6, 0xed, 0xf3),
90            accent: Color::rgb(0x58, 0xa6, 0xff),
91            muted: Color::rgb(0x8b, 0x94, 0x9e),
92            code_bg: Color::rgb(0x16, 0x1b, 0x22),
93            code_text: Color::rgb(0xe6, 0xed, 0xf3),
94            highlight: Color::rgb(0x57, 0x4a, 0x1a),
95            border: Color::rgb(0x30, 0x36, 0x3d),
96            ..Self::common()
97        }
98    }
99
100    /// 亮 / 暗共享的非配色部分(字族 / 字号 / 行高 / 标题阶梯)。字族名对应内置字体。
101    fn common() -> Self {
102        Self {
103            background: Color::rgb(0, 0, 0),
104            text: Color::rgb(0, 0, 0),
105            accent: Color::rgb(0, 0, 0),
106            muted: Color::rgb(0, 0, 0),
107            code_bg: Color::rgb(0, 0, 0),
108            code_text: Color::rgb(0, 0, 0),
109            highlight: Color::rgb(0, 0, 0),
110            border: Color::rgb(0, 0, 0),
111            font_sans: "Noto Sans SC".to_string(), // 内置
112            font_serif: "Noto Serif SC".to_string(), // 内置(思源宋体)
113            font_mono: "JetBrains Mono".to_string(), // 内置(CJK 在等宽语境回退 Noto)
114            font_kai: "LXGW WenKai GB".to_string(),  // 内置(霞鹜文楷)
115            base_size: 30.0,
116            line_height: 1.5,
117            heading_scale: [2.0, 1.6, 1.35, 1.15, 1.0, 0.9],
118        }
119    }
120}
121
122impl Default for Theme {
123    fn default() -> Self {
124        Self::light()
125    }
126}
127
128/// 输出图片格式。文字图首选 `Webp`(最小 + 快);`Png` 通用兜底;`PngFast` 要 PNG 又要快。
129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
130pub enum OutputFormat {
131    /// PNG(无损,平衡压缩,默认——通用兼容)。
132    Png,
133    /// PNG(无损,快压缩:约 8 倍快、体积大 ~40%)。必须出 PNG 又要快时用。
134    PngFast,
135    /// WebP(无损;通常体积最小、速度也好)。文字图首选;画布单边 > 16383px(WebP 上限)时编码报错。
136    Webp,
137    /// WebP 优先,画布单边 > 16383px 时自动落 PNG。要 WebP 的体积、又不想为超长图单独处理报错时用
138    /// ——超限会**改格式**,显式选了才发生。
139    WebpOrPng,
140}
141
142/// 渲染入参。链式覆写;`default()` = 960 逻辑宽、亮色、scale 2、PNG、默认字体句柄。
143#[derive(Clone)]
144pub struct RenderOptions {
145    /// 逻辑内容宽(含左右内边距),默认 960。
146    pub width: f32,
147    /// 页边距(逻辑像素)。
148    pub padding: Insets,
149    /// 超采样系数(输出 = 逻辑尺寸 × scale),默认 2.0。越大越清晰也越慢 / 越大。
150    pub scale: f32,
151    /// 视觉主题。
152    pub theme: Theme,
153    /// 字体栈句柄。
154    pub fonts: FontHandle,
155    /// 输出格式,默认 PNG。
156    pub format: OutputFormat,
157    /// 标记文本里 `@名字` 图片 → 字节。
158    pub images: HashMap<String, Vec<u8>>,
159    /// 页眉条(可选):一行小字排在内容上方,与文档无关的固定标识(品牌 / 出处)。
160    pub header: Option<PageChrome>,
161    /// 页脚条(可选):一行小字排在内容下方,常放项目水印(如「abot · github.com/…」)。
162    pub footer: Option<PageChrome>,
163}
164
165/// 页眉 / 页脚条:一行小字(可富文本)+ 可选的与内容之间的细分割线。参与布局高度
166/// ([`measure_document`](crate::measure_document) 自然包含),不归文档内容管——同一品牌
167/// 标识配在 `RenderOptions` 上,所有出图统一带。
168#[derive(Clone, Debug)]
169pub struct PageChrome {
170    /// 行内内容(纯文字经 [`new`](Self::new),富文本经 [`rich`](Self::rich))。
171    pub inlines: Vec<Inline>,
172    /// 行尾内容(可选):与 `inlines` 同一行,右对齐——「左 logo 右署名」的分栏形态。
173    /// 设了它,`align` 只管 `inlines`(通常配左对齐)。
174    pub trailing: Option<Vec<Inline>>,
175    /// 水平对齐(`with_header` 默认左、`with_footer` 默认居中)。
176    pub align: Align,
177    /// 缺省文字色:未显式上色的 span 用它;`None` = 主题次要色(muted)。
178    pub color: Option<Color>,
179    /// 相对基准字号的倍率(默认 0.72)。
180    pub size: f32,
181    /// 与内容之间画一条细线(默认开;设了 `band` 自动不画)。
182    pub rule: bool,
183    /// 满幅色带(可选,仅页脚生效):整条画布宽的底色带贴住画布底,文字坐在带内——
184    /// 分享卡式的「底栏」。设色深时记得给 span 配亮色文字。
185    pub band: Option<Color>,
186}
187
188impl PageChrome {
189    /// 默认形态:次要色小字、带细线、左对齐。
190    pub fn new(text: impl Into<String>) -> Self {
191        Self::from_inlines(vec![Inline::Text { text: text.into(), style: TextStyle::default() }])
192    }
193
194    /// 富文本形态:闭包拼行内(粗细 / 色 / 字号倍率皆可,如品牌名加重、连接词浅色)。
195    /// `p.styled("abot", |s| { s.weight(600); })` 这类未显式上色的 span 仍按缺省色染。
196    pub fn rich<R>(f: impl FnOnce(&mut ParaBuilder) -> R) -> Self {
197        let mut pb = ParaBuilder::new();
198        let _ = f(&mut pb);
199        Self::from_inlines(pb.into_inlines())
200    }
201
202    fn from_inlines(inlines: Vec<Inline>) -> Self {
203        Self {
204            inlines,
205            trailing: None,
206            align: Align::Left,
207            color: None,
208            size: 0.72,
209            rule: true,
210            band: None,
211        }
212    }
213
214    /// 设行尾内容(右对齐,与主内容同一行):「左 logo 右署名」分栏。
215    pub fn trailing<R>(mut self, f: impl FnOnce(&mut ParaBuilder) -> R) -> Self {
216        let mut pb = ParaBuilder::new();
217        let _ = f(&mut pb);
218        self.trailing = Some(pb.into_inlines());
219        self
220    }
221
222    /// 设满幅色带(十六进制;非法忽略)。仅页脚生效,自动不再画细线。
223    pub fn band(mut self, hex: &str) -> Self {
224        if let Some(c) = Color::hex(hex) {
225            self.band = Some(c);
226        }
227        self
228    }
229    /// 设对齐。
230    pub fn align(mut self, a: Align) -> Self {
231        self.align = a;
232        self
233    }
234    /// 设文字色(十六进制;非法忽略)。
235    pub fn color(mut self, hex: &str) -> Self {
236        if let Some(c) = Color::hex(hex) {
237            self.color = Some(c);
238        }
239        self
240    }
241    /// 设字号倍率(非法忽略)。
242    pub fn size(mut self, mult: f32) -> Self {
243        if mult.is_finite() && mult > 0.0 {
244            self.size = mult;
245        }
246        self
247    }
248    /// 不画细线。
249    pub fn no_rule(mut self) -> Self {
250        self.rule = false;
251        self
252    }
253}
254
255impl Default for RenderOptions {
256    fn default() -> Self {
257        Self {
258            width: 960.0,
259            padding: Insets::symmetric(32.0, 40.0),
260            scale: 2.0,
261            theme: Theme::light(),
262            fonts: FontHandle::shared_default(),
263            format: OutputFormat::Png,
264            images: HashMap::new(),
265            header: None,
266            footer: None,
267        }
268    }
269}
270
271impl RenderOptions {
272    /// 设逻辑内容宽。
273    pub fn with_width(mut self, w: f32) -> Self {
274        self.width = w;
275        self
276    }
277    /// 设页边距(逻辑像素)。
278    pub fn with_padding(mut self, p: Insets) -> Self {
279        self.padding = p;
280        self
281    }
282    /// 设主题。
283    pub fn with_theme(mut self, t: Theme) -> Self {
284        self.theme = t;
285        self
286    }
287    /// 设字体句柄。
288    pub fn with_fonts(mut self, f: FontHandle) -> Self {
289        self.fonts = f;
290        self
291    }
292    /// 设超采样系数(清晰度档位,见 `fast`/`sharp`/`ultra` 预设)。
293    pub fn with_scale(mut self, s: f32) -> Self {
294        self.scale = s.clamp(0.25, 8.0);
295        self
296    }
297    /// 清晰度预设:快(scale 1)——最省、体积小,清晰度一般。
298    pub fn fast(self) -> Self {
299        self.with_scale(1.0)
300    }
301    /// 清晰度预设:标准(scale 1.5)。
302    pub fn standard(self) -> Self {
303        self.with_scale(1.5)
304    }
305    /// 清晰度预设:清晰(scale 2,默认)。
306    pub fn sharp(self) -> Self {
307        self.with_scale(2.0)
308    }
309    /// 清晰度预设:超清(scale 3)——最清晰也最慢 / 最大。
310    pub fn ultra(self) -> Self {
311        self.with_scale(3.0)
312    }
313    /// 设页眉(默认形态:左对齐次要色小字 + 细线);要微调用 [`with_header_chrome`](Self::with_header_chrome)。
314    pub fn with_header(self, text: impl Into<String>) -> Self {
315        self.with_header_chrome(PageChrome::new(text))
316    }
317    /// 设页眉(完整形态)。
318    pub fn with_header_chrome(mut self, c: PageChrome) -> Self {
319        self.header = Some(c);
320        self
321    }
322    /// 设页脚(默认形态:居中次要色小字 + 细线,适合项目水印);微调用 [`with_footer_chrome`](Self::with_footer_chrome)。
323    pub fn with_footer(self, text: impl Into<String>) -> Self {
324        self.with_footer_chrome(PageChrome::new(text).align(Align::Center))
325    }
326    /// 设页脚(完整形态)。
327    pub fn with_footer_chrome(mut self, c: PageChrome) -> Self {
328        self.footer = Some(c);
329        self
330    }
331    /// 设输出格式。
332    pub fn with_format(mut self, f: OutputFormat) -> Self {
333        self.format = f;
334        self
335    }
336    /// 输出 PNG(无损,平衡压缩)。
337    pub fn png(self) -> Self {
338        self.with_format(OutputFormat::Png)
339    }
340    /// 输出 PNG(无损,快压缩——更快但更大)。
341    pub fn png_fast(self) -> Self {
342        self.with_format(OutputFormat::PngFast)
343    }
344    /// 输出 WebP(无损,文字图首选)。画布单边 > 16383px 时编码报错。
345    pub fn webp(self) -> Self {
346        self.with_format(OutputFormat::Webp)
347    }
348    /// 输出 WebP,但画布单边 > 16383px(WebP 上限)时自动落 PNG。
349    pub fn webp_or_png(self) -> Self {
350        self.with_format(OutputFormat::WebpOrPng)
351    }
352}