From 2a022399bb0b6037f06b6ad3175dd98beb0aa7b2 Mon Sep 17 00:00:00 2001 From: Jun Wu Date: Fri, 3 Nov 2023 10:50:09 -0700 Subject: [PATCH] Fallback to SGR when rendering 16/256 colors when MaxColors is 16M When MaxColors is 16M, the "palette index" is treated by "setaf" as a true color, not the classic 256 color. Users of `PaletteIndex` expects 256 color and let's fallback to SGR. For example, setaf on tmux-direct is: setaf=\E[%?%p1%{8}%<%t3%p1%d%e38:2::%p1%{65536}%/%d:%p1%{256}%/%{255}%&%d:%p1%{255}%&%d%;m, It only special treats the first 8 colors (which means `rgb(0,0,0..8)` cannot be rendered with `setaf`). --- termwiz/src/render/terminfo.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/termwiz/src/render/terminfo.rs b/termwiz/src/render/terminfo.rs index c57414759..8de007035 100644 --- a/termwiz/src/render/terminfo.rs +++ b/termwiz/src/render/terminfo.rs @@ -136,8 +136,16 @@ 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, + // Whether to use terminfo to render 256 colors. If this is too large (ex. 16777216 from xterm-direct), + // then setaf expects the index to be true color, in which case we cannot use it to render 256 (or even 16) colors. + let terminfo_256_color: i32 = match self.get_capability::() { + Some(cap::MaxColors(n)) => { + if n > 256 { + 0 + } else { + n + } + } None => 0, }; @@ -160,7 +168,7 @@ impl TerminfoRenderer { (false, ColorAttribute::TrueColorWithPaletteFallback(_, idx)) | (_, ColorAttribute::PaletteIndex(idx)) => { match self.get_capability::() { - Some(set) if (idx as i32) < terminfo_color => { + Some(set) if (idx as i32) < terminfo_256_color => { set.expand().color(idx).to(out.by_ref())?; } _ => { @@ -194,7 +202,7 @@ impl TerminfoRenderer { (false, ColorAttribute::TrueColorWithPaletteFallback(_, idx)) | (_, ColorAttribute::PaletteIndex(idx)) => { match self.get_capability::() { - Some(set) if (idx as i32) < terminfo_color => { + Some(set) if (idx as i32) < terminfo_256_color => { set.expand().color(idx).to(out.by_ref())?; } _ => {