diff --git a/README.md b/README.md index 5ba0538..01a901f 100644 --- a/README.md +++ b/README.md @@ -604,6 +604,17 @@ Text shows the first 128 KiB of the file, cut at the end of a line, and Markdown formatted. A file with a zero byte in its first 8,000 bytes isn't text. Page Up, Page Down, Home, End, Shift+Up, Shift+Down and the mouse wheel scroll it. +Code has its comments, strings, keywords and numbers coloured, in the theme's own terminal +colours, each held to 4.5:1 against the page and a code block's background. That's Rust, C and +C++, Python, JavaScript and TypeScript, shell, Go, PHP (with the HTML around it), JSON, TOML, +YAML, HTML and CSS, known by the file's name or a script's `#!` line, and Markdown code blocks +whose fence names one of them. Gannet's own small tokenizers do it, a line at a time and only +for the lines in view, remembering where each line starts (in a comment, a string or a +heredoc). Scrolling then costs about what plain text does; a jump far down, like Ctrl+End, +works out the lines it skipped once, which the 128 KiB limit keeps short. Anything else is +plain text, as before, and the colours change nothing a selection, a copy or a screen reader +gets. + Dragging over text selects it, a double click takes a word and a third the line, Ctrl+A takes all of it, and Ctrl+C copies. To select from the keyboard, F7 turns on caret mode, with a caret at the start of the text in view. The arrows move it by a character or a line, Ctrl+Left and diff --git a/crates/app/src/doc.rs b/crates/app/src/doc.rs index e88ae13..0fc7666 100644 --- a/crates/app/src/doc.rs +++ b/crates/app/src/doc.rs @@ -3,7 +3,9 @@ //! so parsing whatever a file holds happens in its sandbox. The app reads it back (`decode`), //! believing nothing it hasn't checked, and lays it out (see `docview`). -use pulldown_cmark::{Alignment, Event, Options, Parser, Tag, TagEnd}; +use pulldown_cmark::{Alignment, CodeBlockKind, Event, Options, Parser, Tag, TagEnd}; + +use crate::syntax::Lang; pub const MAGIC: &[u8; 4] = b"GNPD"; /// How much of a file is shown. A file that's longer is cut at the end of a line before this. @@ -32,7 +34,8 @@ pub enum Kind { Paragraph, /// From 1, the biggest, to 6. Heading(u8), - Code, + /// A code block, with the language its fence names when Gannet colours that language. + Code(Option), /// A list item's first block, with its bullet or number. Item(String), Rule, @@ -79,6 +82,9 @@ pub struct Doc { pub blocks: Vec, /// The file goes on past what's here. pub cut: bool, + /// A plain text file's language, by its name or shebang, for its colours. The app sets it, + /// as the decoder doesn't know the file's name. + pub lang: Option, } impl Doc { @@ -136,7 +142,7 @@ pub fn excerpt(raw: &[u8]) -> Option<(String, bool)> { } pub fn plain(text: String, cut: bool) -> Doc { - Doc { blocks: vec![Block { kind: Kind::Plain, quote: 0, indent: 0, spans: vec![Span { style: 0, text }] }], cut } + Doc { blocks: vec![Block { kind: Kind::Plain, quote: 0, indent: 0, spans: vec![Span { style: 0, text }] }], cut, lang: None } } /// Markdown as a document. HTML in it is left out, as there's no way to show it as it means. @@ -175,7 +181,8 @@ pub fn markdown(text: &str, cut: bool) -> Doc { } let kind = match tag { Tag::Heading { level, .. } => Kind::Heading(level as u8), - _ => Kind::Code, + Tag::CodeBlock(CodeBlockKind::Fenced(info)) => Kind::Code(Lang::for_fence(&info)), + _ => Kind::Code(None), }; out.open(kind, quote, indent(&lists)); } @@ -304,7 +311,7 @@ pub fn markdown(text: &str, cut: bool) -> Doc { out.close(); // Code blocks end with their last line's newline, which would be an empty line. for block in &mut out.doc.blocks { - if block.kind == Kind::Code + if matches!(block.kind, Kind::Code(_)) && let Some(last) = block.spans.last_mut() { let trimmed = last.text.trim_end_matches('\n').len(); @@ -337,7 +344,7 @@ impl Builder { } fn in_code(&self) -> bool { - self.open.as_ref().is_some_and(|b| b.kind == Kind::Code) + self.open.as_ref().is_some_and(|b| matches!(b.kind, Kind::Code(_))) } fn set_marker(&mut self, marker: String) { @@ -374,7 +381,8 @@ pub fn encode(doc: &Doc) -> Vec { Kind::Plain => (0, ""), Kind::Paragraph => (1, ""), Kind::Heading(level) => (1 + *level, ""), - Kind::Code => (8, ""), + // The language goes by its name, which the app reads back as one it knows or none. + Kind::Code(lang) => (8, lang.map_or("", Lang::name)), Kind::Item(marker) => (9, marker.as_str()), Kind::Rule => (10, ""), // What the cell starts and its alignment, in the one byte. @@ -420,7 +428,7 @@ pub fn decode(bytes: &[u8]) -> Option { 0 => Kind::Plain, 1 => Kind::Paragraph, 2..=7 => Kind::Heading(kind - 1), - 8 => Kind::Code, + 8 => Kind::Code(Lang::from_name(&marker)), 9 if marker.chars().count() <= 24 => Kind::Item(marker), 10 => Kind::Rule, CELL..=CELL_LAST => { @@ -441,7 +449,7 @@ pub fn decode(bytes: &[u8]) -> Option { } blocks.push(Block { kind, quote, indent, spans }); } - (r.at == bytes.len()).then_some(Doc { blocks, cut }) + (r.at == bytes.len()).then_some(Doc { blocks, cut, lang: None }) } struct Reader<'a> { @@ -516,7 +524,7 @@ mod tests { block(Kind::Heading(1), vec![span(0, "Title")]), block(Kind::Paragraph, vec![span(0, "Some "), span(ITALIC, "soft"), span(0, " and "), span(BOLD, "strong"), span(0, " "), span(CODE, "code"), span(0, ", "), span(LINK, "a link"), span(0, ".")]), block(Kind::Rule, vec![]), - block(Kind::Code, vec![span(CODE, "fn main() {}")]), + block(Kind::Code(Some(Lang::Rust)), vec![span(CODE, "fn main() {}")]), ] ); } @@ -547,7 +555,7 @@ mod tests { let doc = markdown("- ```\n code\n ```\n- # Title\n", false); let kinds: Vec<(Kind, u8)> = doc.blocks.iter().map(|b| (b.kind.clone(), b.indent)).collect(); let bullet = Kind::Item("•".into()); - assert_eq!(kinds, [(bullet.clone(), 1), (Kind::Code, 1), (bullet, 1), (Kind::Heading(1), 1)]); + assert_eq!(kinds, [(bullet.clone(), 1), (Kind::Code(None), 1), (bullet, 1), (Kind::Heading(1), 1)]); assert_eq!(doc.blocks[1].spans, [span(CODE, "code")]); } @@ -659,8 +667,15 @@ mod tests { #[test] fn a_document_goes_between_the_processes_whole() { - let doc = Doc { blocks: markdown("# Hi\n\n- *a* `b`\n\n> c\n\n---\n\n| x | |\n|:-:|--:|\n| **1** | 2 |\n", true).blocks, cut: true }; + let doc = Doc { blocks: markdown("# Hi\n\n- *a* `b`\n\n> c\n\n---\n\n| x | |\n|:-:|--:|\n| **1** | 2 |\n\n```php\n = doc.blocks.iter().map(|b| &b.kind).filter(|k| matches!(k, Kind::Code(_))).collect(); + assert_eq!(kinds, [&Kind::Code(Some(Lang::Php)), &Kind::Code(None)], "a fence's language comes across when Gannet colours it"); + // A language the app doesn't know, from a decoder that's been taken over, is none. + let mut odd = encode(&Doc { blocks: vec![block(Kind::Code(Some(Lang::Go)), vec![span(CODE, "x")])], cut: false, lang: None }); + let at = odd.windows(2).position(|w| w == b"go").unwrap(); + odd[at..at + 2].copy_from_slice(b"zz"); + assert_eq!(decode(&odd).unwrap().blocks[0].kind, Kind::Code(None)); let text = plain("x\ny".to_string(), false); assert_eq!(decode(&encode(&text)).unwrap().lines(), 2); assert_eq!(plain("x\ny\n".to_string(), false).lines(), 2, "a last newline ends a line"); @@ -699,7 +714,7 @@ mod tests { // And each one is the cell it was. for starts in [Starts::Nothing, Starts::Row, Starts::Table] { for align in [Align::Left, Align::Center, Align::Right] { - let doc = Doc { blocks: vec![block(Kind::Cell { starts, align }, vec![])], cut: false }; + let doc = Doc { blocks: vec![block(Kind::Cell { starts, align }, vec![])], cut: false, lang: None }; assert_eq!(decode(&encode(&doc)), Some(doc)); } } diff --git a/crates/app/src/docview.rs b/crates/app/src/docview.rs index 400ecb0..9d09cef 100644 --- a/crates/app/src/docview.rs +++ b/crates/app/src/docview.rs @@ -5,12 +5,14 @@ //! one lays out without measuring a word. Markdown is measured word by word. use std::borrow::Cow; +use std::cell::RefCell; use std::path::{Path, PathBuf}; use gannet_core::tokens::{size, spacing, type_scale}; use crate::canvas::{Canvas, Rect}; use crate::doc::{self, Align, Block, Doc, Kind, Starts}; +use crate::syntax::{self, Lang, Labels, Span, State, Tok}; use crate::text::{self, Text}; const BODY_PX: f32 = type_scale::doc::BODY; @@ -267,9 +269,85 @@ pub struct Layout { pub lines: Vec, /// Where the text ends, as an offset: what selecting all of it covers. pub total: usize, + /// The runs of lines that are code in a language Gannet colours. + code: Vec, + /// What's been worked out for colouring them, as lines are drawn. + colours: RefCell, +} + +/// A plain text file or a code block in a language Gannet colours: its lines, from `first` up +/// to `end`, and the line each of its own lines (the file's, which may wrap) starts on. +struct CodeRun { + lang: Lang, + first: usize, + end: usize, + starts: Vec, +} + +/// Source lines past the last one drawn whose start is worked out with it, so scrolling on a +/// little needs nothing new. +const STATES_AHEAD: usize = 64; + +/// What colouring the code in view needs, kept between frames. Nothing here runs unless a line +/// is drawn, so there's no work while the window is idle. +#[derive(Default)] +struct Colours { + /// For each run, the state each of its source lines starts in, as far down as a line has + /// been drawn. A jump far down (Ctrl+End) goes on from the last one known. + states: Vec>, + labels: Labels, + /// The source line whose runs `spans` holds, as (run, line), so the lines it wraps onto + /// don't tokenize it again. + last: Option<(usize, usize)>, + spans: Vec, + /// A source line's text, put together from the lines it wraps onto. + text: String, } impl Layout { + /// The coloured runs of line `i`'s source line, and where line `i` starts in it, as bytes; + /// `None` when the line isn't code Gannet colours. + fn colours<'c>(&self, i: usize, c: &'c mut Colours) -> Option<(&'c [Span], usize)> { + let r = self.code.partition_point(|r| r.first <= i).checked_sub(1)?; + let run = &self.code[r]; + if i >= run.end { + return None; + } + let s = run.starts.partition_point(|&x| x as usize <= i).checked_sub(1)?; + let source = |j: usize, into: &mut String| { + let to = run.starts.get(j + 1).map_or(run.end, |&x| x as usize); + into.clear(); + for l in &self.lines[run.starts[j] as usize..to] { + l.pieces.iter().for_each(|p| into.push_str(&p.text)); + } + }; + let Colours { states, labels, last, spans, text } = c; + if *last != Some((r, s)) { + if states.len() < self.code.len() { + states.resize_with(self.code.len(), Vec::new); + } + let known = &mut states[r]; + if known.is_empty() { + known.push(State::default()); + } + // The start of each line down to this one, and a little past it, from the last known. + let want = (s + STATES_AHEAD).min(run.starts.len() - 1); + while known.len() <= want { + let j = known.len() - 1; + source(j, text); + spans.clear(); + let next = syntax::line(run.lang, known[j], text, labels, spans); + known.push(next); + } + source(s, text); + spans.clear(); + syntax::line(run.lang, known[s], text, labels, spans); + *last = Some((r, s)); + } + let along = self.lines[run.starts[s] as usize..i].iter().map(Line::len).sum(); + Some((spans.as_slice(), along)) + } + /// Whether it still fits a window this wide, set in these fonts. pub fn fits(&self, width: i32, fonts: &mut Fonts) -> bool { self.width == width && self.generation == fonts.generation() @@ -694,7 +772,7 @@ pub fn lay_out(doc: &Doc, width: i32, fonts: &mut Fonts) -> Layout { let indent_w = fonts.px(spacing::DOC_INDENT); let quote_w = fonts.px(spacing::DOC_QUOTE); let gap = fonts.body.line_height() as i32; - let mut out = Layout { width, generation: fonts.generation(), height: 0, lines: Vec::new(), total: 0 }; + let mut out = Layout { width, generation: fonts.generation(), height: 0, lines: Vec::new(), total: 0, code: Vec::new(), colours: RefCell::default() }; let mut y = fonts.px(spacing::SPACE_16); let mut i = 0; while let Some(block) = doc.blocks.get(i) { @@ -710,8 +788,12 @@ pub fn lay_out(doc: &Doc, width: i32, fonts: &mut Fonts) -> Layout { y += before; i += 1; match &block.kind { - Kind::Plain | Kind::Code => { - let code = block.kind == Kind::Code; + Kind::Plain | Kind::Code(_) => { + let code = matches!(block.kind, Kind::Code(_)); + let lang = match block.kind { + Kind::Code(lang) => lang, + _ => doc.lang, + }; let inset = if code { fonts.px(spacing::SPACE_10) } else { 0 }; let mono = &mut fonts.mono; let advance = mono.measure("0").max(1.0); @@ -723,7 +805,14 @@ pub fn lay_out(doc: &Doc, width: i32, fonts: &mut Fonts) -> Layout { } let first = out.lines.len(); let ended = text.ends_with('\n'); + // Text that isn't really in its language, with more than one character in a + // hundred not UTF-8 at all, stays plain. + let lang = lang.filter(|_| text.matches('\u{fffd}').count() * 100 <= text.len()); + let mut starts = Vec::new(); for source in text.strip_suffix('\n').unwrap_or(&text).split('\n') { + if lang.is_some() { + starts.push(out.lines.len() as u32); + } let pieces = wrap_columns(source, fit); let n = pieces.len(); for (k, piece) in pieces.into_iter().enumerate() { @@ -733,6 +822,9 @@ pub fn lay_out(doc: &Doc, width: i32, fonts: &mut Fonts) -> Layout { y += h; } } + if let Some(lang) = lang { + out.code.push(CodeRun { lang, first, end: out.lines.len(), starts }); + } // A file with no line break at its end copies without one, and a code block is // set apart from what follows. let made = out.lines.len() > first; @@ -1035,6 +1127,19 @@ pub struct Ink { pub rule: u32, pub selection: u32, pub on_selection: u32, + /// Code's comments, strings, keywords and numbers. + pub syntax: [u32; 4], +} + +impl Ink { + fn token(&self, tok: Tok) -> u32 { + self.syntax[match tok { + Tok::Comment => 0, + Tok::String => 1, + Tok::Keyword => 2, + Tok::Number => 3, + }] + } } /// Draws the lines in view, `scroll` pixels down, inside `area`. `selected` is a range of @@ -1046,7 +1151,9 @@ pub fn paint(c: &mut Canvas, area: Rect, scroll: i32, layout: &Layout, fonts: &m let pad = fonts.px(spacing::DOC_MARGIN); let quote_w = fonts.px(spacing::DOC_QUOTE); let top = area.y - scroll; - for line in &layout.lines[layout.line_at(scroll)..] { + let first = layout.line_at(scroll); + let mut colours = layout.colours.borrow_mut(); + for (li, line) in layout.lines.iter().enumerate().skip(first) { let y = top + line.y; if y >= area.bottom() { break; @@ -1077,6 +1184,8 @@ pub fn paint(c: &mut Canvas, area: Rect, scroll: i32, layout: &Layout, fonts: &m } let mut at = line.at; let mut ends_at = area.x as f32 + line.pieces.first().map_or(pad as f32, |p| p.x); + // Code's coloured runs, and where this line starts in its source line. + let toks = if layout.code.is_empty() { None } else { layout.colours(li, &mut colours) }; for piece in &line.pieces { let color = if piece.style & doc::LINK != 0 { ink.link } else if line.quote > 0 { ink.muted } else { ink.text }; let x = area.x as f32 + piece.x; @@ -1084,7 +1193,13 @@ pub fn paint(c: &mut Canvas, area: Rect, scroll: i32, layout: &Layout, fonts: &m let start = at; at += piece.text.len(); let picked = selected.map(|(a, b)| (a.max(start).min(at) - start, b.min(at).max(start) - start)).filter(|(a, b)| a < b); - if picked.is_some() || (piece.tabbed && piece.text.contains('\t')) { + // The coloured runs over this piece, and where it starts among their bytes. + let from = toks.map_or(0, |(_, along)| along + start - line.at); + let spans = toks.map_or(&[][..], |(spans, _)| { + let (a, b) = (spans.partition_point(|s| s.to as usize <= from), spans.partition_point(|s| (s.from as usize) < from + piece.text.len())); + &spans[a..b.max(a)] + }); + if picked.is_some() || (piece.tabbed && piece.text.contains('\t')) || !spans.is_empty() { // Before the code box below: the box goes under the selection. let t = fonts.get(piece.face); let among = !matches!(line.mark, Mark::Code(..)) && (matches!(line.mark, Mark::Table { .. }) || line.pieces.len() > 1); @@ -1101,22 +1216,12 @@ pub fn paint(c: &mut Canvas, area: Rect, scroll: i32, layout: &Layout, fonts: &m let (l, r) = (x + x_of(a), x + x_of(b)); c.fill(Rect::new(l.floor() as i32, y, (r.ceil() - l.floor()) as i32, line.h), ink.selection); } - // Drawn in runs between tabs and the selection's ends, each where it starts. + // Drawn in runs, each where it starts. let t = fonts.get(piece.face); - let mut run = 0; - for (k, &(byte, _)) in stops.iter().enumerate().skip(1) { - let tab = piece.tabbed && piece.text[stops[k - 1].0..byte] == *"\t"; - let edge = picked.is_some_and(|(a, b)| byte == a || byte == b); - let last = k + 1 == stops.len(); - if tab || edge || last { - let to = if tab { stops[k - 1].0 } else { byte }; - if run < to { - let inside = picked.is_some_and(|(a, b)| run >= a && to <= b); - t.draw_str(c, &piece.text[run..to], x + x_of(run), baseline, if inside { ink.on_selection } else { color }); - } - run = byte; - } - } + piece_runs(piece, picked, spans, from, &ink, color, |a, b, colour| { + let ax = stops[stops.partition_point(|s| s.0 < a)].1; + t.draw_str(c, &piece.text[a..b], x + ax, baseline, colour); + }); if piece.style & (doc::STRUCK | doc::LINK) != 0 { let w = t.measure(piece.text.trim_end_matches(' ')).ceil() as i32; let at = if piece.style & doc::STRUCK != 0 { baseline - (t.ascent * 0.3).round() as i32 } else { baseline + 2 }; @@ -1173,6 +1278,34 @@ pub fn paint(c: &mut Canvas, area: Rect, scroll: i32, layout: &Layout, fonts: &m } } +/// The runs a piece is drawn in, as (from, to, colour) by its bytes: split at its tabs (which +/// are left out, as they're only room), at the selection's ends (`picked`) and at the ends of +/// code's coloured runs (`spans`, by bytes from `from` before the piece). Selected text is in +/// the selection's text colour whatever it is; the rest in its token's colour, or `color`. +fn piece_runs(piece: &Piece, picked: Option<(usize, usize)>, spans: &[Span], from: usize, ink: &Ink, color: u32, mut draw: impl FnMut(usize, usize, u32)) { + let text = piece.text.as_str(); + let mut run = 0; + let mut cuts = spans.iter().flat_map(|s| [s.from as usize, s.to as usize]).map(|b| b.saturating_sub(from)).filter(|&b| b > 0).peekable(); + let tok_at = |b: usize| spans.iter().find(|s| (s.from as usize) <= from + b && from + b < s.to as usize).map(|s| s.tok); + let mut prev = 0; + for byte in text.char_indices().map(|(i, _)| i).skip(1).chain(std::iter::once(text.len())) { + let tab = piece.tabbed && &text[prev..byte] == "\t"; + let mut edge = picked.is_some_and(|(a, b)| byte == a || byte == b); + while cuts.peek().is_some_and(|&b| b <= byte) { + edge |= cuts.next() == Some(byte); + } + if tab || edge || byte == text.len() { + let to = if tab { prev } else { byte }; + if run < to { + let inside = picked.is_some_and(|(a, b)| run >= a && to <= b); + draw(run, to, if inside { ink.on_selection } else { tok_at(run).map_or(color, |tok| ink.token(tok)) }); + } + run = byte; + } + prev = byte; + } +} + /// The caret: a bar as tall as the text where it is, in the text's colour on the background and /// in the selection's text colour on the selection. At an edge of the selection it's half in /// each, so each half stands out from what it's on (see the `doc-caret` token). @@ -1461,7 +1594,7 @@ mod tests { assert_eq!(layout.lines.len(), 1, "an empty row is still a row"); assert!(layout.lines[0].h > 0); let cell = |starts| Block { kind: Kind::Cell { starts, align: doc::Align::Center }, quote: 0, indent: 0, spans: vec![doc::Span { style: 0, text: "x".into() }] }; - let odd = Doc { blocks: vec![cell(Starts::Nothing), cell(Starts::Row), cell(Starts::Nothing), cell(Starts::Nothing), cell(Starts::Table)], cut: false }; + let odd = Doc { blocks: vec![cell(Starts::Nothing), cell(Starts::Row), cell(Starts::Nothing), cell(Starts::Nothing), cell(Starts::Table)], cut: false, lang: None }; let layout = lay_out(&odd, 10, &mut fonts); assert_eq!(layout.lines.len(), 3, "two tables, the first of two rows"); } @@ -1596,7 +1729,7 @@ mod tests { let quoted = layout.lines.iter().position(|l| l.quote > 0).unwrap(); let q = &layout.lines[quoted]; let empty = Line { y: q.y, h: q.h, baseline: q.baseline, quote: q.quote, mark: Mark::None, marker: None, pieces: Vec::new(), at: 0, end: q.end }; - let alone = Layout { width: 800, generation: 0, height: 100, lines: vec![empty], total: 0 }; + let alone = Layout { width: 800, generation: 0, height: 100, lines: vec![empty], total: 0, code: Vec::new(), colours: RefCell::default() }; let inside = layout.caret_x(layout.line_start(quoted), &mut fonts).0; assert!((alone.caret_x(Caret { at: 0, line: 0 }, &mut fonts).0 - inside).abs() < 1.0, "inside the quote"); } @@ -1617,4 +1750,124 @@ mod tests { assert_eq!(face_for(&Kind::Paragraph, doc::ITALIC | doc::LINK), Face::Italic); assert_eq!(face_for(&Kind::Item("•".into()), 0), Face::Body); } + + /// Each line's coloured runs as (text, kind), worked out in the order `order` draws them. + fn coloured(layout: &Layout, order: impl Iterator) -> Vec<(usize, Vec<(String, Tok)>)> { + let mut c = layout.colours.borrow_mut(); + let mut out = Vec::new(); + for i in order { + let line = &layout.lines[i]; + let text: String = line.pieces.iter().map(|p| p.text.as_str()).collect(); + let runs = layout.colours(i, &mut c).map(|(spans, along)| { + spans.iter().filter_map(|s| { + let (a, b) = ((s.from as usize).max(along) - along, (s.to as usize).min(along + text.len()).saturating_sub(along)); + (a < b).then(|| (text[a..b].to_string(), s.tok)) + }).collect() + }); + out.push((i, runs.unwrap_or_default())); + } + out + } + + #[test] + fn code_is_coloured_from_the_line_start_state_however_far_down_it_starts() { + let Some(mut fonts) = fonts() else { return }; + let mut text = String::from("/* a comment\n"); + text += &" still the comment\n".repeat(300); + text += "*/ fn main() { let s = \"one\n"; + text += &"string\n".repeat(100); + text += "\"; }\n"; + let mut doc = doc::plain(text.clone(), false); + doc.lang = Some(Lang::Rust); + let layout = lay_out(&doc, 2000, &mut fonts); + let n = layout.lines.len(); + // Jumping to the end first (Ctrl+End), then to the middle, then the top, as scrolling does. + let got = coloured(&layout, [n - 1, 150, 301, 302, 0].into_iter()); + assert_eq!(got[0].1, [("\"".to_string(), Tok::String)], "the string's close, far below where it opened"); + assert_eq!(got[1].1, [(" still the comment".to_string(), Tok::Comment)]); + assert_eq!(got[2].1, [("*/".to_string(), Tok::Comment), ("fn".to_string(), Tok::Keyword), ("let".to_string(), Tok::Keyword), ("\"one".to_string(), Tok::String)]); + assert_eq!(got[3].1, [("string".to_string(), Tok::String)]); + assert_eq!(got[4].1, [("/* a comment".to_string(), Tok::Comment)]); + let known: usize = layout.colours.borrow().states.iter().map(Vec::len).sum(); + assert!(known <= n + 1, "each line start is worked out once: {known}"); + // Colour changes nothing a selection or a screen reader sees. + let plain = lay_out(&doc::plain(text.clone(), false), 2000, &mut fonts); + assert_eq!(layout.text(0, layout.total), text); + assert_eq!(layout.lines, plain.lines); + assert_eq!(layout.line_for_reading(301, 0, None), plain.line_for_reading(301, 0, None)); + } + + #[test] + fn only_lines_near_those_drawn_are_worked_out() { + let Some(mut fonts) = fonts() else { return }; + let mut doc = doc::plain("let x = 1;\n".repeat(10_000), false); + doc.lang = Some(Lang::Rust); + let layout = lay_out(&doc, 2000, &mut fonts); + coloured(&layout, 0..40); + let known = layout.colours.borrow().states[0].len(); + assert!(known <= 40 + STATES_AHEAD + 1, "{known} line starts worked out for 40 lines drawn"); + } + + #[test] + fn a_wrapped_line_keeps_its_colours_on_the_lines_it_wraps_onto() { + let Some(mut fonts) = fonts() else { return }; + let long = format!("let s = \"{}\"; // done", "x".repeat(300)); + let mut doc = doc::plain(long.clone(), false); + doc.lang = Some(Lang::Rust); + let layout = lay_out(&doc, 400, &mut fonts); + assert!(layout.lines.len() > 2, "it wrapped"); + let got = coloured(&layout, 0..layout.lines.len()); + assert_eq!(got[1].1.len(), 1); + assert!(got[1].1[0].1 == Tok::String && got[1].1[0].0.chars().all(|c| c == 'x'), "{:?}", got[1]); + assert_eq!(got.last().unwrap().1.last().unwrap(), &("// done".to_string(), Tok::Comment)); + } + + #[test] + fn a_markdown_fence_naming_a_language_is_coloured_and_others_are_not() { + let Some(mut fonts) = fonts() else { return }; + let doc = doc::markdown("Some `fn` words.\n\n```rust\nfn main() {} // hi\n```\n\n```\nfn plain() {}\n```\n\n```php\n\n```\n", false); + let layout = lay_out(&doc, 2000, &mut fonts); + let got = coloured(&layout, 0..layout.lines.len()); + let runs: Vec> = got.into_iter().map(|(_, r)| r).filter(|r| !r.is_empty()).collect(); + let s = |t: &str, k| (t.to_string(), k); + assert_eq!(runs, [vec![s("fn", Tok::Keyword), s("// hi", Tok::Comment)], vec![s("", Tok::Keyword)]]); + } + + /// What colouring and a selection make of a piece, with no fonts needed, so it runs anywhere. + #[test] + fn selected_code_is_drawn_in_the_selections_text_colour_and_the_rest_in_its_tokens() { + let ink = Ink { text: 1, muted: 2, link: 3, code: 0, rule: 0, selection: 0, on_selection: 9, syntax: [10, 11, 12, 13] }; + let piece = Piece { x: 0.0, face: Face::Mono, style: doc::CODE, text: "fn x\t\"s\" 7".into(), col: 0, tabbed: true }; + // As tokenized from the source line's start, with this piece 3 bytes into it. + let spans = [Span { from: 3, to: 5, tok: Tok::Keyword }, Span { from: 8, to: 11, tok: Tok::String }, Span { from: 12, to: 13, tok: Tok::Number }]; + let runs = |picked| { + let mut out = Vec::new(); + piece_runs(&piece, picked, &spans, 3, &ink, ink.text, |a, b, c| out.push((&piece.text[a..b], c))); + out + }; + assert_eq!(runs(None), [("fn", 12), (" x", 1), ("\"s\"", 11), (" ", 1), ("7", 13)], "the tab is room, not drawn"); + assert_eq!(runs(Some((1, 7))), [("f", 12), ("n", 9), (" x", 9), ("\"s", 9), ("\"", 11), (" ", 1), ("7", 13)], "selected, every kind is in the selection's text colour"); + assert!(runs(Some((0, piece.text.len()))).iter().all(|r| r.1 == 9), "all of it selected"); + } + + #[test] + fn selected_code_keeps_the_selections_text_colour() { + let Some(mut fonts) = fonts() else { return }; + let mut doc = doc::plain("fn fn fn fn\n".into(), false); + doc.lang = Some(Lang::Rust); + let layout = lay_out(&doc, 600, &mut fonts); + let ink = Ink { text: 0x0000ff, muted: 0x0000ff, link: 0x0000ff, code: 0xffffff, rule: 0xffffff, selection: 0x000000, on_selection: 0x00ff00, syntax: [0xff00ff, 0xff00ff, 0xff0000, 0xff00ff] }; + let (w, h) = (600, 80); + let draw = |selected: Option<(usize, usize)>, fonts: &mut Fonts| { + let mut px = vec![0xffffffu32; (w * h) as usize]; + let mut c = Canvas::new(&mut px, w, h); + paint(&mut c, Rect::new(0, 0, w, h), 0, &layout, fonts, ink, selected, None); + px + }; + let has = |px: &[u32], colour: u32| px.iter().any(|&p| p & 0xffffff == colour); + let px = draw(None, &mut fonts); + assert!(has(&px, 0xff0000) && !has(&px, 0x0000ff), "the keywords are in the keyword colour"); + let px = draw(Some((0, layout.total)), &mut fonts); + assert!(has(&px, 0x00ff00) && !has(&px, 0xff0000), "selected, they're in the selection's text colour"); + } } diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index cc3762d..82fa38d 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -9,6 +9,7 @@ mod decode; mod doc; mod drives; mod docview; +mod syntax; mod field; mod format; mod format_drive; diff --git a/crates/app/src/preview.rs b/crates/app/src/preview.rs index a1e60f1..c8baa1d 100644 --- a/crates/app/src/preview.rs +++ b/crates/app/src/preview.rs @@ -458,8 +458,15 @@ fn fetch(at: &Place, slow: Option, video_size: (i32, i32), cancel: &Ow { // A zero byte past the part that was looked at means it isn't text after all. return match (status.code(), read_doc(&helper.output)) { - (Some(0), Some(doc)) => match describe(at, &meta, head.as_deref(), Some(None), cancel) { - Found::Info(info) => Some(Found::Doc { doc, info }), + (Some(0), Some(mut doc)) => match describe(at, &meta, head.as_deref(), Some(None), cancel) { + Found::Info(info) => { + // A text file in a language Gannet colours, by its name or its shebang. + if let [doc::Block { kind: doc::Kind::Plain, spans, .. }] = doc.blocks.as_slice() { + let text = spans.first().map_or("", |s| s.text.as_str()); + doc.lang = crate::syntax::Lang::for_file(&String::from_utf8_lossy(file_name(at.path)), text); + } + Some(Found::Doc { doc, info }) + } other => Some(other), }, (Some(decode::EXIT_UNSUPPORTED), _) => unsupported(), @@ -2211,7 +2218,8 @@ impl App { let Some(layout) = &p.doc_layout else { return }; p.scroll = p.scroll.clamp(0.0, (layout.height - area.h).max(0) as f64); let co = self.colors; - let ink = docview::Ink { text: co.foreground, muted: co.muted, link: co.link, code: co.surface, rule: co.border, selection: co.selection, on_selection: co.on_selection }; + let sx = co.syntax; + let ink = docview::Ink { text: co.foreground, muted: co.muted, link: co.link, code: co.surface, rule: co.border, selection: co.selection, on_selection: co.on_selection, syntax: [sx.comment, sx.string, sx.keyword, sx.number] }; let selected = p.text_sel.map(|s| s.range); let caret = p.caret.map(|c| c.caret); App::with_clip(c, area, |c| docview::paint(c, area, p.scroll as i32, layout, fonts, ink, selected, caret)); diff --git a/crates/app/src/syntax.rs b/crates/app/src/syntax.rs new file mode 100644 index 0000000..4e3a78a --- /dev/null +++ b/crates/app/src/syntax.rs @@ -0,0 +1,1227 @@ +//! Quick View's code colours: a small tokenizer for each family of languages, finding comments, +//! strings, keywords and numbers in one line at a time. Everything else stays the text's colour. +//! +//! A line is tokenized from the state its line starts in (inside a block comment, a string that +//! runs on, a heredoc, or HTML rather than PHP), and gives the state the next line starts in, so +//! a viewer can remember each line's start and colour only the lines it shows (see `docview`). +//! Colour is decoration: the text and its offsets never change. + +/// A language Gannet colours, by file name, shebang or a Markdown fence's info string. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Lang { + Rust, + /// C and C++. + C, + Python, + /// JavaScript and TypeScript. + Js, + Shell, + Go, + Php, + Json, + Toml, + Yaml, + /// HTML, and XML, which reads the same here. + Html, + Css, +} + +impl Lang { + /// The name the decoder writes for a code block's language, and reads back with `from_name`. + pub fn name(self) -> &'static str { + match self { + Lang::Rust => "rust", + Lang::C => "c", + Lang::Python => "python", + Lang::Js => "js", + Lang::Shell => "sh", + Lang::Go => "go", + Lang::Php => "php", + Lang::Json => "json", + Lang::Toml => "toml", + Lang::Yaml => "yaml", + Lang::Html => "html", + Lang::Css => "css", + } + } + + /// A language by a name for it or a file extension, in any case. + pub fn from_name(name: &str) -> Option { + if name.len() > 16 { + return None; + } + Some(match name.to_ascii_lowercase().as_str() { + "rust" | "rs" => Lang::Rust, + "c" | "h" | "cpp" | "c++" | "cc" | "cxx" | "hpp" | "hh" | "hxx" | "ino" => Lang::C, + "python" | "python3" | "py" | "py3" | "pyw" | "pyi" => Lang::Python, + "javascript" | "js" | "mjs" | "cjs" | "jsx" | "typescript" | "ts" | "tsx" | "mts" | "cts" => Lang::Js, + "sh" | "bash" | "shell" | "zsh" | "ksh" | "dash" => Lang::Shell, + "go" | "golang" => Lang::Go, + "php" | "phtml" | "php3" | "php4" | "php5" | "php7" | "php8" => Lang::Php, + "json" | "jsonc" | "json5" => Lang::Json, + "toml" => Lang::Toml, + "yaml" | "yml" => Lang::Yaml, + "html" | "htm" | "xhtml" | "xml" => Lang::Html, + "css" => Lang::Css, + _ => return None, + }) + } + + /// A Markdown fence's language: the first word of its info string (`rust,ignore` is Rust). + pub fn for_fence(info: &str) -> Option { + let word = info.trim().split(|c: char| c.is_whitespace() || c == ',' || c == '{').next()?; + Lang::from_name(word.trim_start_matches('.')) + } + + /// A file's language, by its name, or for a script with no extension, by its shebang. + pub fn for_file(name: &str, text: &str) -> Option { + let lower = name.to_ascii_lowercase(); + match lower.as_str() { + "pkgbuild" | ".bashrc" | ".bash_profile" | ".bash_logout" | ".profile" | ".zshrc" | ".zprofile" | ".zshenv" => return Some(Lang::Shell), + "cargo.lock" => return Some(Lang::Toml), + _ => {} + } + if let Some((stem, ext)) = lower.rsplit_once('.') + && !stem.is_empty() + && let Some(lang) = Lang::from_name(ext) + { + return Some(lang); + } + let first = text.lines().next()?.strip_prefix("#!")?; + let mut words = first.split_whitespace(); + let mut program = words.next()?.rsplit('/').next()?; + if program == "env" { + program = words.find(|w| !w.starts_with('-') && !w.contains('='))?; + } + let program = program.trim_end_matches(|c: char| c.is_ascii_digit() || c == '.'); + match program { + "sh" | "bash" | "zsh" | "ksh" | "dash" | "ash" => Some(Lang::Shell), + "python" => Some(Lang::Python), + "node" | "deno" | "bun" => Some(Lang::Js), + "php" => Some(Lang::Php), + _ => None, + } + } +} + +/// What a coloured run of a line is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Tok { + Comment, + String, + Keyword, + Number, +} + +/// A coloured run of a line, as bytes from its start. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Span { + pub from: u32, + pub to: u32, + pub tok: Tok, +} + +/// What a line starts inside: the state the line before it left. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct State { + code: Inner, + /// For PHP, where the HTML around the code was when it started, to go back to at `?>`. + html: Html, + /// For PHP, inside ``; outside it, the file is HTML. + php: bool, + /// For CSS, how many `{` deep, so a `:` starts a value only inside a block, not in a + /// selector's `a:hover`. + css: u8, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Inner { + #[default] + Code, + /// A block comment, and how deeply nested (Rust's nest). + Block(u8), + /// A string that runs on: what closes it, whether a backslash escapes, whether it's tripled + /// (Python and TOML), and for a Rust raw string, how many `#` follow its closing quote. + Str { quote: u8, escapes: bool, triple: bool, hashes: u8 }, + /// A heredoc's lines, until one that is its label. + Heredoc { label: u16, kind: Here }, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Here { + /// `<`. + Comment, + /// In a `

