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
//! Export-mode methods and helper functions for [`Console`]. The helper
//! functions (`html_escape`, `build_svg_chrome`, `build_svg_text`, etc.) were
//! split out of `console.rs` in v1.2 Phase 2. The `impl Console` export
//! methods (`export_text`, `export_html`, `export_html_with_theme`,
//! `export_html_opts`, `export_svg`, `export_svg_opts`) were relocated here in
//! v1.7.1 to mirror the pattern used by `console_render.rs` and
//! `console_capture.rs`. Callers are unchanged — the methods remain on
//! `Console` at the same public paths.
use std::borrow::Cow;
use std::fmt::Write as _;
use crate::cells::cell_len;
use crate::console::Console;
use crate::export_format::{
FontEmbedding, HtmlExportOptions, SvgExportOptions, CONSOLE_HTML_FORMAT, CONSOLE_SVG_FORMAT,
};
use crate::segment::Segment;
use crate::style::Style;
use crate::terminal_theme::{TerminalTheme, DEFAULT_TERMINAL_THEME, SVG_EXPORT_THEME};
// ---------------------------------------------------------------------------
// Helper functions
// ---------------------------------------------------------------------------
/// Escape HTML special characters.
pub(super) fn html_escape(s: &str) -> Cow<'_, str> {
if !s.contains(['&', '<', '>', '"']) {
return Cow::Borrowed(s);
}
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
_ => out.push(c),
}
}
Cow::Owned(out)
}
/// Find an existing CSS class for a style, or create a new one.
pub(super) fn find_or_insert_class(
cache: &mut Vec<(Style, String)>,
stylesheet: &mut String,
style: &Style,
css: &str,
) -> String {
for (cached_style, class_name) in cache.iter() {
if cached_style == style {
return class_name.clone();
}
}
let mut class_name = String::new();
write!(class_name, "r{}", cache.len() + 1).unwrap();
writeln!(stylesheet, ".{} {{ {} }}", class_name, css).unwrap();
cache.push((style.clone(), class_name.clone()));
class_name
}
/// Build the SVG chrome (window title bar and decorations).
pub(super) fn build_svg_chrome(
width: f64,
height: f64,
theme: &TerminalTheme,
title: &str,
unique_id: &str,
) -> String {
let bg = theme.background_color.hex();
let mut chrome = String::new();
// Background rectangle with rounded corners
writeln!(
chrome,
"<rect fill=\"{}\" stroke=\"rgba(255,255,255,0.35)\" stroke-width=\"1\" \
x=\"0\" y=\"0\" width=\"{}\" height=\"{}\" rx=\"8\"/>",
bg, width, height,
)
.unwrap();
// Window control dots
let dot_colors = ["#ff5f57", "#febc2e", "#28c840"];
for (i, color) in dot_colors.iter().enumerate() {
let cx = 16.0 + (i as f64) * 22.0;
writeln!(
chrome,
" <circle cx=\"{:.0}\" cy=\"18\" r=\"5\" fill=\"{}\"/>",
cx, color
)
.unwrap();
}
// Title text
if !title.is_empty() {
writeln!(
chrome,
" <text class=\"{}-title\" fill=\"{}\" x=\"{}\" y=\"23\" \
text-anchor=\"middle\">{}</text>",
unique_id,
theme.foreground_color.hex(),
width / 2.0,
svg_escape(title),
)
.unwrap();
}
chrome
}
/// Build the SVG text content from segments.
pub(super) fn build_svg_text(
buffer: &[Segment],
theme: &TerminalTheme,
unique_id: &str,
char_width: f64,
line_height: f64,
padding_top: f64,
padding_left: f64,
) -> (String, String, String, String) {
let mut matrix = String::new();
let mut backgrounds = String::new();
let mut styles = String::new();
let lines_defs = String::new();
let mut style_cache: Vec<(String, String)> = Vec::new();
let mut y = padding_top + line_height;
let mut x: f64;
let mut line_segments: Vec<Vec<(String, Option<Style>)>> = Vec::new();
// Split buffer into lines
let mut current_line: Vec<(String, Option<Style>)> = Vec::new();
for seg in buffer {
if seg.is_control() {
continue;
}
let parts: Vec<&str> = seg.text.split('\n').collect();
for (i, part) in parts.iter().enumerate() {
if !part.is_empty() {
current_line.push((part.to_string(), seg.style().cloned()));
}
if i + 1 < parts.len() {
line_segments.push(std::mem::take(&mut current_line));
}
}
}
if !current_line.is_empty() {
line_segments.push(current_line);
}
for line in &line_segments {
x = padding_left;
for (text, style) in line {
let escaped = svg_escape(text);
let text_width = cell_len(text) as f64 * char_width;
if let Some(ref style) = style {
// Background
if let Some(bgcolor) = style.bgcolor() {
let bg_triplet = bgcolor.get_truecolor(Some(theme), false);
writeln!(
backgrounds,
" <rect fill=\"{}\" x=\"{:.1}\" y=\"{:.1}\" \
width=\"{:.1}\" height=\"{:.1}\"/>",
bg_triplet.hex(),
x,
y - line_height + 3.0,
text_width,
line_height,
)
.unwrap();
}
// Foreground text with style class
let css = style.get_html_style(Some(theme));
if !css.is_empty() {
let class_name =
find_or_insert_svg_class(&mut style_cache, &mut styles, unique_id, &css);
writeln!(
matrix,
" <text class=\"{}\" x=\"{:.1}\" y=\"{:.1}\" \
textLength=\"{:.1}\">{}</text>",
class_name, x, y, text_width, escaped
)
.unwrap();
} else {
writeln!(
matrix,
" <text fill=\"{}\" x=\"{:.1}\" y=\"{:.1}\" \
textLength=\"{:.1}\">{}</text>",
theme.foreground_color.hex(),
x,
y,
text_width,
escaped
)
.unwrap();
}
} else {
writeln!(
matrix,
" <text fill=\"{}\" x=\"{:.1}\" y=\"{:.1}\" \
textLength=\"{:.1}\">{}</text>",
theme.foreground_color.hex(),
x,
y,
text_width,
escaped
)
.unwrap();
}
x += text_width;
}
y += line_height;
}
(matrix, backgrounds, styles, lines_defs)
}
/// Find or create an SVG style class.
pub(super) fn find_or_insert_svg_class(
cache: &mut Vec<(String, String)>,
styles: &mut String,
unique_id: &str,
css: &str,
) -> String {
for (cached_css, class_name) in cache.iter() {
if cached_css == css {
return class_name.clone();
}
}
let mut class_name = String::new();
write!(class_name, "{}-s{}", unique_id, cache.len() + 1).unwrap();
// Convert HTML CSS to SVG attributes
let svg_style = css_to_svg_style(css);
writeln!(styles, " .{} {{ {} }}", class_name, svg_style).unwrap();
cache.push((css.to_string(), class_name.clone()));
class_name
}
/// Convert CSS style properties to SVG-compatible style properties.
pub(super) fn css_to_svg_style(css: &str) -> String {
let mut result = String::new();
for part in css.split(';') {
let part = part.trim();
if part.is_empty() {
continue;
}
if let Some((key, value)) = part.split_once(':') {
let key = key.trim();
let value = value.trim();
let svg_key = match key {
"color" => Some("fill"),
"font-weight" => Some("font-weight"),
"font-style" => Some("font-style"),
"text-decoration" => Some("text-decoration"),
_ => None, // Skip background-color and other non-SVG properties
};
if let Some(svg_key) = svg_key {
if !result.is_empty() {
result.push_str("; ");
}
write!(result, "{}: {}", svg_key, value).unwrap();
}
}
}
result
}
/// Escape text for SVG content.
pub(super) fn svg_escape(s: &str) -> Cow<'_, str> {
if !s.contains(['&', '<', '>', '"', '\'']) {
return Cow::Borrowed(s);
}
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
_ => out.push(c),
}
}
Cow::Owned(out)
}
// ---------------------------------------------------------------------------
// Export methods on Console (relocated from console.rs in v1.7.1)
// ---------------------------------------------------------------------------
impl Console {
// -- Export (record mode) -----------------------------------------------
/// Export recorded output as plain or styled text.
///
/// Only works if `record` was enabled when the Console was created.
/// Pass `clear = true` to empty the record buffer after export.
/// Pass `styles = true` to include ANSI escape codes in the output.
///
/// # Examples
///
/// ```
/// use gilt::console::Console;
/// use gilt::text::Text;
/// use gilt::style::Style;
///
/// let mut console = Console::builder()
/// .width(80)
/// .no_color(true)
/// .record(true)
/// .markup(false)
/// .build();
/// let text = Text::new("Export me", Style::null());
/// console.print(&text);
/// let exported = console.export_text(false, false);
/// assert!(exported.contains("Export me"));
/// ```
pub fn export_text(&mut self, clear: bool, styles: bool) -> String {
let buffer = self.record_buffer.clone();
if clear {
self.record_buffer.clear();
}
if styles {
self.render_buffer(&buffer)
} else {
// Strip control segments and just concatenate text
let mut output = String::new();
for segment in &buffer {
if !segment.is_control() {
output.push_str(&segment.text);
}
}
output
}
}
/// Export recorded output as an HTML document.
///
/// Generates a complete HTML page with inline or class-based styles.
/// Requires `record` mode to be enabled.
///
/// # Examples
///
/// ```
/// use gilt::console::Console;
/// use gilt::text::Text;
/// use gilt::style::Style;
///
/// let mut console = Console::builder()
/// .width(80)
/// .record(true)
/// .markup(false)
/// .build();
/// let text = Text::styled("Red text", "red");
/// console.print(&text);
/// let html = console.export_html(None, false, true);
/// assert!(html.contains("<!DOCTYPE html>"));
/// assert!(html.contains("Red text"));
/// ```
pub fn export_html(
&mut self,
theme: Option<&TerminalTheme>,
clear: bool,
inline_styles: bool,
) -> String {
let theme = theme.unwrap_or(&DEFAULT_TERMINAL_THEME);
// Finding #9: iterate by reference; only copy out when clear is needed.
let buffer_ref: &[Segment];
let taken: Vec<Segment>;
if clear {
taken = std::mem::take(&mut self.record_buffer);
buffer_ref = &taken;
} else {
buffer_ref = &self.record_buffer;
}
// Finding #8: merge adjacent same-style segments before HTML iteration.
let simplified = Segment::simplify(buffer_ref);
let mut code = String::new();
let mut stylesheet = String::new();
let mut style_cache: Vec<(Style, String)> = Vec::new();
for segment in &simplified {
if segment.is_control() {
continue;
}
let escaped = html_escape(&segment.text);
if let Some(style) = segment.style() {
// Finding #7: wrap the text in <a href> when the style has a link.
let link_url = style.link().map(|s| s.to_string());
if style.is_null() && link_url.is_none() {
code.push_str(&escaped);
continue;
}
let css = style.get_html_style(Some(theme));
let inner: String;
if css.is_empty() {
inner = escaped.into_owned();
} else if inline_styles {
inner = format!("<span style=\"{}\">{}</span>", css, escaped);
} else {
// Use class-based styles
let class_name =
find_or_insert_class(&mut style_cache, &mut stylesheet, style, &css);
inner = format!("<span class=\"{}\">{}</span>", class_name, escaped);
}
// Wrap in <a href> if there is a link (finding #7).
if let Some(url) = link_url {
write!(code, "<a href=\"{}\">{}</a>", html_escape(&url), inner).unwrap();
} else {
code.push_str(&inner);
}
} else {
code.push_str(&escaped);
}
}
let fg = theme.foreground_color.hex();
let bg = theme.background_color.hex();
CONSOLE_HTML_FORMAT
.replace("{stylesheet}", &stylesheet)
.replace("{foreground}", &fg)
.replace("{background}", &bg)
.replace("{code}", &code)
}
/// Export recorded output as HTML using a named palette from [`ThemeRegistry`].
///
/// Convenience wrapper around [`export_html`](Self::export_html): looks up
/// `theme_name` in `ThemeRegistry` and passes the result. Equivalent to:
///
/// ```rust,ignore
/// let theme = ThemeRegistry::terminal_theme("dracula").unwrap();
/// console.export_html(Some(theme), clear, inline_styles);
/// ```
///
/// Returns the same HTML as `export_html` with `theme = None` (the default
/// terminal theme) when `theme_name` is not found.
///
/// # Examples
///
/// ```
/// use gilt::console::Console;
/// use gilt::text::Text;
/// use gilt::style::Style;
///
/// let mut console = Console::builder()
/// .width(80)
/// .record(true)
/// .force_terminal(true)
/// .markup(false)
/// .build();
/// let text = Text::styled("Dracula", "bold magenta");
/// console.print(&text);
/// let html = console.export_html_with_theme("dracula", false, true);
/// assert!(html.contains("<!DOCTYPE html>"));
/// // Background should come from the Dracula palette (#282a36)
/// assert!(html.contains("#282a36") || html.contains("1a2a36") || html.len() > 100);
/// ```
pub fn export_html_with_theme(
&mut self,
theme_name: &str,
clear: bool,
inline_styles: bool,
) -> String {
use crate::terminal_theme::ThemeRegistry;
let theme = ThemeRegistry::terminal_theme(theme_name);
self.export_html(theme, clear, inline_styles)
}
/// Export recorded output as an HTML document with full control via
/// [`HtmlExportOptions`].
///
/// This is the options-based API; [`export_html`](Self::export_html) and
/// [`export_html_with_theme`](Self::export_html_with_theme) delegate to
/// this method via the default theme.
///
/// # Examples
///
/// ```
/// use gilt::console::Console;
/// use gilt::export_format::HtmlExportOptions;
/// use gilt::text::Text;
/// use gilt::style::Style;
///
/// let mut console = Console::builder()
/// .width(80)
/// .record(true)
/// .markup(false)
/// .build();
/// console.print(&Text::styled("hello", "bold green"));
/// let opts = HtmlExportOptions::default()
/// .inline_styles(true)
/// .dark_mode(true)
/// .copy_button(true);
/// let html = console.export_html_opts(None, &opts);
/// assert!(html.contains("<!DOCTYPE html>"));
/// assert!(html.contains("hello"));
/// ```
pub fn export_html_opts(
&mut self,
theme: Option<&TerminalTheme>,
opts: &HtmlExportOptions,
) -> String {
let theme = theme.unwrap_or(&DEFAULT_TERMINAL_THEME);
// Optionally clear (same logic as export_html)
let buffer_ref: &[Segment];
let taken: Vec<Segment>;
if opts.clear {
taken = std::mem::take(&mut self.record_buffer);
buffer_ref = &taken;
} else {
buffer_ref = &self.record_buffer;
}
let simplified = Segment::simplify(buffer_ref);
let mut code = String::new();
let mut stylesheet = String::new();
let mut style_cache: Vec<(Style, String)> = Vec::new();
for segment in &simplified {
if segment.is_control() {
continue;
}
let escaped = html_escape(&segment.text);
if let Some(style) = segment.style() {
let link_url = style.link().map(|s| s.to_string());
if style.is_null() && link_url.is_none() {
code.push_str(&escaped);
continue;
}
let css = style.get_html_style(Some(theme));
let inner: String;
if css.is_empty() {
inner = escaped.into_owned();
} else if opts.inline_styles {
inner = format!("<span style=\"{}\">{}</span>", css, escaped);
} else {
let class_name =
find_or_insert_class(&mut style_cache, &mut stylesheet, style, &css);
inner = format!("<span class=\"{}\">{}</span>", class_name, escaped);
}
if let Some(url) = link_url {
write!(code, "<a href=\"{}\">{}</a>", html_escape(&url), inner).unwrap();
} else {
code.push_str(&inner);
}
} else {
code.push_str(&escaped);
}
}
let fg = theme.foreground_color.hex();
let bg = theme.background_color.hex();
// Font-family override
let font_family = opts
.font_family
.as_deref()
.unwrap_or("Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace");
// Build @font-face if font_url is provided
let font_face = if let Some(ref url) = opts.font_url {
format!(
"@font-face {{ font-family: '{}'; src: url('{}'); }}\n",
font_family, url
)
} else {
String::new()
};
// Dark-mode CSS block
let dark_css = if opts.dark_mode {
format!(
"\n@media (prefers-color-scheme: dark) {{\n body {{ color: {}; background-color: {}; }}\n}}\n",
bg, fg
)
} else {
String::new()
};
// Full stylesheet
let full_stylesheet = format!("{}{}{}", font_face, stylesheet, dark_css);
// Copy-button HTML + JS
let copy_snippet = if opts.copy_button {
r#"<button id="gilt-copy-btn" onclick="(function(){var p=document.querySelector('pre');if(p){navigator.clipboard&&navigator.clipboard.writeText(p.innerText)||window.prompt('Copy:',p.innerText)}})()">Copy</button>
<script>document.getElementById('gilt-copy-btn').style.cssText='position:absolute;top:8px;right:8px;padding:2px 8px;cursor:pointer';</script>
"#
} else {
""
};
// Choose template
let template = opts.code_format.as_deref().unwrap_or(CONSOLE_HTML_FORMAT);
// Inject copy button before </body>
let html_base = template
.replace("{stylesheet}", &full_stylesheet)
.replace("{foreground}", &fg)
.replace("{background}", &bg)
.replace("{code}", &code);
if opts.copy_button {
html_base.replace("</body>", &format!("{}</body>", copy_snippet))
} else {
html_base
}
}
/// Export recorded output as an SVG document.
///
/// Generates a complete SVG image with terminal-style chrome (title bar,
/// window controls) and styled text content. Requires `record` mode.
///
/// # Examples
///
/// ```
/// use gilt::console::Console;
/// use gilt::text::Text;
/// use gilt::style::Style;
///
/// let mut console = Console::builder()
/// .width(40)
/// .record(true)
/// .no_color(true)
/// .markup(false)
/// .build();
/// let text = Text::new("SVG test", Style::null());
/// console.print(&text);
/// let svg = console.export_svg("Test", None, false, None, 0.61);
/// assert!(svg.contains("<svg"));
/// assert!(svg.contains("SVG test"));
/// ```
pub fn export_svg(
&mut self,
title: &str,
theme: Option<&TerminalTheme>,
clear: bool,
unique_id: Option<&str>,
font_aspect_ratio: f64,
) -> String {
let theme = theme.unwrap_or(&SVG_EXPORT_THEME);
// Finding #9: avoid cloning the whole buffer.
let buffer_ref: &[Segment];
let taken: Vec<Segment>;
if clear {
taken = std::mem::take(&mut self.record_buffer);
buffer_ref = &taken;
} else {
buffer_ref = &self.record_buffer;
}
// Finding #11: derive a unique id from FNV-1a hash of segment text + title
// when the caller leaves unique_id as None.
let derived_id: String;
let unique_id: &str = if let Some(id) = unique_id {
id
} else {
let mut hash: u64 = 14695981039346656037u64; // FNV-1a offset basis
for seg in buffer_ref {
for byte in seg.text.as_bytes() {
hash = hash.wrapping_mul(1099511628211) ^ (*byte as u64);
}
}
for byte in title.as_bytes() {
hash = hash.wrapping_mul(1099511628211) ^ (*byte as u64);
}
derived_id = format!("gilt-{:016x}", hash);
&derived_id
};
// Finding #10: split multi-newline segments into per-line owned Segments.
let text_lines: Vec<Vec<Segment>> = {
let mut lines: Vec<Vec<Segment>> = Vec::new();
let mut current: Vec<Segment> = Vec::new();
for seg in buffer_ref {
if seg.is_control() {
continue;
}
if seg.text.contains('\n') {
let parts: Vec<&str> = seg.text.split('\n').collect();
for (i, part) in parts.iter().enumerate() {
if !part.is_empty() {
// Create an owned sub-segment carrying the original style.
current.push(Segment::new(part, seg.style().cloned(), None));
}
if i + 1 < parts.len() {
lines.push(std::mem::take(&mut current));
}
}
} else {
current.push(seg.clone());
}
}
if !current.is_empty() {
lines.push(current);
}
lines
};
let char_height = 20.0_f64;
let line_height = char_height * 1.22;
let char_width = char_height * font_aspect_ratio;
let margin_top = 1.0;
let margin_right = 1.0;
let margin_bottom = 1.0;
let margin_left = 1.0;
let padding_top = 40.0;
let padding_right = 8.0;
let padding_bottom = 8.0;
let padding_left = 8.0;
let console_width = self.width() as f64;
let line_count = text_lines.len().max(1) as f64;
let terminal_width = (console_width * char_width + padding_left + padding_right).ceil();
let terminal_height = (line_count * line_height + padding_top + padding_bottom).ceil();
let svg_width = (terminal_width + margin_left + margin_right).ceil();
let svg_height = (terminal_height + margin_top + margin_bottom).ceil();
let terminal_x = margin_left;
let terminal_y = margin_top;
// Build the chrome (window decorations)
let chrome = build_svg_chrome(terminal_width, terminal_height, theme, title, unique_id);
// Build the text matrix (pass buffer_ref so build_svg_text doesn't need the split lines)
let (matrix, backgrounds, styles, lines_defs) = build_svg_text(
buffer_ref,
theme,
unique_id,
char_width,
line_height,
padding_top,
padding_left,
);
// Pre-format numeric values into a shared buffer to avoid per-replace allocations.
let mut buf = String::with_capacity(16);
macro_rules! fmt_buf {
($fmt:literal, $val:expr) => {{
buf.clear();
write!(buf, $fmt, $val).unwrap();
&buf
}};
}
// Apply replacements that use the shared buffer one at a time,
// cloning the formatted value so `buf` can be reused.
let mut svg = CONSOLE_SVG_FORMAT.replace("{unique_id}", unique_id);
svg = svg.replace("{char_height}", fmt_buf!("{:.1}", char_height));
svg = svg.replace("{line_height}", fmt_buf!("{:.1}", line_height));
svg = svg.replace("{width}", fmt_buf!("{:.0}", svg_width));
svg = svg.replace("{height}", fmt_buf!("{:.0}", svg_height));
svg = svg.replace("{terminal_width}", fmt_buf!("{:.0}", terminal_width));
svg = svg.replace("{terminal_height}", fmt_buf!("{:.0}", terminal_height));
svg = svg.replace("{terminal_x}", fmt_buf!("{:.0}", terminal_x));
svg = svg.replace("{terminal_y}", fmt_buf!("{:.0}", terminal_y));
svg = svg.replace("{chrome}", &chrome);
svg = svg.replace("{matrix}", &matrix);
svg = svg.replace("{backgrounds}", &backgrounds);
svg = svg.replace("{styles}", &styles);
svg = svg.replace("{lines}", &lines_defs);
svg
}
/// Export recorded output as an SVG document with full control via
/// [`SvgExportOptions`].
///
/// The key addition over [`export_svg`](Self::export_svg) is
/// [`FontEmbedding::Base64`], which embeds raw font bytes as a base64
/// `data:` URL so the SVG is completely self-contained offline.
///
/// # Examples
///
/// ```
/// use gilt::console::Console;
/// use gilt::export_format::{FontEmbedding, SvgExportOptions};
/// use gilt::text::Text;
/// use gilt::style::Style;
///
/// let mut console = Console::builder()
/// .width(40)
/// .record(true)
/// .no_color(true)
/// .markup(false)
/// .build();
/// console.print(&Text::new("SVG opts", Style::null()));
///
/// // Embed a tiny fake font for offline use
/// let opts = SvgExportOptions::default()
/// .title("Demo")
/// .font_embedding(FontEmbedding::Base64(b"FAKE_FONT".to_vec()));
/// let svg = console.export_svg_opts(None, &opts);
/// assert!(svg.contains("<svg"));
/// assert!(svg.contains("data:font/"));
/// ```
pub fn export_svg_opts(
&mut self,
theme: Option<&TerminalTheme>,
opts: &SvgExportOptions,
) -> String {
use crate::utils::control::base64_encode;
let theme = theme.unwrap_or(&SVG_EXPORT_THEME);
let buffer_ref: &[Segment];
let taken: Vec<Segment>;
if opts.clear {
taken = std::mem::take(&mut self.record_buffer);
buffer_ref = &taken;
} else {
buffer_ref = &self.record_buffer;
}
// Derive unique_id
let derived_id: String;
let unique_id: &str = if let Some(ref id) = opts.unique_id {
id.as_str()
} else {
let mut hash: u64 = 14695981039346656037u64;
for seg in buffer_ref {
for byte in seg.text.as_bytes() {
hash = hash.wrapping_mul(1099511628211) ^ (*byte as u64);
}
}
for byte in opts.title.as_bytes() {
hash = hash.wrapping_mul(1099511628211) ^ (*byte as u64);
}
derived_id = format!("gilt-{:016x}", hash);
&derived_id
};
let text_lines: Vec<Vec<Segment>> = {
let mut lines: Vec<Vec<Segment>> = Vec::new();
let mut current: Vec<Segment> = Vec::new();
for seg in buffer_ref {
if seg.is_control() {
continue;
}
if seg.text.contains('\n') {
let parts: Vec<&str> = seg.text.split('\n').collect();
for (i, part) in parts.iter().enumerate() {
if !part.is_empty() {
current.push(Segment::new(part, seg.style().cloned(), None));
}
if i + 1 < parts.len() {
lines.push(std::mem::take(&mut current));
}
}
} else {
current.push(seg.clone());
}
}
if !current.is_empty() {
lines.push(current);
}
lines
};
let char_height = 20.0_f64;
let line_height = char_height * 1.22;
let char_width = char_height * opts.font_aspect_ratio;
let margin_top = 1.0;
let margin_right = 1.0;
let margin_bottom = 1.0;
let margin_left = 1.0;
let padding_top = 40.0;
let padding_right = 8.0;
let padding_bottom = 8.0;
let padding_left = 8.0;
let console_width = self.width() as f64;
let line_count = text_lines.len().max(1) as f64;
let terminal_width = (console_width * char_width + padding_left + padding_right).ceil();
let terminal_height = (line_count * line_height + padding_top + padding_bottom).ceil();
let svg_width = (terminal_width + margin_left + margin_right).ceil();
let svg_height = (terminal_height + margin_top + margin_bottom).ceil();
let terminal_x = margin_left;
let terminal_y = margin_top;
let chrome = build_svg_chrome(
terminal_width,
terminal_height,
theme,
&opts.title,
unique_id,
);
let (matrix, backgrounds, styles, lines_defs) = build_svg_text(
buffer_ref,
theme,
unique_id,
char_width,
line_height,
padding_top,
padding_left,
);
// Build base SVG from standard template
let mut buf = String::with_capacity(16);
macro_rules! fmt_buf {
($fmt:literal, $val:expr) => {{
buf.clear();
write!(buf, $fmt, $val).unwrap();
&buf
}};
}
let mut svg = CONSOLE_SVG_FORMAT.replace("{unique_id}", unique_id);
svg = svg.replace("{char_height}", fmt_buf!("{:.1}", char_height));
svg = svg.replace("{line_height}", fmt_buf!("{:.1}", line_height));
svg = svg.replace("{width}", fmt_buf!("{:.0}", svg_width));
svg = svg.replace("{height}", fmt_buf!("{:.0}", svg_height));
svg = svg.replace("{terminal_width}", fmt_buf!("{:.0}", terminal_width));
svg = svg.replace("{terminal_height}", fmt_buf!("{:.0}", terminal_height));
svg = svg.replace("{terminal_x}", fmt_buf!("{:.0}", terminal_x));
svg = svg.replace("{terminal_y}", fmt_buf!("{:.0}", terminal_y));
svg = svg.replace("{chrome}", &chrome);
svg = svg.replace("{matrix}", &matrix);
svg = svg.replace("{backgrounds}", &backgrounds);
svg = svg.replace("{styles}", &styles);
svg = svg.replace("{lines}", &lines_defs);
// Task 2: inject @font-face with base64 data: URL when FontEmbedding::Base64
if let FontEmbedding::Base64(ref font_bytes) = opts.font_embedding {
let encoded = base64_encode(font_bytes);
let font_face = format!(
"@font-face {{\n font-family: \"Fira Code\";\n src: url(\"data:font/woff2;base64,{}\") format(\"woff2\");\n font-style: normal;\n font-weight: 400;\n}}\n",
encoded
);
// Replace the existing @font-face blocks (everything from the first
// @font-face up to the first `.{unique_id}-matrix` class).
// Simpler: just prepend the embedded rule inside the <style> tag.
svg = svg.replacen("<style>", &format!("<style>\n{}", font_face), 1);
}
svg
}
}