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