Skip to content

Commit

Permalink
Fallback to SGR when rendering 16/256 colors when MaxColors is 16M
Browse files Browse the repository at this point in the history
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`).
  • Loading branch information
quark-zju authored and wez committed Nov 4, 2023
1 parent 3f1a120 commit 2a02239
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions termwiz/src/render/terminfo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,16 @@ impl TerminfoRenderer {
}

let has_true_color = self.caps.color_level() == ColorLevel::TrueColor;
let terminfo_color: i32 = match self.get_capability::<cap::MaxColors>() {
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::<cap::MaxColors>() {
Some(cap::MaxColors(n)) => {
if n > 256 {
0
} else {
n
}
}
None => 0,
};

Expand All @@ -160,7 +168,7 @@ impl TerminfoRenderer {
(false, ColorAttribute::TrueColorWithPaletteFallback(_, idx))
| (_, ColorAttribute::PaletteIndex(idx)) => {
match self.get_capability::<cap::SetAForeground>() {
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())?;
}
_ => {
Expand Down Expand Up @@ -194,7 +202,7 @@ impl TerminfoRenderer {
(false, ColorAttribute::TrueColorWithPaletteFallback(_, idx))
| (_, ColorAttribute::PaletteIndex(idx)) => {
match self.get_capability::<cap::SetABackground>() {
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())?;
}
_ => {
Expand Down

0 comments on commit 2a02239

Please sign in to comment.