Files
lightgui_rust/crates/lightgui-support/src/theme.rs
T
cnmcdee 3d53281388 Add lightgui-debug and lightgui-support: GDB MI debugger + theme/preferences/codeview/cmake ports
lightgui-debug: GdbSession over gdb -q -i=mi2 pipes with hand-written MI
parser (mi.rs), settings/breakpoint/variable types, and the 44-check
C++ harness ported as Rust tests (37 console + 7 GTK, gdb 17.1).
lightgui-support: CodeTheme + C tokenizer/highlighter, FontSettings,
CodeView fold/gutter/inspection widget, CMake project builder.
Tests: debug 59/59, support 23/23 (incl. theme/font/cmake suites).
cargo test clean, zero rustc warnings, clippy clean, cargo fmt clean.
2026-11-29 06:10:11 +00:00

937 lines
29 KiB
Rust

// LightGUI code-view color themes — port of src/theme.cpp / src/theme.h.
// Four built-ins: Light, Dark, Monokai, Solarized Dark. Each theme
// colours keywords, types, strings, comments, numbers, preprocessor
// lines, plus the view background/foreground and the
// current-execution-line background.
//
// Persistence: ~/.config/lightgui/theme.conf (key=value, same pattern as
// the debugger settings); LIGHTGUI_THEME_CONF overrides the path (used
// by tests). The file stores the theme name plus every colour, so a
// hand-edited or picker-customised colour survives a restart: on load
// the named built-in is taken as the base and any colour keys present
// override it.
use std::collections::{BTreeMap, HashSet};
use std::io::Write;
use std::sync::{Mutex, OnceLock};
use gtk::prelude::*;
fn home_dir() -> String {
std::env::var("HOME").unwrap_or_default()
}
fn trim_s(s: &str) -> &str {
s.trim_matches(|c| c == ' ' || c == '\t' || c == '\r' || c == '\n')
}
fn ensure_parent_dir(path: &str) {
if let Some(slash) = path.rfind('/') {
let dir = &path[..slash];
if !dir.is_empty() {
let _ = std::fs::create_dir_all(dir);
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct CodeTheme {
pub name: String,
pub background: String,
pub foreground: String,
pub keyword: String,
pub typ: String,
pub string: String,
pub comment: String,
pub number: String,
pub preprocessor: String,
pub current_line: String,
}
impl Default for CodeTheme {
fn default() -> Self {
CodeTheme {
name: "Light".to_string(),
background: "#ffffff".to_string(),
foreground: "#1a1a1a".to_string(),
keyword: "#0000ff".to_string(),
typ: "#008080".to_string(),
string: "#a31515".to_string(),
comment: "#008000".to_string(),
number: "#098658".to_string(),
preprocessor: "#af00db".to_string(),
current_line: "#e8f2ff".to_string(),
}
}
}
impl CodeTheme {
pub fn builtin_names() -> Vec<String> {
vec![
"Light".to_string(),
"Dark".to_string(),
"Monokai".to_string(),
"Solarized Dark".to_string(),
]
}
pub fn builtin(name: &str) -> CodeTheme {
match name {
"Dark" => CodeTheme {
name: "Dark".to_string(),
background: "#1e1e1e".to_string(),
foreground: "#d4d4d4".to_string(),
keyword: "#569cd6".to_string(),
typ: "#4ec9b0".to_string(),
string: "#ce9178".to_string(),
comment: "#6a9955".to_string(),
number: "#b5cea8".to_string(),
preprocessor: "#c586c0".to_string(),
current_line: "#2a2d2e".to_string(),
},
"Monokai" => CodeTheme {
name: "Monokai".to_string(),
background: "#272822".to_string(),
foreground: "#f8f8f2".to_string(),
keyword: "#f92672".to_string(),
typ: "#66d9ef".to_string(),
string: "#e6db74".to_string(),
comment: "#75715e".to_string(),
number: "#ae81ff".to_string(),
preprocessor: "#fd971f".to_string(),
current_line: "#3e3d32".to_string(),
},
"Solarized Dark" => CodeTheme {
name: "Solarized Dark".to_string(),
background: "#002b36".to_string(),
foreground: "#839496".to_string(),
keyword: "#859900".to_string(),
typ: "#2aa198".to_string(),
string: "#b58900".to_string(),
comment: "#586e75".to_string(),
number: "#d33682".to_string(),
preprocessor: "#cb4b16".to_string(),
current_line: "#073642".to_string(),
},
_ => CodeTheme::default(), // Light, incl. unknown names
}
}
pub fn is_builtin(name: &str) -> bool {
Self::builtin_names().iter().any(|n| n == name)
}
/// Strict "#rrggbb" (case-insensitive hex).
pub fn valid_color(s: &str) -> bool {
let b = s.as_bytes();
if b.len() != 7 || b[0] != b'#' {
return false;
}
b[1..].iter().all(|c| c.is_ascii_hexdigit())
}
pub fn default_path() -> String {
match std::env::var("LIGHTGUI_THEME_CONF") {
Ok(e) if !e.is_empty() => e,
_ => format!("{}/.config/lightgui/theme.conf", home_dir()),
}
}
pub fn save(&self, path: &str) -> bool {
let p = if path.is_empty() {
Self::default_path()
} else {
path.to_string()
};
ensure_parent_dir(&p);
let mut f = match std::fs::File::create(&p) {
Ok(f) => f,
Err(_) => return false,
};
let body = format!(
"theme={}\nbackground={}\nforeground={}\nkeyword={}\ntype={}\nstring={}\ncomment={}\nnumber={}\npreprocessor={}\ncurrent_line={}\n",
self.name,
self.background,
self.foreground,
self.keyword,
self.typ,
self.string,
self.comment,
self.number,
self.preprocessor,
self.current_line,
);
f.write_all(body.as_bytes()).is_ok()
}
pub fn load(&mut self, path: &str) -> bool {
let p = if path.is_empty() {
Self::default_path()
} else {
path.to_string()
};
let text = match std::fs::read_to_string(&p) {
Ok(t) => t,
Err(_) => return false,
};
let mut kv: BTreeMap<String, String> = BTreeMap::new();
for line in text.lines() {
let t = trim_s(line);
if t.is_empty() || t.starts_with('#') {
continue;
}
if let Some(eq) = t.find('=') {
kv.insert(
trim_s(&t[..eq]).to_string(),
trim_s(&t[eq + 1..]).to_string(),
);
}
}
let nm = kv
.get("theme")
.cloned()
.unwrap_or_else(|| "Light".to_string());
let mut base = if nm == "Custom" {
Self::builtin("Dark")
} else {
Self::builtin(&nm)
};
base.name = nm; // keep the stored name, even if customised
let take = |key: &str, field: &mut String| {
if let Some(v) = kv.get(key) {
if Self::valid_color(v) {
*field = v.clone();
}
}
};
take("background", &mut base.background);
take("foreground", &mut base.foreground);
take("keyword", &mut base.keyword);
take("type", &mut base.typ);
take("string", &mut base.string);
take("comment", &mut base.comment);
take("number", &mut base.number);
take("preprocessor", &mut base.preprocessor);
take("current_line", &mut base.current_line);
*self = base;
true
}
/// CSS for the view (sets both "textview" and "textview text": the
/// text area background lives on the "text" subnode).
pub fn css(&self) -> String {
format!(
"textview text {{ background-color: {}; color: {}; }} textview {{ background-color: {}; color: {}; }}",
self.background, self.foreground, self.background, self.foreground
)
}
}
fn type_words() -> &'static HashSet<&'static str> {
use std::sync::OnceLock;
static T: OnceLock<HashSet<&'static str>> = OnceLock::new();
T.get_or_init(|| {
[
"bool",
"char",
"char8_t",
"char16_t",
"char32_t",
"double",
"float",
"int",
"long",
"short",
"signed",
"unsigned",
"void",
"wchar_t",
"size_t",
"ssize_t",
"string",
"vector",
"map",
"set",
"list",
"array",
"pair",
"tuple",
"optional",
"uint8_t",
"uint16_t",
"uint32_t",
"uint64_t",
"int8_t",
"int16_t",
"int32_t",
"int64_t",
"nullptr_t",
"GtkWidget",
"GtkTextBuffer",
"GtkTextIter",
]
.into_iter()
.collect()
})
}
fn keyword_words() -> &'static HashSet<&'static str> {
use std::sync::OnceLock;
static K: OnceLock<HashSet<&'static str>> = OnceLock::new();
K.get_or_init(|| {
[
"alignas",
"alignof",
"and",
"and_eq",
"asm",
"auto",
"break",
"case",
"catch",
"class",
"concept",
"const",
"consteval",
"constexpr",
"constinit",
"continue",
"decltype",
"default",
"delete",
"do",
"else",
"enum",
"explicit",
"export",
"extern",
"false",
"for",
"friend",
"goto",
"if",
"inline",
"mutable",
"namespace",
"new",
"noexcept",
"not",
"not_eq",
"operator",
"or",
"or_eq",
"private",
"protected",
"public",
"register",
"reinterpret_cast",
"requires",
"return",
"sizeof",
"static",
"static_assert",
"static_cast",
"struct",
"switch",
"template",
"this",
"thread_local",
"throw",
"true",
"try",
"typedef",
"typeid",
"typename",
"union",
"using",
"virtual",
"volatile",
"while",
"xor",
"xor_eq",
"override",
"final",
]
.into_iter()
.collect()
})
}
fn ident_start(c: u8) -> bool {
c.is_ascii_alphabetic() || c == b'_'
}
fn ident_char(c: u8) -> bool {
c.is_ascii_alphanumeric() || c == b'_'
}
fn is_digit(c: u8) -> bool {
c.is_ascii_digit()
}
fn is_hex(c: u8) -> bool {
c.is_ascii_hexdigit()
}
/// One highlighted span of C++ source: [start, end) byte offsets, kind
/// is one of "keyword", "type", "string", "comment", "number",
/// "preprocessor". Pure function of the text (no GTK).
#[derive(Debug, Clone, PartialEq)]
pub struct HlSpan {
pub start: usize,
pub end: usize,
pub kind: &'static str,
}
pub fn theme_tokenize(code: &str) -> Vec<HlSpan> {
let b = code.as_bytes();
let n = b.len();
let mut out: Vec<HlSpan> = Vec::new();
let mut i = 0usize;
let mut line_start = true; // only whitespace seen so far on this line
while i < n {
let c = b[i];
if c == b'\n' {
line_start = true;
i += 1;
continue;
}
if line_start && (c == b' ' || c == b'\t' || c == b'\r') {
i += 1;
continue;
}
if line_start && c == b'#' {
let s = i;
while i < n && b[i] != b'\n' {
i += 1;
}
out.push(HlSpan {
start: s,
end: i,
kind: "preprocessor",
});
continue;
}
line_start = false;
if c == b'/' && i + 1 < n && b[i + 1] == b'/' {
let s = i;
while i < n && b[i] != b'\n' {
i += 1;
}
out.push(HlSpan {
start: s,
end: i,
kind: "comment",
});
continue;
}
if c == b'/' && i + 1 < n && b[i + 1] == b'*' {
let s = i;
i += 2;
while i + 1 < n && !(b[i] == b'*' && b[i + 1] == b'/') {
i += 1;
}
if i + 1 < n {
i += 2;
} else {
i = n;
}
out.push(HlSpan {
start: s,
end: i,
kind: "comment",
});
continue;
}
if c == b'"' {
let s = i;
i += 1;
while i < n && b[i] != b'"' && b[i] != b'\n' {
if b[i] == b'\\' && i + 1 < n {
i += 1;
}
i += 1;
}
if i < n && b[i] == b'"' {
i += 1;
}
out.push(HlSpan {
start: s,
end: i,
kind: "string",
});
continue;
}
if c == b'\'' {
// A ' between identifier/digit chars is a C++14 digit
// separator (1'000), not a character literal.
let sep = i > 0 && ident_char(b[i - 1]);
if !sep {
let s = i;
i += 1;
while i < n && b[i] != b'\'' && b[i] != b'\n' {
if b[i] == b'\\' && i + 1 < n {
i += 1;
}
i += 1;
}
if i < n && b[i] == b'\'' {
i += 1;
}
out.push(HlSpan {
start: s,
end: i,
kind: "string",
});
continue;
}
i += 1;
continue;
}
if is_digit(c) || (c == b'.' && i + 1 < n && is_digit(b[i + 1])) {
let s = i;
if c == b'0' && i + 1 < n && (b[i + 1] == b'x' || b[i + 1] == b'X') {
i += 2;
while i < n && (is_hex(b[i]) || b[i] == b'\'') {
i += 1;
}
} else {
while i < n
&& (is_digit(b[i])
|| b[i] == b'.'
|| b[i] == b'_'
|| b[i] == b'\''
|| b[i] == b'e'
|| b[i] == b'E'
|| ((b[i] == b'+' || b[i] == b'-')
&& i > s
&& (b[i - 1] == b'e' || b[i - 1] == b'E')))
{
i += 1;
}
while i < n && b[i].is_ascii_alphabetic() {
i += 1;
}
}
out.push(HlSpan {
start: s,
end: i,
kind: "number",
});
continue;
}
if ident_start(c) {
let s = i;
while i < n && ident_char(b[i]) {
i += 1;
}
let w = &code[s..i];
if type_words().contains(w) {
out.push(HlSpan {
start: s,
end: i,
kind: "type",
});
} else if keyword_words().contains(w) {
out.push(HlSpan {
start: s,
end: i,
kind: "keyword",
});
}
continue;
}
i += 1;
}
out
}
// ------------------------------------------------------------ current theme
struct CurrentTheme {
theme: CodeTheme,
loaded: bool,
}
static CURRENT: OnceLock<Mutex<CurrentTheme>> = OnceLock::new();
fn current_lock() -> &'static Mutex<CurrentTheme> {
CURRENT.get_or_init(|| {
Mutex::new(CurrentTheme {
theme: CodeTheme::default(),
loaded: false,
})
})
}
/// Theme currently in effect (loaded from disk on first call).
pub fn theme_current() -> CodeTheme {
let mut g = current_lock().lock().unwrap();
if !g.loaded {
let mut t = CodeTheme::default();
t.load(""); // missing file: defaults stand
g.theme = t;
g.loaded = true;
}
g.theme.clone()
}
/// Make `t` current and persist it.
pub fn theme_set_current(t: &CodeTheme) {
let mut g = current_lock().lock().unwrap();
g.theme = t.clone();
g.loaded = true;
g.theme.save("");
}
// ------------------------------------------------------------ GTK apply
fn ensure_tag(buf: &gtk::TextBuffer, name: &str, color: &str) -> gtk::TextTag {
let table = buf.tag_table().expect("text tag table");
if let Some(tag) = table.lookup(name) {
tag.set_property("foreground", color);
tag
} else {
let tag = gtk::TextTag::new(Some(name));
tag.set_property("foreground", color);
table.add(&tag);
tag
}
}
/// Apply the theme's token colours to a buffer: creates/updates tags
/// named "theme-keyword" etc., clears them over the whole buffer, then
/// applies theme_tokenize() spans. The buffer text is unchanged.
pub fn theme_highlight_buffer(buf: &gtk::TextBuffer, theme: &CodeTheme) {
let (start, end) = buf.bounds();
let text = buf
.text(&start, &end, false)
.map(|g| String::from(g.as_str()))
.unwrap_or_default();
let kinds = [
"keyword",
"type",
"string",
"comment",
"number",
"preprocessor",
];
let mut tags: Vec<(String, gtk::TextTag)> = Vec::new();
for k in kinds {
let color = match k {
"keyword" => &theme.keyword,
"type" => &theme.typ,
"string" => &theme.string,
"comment" => &theme.comment,
"number" => &theme.number,
_ => &theme.preprocessor,
};
let tag = ensure_tag(buf, &format!("theme-{}", k), color);
buf.remove_tag(&tag, &start, &end);
tags.push((k.to_string(), tag));
}
for sp in theme_tokenize(&text) {
let Some((_, tag)) = tags.iter().find(|(k, _)| k == sp.kind) else {
continue;
};
let sa = buf.iter_at_offset(sp.start as i32);
let sb = buf.iter_at_offset(sp.end as i32);
buf.apply_tag(tag, &sa, &sb);
}
}
/// Install the theme background/foreground on one text view (per-view
/// CSS provider, re-appliable).
pub fn theme_apply_to_view(view: &gtk::Widget, theme: &CodeTheme) {
// Per-view provider, stored on the widget like the C++ version
// (g_object_set_data). glib 0.18 exposes this only via unsafe.
let provider: gtk::CssProvider = unsafe {
match view.data::<gtk::CssProvider>("theme-css-provider") {
Some(ptr) => ptr.as_ref().clone(),
None => {
let p = gtk::CssProvider::new();
view.style_context()
.add_provider(&p, gtk::STYLE_PROVIDER_PRIORITY_USER);
view.set_data("theme-css-provider", p.clone());
p
}
}
};
if let Err(e) = provider.load_from_data(theme.css().as_bytes()) {
eprintln!("lightgui: theme CSS failed: {}", e);
}
}
// ------------------------------------------------------------ picker dialog
fn color_of_button(btn: &gtk::ColorButton) -> String {
let rgba = btn.rgba();
format!(
"#{:02x}{:02x}{:02x}",
(rgba.red() * 255.0 + 0.5) as u8,
(rgba.green() * 255.0 + 0.5) as u8,
(rgba.blue() * 255.0 + 0.5) as u8
)
}
fn set_button_color(btn: &gtk::ColorButton, hex: &str) {
let rgba = gdk::RGBA::parse(hex).unwrap_or_else(|_| gdk::RGBA::new(0.0, 0.0, 0.0, 1.0));
btn.set_rgba(&rgba);
}
/// Called with the chosen theme when the picker is applied.
pub type ThemeApplyCallback = Box<dyn Fn(&CodeTheme)>;
/// Open the theme picker dialog (theme combo + per-role colour buttons).
/// On Apply/OK the choice is saved, made current, and on_apply (if set)
/// is called so the caller can repaint open code views. Returns true on
/// Apply/OK, false on Cancel.
pub fn theme_picker_open(
parent: Option<&gtk::Window>,
on_apply: Option<ThemeApplyCallback>,
) -> bool {
use std::cell::RefCell;
use std::rc::Rc;
struct PickerCtx {
edited: CodeTheme,
combo: gtk::ComboBoxText,
buttons: BTreeMap<String, gtk::ColorButton>,
}
let ctx = Rc::new(RefCell::new(PickerCtx {
edited: theme_current(),
combo: gtk::ComboBoxText::new(),
buttons: BTreeMap::new(),
}));
let dlg = gtk::Dialog::with_buttons(
Some("Color Theme"),
parent,
gtk::DialogFlags::MODAL,
&[
("_Cancel", gtk::ResponseType::Cancel),
("_Apply", gtk::ResponseType::Apply),
],
);
dlg.set_default_size(420, 480);
let content = dlg.content_area();
let grid = gtk::Grid::new();
grid.set_row_spacing(6);
grid.set_column_spacing(12);
grid.set_margin_top(12);
grid.set_margin_bottom(12);
grid.set_margin_start(12);
grid.set_margin_end(12);
content.add(&grid);
let name_lbl = gtk::Label::new(Some("Theme"));
name_lbl.set_halign(gtk::Align::Start);
grid.attach(&name_lbl, 0, 0, 1, 1);
{
let c = ctx.borrow();
for n in CodeTheme::builtin_names() {
c.combo.append_text(&n);
}
let active = CodeTheme::builtin_names()
.iter()
.position(|n| *n == c.edited.name)
.unwrap_or(0) as u32;
c.combo.set_active(Some(active));
grid.attach(&c.combo, 1, 0, 1, 1);
}
let roles: [(&str, &str); 9] = [
("background", "Background"),
("foreground", "Foreground"),
("keyword", "Keyword"),
("type", "Type"),
("string", "String"),
("comment", "Comment"),
("number", "Number"),
("preprocessor", "Preprocessor"),
("current_line", "Current line"),
];
for (row, (role, label)) in roles.iter().enumerate() {
let lbl = gtk::Label::new(Some(label));
lbl.set_halign(gtk::Align::Start);
grid.attach(&lbl, 0, (row + 1) as i32, 1, 1);
let btn = gtk::ColorButton::new();
btn.set_title(label);
{
let c = ctx.borrow();
let field: &str = match *role {
"background" => &c.edited.background,
"foreground" => &c.edited.foreground,
"keyword" => &c.edited.keyword,
"type" => &c.edited.typ,
"string" => &c.edited.string,
"comment" => &c.edited.comment,
"number" => &c.edited.number,
"preprocessor" => &c.edited.preprocessor,
_ => &c.edited.current_line,
};
set_button_color(&btn, field);
}
grid.attach(&btn, 1, (row + 1) as i32, 1, 1);
ctx.borrow_mut().buttons.insert(role.to_string(), btn);
}
let note = gtk::Label::new(Some(
"Pick a built-in theme, then tweak any colour.\nApply saves to ~/.config/lightgui/theme.conf.",
));
note.set_line_wrap(true);
note.set_halign(gtk::Align::Start);
grid.attach(&note, 0, 10, 2, 1);
{
let ctx2 = Rc::clone(&ctx);
ctx.borrow().combo.connect_changed(move |combo| {
if let Some(name) = combo.active_text() {
let base = CodeTheme::builtin(&name);
let mut c = ctx2.borrow_mut();
c.edited = base;
for (role, btn) in c.buttons.iter() {
let field: &str = match role.as_str() {
"background" => &c.edited.background,
"foreground" => &c.edited.foreground,
"keyword" => &c.edited.keyword,
"type" => &c.edited.typ,
"string" => &c.edited.string,
"comment" => &c.edited.comment,
"number" => &c.edited.number,
"preprocessor" => &c.edited.preprocessor,
_ => &c.edited.current_line,
};
set_button_color(btn, field);
}
}
});
}
dlg.show_all();
let resp = dlg.run();
let mut applied = false;
if resp == gtk::ResponseType::Apply {
let cols: Vec<(String, String)> = {
let c = ctx.borrow();
c.buttons
.iter()
.map(|(role, btn)| (role.clone(), color_of_button(btn)))
.collect()
};
let mut c = ctx.borrow_mut();
for (role, col) in cols {
match role.as_str() {
"background" => c.edited.background = col,
"foreground" => c.edited.foreground = col,
"keyword" => c.edited.keyword = col,
"type" => c.edited.typ = col,
"string" => c.edited.string = col,
"comment" => c.edited.comment = col,
"number" => c.edited.number = col,
"preprocessor" => c.edited.preprocessor = col,
_ => c.edited.current_line = col,
}
}
// If colours were tweaked away from the named built-in, the
// stored name still records the base theme.
theme_set_current(&c.edited);
if let Some(cb) = on_apply.as_ref() {
cb(&c.edited);
}
applied = true;
}
dlg.close();
applied
}
#[cfg(test)]
mod tests {
use super::*;
fn has_span(spans: &[HlSpan], code: &str, kind: &str, word: &str) -> bool {
spans
.iter()
.any(|sp| sp.kind == kind && &code[sp.start..sp.end] == word)
}
#[test]
fn builtins() {
let names = CodeTheme::builtin_names();
assert_eq!(names, vec!["Light", "Dark", "Monokai", "Solarized Dark"]);
let light = CodeTheme::builtin("Light");
let dark = CodeTheme::builtin("Dark");
let mono = CodeTheme::builtin("Monokai");
let solar = CodeTheme::builtin("Solarized Dark");
assert!(light.keyword != dark.keyword);
assert!(dark.keyword != mono.keyword);
assert!(mono.keyword != solar.keyword);
assert!(light.background != dark.background);
assert!(dark.background != mono.background);
assert_eq!(CodeTheme::builtin("Nope").name, "Light");
assert!(CodeTheme::is_builtin("Dark"));
assert!(!CodeTheme::is_builtin("Custom"));
}
#[test]
fn valid_color_cases() {
assert!(CodeTheme::valid_color("#1a2b3c"));
assert!(CodeTheme::valid_color("#FFFFFF"));
assert!(!CodeTheme::valid_color("red"));
assert!(!CodeTheme::valid_color("#12345"));
assert!(!CodeTheme::valid_color("#gggggg"));
assert!(!CodeTheme::valid_color(""));
}
#[test]
fn save_load_roundtrip() {
let dir = std::env::temp_dir().join("lightgui_theme_unit");
let _ = std::fs::create_dir_all(&dir);
let p = dir.join("theme.conf");
let mut custom = CodeTheme::builtin("Dark");
custom.keyword = "#ff0000".to_string();
assert!(custom.save(p.to_str().unwrap()));
let mut reloaded = CodeTheme::default();
assert!(reloaded.load(p.to_str().unwrap()));
assert_eq!(reloaded.name, "Dark");
assert_eq!(reloaded.keyword, "#ff0000");
assert_eq!(reloaded.background, CodeTheme::builtin("Dark").background);
// Missing file: load fails, defaults kept.
let mut miss = CodeTheme::default();
assert!(!miss.load("/tmp/lightgui_theme_no_such_unit.conf"));
assert_eq!(miss.name, "Light");
// Garbage in the file does not break loading; bad colours ignored.
let g = dir.join("garbage.conf");
std::fs::write(
&g,
"# comment\nnot-a-kv-line\ntheme=Dark\nkeyword=red\nbackground=#1e1e1e\n",
)
.unwrap();
let mut garb = CodeTheme::default();
assert!(garb.load(g.to_str().unwrap()));
let dark = CodeTheme::builtin("Dark");
assert_eq!(garb.name, "Dark");
assert_eq!(garb.keyword, dark.keyword);
assert_eq!(garb.background, "#1e1e1e");
}
#[test]
fn tokenizer_spans() {
let sample =
"#include <gtk/gtk.h>\n// hi\nint main() { const char* s = \"x\"; return 42; }\n";
let spans = theme_tokenize(sample);
assert!(has_span(
&spans,
sample,
"preprocessor",
"#include <gtk/gtk.h>"
));
assert!(has_span(&spans, sample, "comment", "// hi"));
assert!(has_span(&spans, sample, "type", "int"));
assert!(has_span(&spans, sample, "keyword", "return"));
assert!(has_span(&spans, sample, "string", "\"x\""));
assert!(has_span(&spans, sample, "number", "42"));
let sample2 =
"/* { not a fold */\nchar c = 'x';\nint n = 1'000;\nconst char* s = \"a{b\";\nfloat f = 1.5e-3;\n";
let spans2 = theme_tokenize(sample2);
assert!(has_span(&spans2, sample2, "comment", "/* { not a fold */"));
assert!(has_span(&spans2, sample2, "string", "'x'"));
assert!(has_span(&spans2, sample2, "number", "1'000"));
}
}