From 2957173a57a9d76b025cf6fbbbcc3a7af63aa56c Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Wed, 17 Jun 2020 21:56:30 -0700 Subject: [PATCH] termwiz: also allow `#FFF` form of color spec We allowed the 6-digit variant, also allow the 3-digit variant. --- termwiz/src/color.rs | 25 ++++++++++++++++++++++++- termwiz/src/escape/osc.rs | 4 ++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/termwiz/src/color.rs b/termwiz/src/color.rs index 717f8192b..5b46365b6 100644 --- a/termwiz/src/color.rs +++ b/termwiz/src/color.rs @@ -141,7 +141,20 @@ impl RgbColor { /// Construct a color from a string of the form `#RRGGBB` where /// R, G and B are all hex digits. pub fn from_rgb_str(s: &str) -> Option { - if s.len() == 7 && s.as_bytes()[0] == b'#' { + if s.len() == 4 && s.as_bytes()[0] == b'#' { + let mut chars = s.chars().skip(1); + + macro_rules! digit { + () => {{ + let lo = match chars.next().unwrap().to_digit(16) { + Some(v) => v as u8, + None => return None, + }; + lo << 4 | lo + }}; + } + Some(Self::new(digit!(), digit!(), digit!())) + } else if s.len() == 7 && s.as_bytes()[0] == b'#' { let mut chars = s.chars().skip(1); macro_rules! digit { @@ -324,6 +337,16 @@ mod tests { assert!(RgbColor::from_rgb_str("").is_none()); assert!(RgbColor::from_rgb_str("#xyxyxy").is_none()); + let black = RgbColor::from_rgb_str("#000").unwrap(); + assert_eq!(black.red, 0); + assert_eq!(black.green, 0); + assert_eq!(black.blue, 0); + + let black = RgbColor::from_rgb_str("#FFF").unwrap(); + assert_eq!(black.red, 0xff); + assert_eq!(black.green, 0xff); + assert_eq!(black.blue, 0xff); + let black = RgbColor::from_rgb_str("#000000").unwrap(); assert_eq!(black.red, 0); assert_eq!(black.green, 0); diff --git a/termwiz/src/escape/osc.rs b/termwiz/src/escape/osc.rs index 6419391a9..b70a09c93 100644 --- a/termwiz/src/escape/osc.rs +++ b/termwiz/src/escape/osc.rs @@ -201,7 +201,7 @@ impl OperatingSystemCommand { } else { ColorOrQuery::Color( RgbColor::from_named_or_rgb_string(spec) - .ok_or_else(|| anyhow!("invalid color spec"))?, + .ok_or_else(|| anyhow!("invalid color spec {:?}", spec))?, ) }; @@ -232,7 +232,7 @@ impl OperatingSystemCommand { let spec = str::from_utf8(spec)?; colors.push(ColorOrQuery::Color( RgbColor::from_named_or_rgb_string(spec) - .ok_or_else(|| anyhow!("invalid color spec"))?, + .ok_or_else(|| anyhow!("invalid color spec {:?}", spec))?, )); } }