From 228eab546e45c7afee68bbafb52e2edb49019159 Mon Sep 17 00:00:00 2001 From: Jun Wu Date: Thu, 8 Apr 2021 21:18:03 -0700 Subject: [PATCH] termwiz: do not use terminfo for unsupported 256-colors I noticed edenscm log -p (using streampager) cannot render 256 colors if TERM is not "*-256color", despite forcing enabling true colors in streampager (https://github.com/markbt/streampager/pull/28). I tracked it down here. The problem is that we ask terminfo for colors it does not claim to support. Fix it by using fallback CSI rendering for colors exceeding the terminfo max color. --- termwiz/src/render/terminfo.rs | 42 +++++++++++++++++++++------------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/termwiz/src/render/terminfo.rs b/termwiz/src/render/terminfo.rs index ac2ec9d08..d80b4892f 100644 --- a/termwiz/src/render/terminfo.rs +++ b/termwiz/src/render/terminfo.rs @@ -125,6 +125,10 @@ impl TerminfoRenderer { } let has_true_color = self.caps.color_level() == ColorLevel::TrueColor; + let terminfo_color: i32 = match self.get_capability::() { + Some(cap::MaxColors(n)) => n, + None => 0, + }; if attr.foreground != current_foreground { match (has_true_color, attr.foreground) { @@ -144,14 +148,17 @@ impl TerminfoRenderer { } (false, ColorAttribute::TrueColorWithPaletteFallback(_, idx)) | (_, ColorAttribute::PaletteIndex(idx)) => { - if let Some(set) = self.get_capability::() { - set.expand().color(idx).to(out.by_ref())?; - } else { - write!( - out, - "{}", - CSI::Sgr(Sgr::Foreground(ColorSpec::PaletteIndex(idx))) - )?; + match self.get_capability::() { + Some(set) if (idx as i32) < terminfo_color => { + set.expand().color(idx).to(out.by_ref())?; + } + _ => { + write!( + out, + "{}", + CSI::Sgr(Sgr::Foreground(ColorSpec::PaletteIndex(idx))) + )?; + } } } } @@ -175,14 +182,17 @@ impl TerminfoRenderer { } (false, ColorAttribute::TrueColorWithPaletteFallback(_, idx)) | (_, ColorAttribute::PaletteIndex(idx)) => { - if let Some(set) = self.get_capability::() { - set.expand().color(idx).to(out.by_ref())?; - } else { - write!( - out, - "{}", - CSI::Sgr(Sgr::Background(ColorSpec::PaletteIndex(idx))) - )?; + match self.get_capability::() { + Some(set) if (idx as i32) < terminfo_color => { + set.expand().color(idx).to(out.by_ref())?; + } + _ => { + write!( + out, + "{}", + CSI::Sgr(Sgr::Background(ColorSpec::PaletteIndex(idx))) + )?; + } } } }