[repo] Merge: feature/dark-reader (Sanitiser: the dark reader's colours, v0.2.0, PR #2)

This commit is contained in:
2026-11-22 21:25:45 +01:00
9 changed files with 975 additions and 16 deletions
+2 -1
View File
@@ -13,7 +13,8 @@ src/compose.rs compose (mail-builder): multipart/alternative, attachments, re
src/filename.rs hostile attachment names -> safe names (../, reserved Windows names, bidi controls)
src/thread.rs threading: Message-ID / In-Reply-To / References, normalised-subject fallback
src/rules.rs incoming rules (from/to/subject contains -> move to folder), first match wins; Sieve export
src/sanitize.rs HTML sanitiser (ammonia allow-list), remote images -> placeholders
src/sanitize.rs HTML sanitiser (ammonia allow-list), remote images -> placeholders, the dark reader's colours
src/sanitize/colour.rs CSS colours: parse, WCAG contrast, grey, lighten in hue to 4.5 : 1
src/search.rs search query parser (free text, from:, to:, subject:, has:attachment, is:starred) -> FTS5
tests/ the mandatory tests (fixtures are built in code; no corpora in git)
```
Generated
+1 -1
View File
@@ -184,7 +184,7 @@ dependencies = [
[[package]]
name = "epistula-core"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"ammonia",
"base64",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "epistula-core"
version = "0.1.0"
version = "0.2.0"
edition = "2024"
rust-version = "1.85"
license = "MPL-2.0"
+3 -1
View File
@@ -176,7 +176,9 @@ fn original_html(original: &Parsed) -> String {
})
.collect();
match &original.html {
Some(html) => sanitize(html, &SanitizeOptions { load_remote_images: false, inline_images }).html,
Some(html) => {
sanitize(html, &SanitizeOptions { load_remote_images: false, inline_images, ..Default::default() }).html
}
None => text_to_html(original.text.as_deref().unwrap_or("")),
}
}
+1 -1
View File
@@ -53,6 +53,6 @@ pub use compose::{Draft, OutAttachment, ReplyMode, compose, forward, message_id,
pub use filename::safe_filename;
pub use mime::{Attachment, ParseError, Parsed, parse};
pub use rules::{Condition, Field, Rule, RuleMessage, first_match, to_sieve};
pub use sanitize::{SanitizeOptions, Sanitized, sanitize, text_to_html};
pub use sanitize::{Colours, DarkPalette, SanitizeOptions, Sanitized, sanitize, text_to_html};
pub use search::{Query, parse_query};
pub use thread::{ThreadInput, normalize_subject, thread};
+168 -9
View File
@@ -5,12 +5,24 @@
//! Defence in depth after ammonia: in text and attribute values `:` and `=` are written as `:` and `=`.
//! A browser shows and follows exactly the same thing, but the output can never contain the literal sequences
//! `javascript:` or ` onclick=`, whatever a later bug in a filter lets through.
//!
//! Colours: `Colours::Original` keeps the mail's own (sanitised as above). `Colours::Dark` writes it for a dark
//! reader: backgrounds removed (a highlight on a few words becomes the palette's tint), black, grey and white
//! text removed, other text colours lightened in their own hue to `MIN_CONTRAST` on the body, borders in the rule
//! colour, links with no colour, background or decoration of their own, `!important` removed. Images are never
//! touched. `Sanitized::colours_changed` says whether that changed the look (the reader then offers the original).
mod colour;
pub use colour::{
GREY_CHROMA, GREY_SATURATION, MIN_CONTRAST, Rgb, contrast, is_grey, luminance, parse_colour, readable_on,
};
use base64::Engine;
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
/// What an inline `cid:` image resolves to.
pub struct InlineImage<'a> {
@@ -24,6 +36,46 @@ pub struct SanitizeOptions<'a> {
pub load_remote_images: bool,
/// Inline parts by Content-ID (no brackets): `cid:` sources become `data:` URIs.
pub inline_images: HashMap<String, InlineImage<'a>>,
/// The colours to write for: the mail's own (the default), or a dark reader's.
pub colours: Colours,
}
/// Which colours the output carries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Colours {
/// The mail's own colours, as v0.1.0 wrote them (byte for byte).
#[default]
Original,
/// Rewritten for a dark body: see the module docs.
Dark(DarkPalette),
}
/// The reader's colours the dark output is written for. `body` must be dark: white reaches `MIN_CONTRAST` on it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DarkPalette {
/// The body's background: every kept text colour reaches `MIN_CONTRAST` on it.
pub body: Rgb,
/// Every border and rule.
pub rule: Rgb,
/// A highlight on a few words, drawn at `highlight_alpha_percent` over the body.
pub highlight: Rgb,
pub highlight_alpha_percent: u8,
}
impl DarkPalette {
/// Epistula's dark Domi theme: `--reader-bg` `#111726`, `--reader-rule` `#6b7a99`, the tint of `--second`.
pub const DOMI: Self = Self {
body: Rgb::new(0x11, 0x17, 0x26),
rule: Rgb::new(0x6b, 0x7a, 0x99),
highlight: Rgb::new(244, 201, 93),
highlight_alpha_percent: 13,
};
/// The highlight as a CSS value, e.g. `rgba(244, 201, 93, 0.13)`.
pub fn highlight_css(&self) -> String {
let h = self.highlight;
format!("rgba({}, {}, {}, {})", h.r, h.g, h.b, f64::from(self.highlight_alpha_percent.min(100)) / 100.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -31,11 +83,52 @@ pub struct Sanitized {
pub html: String,
/// Remote images replaced by the placeholder: show "Load images" only when this is not zero.
pub blocked_images: usize,
/// `Colours::Dark` changed the look: a background was removed or a colour lightened. Black, grey or white
/// text removed is no change (the body's white is what it meant). Always `false` for `Colours::Original`.
pub colours_changed: bool,
}
/// The placeholder for a blocked remote image (a small grey square, SVG in a data URI: no script runs in `<img>`).
pub const BLOCKED_IMAGE_SRC: &str = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCI+PHJlY3Qgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiBmaWxsPSIjNDQ0Ii8+PC9zdmc+";
/// The same placeholder in the dark (`#6b7a99`: `#444` is 1.9 : 1 on the dark body).
pub const BLOCKED_IMAGE_SRC_DARK: &str = "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCI+PHJlY3Qgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiBmaWxsPSIjNmI3YTk5Ii8+PC9zdmc+";
/// Where a background is a highlight on a few words (it becomes the palette's tint), not a block's paint.
const HIGHLIGHT_TAGS: &[&str] = &["span", "font", "mark", "b", "i", "u", "strong", "em"];
/// Border shorthands: their colour words are replaced by the rule colour.
const BORDER_SHORTHANDS: &[&str] = &["border", "border-top", "border-right", "border-bottom", "border-left"];
/// The dark rewrite's state for one `sanitize` call.
struct Dark {
palette: DarkPalette,
changed: Arc<AtomicBool>,
}
impl Dark {
fn change(&self) {
self.changed.store(true, Ordering::Relaxed);
}
/// A text colour: `None` (removed) for grey or unreadable values, else readable on the body.
fn text_colour(&self, value: &str) -> Option<Rgb> {
let c = parse_colour(value).filter(|c| !is_grey(*c))?;
let out = readable_on(c, self.palette.body);
if out != c {
self.change();
}
Some(out)
}
/// A removed background: a change unless it named nothing (`none`, `transparent`, …).
fn removed_background(&self, value: &str) {
if !colour::names_nothing(value) {
self.change();
}
}
}
/// Inline images larger than this are not embedded (they stay attachments).
pub const MAX_INLINE_IMAGE_BYTES: usize = 10 * 1024 * 1024;
@@ -252,6 +345,11 @@ pub fn sanitize(html: &str, options: &SanitizeOptions<'_>) -> Sanitized {
.collect(),
);
let load_remote = options.load_remote_images;
let changed = Arc::new(AtomicBool::new(false));
let dark = match options.colours {
Colours::Original => None,
Colours::Dark(palette) => Some(Dark { palette, changed: changed.clone() }),
};
let mut builder = ammonia::Builder::empty();
builder
@@ -272,11 +370,15 @@ pub fn sanitize(html: &str, options: &SanitizeOptions<'_>) -> Sanitized {
{
let blocked = blocked.clone();
builder.attribute_filter(move |element, attribute, value| {
filter_attribute(element, attribute, value, load_remote, &inline, &blocked)
filter_attribute(element, attribute, value, load_remote, &inline, &blocked, dark.as_ref())
});
}
let cleaned = builder.clean(html).to_string();
Sanitized { html: escape_punctuation(&cleaned), blocked_images: blocked.load(Ordering::Relaxed) }
Sanitized {
html: escape_punctuation(&cleaned),
blocked_images: blocked.load(Ordering::Relaxed),
colours_changed: changed.load(Ordering::Relaxed),
}
}
/// The scheme of a URL as a browser would read it: ASCII whitespace and controls removed, lower case.
@@ -292,6 +394,7 @@ fn filter_attribute<'u>(
load_remote: bool,
inline: &HashMap<String, String>,
blocked: &AtomicUsize,
dark: Option<&Dark>,
) -> Option<Cow<'u, str>> {
match (element, attribute) {
("img", "src") => {
@@ -309,7 +412,7 @@ fn filter_attribute<'u>(
return Some(Cow::Borrowed(value));
}
blocked.fetch_add(1, Ordering::Relaxed);
return Some(Cow::Borrowed(BLOCKED_IMAGE_SRC));
return Some(Cow::Borrowed(if dark.is_some() { BLOCKED_IMAGE_SRC_DARK } else { BLOCKED_IMAGE_SRC }));
}
None
}
@@ -318,18 +421,32 @@ fn filter_attribute<'u>(
(url.starts_with("https:") || url.starts_with("http:") || url.starts_with("mailto:"))
.then_some(Cow::Borrowed(value))
}
(_, "style") => filter_css(value).map(Cow::Owned),
(_, "style") => filter_css(value, element, dark).map(Cow::Owned),
(_, "bgcolor") if dark.is_some() => {
if let Some(d) = dark {
d.removed_background(value);
}
None
}
("font", "color") if dark.is_some() => {
dark.and_then(|d| d.text_colour(value)).map(|c| Cow::Owned(c.to_string()))
}
_ => Some(Cow::Borrowed(value)),
}
}
/// Keeps only allow-listed properties whose values cannot run or load anything.
fn filter_css(style: &str) -> Option<String> {
/// Keeps only allow-listed properties whose values cannot run or load anything; in the dark, rewrites colours.
fn filter_css(style: &str, element: &str, dark: Option<&Dark>) -> Option<String> {
let mut kept = Vec::new();
let mut tinted = false;
for declaration in style.split(';') {
let Some((property, value)) = declaration.split_once(':') else { continue };
let property = property.trim().to_ascii_lowercase();
let value = value.trim();
let mut value = value.trim();
if dark.is_some() {
// `!important` (and anything else after a `!`) goes, so the reader's own rules always win.
value = value.split('!').next().unwrap_or("").trim_end();
}
let lower = value.to_ascii_lowercase();
if !CSS_PROPERTIES.contains(&property.as_str())
|| value.is_empty()
@@ -338,11 +455,53 @@ fn filter_css(style: &str) -> Option<String> {
{
continue;
}
kept.push(format!("{property}: {value}"));
match dark {
None => kept.push(format!("{property}: {value}")),
Some(d) => kept.extend(dark_declaration(&property, value, element, d, &mut tinted)),
}
}
(!kept.is_empty()).then(|| kept.join("; "))
}
/// A word of a CSS value that is a colour (`transparent` and `currentcolor` included).
fn is_colour_word(word: &str) -> bool {
parse_colour(word).is_some()
|| word.eq_ignore_ascii_case("transparent")
|| word.eq_ignore_ascii_case("currentcolor")
}
/// One allowed declaration, rewritten for the dark (`None`: removed).
fn dark_declaration(property: &str, value: &str, element: &str, dark: &Dark, tinted: &mut bool) -> Option<String> {
let rule = dark.palette.rule;
match property {
"background" | "background-color" => {
dark.removed_background(value);
let highlight = HIGHLIGHT_TAGS.contains(&element)
&& colour::words(value).iter().filter_map(|w| parse_colour(w)).any(|c| !is_grey(c));
if highlight && !*tinted {
*tinted = true;
return Some(format!("background-color: {}", dark.palette.highlight_css()));
}
None
}
// Links are the reader's: its colour, its underline.
"color" | "text-decoration" if element == "a" => None,
"color" => dark.text_colour(value).map(|c| format!("color: {c}")),
"text-decoration" => {
let rest: Vec<&str> = colour::words(value).into_iter().filter(|w| !is_colour_word(w)).collect();
(!rest.is_empty()).then(|| format!("{property}: {}", rest.join(" ")))
}
p if p.starts_with("border") && p.ends_with("-color") => Some(format!("{property}: {rule}")),
p if BORDER_SHORTHANDS.contains(&p) => {
let mut rest: Vec<String> =
colour::words(value).into_iter().filter(|w| !is_colour_word(w)).map(String::from).collect();
rest.push(rule.to_string());
Some(format!("{property}: {}", rest.join(" ")))
}
_ => Some(format!("{property}: {value}")),
}
}
/// Writes `:` and `=` in text and attribute values as character references (see the module docs).
/// The input is ammonia's serialisation: attribute values are always double-quoted and text never holds a raw `<`.
fn escape_punctuation(html: &str) -> String {
+399
View File
@@ -0,0 +1,399 @@
//! CSS colours as a mail writes them, and the arithmetic of the dark reader: WCAG contrast, "is this grey",
//! and lightening a colour in its own hue until it reads on the body.
//!
//! A mail's colour is hostile input like the rest of it: anything this parser does not know is `None`, and the
//! sanitiser then drops it.
use std::fmt;
/// An opaque sRGB colour. Written (`Display`) as `#rrggbb`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Rgb {
pub r: u8,
pub g: u8,
pub b: u8,
}
impl Rgb {
pub const fn new(r: u8, g: u8, b: u8) -> Self {
Self { r, g, b }
}
}
impl fmt::Display for Rgb {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "#{:02x}{:02x}{:02x}", self.r, self.g, self.b)
}
}
/// The contrast every text colour of a dark mail reaches on the body (WCAG AA for body text).
pub const MIN_CONTRAST: f64 = 4.5;
/// Under this HSL saturation a colour is a grey (black and white included): the sanitiser removes it.
pub const GREY_SATURATION: f64 = 0.10;
/// Under this chroma (the largest channel minus the smallest, of 255) a colour is a grey too: near-black and
/// near-white tints such as `#1b2130` or `#fff8f0` have a high HSL saturation but read as black and white.
pub const GREY_CHROMA: f64 = 0.10;
/// How far one step of lightening moves the HSL lightness.
const LIGHTEN_STEP: f64 = 0.01;
fn linear(channel: u8) -> f64 {
let s = f64::from(channel) / 255.0;
if s <= 0.04045 { s / 12.92 } else { ((s + 0.055) / 1.055).powf(2.4) }
}
/// WCAG relative luminance.
pub fn luminance(c: Rgb) -> f64 {
0.2126 * linear(c.r) + 0.7152 * linear(c.g) + 0.0722 * linear(c.b)
}
/// WCAG contrast ratio, 1 to 21.
pub fn contrast(a: Rgb, b: Rgb) -> f64 {
let (x, y) = (luminance(a), luminance(b));
(x.max(y) + 0.05) / (x.min(y) + 0.05)
}
/// Hue in degrees, saturation and lightness in 0..=1.
fn to_hsl(c: Rgb) -> (f64, f64, f64) {
let (r, g, b) = (f64::from(c.r) / 255.0, f64::from(c.g) / 255.0, f64::from(c.b) / 255.0);
let max = r.max(g).max(b);
let min = r.min(g).min(b);
let l = (max + min) / 2.0;
let d = max - min;
if d == 0.0 {
return (0.0, 0.0, l);
}
let s = d / (1.0 - (2.0 * l - 1.0).abs());
let h = if max == r {
60.0 * (((g - b) / d).rem_euclid(6.0))
} else if max == g {
60.0 * ((b - r) / d + 2.0)
} else {
60.0 * ((r - g) / d + 4.0)
};
(h, s.min(1.0), l)
}
fn from_hsl(h: f64, s: f64, l: f64) -> Rgb {
let c = (1.0 - (2.0 * l - 1.0).abs()) * s;
let hp = h.rem_euclid(360.0) / 60.0;
let x = c * (1.0 - (hp.rem_euclid(2.0) - 1.0).abs());
let (r, g, b) = match hp as u32 {
0 => (c, x, 0.0),
1 => (x, c, 0.0),
2 => (0.0, c, x),
3 => (0.0, x, c),
4 => (x, 0.0, c),
_ => (c, 0.0, x),
};
let m = l - c / 2.0;
let byte = |v: f64| ((v + m) * 255.0).round().clamp(0.0, 255.0) as u8;
Rgb::new(byte(r), byte(g), byte(b))
}
/// Black, grey or white: removed in the dark, so the text is the body's own.
pub fn is_grey(c: Rgb) -> bool {
let (_, s, _) = to_hsl(c);
let chroma = f64::from(c.r.max(c.g).max(c.b) - c.r.min(c.g).min(c.b)) / 255.0;
s < GREY_SATURATION || chroma < GREY_CHROMA
}
/// The colour itself if it reaches `MIN_CONTRAST` on `body`; else the same hue and saturation, lightened step by
/// step until it does. `body` must be dark (white reaches 4.5 : 1 on it), as the dark palette's is.
pub fn readable_on(c: Rgb, body: Rgb) -> Rgb {
if contrast(c, body) >= MIN_CONTRAST {
return c;
}
let (h, s, l) = to_hsl(c);
let mut step = 1.0;
loop {
let lightness = (l + LIGHTEN_STEP * step).min(1.0);
let out = from_hsl(h, s, lightness);
if contrast(out, body) >= MIN_CONTRAST || lightness >= 1.0 {
return out;
}
step += 1.0;
}
}
/// Values that name no colour at all: a background of these was not there to remove.
pub(super) fn names_nothing(value: &str) -> bool {
matches!(
value.trim().to_ascii_lowercase().as_str(),
"" | "none" | "transparent" | "inherit" | "initial" | "unset" | "revert" | "currentcolor" | "0"
)
}
/// The words of a CSS value, split on spaces outside parentheses (`1px solid rgb(1, 2, 3)` is three words).
pub(super) fn words(value: &str) -> Vec<&str> {
let mut out = Vec::new();
let mut depth = 0u32;
let mut start = None;
for (i, c) in value.char_indices() {
match c {
'(' => depth += 1,
')' => depth = depth.saturating_sub(1),
_ => {}
}
if c.is_ascii_whitespace() && depth == 0 {
if let Some(s) = start.take() {
out.push(&value[s..i]);
}
} else if start.is_none() {
start = Some(i);
}
}
if let Some(s) = start {
out.push(&value[s..]);
}
out
}
/// A CSS colour: `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()`/`rgba()`, `hsl()`/`hsla()` (commas or spaces,
/// numbers or percentages) or a named colour. Alpha is ignored (text a mail makes transparent is shown).
/// `transparent`, `currentcolor` and anything else are `None`.
pub fn parse_colour(value: &str) -> Option<Rgb> {
let v = value.trim().to_ascii_lowercase();
if let Some(hex) = v.strip_prefix('#') {
return parse_hex(hex);
}
if let Some(args) = v.strip_prefix("rgba(").or_else(|| v.strip_prefix("rgb(")) {
let n = arguments(args)?;
let channel = |s: &str| -> Option<u8> {
let x = match s.strip_suffix('%') {
Some(p) => p.parse::<f64>().ok()? * 2.55,
None => s.parse::<f64>().ok()?,
};
x.is_finite().then(|| x.round().clamp(0.0, 255.0) as u8)
};
return Some(Rgb::new(channel(n[0])?, channel(n[1])?, channel(n[2])?));
}
if let Some(args) = v.strip_prefix("hsla(").or_else(|| v.strip_prefix("hsl(")) {
let n = arguments(args)?;
let h = n[0].strip_suffix("deg").unwrap_or(n[0]).parse::<f64>().ok()?;
let percent = |s: &str| -> Option<f64> {
s.strip_suffix('%').unwrap_or(s).parse::<f64>().ok().map(|p| (p / 100.0).clamp(0.0, 1.0))
};
let (s, l) = (percent(n[1])?, percent(n[2])?);
return h.is_finite().then(|| from_hsl(h, s, l));
}
NAMED.iter().find(|(name, _)| *name == v).map(|(_, hex)| Rgb::new((hex >> 16) as u8, (hex >> 8) as u8, *hex as u8))
}
/// The 3 or 4 arguments of `rgb(…)` / `hsl(…)`, up to the closing parenthesis, which must end the value.
fn arguments(args: &str) -> Option<Vec<&str>> {
let inner = args.strip_suffix(')')?;
let n: Vec<&str> = inner.split([',', ' ', '/']).filter(|s| !s.is_empty()).collect();
(n.len() == 3 || n.len() == 4).then_some(n)
}
fn parse_hex(hex: &str) -> Option<Rgb> {
if !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let digit = |i: usize| u8::from_str_radix(&hex[i..i + 1], 16).ok();
let pair = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).ok();
match hex.len() {
3 | 4 => Some(Rgb::new(digit(0)? * 17, digit(1)? * 17, digit(2)? * 17)),
6 | 8 => Some(Rgb::new(pair(0)?, pair(2)?, pair(4)?)),
_ => None,
}
}
/// The CSS named colours (CSS Color 4), but `transparent`.
const NAMED: &[(&str, u32)] = &[
("aliceblue", 0xf0f8ff),
("antiquewhite", 0xfaebd7),
("aqua", 0x00ffff),
("aquamarine", 0x7fffd4),
("azure", 0xf0ffff),
("beige", 0xf5f5dc),
("bisque", 0xffe4c4),
("black", 0x000000),
("blanchedalmond", 0xffebcd),
("blue", 0x0000ff),
("blueviolet", 0x8a2be2),
("brown", 0xa52a2a),
("burlywood", 0xdeb887),
("cadetblue", 0x5f9ea0),
("chartreuse", 0x7fff00),
("chocolate", 0xd2691e),
("coral", 0xff7f50),
("cornflowerblue", 0x6495ed),
("cornsilk", 0xfff8dc),
("crimson", 0xdc143c),
("cyan", 0x00ffff),
("darkblue", 0x00008b),
("darkcyan", 0x008b8b),
("darkgoldenrod", 0xb8860b),
("darkgray", 0xa9a9a9),
("darkgreen", 0x006400),
("darkgrey", 0xa9a9a9),
("darkkhaki", 0xbdb76b),
("darkmagenta", 0x8b008b),
("darkolivegreen", 0x556b2f),
("darkorange", 0xff8c00),
("darkorchid", 0x9932cc),
("darkred", 0x8b0000),
("darksalmon", 0xe9967a),
("darkseagreen", 0x8fbc8f),
("darkslateblue", 0x483d8b),
("darkslategray", 0x2f4f4f),
("darkslategrey", 0x2f4f4f),
("darkturquoise", 0x00ced1),
("darkviolet", 0x9400d3),
("deeppink", 0xff1493),
("deepskyblue", 0x00bfff),
("dimgray", 0x696969),
("dimgrey", 0x696969),
("dodgerblue", 0x1e90ff),
("firebrick", 0xb22222),
("floralwhite", 0xfffaf0),
("forestgreen", 0x228b22),
("fuchsia", 0xff00ff),
("gainsboro", 0xdcdcdc),
("ghostwhite", 0xf8f8ff),
("gold", 0xffd700),
("goldenrod", 0xdaa520),
("gray", 0x808080),
("green", 0x008000),
("greenyellow", 0xadff2f),
("grey", 0x808080),
("honeydew", 0xf0fff0),
("hotpink", 0xff69b4),
("indianred", 0xcd5c5c),
("indigo", 0x4b0082),
("ivory", 0xfffff0),
("khaki", 0xf0e68c),
("lavender", 0xe6e6fa),
("lavenderblush", 0xfff0f5),
("lawngreen", 0x7cfc00),
("lemonchiffon", 0xfffacd),
("lightblue", 0xadd8e6),
("lightcoral", 0xf08080),
("lightcyan", 0xe0ffff),
("lightgoldenrodyellow", 0xfafad2),
("lightgray", 0xd3d3d3),
("lightgreen", 0x90ee90),
("lightgrey", 0xd3d3d3),
("lightpink", 0xffb6c1),
("lightsalmon", 0xffa07a),
("lightseagreen", 0x20b2aa),
("lightskyblue", 0x87cefa),
("lightslategray", 0x778899),
("lightslategrey", 0x778899),
("lightsteelblue", 0xb0c4de),
("lightyellow", 0xffffe0),
("lime", 0x00ff00),
("limegreen", 0x32cd32),
("linen", 0xfaf0e6),
("magenta", 0xff00ff),
("maroon", 0x800000),
("mediumaquamarine", 0x66cdaa),
("mediumblue", 0x0000cd),
("mediumorchid", 0xba55d3),
("mediumpurple", 0x9370db),
("mediumseagreen", 0x3cb371),
("mediumslateblue", 0x7b68ee),
("mediumspringgreen", 0x00fa9a),
("mediumturquoise", 0x48d1cc),
("mediumvioletred", 0xc71585),
("midnightblue", 0x191970),
("mintcream", 0xf5fffa),
("mistyrose", 0xffe4e1),
("moccasin", 0xffe4b5),
("navajowhite", 0xffdead),
("navy", 0x000080),
("oldlace", 0xfdf5e6),
("olive", 0x808000),
("olivedrab", 0x6b8e23),
("orange", 0xffa500),
("orangered", 0xff4500),
("orchid", 0xda70d6),
("palegoldenrod", 0xeee8aa),
("palegreen", 0x98fb98),
("paleturquoise", 0xafeeee),
("palevioletred", 0xdb7093),
("papayawhip", 0xffefd5),
("peachpuff", 0xffdab9),
("peru", 0xcd853f),
("pink", 0xffc0cb),
("plum", 0xdda0dd),
("powderblue", 0xb0e0e6),
("purple", 0x800080),
("rebeccapurple", 0x663399),
("red", 0xff0000),
("rosybrown", 0xbc8f8f),
("royalblue", 0x4169e1),
("saddlebrown", 0x8b4513),
("salmon", 0xfa8072),
("sandybrown", 0xf4a460),
("seagreen", 0x2e8b57),
("seashell", 0xfff5ee),
("sienna", 0xa0522d),
("silver", 0xc0c0c0),
("skyblue", 0x87ceeb),
("slateblue", 0x6a5acd),
("slategray", 0x708090),
("slategrey", 0x708090),
("snow", 0xfffafa),
("springgreen", 0x00ff7f),
("steelblue", 0x4682b4),
("tan", 0xd2b48c),
("teal", 0x008080),
("thistle", 0xd8bfd8),
("tomato", 0xff6347),
("turquoise", 0x40e0d0),
("violet", 0xee82ee),
("wheat", 0xf5deb3),
("white", 0xffffff),
("whitesmoke", 0xf5f5f5),
("yellow", 0xffff00),
("yellowgreen", 0x9acd32),
];
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hsl_round_trips_every_grey_and_primary() {
for c in [
Rgb::new(0, 0, 0),
Rgb::new(255, 255, 255),
Rgb::new(255, 0, 0),
Rgb::new(0, 128, 0),
Rgb::new(0x1a, 0x43, 0xa6),
] {
let (h, s, l) = to_hsl(c);
assert_eq!(from_hsl(h, s, l), c);
}
}
#[test]
fn words_keep_functions_whole() {
assert_eq!(words(" 1px solid rgb(1, 2, 3) "), ["1px", "solid", "rgb(1, 2, 3)"]);
assert_eq!(words(""), Vec::<&str>::new());
}
#[test]
fn hostile_colour_values_are_none_not_a_panic() {
for v in [
"#",
"#ééé",
"rgb(",
"rgb()",
"rgb(1e999, 0, 0)",
"rgb(nan, 0, 0)",
"hsl(inf, 1%, 1%)",
"rgb(1,2,3,4,5)",
"ĉ",
] {
let _ = parse_colour(v);
}
assert_eq!(parse_colour("rgb(1e999, 0, 0)"), None);
assert_eq!(parse_colour("hsl(inf, 1%, 1%)"), None);
assert_eq!(parse_colour("#ééé"), None);
assert_eq!(parse_colour(" RGB(255 0 0 / 50%) "), Some(Rgb::new(255, 0, 0)));
assert_eq!(parse_colour("#0f08"), Some(Rgb::new(0, 255, 0)));
}
}
+4 -2
View File
@@ -120,8 +120,10 @@ fn inline_cid_image_becomes_a_data_uri_in_the_reader() {
inline.content_id.clone().unwrap(),
InlineImage { content_type: &inline.content_type, data: &inline.data },
);
let out =
sanitize(m.html.as_deref().unwrap(), &SanitizeOptions { load_remote_images: false, inline_images: images });
let out = sanitize(
m.html.as_deref().unwrap(),
&SanitizeOptions { load_remote_images: false, inline_images: images, ..Default::default() },
);
assert!(out.html.contains("data&#58;image/png;base64,"), "{}", out.html);
assert!(!out.html.contains("cid"), "{}", out.html);
assert_eq!(out.blocked_images, 0);
+396
View File
@@ -390,3 +390,399 @@ proptest! {
prop_assert_eq!(dangerous(&twice), None);
}
}
// ---------- the dark reader (the app's docs/06_screens.md, "Making a mail's HTML dark") ----------
use epistula_core::sanitize::{
BLOCKED_IMAGE_SRC_DARK, Colours, DarkPalette, MIN_CONTRAST, Rgb, contrast, is_grey, parse_colour,
};
const PALETTE: DarkPalette = DarkPalette::DOMI;
fn dark(html: &str) -> epistula_core::Sanitized {
sanitize(html, &SanitizeOptions { colours: Colours::Dark(PALETTE), ..Default::default() })
}
/// A coloured mail: a white table, a red border, grey text, a green font, a highlight, a link drawn as a button, a
/// remote image, white text, a light rule.
const COLOURED: &str = "<table bgcolor=\"#ffffff\" style=\"background-color: #fafafa !important; border: 1px solid #c0392b\"><tr><td style=\"color: #333333; background: yellow\"><font color=\"#2e7d32\">green</font> <span style=\"background-color: #ffff00; color: #1a43a6\">hi</span> <a href=\"https://example.cz\" style=\"color: red; text-decoration: none; background: #0055ff\">button</a> <img src=\"https://example.cz/x.png\" width=\"20\"></td></tr></table><p style=\"color: white\">hidden</p><hr style=\"border-color: #ddd\">";
/// What v0.1.0 wrote for `COLOURED` (recorded before the dark option existed).
const COLOURED_ORIGINAL: &str = "<table bgcolor=\"#ffffff\" style=\"border&#58; 1px solid #c0392b\"><tbody><tr><td style=\"color&#58; #333333; background&#58; yellow\"><font color=\"#2e7d32\">green</font> <span style=\"background-color&#58; #ffff00; color&#58; #1a43a6\">hi</span> <a href=\"https&#58;//example.cz\" style=\"color&#58; red; text-decoration&#58; none; background&#58; #0055ff\" rel=\"noopener noreferrer\">button</a> <img src=\"data&#58;image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCI+PHJlY3Qgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0IiBmaWxsPSIjNDQ0Ii8+PC9zdmc+\" width=\"20\"></td></tr></tbody></table><p style=\"color&#58; white\">hidden</p><hr style=\"border-color&#58; #ddd\">";
/// Every CSS declaration of every `style` in the output, with the tag it sits on.
fn declarations(out: &str) -> Vec<(String, String, String)> {
let mut all = Vec::new();
for (tag, attrs) in tags(out) {
for (attr, value) in attrs {
if attr != "style" {
continue;
}
for d in value.split(';') {
if let Some((p, v)) = d.split_once(':') {
all.push((tag.clone(), p.trim().to_ascii_lowercase(), v.trim().to_ascii_lowercase()));
}
}
}
}
all
}
fn tint() -> String {
PALETTE.highlight_css()
}
/// The first `color: …` value in the decoded output.
fn first_colour(html: &str) -> Option<String> {
html.split("color: ").nth(1).and_then(|s| s.split(['"', ';']).next()).map(String::from)
}
/// The dark rules the output must keep, whatever the input: no background but the highlight tint on words, every
/// text colour readable on the body and never grey, borders in the rule colour, links without colours or
/// decorations of their own, no `!important`, no `bgcolor`.
fn dark_violation(out: &str) -> Option<String> {
for (tag, attrs) in tags(out) {
for (attr, value) in &attrs {
if attr == "bgcolor" {
return Some(format!("bgcolor on {tag}"));
}
if tag == "font" && attr == "color" {
match parse_colour(value) {
Some(c) if !is_grey(c) && contrast(c, PALETTE.body) >= MIN_CONTRAST => {}
_ => return Some(format!("font color {value:?}")),
}
}
}
}
let rule = format!("{}", PALETTE.rule);
for (tag, property, value) in declarations(out) {
if value.contains('!') {
return Some(format!("{property}: {value} keeps a !"));
}
if property.starts_with("background") {
if property != "background-color" || value != tint() {
return Some(format!("{tag} {property}: {value}"));
}
if !matches!(tag.as_str(), "span" | "font" | "mark" | "b" | "i" | "u" | "strong" | "em") {
return Some(format!("a highlight on {tag}"));
}
}
if property == "color" {
if tag == "a" {
return Some("a link with its own colour".into());
}
match parse_colour(&value) {
Some(c) if !is_grey(c) && contrast(c, PALETTE.body) >= MIN_CONTRAST => {}
_ => return Some(format!("{tag} color {value:?}")),
}
}
if property.starts_with("border") && property.ends_with("color") && value != rule {
return Some(format!("{tag} {property}: {value}"));
}
if property.starts_with("border")
&& !property.ends_with("color")
&& matches!(property.as_str(), "border" | "border-top" | "border-right" | "border-bottom" | "border-left")
{
let colours: Vec<&str> = value.split_whitespace().filter(|t| parse_colour(t).is_some()).collect();
if colours != [rule.as_str()] {
return Some(format!("{tag} {property}: {value}"));
}
}
if tag == "a" && property == "text-decoration" {
return Some("a link that may lose its underline".into());
}
if property == "text-decoration" && value.split_whitespace().any(|t| parse_colour(t).is_some()) {
return Some(format!("a coloured decoration {value:?}"));
}
}
None
}
#[test]
fn original_is_byte_for_byte_what_v0_1_0_wrote() {
let out = sanitize(COLOURED, &SanitizeOptions::default());
assert_eq!(out.html, COLOURED_ORIGINAL);
assert_eq!(out.blocked_images, 1);
assert!(!out.colours_changed, "the original look is never a change");
let explicit = sanitize(COLOURED, &SanitizeOptions { colours: Colours::Original, ..Default::default() });
assert_eq!(explicit.html, COLOURED_ORIGINAL);
}
#[test]
fn dark_rewrites_a_coloured_mail() {
let out = dark(COLOURED);
assert_eq!(dark_violation(&out.html), None, "{}", out.html);
assert!(out.colours_changed, "backgrounds were removed");
assert_eq!(out.blocked_images, 1);
let html = decoded(&out.html);
// The white table and the yellow cell lose their backgrounds; the highlight on words becomes the tint.
assert!(!html.contains("bgcolor") && !html.contains("yellow") && !html.contains("#fafafa"), "{html}");
assert!(html.contains(&format!("<span style=\"background-color: {}", tint())), "{html}");
// Grey and white text go: the body's white shows.
assert!(!html.contains("#333333") && !html.contains("color: white"), "{html}");
// The green keeps its hue, lightened; the link keeps no colour, no background, no decoration.
assert!(html.contains("<font color=\"#") && !html.contains("#2e7d32"), "{html}");
assert!(html.contains("<a href=\"https://example.cz\" rel=\"noopener noreferrer\">button</a>"), "{html}");
// Borders and the rule take the rule colour.
assert!(html.contains(&format!("border: 1px solid {}", PALETTE.rule)), "{html}");
assert!(html.contains(&format!("<hr style=\"border-color: {}\">", PALETTE.rule)), "{html}");
// The blocked image is the dark placeholder, and the image itself is untouched (never inverted or dimmed).
assert!(html.contains(&format!("<img src=\"{BLOCKED_IMAGE_SRC_DARK}\" width=\"20\">")), "{html}");
assert!(!html.contains("filter") && !html.contains("invert") && !html.contains("opacity"), "{html}");
}
#[test]
fn colours_are_lightened_in_their_hue_to_the_minimum_contrast() {
// The examples of the design: exactly the drawn colours (HSL lightness raised in steps of 1 %).
for (from, drawn) in [("#c0392b", "#d7594c"), ("#2e7d32", "#36933b"), ("#1a43a6", "#517ce4")] {
let out = dark(&format!("<p style=\"color: {from}\">x</p>"));
assert!(out.colours_changed, "{from} was lightened");
let html = decoded(&out.html);
let value = first_colour(&html).unwrap_or_default();
let got = parse_colour(&value).unwrap_or_else(|| panic!("{from}: no colour in {html}"));
assert!(contrast(got, PALETTE.body) >= MIN_CONTRAST, "{from} -> {got}");
assert!(contrast(got, PALETTE.body) < MIN_CONTRAST + 0.4, "{from} -> {got}: lightened more than needed");
assert_eq!(got.to_string(), drawn, "{from}");
}
// A colour that is already readable stays as it is, and is no change.
let light = dark("<p style=\"color: #8fd8b5\">x</p>");
assert!(decoded(&light.html).contains("color: #8fd8b5"), "{}", light.html);
assert!(!light.colours_changed);
}
#[test]
fn black_grey_and_white_text_goes_and_is_no_change() {
for colour in [
"black",
"#000",
"#333",
"#777777",
"grey",
"rgb(128, 128, 128)",
"white",
"#fff",
"#fdfdfd",
"#1b2130",
"rgba(0,0,0,0.8)",
"transparent",
"inherit",
"currentColor",
"hsl(0, 5%, 40%)",
] {
let out =
dark(&format!("<p style=\"color: {colour}; font-size: 14px\">x</p><font color=\"{colour}\">y</font>"));
let html = decoded(&out.html);
assert!(!html.contains("color"), "{colour}: {html}");
assert!(html.contains("font-size: 14px"), "{colour}: everything else stays ({html})");
assert!(!out.colours_changed, "{colour}: only grey text is nothing to restore");
}
}
#[test]
fn a_colour_that_cannot_be_read_is_removed() {
for colour in ["notacolour", "#12", "#gggggg", "rgb(1,2)", "red green"] {
let html = decoded(&dark(&format!("<p style=\"color: {colour}\">x</p>")).html);
assert!(!html.contains("color"), "{colour}: {html}");
}
}
#[test]
fn important_is_removed_so_the_reader_wins() {
let out = dark("<p style=\"color: #c0392b !important; font-weight: bold ! IMPORTANT\">x</p>");
let html = decoded(&out.html).to_ascii_lowercase();
assert!(!html.contains("important") && !html.contains('!'), "{html}");
assert!(html.contains("font-weight: bold"), "{html}");
assert!(html.contains("color: #"), "the colour survives without !important: {html}");
}
#[test]
fn a_highlight_on_words_becomes_the_tint_and_blocks_lose_theirs() {
for tag in ["span", "font", "mark", "b", "i", "u"] {
let out = dark(&format!("<{tag} style=\"background: #ffeb3b\">x</{tag}>"));
assert!(decoded(&out.html).contains(&format!("background-color: {}", tint())), "{tag}: {}", out.html);
assert!(out.colours_changed);
}
for tag in ["div", "p", "td"] {
let html = decoded(
&dark(&format!("<table><tr><td><{tag} style=\"background-color: #ffeb3b\">x</{tag}></td></tr></table>"))
.html,
);
assert!(!html.contains("background"), "{tag}: {html}");
}
// A white or grey background on words is no highlight: it just goes.
let white = decoded(&dark("<span style=\"background-color: #ffffff\">x</span>").html);
assert!(!white.contains("background"), "{white}");
// A background of nothing is no change.
let none = dark("<div style=\"background: transparent\">x</div><div style=\"background-color: none\">y</div>");
assert!(!none.colours_changed, "{}", none.html);
}
#[test]
fn bgcolor_is_removed_and_counts_as_a_change() {
let out = dark("<table bgcolor=\"#f4f4f4\"><tr bgcolor=\"red\"><td bgcolor=\"#123456\">x</td></tr></table>");
assert!(!out.html.contains("bgcolor"), "{}", out.html);
assert!(out.colours_changed);
}
#[test]
fn borders_take_the_rule_colour() {
let out = dark(
"<div style=\"border: 2px dashed rgb(255, 0, 0); border-left-color: #00ff00; border-top: 1px solid\">x</div>",
);
let html = decoded(&out.html);
let rule = PALETTE.rule;
assert!(html.contains(&format!("border: 2px dashed {rule}")), "{html}");
assert!(html.contains(&format!("border-left-color: {rule}")), "{html}");
assert!(html.contains(&format!("border-top: 1px solid {rule}")), "{html}");
assert_eq!(dark_violation(&out.html), None, "{html}");
}
#[test]
fn links_are_always_the_theme_s() {
let out = dark(
"<a href=\"https://example.cz\" style=\"color: #fff; background-color: #e91e63; text-decoration: none; padding: 8px 16px; border-radius: 4px\">Buy now</a>",
);
let html = decoded(&out.html);
assert!(!html.contains("color:") && !html.contains("background") && !html.contains("text-decoration"), "{html}");
assert!(html.contains("padding: 8px 16px"), "{html}");
assert!(out.colours_changed, "the button lost its background");
}
#[test]
fn plain_text_has_no_colours_to_change() {
let html = text_to_html("Hello\nhttps://example.cz");
assert!(!html.contains("style"), "{html}");
}
#[test]
fn the_hostile_corpus_is_as_safe_in_the_dark() {
for input in CORPUS {
let raw = dark(input).html;
assert_eq!(dangerous(&raw), None, "input {input:?} output {raw:?}");
let out = decoded(&raw).to_ascii_lowercase();
for bad in FORBIDDEN {
assert!(!out.contains(bad), "input {input:?}\noutput {out:?}\ncontains {bad:?}");
}
assert_eq!(dark_violation(&raw), None, "input {input:?} output {raw:?}");
}
}
#[test]
fn the_palette_is_the_theme_s() {
assert_eq!(PALETTE.body, Rgb { r: 0x11, g: 0x17, b: 0x26 });
assert_eq!(format!("{}", PALETTE.rule), "#6b7a99");
assert_eq!(tint(), "rgba(244, 201, 93, 0.13)");
let prefix = "data:image/svg+xml;base64,";
assert!(BLOCKED_IMAGE_SRC_DARK.starts_with(prefix));
use base64::Engine as _;
let svg = base64::engine::general_purpose::STANDARD.decode(&BLOCKED_IMAGE_SRC_DARK[prefix.len()..]).unwrap();
assert!(String::from_utf8(svg).unwrap().contains("fill=\"#6b7a99\""));
let fg = Rgb { r: 0xee, g: 0xf2, b: 0xfa };
assert!((contrast(fg, PALETTE.body) - 15.9).abs() < 0.1, "{}", contrast(fg, PALETTE.body));
assert!(contrast(Rgb { r: 0x1d, g: 0x4f, b: 0x91 }, PALETTE.body) < 3.0, "the old link colour fails on the dark");
}
fn colour_value() -> impl Strategy<Value = String> {
prop_oneof![
any::<(u8, u8, u8)>().prop_map(|(r, g, b)| format!("#{r:02x}{g:02x}{b:02x}")),
any::<(u8, u8, u8)>().prop_map(|(r, g, b)| format!("rgb({r}, {g}, {b})")),
any::<(u8, u8, u8)>().prop_map(|(r, g, b)| format!("#{:x}{:x}{:x}", r >> 4, g >> 4, b >> 4)),
(0u16..360, 0u8..=100, 0u8..=100).prop_map(|(h, s, l)| format!("hsl({h}, {s}%, {l}%)")),
prop::sample::select(vec![
"red",
"navy",
"maroon",
"teal",
"olive",
"purple",
"orange",
"black",
"white",
"silver",
"gold",
"transparent",
"inherit",
"blah",
])
.prop_map(String::from),
]
}
fn coloured_fragment() -> impl Strategy<Value = String> {
let property = prop::sample::select(vec![
"color",
"background",
"background-color",
"border",
"border-color",
"border-top",
"border-left-color",
"text-decoration",
]);
let tag = prop::sample::select(vec!["p", "span", "div", "td", "font", "a href=\"https://x.example\"", "b", "mark"]);
prop_oneof![
(tag, proptest::collection::vec((property, colour_value(), any::<bool>()), 1..5)).prop_map(|(tag, decls)| {
let style: Vec<String> = decls
.into_iter()
.map(|(p, v, imp)| {
let imp = if imp { " !important" } else { "" };
match p {
"border" | "border-top" => format!("{p}: 1px solid {v}{imp}"),
"text-decoration" => format!("{p}: underline {v}"),
_ => format!("{p}: {v}{imp}"),
}
})
.collect();
let name = tag.split(' ').next().unwrap_or("p");
format!("<{tag} style=\"{}\">x</{name}>", style.join("; "))
}),
colour_value().prop_map(|v| format!("<font color=\"{v}\">f</font>")),
colour_value().prop_map(|v| format!("<table bgcolor=\"{v}\"><tr><td bgcolor=\"{v}\">t</td></tr></table>")),
fragment(),
]
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(2000))]
#[test]
fn no_background_survives_dark_and_every_colour_is_readable(parts in proptest::collection::vec(coloured_fragment(), 0..12)) {
let input = parts.concat();
let out = dark(&input).html;
prop_assert_eq!(dark_violation(&out), None, "input {:?} output {:?}", input, out);
prop_assert_eq!(dangerous(&out), None, "input {:?} output {:?}", input, out);
prop_assert!(!has_event_handler(&out));
}
#[test]
fn a_lightened_colour_keeps_its_hue(r in any::<u8>(), g in any::<u8>(), b in any::<u8>()) {
let from = Rgb { r, g, b };
let out = dark(&format!("<p style=\"color: {from}\">x</p>"));
let html = decoded(&out.html);
match first_colour(&html) {
None => {
prop_assert!(is_grey(from), "{} removed but not grey", from);
prop_assert!(!out.colours_changed);
}
Some(v) => {
let to = parse_colour(&v).unwrap();
prop_assert!(!is_grey(from));
prop_assert!(contrast(to, PALETTE.body) >= MIN_CONTRAST, "{} -> {}", from, to);
prop_assert_eq!(out.colours_changed, to != from);
// Lightened: no channel darker, and the order of the channels kept (the hue).
prop_assert!(to.r >= from.r.saturating_sub(1) && to.g >= from.g.saturating_sub(1) && to.b >= from.b.saturating_sub(1), "{} -> {}", from, to);
let order = |c: Rgb| { let mut v = [(c.r, 0), (c.g, 1), (c.b, 2)]; v.sort(); [v[0].1, v[1].1, v[2].1] };
let distinct = |c: Rgb| c.r.abs_diff(c.g) > 6 && c.g.abs_diff(c.b) > 6 && c.r.abs_diff(c.b) > 6;
if distinct(from) && distinct(to) {
prop_assert_eq!(order(from), order(to), "{} -> {}", from, to);
}
}
}
}
#[test]
fn original_never_reports_a_change(parts in proptest::collection::vec(coloured_fragment(), 0..8)) {
let out = sanitize(&parts.concat(), &SanitizeOptions::default());
prop_assert!(!out.colours_changed);
}
}