t

\n"); + assert_eq!(of(&r, Keyword), ["", "", "

", ""]); + assert_eq!(of(&r, Str), ["\"x\"", "\"y\""], "a quote in a script starts no attribute"); + let r = colour(Lang::Php, ""); + assert_eq!(of(&r, Keyword), [""]); + } + + #[test] + fn a_long_line_of_slashes_stays_fast() { + let line = "x = a / b / c ".repeat(10_000) + "= /"; + let start = std::time::Instant::now(); + let r = colour(Lang::Js, &line); + assert!(start.elapsed() < std::time::Duration::from_millis(200), "{:?}", start.elapsed()); + assert!(of(&r, Str).is_empty()); + let mut long = String::from("x = (/"); + long += &"a".repeat(5000); + long += "/)"; + assert!(of(&colour(Lang::Js, &long), Str).is_empty(), "a regex longer than any real one isn't looked for"); + assert_eq!(of(&colour(Lang::Js, "f(/a\\/b[/]/g, 1 / 2)"), Str), ["/a\\/b[/]/g"]); + } + + #[test] + fn a_quote_inside_a_word_isnt_a_string() { + let r = colour(Lang::Yaml, "msg: don't stop # c\nnext: 'quoted'\n- \"item\"\nflow: [a, 'b']"); + assert_eq!(of(&r, Str), ["'quoted'", "\"item\"", "'b'"]); + assert_eq!(of(&r, Comment), ["# c"]); + let r = colour(Lang::C, "int n = 1'000'000; char c = 'x';"); + assert_eq!(of(&r, Number), ["1'000'000"]); + assert_eq!(of(&r, Str), ["'x'"]); + } + + #[test] + fn members_and_variables_are_names_not_keywords() { + let r = colour(Lang::Php, "class; static::new(); return $x;"); + assert_eq!(of(&r, Keyword), [" Self { Self::new() } x.await"), Keyword), ["for", "in", "self", "fn", "Self", "Self", "await"]); + assert_eq!(of(&colour(Lang::Js, "f(...this.args); a.this"), Keyword), ["this"]); + assert_eq!(of(&colour(Lang::Go, "func f(a ...interface{}) {}"), Keyword), ["func", "interface"]); + assert_eq!(of(&colour(Lang::Python, "def f() -> None: return x.None"), Keyword), ["def", "None", "return"]); + assert_eq!(of(&colour(Lang::C, "auto f() -> int { return std::nullptr; }"), Keyword), ["auto", "int", "return", "nullptr"]); + assert_eq!(of(&colour(Lang::Php, "class; Foo::new; ...$args; [...self::X];"), Keyword), [" ü"; + for lang in [Lang::Rust, Lang::C, Lang::Python, Lang::Js, Lang::Shell, Lang::Go, Lang::Php, Lang::Json, Lang::Toml, Lang::Yaml, Lang::Html, Lang::Css] { + let mut labels = Labels::default(); + let mut state = State::default(); + for l in text.split('\n') { + let mut out = Vec::new(); + state = line(lang, state, l, &mut labels, &mut out); + let mut at = 0; + for s in &out { + assert!(s.from >= at && s.from < s.to && s.to as usize <= l.len(), "{lang:?}: {out:?}"); + assert!(l.is_char_boundary(s.from as usize) && l.is_char_boundary(s.to as usize), "{lang:?}: {out:?}"); + at = s.to; + } + } + } + } +} diff --git a/crates/core/src/theme.rs b/crates/core/src/theme.rs index b0f70b7..856b8fd 100644 --- a/crates/core/src/theme.rs +++ b/crates/core/src/theme.rs @@ -99,6 +99,19 @@ pub struct Colors { /// Behind a notice that only tells, such as a finished or stopped job, with its text readable on it. pub info_tint: Rgb, pub warning: Rgb, + /// Quick View's code colours: comments, strings, keywords and numbers. Each is the theme's + /// own terminal colour for it (bright black, green, magenta and yellow), moved toward the + /// text until it reads at 4.5:1 on the window and on a code block's background. + pub syntax: Syntax, +} + +/// The colours code is drawn in, as `Colors::syntax` has them. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Syntax { + pub comment: Rgb, + pub string: Rgb, + pub keyword: Rgb, + pub number: Rgb, } /// Parses `colors.toml` by hand: only `key = "#rrggbb"` lines matter, and this file is @@ -142,6 +155,16 @@ pub fn parse_colors(text: &str) -> Option { let danger = toward(danger, fg, |d| on_all(d, &[bg, surface, hover], TEXT_CONTRAST)); let muted = toward(blend(fg, bg, 0.40), fg, |m| on_all(m, &[bg, surface, hover], TEXT_CONTRAST)); let accent_mark = toward(accent, fg, |a| on_all(a, &[bg, surface, hover], GRAPHIC_CONTRAST)); + let warning = get("color3").or_else(|| get("yellow")).unwrap_or(if luminance(bg) < 0.4 { 0xe5c07b } else { 0xb7791f }); + // Code is drawn on the window (a text file) and on a code block's background (Markdown). + let code = |seed: Rgb| toward(seed, fg, |c| on_all(c, &[bg, surface], TEXT_CONTRAST)); + let dark_bg = luminance(bg) < 0.4; + let syntax = Syntax { + comment: code(get("color8").or_else(|| get("bright_black")).unwrap_or_else(|| blend(fg, bg, 0.45))), + string: code(get("color2").or_else(|| get("green")).unwrap_or(if dark_bg { 0x98c379 } else { 0x3f8a3a })), + keyword: code(get("color5").or_else(|| get("magenta")).unwrap_or(if dark_bg { 0xc678dd } else { 0xa626a4 })), + number: code(warning), + }; Some(Colors { dark, base: bg, @@ -171,7 +194,8 @@ pub fn parse_colors(text: &str) -> Option { on_danger: readable_on(danger), danger_tint: toward(blend(surface, danger, 0.16), surface, |t| on_all(t, &[fg, muted, danger], TEXT_CONTRAST)), info_tint: toward(blend(surface, accent, 0.10), surface, |t| on_all(t, &[fg, muted], TEXT_CONTRAST)), - warning: get("color3").or_else(|| get("yellow")).unwrap_or(if luminance(bg) < 0.4 { 0xe5c07b } else { 0xb7791f }), + warning, + syntax, }) } @@ -370,7 +394,7 @@ mod tests { /// A shipped theme's `colors.toml`, with only the keys read here, from design/tokens.json's /// `shipped-themes` table (aliasOS's themes/*/colors.toml). fn shipped_toml(row: &tokens::shipped_themes::Row) -> String { - let keys = [("background", row.background), ("foreground", row.foreground), ("accent", row.accent), ("selection_background", row.selection), ("selection_foreground", row.selection_foreground), ("color1", row.danger), ("color3", row.warning), ("mode", row.mode)]; + let keys = [("background", row.background), ("foreground", row.foreground), ("accent", row.accent), ("selection_background", row.selection), ("selection_foreground", row.selection_foreground), ("color1", row.danger), ("color3", row.warning), ("color2", row.string), ("color5", row.keyword), ("color8", row.comment), ("mode", row.mode)]; keys.iter().filter(|(_, v)| !v.is_empty()).map(|(k, v)| format!("{k} = \"{v}\"\n")).collect() } @@ -412,6 +436,11 @@ mod tests { check("quieter text beside a rename's problem", c.muted, c.danger_tint, TEXT_CONTRAST); check("a link", c.link, c.base, TEXT_CONTRAST); check("a link on the bars", c.link, c.surface, TEXT_CONTRAST); + let s = c.syntax; + for (what, colour) in [("a comment", s.comment), ("a string", s.string), ("a keyword", s.keyword), ("a number", s.number)] { + check(&format!("{what} in a text file"), colour, c.base, TEXT_CONTRAST); + check(&format!("{what} in a code block"), colour, c.surface, TEXT_CONTRAST); + } if check_accent { // The theme's own accent, kept as it is: the shipped themes' meet 3:1 unchanged. check("the shipped accent", c.accent, c.base, GRAPHIC_CONTRAST); @@ -448,9 +477,9 @@ mod tests { macro_rules! check { ($name:expr, $c:expr, $m:ident) => {{ let c: Colors = $c; - let got = [c.base, c.surface, c.hover, c.border, c.control_border, c.foreground, c.muted, c.accent, c.on_accent, c.accent_mark, c.accent_hover, c.link, c.selection, c.on_selection, c.on_selection_muted, c.selection_mark, c.drop_target, c.danger, c.on_danger, c.danger_tint, c.info_tint, c.warning, c.button_hover()]; + let got = [c.base, c.surface, c.hover, c.border, c.control_border, c.foreground, c.muted, c.accent, c.on_accent, c.accent_mark, c.accent_hover, c.link, c.selection, c.on_selection, c.on_selection_muted, c.selection_mark, c.drop_target, c.danger, c.on_danger, c.danger_tint, c.info_tint, c.warning, c.button_hover(), c.syntax.comment, c.syntax.string, c.syntax.keyword, c.syntax.number]; use crate::tokens::$m as t; - let want = [t::BASE, t::SURFACE, t::HOVER, t::BORDER, t::CONTROL_BORDER, t::FOREGROUND, t::MUTED, t::ACCENT, t::ON_ACCENT, t::ACCENT_MARK, t::ACCENT_HOVER, t::LINK, t::SELECTION, t::ON_SELECTION, t::ON_SELECTION_MUTED, t::SELECTION_MARK, t::DROP_TARGET, t::DANGER, t::ON_DANGER, t::DANGER_TINT, t::INFO_TINT, t::WARNING, t::BUTTON_HOVER]; + let want = [t::BASE, t::SURFACE, t::HOVER, t::BORDER, t::CONTROL_BORDER, t::FOREGROUND, t::MUTED, t::ACCENT, t::ON_ACCENT, t::ACCENT_MARK, t::ACCENT_HOVER, t::LINK, t::SELECTION, t::ON_SELECTION, t::ON_SELECTION_MUTED, t::SELECTION_MARK, t::DROP_TARGET, t::DANGER, t::ON_DANGER, t::DANGER_TINT, t::INFO_TINT, t::WARNING, t::BUTTON_HOVER, t::SYNTAX_COMMENT, t::SYNTAX_STRING, t::SYNTAX_KEYWORD, t::SYNTAX_NUMBER]; assert_eq!(got.map(|v| format!("{v:06x}")), want.map(|v| format!("{v:06x}")), "{}: design/tokens.json differs from what Gannet derives", $name); }}; } diff --git a/crates/core/src/tokens.rs b/crates/core/src/tokens.rs index c1ffcab..954642f 100644 --- a/crates/core/src/tokens.rs +++ b/crates/core/src/tokens.rs @@ -74,6 +74,18 @@ pub mod aliasos { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0x31383C; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x808A90; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0x93A58D; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0xA398AA; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0xC8B893; } /// The aliasOS Amber theme's colours. @@ -146,6 +158,18 @@ pub mod aliasos_amber { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0x34302B; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x8B7F70; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0x93A986; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0xAC9BB0; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0xD3BD8E; } /// The aliasOS Azure theme's colours. @@ -218,6 +242,18 @@ pub mod aliasos_azure { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0x273239; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x768692; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0x93A986; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0xAC9BB0; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0xD3BD8E; } /// The aliasOS Teal theme's colours. @@ -290,6 +326,18 @@ pub mod aliasos_teal { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0x273539; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x768A92; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0x93A986; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0xAC9BB0; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0xD3BD8E; } /// The Ayu Dark theme's colours. @@ -362,6 +410,18 @@ pub mod ayu_dark { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0x26292D; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x82827F; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0x7FD962; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0xCDA1FA; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0xF9AF4F; } /// The Last Horizon theme's colours. @@ -434,6 +494,18 @@ pub mod last_horizon { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0x313031; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x8F908F; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0x87A9B0; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0xC4D8E2; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0x887E8E; } /// The Matte Black theme's colours. @@ -506,6 +578,18 @@ pub mod matte_black { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0x2D2D2D; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x8A8A8D; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0xFFC107; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0xD35F5F; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0xBC6D6D; } /// The Osaka Jade theme's colours. @@ -578,6 +662,18 @@ pub mod osaka_jade { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0x2C352B; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x7F8D73; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0x549E6A; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0xD2689C; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0x519958; } /// The Retro 82 theme's colours. @@ -650,6 +746,18 @@ pub mod retro_82 { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0x2A3641; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x8F8876; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0x339596; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0x48938C; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0xE97B3C; } /// The Built-in light (no aliasOS theme) theme's colours. @@ -722,6 +830,18 @@ pub mod light { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0xD8D9DA; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x696C6F; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0x3A7B37; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0xA626A4; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0x916421; } /// The Built-in dark (no aliasOS theme) theme's colours. @@ -794,6 +914,18 @@ pub mod dark { /// A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover). pub const BUTTON_HOVER: u32 = 0x383A3E; + + /// Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way. + pub const SYNTAX_COMMENT: u32 = 0x8C8F93; + + /// Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_STRING: u32 = 0x98C379; + + /// Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_KEYWORD: u32 = 0xC678DD; + + /// Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface. + pub const SYNTAX_NUMBER: u32 = 0xE5C07B; } /// Every word Gannet draws apart from a document's own fonts. Not a font name: fontconfig's monospace alias, the desktop's monospace font, which aliasOS's font menu (aliasos-font-set) sets, so Gannet matches the terminal, the bar and the launcher (crates/app/src/text.rs UI_FONT). Drawn unhinted. @@ -1299,6 +1431,12 @@ pub mod shipped_themes { pub danger: &'static str, /// color3, or yellow where the theme names its colours. pub warning: &'static str, + /// color2, or green where the theme names its colours: the seed for syntax-string. + pub string: &'static str, + /// color5, or magenta where the theme names its colours: the seed for syntax-keyword. + pub keyword: &'static str, + /// color8, or bright_black where the theme names its colours: the seed for syntax-comment. Empty where the theme gives none. + pub comment: &'static str, /// mode = "dark" or "light" where the theme says outright. Empty where it doesn't. pub mode: &'static str, } @@ -1313,6 +1451,9 @@ pub mod shipped_themes { selection_foreground: "#D8DDE0", danger: "#B9827B", warning: "#C8B893", + string: "#93A58D", + keyword: "#A398AA", + comment: "#46525A", mode: "", }; @@ -1326,6 +1467,9 @@ pub mod shipped_themes { selection_foreground: "#E6DFD3", danger: "#C97B72", warning: "#D3BD8E", + string: "#93A986", + keyword: "#AC9BB0", + comment: "#5A4B3A", mode: "", }; @@ -1339,6 +1483,9 @@ pub mod shipped_themes { selection_foreground: "#DCE2E6", danger: "#C97B72", warning: "#D3BD8E", + string: "#93A986", + keyword: "#AC9BB0", + comment: "#32485A", mode: "", }; @@ -1352,6 +1499,9 @@ pub mod shipped_themes { selection_foreground: "#DCE2E6", danger: "#C97B72", warning: "#D3BD8E", + string: "#93A986", + keyword: "#AC9BB0", + comment: "#32505A", mode: "", }; @@ -1365,6 +1515,9 @@ pub mod shipped_themes { selection_foreground: "", danger: "#ea6c73", warning: "#f9af4f", + string: "#7fd962", + keyword: "#cda1fa", + comment: "#686868", mode: "", }; @@ -1378,6 +1531,9 @@ pub mod shipped_themes { selection_foreground: "", danger: "#c38b7b", warning: "#6B5E73", + string: "#87a9b0", + keyword: "#c4d8e2", + comment: "", mode: "dark", }; @@ -1391,6 +1547,9 @@ pub mod shipped_themes { selection_foreground: "#bebebe", danger: "#D35F5F", warning: "#b91c1c", + string: "#FFC107", + keyword: "#D35F5F", + comment: "#8a8a8d", mode: "", }; @@ -1404,6 +1563,9 @@ pub mod shipped_themes { selection_foreground: "#111C18", danger: "#FF5345", warning: "#459451", + string: "#549e6a", + keyword: "#D2689C", + comment: "#53685B", mode: "", }; @@ -1417,6 +1579,9 @@ pub mod shipped_themes { selection_foreground: "", danger: "#f85525", warning: "#e97b3c", + string: "#028391", + keyword: "#3f8f8a", + comment: "", mode: "dark", }; diff --git a/design/tokens.json b/design/tokens.json index 5a59906..5c9a92b 100644 --- a/design/tokens.json +++ b/design/tokens.json @@ -444,6 +444,74 @@ "dark": "#383a3e" }, "usage": "A plain button under the pointer (Cancel, Empty Trash, the chooser's filter): hover blended 8% toward the text (Colors::button_hover)." + }, + { + "name": "syntax-comment", + "value": { + "aliasos": "#808a90", + "aliasos_amber": "#8b7f70", + "aliasos_azure": "#768692", + "aliasos_teal": "#768a92", + "ayu_dark": "#82827f", + "last_horizon": "#8f908f", + "matte_black": "#8a8a8d", + "osaka_jade": "#7f8d73", + "retro_82": "#8f8876", + "light": "#696c6f", + "dark": "#8c8f93" + }, + "usage": "Comments in Quick View's code: a text file in a language Gannet knows, or a Markdown code block that names one. The theme's bright black (color8), moved toward foreground until it reads at 4.5:1 on base and surface; without one, foreground blended 45% toward base, moved the same way." + }, + { + "name": "syntax-string", + "value": { + "aliasos": "#93a58d", + "aliasos_amber": "#93a986", + "aliasos_azure": "#93a986", + "aliasos_teal": "#93a986", + "ayu_dark": "#7fd962", + "last_horizon": "#87a9b0", + "matte_black": "#ffc107", + "osaka_jade": "#549e6a", + "retro_82": "#339596", + "light": "#3a7b37", + "dark": "#98c379" + }, + "usage": "Strings (and characters, raw strings, heredocs) in Quick View's code. The theme's green (color2), moved toward foreground until it reads at 4.5:1 on base and surface." + }, + { + "name": "syntax-keyword", + "value": { + "aliasos": "#a398aa", + "aliasos_amber": "#ac9bb0", + "aliasos_azure": "#ac9bb0", + "aliasos_teal": "#ac9bb0", + "ayu_dark": "#cda1fa", + "last_horizon": "#c4d8e2", + "matte_black": "#d35f5f", + "osaka_jade": "#d2689c", + "retro_82": "#48938c", + "light": "#a626a4", + "dark": "#c678dd" + }, + "usage": "Keywords in Quick View's code. The theme's magenta (color5), moved toward foreground until it reads at 4.5:1 on base and surface." + }, + { + "name": "syntax-number", + "value": { + "aliasos": "#c8b893", + "aliasos_amber": "#d3bd8e", + "aliasos_azure": "#d3bd8e", + "aliasos_teal": "#d3bd8e", + "ayu_dark": "#f9af4f", + "last_horizon": "#887e8e", + "matte_black": "#bc6d6d", + "osaka_jade": "#519958", + "retro_82": "#e97b3c", + "light": "#916421", + "dark": "#e5c07b" + }, + "usage": "Numbers in Quick View's code. The theme's yellow (color3, as warning), moved toward foreground until it reads at 4.5:1 on base and surface." } ] }, @@ -1287,6 +1355,21 @@ "type": "text", "usage": "color3, or yellow where the theme names its colours." }, + { + "name": "string", + "type": "text", + "usage": "color2, or green where the theme names its colours: the seed for syntax-string." + }, + { + "name": "keyword", + "type": "text", + "usage": "color5, or magenta where the theme names its colours: the seed for syntax-keyword." + }, + { + "name": "comment", + "type": "text", + "usage": "color8, or bright_black where the theme names its colours: the seed for syntax-comment. Empty where the theme gives none." + }, { "name": "mode", "type": "text", @@ -1304,6 +1387,9 @@ "selection-foreground": "#D8DDE0", "danger": "#B9827B", "warning": "#C8B893", + "string": "#93A58D", + "keyword": "#A398AA", + "comment": "#46525A", "mode": "" }, "usage": "themes/aliasos/colors.toml." @@ -1318,6 +1404,9 @@ "selection-foreground": "#E6DFD3", "danger": "#C97B72", "warning": "#D3BD8E", + "string": "#93A986", + "keyword": "#AC9BB0", + "comment": "#5A4B3A", "mode": "" }, "usage": "themes/aliasos-amber/colors.toml." @@ -1332,6 +1421,9 @@ "selection-foreground": "#DCE2E6", "danger": "#C97B72", "warning": "#D3BD8E", + "string": "#93A986", + "keyword": "#AC9BB0", + "comment": "#32485A", "mode": "" }, "usage": "themes/aliasos-azure/colors.toml." @@ -1346,6 +1438,9 @@ "selection-foreground": "#DCE2E6", "danger": "#C97B72", "warning": "#D3BD8E", + "string": "#93A986", + "keyword": "#AC9BB0", + "comment": "#32505A", "mode": "" }, "usage": "themes/aliasos-teal/colors.toml." @@ -1360,6 +1455,9 @@ "selection-foreground": "", "danger": "#ea6c73", "warning": "#f9af4f", + "string": "#7fd962", + "keyword": "#cda1fa", + "comment": "#686868", "mode": "" }, "usage": "themes/ayu-dark/colors.toml." @@ -1374,6 +1472,9 @@ "selection-foreground": "", "danger": "#c38b7b", "warning": "#6B5E73", + "string": "#87a9b0", + "keyword": "#c4d8e2", + "comment": "", "mode": "dark" }, "usage": "themes/last-horizon/colors.toml." @@ -1388,6 +1489,9 @@ "selection-foreground": "#bebebe", "danger": "#D35F5F", "warning": "#b91c1c", + "string": "#FFC107", + "keyword": "#D35F5F", + "comment": "#8a8a8d", "mode": "" }, "usage": "themes/matte-black/colors.toml." @@ -1402,6 +1506,9 @@ "selection-foreground": "#111C18", "danger": "#FF5345", "warning": "#459451", + "string": "#549e6a", + "keyword": "#D2689C", + "comment": "#53685B", "mode": "" }, "usage": "themes/osaka-jade/colors.toml." @@ -1416,6 +1523,9 @@ "selection-foreground": "", "danger": "#f85525", "warning": "#e97b3c", + "string": "#028391", + "keyword": "#3f8f8a", + "comment": "", "mode": "dark" }, "usage": "themes/retro-82/colors.toml." @@ -1651,6 +1761,54 @@ "bg": "selection", "min": 3, "usage": "Quick View's caret over the selection: inside it, or the half on its side where the caret is at its edge (the other half is in foreground, on the background)." + }, + { + "fg": "syntax-comment", + "bg": "base", + "min": 4.5, + "usage": "A comment in Quick View's code, in a text file." + }, + { + "fg": "syntax-comment", + "bg": "surface", + "min": 4.5, + "usage": "A comment in a Markdown code block in Quick View." + }, + { + "fg": "syntax-string", + "bg": "base", + "min": 4.5, + "usage": "A string in Quick View's code, in a text file." + }, + { + "fg": "syntax-string", + "bg": "surface", + "min": 4.5, + "usage": "A string in a Markdown code block in Quick View." + }, + { + "fg": "syntax-keyword", + "bg": "base", + "min": 4.5, + "usage": "A keyword in Quick View's code, in a text file." + }, + { + "fg": "syntax-keyword", + "bg": "surface", + "min": 4.5, + "usage": "A keyword in a Markdown code block in Quick View." + }, + { + "fg": "syntax-number", + "bg": "base", + "min": 4.5, + "usage": "A number in Quick View's code, in a text file." + }, + { + "fg": "syntax-number", + "bg": "surface", + "min": 4.5, + "usage": "A number in a Markdown code block in Quick View." } ] } diff --git a/tests/e2e.py b/tests/e2e.py index 31e72ce..4b8c7d4 100644 --- a/tests/e2e.py +++ b/tests/e2e.py @@ -4637,6 +4637,102 @@ def text_and_markdown_show_as_documents(h): a.close() +# A theme as aliasOS ships it (themes/aliasos/colors.toml), with the keys Gannet reads. +ALIASOS_THEME = """accent = "#7F96A1" +foreground = "#D8DDE0" +background = "#131A1F" +selection_foreground = "#D8DDE0" +selection_background = "#1B2328" +color1 = "#B9827B" +color2 = "#93A58D" +color3 = "#C8B893" +color5 = "#A398AA" +color8 = "#46525A" +""" + +# Code's colours in each theme, as design/tokens.json has them: comment, string, keyword, number. +CODE_COLOURS = {"light": (0x696C6F, 0x3A7B37, 0xA626A4, 0x916421), "aliasos": (0x808A90, 0x93A58D, 0xA398AA, 0xC8B893)} + + +def preview_colours(a, name): + """Takes a picture of the screen, and gives every colour in the preview window, by how many + pixels have it.""" + a.shot(name) + ppm = SCRATCH / f"{name}.ppm" + subprocess.run(["grim", "-t", "ppm", str(ppm)], env=a.env, capture_output=True, timeout=10) + data = ppm.read_bytes() + # P6, then width, height and the most a value can be, each after whitespace, then one + # whitespace byte and the pixels, whose first bytes may look like whitespace too. + fields, at = [], 0 + while len(fields) < 4: + while data[at:at + 1].isspace(): + at += 1 + start = at + while not data[at:at + 1].isspace(): + at += 1 + fields.append(data[start:at]) + assert fields[0] == b"P6" and fields[3] == b"255", fields + w, hgt = int(fields[1]), int(fields[2]) + px = data[at + 1:] + assert len(px) == w * hgt * 3, (len(px), w, hgt) + x0, y0, pw, ph = a.preview_window() + counts = {} + for y in range(max(y0, 0), min(y0 + ph, hgt)): + row = px[(y * w + x0) * 3:(y * w + min(x0 + pw, w)) * 3] + for i in range(0, len(row), 3): + c = row[i] << 16 | row[i + 1] << 8 | row[i + 2] + counts[c] = counts.get(c, 0) + 1 + return counts + + +def drawn_in(seen, colour): + """How many pixels are in a colour, or within a step or two of it, as a glyph's solid middle is.""" + near = lambda c: all(abs((c >> k & 255) - (colour >> k & 255)) <= 6 for k in (16, 8, 0)) + return sum(n for c, n in seen.items() if near(c)) + + +@check +def code_is_coloured_in_light_and_dark_themes(h): + fs = fresh_fs() + (fs / "a-main.rs").write_text( + "// Quick View colours code.\n/* A block comment\n over two lines. */\nfn main() {\n" + " let name = \"Gannet\";\n let count: u32 = 42 + 0x1f;\n" + " if count > 1 {\n println!(\"{name} {count}\");\n }\n}\n") + (fs / "b-fence.md").write_text( + "# Code\n\nA fence that names its language is coloured:\n\n```rust\nfn main() {\n" + " let s = \"Hello from a fenced block\"; // greet whoever reads it\n return 1_000_000;\n}\n```\n\nOne that doesn't, isn't:\n\n```\nfn plain() {}\n```\n") + (fs / "c-page.php").write_text( + "\n

