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