Files
lightgui_rust/crates/lightgui-support/tests/theme_tests.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

397 lines
14 KiB
Rust

// Theme + code-view gutter/folding tests — Rust port of
// tests/theme_tests.cpp (sections 1-8). Run under Xvfb:
// xvfb-run -a cargo test -p lightgui-support --test theme_tests
// HOME is redirected to a scratch dir so no real config is touched.
// Section 9 of the C++ harness (debugger_toggle_breakpoint) belongs to
// the debugger UI window (debugger_ui.cpp, designer scope), not to
// this crate, and is intentionally not ported here.
// The whole suite runs as one #[test] because theme_current() is a
// process-wide global, exactly like the C++ harness's single main().
use gtk::prelude::*;
use lightgui_support::codeview::{codeview_find_regions, codeview_visible_lines, CodeView};
use lightgui_support::theme::{theme_current, theme_set_current, theme_tokenize, CodeTheme};
use std::collections::BTreeSet;
struct Checker {
pass: usize,
fail: usize,
failed: Vec<String>,
}
impl Checker {
fn check(&mut self, cond: bool, name: &str) {
if cond {
self.pass += 1;
println!("PASS {}", name);
} else {
self.fail += 1;
self.failed.push(name.to_string());
println!("FAIL {}", name);
}
}
fn finish(&self) {
println!("THEME TESTS: {} pass, {} fail", self.pass, self.fail);
if !self.failed.is_empty() {
panic!("FAILED: {}", self.failed.join(" "));
}
}
}
fn file_contains(path: &str, needle: &str) -> bool {
std::fs::read_to_string(path)
.map(|s| s.contains(needle))
.unwrap_or(false)
}
// The fold sample used by both the pure-logic and widget checks.
fn fold_lines() -> Vec<String> {
vec![
"#region Outer".to_string(),
"class Foo {".to_string(),
" void bar() {".to_string(),
" if (x) {".to_string(),
" work();".to_string(),
" }".to_string(),
" /* multi".to_string(),
" line */".to_string(),
" }".to_string(),
"};".to_string(),
"#endregion".to_string(),
"#if DEBUG".to_string(),
"int d = 1;".to_string(),
"#endif".to_string(),
"}".to_string(),
"int leftover() {".to_string(),
" return 1;".to_string(),
]
}
fn join_lines(lines: &[String]) -> String {
lines.iter().map(|l| format!("{}\n", l)).collect()
}
#[test]
fn theme_suite() {
// Isolate all HOME-based config (theme file).
std::env::set_var("HOME", "/tmp/lightgui_theme_home_rust");
std::env::set_var("LIGHTGUI_THEME_CONF", "");
gtk::init().expect("gtk::init");
let mut ck = Checker {
pass: 0,
fail: 0,
failed: Vec::new(),
};
// 1. Built-in themes.
let names = CodeTheme::builtin_names();
ck.check(names.len() == 4, "builtins-count-4");
ck.check(
names[0] == "Light"
&& names[1] == "Dark"
&& names[2] == "Monokai"
&& names[3] == "Solarized Dark",
"builtins-names",
);
let light = CodeTheme::builtin("Light");
let dark = CodeTheme::builtin("Dark");
let mono = CodeTheme::builtin("Monokai");
let solar = CodeTheme::builtin("Solarized Dark");
ck.check(
light.keyword != dark.keyword
&& dark.keyword != mono.keyword
&& mono.keyword != solar.keyword,
"builtins-distinct-keywords",
);
ck.check(
light.background != dark.background && dark.background != mono.background,
"builtins-distinct-backgrounds",
);
ck.check(
CodeTheme::builtin("Nope").name == "Light",
"builtin-unknown-light",
);
ck.check(
CodeTheme::is_builtin("Dark") && !CodeTheme::is_builtin("Custom"),
"is-builtin",
);
// 2. Colour validation.
ck.check(
CodeTheme::valid_color("#1a2b3c")
&& CodeTheme::valid_color("#FFFFFF")
&& !CodeTheme::valid_color("red")
&& !CodeTheme::valid_color("#12345")
&& !CodeTheme::valid_color("#gggggg")
&& !CodeTheme::valid_color(""),
"valid-color",
);
// 3. Save / load round-trip at an explicit path, incl. custom colour.
let mut custom = dark.clone();
custom.keyword = "#ff0000".to_string();
let tpath = "/tmp/lightgui_theme_harness_rust.conf";
ck.check(custom.save(tpath), "save-roundtrip");
let mut reloaded = CodeTheme::default();
ck.check(reloaded.load(tpath), "load-roundtrip");
ck.check(
reloaded.name == "Dark"
&& reloaded.keyword == "#ff0000"
&& reloaded.background == dark.background,
"roundtrip-values",
);
// Missing file: load fails, defaults kept.
let mut miss = CodeTheme::default();
ck.check(
!miss.load("/tmp/lightgui_theme_no_such_rust.conf"),
"load-missing-fails",
);
ck.check(miss.name == "Light", "load-missing-keeps-defaults");
// Garbage in the file does not break loading; bad colours ignored.
std::fs::write(
"/tmp/lightgui_theme_garbage_rust.conf",
"# comment\nnot-a-kv-line\ntheme=Dark\nkeyword=red\nbackground=#1e1e1e\n",
)
.unwrap();
let mut garb = CodeTheme::default();
ck.check(
garb.load("/tmp/lightgui_theme_garbage_rust.conf"),
"load-garbage-file",
);
ck.check(
garb.name == "Dark" && garb.keyword == dark.keyword && garb.background == "#1e1e1e",
"garbage-bad-colour-ignored",
);
// 4. Default-path persistence (HOME is redirected above).
let dp = CodeTheme::builtin("Monokai");
theme_set_current(&dp);
ck.check(
file_contains(
"/tmp/lightgui_theme_home_rust/.config/lightgui/theme.conf",
"theme=Monokai",
),
"default-path-persists",
);
let cur = theme_current();
ck.check(
cur.name == "Monokai" && cur.keyword == mono.keyword,
"theme-current-roundtrip",
);
// 5. Tokeniser spans.
let sample = "#include <gtk/gtk.h>\n// hi\nint main() { const char* s = \"x\"; return 42; }\n";
let spans = theme_tokenize(sample);
let has_span = |kind: &str, word: &str| {
spans
.iter()
.any(|sp| sp.kind == kind && &sample[sp.start..sp.end] == word)
};
ck.check(
has_span("preprocessor", "#include <gtk/gtk.h>"),
"token-preprocessor",
);
ck.check(has_span("comment", "// hi"), "token-line-comment");
ck.check(has_span("type", "int"), "token-type");
ck.check(has_span("keyword", "return"), "token-keyword");
ck.check(has_span("string", "\"x\""), "token-string");
ck.check(has_span("number", "42"), "token-number");
// Block comment, char literal, digit separator, string with brace.
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);
let (mut block_ok, mut char_ok, mut num_ok) = (false, false, false);
for sp in &spans2 {
let w = &sample2[sp.start..sp.end];
if sp.kind == "comment" && w == "/* { not a fold */" {
block_ok = true;
}
if sp.kind == "string" && w == "'x'" {
char_ok = true;
}
if sp.kind == "number" && w == "1'000" {
num_ok = true;
}
}
ck.check(block_ok, "token-block-comment");
ck.check(char_ok, "token-char-literal");
ck.check(num_ok, "token-digit-separator");
// 6. Fold regions: braces, region, comment, #if, nesting, unbalanced.
let flines = fold_lines();
let regs = codeview_find_regions(&flines);
ck.check(regs.len() == 6, "regions-count-6");
let has_region = |st: i32, en: i32, kind: &str| {
regs.iter()
.any(|r| r.start_line == st && r.end_line == en && r.kind == kind)
};
ck.check(has_region(0, 10, "region"), "region-outer");
ck.check(has_region(1, 9, "brace"), "brace-class");
ck.check(has_region(2, 8, "brace"), "brace-method");
ck.check(has_region(3, 5, "brace"), "brace-if");
ck.check(has_region(6, 7, "comment"), "region-comment");
ck.check(has_region(11, 13, "preproc"), "region-if");
let mut depth_of = [-1i32; 17];
for r in &regs {
depth_of[r.start_line as usize] = r.depth;
}
ck.check(
depth_of[0] == 0
&& depth_of[1] == 1
&& depth_of[2] == 2
&& depth_of[3] == 3
&& depth_of[6] == 3
&& depth_of[11] == 0,
"regions-depths-nested",
);
// No region starts at the extra close (14) or the unclosed brace (15).
let bad_start = regs
.iter()
.any(|r| r.start_line == 14 || r.start_line == 15);
ck.check(!bad_start, "unbalanced-no-bogus-region");
// A brace inside a string / comment opens no fold.
let trick = vec![
"const char* s = \"{\";".to_string(),
"/* { */".to_string(),
"int ok() {".to_string(),
" return 0;".to_string(),
"}".to_string(),
];
let tregs = codeview_find_regions(&trick);
ck.check(
tregs.len() == 1 && tregs[0].start_line == 2 && tregs[0].end_line == 4,
"braces-in-string-comment-ignored",
);
// Single-line block: nothing to fold.
let sregs = codeview_find_regions(&["int f() { return 0; }".to_string()]);
ck.check(sregs.is_empty(), "single-line-block-no-fold");
// Comment-style region markers (the form the generator emits:
// `// #region Name` / `// #endregion`) fold like bare #region.
// An unclosed one and one inside a string open no fold.
let clines = vec![
" // #region Widget".to_string(),
" int x = 1;".to_string(),
" // #endregion".to_string(),
" // #region Open".to_string(),
" int y = 2;".to_string(),
"const char* s = \"// #region nope\";".to_string(),
];
let cregs = codeview_find_regions(&clines);
let cok = cregs
.iter()
.any(|r| r.start_line == 0 && r.end_line == 2 && r.kind == "region");
ck.check(cok, "comment-region-folds");
ck.check(cregs.len() == 1, "comment-region-count-1");
// 7. Visible lines under folds.
let mut folded = BTreeSet::new();
folded.insert(0);
let vis = codeview_visible_lines(&flines, &folded);
ck.check(
vis.len() == 8 && vis[0] == 0 && vis[1] == 10,
"visible-fold-region",
);
let mut folded = BTreeSet::new();
folded.insert(2);
let vis = codeview_visible_lines(&flines, &folded);
ck.check(vis.len() == 12, "visible-fold-method");
let mut folded = BTreeSet::new();
folded.insert(0);
folded.insert(2);
let vis = codeview_visible_lines(&flines, &folded);
ck.check(vis.len() == 8, "visible-nested-fold-same-as-outer");
let mut folded = BTreeSet::new();
folded.insert(3);
let vis = codeview_visible_lines(&flines, &folded);
ck.check(
vis.len() == 16 && vis[3] == 3 && vis[4] == 5,
"visible-fold-if-only",
);
// 8. Widget level: regions, fold toggle, gutter clicks, current
// line, theme switch changing the tag colour, real fold collapse.
let win = gtk::Window::new(gtk::WindowType::Toplevel);
let cv = CodeView::new();
win.add(&cv.widget());
win.show_all();
while gtk::events_pending() {
gtk::main_iteration();
}
cv.set_text(&join_lines(&flines), "/tmp/lightgui_codeview_test.cpp");
while gtk::events_pending() {
gtk::main_iteration();
}
ck.check(cv.line_count() == 17, "widget-line-count");
ck.check(cv.regions().len() == 6, "widget-regions");
ck.check(cv.toggle_fold_at(3), "widget-fold-toggle-ok");
ck.check(cv.is_folded(3), "widget-folded");
ck.check(!cv.toggle_fold_at(5), "widget-fold-no-region-start");
cv.gutter_click(3, true);
ck.check(!cv.is_folded(3), "widget-gutter-fold-click-unfolds");
cv.gutter_click(5, false);
ck.check(
cv.breakpoint_lines().contains(&5),
"widget-gutter-bp-click-sets",
);
cv.gutter_click(5, false);
ck.check(
cv.breakpoint_lines().is_empty(),
"widget-gutter-bp-click-clears",
);
cv.set_current_line(4);
ck.check(cv.current_line() == 4, "widget-current-line");
// Theme switch changes the keyword tag colour. "foreground" is
// write-only and "foreground-rgba" does not read back on this GTK,
// so — exactly as the C++ harness does — read "foreground-gdk"
// (16-bit, 8-bit values as v*257). Dark keyword #569cd6.
cv.set_theme(&dark);
let cbuf = cv.text_view().buffer().expect("buffer");
let kw = cbuf.tag_table().expect("tag table").lookup("theme-keyword");
// g_object_get hands back a *copy* of the boxed GdkColor, so pass
// a pointer-to-pointer and free the copy with gdk_color_free.
let mut col_ptr: *mut gdk::Color = std::ptr::null_mut();
if let Some(tag) = kw.as_ref() {
unsafe {
glib::gobject_ffi::g_object_get(
tag.as_ptr() as *mut glib::gobject_ffi::GObject,
c"foreground-gdk".as_ptr(),
&mut col_ptr as *mut *mut gdk::Color,
std::ptr::null_mut::<std::ffi::c_void>(),
);
}
}
let col = if col_ptr.is_null() {
gdk::Color {
pixel: 0,
red: 0,
green: 0,
blue: 0,
}
} else {
let c = unsafe { *col_ptr };
unsafe { gdk::ffi::gdk_color_free(col_ptr) };
c
};
ck.check(
kw.is_some() && col.red / 257 == 0x56 && col.green / 257 == 0x9c && col.blue / 257 == 0xd6,
"widget-theme-switch-changes-tag",
);
// Real collapse: fold bar() (lines 3..8, 1-based) and check the
// hidden buffer lines report zero height.
cv.toggle_fold_at(3);
while gtk::events_pending() {
gtk::main_iteration();
}
{
let tv = cv.text_view();
let it4 = cbuf.iter_at_line(3); // file line 4
let (_, h4) = tv.line_yrange(&it4);
let it7 = cbuf.iter_at_line(6); // file line 7
let (_, h7) = tv.line_yrange(&it7);
ck.check(h4 == 0 && h7 == 0, "widget-fold-collapses-lines");
}
win.close();
ck.finish();
}