// Mermaid diagrams in chat (```mermaid fences), like the original's own Mermaid-compatible // engine: pure Rust (mermaid-rs-renderer → SVG), drawn with resvg using AnyBot's fonts so // Chinese labels show. Flowcharts, sequence, class, state, ER, gantt, pie, mindmap, timeline… use std::sync::OnceLock; /// The original refuses diagrams over 50 000 characters. pub const MAX_SOURCE: usize = 50_000; fn fontdb() -> std::sync::Arc { static DB: OnceLock> = OnceLock::new(); DB.get_or_init(|| { let mut db = resvg::usvg::fontdb::Database::new(); db.load_font_data(crate::NOTO_TC.to_vec()); db.load_font_data(crate::NOTO_TC_BOLD.to_vec()); db.load_system_fonts(); // Every family the diagram asks for falls back to 思源黑體 (Latin and CJK, the app's own). let found: Option = db.faces().find(|f| f.families.iter().any(|(n, _)| n == "Noto Sans TC")).and_then(|f| f.families.first().map(|(n, _)| n.clone())); if let Some(name) = found { db.set_sans_serif_family(name.clone()); db.set_serif_family(name); } std::sync::Arc::new(db) }) .clone() } /// The house look for diagrams (same spirit as the chart cards, and the same six-colour /// series palette): quiet cards, thin grey connectors, no heavy borders — Mermaid's default /// blues are loud and read as "report software" next to the rest of the app. fn house_theme(dark: bool) -> mermaid_rs_renderer::Theme { let mut t = if dark { mermaid_rs_renderer::Theme::dark() } else { mermaid_rs_renderer::Theme::neutral() }; let (card, line, ink, faint, fill2, fill3, grid) = if dark { ("#252525", "#8a8a8a", "#f5f5f5", "#3a3a3a", "#2f3438", "#2b2d31", "#1f1f1f") } else { ("#ffffff", "#9b9a97", "#1c1c1c", "#e3e2df", "#f1f1ef", "#eff5fb", "#f7f7f5") }; t.primary_color = card.into(); t.primary_border_color = faint.into(); t.primary_text_color = ink.into(); t.line_color = line.into(); t.secondary_color = fill2.into(); t.tertiary_color = fill3.into(); t.edge_label_background = card.into(); t.cluster_background = grid.into(); t.cluster_border = faint.into(); t.background = if dark { "#1f1f1f".into() } else { "transparent".into() }; t.sequence_actor_fill = fill2.into(); t.sequence_actor_border = faint.into(); t.sequence_actor_line = line.into(); t.sequence_note_fill = if dark { "#3a3212".into() } else { "#fff8e1".into() }; t.sequence_note_border = faint.into(); t.sequence_activation_fill = fill3.into(); t.sequence_activation_border = if dark { "#529cca" } else { "#2383e2" }.into(); t.text_color = ink.into(); // Pie and git series: the house palette (theme.rs chart_cat), in order, then repeats lighter. let cat: [&str; 6] = if dark { ["#529cca", "#b493e5", "#4dab9a", "#e3a062", "#f291c0", "#a09e9a"] } else { ["#2383e2", "#9065b0", "#0f7b6c", "#d9730d", "#e06b9e", "#6e6c68"] }; t.pie_colors = std::array::from_fn(|i| cat[i % 6].to_string()); t.pie_stroke_color = card.into(); // Slices meet on thin seams in the card's colour; no heavy ring around the whole pie, and // its words on the app's type scale (title 16, labels and legend 13). t.pie_stroke_width = 2.0; t.pie_outer_stroke_width = 0.0; t.pie_outer_stroke_color = card.into(); t.pie_opacity = 1.0; t.pie_title_text_size = crate::theme::fs::READ; t.pie_section_text_size = crate::theme::fs::SMALL; t.pie_legend_text_size = crate::theme::fs::SMALL; t.pie_title_text_color = ink.into(); t.pie_section_text_color = ink.into(); t.pie_legend_text_color = ink.into(); t } /// Mermaid source → SVG text. pub fn svg(source: &str, dark: bool) -> Result { if source.len() > MAX_SOURCE { return Err("圖表太大".into()); } let mut opts = mermaid_rs_renderer::RenderOptions { theme: house_theme(dark), ..Default::default() }; opts.theme.font_family = "sans-serif".into(); // A panic inside the layout must not take the window down. let src = source.to_string(); std::panic::catch_unwind(move || mermaid_rs_renderer::render_strict(&src, opts).map_err(|e| e.to_string())) .map_err(|_| "圖表排版失敗".to_string())? } /// Mermaid source → RGBA pixels at `scale` (2.0 for sharp text on Retina). pub fn render(source: &str, dark: bool, scale: f32) -> Result { let svg = svg(source, dark)?; let opt = resvg::usvg::Options { fontdb: fontdb(), font_family: "sans-serif".into(), ..Default::default() }; let tree = resvg::usvg::Tree::from_str(&svg, &opt).map_err(|e| e.to_string())?; let size = tree.size(); let (w, h) = ((size.width() * scale).ceil().max(1.0) as u32, (size.height() * scale).ceil().max(1.0) as u32); if w as u64 * h as u64 > 40_000_000 { return Err("圖表太大".into()); } let mut pm = resvg::tiny_skia::Pixmap::new(w, h).ok_or("圖表太大")?; resvg::render(&tree, resvg::tiny_skia::Transform::from_scale(scale, scale), &mut pm.as_mut()); // tiny-skia is premultiplied; egui wants straight alpha. let mut px = pm.take(); for c in px.as_chunks_mut::<4>().0 { let a = c[3] as u32; if a > 0 && a < 255 { for v in &mut c[..3] { *v = ((*v as u32 * 255 + a / 2) / a).min(255) as u8; } } } image::RgbaImage::from_raw(w, h, px).ok_or_else(|| "圖表轉換失敗".into()) } #[cfg(test)] mod tests { use super::*; #[test] fn flowchart_and_errors() { let img = render("flowchart TD\n A[開始] --> B{要不要出門?}\n B -->|要| C[帶傘]\n B -->|不要| D[在家看書]\n C --> E[結束]\n D --> E", false, 1.0).unwrap(); assert!(img.width() > 100 && img.height() > 100); // Some ink in the picture (not all transparent). assert!(img.pixels().filter(|p| p.0[3] > 0).count() > 1000); if let Ok(out) = std::env::var("ANYBOT_DIAGRAM_OUT") { img.save(out).unwrap(); } assert!(render("this is not mermaid at all {{{", false, 1.0).is_err()); assert!(render(&"x".repeat(MAX_SOURCE + 1), false, 1.0).is_err()); } }