\">Hello

\n$n items

\n EOT;\n" + " return $html; # done\n}\n?>\n

Bye

\n") + client = SCRATCH / "client" + for theme in ("light", "aliasos"): + if client.exists(): + shutil.rmtree(client) + if theme == "aliasos": + cur = client / "home/.local/state/aliasos/current/theme" + cur.mkdir(parents=True) + (cur / "colors.toml").write_text(ALIASOS_THEME) + a = App(h, fs) + a.wait(lambda s: s["count"] == 3, "listing") + a.key("space") + comment, string, keyword, number = CODE_COLOURS[theme] + a.wait(lambda s: preview_of(s).get("name") == "a-main.rs" and doc_of(s).get("lines", 0) > 0, "the Rust file") + seen = preview_colours(a, f"code-rust-{theme}") + for what, colour in (("comment", comment), ("string", string), ("keyword", keyword), ("number", number)): + assert drawn_in(seen, colour) > 10, f"{theme}: no {what} colour #{colour:06x} in the Rust file" + a.key("Down") + a.wait(lambda s: preview_of(s).get("name") == "b-fence.md" and preview_of(s)["state"] == "markdown" and doc_of(s).get("lines", 0) > 0, "the Markdown") + seen = preview_colours(a, f"code-fence-{theme}") + for what, colour in (("comment", comment), ("string", string), ("keyword", keyword), ("number", number)): + assert drawn_in(seen, colour) > 3, f"{theme}: no {what} colour #{colour:06x} in the fence" + a.key("Down") + a.wait(lambda s: preview_of(s).get("name") == "c-page.php" and doc_of(s).get("lines", 0) > 0, "the PHP page") + a.shot(f"code-php-{theme}") + a.close() + shutil.rmtree(client) + + @check def text_in_a_preview_can_be_selected_and_copied(h): fs = fresh_fs()