1use std::fmt;
34use std::io::{self, Write};
35
36use crate::buffer::Surface;
37use crate::cell::Cell;
38use crate::color::Profile;
39use crate::layout::Position;
40use crate::style::diff::{convert_style, write_link, write_style_diff};
41use crate::style::{Style, UnderlineStyle};
42
43pub trait Encode: Surface {
59 fn encode<W: Write>(&self, w: &mut W) -> io::Result<()> {
80 encode_surface(self, w, Profile::TrueColor)
81 }
82
83 fn encode_with<W: Write>(&self, w: &mut W, profile: Profile) -> io::Result<()> {
97 encode_surface(self, w, profile)
98 }
99
100 fn display(&self) -> SurfaceDisplay<'_, Self> {
107 SurfaceDisplay {
108 surface: self,
109 profile: Profile::TrueColor,
110 }
111 }
112
113 fn display_with(&self, profile: Profile) -> SurfaceDisplay<'_, Self> {
119 SurfaceDisplay {
120 surface: self,
121 profile,
122 }
123 }
124}
125
126impl<S: Surface + ?Sized> Encode for S {}
127
128pub struct SurfaceDisplay<'a, S: Surface + ?Sized> {
134 surface: &'a S,
135 profile: Profile,
136}
137
138impl<S: Surface + ?Sized> fmt::Display for SurfaceDisplay<'_, S> {
139 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140 let mut buf = Vec::new();
143 encode_surface(self.surface, &mut buf, self.profile).map_err(|_| fmt::Error)?;
144 let s = std::str::from_utf8(&buf).map_err(|_| fmt::Error)?;
145 f.write_str(s)
146 }
147}
148
149fn encode_surface<S: Surface + ?Sized, W: Write>(
151 surface: &S,
152 w: &mut W,
153 profile: Profile,
154) -> io::Result<()> {
155 match profile {
156 Profile::Disabled => encode_impl::<false, false, _, _>(surface, w, std::convert::identity),
157 Profile::Ascii => encode_impl::<true, false, _, _>(surface, w, std::convert::identity),
158 Profile::TrueColor => encode_impl::<true, true, _, _>(surface, w, std::convert::identity),
159 Profile::Ansi => {
160 encode_impl::<true, true, _, _>(surface, w, |style| convert_style(style, Profile::Ansi))
161 }
162 Profile::Ansi256 => encode_impl::<true, true, _, _>(surface, w, |style| {
163 convert_style(style, Profile::Ansi256)
164 }),
165 }
166}
167
168#[inline(never)]
170fn encode_impl<const STYLED: bool, const COLORS: bool, S: Surface + ?Sized, W: Write>(
171 surface: &S,
172 w: &mut W,
173 convert: impl Fn(Style) -> Style,
174) -> io::Result<()> {
175 let bounds = surface.bounds();
176 let default = Style::default();
177 let x_end = bounds.x.saturating_add(bounds.width);
178 let y_end = bounds.y.saturating_add(bounds.height);
179
180 for (row, y) in (bounds.y..y_end).enumerate() {
181 if row > 0 {
182 w.write_all(b"\r\n")?;
183 }
184
185 let last_visible = (bounds.x..x_end).rev().find(|&x| {
191 surface.cell(Position::new(x, y)).is_some_and(|cell| {
192 !cell.is_blank()
193 || (STYLED
194 && ((if COLORS {
195 !cell.style().is_empty()
196 } else {
197 !cell.attrs.is_empty() || cell.underline != UnderlineStyle::None
198 }) || cell.link().is_some()))
199 })
200 });
201 let Some(last_visible) = last_visible else {
202 continue;
204 };
205
206 let mut raw = &Cell::BLANK;
208 let mut pen = default;
209 let mut link = None;
210 for x in bounds.x..=last_visible {
211 let Some(cell) = surface.cell(Position::new(x, y)) else {
212 continue;
213 };
214 if cell.is_continuation() {
217 continue;
218 }
219
220 if STYLED {
222 let changed = if COLORS {
223 cell.fg != raw.fg
224 || cell.bg != raw.bg
225 || cell.underline_color != raw.underline_color
226 || cell.attrs != raw.attrs
227 || cell.underline != raw.underline
228 } else {
229 cell.attrs != pen.attrs || cell.underline != pen.underline
230 };
231 if changed {
232 let to = if COLORS {
233 convert(cell.style())
234 } else {
235 Style {
236 attrs: cell.attrs,
237 underline: cell.underline,
238 ..default
239 }
240 };
241 write_style_diff(w, &pen, &to)?;
242 raw = cell;
243 pen = to;
244 }
245 let to_link = cell.link();
246 if link != to_link {
247 write_link(w, to_link)?;
248 link = to_link;
249 }
250 }
251 w.write_all(cell.draw_bytes())?;
252 }
253
254 if STYLED {
257 write_style_diff(w, &pen, &default)?;
258 if link.is_some() {
259 write_link(w, None)?;
260 }
261 }
262 }
263
264 Ok(())
265}
266
267#[cfg(test)]
268mod tests {
269 use super::*;
270 use crate::buffer::{Buffer, SurfaceMut};
271 use crate::cell::Cell;
272 use crate::style::{RESET, Style};
273
274 fn reset() -> &'static str {
275 std::str::from_utf8(RESET).unwrap()
276 }
277
278 #[test]
279 fn visual_and_link_runs_transition_independently() {
280 use crate::color::Color;
281
282 let open = "\x1b]8;id=run;https://x\x1b\\";
283 let close = "\x1b]8;;\x1b\\";
284 for (profile, red, blue) in [
285 (Profile::TrueColor, "\x1b[31m", "\x1b[34m"),
286 (Profile::Ascii, "", ""),
287 ] {
288 let mut buf = Buffer::new(5, 1);
289 let link = crate::style::test_link("https://x", "id=run");
290 let equal = crate::style::test_link("https://x", "id=run");
291 for (x, text, style, target) in [
292 (0, "a", Style::new().fg(Color::Red), Some(&link)),
293 (1, "b", Style::new().fg(Color::Red), Some(&equal)),
294 (2, "c", Style::new().fg(Color::Blue), Some(&link)),
295 (3, "d", Style::new().fg(Color::Blue).bold(), None),
296 (4, " ", Style::new().fg(Color::Blue).bold(), Some(&link)),
297 ] {
298 let mut cell = Cell::new(text, 1).with_style(style);
299 cell.set_link(target.cloned());
300 buf.set_cell((x, 0).into(), &cell);
301 }
302 assert_eq!(
303 buf.display_with(profile).to_string(),
304 format!("{red}{open}ab{blue}c\x1b[1m{close}d{open} \x1b[m{close}"),
305 "{profile:?}"
306 );
307 }
308 }
309
310 #[test]
311 fn styled_run_emits_one_opener_and_a_trailing_reset() {
312 let mut buf = Buffer::new(2, 1);
313 let bold = Style::new().bold();
314 buf.set_cell((0, 0).into(), &Cell::new("h", 1).with_style(bold));
315 buf.set_cell((1, 0).into(), &Cell::new("i", 1).with_style(bold));
316
317 let out = buf.display().to_string();
318 assert!(out.contains("hi"), "content present: {out:?}");
321 assert!(out.ends_with(reset()), "row reset: {out:?}");
322 assert_eq!(out.matches(reset()).count(), 1, "single reset: {out:?}");
323 assert_eq!(
324 out.matches("\x1b[").count(),
325 2,
326 "one opener + reset: {out:?}"
327 );
328 }
329
330 #[test]
331 fn a_cell_that_stores_nothing_is_blanked_across_its_whole_width() {
332 let mut buf = Buffer::new(5, 1);
333 buf.set_cell((0, 0).into(), &Cell::new("A", 1));
334 buf.set_cell(
335 (1, 0).into(),
336 &Cell::new("", 3).with_style(Style::new().bold()),
337 );
338 buf.set_cell((4, 0).into(), &Cell::new("B", 1));
339
340 let out = buf.display().to_string();
344 assert!(out.contains(" "), "three blanks between: {out:?}");
345 assert!(out.starts_with('A'), "row starts at A: {out:?}");
346 assert!(out.ends_with(&format!("{}B", reset())), "B last: {out:?}");
347 }
348
349 #[test]
350 fn wide_continuation_is_skipped() {
351 let mut buf = Buffer::new(2, 1);
352 buf.set_cell((0, 0).into(), &Cell::new("世", 2));
353 let out = buf.display().to_string();
355 assert_eq!(out, "世");
357 }
358
359 #[test]
360 fn encode_matches_display() {
361 let mut buf = Buffer::new(2, 1);
362 buf.set_cell(
363 (0, 0).into(),
364 &Cell::new("A", 1).with_style(Style::new().bold()),
365 );
366 let mut bytes = Vec::new();
367 buf.encode(&mut bytes).unwrap();
368 assert_eq!(String::from_utf8(bytes).unwrap(), buf.display().to_string());
369 }
370
371 #[test]
372 fn rows_are_crlf_separated_without_trailing_newline() {
373 let buf = Buffer::new(1, 3);
374 let out = buf.display().to_string();
376 assert_eq!(out, "\r\n\r\n");
377 }
378
379 #[test]
380 fn trailing_unstyled_spaces_are_trimmed() {
381 let mut buf = Buffer::new(5, 1);
382 buf.set_cell((0, 0).into(), &Cell::new("h", 1));
383 buf.set_cell((1, 0).into(), &Cell::new("i", 1));
384 assert_eq!(buf.display().to_string(), "hi");
386 }
387
388 #[test]
389 fn a_trailing_column_holding_nothing_trims_like_one_holding_a_space() {
390 for tail in [Cell::BLANK, Cell::new(" ", 1), Cell::new("", 1)] {
393 let mut buf = Buffer::new(5, 1);
394 buf.set_cell((0, 0).into(), &Cell::new("h", 1));
395 buf.set_cell((1, 0).into(), &tail);
396 assert_eq!(buf.display().to_string(), "h", "tail {tail:?}");
397 }
398 }
399
400 #[test]
401 fn interior_blanks_are_kept_only_trailing_trimmed() {
402 let mut buf = Buffer::new(5, 1);
403 buf.set_cell((0, 0).into(), &Cell::new("a", 1));
404 buf.set_cell((2, 0).into(), &Cell::new("b", 1));
405 assert_eq!(buf.display().to_string(), "a b");
407 }
408
409 #[test]
410 fn linked_trailing_spaces_close_at_each_row() {
411 let mut buf = Buffer::new(4, 2);
412 let mut space = Cell::BLANK;
413 space.set_link(Some(crate::style::test_link("https://x", "")));
414 for y in 0..2 {
415 buf.set_cell((1, y).into(), &space);
416 }
417 assert_eq!(
418 buf.display().to_string(),
419 " \x1b]8;;https://x\x1b\\ \x1b]8;;\x1b\\\r\n \x1b]8;;https://x\x1b\\ \x1b]8;;\x1b\\"
420 );
421 assert_eq!(buf.display_with(Profile::Disabled).to_string(), "\r\n");
422 }
423
424 #[test]
425 fn styled_trailing_space_is_not_trimmed() {
426 use crate::color::Color;
427 let mut buf = Buffer::new(3, 1);
428 buf.set_cell((0, 0).into(), &Cell::new("a", 1));
429 let bg = Style::new().bg(Color::Red);
431 buf.set_cell((2, 0).into(), &Cell::new(" ", 1).with_style(bg));
432 assert_eq!(buf.display().to_string(), "a \x1b[41m \x1b[m");
434 }
435
436 #[test]
437 fn disabled_profile_trims_styled_trailing_space() {
438 use crate::color::{Color, Profile};
439 let mut buf = Buffer::new(3, 1);
440 buf.set_cell((0, 0).into(), &Cell::new("a", 1));
441 let mut tail = Cell::new(" ", 1).with_style(Style::new().bg(Color::Red));
442 tail.set_link(Some(crate::style::test_link(
443 "https://example.test/tail",
444 "",
445 )));
446 buf.set_cell((2, 0).into(), &tail);
447 assert_eq!(buf.display_with(Profile::Disabled).to_string(), "a");
450 }
451
452 #[test]
453 fn profile_disabled_drops_all_styling() {
454 use crate::color::{Color, Profile};
455 let mut buf = Buffer::new(2, 1);
456 let styled = Style::new().bold().fg(Color::Red);
457 for (x, text) in ["h", "i"].into_iter().enumerate() {
458 let mut cell = Cell::new(text, 1).with_style(styled);
459 cell.set_link(Some(crate::style::test_link(
460 "https://example.test/text",
461 "",
462 )));
463 buf.set_cell((x as u16, 0).into(), &cell);
464 }
465 assert_eq!(buf.display_with(Profile::Disabled).to_string(), "hi");
467 }
468
469 #[test]
470 fn color_profiles_preserve_raw_transitions_and_merge_equal_palette_colors() {
471 use crate::color::{Color, Profile};
472 let mut buf = Buffer::new(6, 1);
473 let colors = Style::new()
474 .italic()
475 .underline()
476 .fg(Color::Rgb(255, 0, 0))
477 .bg(Color::Rgb(0, 255, 0))
478 .underline_color(Color::Rgb(0, 0, 255));
479 let fg = colors.fg(Color::Rgb(254, 0, 0));
480 let bg = fg.bg(Color::Rgb(0, 254, 0));
481 let underline_color = bg.underline_color(Color::Rgb(0, 0, 254));
482 let link = crate::style::test_link("https://x", "id=colors");
483 let equal = crate::style::test_link("https://x", "id=colors");
484 for (x, text, style, target) in [
485 (0, "a", colors, Some(&link)),
486 (1, "b", fg, Some(&equal)),
487 (2, "c", bg, Some(&link)),
488 (3, "d", underline_color, Some(&link)),
489 (4, "e", Style::new().italic().underline(), None),
490 (5, "f", Style::EMPTY, None),
491 ] {
492 let mut cell = Cell::new(text, 1).with_style(style);
493 cell.set_link(target.cloned());
494 buf.set_cell((x, 0).into(), &cell);
495 }
496 let open = "\x1b]8;id=colors;https://x\x1b\\";
497 let close = "\x1b]8;;\x1b\\";
498 for (profile, start, run) in [
499 (
500 Profile::TrueColor,
501 "\x1b[3;4;38;2;255;0;0;48;2;0;255;0;58:2::0:0:255m",
502 "a\x1b[38;2;254;0;0mb\x1b[48;2;0;254;0mc\x1b[58:2::0:0:254md",
503 ),
504 (
505 Profile::Ansi256,
506 "\x1b[3;4;38;5;196;48;5;46;58:5:21m",
507 "abcd",
508 ),
509 (Profile::Ansi, "\x1b[3;4;91;102;58:5:12m", "abcd"),
510 ] {
511 assert_eq!(
512 buf.display_with(profile).to_string(),
513 format!("{start}{open}{run}\x1b[39;49;59m{close}e\x1b[mf"),
514 "{profile:?}"
515 );
516 }
517 }
518
519 #[test]
520 fn profile_ascii_keeps_visual_and_link_transitions_but_drops_colors() {
521 use crate::color::{Color, Profile};
522 let mut buf = Buffer::new(10, 1);
523 let colors = Style::new()
524 .fg(Color::Rgb(10, 20, 30))
525 .bg(Color::Red)
526 .underline_color(Color::Blue);
527 let decorated = colors.bold().underline_style(UnderlineStyle::Curly);
528 let fg = decorated.fg(Color::Green);
529 let bg = fg.bg(Color::Yellow);
530 let underline_color = bg.underline_color(Color::Cyan);
531 let link = crate::style::test_link("https://x", "id=ascii");
532 let equal = crate::style::test_link("https://x", "id=ascii");
533 for (x, text, style, target) in [
534 (0, "a", colors, None),
535 (1, "b", decorated, Some(&link)),
536 (2, "c", fg, Some(&equal)),
537 (3, "d", bg, Some(&link)),
538 (4, "e", underline_color, Some(&link)),
539 (5, "f", underline_color, None),
540 (
541 6,
542 "g",
543 underline_color.underline_style(UnderlineStyle::Dotted),
544 None,
545 ),
546 (7, "h", colors, Some(&link)),
547 (8, " ", colors, Some(&link)),
548 (9, " ", colors, None),
549 ] {
550 let mut cell = Cell::new(text, 1).with_style(style);
551 cell.set_link(target.cloned());
552 buf.set_cell((x, 0).into(), &cell);
553 }
554 let open = "\x1b]8;id=ascii;https://x\x1b\\";
555 let close = "\x1b]8;;\x1b\\";
556 assert_eq!(
557 buf.display_with(Profile::Ascii).to_string(),
558 format!("a\x1b[1;4:3m{open}bcde{close}f\x1b[4:4mg\x1b[m{open}h {close}")
559 );
560 }
561
562 #[test]
563 fn truecolor_profile_matches_default() {
564 use crate::color::{Color, Profile};
565 let mut buf = Buffer::new(2, 1);
566 let styled = Style::new().fg(Color::Rgb(1, 2, 3));
567 for (x, text) in ["h", "i"].into_iter().enumerate() {
568 let mut cell = Cell::new(text, 1).with_style(styled);
569 cell.set_link(Some(crate::style::test_link("https://e.x", "")));
570 buf.set_cell((x as u16, 0).into(), &cell);
571 }
572 assert_eq!(
573 buf.display_with(Profile::TrueColor).to_string(),
574 buf.display().to_string(),
575 );
576 }
577}