Repository navigation
Expand file tree
/
Copy pathrender_svg.rs
More file actions
4364 lines (4070 loc) · 150 KB
/
Copy pathrender_svg.rs
File metadata and controls
4364 lines (4070 loc) · 150 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Animated SVG renderer for [`Recording`].
//!
//! ## Why SVG?
//!
//! - Vector text: the rendered glyphs stay sharp at any zoom level and
//! are selectable / searchable in the browser.
//! - Tiny diff-friendly artifact: identical-to-previous frames are
//! skipped entirely; per-frame data is rectangles + text runs rather
//! than rasterised pixels.
//! - Plays in any browser (and on github.com when embedded as `<img>`)
//! via SMIL animations — no JS required.
//!
//! ## Animation model
//!
//! We use a **cell-based** animation model. Instead of showing/hiding
//! entire frame groups (which causes characters to flash briefly then
//! disappear), we track each cell position across frames and emit one
//! SVG element per "span" — the time interval during which a cell has
//! identical visual content (text, fg, bg, style). Each element uses a
//! `<set>` to be visible only for its span duration.
//!
//! A single dummy `<animate id="t">` provides a synchronised global
//! timer of `total_duration` seconds with `repeatCount="indefinite"`.
//! Each cell-span element references this timer so the animation loops.
//!
//! ## Style mapping
//!
//! - Cell background → `<rect fill="#rrggbb">` (only emitted when not
//! the canvas default).
//! - Cell text → `<text>`; runs of cells with identical
//! foreground/style are coalesced into a single `<text>` element.
//! - Bold / italic → `font-weight` / `font-style` attributes.
//! - Underline → a 1-pixel `<rect>` at the cell baseline.
//! - Inverse → the cell's bg/fg are swapped before emission.
//! - Cursor → an inverted-fill rect over the cell, sourced from
//! the recorded cursor position.
use std::{
fs::File,
io::Write,
path::{Path, PathBuf},
thread::{self, JoinHandle},
};
use flate2::Compression;
use flate2::write::GzEncoder;
use crate::render_common::{is_box_drawing, is_braille};
use anyhow::{Context, Result, anyhow};
use crossbeam_channel::{Receiver, Sender, bounded};
use crate::font::SvgFontEmbeddingPolicy;
use crate::font::load_font_family;
use ab_glyph::Font;
use base64::prelude::*;
use std::collections::{BTreeSet, HashMap};
use unicode_width::UnicodeWidthChar;
use crate::{
recording::{RawFrame, Recording, style_flags},
render_common::{RAW_FRAME_CONSUMER_CHANNEL_CAPACITY, ViewportConfig},
style::{rgb_hex, window_bar_dot_metrics},
};
fn generate_style_block(frames: &[RawFrame], opts: &SvgOptions) -> Result<String> {
let loaded = load_font_family(opts.font_path.as_deref())?;
if opts.no_system_fonts {
for frame in frames {
for cell in &frame.cells {
for c in cell.text.chars() {
if is_box_drawing(c) || is_braille(c) {
continue;
}
let (_, font) = loaded.font_set.select_for_char(cell.flags, c);
if font.glyph_id(c).0 == 0 {
return Err(anyhow::anyhow!(
"Glyph not found in embedded fonts for character '{}' (U+{:04X})",
c,
c as u32
));
}
}
}
}
}
if !opts.embed_fonts {
return Ok(String::new());
}
let mut style = String::new();
style.push_str("<style>\n");
let mut used_fonts: HashMap<usize, BTreeSet<char>> = HashMap::new();
// Check which fonts are actually selected/used by cells.
for frame in frames {
for cell in &frame.cells {
for c in cell.text.chars() {
if is_box_drawing(c) || is_braille(c) {
continue;
}
let (idx, _) = loaded.font_set.select_for_char(cell.flags, c);
used_fonts.entry(idx).or_default().insert(c);
}
}
}
if used_fonts.is_empty() {
return Ok(String::new());
}
// Embed the used fonts.
let mut sorted_indices: Vec<_> = used_fonts.keys().copied().collect();
sorted_indices.sort();
for idx in sorted_indices {
if idx >= loaded.font_set.fonts.len() {
continue;
}
let info = &loaded.font_set.fonts[idx];
let chars = &used_fonts[&idx];
if chars.is_empty() {
continue;
}
let mut embed_comment = None;
let (font_bytes, format_str, mime_type) = match info.svg_embedding_policy() {
Ok(SvgFontEmbeddingPolicy::AllowSubsetting) => match info.subset(chars) {
Ok(subset) => (subset, "woff2", "font/woff2"),
Err(err) => {
tracing::warn!(
"failed to subset font '{}' ({} chars), embedding the entire font: {:?}",
info.family_name,
chars.len(),
err
);
embed_comment = Some(format!(
"/* Font subsetting failed for '{}'; embedding the full font data in this SVG. */\n",
info.family_name
));
if let Some(ref woff2) = info.woff2_bytes {
(woff2.clone(), "woff2", "font/woff2")
} else {
let is_otf = info.get_ttf_bytes().starts_with(b"OTTO");
let (fmt, mime) = if is_otf {
("opentype", "font/opentype")
} else {
("truetype", "font/truetype")
};
(info.get_ttf_bytes().to_vec(), fmt, mime)
}
}
},
Ok(SvgFontEmbeddingPolicy::EmbedFullFont { reason }) => {
embed_comment = Some(format!("/* {} */\n", reason));
if let Some(ref woff2) = info.woff2_bytes {
(woff2.clone(), "woff2", "font/woff2")
} else {
let is_otf = info.get_ttf_bytes().starts_with(b"OTTO");
let (fmt, mime) = if is_otf {
("opentype", "font/opentype")
} else {
("truetype", "font/truetype")
};
(info.get_ttf_bytes().to_vec(), fmt, mime)
}
}
Ok(SvgFontEmbeddingPolicy::OmitFont { reason }) => {
style.push_str(&format!("/* {} */\n", reason));
continue;
}
Err(err) => {
tracing::warn!(
"failed to inspect font permissions for '{}' ({} chars), embedding the entire font: {:?}",
info.family_name,
chars.len(),
err
);
embed_comment = Some(format!(
"/* Font permission check failed for '{}'; embedding the full font data in this SVG. */\n",
info.family_name
));
if let Some(ref woff2) = info.woff2_bytes {
(woff2.clone(), "woff2", "font/woff2")
} else {
let is_otf = info.get_ttf_bytes().starts_with(b"OTTO");
let (fmt, mime) = if is_otf {
("opentype", "font/opentype")
} else {
("truetype", "font/truetype")
};
(info.get_ttf_bytes().to_vec(), fmt, mime)
}
}
};
let encoded = BASE64_STANDARD.encode(font_bytes);
let src = format!("url(data:{mime_type};base64,{encoded})");
if let Some(comment) = embed_comment {
style.push_str(&comment);
}
let css_template = format!(
"@font-face {{ font-family: '{}'; src: {} format('{}'); font-weight: {}; font-style: {}; }}\n",
info.family_name, src, format_str, info.weight, info.style
);
style.push_str(&css_template);
}
style.push_str("</style>\n");
Ok(style)
}
/// Tunables for the SVG renderer.
#[derive(Debug, Clone)]
pub struct SvgOptions {
/// Optional path to a custom TTF font file.
pub font_path: Option<String>,
/// CSS `font-family` value applied to every `<text>` element.
/// Defaults to a stack of common monospace families.
pub font_family: String,
/// `font-size` (CSS px) for the rendered glyphs. The recording's
/// `cell_width_px` / `cell_height_px` are *layout* metrics — we
/// honour them as cell sizes regardless, but `font_size` is what
/// actually controls glyph height in the browser.
pub font_size: f32,
/// Whether to embed base64-encoded subset font data in the SVG.
/// If false, relies entirely on system fonts.
pub embed_fonts: bool,
/// Whether to exclude system fonts from the font-family stack.
pub no_system_fonts: bool,
/// Whether this is a static screenshot (disables all animation/SMIL elements).
pub is_screenshot: bool,
pub window_bar_title: Option<String>,
pub window_bar_font_family: Option<String>,
pub window_bar_font_size: Option<f32>,
}
pub struct SvgStreamHandle {
pub tx: Sender<RawFrame>,
join: JoinHandle<Result<()>>,
}
impl SvgStreamHandle {
pub fn join(self) -> Result<()> {
drop(self.tx);
self.join.join().expect("svg stream worker panicked")
}
}
pub fn spawn_svg_stream(
cfg: ViewportConfig,
opts: SvgOptions,
output: PathBuf,
) -> Result<SvgStreamHandle> {
let _timer = crate::telemetry::ScopeTimer::new("spawn_svg_stream_setup");
let (tx, rx): (Sender<RawFrame>, Receiver<RawFrame>) =
bounded(RAW_FRAME_CONSUMER_CHANNEL_CAPACITY);
let join = thread::Builder::new()
.name("evp-svg-stream".into())
.spawn(move || run_svg_stream_worker(rx, cfg, opts, output))
.expect("failed to spawn svg stream worker");
Ok(SvgStreamHandle { tx, join })
}
impl Default for SvgOptions {
fn default() -> Self {
Self {
font_path: None,
font_family: "'JetBrainsMono Nerd Font Mono', 'Noto Sans Mono', 'Noto Emoji', 'Noto Sans Symbols 2', 'Noto Sans Mono CJK JP', 'unifont_upper', 'unifont_csur', ui-monospace, Menlo, Consolas, 'DejaVu Sans Mono', monospace".to_string(),
font_size: 16.0,
embed_fonts: true,
no_system_fonts: false,
is_screenshot: false,
window_bar_title: None,
window_bar_font_family: None,
window_bar_font_size: None,
}
}
}
/// Render `rec` as an animated SVG written to `out`.
pub fn render_svg(rec: &Recording, opts: &SvgOptions, out: &Path) -> Result<()> {
let stream = spawn_svg_stream(
ViewportConfig::new(
rec.cols,
rec.rows,
rec.framerate,
rec.cell_width_px,
rec.cell_height_px,
rec.frame_style,
rec.font_size_px,
rec.char_height_px,
rec.ascent_px,
rec.letter_spacing,
),
opts.clone(),
out.to_path_buf(),
)?;
for i in 0..rec.frames.len() {
let frame = rec
.reconstruct(i)
.ok_or_else(|| anyhow!("failed to reconstruct frame {i}"))?;
if stream.tx.send(frame).is_err() {
break;
}
}
stream.join()
}
/// Same as [`render_svg`] but returns the document as a `String` —
/// useful for tests and for callers embedding the SVG inline.
pub fn render_svg_to_string(rec: &Recording, opts: &SvgOptions) -> Result<String> {
let start_time = std::time::Instant::now();
let cfg = ViewportConfig::new(
rec.cols,
rec.rows,
rec.framerate,
rec.cell_width_px,
rec.cell_height_px,
rec.frame_style,
rec.font_size_px,
rec.char_height_px,
rec.ascent_px,
rec.letter_spacing,
);
// Reconstruct every frame up-front.
let mut frames: Vec<RawFrame> = Vec::with_capacity(rec.frames.len());
for i in 0..rec.frames.len() {
let f = rec
.reconstruct(i)
.ok_or_else(|| anyhow!("failed to reconstruct frame {i}"))?;
frames.push(f);
}
render_from_frames(&frames, cfg, opts, start_time)
}
/// Render a single [`RawFrame`] as a static SVG document returned as a `String`.
pub fn render_svg_frame_to_string(
frame: &RawFrame,
cfg: ViewportConfig,
opts: &SvgOptions,
) -> Result<String> {
let start_time = std::time::Instant::now();
render_from_frames(std::slice::from_ref(frame), cfg, opts, start_time)
}
// ---------------------------------------------------------------------------
// Core rendering logic shared by both paths
// ---------------------------------------------------------------------------
/// Visual state of a single cell, used for diffing across frames.
#[derive(Clone, PartialEq, Eq)]
struct CellVisual {
text: String,
fg: [u8; 3],
bg: [u8; 3],
flags: u8,
}
impl CellVisual {
fn from_snap(cell: &crate::recording::CellSnap) -> Self {
let (fg, bg) = effective_colors(cell);
Self {
text: cell.text.clone(),
fg,
bg,
flags: cell.flags,
}
}
fn is_blank(&self, default_bg: [u8; 3]) -> bool {
self.text.is_empty() && self.bg == default_bg
}
}
fn is_wide_char(ch: char) -> bool {
ch.width() == Some(2)
}
fn get_frame_visuals(frame: &RawFrame) -> Vec<CellVisual> {
let cols = frame.cols as usize;
let rows = frame.rows as usize;
let default_bg = frame.default_bg;
let mut visuals = Vec::with_capacity(frame.cells.len());
for r in 0..rows {
let mut last_active = None;
for c in (0..cols).rev() {
let idx = r * cols + c;
let cell = &frame.cells[idx];
if !cell.text.is_empty() || cell.bg != default_bg {
last_active = Some(c);
break;
}
}
for c in 0..cols {
let idx = r * cols + c;
let cell = &frame.cells[idx];
let mut visual = CellVisual::from_snap(cell);
let prev_is_wide = if c > 0 {
let prev_idx = r * cols + (c - 1);
let prev_cell = &frame.cells[prev_idx];
prev_cell
.text
.chars()
.next()
.map(is_wide_char)
.unwrap_or(false)
} else {
false
};
if visual.text.is_empty()
&& last_active.is_some()
&& c <= last_active.unwrap()
&& !prev_is_wide
{
visual.text = " ".to_string();
}
visuals.push(visual);
}
}
visuals
}
/// A time span during which a cell has a particular visual state.
#[derive(Clone)]
struct CellSpan {
row: u16,
col: u16,
start_ms: u32,
end_ms: u32,
visual: CellVisual,
default_bg: [u8; 3],
}
/// A time span during which the cursor is at a particular position.
struct CursorSpan {
col: u16,
row: u16,
start_ms: u32,
end_ms: u32,
color: [u8; 3],
}
#[derive(Clone)]
pub struct MouseSpan {
pub cx: f32,
pub cy: f32,
pub state: crate::recording::MouseState,
pub start_ms: u32,
pub end_ms: u32,
}
#[derive(Clone, Debug, PartialEq)]
pub struct StyleKeyframe {
pub start_ms: u32,
pub fg: [u8; 3],
pub bold: bool,
pub italic: bool,
pub underline: bool,
pub strikethrough: bool,
}
#[derive(Clone, Debug, PartialEq)]
pub enum AnimatedProperty {
Fg(Vec<(u32, [u8; 3])>),
FontWeight(Vec<(u32, bool)>),
FontStyle(Vec<(u32, bool)>),
TextDecoration(Vec<(u32, (bool, bool))>),
}
#[derive(Clone, Debug, PartialEq)]
pub struct StyleAnimation {
pub begin_ms: u32,
pub dur_ms: u32,
pub property: AnimatedProperty,
}
impl StyleAnimation {
fn to_svg_string(&self, color_classes: &HashMap<[u8; 3], String>, is_hidden: bool) -> String {
let (attr_name, values): (&str, Vec<String>) = match &self.property {
AnimatedProperty::Fg(keyframes) => {
let use_class = keyframes
.iter()
.all(|(_, color)| color_classes.contains_key(color));
if use_class {
let vals = keyframes
.iter()
.map(|(_, color)| color_classes.get(color).cloned().unwrap_or_default())
.collect();
("class", vals)
} else {
let vals = keyframes.iter().map(|(_, color)| rgb_hex(*color)).collect();
("fill", vals)
}
}
AnimatedProperty::FontWeight(keyframes) => {
let vals = keyframes
.iter()
.map(|(_, bold)| {
if *bold {
"bold".to_string()
} else {
"normal".to_string()
}
})
.collect();
("font-weight", vals)
}
AnimatedProperty::FontStyle(keyframes) => {
let vals = keyframes
.iter()
.map(|(_, italic)| {
if *italic {
"italic".to_string()
} else {
"normal".to_string()
}
})
.collect();
("font-style", vals)
}
AnimatedProperty::TextDecoration(keyframes) => {
let vals = keyframes
.iter()
.map(|(_, (u, s))| {
if *u && *s {
"underline line-through".to_string()
} else if *u {
"underline".to_string()
} else if *s {
"line-through".to_string()
} else {
"none".to_string()
}
})
.collect();
("text-decoration", vals)
}
};
let key_times_str = match &self.property {
AnimatedProperty::Fg(kf) => kf
.iter()
.map(|(t, _)| format_key_time((*t - self.begin_ms) as f32 / self.dur_ms as f32))
.collect::<Vec<_>>()
.join(";"),
AnimatedProperty::FontWeight(kf) => kf
.iter()
.map(|(t, _)| format_key_time((*t - self.begin_ms) as f32 / self.dur_ms as f32))
.collect::<Vec<_>>()
.join(";"),
AnimatedProperty::FontStyle(kf) => kf
.iter()
.map(|(t, _)| format_key_time((*t - self.begin_ms) as f32 / self.dur_ms as f32))
.collect::<Vec<_>>()
.join(";"),
AnimatedProperty::TextDecoration(kf) => kf
.iter()
.map(|(t, _)| format_key_time((*t - self.begin_ms) as f32 / self.dur_ms as f32))
.collect::<Vec<_>>()
.join(";"),
};
let values_str = values.join(";");
let fill_freeze = if is_hidden { "" } else { r#" fill="freeze""# };
format!(
r#"<animate attributeName="{attr}" calcMode="discrete" values="{values}" keyTimes="{key_times}" dur="{dur}" begin="{begin}"{freeze} />"#,
attr = attr_name,
values = values_str,
key_times = key_times_str,
dur = format_time(self.dur_ms),
begin = format_begin(self.begin_ms),
freeze = fill_freeze,
)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct TSpan {
pub x_coords: Vec<f32>,
pub text: String,
pub fg: [u8; 3],
pub bold: bool,
pub italic: bool,
pub underline: bool,
pub strikethrough: bool,
pub is_box: bool,
pub scale_y: f32,
pub cell_center_y_offset: f32,
pub char_center_y_offset: f32,
pub cell_w: u32,
pub cell_h: u32,
pub baseline: u32,
pub letter_spacing: f32,
pub start_ms: u32,
pub end_ms: u32,
pub style_animations: Vec<StyleAnimation>,
pub style_history: Vec<StyleKeyframe>,
}
impl TSpan {
fn to_svg_string(
&self,
color_classes: &HashMap<[u8; 3], String>,
parent_start_ms: u32,
parent_end_ms: u32,
total_ms: u32,
default_letter_spacing: f32,
default_fg: Option<[u8; 3]>,
make_transparent: bool,
) -> String {
let x_str = self
.x_coords
.iter()
.map(|x| {
let formatted = format!("{:.2}", x);
let mut trimmed = formatted.trim_end_matches('0');
if trimmed.ends_with('.') {
trimmed = &trimmed[..trimmed.len() - 1];
}
trimmed.to_string()
})
.collect::<Vec<_>>()
.join(" ");
let mut styles = Vec::new();
if (self.letter_spacing - default_letter_spacing).abs() >= 1e-5 {
styles.push(format!(
"letter-spacing: {}px",
format_seconds(self.letter_spacing)
));
}
if make_transparent {
styles.push("fill-opacity: 0".to_string());
}
let style = if styles.is_empty() {
String::new()
} else {
format!(r#" style="{}""#, styles.join("; "))
};
let is_tspan_static = is_static(self.start_ms, self.end_ms, total_ms);
let matches_parent = self.start_ms <= parent_start_ms && self.end_ms >= parent_end_ms;
let is_hidden = !is_tspan_static && !matches_parent;
let mut style_classes = Vec::new();
if self.bold {
style_classes.push("b");
}
if self.italic {
style_classes.push("i");
}
if self.underline && self.strikethrough {
style_classes.push("us");
} else if self.underline {
style_classes.push("u");
} else if self.strikethrough {
style_classes.push("s");
}
if is_hidden {
style_classes.push("h");
}
let mut fill_attr = String::new();
if let Some(cls) = color_classes.get(&self.fg) {
style_classes.push(cls);
} else if Some(self.fg) != default_fg {
fill_attr = format!(r#" fill="{}""#, rgb_hex(self.fg));
}
let class_attr = if !style_classes.is_empty() {
format!(r#" class="{}""#, style_classes.join(" "))
} else {
String::new()
};
let set_str = if is_hidden {
visibility_set(self.start_ms, self.end_ms, total_ms)
} else {
String::new()
};
let mut anim_str = String::new();
for anim in &self.style_animations {
anim_str.push_str(&anim.to_svg_string(color_classes, is_hidden));
}
format!(
r#"<tspan x="{x}"{fill}{cls}{s}>{set}{anim}{txt}</tspan>"#,
x = x_str,
fill = fill_attr,
cls = class_attr,
s = style,
set = set_str,
anim = anim_str,
txt = escape_text(&self.text),
)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct YAnimation {
pub begin_ms: u32,
pub segments: Vec<(u32, u32)>, // (y_value, start_ms_of_segment)
pub dur_ms: u32,
}
impl YAnimation {
fn to_svg_string(&self) -> String {
let values_str = self
.segments
.iter()
.map(|(y, _)| y.to_string())
.collect::<Vec<_>>()
.join(";");
let key_times_str = self
.segments
.iter()
.map(|(_, start)| format_key_time((start - self.begin_ms) as f32 / self.dur_ms as f32))
.collect::<Vec<_>>()
.join(";");
format!(
r#"<animate attributeName="y" calcMode="discrete" values="{values}" keyTimes="{key_times}" dur="{dur}" begin="{begin}" fill="freeze"/>"#,
values = values_str,
key_times = key_times_str,
dur = format_time(self.dur_ms),
begin = format_begin(self.begin_ms),
)
}
fn to_svg_transform_animation(&self, cell_x: f32, baseline: u32) -> String {
let values_str = self
.segments
.iter()
.map(|(y, _)| format!("{lx},{ly}", lx = cell_x, ly = *y as f32 - baseline as f32))
.collect::<Vec<_>>()
.join(";");
let key_times_str = self
.segments
.iter()
.map(|(_, start)| format_key_time((start - self.begin_ms) as f32 / self.dur_ms as f32))
.collect::<Vec<_>>()
.join(";");
format!(
r#"<animateTransform attributeName="transform" type="translate" calcMode="discrete" values="{values}" keyTimes="{key_times}" dur="{dur}" begin="{begin}" fill="freeze"/>"#,
values = values_str,
key_times = key_times_str,
dur = format_time(self.dur_ms),
begin = format_begin(self.begin_ms),
)
}
}
fn get_box_drawing_path(
ch: char,
cell_w: f32,
cell_h: f32,
lw: f32,
hw: f32,
d_off: f32,
r: f32,
) -> Option<String> {
let cx = cell_w / 2.0;
let cy = cell_h / 2.0;
let rx = cell_w;
let by = cell_h;
match ch {
// --- Single lines ---
'─' => Some(format!(
r#"<path d="M 0 {cy} H {rx}" fill="none" stroke-width="{lw}" stroke-linecap="butt"/>"#
)),
'━' => Some(format!(
r#"<path d="M 0 {cy} H {rx}" fill="none" stroke-width="{hw}" stroke-linecap="butt"/>"#
)),
'│' => Some(format!(
r#"<path d="M {cx} 0 V {by}" fill="none" stroke-width="{lw}" stroke-linecap="butt"/>"#
)),
'┃' => Some(format!(
r#"<path d="M {cx} 0 V {by}" fill="none" stroke-width="{hw}" stroke-linecap="butt"/>"#
)),
// --- Dashed lines ---
'┄' => Some(format!(
r#"<path d="M 0 {cy} H {rx}" fill="none" stroke-width="{lw}" stroke-dasharray="3,3" stroke-linecap="butt"/>"#
)),
'┅' => Some(format!(
r#"<path d="M 0 {cy} H {rx}" fill="none" stroke-width="{hw}" stroke-dasharray="3,3" stroke-linecap="butt"/>"#
)),
'┆' => Some(format!(
r#"<path d="M {cx} 0 V {by}" fill="none" stroke-width="{lw}" stroke-dasharray="3,3" stroke-linecap="butt"/>"#
)),
'┇' => Some(format!(
r#"<path d="M {cx} 0 V {by}" fill="none" stroke-width="{hw}" stroke-dasharray="3,3" stroke-linecap="butt"/>"#
)),
'┈' => Some(format!(
r#"<path d="M 0 {cy} H {rx}" fill="none" stroke-width="{lw}" stroke-dasharray="2,2" stroke-linecap="butt"/>"#
)),
'┉' => Some(format!(
r#"<path d="M 0 {cy} H {rx}" fill="none" stroke-width="{hw}" stroke-dasharray="2,2" stroke-linecap="butt"/>"#
)),
'┊' => Some(format!(
r#"<path d="M {cx} 0 V {by}" fill="none" stroke-width="{lw}" stroke-dasharray="2,2" stroke-linecap="butt"/>"#
)),
'┋' => Some(format!(
r#"<path d="M {cx} 0 V {by}" fill="none" stroke-width="{hw}" stroke-dasharray="2,2" stroke-linecap="butt"/>"#
)),
// --- Corners (Light) ---
'┌' => Some(format!(
r#"<path d="M {rx} {cy} H {cx} V {by}" fill="none" stroke-width="{lw}" stroke-linejoin="miter"/>"#
)),
'┐' => Some(format!(
r#"<path d="M 0 {cy} H {cx} V {by}" fill="none" stroke-width="{lw}" stroke-linejoin="miter"/>"#
)),
'└' => Some(format!(
r#"<path d="M {rx} {cy} H {cx} V 0" fill="none" stroke-width="{lw}" stroke-linejoin="miter"/>"#
)),
'┘' => Some(format!(
r#"<path d="M 0 {cy} H {cx} V 0" fill="none" stroke-width="{lw}" stroke-linejoin="miter"/>"#
)),
// --- Corners (Heavy) ---
'┏' => Some(format!(
r#"<path d="M {rx} {cy} H {cx} V {by}" fill="none" stroke-width="{hw}" stroke-linejoin="miter"/>"#
)),
'┓' => Some(format!(
r#"<path d="M 0 {cy} H {cx} V {by}" fill="none" stroke-width="{hw}" stroke-linejoin="miter"/>"#
)),
'┗' => Some(format!(
r#"<path d="M {rx} {cy} H {cx} V 0" fill="none" stroke-width="{hw}" stroke-linejoin="miter"/>"#
)),
'┛' => Some(format!(
r#"<path d="M 0 {cy} H {cx} V 0" fill="none" stroke-width="{hw}" stroke-linejoin="miter"/>"#
)),
// --- Corners (Mixed Down/Right) ---
'┍' => Some(format!(
r#"<path d="M {rx} {cy} H {cx}" fill="none" stroke-width="{hw}"/>
<path d="M {cx} {cy} V {by}" fill="none" stroke-width="{lw}"/>"#
)),
'┎' => Some(format!(
r#"<path d="M {rx} {cy} H {cx}" fill="none" stroke-width="{lw}"/>
<path d="M {cx} {cy} V {by}" fill="none" stroke-width="{hw}"/>"#
)),
// --- Corners (Mixed Down/Left) ---
'┑' => Some(format!(
r#"<path d="M 0 {cy} H {cx}" fill="none" stroke-width="{hw}"/>
<path d="M {cx} {cy} V {by}" fill="none" stroke-width="{lw}"/>"#
)),
'┒' => Some(format!(
r#"<path d="M 0 {cy} H {cx}" fill="none" stroke-width="{lw}"/>
<path d="M {cx} {cy} V {by}" fill="none" stroke-width="{hw}"/>"#
)),
// --- Corners (Mixed Up/Right) ---
'┕' => Some(format!(
r#"<path d="M {rx} {cy} H {cx}" fill="none" stroke-width="{hw}"/>
<path d="M {cx} {cy} V 0" fill="none" stroke-width="{lw}"/>"#
)),
'┖' => Some(format!(
r#"<path d="M {rx} {cy} H {cx}" fill="none" stroke-width="{lw}"/>
<path d="M {cx} {cy} V 0" fill="none" stroke-width="{hw}"/>"#
)),
// --- Corners (Mixed Up/Left) ---
'┙' => Some(format!(
r#"<path d="M 0 {cy} H {cx}" fill="none" stroke-width="{hw}"/>
<path d="M {cx} {cy} V 0" fill="none" stroke-width="{lw}"/>"#
)),
'┚' => Some(format!(
r#"<path d="M 0 {cy} H {cx}" fill="none" stroke-width="{lw}"/>
<path d="M {cx} {cy} V 0" fill="none" stroke-width="{hw}"/>"#
)),
// --- Rounded Corners ---
'╭' => Some(format!(
r#"<path d="M {rx} {cy} H {cx_r} Q {cx} {cy} {cx} {cy_r} V {by}" fill="none" stroke-width="{lw}" stroke-linejoin="round"/>"#,
cx_r = cx + r,
cy_r = cy + r
)),
'╮' => Some(format!(
r#"<path d="M 0 {cy} H {cx_r} Q {cx} {cy} {cx} {cy_r} V {by}" fill="none" stroke-width="{lw}" stroke-linejoin="round"/>"#,
cx_r = cx - r,
cy_r = cy + r
)),
'╯' => Some(format!(
r#"<path d="M 0 {cy} H {cx_r} Q {cx} {cy} {cx} {cy_r} V 0" fill="none" stroke-width="{lw}" stroke-linejoin="round"/>"#,
cx_r = cx - r,
cy_r = cy - r
)),
'╰' => Some(format!(
r#"<path d="M {rx} {cy} H {cx_r} Q {cx} {cy} {cx} {cy_r} V 0" fill="none" stroke-width="{lw}" stroke-linejoin="round"/>"#,
cx_r = cx + r,
cy_r = cy - r
)),
// --- Tees (Light) ---
'├' => Some(format!(
r#"<path d="M {cx} 0 V {by} M {cx} {cy} H {rx}" fill="none" stroke-width="{lw}"/>"#
)),
'┤' => Some(format!(
r#"<path d="M {cx} 0 V {by} M {cx} {cy} H 0" fill="none" stroke-width="{lw}"/>"#
)),
'┬' => Some(format!(
r#"<path d="M 0 {cy} H {rx} M {cx} {cy} V {by}" fill="none" stroke-width="{lw}"/>"#
)),
'┴' => Some(format!(
r#"<path d="M 0 {cy} H {rx} M {cx} {cy} V 0" fill="none" stroke-width="{lw}"/>"#
)),
'┼' => Some(format!(
r#"<path d="M 0 {cy} H {rx} M {cx} 0 V {by}" fill="none" stroke-width="{lw}"/>"#
)),
// --- Tees (Heavy) ---
'┣' => Some(format!(
r#"<path d="M {cx} 0 V {by} M {cx} {cy} H {rx}" fill="none" stroke-width="{hw}"/>"#
)),
'┫' => Some(format!(
r#"<path d="M {cx} 0 V {by} M {cx} {cy} H 0" fill="none" stroke-width="{hw}"/>"#
)),
'┳' => Some(format!(
r#"<path d="M 0 {cy} H {rx} M {cx} {cy} V {by}" fill="none" stroke-width="{hw}"/>"#
)),
'┻' => Some(format!(
r#"<path d="M 0 {cy} H {rx} M {cx} {cy} V 0" fill="none" stroke-width="{hw}"/>"#
)),
'╋' => Some(format!(
r#"<path d="M 0 {cy} H {rx} M {cx} 0 V {by}" fill="none" stroke-width="{hw}"/>"#
)),
// --- Mixed Tees (Light/Heavy/Vertical/Horizontal) ---
'┠' => Some(format!(
r#"<path d="M {cx} 0 V {by}" fill="none" stroke-width="{hw}"/>
<path d="M {cx} {cy} H {rx}" fill="none" stroke-width="{lw}"/>"#
)),
'┨' => Some(format!(
r#"<path d="M {cx} 0 V {by}" fill="none" stroke-width="{hw}"/>
<path d="M {cx} {cy} H 0" fill="none" stroke-width="{lw}"/>"#
)),
'┰' => Some(format!(
r#"<path d="M 0 {cy} H {rx}" fill="none" stroke-width="{hw}"/>
<path d="M {cx} {cy} V {by}" fill="none" stroke-width="{lw}"/>"#
)),
'┸' => Some(format!(
r#"<path d="M 0 {cy} H {rx}" fill="none" stroke-width="{hw}"/>
<path d="M {cx} {cy} V 0" fill="none" stroke-width="{lw}"/>"#
)),
'┝' => Some(format!(
r#"<path d="M {cx} 0 V {by}" fill="none" stroke-width="{lw}"/>
<path d="M {cx} {cy} H {rx}" fill="none" stroke-width="{hw}"/>"#
)),
'┥' => Some(format!(
r#"<path d="M {cx} 0 V {by}" fill="none" stroke-width="{lw}"/>
<path d="M {cx} {cy} H 0" fill="none" stroke-width="{hw}"/>"#
)),
'┯' => Some(format!(
r#"<path d="M 0 {cy} H {rx}" fill="none" stroke-width="{lw}"/>
<path d="M {cx} {cy} V {by}" fill="none" stroke-width="{hw}"/>"#
)),
'┷' => Some(format!(
r#"<path d="M 0 {cy} H {rx}" fill="none" stroke-width="{lw}"/>
<path d="M {cx} {cy} V 0" fill="none" stroke-width="{hw}"/>"#
)),
// --- Double lines ---
'═' => Some(format!(
r#"<path d="M 0 {y1} H {rx} M 0 {y2} H {rx}" fill="none" stroke-width="{lw}"/>"#,
y1 = cy - d_off,
y2 = cy + d_off,
)),
'║' => Some(format!(
r#"<path d="M {x1} 0 V {by} M {x2} 0 V {by}" fill="none" stroke-width="{lw}"/>"#,
x1 = cx - d_off,
x2 = cx + d_off,
)),
'╔' => Some(format!(
r#"<path d="M {rx} {y1} H {x1} V {by}" fill="none" stroke-width="{lw}"/>
<path d="M {rx} {y2} H {x2} V {by}" fill="none" stroke-width="{lw}"/>"#,
y1 = cy - d_off,
y2 = cy + d_off,
x1 = cx - d_off,
x2 = cx + d_off,
)),
'╗' => Some(format!(
r#"<path d="M 0 {y1} H {x2} V {by}" fill="none" stroke-width="{lw}"/>
<path d="M 0 {y2} H {x1} V {by}" fill="none" stroke-width="{lw}"/>"#,
y1 = cy - d_off,
y2 = cy + d_off,