From 3d5328138835687a28a961bd35049ec8da326483 Mon Sep 17 00:00:00 2001 From: cnmcdee Date: Sun, 29 Nov 2026 06:10:11 +0000 Subject: [PATCH] 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. --- .gitignore | 3 + Cargo.lock | 169 +- Cargo.toml | 4 +- crates/lightgui-debug/Cargo.toml | 11 + crates/lightgui-debug/src/lib.rs | 30 + crates/lightgui-debug/src/mi.rs | 351 ++++ crates/lightgui-debug/src/session.rs | 1419 +++++++++++++++++ crates/lightgui-debug/src/types.rs | 578 +++++++ crates/lightgui-debug/tests/common/mod.rs | 133 ++ crates/lightgui-debug/tests/console.rs | 832 ++++++++++ crates/lightgui-debug/tests/gtk.rs | 152 ++ .../lightgui-debug/tests/targets/console.cpp | 32 + .../lightgui-debug/tests/targets/gtkapp.cpp | 50 + crates/lightgui-debug/tests/targets/spin.cpp | 12 + crates/lightgui-support/Cargo.toml | 14 + crates/lightgui-support/src/cmake.rs | 352 ++++ crates/lightgui-support/src/codeview.rs | 1167 ++++++++++++++ crates/lightgui-support/src/lib.rs | 34 + crates/lightgui-support/src/preferences.rs | 429 +++++ crates/lightgui-support/src/theme.rs | 936 +++++++++++ crates/lightgui-support/tests/cmake_tests.rs | 202 +++ crates/lightgui-support/tests/font_tests.rs | 180 +++ crates/lightgui-support/tests/theme_tests.rs | 396 +++++ 23 files changed, 7481 insertions(+), 5 deletions(-) create mode 100644 crates/lightgui-debug/Cargo.toml create mode 100644 crates/lightgui-debug/src/lib.rs create mode 100644 crates/lightgui-debug/src/mi.rs create mode 100644 crates/lightgui-debug/src/session.rs create mode 100644 crates/lightgui-debug/src/types.rs create mode 100644 crates/lightgui-debug/tests/common/mod.rs create mode 100644 crates/lightgui-debug/tests/console.rs create mode 100644 crates/lightgui-debug/tests/gtk.rs create mode 100644 crates/lightgui-debug/tests/targets/console.cpp create mode 100644 crates/lightgui-debug/tests/targets/gtkapp.cpp create mode 100644 crates/lightgui-debug/tests/targets/spin.cpp create mode 100644 crates/lightgui-support/Cargo.toml create mode 100644 crates/lightgui-support/src/cmake.rs create mode 100644 crates/lightgui-support/src/codeview.rs create mode 100644 crates/lightgui-support/src/lib.rs create mode 100644 crates/lightgui-support/src/preferences.rs create mode 100644 crates/lightgui-support/src/theme.rs create mode 100644 crates/lightgui-support/tests/cmake_tests.rs create mode 100644 crates/lightgui-support/tests/font_tests.rs create mode 100644 crates/lightgui-support/tests/theme_tests.rs diff --git a/.gitignore b/.gitignore index 7a60b85..8782eff 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,5 @@ __pycache__/ *.pyc +/target +/test-results +/screenshots diff --git a/Cargo.lock b/Cargo.lock index 0e3cae7..efa467c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,35 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "atk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b" +dependencies = [ + "atk-sys", + "glib", + "libc", +] + +[[package]] +name = "atk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + [[package]] name = "bitflags" version = "2.13.2" @@ -59,6 +88,16 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "field-offset" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f" +dependencies = [ + "memoffset", + "rustc_version", +] + [[package]] name = "futures-channel" version = "0.3.34" @@ -251,7 +290,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc" dependencies = [ "heck 0.4.1", - "proc-macro-crate", + "proc-macro-crate 2.0.2", "proc-macro-error", "proc-macro2", "quote", @@ -279,6 +318,58 @@ dependencies = [ "system-deps", ] +[[package]] +name = "gtk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a" +dependencies = [ + "atk", + "cairo-rs", + "field-offset", + "futures-channel", + "gdk", + "gdk-pixbuf", + "gio", + "glib", + "gtk-sys", + "gtk3-macros", + "libc", + "pango", + "pkg-config", +] + +[[package]] +name = "gtk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414" +dependencies = [ + "atk-sys", + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "system-deps", +] + +[[package]] +name = "gtk3-macros" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d" +dependencies = [ + "proc-macro-crate 1.3.1", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "hashbrown" version = "0.17.2" @@ -334,6 +425,21 @@ dependencies = [ "libc", ] +[[package]] +name = "lightgui-designer" +version = "0.1.0" +dependencies = [ + "cairo-rs", + "gdk", + "gdk-pixbuf", + "glib", + "gtk", + "lightgui-core", + "lightgui-gen", + "pango", + "serde_json", +] + [[package]] name = "lightgui-gen" version = "0.1.0" @@ -341,6 +447,18 @@ dependencies = [ "lightgui-core", ] +[[package]] +name = "lightgui-support" +version = "0.1.0" +dependencies = [ + "cairo-rs", + "gdk", + "glib", + "gtk", + "lightgui-debug", + "pango", +] + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -353,6 +471,15 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -396,6 +523,16 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" +[[package]] +name = "proc-macro-crate" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +dependencies = [ + "once_cell", + "toml_edit 0.19.15", +] + [[package]] name = "proc-macro-crate" version = "2.0.2" @@ -403,7 +540,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24" dependencies = [ "toml_datetime", - "toml_edit", + "toml_edit 0.20.2", ] [[package]] @@ -448,6 +585,15 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rustix" version = "1.1.6" @@ -461,6 +607,12 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -605,7 +757,7 @@ dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit", + "toml_edit 0.20.2", ] [[package]] @@ -617,6 +769,17 @@ dependencies = [ "serde", ] +[[package]] +name = "toml_edit" +version = "0.19.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" +dependencies = [ + "indexmap", + "toml_datetime", + "winnow", +] + [[package]] name = "toml_edit" version = "0.20.2" diff --git a/Cargo.toml b/Cargo.toml index 12bf41b..8a401a9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,6 +3,7 @@ resolver = "2" members = [ "crates/lightgui-core", "crates/lightgui-gen", + "crates/lightgui-designer", "crates/lightgui-debug", "crates/xframe-common", "crates/xframe-demo", @@ -12,7 +13,7 @@ members = [ "crates/xframe-core", "crates/xframe-indicators", "crates/xframe-widgets", - # TEMP-xframe-apps: "crates/lightgui-support", # no targets yet, restore before commit + "crates/lightgui-support", ] exclude = ["probe"] @@ -23,7 +24,6 @@ glib = "0.18" pango = "0.18" cairo-rs = "0.18" libc = "0.2" -serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" [profile.dev] diff --git a/crates/lightgui-debug/Cargo.toml b/crates/lightgui-debug/Cargo.toml new file mode 100644 index 0000000..75ac8a6 --- /dev/null +++ b/crates/lightgui-debug/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "lightgui-debug" +version = "0.1.0" +edition = "2021" +description = "LightGUI stepping debugger — GDB/MI backend (port of src/debugger.cpp/.h)" +license = "MIT" + +[dependencies] +libc = { workspace = true } + +[dev-dependencies] diff --git a/crates/lightgui-debug/src/lib.rs b/crates/lightgui-debug/src/lib.rs new file mode 100644 index 0000000..d6a604b --- /dev/null +++ b/crates/lightgui-debug/src/lib.rs @@ -0,0 +1,30 @@ +//! LightGUI stepping debugger — GDB/MI backend (no GTK dependency). +//! +//! Port of `src/debugger.h` / `src/debugger.cpp` from lightgui +//! (`eb0b5fc`). Drives a real gdb process over the machine interface +//! (`gdb -q -i=mi2`): launch target, breakpoints, step over/into/out, +//! continue, kill, restart, locals / watches / stack frames, target +//! stdout/stderr capture. +//! +//! Target output: in MI mode gdb forwards the inferior's stdout/stderr +//! as bare lines on gdb's stdout (not `@"..."` records); the parser +//! treats any line with no MI prefix as target output. Breakpoints may +//! resolve to several locations; the breakpoint id reported is the +//! parent number. +//! +//! Breakpoint handlers: every breakpoint carries a kind — plain, +//! conditional (stops only when a gdb expression is true, via +//! `-break-condition`) or logpoint (a gdb dprintf: prints a message and +//! never stops). Any kind may also carry an ignore count and a group +//! label. See `Breakpoint` for the full contract. + +pub mod mi; +pub mod session; +pub mod types; + +pub use mi::{mi_parse_value, mi_unescape, MiValue}; +pub use session::GdbSession; +pub use types::{ + bp_kind_from_name, bp_kind_name, logpoint_to_printf, parse_breakpoint_location, BpKind, + Breakpoint, DbgState, DebuggerSettings, StackFrame, StopInfo, Variable, +}; diff --git a/crates/lightgui-debug/src/mi.rs b/crates/lightgui-debug/src/mi.rs new file mode 100644 index 0000000..9a02bf6 --- /dev/null +++ b/crates/lightgui-debug/src/mi.rs @@ -0,0 +1,351 @@ +// Minimal GDB/MI value parser — direct port of the MI parsing half of +// src/debugger.cpp (mi_unescape, mi_parse_value, mi_parse_fields). +// A value is a string, a tuple {k=v,...} or a list [v,...]; the C++ +// MiValue holds all three at once (str + tuple + list), and this port +// keeps that shape so callers read fields the same way. + +use std::collections::BTreeMap; + +/// Minimal MI value: string, tuple {k=v,...} or list [v,...]. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct MiValue { + pub str_: String, + pub tuple: BTreeMap, + pub list: Vec, + pub is_list: bool, + pub is_tuple: bool, +} + +impl MiValue { + pub fn get(&self, key: &str) -> Option<&MiValue> { + self.tuple.get(key) + } + + pub fn get_str(&self, key: &str) -> &str { + self.get(key).map(|v| v.str_.as_str()).unwrap_or("") + } + + pub fn get_str_or(&self, key: &str, dflt: &str) -> String { + match self.get(key) { + Some(v) => v.str_.clone(), + None => dflt.to_string(), + } + } +} + +/// Decode an MI C-escaped string body (no surrounding quotes). +pub fn mi_unescape(s: &str) -> String { + let b = s.as_bytes(); + let mut out = String::with_capacity(s.len()); + let mut i = 0; + while i < b.len() { + if b[i] == b'\\' && i + 1 < b.len() { + let c = b[i + 1] as char; + i += 2; + match c { + 'n' => out.push('\n'), + 't' => out.push('\t'), + 'r' => out.push('\r'), + '"' => out.push('"'), + '\\' => out.push('\\'), + // \0nnn octal etc: keep char + _ => out.push(c), + } + } else { + out.push(b[i] as char); + i += 1; + } + } + out +} + +fn mi_skip_ws(s: &[u8], pos: &mut usize) { + while *pos < s.len() && (s[*pos] == b' ' || s[*pos] == b'\t') { + *pos += 1; + } +} + +fn mi_parse_string(s: &[u8], pos: &mut usize, out: &mut String) -> bool { + if *pos >= s.len() || s[*pos] != b'"' { + return false; + } + *pos += 1; + let mut raw = String::new(); + while *pos < s.len() { + let c = s[*pos]; + *pos += 1; + if c == b'\\' && *pos < s.len() { + raw.push('\\'); + raw.push(s[*pos] as char); + *pos += 1; + } else if c == b'"' { + *out = mi_unescape(&raw); + return true; + } else { + raw.push(c as char); + } + } + false +} + +/// Parse one MI value starting at s[pos]; advances pos. +pub fn mi_parse_value(s: &str, pos: &mut usize, out: &mut MiValue) -> bool { + let b = s.as_bytes(); + mi_skip_ws(b, pos); + if *pos >= b.len() { + return false; + } + *out = MiValue::default(); + let c = b[*pos]; + if c == b'"' { + return mi_parse_string(b, pos, &mut out.str_); + } + if c == b'{' { + out.is_tuple = true; + *pos += 1; + loop { + mi_skip_ws(b, pos); + if *pos >= b.len() { + return false; + } + if b[*pos] == b'}' { + *pos += 1; + return true; + } + let ks = *pos; + while *pos < b.len() && b[*pos] != b'=' && b[*pos] != b',' && b[*pos] != b'}' { + *pos += 1; + } + let key = s[ks..*pos].to_string(); + if *pos < b.len() && b[*pos] == b'=' { + *pos += 1; + let mut v = MiValue::default(); + if !mi_parse_value(s, pos, &mut v) { + return false; + } + out.tuple.insert(key, v); + } else { + // Bare value inside a tuple. + let v = MiValue { + str_: key, + ..Default::default() + }; + out.list.push(v); + } + mi_skip_ws(b, pos); + if *pos < b.len() && b[*pos] == b',' { + *pos += 1; + continue; + } + if *pos < b.len() && b[*pos] == b'}' { + *pos += 1; + return true; + } + return false; + } + } + if c == b'[' { + out.is_list = true; + *pos += 1; + loop { + mi_skip_ws(b, pos); + if *pos >= b.len() { + return false; + } + if b[*pos] == b']' { + *pos += 1; + return true; + } + // List element: either a value or key=value (result-record + // style). NOTE: an element starting with '{', '[' or '"' is + // a plain value; scanning it for '=' would mistake the + // tuple's first key for a list-level key and corrupt the + // parse. + let save = *pos; + if *pos < b.len() && (b[*pos] == b'{' || b[*pos] == b'[' || b[*pos] == b'"') { + let mut v = MiValue::default(); + if !mi_parse_value(s, pos, &mut v) { + return false; + } + out.list.push(v); + mi_skip_ws(b, pos); + if *pos < b.len() && b[*pos] == b',' { + *pos += 1; + continue; + } + if *pos < b.len() && b[*pos] == b']' { + *pos += 1; + return true; + } + return false; + } + let ks = *pos; + while *pos < b.len() && b[*pos] != b'=' && b[*pos] != b',' && b[*pos] != b']' { + *pos += 1; + } + if *pos < b.len() && b[*pos] == b'=' { + let key = s[ks..*pos].to_string(); + *pos += 1; + let mut v = MiValue::default(); + if !mi_parse_value(s, pos, &mut v) { + return false; + } + let mut pair = MiValue { + is_tuple: true, + ..Default::default() + }; + pair.tuple.insert(key, v); + out.list.push(pair); + } else { + *pos = save; + let mut v = MiValue::default(); + if !mi_parse_value(s, pos, &mut v) { + return false; + } + out.list.push(v); + } + mi_skip_ws(b, pos); + if *pos < b.len() && b[*pos] == b',' { + *pos += 1; + continue; + } + if *pos < b.len() && b[*pos] == b']' { + *pos += 1; + return true; + } + return false; + } + } + // Bare token up to , } ] + let start = *pos; + while *pos < b.len() && b[*pos] != b',' && b[*pos] != b'}' && b[*pos] != b']' { + *pos += 1; + } + out.str_ = s[start..*pos].to_string(); + true +} + +/// Parse the comma-separated key=value fields after a record prefix into +/// a tuple MiValue (e.g. after "*stopped," or "1^done,"). +pub fn mi_parse_fields(s: &str) -> MiValue { + let mut out = MiValue { + is_tuple: true, + ..Default::default() + }; + let mut p = 0usize; + while p < s.len() { + let b = s.as_bytes(); + mi_skip_ws(b, &mut p); + if p >= s.len() { + break; + } + let ks = p; + while p < s.len() && b[p] != b'=' && b[p] != b',' { + p += 1; + } + let key = s[ks..p].to_string(); + if p < s.len() && b[p] == b'=' { + p += 1; + let mut v = MiValue::default(); + if !mi_parse_value(s, &mut p, &mut v) { + break; + } + out.tuple.insert(key, v); + } else if !key.is_empty() { + let v = MiValue { + str_: key, + ..Default::default() + }; + out.list.push(v); + } + if p < s.len() && b[p] == b',' { + p += 1; + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(s: &str) -> Option { + let mut v = MiValue::default(); + let mut p = 0; + if mi_parse_value(s, &mut p, &mut v) { + Some(v) + } else { + None + } + } + + #[test] + fn unescape_basic() { + assert_eq!(mi_unescape("a\\nb\\t\\\"c\\\\d"), "a\nb\t\"c\\d"); + assert_eq!(mi_unescape("plain"), "plain"); + assert_eq!(mi_unescape("\\r\\n"), "\r\n"); + } + + #[test] + fn value_string() { + let v = parse("\"hello \\\"x\\\"\"").unwrap(); + assert_eq!(v.str_, "hello \"x\""); + assert!(!v.is_list && !v.is_tuple); + } + + #[test] + fn value_tuple() { + let v = parse("{number=\"1\",type=\"breakpoint\",enabled=\"y\",times=\"3\"}").unwrap(); + assert!(v.is_tuple); + assert_eq!(v.get_str("number"), "1"); + assert_eq!(v.get_str("type"), "breakpoint"); + assert_eq!(v.get_str("times"), "3"); + assert_eq!(v.get_str("missing"), ""); + } + + #[test] + fn value_nested_list_of_tuples() { + // -stack-list-frames shape: stack=[frame={level="0",func="main",...}] + let v = parse( + "[frame={level=\"0\",func=\"main\",line=\"42\"},frame={level=\"1\",func=\"helper\"}]", + ) + .unwrap(); + assert!(v.is_list); + assert_eq!(v.list.len(), 2); + assert_eq!(v.list[0].get("frame").unwrap().get_str("func"), "main"); + assert_eq!(v.list[0].get("frame").unwrap().get_str("line"), "42"); + assert_eq!(v.list[1].get("frame").unwrap().get_str("func"), "helper"); + } + + #[test] + fn value_plain_list() { + let v = parse("[{name=\"argc\",value=\"1\"},{name=\"argv\",value=\"0x0\"}]").unwrap(); + assert!(v.is_list); + assert_eq!(v.list.len(), 2); + assert_eq!(v.list[0].get_str("name"), "argc"); + } + + #[test] + fn value_bare_token() { + let v = parse("exited-normally").unwrap(); + assert_eq!(v.str_, "exited-normally"); + } + + #[test] + fn fields_after_stopped() { + let f = mi_parse_fields( + "reason=\"breakpoint-hit\",bkptno=\"2\",frame={func=\"main\",fullname=\"/tmp/console.cpp\",line=\"27\"}", + ); + assert_eq!(f.get_str("reason"), "breakpoint-hit"); + assert_eq!(f.get_str("bkptno"), "2"); + assert_eq!(f.get("frame").unwrap().get_str("func"), "main"); + assert_eq!(f.get("frame").unwrap().get_str("line"), "27"); + } + + #[test] + fn value_unterminated_fails() { + assert!(parse("{number=\"1\"").is_none()); + assert!(parse("[1,2").is_none()); + assert!(parse("\"abc").is_none()); + } +} diff --git a/crates/lightgui-debug/src/session.rs b/crates/lightgui-debug/src/session.rs new file mode 100644 index 0000000..952b29b --- /dev/null +++ b/crates/lightgui-debug/src/session.rs @@ -0,0 +1,1419 @@ +// GdbSession — drives `gdb -q -i=mi2` over pipes with the hand-written +// MI parser in mi.rs. Direct port of src/debugger.cpp / debugger.h. +// +// Rust shape: std::process::Command spawns gdb with piped stdin/stdout/ +// stderr; a dedicated reader thread polls both output fds (libc::poll), +// splits lines, and feeds handle_line() under a Mutex; synchronous +// commands wait on a Condvar for their token's ^done/^error reply. +// Target stdout/stderr arrive as bare lines on gdb's stdout in MI mode +// and are treated as target output, exactly as in the C++ version. + +use std::collections::HashMap; +use std::io::Write; +use std::os::unix::io::AsRawFd; +use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::{Duration, Instant}; + +use crate::mi::{mi_parse_fields, mi_unescape, MiValue}; +use crate::types::{ + bp_kind_from_name, bp_kind_name, bps_escape, bps_split, bps_unescape, ensure_parent_dir, + home_dir, logpoint_to_printf, mi_quote, parse_breakpoint_location, trim_s, BpKind, Breakpoint, + DbgState, DebuggerSettings, StackFrame, StopInfo, Variable, +}; + +const POLLIN: i16 = 0x1; +const POLLHUP: i16 = 0x10; +const POLLERR: i16 = 0x8; + +struct Inner { + settings: DebuggerSettings, + stop_seq: u64, + line_seq: u64, + child: Option, + stdin: Option, + stdout: Option, + stderr: Option, + next_token: i32, + state: DbgState, + executable: String, + args: String, + target_output: String, + gdb_log: String, + last_error: String, + last_stop: StopInfo, + bps: Vec, + watch_exprs: Vec, + watches: Vec, + locals: Vec, + frames: Vec, + pending_results: HashMap, + pending_error: String, + inferior_pid: i32, + reader_done: bool, +} + +impl Inner { + fn new(settings: DebuggerSettings) -> Self { + Inner { + settings, + stop_seq: 0, + line_seq: 0, + child: None, + stdin: None, + stdout: None, + stderr: None, + next_token: 1, + state: DbgState::Idle, + executable: String::new(), + args: String::new(), + target_output: String::new(), + gdb_log: String::new(), + last_error: String::new(), + last_stop: StopInfo::new(), + bps: Vec::new(), + watch_exprs: Vec::new(), + watches: Vec::new(), + locals: Vec::new(), + frames: Vec::new(), + pending_results: HashMap::new(), + pending_error: String::new(), + inferior_pid: -1, + reader_done: false, + } + } + + /// Non-blocking try_wait on the gdb child. Caller must hold the lock. + fn is_alive_locked(&mut self) -> bool { + match self.child.as_mut() { + Some(c) => matches!(c.try_wait(), Ok(None)), + None => false, + } + } +} + +struct Shared { + inner: Mutex, + cond: Condvar, +} + +impl Shared { + fn handle_line(&self, line: &str) { + if line.is_empty() || line == "(gdb)" { + return; + } + let mut g = self.inner.lock().unwrap(); + let c0 = line.as_bytes()[0] as char; + // Result record: [token]^done/^error/^running/^exit[,fields] + if c0 == '^' || c0.is_ascii_digit() { + if let Some(caret) = line.find('^') { + let token: i32 = if caret > 0 { + line[..caret].parse().unwrap_or(0) + } else { + 0 + }; + let rest = &line[caret + 1..]; + let (kind, fields) = match rest.find(',') { + Some(comma) => (&rest[..comma], mi_parse_fields(&rest[comma + 1..])), + None => (rest, MiValue::default()), + }; + if matches!(kind, "done" | "error" | "running" | "exit") { + if token > 0 { + g.pending_results + .insert(token, (kind != "error", fields.clone())); + if kind == "error" { + g.pending_error = fields + .get("msg") + .map(|m| m.str_.clone()) + .unwrap_or_else(|| "gdb error".to_string()); + } + } + if kind == "running" { + g.state = DbgState::Running; + } + if kind == "exit" { + g.state = DbgState::Exited; + } + g.line_seq += 1; + self.cond.notify_all(); + return; + } + } + } + if c0 == '*' { + // Async exec record: *stopped / *running + let comma = line.find(','); + let kind = match comma { + Some(c) => &line[1..c], + None => &line[1..], + }; + let fields = match comma { + Some(c) => mi_parse_fields(&line[c + 1..]), + None => MiValue::default(), + }; + if kind == "stopped" { + g.stop_seq += 1; + let mut si = StopInfo::new(); + si.reason = fields.get_str("reason").to_string(); + si.breakpoint_id = fields.get_str_or("bkptno", "0").parse().unwrap_or(0); + if let Some(fr) = fields.get("frame") { + si.frame.function = fr.get_str("func").to_string(); + si.frame.file = fr.get_str("fullname").to_string(); + if si.frame.file.is_empty() { + si.frame.file = fr.get_str("file").to_string(); + } + si.frame.line = fr.get_str_or("line", "0").parse().unwrap_or(0); + si.frame.address = fr.get_str("addr").to_string(); + si.frame.level = fr.get_str_or("level", "0").parse().unwrap_or(0); + } + if matches!( + si.reason.as_str(), + "exited-normally" | "exited" | "exited-signalled" + ) { + si.exited = true; + si.exit_code = fields.get_str_or("exit-code", "0").parse().unwrap_or(0); + if si.reason == "exited-signalled" { + si.exit_code = -1; + } + g.state = DbgState::Exited; + } else { + g.state = DbgState::Stopped; + } + if si.breakpoint_id > 0 { + for b in g.bps.iter_mut() { + if b.id == si.breakpoint_id { + b.hits += 1; + } + } + } + g.last_stop = si; + } else if kind == "running" { + g.state = DbgState::Running; + } + g.line_seq += 1; + self.cond.notify_all(); + return; + } + if c0 == '=' { + // Notify records (thread/breakpoint/library). Track the + // inferior pid from =thread-group-started so kill_target() + // can SIGKILL it directly: gdb 13's MI has no -exec-kill. + if let Some(rest) = line.strip_prefix("=thread-group-started,") { + let f = mi_parse_fields(rest); + g.inferior_pid = f.get_str_or("pid", "0").parse().unwrap_or(0); + } else if line.starts_with("=thread-group-exited,") { + g.inferior_pid = -1; + } + g.line_seq += 1; + self.cond.notify_all(); + return; + } + if c0 == '~' || c0 == '&' { + // Console / log stream: "~\"...\"" — decode the quoted body. + if let (Some(q1), Some(q2)) = (line.find('"'), line.rfind('"')) { + if q2 > q1 { + let body = mi_unescape(&line[q1 + 1..q2]); + g.gdb_log.push_str(&body); + } + } + g.line_seq += 1; + self.cond.notify_all(); + return; + } + if c0 == '@' { + if let (Some(q1), Some(q2)) = (line.find('"'), line.rfind('"')) { + if q2 > q1 { + let body = mi_unescape(&line[q1 + 1..q2]); + g.target_output.push_str(&body); + } + } + g.line_seq += 1; + self.cond.notify_all(); + return; + } + // Anything else is the inferior's own stdout/stderr, forwarded + // raw by gdb in MI mode (plain "i=0 x=1 ..." lines). + g.target_output.push_str(line); + g.target_output.push('\n'); + g.line_seq += 1; + self.cond.notify_all(); + } + + fn set_error(&self) { + let mut g = self.inner.lock().unwrap(); + g.state = DbgState::Error; + g.reader_done = true; + self.cond.notify_all(); + } +} + +pub struct GdbSession { + shared: Arc, +} + +impl Default for GdbSession { + fn default() -> Self { + Self::new(DebuggerSettings::default()) + } +} + +impl GdbSession { + pub fn new(settings: DebuggerSettings) -> Self { + GdbSession { + shared: Arc::new(Shared { + inner: Mutex::new(Inner::new(settings)), + cond: Condvar::new(), + }), + } + } + + pub fn settings(&self) -> DebuggerSettings { + self.shared.inner.lock().unwrap().settings.clone() + } + + pub fn set_settings(&mut self, s: DebuggerSettings) { + self.shared.inner.lock().unwrap().settings = s; + } + + pub fn is_alive(&self) -> bool { + self.shared.inner.lock().unwrap().is_alive_locked() + } + + pub fn target_running(&self) -> bool { + self.shared.inner.lock().unwrap().state == DbgState::Running + } + + pub fn state(&self) -> DbgState { + self.shared.inner.lock().unwrap().state + } + + pub fn executable(&self) -> String { + self.shared.inner.lock().unwrap().executable.clone() + } + + pub fn exit_code(&self) -> i32 { + self.shared.inner.lock().unwrap().last_stop.exit_code + } + + pub fn last_stop(&self) -> StopInfo { + self.shared.inner.lock().unwrap().last_stop.clone() + } + + pub fn stop_seq(&self) -> u64 { + self.shared.inner.lock().unwrap().stop_seq + } + + pub fn breakpoints(&self) -> Vec { + self.shared.inner.lock().unwrap().bps.clone() + } + + pub fn watches(&self) -> Vec { + self.shared.inner.lock().unwrap().watches.clone() + } + + pub fn locals(&self) -> Vec { + self.shared.inner.lock().unwrap().locals.clone() + } + + pub fn frames(&self) -> Vec { + self.shared.inner.lock().unwrap().frames.clone() + } + + pub fn target_output(&self) -> String { + self.shared.inner.lock().unwrap().target_output.clone() + } + + pub fn gdb_log(&self) -> String { + self.shared.inner.lock().unwrap().gdb_log.clone() + } + + pub fn last_error(&self) -> String { + self.shared.inner.lock().unwrap().last_error.clone() + } + + pub fn clear_output(&mut self) { + let mut g = self.shared.inner.lock().unwrap(); + g.target_output.clear(); + g.gdb_log.clear(); + } + + /// ~/.config/lightgui/debugger_bps.conf + pub fn default_bps_path() -> String { + format!("{}/.config/lightgui/debugger_bps.conf", home_dir()) + } + + // ------------------------------------------------------------ internals + + fn send_raw(&self, text: &str) -> bool { + let mut g = self.shared.inner.lock().unwrap(); + match g.stdin.as_mut() { + Some(stdin) => stdin.write_all(text.as_bytes()).is_ok(), + None => false, + } + } + + /// Wait until a line arrives (or the deadline passes). Used for the + /// initial drain and the kill_target settle waits. + fn pump(&self, timeout_ms: i64) -> bool { + let deadline = Instant::now() + Duration::from_millis(timeout_ms.max(0) as u64); + let mut g = self.shared.inner.lock().unwrap(); + let start_seq = g.line_seq; + loop { + if g.line_seq != start_seq { + return true; + } + let now = Instant::now(); + if now >= deadline { + return false; + } + let remain = deadline - now; + let (ng, _t) = self + .shared + .cond + .wait_timeout(g, std::cmp::min(remain, Duration::from_millis(100))) + .unwrap(); + g = ng; + } + } + + fn wait_result(&self, token: i32, timeout_ms: i64) -> Result { + let timeout = if timeout_ms < 0 { + self.shared.inner.lock().unwrap().settings.cmd_timeout_ms + } else { + timeout_ms + }; + let deadline = Instant::now() + Duration::from_millis(timeout.max(0) as u64); + let mut g = self.shared.inner.lock().unwrap(); + loop { + if let Some((ok, result)) = g.pending_results.remove(&token) { + if !ok { + let err = if g.pending_error.is_empty() { + "gdb reported an error".to_string() + } else { + g.pending_error.clone() + }; + g.last_error = err.clone(); + return Err(err); + } + return Ok(result); + } + if !g.is_alive_locked() { + let err = "gdb process died".to_string(); + g.last_error = err.clone(); + return Err(err); + } + let now = Instant::now(); + if now >= deadline { + let err = "timed out waiting for gdb reply".to_string(); + g.last_error = err.clone(); + return Err(err); + } + let (ng, _t) = self + .shared + .cond + .wait_timeout(g, Duration::from_millis(100)) + .unwrap(); + g = ng; + } + } + + /// Send one MI command, wait for its ^done/^error. Public so the + /// GUI/tests can run extra MI commands. + pub fn command(&mut self, mi_cmd: &str, timeout_ms: i64) -> Result { + { + let g = self.shared.inner.lock().unwrap(); + if g.child.is_none() { + return Err("gdb is not running".to_string()); + } + } + let token = { + let mut g = self.shared.inner.lock().unwrap(); + let t = g.next_token; + g.next_token += 1; + g.pending_results.remove(&t); + t + }; + let line = format!("{}{}\n", token, mi_cmd); + if !self.send_raw(&line) { + return Err("failed to write to gdb".to_string()); + } + self.wait_result(token, timeout_ms) + } + + fn spawn_gdb(&mut self) -> Result<(), String> { + { + let g = self.shared.inner.lock().unwrap(); + if g.child.is_some() { + return Ok(()); + } + } + let gdb_path = self.settings().gdb_path; + // access(X_OK) check, as in the C++ version. + let cpath = std::ffi::CString::new(gdb_path.clone()).unwrap(); + let accessible = unsafe { libc::access(cpath.as_ptr(), libc::X_OK) } == 0; + if !accessible { + let mut g = self.shared.inner.lock().unwrap(); + g.state = DbgState::Error; + return Err(format!("gdb not executable: {}", gdb_path)); + } + let mut child = Command::new(&gdb_path) + .args(["-q", "-i=mi2"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| format!("failed to spawn gdb: {}", e))?; + let stdin = child.stdin.take().unwrap(); + let stdout = child.stdout.take().unwrap(); + let stderr = child.stderr.take().unwrap(); + // Non-blocking reads so the reader thread can poll. + for f in [stdout.as_raw_fd(), stderr.as_raw_fd()] { + unsafe { + let flags = libc::fcntl(f, libc::F_GETFL, 0); + libc::fcntl(f, libc::F_SETFL, flags | libc::O_NONBLOCK); + } + } + let out_fd = stdout.as_raw_fd(); + let err_fd = stderr.as_raw_fd(); + { + let mut g = self.shared.inner.lock().unwrap(); + g.stdin = Some(stdin); + g.stdout = Some(stdout); + g.stderr = Some(stderr); + g.child = Some(child); + g.state = DbgState::Starting; + } + // Reader thread: poll both fds, split lines, feed handle_line. + let shared = Arc::clone(&self.shared); + std::thread::spawn(move || { + reader_loop(shared, out_fd, err_fd); + }); + // Wait for the initial "(gdb)" prompt / thread-group-added notice. + self.pump(2000); + if !self.is_alive() { + let mut g = self.shared.inner.lock().unwrap(); + g.state = DbgState::Error; + return Err("gdb exited immediately".to_string()); + } + if self.settings().pretty_print { + let _ = self.command("-enable-pretty-printing", 2000); + } + Ok(()) + } + + pub fn shutdown(&mut self) { + // Send -gdb-exit, give gdb a moment, then SIGKILL it if it + // lingers (C++ kills at 0.5s, gives up waiting at 1s). + { + let mut g = self.shared.inner.lock().unwrap(); + if let Some(stdin) = g.stdin.as_mut() { + let _ = stdin.write_all(b"-gdb-exit\n"); + let _ = stdin.flush(); + } + } + let start = Instant::now(); + let mut killed = false; + loop { + let exited = { + let mut g = self.shared.inner.lock().unwrap(); + match g.child.as_mut() { + Some(c) => matches!(c.try_wait(), Ok(Some(_))), + None => true, + } + }; + if exited { + break; + } + let elapsed = start.elapsed(); + if !killed && elapsed >= Duration::from_millis(500) { + let mut g = self.shared.inner.lock().unwrap(); + if let Some(c) = g.child.as_mut() { + let _ = c.kill(); + } + killed = true; + } + if elapsed >= Duration::from_secs(1) { + break; + } + std::thread::sleep(Duration::from_millis(100)); + } + let mut g = self.shared.inner.lock().unwrap(); + if let Some(c) = g.child.as_mut() { + let _ = c.try_wait(); + } + g.stdin = None; + g.stdout = None; + g.stderr = None; + g.child = None; + g.state = DbgState::Idle; + g.bps.clear(); + } + + pub fn start_gdb_only(&mut self) -> Result<(), String> { + if self.shared.inner.lock().unwrap().child.is_some() { + return Ok(()); + } + self.spawn_gdb() + } + + pub fn load_executable(&mut self, executable: &str) -> Result<(), String> { + let cpath = std::ffi::CString::new(executable).unwrap(); + if unsafe { libc::access(cpath.as_ptr(), libc::X_OK) } != 0 { + return Err(format!("target not executable: {}", executable)); + } + self.start_gdb_only()?; + let cmd = format!("-file-exec-and-symbols \"{}\"", executable); + self.command(&cmd, -1)?; + self.shared.inner.lock().unwrap().executable = executable.to_string(); + Ok(()) + } + + pub fn start(&mut self, executable: &str, args: &str) -> Result<(), String> { + self.load_executable(executable)?; + { + let mut g = self.shared.inner.lock().unwrap(); + g.args = args.to_string(); + } + if !args.is_empty() { + self.command(&format!("-exec-arguments {}", args), -1)?; + } + // Re-apply saved breakpoints (restart keeps them), with their + // full handler options. Best effort: a stale location must not + // abort the run. + let old: Vec = { + let mut g = self.shared.inner.lock().unwrap(); + let old = g.bps.clone(); + g.bps.clear(); + old + }; + for b in old { + let _ = self.add_breakpoint_opts(&b.location, &b); + } + if self.settings().break_on_main || self.settings().stop_on_entry { + let _ = self.add_breakpoint("main"); + } + self.run() + } + + fn issue_exec(&mut self, mi_cmd: &str) -> Result<(), String> { + // A stop event for this very command can arrive while command() + // is still draining the ^running reply (e.g. a breakpoint on the + // first line, or a one-line step). Only move to Running when no + // new stop arrived. + let gen = self.stop_seq(); + self.command(mi_cmd, -1)?; + let mut g = self.shared.inner.lock().unwrap(); + if g.stop_seq == gen { + g.state = DbgState::Running; + } + Ok(()) + } + + pub fn run(&mut self) -> Result<(), String> { + let (has_child, exe_empty) = { + let g = self.shared.inner.lock().unwrap(); + (g.child.is_some(), g.executable.is_empty()) + }; + if !has_child || exe_empty { + return Err("no target loaded".to_string()); + } + self.issue_exec("-exec-run") + } + + pub fn cont(&mut self) -> Result<(), String> { + self.issue_exec("-exec-continue") + } + + pub fn step_over(&mut self) -> Result<(), String> { + self.issue_exec("-exec-next") + } + + pub fn step_into(&mut self) -> Result<(), String> { + self.issue_exec("-exec-step") + } + + pub fn step_out(&mut self) -> Result<(), String> { + self.issue_exec("-exec-finish") + } + + pub fn kill_target(&mut self) -> Result<(), String> { + let inferior_pid = self.shared.inner.lock().unwrap().inferior_pid; + if inferior_pid > 0 { + // gdb 13 MI has no -exec-kill: SIGKILL the inferior directly. + let rc = unsafe { libc::kill(inferior_pid, libc::SIGKILL) }; + if rc != 0 { + let e = std::io::Error::last_os_error(); + if e.raw_os_error() != Some(libc::ESRCH) { + return Err("failed to kill target process".to_string()); + } + } + self.pump(500); + if self.state() == DbgState::Running { + self.pump(500); + } + return Ok(()); + } + // No inferior pid known: fall back to interrupting, then the + // console "kill" command. + self.command("-exec-interrupt", -1)?; + self.pump(300); + self.command("-interpreter-exec console \"kill\"", -1)?; + self.pump(500); + Ok(()) + } + + pub fn interrupt(&mut self) -> Result<(), String> { + self.command("-exec-interrupt", -1)?; + Ok(()) + } + + pub fn restart(&mut self) -> Result<(), String> { + if self.state() == DbgState::Running { + self.kill_target()?; + self.pump(300); + } + self.shared.inner.lock().unwrap().last_stop = StopInfo::new(); + self.run() + } + + pub fn poll_events(&mut self) { + if self.shared.inner.lock().unwrap().child.is_some() { + self.pump(20); + } + } + + pub fn wait_for_stop(&mut self, timeout_ms: i64) -> bool { + let timeout = if timeout_ms < 0 { + self.shared.inner.lock().unwrap().settings.stop_timeout_ms + } else { + timeout_ms + }; + let deadline = Instant::now() + Duration::from_millis(timeout.max(0) as u64); + let mut g = self.shared.inner.lock().unwrap(); + loop { + if g.state == DbgState::Stopped || g.state == DbgState::Exited { + return true; + } + if g.state == DbgState::Error { + return false; + } + let now = Instant::now(); + if now >= deadline { + break; + } + let (ng, _t) = self + .shared + .cond + .wait_timeout(g, Duration::from_millis(100)) + .unwrap(); + g = ng; + } + g.state == DbgState::Stopped || g.state == DbgState::Exited + } + + // ------------------------------------------------------------ breakpoints + + pub fn stage_breakpoint(&mut self, location: &str) -> bool { + self.stage_breakpoint_opts(location, &Breakpoint::default()) + } + + pub fn stage_breakpoint_opts(&mut self, location: &str, opts: &Breakpoint) -> bool { + let mut file = String::new(); + let mut line = 0; + let mut func = String::new(); + if !parse_breakpoint_location(location, &mut file, &mut line, &mut func) { + return false; + } + let mut b = opts.clone(); + b.location = location.to_string(); + b.file = file; + b.line = line; + b.function = func; + b.id = 0; // not in gdb yet + // A condition without an explicit kind is a conditional breakpoint. + if b.kind == BpKind::Plain && !b.condition.is_empty() { + b.kind = BpKind::Conditional; + } + let mut g = self.shared.inner.lock().unwrap(); + for old in g.bps.iter_mut() { + if old.location != location { + continue; + } + if old.id == 0 { + *old = b; // re-stage: replace the staged entry's options + return true; + } + return true; // live breakpoint at this location: leave it alone + } + g.bps.push(b); + true + } + + fn apply_bp_options(&mut self, id: i32, opts: &Breakpoint) -> Result<(), String> { + if !opts.condition.is_empty() { + self.command( + &format!("-break-condition {} {}", id, mi_quote(&opts.condition)), + -1, + )?; + } + if opts.ignore_count > 0 { + self.command(&format!("-break-after {} {}", id, opts.ignore_count), -1)?; + } + Ok(()) + } + + pub fn add_breakpoint(&mut self, location: &str) -> Result { + self.add_breakpoint_opts(location, &Breakpoint::default()) + } + + #[allow(clippy::field_reassign_with_default)] + pub fn add_breakpoint_opts( + &mut self, + location: &str, + opts: &Breakpoint, + ) -> Result { + let mut file = String::new(); + let mut line = 0; + let mut func = String::new(); + if !parse_breakpoint_location(location, &mut file, &mut line, &mut func) { + return Err(format!( + "not a breakpoint location (need file:line or function): {}", + location + )); + } + let mut want = opts.clone(); + want.location = location.to_string(); + if want.kind == BpKind::Plain && !want.condition.is_empty() { + want.kind = BpKind::Conditional; + } + if want.kind == BpKind::Conditional && trim_s(&want.condition).is_empty() { + return Err("conditional breakpoint needs a condition".to_string()); + } + if want.kind == BpKind::Logpoint && trim_s(&want.log_message).is_empty() { + return Err("logpoint needs a log message".to_string()); + } + if want.ignore_count < 0 { + want.ignore_count = 0; + } + + if want.kind == BpKind::Logpoint { + // Logpoint = gdb dprintf via the console interpreter. The + // ^done reply carries no breakpoint number, so find the new + // dprintf entry with a re-list. + let mut fmt = String::new(); + let mut args = Vec::new(); + if !logpoint_to_printf(&want.log_message, &mut fmt, &mut args) { + return Err(format!( + "bad log message template (unbalanced {{braces}} or empty {{}}) : {}", + want.log_message + )); + } + let mut console_cmd = format!("dprintf {},\"{}\"", location, fmt); + for a in &args { + console_cmd.push_str(", "); + console_cmd.push_str(a); + } + let before: Vec = self + .shared + .inner + .lock() + .unwrap() + .bps + .iter() + .map(|b| b.id) + .collect(); + self.command( + &format!("-interpreter-exec console {}", mi_quote(&console_cmd)), + -1, + )?; + self.refresh_breakpoints()?; + let found: Option = { + let g = self.shared.inner.lock().unwrap(); + let mut best: Option = None; + for cand in g.bps.iter() { + if cand.kind != BpKind::Logpoint { + continue; + } + if before.contains(&cand.id) { + continue; + } + if best.as_ref().map(|b| cand.id > b.id).unwrap_or(true) { + best = Some(cand.clone()); + } + } + best + }; + let mut found = match found { + Some(f) => f, + None => return Err("logpoint was created but gdb did not list it".to_string()), + }; + // Condition / ignore count also apply to dprintf breakpoints. + if let Err(e) = self.apply_bp_options(found.id, &want) { + let _ = self.remove_breakpoint(found.id); + return Err(e); + } + found.condition = want.condition.clone(); + found.ignore_count = want.ignore_count; + found.log_message = want.log_message.clone(); + found.group = want.group.clone(); + if !want.enabled { + let _ = self.enable_breakpoint(found.id, false); + found.enabled = false; + } + { + let mut g = self.shared.inner.lock().unwrap(); + for old in g.bps.iter_mut() { + if old.id == found.id { + *old = found.clone(); + } + } + } + return Ok(found); + } + + let r = self.command(&format!("-break-insert {}", location), -1)?; + let mut b = Breakpoint::default(); + b.location = location.to_string(); + b.enabled = true; + if let Some(bk) = r.get("bkpt") { + b.id = bk.get_str_or("number", "0").parse().unwrap_or(0); + b.file = bk.get_str("fullname").to_string(); + if b.file.is_empty() { + b.file = bk.get_str("file").to_string(); + } + b.line = bk.get_str_or("line", "0").parse().unwrap_or(0); + b.function = bk.get_str("func").to_string(); + // Multi-location breakpoints report number "1" with + // sub-entries; keep the parent id, file/line from the first + // sub-entry if needed. + if b.line == 0 && !bk.list.is_empty() { + let first = &bk.list[0]; + b.line = first.get_str_or("line", "0").parse().unwrap_or(0); + b.file = first.get_str("fullname").to_string(); + b.function = first.get_str("func").to_string(); + } + } + if b.id <= 0 { + return Err("gdb did not return a breakpoint number".to_string()); + } + b.kind = want.kind; + b.condition = want.condition.clone(); + b.ignore_count = want.ignore_count; + b.log_message = want.log_message.clone(); + b.group = want.group.clone(); + { + let mut g = self.shared.inner.lock().unwrap(); + let mut replaced = false; + for old in g.bps.iter_mut() { + if old.id == b.id { + *old = b.clone(); + replaced = true; + } + } + if !replaced { + g.bps.push(b.clone()); + } + } + // gdb validates the condition here (unknown variable -> ^error); + // roll the breakpoint back so a bad condition leaves nothing. + if let Err(e) = self.apply_bp_options(b.id, &want) { + let _ = self.remove_breakpoint(b.id); + return Err(e); + } + if !want.enabled { + let _ = self.enable_breakpoint(b.id, false); + b.enabled = false; + let mut g = self.shared.inner.lock().unwrap(); + for old in g.bps.iter_mut() { + if old.id == b.id { + old.enabled = false; + } + } + } + Ok(b) + } + + pub fn update_breakpoint(&mut self, id: i32, opts: &Breakpoint) -> Result { + let cur: Option = self + .shared + .inner + .lock() + .unwrap() + .bps + .iter() + .find(|b| b.id == id) + .cloned(); + let cur = match cur { + Some(c) => c, + None => { + // Staged entry (id 0): match by location, update in place. + let staged: Option = self + .shared + .inner + .lock() + .unwrap() + .bps + .iter() + .find(|b| b.id == 0 && b.location == opts.location) + .cloned(); + let staged = match staged { + Some(s) => s, + None => { + return Err(format!("no breakpoint with id {}", id)); + } + }; + let mut want = opts.clone(); + want.location = staged.location.clone(); // not editable here + want.id = 0; + want.file = staged.file.clone(); + want.line = staged.line; + want.function = staged.function.clone(); + want.hits = staged.hits; + if want.kind == BpKind::Plain && !want.condition.is_empty() { + want.kind = BpKind::Conditional; + } + let mut g = self.shared.inner.lock().unwrap(); + for old in g.bps.iter_mut() { + if old.id == 0 && old.location == staged.location { + *old = want.clone(); + } + } + return Ok(want); + } + }; + if !self.is_alive() { + // gdb is down: keep the entry, options included, for start(). + let mut want = opts.clone(); + want.location = cur.location.clone(); + want.id = cur.id; + want.file = cur.file.clone(); + want.line = cur.line; + want.function = cur.function.clone(); + want.hits = cur.hits; + if want.kind == BpKind::Plain && !want.condition.is_empty() { + want.kind = BpKind::Conditional; + } + let mut g = self.shared.inner.lock().unwrap(); + for old in g.bps.iter_mut() { + if old.id == cur.id { + *old = want.clone(); + } + } + return Ok(want); + } + // Live: a kind change needs a new breakpoint (a plain breakpoint + // cannot become a dprintf in place), so delete + re-insert at the + // same location. The gdb id may change. + let loc = cur.location.clone(); + let mut want = opts.clone(); + want.location = loc.clone(); + self.remove_breakpoint(id)?; + self.add_breakpoint_opts(&loc, &want) + } + + pub fn remove_staged_breakpoint(&mut self, location: &str) -> bool { + let mut g = self.shared.inner.lock().unwrap(); + let before = g.bps.len(); + g.bps.retain(|b| !(b.location == location && b.id == 0)); + g.bps.len() != before + } + + pub fn remove_breakpoint(&mut self, id: i32) -> Result<(), String> { + self.command(&format!("-break-delete {}", id), -1)?; + self.shared.inner.lock().unwrap().bps.retain(|b| b.id != id); + Ok(()) + } + + pub fn enable_breakpoint(&mut self, id: i32, enable: bool) -> Result<(), String> { + let cmd = if enable { + "-break-enable " + } else { + "-break-disable " + }; + self.command(&format!("{}{}", cmd, id), -1)?; + let mut g = self.shared.inner.lock().unwrap(); + for b in g.bps.iter_mut() { + if b.id == id { + b.enabled = enable; + } + } + Ok(()) + } + + #[allow(clippy::field_reassign_with_default)] + pub fn refresh_breakpoints(&mut self) -> Result<(), String> { + let r = self.command("-break-list", -1)?; + let mut fresh: Vec = Vec::new(); + if let Some(list) = r.get("BreakpointTable") { + if let Some(body) = list.get("body") { + for item in &body.list { + let bk: Option<&MiValue> = if item.tuple.contains_key("bkpt") { + item.tuple.get("bkpt") + } else if item.is_tuple { + Some(item) + } else { + None + }; + let Some(bk) = bk else { continue }; + let mut b = Breakpoint::default(); + b.id = bk.get_str_or("number", "0").parse().unwrap_or(0); + if b.id <= 0 { + continue; + } + b.file = bk.get_str("fullname").to_string(); + if b.file.is_empty() { + b.file = bk.get_str("file").to_string(); + } + b.line = bk.get_str_or("line", "0").parse().unwrap_or(0); + b.function = bk.get_str("func").to_string(); + b.enabled = bk.get_str_or("enabled", "y") == "y"; + b.location = bk.get_str("original-location").to_string(); + if b.location.is_empty() { + b.location = if b.file.is_empty() { + b.function.clone() + } else { + format!("{}:{}", b.file, b.line) + }; + } + b.hits = bk.get_str_or("times", "0").parse().unwrap_or(0); + // Handler fields straight from gdb: dprintf + // breakpoints report type="dprintf"; conditions and + // the remaining ignore count come back as cond= / + // ignore=. (gdb drops `ignore` once the count is + // spent, so a missing field means 0 remaining. The + // log template itself is not reported — it is merged + // back from our own record below.) + let typ = bk.get_str("type"); + b.condition = bk.get_str("cond").to_string(); + b.ignore_count = bk.get_str_or("ignore", "0").parse().unwrap_or(0); + if typ == "dprintf" { + b.kind = BpKind::Logpoint; + } else if !b.condition.is_empty() { + b.kind = BpKind::Conditional; + } + fresh.push(b); + } + } + } + // Merge: gdb is authoritative for kind/condition/ignore/hits, + // but our own records keep the log template and group (gdb + // cannot report them). Staged entries (id 0) are kept. + let mut merged: Vec = Vec::new(); + { + let g = self.shared.inner.lock().unwrap(); + for mut f in fresh { + for old in g.bps.iter() { + if old.id != f.id { + continue; + } + f.log_message = old.log_message.clone(); + f.group = old.group.clone(); + if f.condition.is_empty() { + f.condition = old.condition.clone(); + } + break; + } + merged.push(f); + } + for old in g.bps.iter() { + if old.id == 0 { + merged.push(old.clone()); + } + } + } + self.shared.inner.lock().unwrap().bps = merged; + Ok(()) + } + + pub fn save_breakpoints(&self, path: &str) -> bool { + let p = if path.is_empty() { + Self::default_bps_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 mut body = String::from("# location|enabled|kind|condition|ignore|log_message|group\n"); + let g = self.shared.inner.lock().unwrap(); + for b in g.bps.iter() { + body.push_str(&format!( + "{}|{}|{}|{}|{}|{}|{}\n", + bps_escape(&b.location), + if b.enabled { "1" } else { "0" }, + bp_kind_name(b.kind), + bps_escape(&b.condition), + b.ignore_count, + bps_escape(&b.log_message), + bps_escape(&b.group), + )); + } + f.write_all(body.as_bytes()).is_ok() + } + + #[allow(clippy::field_reassign_with_default)] + pub fn load_breakpoints(&mut self, path: &str) -> bool { + let p = if path.is_empty() { + Self::default_bps_path() + } else { + path.to_string() + }; + let text = match std::fs::read_to_string(&p) { + Ok(t) => t, + Err(_) => return false, + }; + let mut bps = Vec::new(); + for line in text.lines() { + let t = trim_s(line); + if t.is_empty() || t.starts_with('#') { + continue; + } + let parts = bps_split(t); + let mut b = Breakpoint::default(); + b.location = bps_unescape(&parts[0]); + b.enabled = parts.len() < 2 || parts[1] != "0"; + if parts.len() >= 3 && !parts[2].is_empty() { + if let Some(k) = bp_kind_from_name(&parts[2]) { + b.kind = k; + } + } + if parts.len() >= 4 { + b.condition = bps_unescape(&parts[3]); + } + if parts.len() >= 5 { + b.ignore_count = parts[4].parse().unwrap_or(0); + } + if parts.len() >= 6 { + b.log_message = bps_unescape(&parts[5]); + } + if parts.len() >= 7 { + b.group = bps_unescape(&parts[6]); + } + // Split "file:line" into file/line so the code-view gutter + // can show persisted breakpoints. Function-only locations + // ("compute") have neither. + if let Some(colon) = b.location.rfind(':') { + if colon + 1 < b.location.len() { + let tail = &b.location[colon + 1..]; + if !tail.is_empty() && tail.chars().all(|c| c.is_ascii_digit()) { + b.file = b.location[..colon].to_string(); + b.line = tail.parse().unwrap_or(0); + } + } + } + // A condition without an explicit kind is a conditional + // breakpoint (also covers hand-edited files). + if b.kind == BpKind::Plain && !b.condition.is_empty() { + b.kind = BpKind::Conditional; + } + bps.push(b); + } + self.shared.inner.lock().unwrap().bps = bps; + true + } + + // ------------------------------------------------------------ inspection + + #[allow(clippy::field_reassign_with_default)] + pub fn list_locals(&mut self) -> Result, String> { + let r = self.command("-stack-list-variables --simple-values", -1)?; + let mut out: Vec = Vec::new(); + if let Some(vars) = r.get("variables") { + for item in &vars.list { + let mut var = Variable::default(); + var.name = item.get_str("name").to_string(); + var.typ = item.get_str("type").to_string(); + var.value = item.get_str("value").to_string(); + if !var.name.is_empty() { + out.push(var); + } + } + } + self.shared.inner.lock().unwrap().locals = out.clone(); + Ok(out) + } + + #[allow(clippy::field_reassign_with_default)] + pub fn list_frames(&mut self) -> Result, String> { + let r = self.command("-stack-list-frames", -1)?; + let mut out: Vec = Vec::new(); + if let Some(stack) = r.get("stack") { + for item in &stack.list { + let fr: Option<&MiValue> = if item.tuple.contains_key("frame") { + item.tuple.get("frame") + } else if item.is_tuple { + Some(item) + } else { + None + }; + let Some(fr) = fr else { continue }; + let mut f = StackFrame::default(); + f.level = fr.get_str_or("level", "0").parse().unwrap_or(0); + f.function = fr.get_str("func").to_string(); + f.file = fr.get_str("fullname").to_string(); + if f.file.is_empty() { + f.file = fr.get_str("file").to_string(); + } + f.line = fr.get_str_or("line", "0").parse().unwrap_or(0); + f.address = fr.get_str("addr").to_string(); + out.push(f); + } + } + self.shared.inner.lock().unwrap().frames = out.clone(); + Ok(out) + } + + pub fn evaluate(&mut self, expr: &str) -> Result { + let r = self.command(&format!("-data-evaluate-expression \"{}\"", expr), -1)?; + Ok(r.get_str("value").to_string()) + } + + pub fn add_watch(&mut self, expr: &str) -> Result<(), String> { + let t = trim_s(expr).to_string(); + if t.is_empty() { + return Err("empty watch expression".to_string()); + } + { + let mut g = self.shared.inner.lock().unwrap(); + if g.watch_exprs.contains(&t) { + return Ok(()); + } + g.watch_exprs.push(t); + } + self.refresh_watches(); + Ok(()) + } + + pub fn remove_watch(&mut self, expr: &str) -> bool { + let mut g = self.shared.inner.lock().unwrap(); + g.watch_exprs.retain(|w| w != expr); + g.watches.retain(|v| v.name != expr); + true + } + + #[allow(clippy::field_reassign_with_default)] + pub fn refresh_watches(&mut self) -> bool { + let exprs: Vec = self.shared.inner.lock().unwrap().watch_exprs.clone(); + let mut watches = Vec::new(); + for expr in exprs { + let mut v = Variable::default(); + v.name = expr.clone(); + match self.evaluate(&expr) { + Ok(value) => { + v.value = value; + // Type via a second query is expensive; leave blank + // unless the expression is a plain variable name + // (locals carry it). + let locals = self.shared.inner.lock().unwrap().locals.clone(); + for l in locals { + if l.name == expr { + v.typ = l.typ.clone(); + } + } + } + Err(e) => { + v.value = format!("", e); + } + } + watches.push(v); + } + self.shared.inner.lock().unwrap().watches = watches; + true + } + + /// Refresh locals+frames+watches after a stop (best effort). + pub fn refresh_on_stop(&mut self) { + if self.state() != DbgState::Stopped { + return; + } + if self.settings().print_all_locals { + let _ = self.list_locals(); + } + let _ = self.list_frames(); + self.refresh_watches(); + } +} + +impl Drop for GdbSession { + fn drop(&mut self) { + self.shutdown(); + } +} + +/// Reader thread: poll gdb's stdout/stderr fds, split into lines, feed +/// Shared::handle_line. Exits on stdout EOF (gdb died) or when both fds +/// are closed. +fn reader_loop(shared: Arc, out_fd: i32, err_fd: i32) { + let mut out_buf: Vec = Vec::new(); + let mut err_buf: Vec = Vec::new(); + let mut out_open = true; + let mut err_open = err_fd >= 0; + let mut tmp = [0u8; 8192]; + while out_open || err_open { + let mut fds = [ + libc::pollfd { + fd: if out_open { out_fd } else { -1 }, + events: POLLIN, + revents: 0, + }, + libc::pollfd { + fd: if err_open { err_fd } else { -1 }, + events: POLLIN, + revents: 0, + }, + ]; + let r = unsafe { libc::poll(fds.as_mut_ptr(), 2, 50) }; + if r < 0 { + let e = std::io::Error::last_os_error(); + if e.raw_os_error() == Some(libc::EINTR) { + continue; + } + break; + } + if r == 0 { + continue; + } + for (idx, is_out) in [(0, true), (1, false)] { + if fds[idx].revents & (POLLIN | POLLHUP | POLLERR) == 0 { + continue; + } + let fd = if is_out { out_fd } else { err_fd }; + let n = unsafe { libc::read(fd, tmp.as_mut_ptr() as *mut libc::c_void, tmp.len()) }; + if n > 0 { + let buf = if is_out { &mut out_buf } else { &mut err_buf }; + buf.extend_from_slice(&tmp[..n as usize]); + let mut pos = 0; + while let Some(nl) = buf[pos..].iter().position(|&c| c == b'\n') { + let end = pos + nl; + let raw = String::from_utf8_lossy(&buf[pos..end]).to_string(); + let line = raw.trim_end_matches(['\r', ' ', '\t']).to_string(); + shared.handle_line(&line); + pos = end + 1; + } + buf.drain(..pos); + } else if n == 0 { + // EOF. + if is_out { + out_open = false; + shared.set_error(); + } else { + err_open = false; + } + } else { + let e = std::io::Error::last_os_error(); + if e.raw_os_error() != Some(libc::EAGAIN) + && e.raw_os_error() != Some(libc::EWOULDBLOCK) + { + if is_out { + out_open = false; + shared.set_error(); + } else { + err_open = false; + } + } + } + } + } +} diff --git a/crates/lightgui-debug/src/types.rs b/crates/lightgui-debug/src/types.rs new file mode 100644 index 0000000..14de285 --- /dev/null +++ b/crates/lightgui-debug/src/types.rs @@ -0,0 +1,578 @@ +// Shared types for the GDB/MI backend — port of the data types and +// pure helpers in src/debugger.h / src/debugger.cpp: +// DebuggerSettings (+ key=value persistence), BpKind, Breakpoint, +// Variable, StackFrame, StopInfo, DbgState, parse_breakpoint_location, +// logpoint_to_printf, breakpoint-file escape helpers. + +use std::io::Write; + +// ---------------------------------------------------------------- helpers + +pub fn home_dir() -> String { + std::env::var("HOME").unwrap_or_default() +} + +pub fn trim_s(s: &str) -> &str { + s.trim_matches(|c| c == ' ' || c == '\t' || c == '\r' || c == '\n') +} + +pub 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); + } + } +} + +// ---------------------------------------------------------------- settings + +#[derive(Debug, Clone, PartialEq)] +pub struct DebuggerSettings { + pub gdb_path: String, + /// Insert a breakpoint at main before run. + pub break_on_main: bool, + /// Stop at main on entry (temp bp at main). + pub stop_on_entry: bool, + /// -enable-pretty-printing on session start. + pub pretty_print: bool, + /// Refresh locals on every stop. + pub print_all_locals: bool, + /// Args passed to the target by default. + pub default_args: String, + /// How long to wait for a stop event. + pub stop_timeout_ms: i64, + /// How long to wait for a ^done/^error. + pub cmd_timeout_ms: i64, +} + +impl Default for DebuggerSettings { + fn default() -> Self { + DebuggerSettings { + gdb_path: "/usr/bin/gdb".to_string(), + break_on_main: false, + stop_on_entry: false, + pretty_print: true, + print_all_locals: true, + default_args: String::new(), + stop_timeout_ms: 10_000, + cmd_timeout_ms: 5_000, + } + } +} + +impl DebuggerSettings { + /// ~/.config/lightgui/debugger.conf; LIGHTGUI_DEBUGGER_CONF overrides. + pub fn default_path() -> String { + match std::env::var("LIGHTGUI_DEBUGGER_CONF") { + Ok(e) if !e.is_empty() => e, + _ => format!("{}/.config/lightgui/debugger.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!( + "# LightGUI debugger settings\n\ + gdb_path={}\n\ + break_on_main={}\n\ + stop_on_entry={}\n\ + pretty_print={}\n\ + print_all_locals={}\n\ + default_args={}\n\ + stop_timeout_ms={}\n\ + cmd_timeout_ms={}\n", + self.gdb_path, + if self.break_on_main { "1" } else { "0" }, + if self.stop_on_entry { "1" } else { "0" }, + if self.pretty_print { "1" } else { "0" }, + if self.print_all_locals { "1" } else { "0" }, + self.default_args, + self.stop_timeout_ms, + self.cmd_timeout_ms, + ); + 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 boolean = |v: &str| v == "1" || v == "true" || v == "yes" || v == "on"; + for line in text.lines() { + let t = trim_s(line); + if t.is_empty() || t.starts_with('#') { + continue; + } + let Some(eq) = t.find('=') else { continue }; + let k = trim_s(&t[..eq]); + let v = trim_s(&t[eq + 1..]); + match k { + "gdb_path" if !v.is_empty() => self.gdb_path = v.to_string(), + "break_on_main" => self.break_on_main = boolean(v), + "stop_on_entry" => self.stop_on_entry = boolean(v), + "pretty_print" => self.pretty_print = boolean(v), + "print_all_locals" => self.print_all_locals = boolean(v), + "default_args" => self.default_args = v.to_string(), + "stop_timeout_ms" => { + if let Ok(n) = v.parse::() { + self.stop_timeout_ms = n; + } + } + "cmd_timeout_ms" => { + if let Ok(n) = v.parse::() { + self.cmd_timeout_ms = n; + } + } + _ => {} + } + } + if self.stop_timeout_ms <= 0 { + self.stop_timeout_ms = 10_000; + } + if self.cmd_timeout_ms <= 0 { + self.cmd_timeout_ms = 5_000; + } + true + } +} + +// ---------------------------------------------------------------- breakpoints + +/// What a breakpoint does when its location is reached. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BpKind { + Plain, + Conditional, + Logpoint, +} + +/// Display name for a breakpoint kind ("plain"/"conditional"/"logpoint"). +pub fn bp_kind_name(kind: BpKind) -> &'static str { + match kind { + BpKind::Plain => "plain", + BpKind::Conditional => "conditional", + BpKind::Logpoint => "logpoint", + } +} + +/// Parse a kind name; accepts "plain", "conditional"/"cond", +/// "logpoint"/"log"/"dprintf". Returns false for anything else. +pub fn bp_kind_from_name(name: &str) -> Option { + match name { + "plain" => Some(BpKind::Plain), + "conditional" | "cond" => Some(BpKind::Conditional), + "logpoint" | "log" | "dprintf" => Some(BpKind::Logpoint), + _ => None, + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Breakpoint { + /// gdb breakpoint number (0 = staged, not yet in gdb). + pub id: i32, + /// As requested: "file:line" or "func". + pub location: String, + /// Resolved file (may be empty). + pub file: String, + /// Resolved line (0 if by function). + pub line: i32, + /// Resolved function (may be empty). + pub function: String, + pub enabled: bool, + /// gdb `times`: reaches (conditional: stops). + pub hits: i32, + pub kind: BpKind, + /// Conditional: gdb expression, e.g. "i == 5". + pub condition: String, + /// Skip the first N hits (-break-after). + pub ignore_count: i32, + /// Logpoint template, e.g. "i={i} sum={sum}". + pub log_message: String, + /// Optional group label (organisation only). + pub group: String, +} + +impl Default for Breakpoint { + fn default() -> Self { + Breakpoint { + id: 0, + location: String::new(), + file: String::new(), + line: 0, + function: String::new(), + enabled: true, + hits: 0, + kind: BpKind::Plain, + condition: String::new(), + ignore_count: 0, + log_message: String::new(), + group: String::new(), + } + } +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Variable { + pub name: String, + pub typ: String, + pub value: String, +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct StackFrame { + pub level: i32, + pub function: String, + pub file: String, + pub line: i32, + pub address: String, +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct StopInfo { + /// breakpoint-hit, end-stepping-range, exited-normally, ... + pub reason: String, + pub breakpoint_id: i32, + pub frame: StackFrame, + /// >= 0 once the target has exited. + pub exit_code: i32, + pub exited: bool, +} + +impl StopInfo { + pub fn new() -> Self { + StopInfo { + exit_code: -1, + ..Default::default() + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DbgState { + Idle, + Starting, + Running, + Stopped, + Exited, + Error, +} + +// ---------------------------------------------------------------- locations + +/// Parse a "file:line" or "function" breakpoint location. Returns false +/// if the text is not a plausible location (empty, no colon/function +/// chars). On success fills exactly one of (file, line) / function. +pub fn parse_breakpoint_location( + text: &str, + file: &mut String, + line: &mut i32, + function: &mut String, +) -> bool { + file.clear(); + *line = 0; + function.clear(); + let t: String = text + .chars() + .filter(|c| *c != ' ' && *c != '\t' && *c != '\r' && *c != '\n') + .collect(); + if t.is_empty() { + return false; + } + if let Some(colon) = t.rfind(':') { + if colon + 1 < t.len() { + let num = &t[colon + 1..]; + if !num.is_empty() && num.chars().all(|c| c.is_ascii_digit()) { + *file = t[..colon].to_string(); + *line = num.parse().unwrap_or(0); + return !file.is_empty() && *line > 0; + } + } + } + // Function name: identifier-ish (letters, digits, _, :, <>, ~). + let first = t.chars().next().unwrap(); + let mut ok = first.is_ascii_alphabetic() || first == '_' || first == '~'; + for c in t.chars() { + if !(c.is_ascii_alphanumeric() || c == '_' || c == ':' || c == '<' || c == '>' || c == '~') + { + ok = false; + } + } + if ok { + *function = t; + return true; + } + false +} + +/// Quote one argument as an MI C-string: "s" with \ and " escaped. +pub fn mi_quote(s: &str) -> String { + let mut out = String::from("\""); + for c in s.chars() { + if c == '\\' || c == '"' { + out.push('\\'); + } + out.push(c); + } + out.push('"'); + out +} + +/// Convert a logpoint message template ("reached loop, i={i} name={s:name}") +/// to a gdb printf format string plus the argument expressions, in order. +/// {expr} prints as %d; {s:expr} %s, {f:expr} %f, {x:expr} %#x, {p:expr} %p. +/// Literal % in the template is escaped to %%. Returns false on an +/// unbalanced brace or an empty placeholder. +pub fn logpoint_to_printf(tmpl: &str, fmt: &mut String, args: &mut Vec) -> bool { + fmt.clear(); + args.clear(); + let chars: Vec = tmpl.chars().collect(); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + if c == '%' { + fmt.push_str("%%"); + i += 1; + continue; + } + if c != '{' { + fmt.push(c); + i += 1; + continue; + } + let rest: String = chars[i + 1..].iter().collect(); + let Some(close) = rest.find('}') else { + return false; // unbalanced { + }; + let close = i + 1 + close; + let inner: String = chars[i + 1..close].iter().collect(); + if trim_s(&inner).is_empty() { + return false; // empty {} + } + // Optional one-letter format prefix before the first colon: + // {s:name} -> %s. Anything else (including a:b ternaries and + // a::b qualified names) is the whole expression, printed %d. + let mut spec = "%d"; + let mut expr = inner.clone(); + let inner_chars: Vec = inner.chars().collect(); + if inner_chars.len() >= 2 && inner_chars[1] == ':' { + let m = match inner_chars[0] { + 'd' => Some("%d"), + 's' => Some("%s"), + 'f' => Some("%f"), + 'x' => Some("%#x"), + 'p' => Some("%p"), + _ => None, + }; + if let Some(m) = m { + spec = m; + expr = inner_chars[2..].iter().collect(); + } + } + let expr = trim_s(&expr).to_string(); + if expr.is_empty() { + return false; + } + fmt.push_str(spec); + args.push(expr); + i = close + 1; + } + // dprintf output without a trailing newline would run into gdb's own + // console output; terminate the message (fmt holds a literal \n as + // backslash+n, which gdb's console parser turns into a newline). + if fmt.len() < 2 || !fmt.ends_with("\\n") { + fmt.push_str("\\n"); + } + true +} + +// ---------------------------------------------------------------- bps file + +/// Escape one persistence field: \ -> \\, | -> \|, newline -> \n, CR -> \r. +pub fn bps_escape(s: &str) -> String { + let mut out = String::new(); + for c in s.chars() { + match c { + '\\' => out.push_str("\\\\"), + '|' => out.push_str("\\|"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + _ => out.push(c), + } + } + out +} + +pub fn bps_unescape(s: &str) -> String { + let mut out = String::new(); + let mut it = s.chars().peekable(); + while let Some(c) = it.next() { + if c == '\\' { + if let Some(n) = it.next() { + match n { + 'n' => out.push('\n'), + 'r' => out.push('\r'), + _ => out.push(n), // \\ and \| (and anything else) + } + } else { + out.push(c); + } + } else { + out.push(c); + } + } + out +} + +/// Split a persistence line on unescaped '|' (escapes stay in the parts +/// for bps_unescape to handle). +pub fn bps_split(line: &str) -> Vec { + let mut parts = Vec::new(); + let mut cur = String::new(); + let mut it = line.chars().peekable(); + while let Some(c) = it.next() { + if c == '\\' { + if let Some(n) = it.next() { + cur.push(c); + cur.push(n); + continue; + } + } + if c == '|' { + parts.push(std::mem::take(&mut cur)); + continue; + } + cur.push(c); + } + parts.push(cur); + parts +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn settings_save_load_roundtrip() { + let dir = std::env::temp_dir().join("lightgui_dbg_settings_test"); + let _ = std::fs::create_dir_all(&dir); + let p = dir.join("debugger.conf"); + let s = DebuggerSettings { + gdb_path: "/usr/bin/gdb".to_string(), + break_on_main: true, + stop_on_entry: false, + pretty_print: false, + default_args: "a b".to_string(), + ..Default::default() + }; + assert!(s.save(p.to_str().unwrap())); + let mut s2 = DebuggerSettings::default(); + assert!(s2.load(p.to_str().unwrap())); + assert_eq!(s2.gdb_path, "/usr/bin/gdb"); + assert!(s2.break_on_main); + assert!(!s2.pretty_print); + assert_eq!(s2.default_args, "a b"); + } + + #[test] + fn settings_load_missing_keeps_defaults() { + let mut s = DebuggerSettings::default(); + assert!(!s.load("/tmp/lightgui_dbg_no_such_conf_12345")); + assert_eq!(s.gdb_path, "/usr/bin/gdb"); + } + + #[test] + fn parse_location_file_line() { + let (mut f, mut l, mut fn_) = (String::new(), 0, String::new()); + assert!(parse_breakpoint_location( + "/tmp/console.cpp:27", + &mut f, + &mut l, + &mut fn_ + )); + assert_eq!(f, "/tmp/console.cpp"); + assert_eq!(l, 27); + assert!(fn_.is_empty()); + } + + #[test] + fn parse_location_function() { + let (mut f, mut l, mut fn_) = (String::new(), 0, String::new()); + assert!(parse_breakpoint_location( + "compute", &mut f, &mut l, &mut fn_ + )); + assert_eq!(fn_, "compute"); + assert!(parse_breakpoint_location( + "ns::foo", + &mut f, + &mut l, + &mut fn_ + )); + assert!(!parse_breakpoint_location("", &mut f, &mut l, &mut fn_)); + assert!(!parse_breakpoint_location( + "not a location!!!", + &mut f, + &mut l, + &mut fn_ + )); + assert!(!parse_breakpoint_location( + "file.cpp:0", + &mut f, + &mut l, + &mut fn_ + )); + } + + #[test] + fn logpoint_templates() { + let (mut fmt, mut args) = (String::new(), Vec::new()); + assert!(logpoint_to_printf( + "i={i} s={s:name} x={x:v}", + &mut fmt, + &mut args + )); + assert_eq!(fmt, "i=%d s=%s x=%#x\\n"); + assert_eq!(args, vec!["i", "name", "v"]); + assert!(logpoint_to_printf("100% done", &mut fmt, &mut args)); + assert_eq!(fmt, "100%% done\\n"); + assert!(args.is_empty()); + assert!(!logpoint_to_printf("oops {i", &mut fmt, &mut args)); + assert!(!logpoint_to_printf("oops {}", &mut fmt, &mut args)); + assert!(logpoint_to_printf("a::b", &mut fmt, &mut args)); + assert_eq!(fmt, "a::b\\n"); // qualified name: no prefix split + } + + #[test] + fn bp_kind_names() { + assert_eq!(bp_kind_name(BpKind::Plain), "plain"); + assert_eq!(bp_kind_name(BpKind::Conditional), "conditional"); + assert_eq!(bp_kind_name(BpKind::Logpoint), "logpoint"); + assert_eq!(bp_kind_from_name("cond"), Some(BpKind::Conditional)); + assert_eq!(bp_kind_from_name("dprintf"), Some(BpKind::Logpoint)); + assert_eq!(bp_kind_from_name("bogus"), None); + } + + #[test] + fn bps_escape_roundtrip() { + let s = "a|b\\c\nd"; + assert_eq!(bps_unescape(&bps_escape(s)), s); + let parts = bps_split("a\\|b|1|cond"); + assert_eq!(parts.len(), 3); + assert_eq!(bps_unescape(&parts[0]), "a|b"); + } +} diff --git a/crates/lightgui-debug/tests/common/mod.rs b/crates/lightgui-debug/tests/common/mod.rs new file mode 100644 index 0000000..d95ebf1 --- /dev/null +++ b/crates/lightgui-debug/tests/common/mod.rs @@ -0,0 +1,133 @@ +// Shared helpers for the debugger integration tests (port of the +// harness utilities in tests/debugger/dbg_harness.cpp). The C++ test +// targets (console.cpp, spin.cpp, gtkapp.cpp) are vendored under +// tests/targets/ and compiled here with `g++ -g -O0` from their +// absolute paths, so the DWARF source paths match the file:line +// breakpoints the tests use. + +use lightgui_debug::Variable; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::OnceLock; + +#[allow(dead_code)] +pub struct Targets { + pub dir: PathBuf, + pub console: PathBuf, + pub console_src: PathBuf, + pub spin: PathBuf, + pub gtkapp: PathBuf, + pub gtkapp_src: PathBuf, +} + +pub fn targets() -> &'static Targets { + static T: OnceLock = OnceLock::new(); + T.get_or_init(build_targets) +} + +fn run_or_panic(mut cmd: Command, what: &str) { + let out = cmd + .output() + .unwrap_or_else(|e| panic!("failed to run {}: {}", what, e)); + assert!( + out.status.success(), + "{} failed: {}\n{}", + what, + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); +} + +fn build_targets() -> Targets { + let dir = std::env::temp_dir().join("lightgui_dbg_targets"); + let _ = std::fs::create_dir_all(&dir); + let src_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/targets"); + let console_src = src_dir.join("console.cpp"); + let spin_src = src_dir.join("spin.cpp"); + let gtk_src = src_dir.join("gtkapp.cpp"); + let console = dir.join("console"); + let spin = dir.join("spin"); + let gtkapp = dir.join("gtkapp"); + + run_or_panic( + { + let mut c = Command::new("g++"); + c.args(["-g", "-O0", "-o"]); + c.arg(&console); + c.arg(&console_src); + c + }, + "build console target", + ); + run_or_panic( + { + let mut c = Command::new("g++"); + c.args(["-g", "-O0", "-o"]); + c.arg(&spin); + c.arg(&spin_src); + c + }, + "build spin target", + ); + let pkg = Command::new("pkg-config") + .args(["--cflags", "--libs", "gtk+-3.0"]) + .output() + .expect("pkg-config gtk+-3.0"); + assert!(pkg.status.success(), "pkg-config gtk+-3.0 failed"); + let flags: Vec = String::from_utf8_lossy(&pkg.stdout) + .split_whitespace() + .map(|s| s.to_string()) + .collect(); + run_or_panic( + { + let mut c = Command::new("g++"); + c.args(["-g", "-O0", "-o"]); + c.arg(>kapp); + c.arg(>k_src); + c.args(&flags); + c + }, + "build gtkapp target", + ); + + Targets { + dir, + console, + console_src, + spin, + gtkapp, + gtkapp_src: gtk_src, + } +} + +/// 1-based line number of the first line containing `mark`, or -1. +pub fn mark_line(file: &PathBuf, mark: &str) -> i32 { + let text = std::fs::read_to_string(file).expect("read target source"); + for (i, line) in text.lines().enumerate() { + if line.contains(mark) { + return (i + 1) as i32; + } + } + -1 +} + +pub fn loc(file: &Path, line: i32) -> String { + format!("{}:{}", file.to_string_lossy(), line) +} + +pub fn has(vars: &[Variable], name: &str, value: &str) -> bool { + vars.iter().any(|v| v.name == name && v.value == value) +} + +pub fn var_value(vars: &[Variable], name: &str) -> String { + vars.iter() + .find(|v| v.name == name) + .map(|v| v.value.clone()) + .unwrap_or_else(|| "".to_string()) +} + +/// Unique scratch path for one test (parallel-safe). +#[allow(dead_code)] +pub fn tmp_path(name: &str) -> PathBuf { + std::env::temp_dir().join(format!("dbgtest_{}_{}", name, std::process::id())) +} diff --git a/crates/lightgui-debug/tests/console.rs b/crates/lightgui-debug/tests/console.rs new file mode 100644 index 0000000..452a725 --- /dev/null +++ b/crates/lightgui-debug/tests/console.rs @@ -0,0 +1,832 @@ +// Console debugger suite — Rust port of console_tests() in +// tests/debugger/dbg_harness.cpp (37 checks: marks_found + tests 1-36). +// Each check is its own #[test], named after the C++ report() name. +// Run with: cargo test -p lightgui-debug --test console + +#[path = "common/mod.rs"] +mod common; + +use common::{has, loc, mark_line, targets, tmp_path, var_value}; +use lightgui_debug::{ + logpoint_to_printf, BpKind, Breakpoint, DbgState, DebuggerSettings, GdbSession, +}; +use std::path::PathBuf; + +fn console() -> PathBuf { + targets().console.clone() +} +fn console_src() -> PathBuf { + targets().console_src.clone() +} +fn spin() -> PathBuf { + targets().spin.clone() +} +fn marks() -> (i32, i32, i32, i32, i32, i32) { + let src = console_src(); + ( + mark_line(&src, "MARK:LOOP"), + mark_line(&src, "MARK:LOOP_NEXT"), + mark_line(&src, "MARK:CALL"), + mark_line(&src, "MARK:AFTER_CALL"), + mark_line(&src, "MARK:COMPUTE"), + mark_line(&src, "MARK:HELPER"), + ) +} + +#[test] +fn marks_found() { + let (a, b, c, d, e, f) = marks(); + assert!(a > 0 && b > 0 && c > 0 && d > 0 && e > 0 && f > 0); +} + +// 1. gdb exists at the default path +#[test] +fn gdb_default_path_executable() { + let s = DebuggerSettings::default(); + assert!(std::fs::metadata(&s.gdb_path).is_ok(), "{}", s.gdb_path); +} + +// 2. settings save/load round-trip +#[test] +fn settings_save_load() { + let s = DebuggerSettings { + gdb_path: "/usr/bin/gdb".to_string(), + break_on_main: true, + stop_on_entry: false, + pretty_print: false, + default_args: "a b".to_string(), + ..Default::default() + }; + let p = tmp_path("conf"); + assert!(s.save(p.to_str().unwrap())); + let mut s2 = DebuggerSettings::default(); + assert!(s2.load(p.to_str().unwrap())); + assert_eq!(s2.gdb_path, "/usr/bin/gdb"); + assert!(s2.break_on_main); + assert!(!s2.pretty_print); + assert_eq!(s2.default_args, "a b"); +} + +// 3. bad gdb path fails cleanly +#[test] +fn bad_gdb_path_fails() { + let s = DebuggerSettings { + gdb_path: "/nonexistent/gdb".to_string(), + ..Default::default() + }; + let mut sess = GdbSession::new(s); + let err = sess.start(console().to_str().unwrap(), "").unwrap_err(); + assert!(!err.is_empty(), "expected an error message"); +} + +// 4. run to completion, no breakpoints +#[test] +fn run_to_completion() { + let mut sess = GdbSession::default(); + sess.start(console().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(10_000)); + assert_eq!(sess.state(), DbgState::Exited); + assert_eq!(sess.exit_code(), 0); + assert!( + sess.target_output().contains("DONE sum=9"), + "out: {}", + sess.target_output() + ); +} + +// 5. breakpoint by file:line is hit +#[test] +fn bp_file_line_hit() { + let (l_loop, _, _, _, _, _) = marks(); + let mut sess = GdbSession::default(); + assert!(sess.stage_breakpoint(&loc(&console_src(), l_loop))); + sess.start(console().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.state(), DbgState::Stopped); + assert_eq!(sess.last_stop().reason, "breakpoint-hit"); + assert_eq!(sess.last_stop().frame.line, l_loop); + assert_eq!(sess.last_stop().frame.function, "main"); +} + +// 6. locals at the breakpoint (first iteration: i=0, sum=0) +#[test] +fn locals_at_bp() { + let (l_loop, _, _, _, _, _) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint(&loc(&console_src(), l_loop)); + sess.start(console().to_str().unwrap(), "").expect("start"); + sess.wait_for_stop(-1); + sess.refresh_on_stop(); + assert!( + has(&sess.locals(), "i", "0"), + "i={}", + var_value(&sess.locals(), "i") + ); + assert!( + has(&sess.locals(), "sum", "0"), + "sum={}", + var_value(&sess.locals(), "sum") + ); +} + +// 7. watch expression + evaluate +#[test] +fn watch_and_evaluate() { + let (l_loop, _, _, _, _, _) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint(&loc(&console_src(), l_loop)); + sess.start(console().to_str().unwrap(), "").expect("start"); + sess.wait_for_stop(-1); + sess.refresh_on_stop(); + sess.add_watch("sum + 1").expect("add_watch"); + let v = sess.evaluate("i + 5").expect("evaluate i+5"); + assert_eq!(v, "5", "i+5={}", v); + assert!(has(&sess.watches(), "sum + 1", "1")); +} + +// 8. step over: LOOP -> LOOP_NEXT, x == 1 after the call +#[test] +fn step_over() { + let (l_loop, l_next, _, _, _, _) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint(&loc(&console_src(), l_loop)); + sess.start(console().to_str().unwrap(), "").expect("start"); + sess.wait_for_stop(-1); + sess.step_over().expect("step_over"); + assert!(sess.wait_for_stop(-1)); + assert_eq!( + sess.last_stop().frame.line, + l_next, + "line={}", + sess.last_stop().frame.line + ); + let v = sess.evaluate("x").expect("evaluate x"); + assert_eq!(v, "1", "x={}", v); +} + +// 9. step into: CALL line -> inside compute() +#[test] +fn step_into() { + let (_, _, l_call, _, _, _) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint(&loc(&console_src(), l_call)); + sess.start(console().to_str().unwrap(), "").expect("start"); + sess.wait_for_stop(-1); + sess.step_into().expect("step_into"); + assert!(sess.wait_for_stop(-1)); + assert!( + sess.last_stop().frame.function.contains("compute"), + "func={}", + sess.last_stop().frame.function + ); +} + +// 10. step out: from compute() back to main, line after the call +#[test] +fn step_out() { + let (_, _, l_call, l_after, _, _) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint(&loc(&console_src(), l_call)); + sess.start(console().to_str().unwrap(), "").expect("start"); + sess.wait_for_stop(-1); + sess.step_into().expect("step_into"); + sess.wait_for_stop(-1); + sess.step_out().expect("step_out"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.last_stop().frame.function, "main"); + assert!( + sess.last_stop().frame.line == l_after || sess.last_stop().frame.line == l_call, + "line={}", + sess.last_stop().frame.line + ); + if sess.last_stop().frame.line == l_call { + // finish stops on the call-site assignment line; one step over + // executes the store, landing on the line after. + sess.step_over().expect("step_over"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.last_stop().frame.line, l_after); + } + let v = sess.evaluate("total").expect("evaluate total"); + assert_eq!(v, "61", "total={}", v); +} + +// 11. continue to the next breakpoint (loop bp, then helper bp) +#[test] +fn continue_to_next_bp() { + let (l_loop, _, _, _, _, l_helper) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint(&loc(&console_src(), l_loop)); + sess.stage_breakpoint(&loc(&console_src(), l_helper)); + sess.start(console().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.last_stop().frame.line, l_loop); + sess.cont().expect("cont"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.last_stop().reason, "breakpoint-hit"); + assert!( + sess.last_stop().frame.function.contains("helper"), + "func={}", + sess.last_stop().frame.function + ); +} + +// 12. multiple breakpoints listed with ids +#[test] +fn multiple_bps_listed() { + let (l_loop, _, _, _, _, l_helper) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint(&loc(&console_src(), l_loop)); + sess.stage_breakpoint(&loc(&console_src(), l_helper)); + sess.start(console().to_str().unwrap(), "").expect("start"); + sess.wait_for_stop(-1); + sess.refresh_breakpoints().expect("refresh"); + assert!( + sess.breakpoints().len() >= 2, + "count={}", + sess.breakpoints().len() + ); +} + +// 13. disable a breakpoint: it is not hit +#[test] +fn disable_bp_skips() { + let (l_loop, _, _, _, _, l_helper) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint(&loc(&console_src(), l_loop)); + sess.stage_breakpoint(&loc(&console_src(), l_helper)); + sess.start(console().to_str().unwrap(), "").expect("start"); + sess.wait_for_stop(-1); // at LOOP + let loop_id = sess + .breakpoints() + .iter() + .find(|b| b.line == l_loop) + .map(|b| b.id) + .unwrap_or(0); + assert!(loop_id > 0); + sess.enable_breakpoint(loop_id, false).expect("disable"); + sess.cont().expect("cont"); + assert!(sess.wait_for_stop(-1)); + // Next stop must be the helper bp, not the loop bp. + assert!( + sess.last_stop().frame.function.contains("helper"), + "func={}", + sess.last_stop().frame.function + ); +} + +// 14. re-enable: the breakpoint is hit again +#[test] +fn enable_bp_hits_again() { + let (l_loop, _, _, _, _, _) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint(&loc(&console_src(), l_loop)); + sess.start(console().to_str().unwrap(), "").expect("start"); + sess.wait_for_stop(-1); + let loop_id = sess + .breakpoints() + .iter() + .find(|b| b.line == l_loop) + .map(|b| b.id) + .unwrap_or(0); + sess.enable_breakpoint(loop_id, false).expect("disable"); + sess.cont().expect("cont"); + assert!(sess.wait_for_stop(-1)); + // Disabled: runs to completion (no more bps). + assert_eq!(sess.state(), DbgState::Exited); + // Restart with the bp re-enabled: must stop at LOOP again. + sess.enable_breakpoint(loop_id, true).expect("enable"); + sess.restart().expect("restart"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.state(), DbgState::Stopped); + assert_eq!(sess.last_stop().frame.line, l_loop); +} + +// 15. delete a breakpoint: gone from the list, never hit +#[test] +fn delete_bp() { + let (l_loop, _, _, _, _, _) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint(&loc(&console_src(), l_loop)); + sess.start(console().to_str().unwrap(), "").expect("start"); + sess.wait_for_stop(-1); + let loop_id = sess + .breakpoints() + .iter() + .find(|b| b.line == l_loop) + .map(|b| b.id) + .unwrap_or(0); + sess.remove_breakpoint(loop_id).expect("remove"); + sess.refresh_breakpoints().expect("refresh"); + assert!( + sess.breakpoints().is_empty(), + "remaining={}", + sess.breakpoints().len() + ); + sess.cont().expect("cont"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.state(), DbgState::Exited); +} + +// 16. breakpoint by function name +#[test] +fn bp_by_function() { + let (_, _, _, _, l_compute, _) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint("compute"); + sess.start(console().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(-1)); + assert!( + sess.last_stop().frame.function.contains("compute"), + "func={}", + sess.last_stop().frame.function + ); + assert_eq!(sess.last_stop().frame.line, l_compute); +} + +// 17. invalid breakpoints fail gracefully +#[test] +fn invalid_bp_rejected() { + let mut sess = GdbSession::default(); + assert!(!sess.stage_breakpoint("")); + assert!(!sess.stage_breakpoint("not a location!!!")); + // gdb-side rejection of a nonexistent file + sess.start_gdb_only().expect("start_gdb_only"); + sess.load_executable(console().to_str().unwrap()) + .expect("load_executable"); + let r = sess.add_breakpoint("no_such_file.cpp:9999"); + assert!(r.is_err(), "expected gdb rejection"); + assert!(!r.unwrap_err().is_empty()); +} + +// 18. stack frames at a stop +#[test] +fn frames_at_stop() { + let (l_loop, _, _, _, _, _) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint(&loc(&console_src(), l_loop)); + sess.start(console().to_str().unwrap(), "").expect("start"); + sess.wait_for_stop(-1); + sess.refresh_on_stop(); + assert!(!sess.frames().is_empty(), "n={}", sess.frames().len()); + assert_eq!(sess.frames()[0].function, "main"); + assert_eq!(sess.frames()[0].line, l_loop); +} + +// 19. stack depth inside nested calls (main > compute > helper) +#[test] +fn stack_depth_nested() { + let (_, _, _, _, _, l_helper) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint(&loc(&console_src(), l_helper)); + sess.start(console().to_str().unwrap(), "").expect("start"); + let mut ok = sess.wait_for_stop(-1); + // Hits 1-3 are helper() called from the loop (depth 2); hit 4 is + // helper() called from compute() (depth 3: main > compute > helper). + for _ in 0..3 { + if !ok { + break; + } + ok = sess.cont().is_ok() && sess.wait_for_stop(-1); + } + sess.refresh_on_stop(); + assert!(ok); + assert!(sess.frames().len() >= 3, "n={}", sess.frames().len()); + assert!(sess.frames()[0].function.contains("helper")); + assert!(sess.frames()[1].function.contains("compute")); + assert_eq!(sess.frames()[2].function, "main"); +} + +// 20. kill a running (spinning) target +#[test] +fn kill_running_target() { + let mut sess = GdbSession::default(); + sess.start(spin().to_str().unwrap(), "").expect("start"); + std::thread::sleep(std::time::Duration::from_millis(500)); + assert!(sess.target_running()); + sess.kill_target().expect("kill_target"); + assert!(sess.wait_for_stop(5000)); + assert!(!sess.target_running()); + assert!(sess.is_alive()); +} + +// 21. restart after exit hits the breakpoint again +#[test] +fn restart_after_exit() { + let (l_loop, _, _, _, _, _) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint(&loc(&console_src(), l_loop)); + sess.start(console().to_str().unwrap(), "").expect("start"); + let mut ok = sess.wait_for_stop(-1); + // The loop bp fires once per iteration (i=0,1,2): three continues + // run the program to completion. + for _ in 0..3 { + if !ok { + break; + } + ok = sess.cont().is_ok() && sess.wait_for_stop(-1); + } + assert!(ok); + assert_eq!(sess.state(), DbgState::Exited); + sess.restart().expect("restart"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.state(), DbgState::Stopped); + assert_eq!(sess.last_stop().frame.line, l_loop); +} + +// 22. restart after kill: target runs again, can be killed again +#[test] +fn restart_after_kill() { + let mut sess = GdbSession::default(); + sess.start(spin().to_str().unwrap(), "").expect("start"); + std::thread::sleep(std::time::Duration::from_millis(300)); + sess.kill_target().expect("kill 1"); + assert!(sess.wait_for_stop(5000)); + sess.restart().expect("restart"); + std::thread::sleep(std::time::Duration::from_millis(300)); + assert!(sess.target_running()); + sess.kill_target().expect("kill 2"); + assert!(sess.wait_for_stop(5000)); + assert!(!sess.target_running()); +} + +// 23. break_on_main setting stops at main +#[test] +fn setting_break_on_main() { + let s = DebuggerSettings { + break_on_main: true, + ..Default::default() + }; + let mut sess = GdbSession::new(s); + sess.start(console().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.state(), DbgState::Stopped); + assert_eq!(sess.last_stop().reason, "breakpoint-hit"); + assert_eq!(sess.last_stop().frame.function, "main"); +} + +// 24. stop_on_entry setting stops at main +#[test] +fn setting_stop_on_entry() { + let s = DebuggerSettings { + stop_on_entry: true, + ..Default::default() + }; + let mut sess = GdbSession::new(s); + sess.start(console().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.state(), DbgState::Stopped); + assert_eq!(sess.last_stop().frame.function, "main"); +} + +// 25. pretty-print: vector value comes back expanded +#[test] +fn setting_pretty_print() { + let (l_loop, _, _, _, _, _) = marks(); + let s = DebuggerSettings { + pretty_print: true, + ..Default::default() + }; + let mut sess = GdbSession::new(s); + sess.stage_breakpoint(&loc(&console_src(), l_loop)); + sess.start(console().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(-1)); + sess.refresh_on_stop(); + let v = sess.evaluate("vals").expect("evaluate vals"); + assert!(v.contains('1') && v.contains('3'), "vals={}", v); + // And the setting is what got saved to disk. + let s2 = DebuggerSettings { + pretty_print: true, + ..Default::default() + }; + let p = tmp_path("conf2"); + assert!(s2.save(p.to_str().unwrap())); + let mut s3 = DebuggerSettings::default(); + assert!(s3.load(p.to_str().unwrap()) && s3.pretty_print); +} + +// 26. settings file is actually read and applied (break_on_main via file) +#[test] +fn settings_file_applied() { + let s = DebuggerSettings { + gdb_path: "/usr/bin/gdb".to_string(), + break_on_main: true, + ..Default::default() + }; + let p = tmp_path("conf3"); + s.save(p.to_str().unwrap()); + let mut loaded = DebuggerSettings::default(); + assert!(loaded.load(p.to_str().unwrap()) && loaded.break_on_main); + let mut sess = GdbSession::new(loaded); + sess.start(console().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.last_stop().frame.function, "main"); +} + +// 27. target stdout/stderr captured +#[test] +fn target_output_captured() { + let mut sess = GdbSession::default(); + sess.start(console().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(10_000)); + let out = sess.target_output(); + assert!(out.contains("i=0 x=1 sum=1"), "out: {}", out); + assert!(out.contains("i=2 x=5 sum=9"), "out: {}", out); + assert!(out.contains("TOTAL total=61 sum=9"), "out: {}", out); +} + +// 28. evaluate arithmetic at a stop +#[test] +fn evaluate_arithmetic() { + let (l_loop, _, _, _, _, _) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint(&loc(&console_src(), l_loop)); + sess.start(console().to_str().unwrap(), "").expect("start"); + sess.wait_for_stop(-1); + let v = sess.evaluate("sum + 100").expect("sum+100"); + assert_eq!(v, "100", "sum+100={}", v); + let v = sess.evaluate("vals[2]").expect("vals[2]"); + assert_eq!(v, "3"); + let v = sess.evaluate("vals.size()").expect("vals.size()"); + assert_eq!(v, "3"); +} + +// 29. target args are passed through +#[test] +fn target_args_passed() { + let mut sess = GdbSession::default(); + sess.start(console().to_str().unwrap(), "hello") + .expect("start"); + assert!(sess.wait_for_stop(10_000)); + assert!( + sess.target_output().contains("ARG=hello"), + "out: {}", + sess.target_output() + ); +} + +// 30. breakpoints persist to disk and load back +#[test] +fn bps_persist_to_disk() { + let (l_loop, _, _, _, _, _) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint(&loc(&console_src(), l_loop)); + sess.stage_breakpoint("compute"); + let p = tmp_path("bps"); + assert!(sess.save_breakpoints(p.to_str().unwrap())); + let mut sess2 = GdbSession::default(); + assert!(sess2.load_breakpoints(p.to_str().unwrap())); + assert_eq!(sess2.breakpoints().len(), 2); + assert_eq!(sess2.breakpoints()[0].location, loc(&console_src(), l_loop)); + assert_eq!(sess2.breakpoints()[1].location, "compute"); +} + +// 31. conditional breakpoint: fires only when i == 2, never before +#[test] +fn bp_conditional_only_when_true() { + let (l_loop, _, _, _, _, _) = marks(); + let mut sess = GdbSession::default(); + let opts = Breakpoint { + kind: BpKind::Conditional, + condition: "i == 2".to_string(), + ..Default::default() + }; + assert!(sess.stage_breakpoint_opts(&loc(&console_src(), l_loop), &opts)); + sess.start(console().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.state(), DbgState::Stopped); + assert_eq!(sess.last_stop().reason, "breakpoint-hit"); + assert_eq!(sess.last_stop().frame.line, l_loop); + let v = sess.evaluate("i").expect("evaluate i"); + assert_eq!(v, "2", "i={}", v); + // It must NOT have stopped at i=0/1: both iterations printed before + // the first (and only) stop. + let out = sess.target_output(); + assert!(out.contains("i=0 x=1 sum=1"), "out: {}", out); + assert!(out.contains("i=1 x=3 sum=4"), "out: {}", out); + // Hit count from gdb: a conditional breakpoint counts stops only + // (reaches with a false condition are not hits) -> 1. + sess.refresh_breakpoints().expect("refresh"); + let hits = sess + .breakpoints() + .iter() + .find(|b| b.line == l_loop) + .map(|b| b.hits) + .unwrap_or(-1); + assert_eq!(hits, 1, "hits={}", hits); + sess.cont().expect("cont"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.state(), DbgState::Exited); +} + +// 32. ignore count: first 2 hits skipped, stops on the 3rd (i == 2) +#[test] +fn bp_ignore_count_skips() { + let (l_loop, _, _, _, _, _) = marks(); + let mut sess = GdbSession::default(); + let opts = Breakpoint { + ignore_count: 2, + ..Default::default() + }; + assert!(sess.stage_breakpoint_opts(&loc(&console_src(), l_loop), &opts)); + sess.start(console().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.state(), DbgState::Stopped); + assert_eq!(sess.last_stop().frame.line, l_loop); + let v = sess.evaluate("i").expect("evaluate i"); + assert_eq!(v, "2", "i={}", v); + let out = sess.target_output(); + assert!(out.contains("i=0 x=1 sum=1"), "out: {}", out); + assert!(out.contains("i=1 x=3 sum=4"), "out: {}", out); + // gdb counts every reach, ignored or not, in `times` -> 3. + sess.refresh_breakpoints().expect("refresh"); + let hits = sess + .breakpoints() + .iter() + .find(|b| b.line == l_loop) + .map(|b| b.hits) + .unwrap_or(-1); + assert_eq!(hits, 3, "hits={}", hits); + sess.cont().expect("cont"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.state(), DbgState::Exited); +} + +// 33. logpoint: prints its message at every hit, never stops +#[test] +fn bp_logpoint_prints_no_stop() { + let (l_loop, _, _, _, _, _) = marks(); + let mut sess = GdbSession::default(); + let opts = Breakpoint { + kind: BpKind::Logpoint, + log_message: "LOG i={i}".to_string(), + ..Default::default() + }; + assert!(sess.stage_breakpoint_opts(&loc(&console_src(), l_loop), &opts)); + sess.start(console().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(10_000)); + // No stop at all: straight to a clean exit. + assert_eq!(sess.state(), DbgState::Exited); + assert_eq!(sess.exit_code(), 0); + // dprintf output arrives on gdb's console stream (-> gdb_log()). + let log = sess.gdb_log(); + assert!(log.contains("LOG i=0"), "log: {}", log); + assert!(log.contains("LOG i=1"), "log: {}", log); + assert!(log.contains("LOG i=2"), "log: {}", log); + assert!(sess.target_output().contains("DONE sum=9")); +} + +// 34. logpoint template with several placeholders and formats +#[test] +fn bp_logpoint_template() { + // Template conversion is pure string work: check it directly. + let (mut fmt, mut args) = (String::new(), Vec::new()); + assert!(logpoint_to_printf( + "i={i} s={s:name} x={x:v}", + &mut fmt, + &mut args + )); + assert_eq!(fmt, "i=%d s=%s x=%#x\\n"); + assert_eq!(args.len(), 3); + assert_eq!(args[0], "i"); + assert_eq!(args[1], "name"); + assert_eq!(args[2], "v"); + assert!(logpoint_to_printf("100% done", &mut fmt, &mut args)); + assert_eq!(fmt, "100%% done\\n"); + assert!(args.is_empty()); + assert!(!logpoint_to_printf("oops {i", &mut fmt, &mut args)); + assert!(!logpoint_to_printf("oops {}", &mut fmt, &mut args)); + // And end to end: two placeholders print at the loop. + let (l_loop, _, _, _, _, _) = marks(); + let mut sess = GdbSession::default(); + let opts = Breakpoint { + kind: BpKind::Logpoint, + log_message: "LP i={i} sum={sum}".to_string(), + ..Default::default() + }; + assert!(sess.stage_breakpoint_opts(&loc(&console_src(), l_loop), &opts)); + sess.start(console().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(10_000)); + assert_eq!(sess.state(), DbgState::Exited); + let log = sess.gdb_log(); + assert!(log.contains("LP i=0 sum=0"), "log: {}", log); + assert!(log.contains("LP i=2 sum=4"), "log: {}", log); +} + +// 35. edit a live breakpoint: plain -> conditional, takes effect +#[test] +fn bp_update_plain_to_conditional() { + let (l_loop, _, _, _, _, _) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint(&loc(&console_src(), l_loop)); + sess.start(console().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.state(), DbgState::Stopped); + let v = sess.evaluate("i").expect("evaluate i"); + assert_eq!(v, "0", "i={}", v); // plain: stops at 0 + let loop_id = sess + .breakpoints() + .iter() + .find(|b| b.line == l_loop) + .map(|b| b.id) + .unwrap_or(0); + assert!(loop_id > 0); + let upd = Breakpoint { + kind: BpKind::Conditional, + condition: "i == 2".to_string(), + location: loc(&console_src(), l_loop), + ..Default::default() + }; + let out = sess.update_breakpoint(loop_id, &upd).expect("update"); + assert_eq!(out.kind, BpKind::Conditional); + assert_eq!(out.condition, "i == 2"); + sess.cont().expect("cont"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.state(), DbgState::Stopped); + assert_eq!(sess.last_stop().frame.line, l_loop); + let v = sess.evaluate("i").expect("evaluate i"); + assert_eq!(v, "2", "i={}", v); + sess.cont().expect("cont"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.state(), DbgState::Exited); +} + +// 36. handler fields persist to disk and load back; old two-field files +// still load as plain breakpoints. +#[test] +fn bp_handlers_persist_roundtrip() { + let (l_loop, _, _, _, _, l_helper) = marks(); + let mut sess = GdbSession::default(); + let mut c = Breakpoint { + kind: BpKind::Conditional, + ..Default::default() + }; + c.condition = "i == 2 || sum > 3".to_string(); // exercises | escaping + c.group = "loop".to_string(); + let l = Breakpoint { + kind: BpKind::Logpoint, + log_message: "LOG i={i} | sum={sum}".to_string(), + group: "trace".to_string(), + ..Default::default() + }; + let p = Breakpoint { + ignore_count: 3, + ..Default::default() + }; + assert!(sess.stage_breakpoint_opts(&loc(&console_src(), l_loop), &c)); + assert!(sess.stage_breakpoint_opts(&loc(&console_src(), l_helper), &l)); + assert!(sess.stage_breakpoint_opts("compute", &p)); + let path = tmp_path("bps2"); + assert!(sess.save_breakpoints(path.to_str().unwrap())); + let mut sess2 = GdbSession::default(); + assert!(sess2.load_breakpoints(path.to_str().unwrap())); + assert_eq!(sess2.breakpoints().len(), 3); + let b0 = sess2.breakpoints()[0].clone(); + let b1 = sess2.breakpoints()[1].clone(); + let b2 = sess2.breakpoints()[2].clone(); + assert_eq!(b0.kind, BpKind::Conditional); + assert_eq!(b0.condition, "i == 2 || sum > 3"); + assert_eq!(b0.group, "loop"); + assert_eq!(b0.file, console_src().to_string_lossy()); + assert_eq!(b0.line, l_loop); + assert_eq!(b1.kind, BpKind::Logpoint); + assert_eq!(b1.log_message, "LOG i={i} | sum={sum}"); + assert_eq!(b1.group, "trace"); + assert_eq!(b1.file, console_src().to_string_lossy()); + assert_eq!(b1.line, l_helper); + assert_eq!(b2.kind, BpKind::Plain); + assert_eq!(b2.ignore_count, 3); + assert_eq!(b2.location, "compute"); + assert!(b2.file.is_empty()); + assert_eq!(b2.line, 0); + // Old format: location|enabled, nothing else. + let old_path = tmp_path("bps_old"); + std::fs::write( + &old_path, + format!("{}|1\ncompute|0\n", loc(&console_src(), l_loop)), + ) + .unwrap(); + let mut sess3 = GdbSession::default(); + assert!(sess3.load_breakpoints(old_path.to_str().unwrap())); + assert_eq!(sess3.breakpoints().len(), 2); + assert_eq!(sess3.breakpoints()[0].kind, BpKind::Plain); + assert!(sess3.breakpoints()[0].enabled); + assert_eq!(sess3.breakpoints()[0].file, console_src().to_string_lossy()); + assert_eq!(sess3.breakpoints()[0].line, l_loop); + assert_eq!(sess3.breakpoints()[1].kind, BpKind::Plain); + assert!(!sess3.breakpoints()[1].enabled); + assert!(sess3.breakpoints()[1].file.is_empty()); + // A bad condition is rejected and leaves no breakpoint behind. + let mut s4 = GdbSession::default(); + s4.start_gdb_only().expect("start_gdb_only"); + s4.load_executable(console().to_str().unwrap()) + .expect("load_executable"); + let bad = Breakpoint { + kind: BpKind::Conditional, + condition: "nosuchvar == 2".to_string(), + ..Default::default() + }; + let r = s4.add_breakpoint_opts(&loc(&console_src(), l_loop), &bad); + assert!(r.is_err(), "expected rejection"); + assert!(!r.unwrap_err().is_empty()); + assert!(s4.breakpoints().is_empty()); +} diff --git a/crates/lightgui-debug/tests/gtk.rs b/crates/lightgui-debug/tests/gtk.rs new file mode 100644 index 0000000..9c9e910 --- /dev/null +++ b/crates/lightgui-debug/tests/gtk.rs @@ -0,0 +1,152 @@ +// GTK debugger suite — Rust port of gtk_tests() in +// tests/debugger/dbg_harness.cpp (7 checks: marks_found + tests 31-36). +// The target is a real GTK app, so these tests need a display: +// xvfb-run -a cargo test -p lightgui-debug --test gtk +// Each check is self-contained (its own GdbSession), unlike the C++ +// version where tests 32-33 chained inside test 31's session. + +#[path = "common/mod.rs"] +mod common; + +use common::{has, loc, mark_line, targets, var_value}; +use lightgui_debug::{BpKind, Breakpoint, DbgState, GdbSession}; +use std::path::PathBuf; + +fn app() -> PathBuf { + targets().gtkapp.clone() +} +fn app_src() -> PathBuf { + targets().gtkapp_src.clone() +} +fn marks() -> (i32, i32) { + let src = app_src(); + (mark_line(&src, "MARK:CB"), mark_line(&src, "MARK:CB_NEXT")) +} + +#[test] +fn gtk_marks_found() { + let (a, b) = marks(); + assert!(a > 0 && b > 0); +} + +// 31. breakpoint in the button callback is hit on auto-click +#[test] +fn gtk_bp_in_callback() { + let (l_cb, _) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint(&loc(&app_src(), l_cb)); + sess.start(app().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(15_000)); + assert_eq!(sess.state(), DbgState::Stopped); + assert_eq!(sess.last_stop().reason, "breakpoint-hit"); + assert!( + sess.last_stop().frame.function.contains("on_clicked"), + "func={}", + sess.last_stop().frame.function + ); + assert_eq!(sess.last_stop().frame.line, l_cb); +} + +// 32. step through the callback: counter becomes 1. (At the CB line +// `before` is still unassigned, so step to the next line first, where +// before == 0.) +#[test] +fn gtk_step_in_callback() { + let (l_cb, l_cb_next) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint(&loc(&app_src(), l_cb)); + sess.start(app().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(15_000)); + sess.step_over().expect("step_over"); + assert!(sess.wait_for_stop(-1)); + assert_eq!(sess.last_stop().frame.line, l_cb_next); + sess.refresh_on_stop(); + assert!( + has(&sess.locals(), "before", "0"), + "before={}", + var_value(&sess.locals(), "before") + ); + sess.step_over().expect("step_over"); + assert!(sess.wait_for_stop(-1)); + let v = sess.evaluate("counter").expect("evaluate counter"); + assert_eq!(v, "1", "counter={}", v); +} + +// 33. continue: app finishes on its own timer, exit 0 +#[test] +fn gtk_continue_to_exit() { + let (l_cb, _) = marks(); + let mut sess = GdbSession::default(); + sess.stage_breakpoint(&loc(&app_src(), l_cb)); + sess.start(app().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(15_000)); + sess.cont().expect("cont"); + assert!(sess.wait_for_stop(15_000)); + assert_eq!(sess.state(), DbgState::Exited); + assert_eq!(sess.exit_code(), 0); + assert!( + sess.target_output().contains("CLICKS=1"), + "out: {}", + sess.target_output() + ); +} + +// 34. GTK app runs to completion with no breakpoints +#[test] +fn gtk_run_to_completion() { + let mut sess = GdbSession::default(); + sess.start(app().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(15_000)); + assert_eq!(sess.state(), DbgState::Exited); + assert_eq!(sess.exit_code(), 0); + assert!( + sess.target_output().contains("CLICKS=1"), + "out: {}", + sess.target_output() + ); +} + +// 35. logpoint in the callback: prints, never stops, app exits 0 +#[test] +fn gtk_logpoint_no_stop() { + let (l_cb, _) = marks(); + let mut sess = GdbSession::default(); + let opts = Breakpoint { + kind: BpKind::Logpoint, + log_message: "CLICK counter={counter}".to_string(), + ..Default::default() + }; + assert!(sess.stage_breakpoint_opts(&loc(&app_src(), l_cb), &opts)); + sess.start(app().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(15_000)); + assert_eq!(sess.state(), DbgState::Exited); + assert_eq!(sess.exit_code(), 0); + assert!(sess.target_output().contains("CLICKS=1")); + // At the callback entry counter is still 0 (the click has not been + // counted yet); the dprintf output is on gdb's console stream. + let log = sess.gdb_log(); + assert!(log.contains("CLICK counter=0"), "log: {}", log); +} + +// 36. conditional breakpoint in the callback: fires when counter == 0 +#[test] +fn gtk_conditional_in_callback() { + let (l_cb, _) = marks(); + let mut sess = GdbSession::default(); + let opts = Breakpoint { + kind: BpKind::Conditional, + condition: "counter == 0".to_string(), + ..Default::default() + }; + assert!(sess.stage_breakpoint_opts(&loc(&app_src(), l_cb), &opts)); + sess.start(app().to_str().unwrap(), "").expect("start"); + assert!(sess.wait_for_stop(15_000)); + assert_eq!(sess.state(), DbgState::Stopped); + assert_eq!(sess.last_stop().reason, "breakpoint-hit"); + assert_eq!(sess.last_stop().frame.line, l_cb); + sess.cont().expect("cont"); + assert!(sess.wait_for_stop(15_000)); + assert_eq!(sess.state(), DbgState::Exited); + assert_eq!(sess.exit_code(), 0); + assert!(sess.target_output().contains("CLICKS=1")); +} diff --git a/crates/lightgui-debug/tests/targets/console.cpp b/crates/lightgui-debug/tests/targets/console.cpp new file mode 100644 index 0000000..928c450 --- /dev/null +++ b/crates/lightgui-debug/tests/targets/console.cpp @@ -0,0 +1,32 @@ +// Debugger test target: console C++ program. +// Markers (// MARK:xxx) are found by the harness to get line numbers, so +// edits here do not break the tests. Compile with: g++ -g -O0 -o console console.cpp +#include +#include + +int helper(int v) { + int r = v * 2 + 1; // MARK:HELPER + return r; +} + +int compute(int a, int b) { + int s = a + b; // MARK:COMPUTE + int d = helper(s); // MARK:COMPUTE_CALL + return d; +} + +int main(int argc, char** argv) { + if (argc > 1) std::printf("ARG=%s\n", argv[1]); // MARK:ARG + int sum = 0; + std::vector vals = {1, 2, 3}; + for (int i = 0; i < 3; i++) { + int x = helper(i); // MARK:LOOP + sum += x; // MARK:LOOP_NEXT + std::printf("i=%d x=%d sum=%d\n", i, x, sum); + std::fflush(stdout); // line-buffered for the debugger's live view + } + int total = compute(10, 20); // MARK:CALL + std::printf("TOTAL total=%d sum=%d\n", total, sum); // MARK:AFTER_CALL + std::printf("DONE sum=%d\n", sum); + return 0; +} diff --git a/crates/lightgui-debug/tests/targets/gtkapp.cpp b/crates/lightgui-debug/tests/targets/gtkapp.cpp new file mode 100644 index 0000000..aebac09 --- /dev/null +++ b/crates/lightgui-debug/tests/targets/gtkapp.cpp @@ -0,0 +1,50 @@ +// Debugger test target: small GTK app with a button callback. +// The button auto-clicks itself 800 ms after startup (so the test can +// drive it headlessly under Xvfb), and the app quits 4 s after startup. +// Compile with: g++ -g -O0 -o gtkapp gtkapp.cpp $(pkg-config --cflags --libs gtk+-3.0) +#include +#include + +static int counter = 0; +static GtkWidget* label = nullptr; +static GtkWidget* button = nullptr; + +static void on_clicked(GtkButton*, gpointer) { + int before = counter; // MARK:CB + counter = before + 1; // MARK:CB_NEXT + char buf[64]; + std::snprintf(buf, sizeof buf, "Clicks: %d", counter); + gtk_label_set_text(GTK_LABEL(label), buf); +} + +static gboolean auto_click(gpointer) { + gtk_button_clicked(GTK_BUTTON(button)); + return G_SOURCE_REMOVE; +} + +static gboolean quit_app(gpointer) { + gtk_main_quit(); + return G_SOURCE_REMOVE; +} + +int main(int argc, char** argv) { + gtk_init(&argc, &argv); + GtkWidget* win = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_title(GTK_WINDOW(win), "Debugger GTK Test"); + gtk_window_set_default_size(GTK_WINDOW(win), 300, 120); + g_signal_connect(win, "destroy", G_CALLBACK(gtk_main_quit), nullptr); + GtkWidget* box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6); + gtk_container_add(GTK_CONTAINER(win), box); + label = gtk_label_new("Clicks: 0"); + gtk_box_pack_start(GTK_BOX(box), label, TRUE, TRUE, 0); + button = gtk_button_new_with_label("Click me"); + g_signal_connect(button, "clicked", G_CALLBACK(on_clicked), nullptr); + gtk_box_pack_start(GTK_BOX(box), button, TRUE, TRUE, 0); + gtk_widget_show_all(win); + g_timeout_add(800, auto_click, nullptr); + g_timeout_add(4000, quit_app, nullptr); + gtk_main(); + std::printf("CLICKS=%d\n", counter); + std::fflush(stdout); + return 0; +} diff --git a/crates/lightgui-debug/tests/targets/spin.cpp b/crates/lightgui-debug/tests/targets/spin.cpp new file mode 100644 index 0000000..27767e1 --- /dev/null +++ b/crates/lightgui-debug/tests/targets/spin.cpp @@ -0,0 +1,12 @@ +// Debugger test target: never exits on its own (kill/restart tests). +// Compile with: g++ -g -O0 -o spin spin.cpp +#include +int main() { + volatile long n = 0; + std::printf("SPINNING\n"); + std::fflush(stdout); + while (1) { + n++; + } + return 0; +} diff --git a/crates/lightgui-support/Cargo.toml b/crates/lightgui-support/Cargo.toml new file mode 100644 index 0000000..2bc22de --- /dev/null +++ b/crates/lightgui-support/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "lightgui-support" +version = "0.1.0" +edition = "2021" +description = "LightGUI support modules — themes, preferences, code view, CMake builds (port of src/theme.cpp, src/preferences.cpp, src/codeview.cpp, src/cmake_build.cpp)" +license = "MIT" + +[dependencies] +gtk = { workspace = true } +gdk = { workspace = true } +glib = { workspace = true } +pango = { workspace = true } +cairo-rs = { workspace = true } +lightgui-debug = { path = "../lightgui-debug" } diff --git a/crates/lightgui-support/src/cmake.rs b/crates/lightgui-support/src/cmake.rs new file mode 100644 index 0000000..5ba15d8 --- /dev/null +++ b/crates/lightgui-support/src/cmake.rs @@ -0,0 +1,352 @@ +// LightGUI CMake handling — port of src/cmake_build.cpp / +// src/cmake_build.h (no GTK dependency). +// Emits CMakeLists.txt text for generated projects, builds any +// directory containing one (configure + build), and persists the CMake +// settings (generator / build type / build directory) in +// ~/.config/lightgui/cmake.conf, following the debugger.conf pattern +// (key=value; LIGHTGUI_CMAKE_CONF overrides the path, used by tests). + +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::Command; + +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 CMakeSettings { + /// cmake binary (PATH lookup or path). + pub cmake_path: String, + /// "" = CMake default generator. + pub generator: String, + pub build_type: String, + /// Relative to the project directory. + pub build_dir: String, +} + +impl Default for CMakeSettings { + fn default() -> Self { + CMakeSettings { + cmake_path: "cmake".to_string(), + generator: String::new(), + build_type: "Release".to_string(), + build_dir: "build".to_string(), + } + } +} + +impl CMakeSettings { + /// ~/.config/lightgui/cmake.conf + pub fn default_path() -> String { + match std::env::var("LIGHTGUI_CMAKE_CONF") { + Ok(e) if !e.is_empty() => e, + _ => format!("{}/.config/lightgui/cmake.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!( + "# LightGUI CMake settings\ncmake_path={}\ngenerator={}\nbuild_type={}\nbuild_dir={}\n", + self.cmake_path, self.generator, self.build_type, self.build_dir, + ); + 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, + }; + for line in text.lines() { + let line = trim_s(line); + if line.is_empty() || line.starts_with('#') { + continue; + } + let Some(eq) = line.find('=') else { continue }; + let key = trim_s(&line[..eq]); + let val = trim_s(&line[eq + 1..]); + match key { + "cmake_path" => self.cmake_path = val.to_string(), + "generator" => self.generator = val.to_string(), + "build_type" => self.build_type = val.to_string(), + "build_dir" => self.build_dir = val.to_string(), + // Unknown keys are ignored, so newer settings files stay + // readable. + _ => {} + } + } + if self.cmake_path.is_empty() { + self.cmake_path = "cmake".to_string(); + } + if self.build_type.is_empty() { + self.build_type = "Release".to_string(); + } + if self.build_dir.is_empty() { + self.build_dir = "build".to_string(); + } + true + } +} + +/// CMakeLists.txt text for a generated project: project , GTK 3 +/// via PkgConfig, C++17, and add_executable(app ). `sources` +/// are the generated .cpp file names (e.g. main.cpp, MyWindow.cpp, +/// Button_001.cpp). +pub fn cmake_lists_text(project_name: &str, sources: &[String]) -> String { + let mut o = String::new(); + o.push_str("# Generated by LightGUI (C++/GTK). Build with:\n"); + o.push_str("# cmake -S . -B build && cmake --build build\n"); + o.push_str("# (or use File -> Build with CMake in the designer).\n"); + o.push_str("cmake_minimum_required(VERSION 3.10)\n"); + o.push_str(&format!("project({} CXX)\n\n", project_name)); + o.push_str("set(CMAKE_CXX_STANDARD 17)\n"); + o.push_str("set(CMAKE_CXX_STANDARD_REQUIRED ON)\n\n"); + o.push_str("find_package(PkgConfig REQUIRED)\n"); + o.push_str("pkg_check_modules(GTK3 REQUIRED gtk+-3.0)\n\n"); + o.push_str("add_executable(app\n"); + for s in sources { + o.push_str(&format!(" {}\n", s)); + } + o.push_str(")\n\n"); + o.push_str("target_include_directories(app PRIVATE ${GTK3_INCLUDE_DIRS})\n"); + o.push_str("target_compile_options(app PRIVATE ${GTK3_CFLAGS_OTHER})\n"); + o.push_str("target_link_libraries(app PRIVATE ${GTK3_LIBRARIES})\n"); + o +} + +/// True when /CMakeLists.txt exists. +pub fn cmake_project_exists(dir: &str) -> bool { + Path::new(dir).join("CMakeLists.txt").is_file() +} + +/// Shell-quote one argument for /bin/sh. +pub fn cmake_shell_quote(s: &str) -> String { + let mut out = String::from("'"); + for c in s.chars() { + if c == '\'' { + out.push_str("'\\''"); + } else { + out.push(c); + } + } + out.push('\''); + out +} + +#[derive(Debug, Clone, Default)] +pub struct CMakeBuildResult { + /// Configure AND build both succeeded. + pub ok: bool, + /// Configure step succeeded. + pub configured: bool, + /// Combined stdout+stderr of both steps. + pub output: String, + /// Absolute build directory used. + pub build_dir: String, + /// /app when it exists after build. + pub exe_path: String, +} + +/// Absolute path of the executable a successful cmake_build_project +/// leaves behind for `dir` under `settings`. +pub fn cmake_exe_path(dir: &str, settings: &CMakeSettings) -> String { + let mut d = PathBuf::from(dir); + if d.is_relative() { + d = std::fs::canonicalize(&d).unwrap_or_else(|_| { + std::env::current_dir() + .unwrap_or_else(|_| PathBuf::from("/")) + .join(&d) + }); + } + d.join(&settings.build_dir) + .join("app") + .to_string_lossy() + .to_string() +} + +/// Run `cmd`, appending its combined stdout+stderr to `out`; true on +/// exit 0. +fn run_capture(cmd: &str, out: &mut String) -> bool { + let full = format!("{} 2>&1", cmd); + match Command::new("sh").arg("-c").arg(&full).output() { + Ok(o) => { + out.push_str(&String::from_utf8_lossy(&o.stdout)); + out.push_str(&String::from_utf8_lossy(&o.stderr)); + o.status.success() + } + Err(e) => { + out.push_str(&format!("cannot run: {}\n", cmd)); + let _ = e; + false + } + } +} + +/// Configure + build the CMake project in `dir` (which must contain a +/// CMakeLists.txt). The executable is //app, matching +/// the generated Makefile's `app` target. Blocking; captures all output. +pub fn cmake_build_project(dir: &str, settings: &CMakeSettings) -> CMakeBuildResult { + let mut r = CMakeBuildResult::default(); + let mut d = PathBuf::from(dir); + if d.is_relative() { + d = std::fs::canonicalize(&d).unwrap_or_else(|_| { + std::env::current_dir() + .unwrap_or_else(|_| PathBuf::from("/")) + .join(&d) + }); + } + r.build_dir = d.join(&settings.build_dir).to_string_lossy().to_string(); + r.exe_path = cmake_exe_path(dir, settings); + if !cmake_project_exists(&d.to_string_lossy()) { + r.output = format!("no CMakeLists.txt in {}\n", d.to_string_lossy()); + return r; + } + let cmake = if settings.cmake_path.is_empty() { + "cmake".to_string() + } else { + settings.cmake_path.clone() + }; + let gen = if !settings.generator.is_empty() { + format!(" -G {}", cmake_shell_quote(&settings.generator)) + } else { + String::new() + }; + let build_type = if settings.build_type.is_empty() { + "Release".to_string() + } else { + settings.build_type.clone() + }; + let cfg = format!( + "{} -S {} -B {}{} -DCMAKE_BUILD_TYPE={}", + cmake_shell_quote(&cmake), + cmake_shell_quote(&d.to_string_lossy()), + cmake_shell_quote(&r.build_dir), + gen, + cmake_shell_quote(&build_type), + ); + r.output.push_str(&format!("$ {}\n", cfg)); + r.configured = run_capture(&cfg, &mut r.output); + if !r.configured { + return r; + } + let bld = format!( + "{} --build {}", + cmake_shell_quote(&cmake), + cmake_shell_quote(&r.build_dir), + ); + r.output.push_str(&format!("$ {}\n", bld)); + let built = run_capture(&bld, &mut r.output); + r.ok = built && Path::new(&r.exe_path).is_file(); + if built && !r.ok { + r.output.push_str(&format!( + "build reported success but {} is missing\n", + r.exe_path + )); + } + r +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lists_text_content() { + let sources = vec![ + "main.cpp".to_string(), + "MyWindow.cpp".to_string(), + "Button_001.cpp".to_string(), + "Label_001.cpp".to_string(), + "Entry_001.cpp".to_string(), + ]; + let cm = cmake_lists_text("MyWindow", &sources); + assert!(cm.contains("cmake_minimum_required(VERSION 3.10)")); + assert!(cm.contains("project(MyWindow CXX)")); + assert!(cm.contains("find_package(PkgConfig REQUIRED)")); + assert!(cm.contains("pkg_check_modules(GTK3 REQUIRED gtk+-3.0)")); + assert!(cm.contains("add_executable(app")); + for s in &sources { + assert!(cm.contains(s.as_str()), "missing {}", s); + } + assert!(cm.contains("target_include_directories(app PRIVATE ${GTK3_INCLUDE_DIRS})")); + assert!(cm.contains("target_link_libraries(app PRIVATE ${GTK3_LIBRARIES})")); + assert!(cm.contains("CMAKE_CXX_STANDARD 17")); + } + + #[test] + fn shell_quote_cases() { + assert_eq!(cmake_shell_quote("abc"), "'abc'"); + assert_eq!(cmake_shell_quote("a'b"), "'a'\\''b'"); + assert_eq!(cmake_shell_quote("dir with space"), "'dir with space'"); + } + + #[test] + fn settings_roundtrip() { + let dir = std::env::temp_dir().join("lightgui_cmake_unit"); + let _ = std::fs::create_dir_all(&dir); + let s = CMakeSettings { + cmake_path: "cmake".to_string(), + generator: "Unix Makefiles".to_string(), + build_type: "Debug".to_string(), + build_dir: "out".to_string(), + }; + let p = dir.join("cmake.conf"); + assert!(s.save(p.to_str().unwrap())); + let mut s2 = CMakeSettings::default(); + assert!(s2.load(p.to_str().unwrap())); + assert_eq!(s2.generator, "Unix Makefiles"); + assert_eq!(s2.build_type, "Debug"); + assert_eq!(s2.build_dir, "out"); + assert_eq!(s2.cmake_path, "cmake"); + // Unknown keys ignored, empty file loads as defaults. + let p2 = dir.join("cmake2.conf"); + std::fs::write(&p2, "# comment\nunknown_key=1\n").unwrap(); + let mut s3 = CMakeSettings::default(); + assert!(s3.load(p2.to_str().unwrap())); + assert_eq!(s3.build_type, "Release"); + assert_eq!(s3.build_dir, "build"); + } + + #[test] + fn project_exists_check() { + // Unique dir per process: a fixed name would keep a CMakeLists.txt + // from an earlier run and break the first assertion on re-runs. + let dir = + std::env::temp_dir().join(format!("lightgui_cmake_unit_exists_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::create_dir_all(&dir); + assert!(!cmake_project_exists(dir.to_str().unwrap())); + std::fs::write(dir.join("CMakeLists.txt"), "x\n").unwrap(); + assert!(cmake_project_exists(dir.to_str().unwrap())); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/lightgui-support/src/codeview.rs b/crates/lightgui-support/src/codeview.rs new file mode 100644 index 0000000..f99e286 --- /dev/null +++ b/crates/lightgui-support/src/codeview.rs @@ -0,0 +1,1167 @@ +// LightGUI code view — port of src/codeview.cpp / src/codeview.h. +// GtkTextView showing generated code, with a gutter (line numbers, +// red-dot breakpoints, fold toggles) and syntax highlighting from a +// CodeTheme (theme.rs). +// +// Folding covers every natural foldable unit the scanner can find: +// * #region / #endregion blocks (nested) +// * every matched-brace span: functions, if/else, loops, classes, +// structs, namespaces, initializer blocks, any other {} block +// * multi-line /* */ comments +// * preprocessor #if / #ifdef / #ifndef ... #endif blocks +// Braces inside strings, character literals, raw strings and comments +// are ignored. Unbalanced input fails gracefully: an unmatched '}' is +// ignored and an unclosed '{' / #region / #if at end of file simply +// produces no fold. +// +// Foldable regions are found by the pure function +// codeview_find_regions(); the widget hides folded lines with an +// invisible text tag, so file line numbers stay exact and breakpoint +// lines keep their meaning. + +use std::cell::RefCell; +use std::collections::BTreeSet; +use std::rc::Rc; + +use gtk::prelude::*; +use lightgui_debug::Variable; + +use crate::theme::{theme_apply_to_view, theme_current, theme_highlight_buffer, CodeTheme}; + +// ------------------------------------------------------------ pure logic + +fn trim2(s: &str) -> &str { + s.trim_matches(|c| c == ' ' || c == '\t' || c == '\r') +} + +pub fn codeview_split_lines(text: &str) -> Vec { + let mut out = Vec::new(); + let mut start = 0usize; + while start <= text.len() { + match text[start..].find('\n') { + None => { + if start < text.len() { + out.push(text[start..].to_string()); + } + break; + } + Some(rel) => { + let nl = start + rel; + let mut ln = &text[start..nl]; + if ln.ends_with('\r') { + ln = &ln[..ln.len() - 1]; + } + out.push(ln.to_string()); + start = nl + 1; + if start == text.len() { + break; // trailing \n: no phantom line + } + } + } + } + out +} + +/// One foldable span. Lines are 0-based, inclusive at both ends; only +/// spans longer than one line are reported. kind is "region", "brace", +/// "comment" or "preproc". depth is the nesting depth (0 = outermost). +/// label is a short human hint (region name, "#if ...", or the trimmed +/// first line). +#[derive(Debug, Clone, PartialEq)] +pub struct FoldRegion { + pub start_line: i32, + pub end_line: i32, + pub kind: &'static str, + pub depth: i32, + pub label: String, +} + +pub fn codeview_find_regions(lines: &[String]) -> Vec { + // Rejoin for a single character stream so strings/comments/braces + // are tracked across line boundaries with exact line numbers. + let mut text = String::new(); + for l in lines { + text.push_str(l); + text.push('\n'); + } + let b = text.as_bytes(); + let n = b.len(); + let mut out: Vec = Vec::new(); + let mut brace_stack: Vec = Vec::new(); + let mut region_stack: Vec<(i32, String)> = Vec::new(); // start, label + let mut if_stack: Vec = Vec::new(); + let open_count = + |brace_stack: &Vec, region_stack: &Vec<(i32, String)>, if_stack: &Vec| -> i32 { + (brace_stack.len() + region_stack.len() + if_stack.len()) as i32 + }; + let mut i = 0usize; + let mut line: i32 = 0; // 0-based line of text[i] + let mut line_start = true; + let mut in_block_comment = false; + let mut in_line_comment = false; + let mut in_string = false; + let mut in_char = false; + let mut comment_start: i32 = -1; + while i < n { + let mut c = b[i]; + if c == b'\n' { + in_line_comment = false; + in_string = false; // unterminated string ends at EOL + in_char = false; + line += 1; + line_start = true; + i += 1; + continue; + } + if in_line_comment { + i += 1; + continue; + } + if in_block_comment { + if c == b'*' && i + 1 < n && b[i + 1] == b'/' { + in_block_comment = false; + if line > comment_start { + out.push(FoldRegion { + start_line: comment_start, + end_line: line, + kind: "comment", + depth: open_count(&brace_stack, ®ion_stack, &if_stack), + label: "/* ... */".to_string(), + }); + } + i += 2; + line_start = false; + continue; + } + i += 1; + continue; + } + if in_string { + if c == b'\\' && i + 1 < n { + i += 2; + continue; + } + if c == b'"' { + in_string = false; + } + i += 1; + continue; + } + if in_char { + if c == b'\\' && i + 1 < n { + i += 2; + continue; + } + if c == b'\'' { + in_char = false; + } + i += 1; + continue; + } + if line_start && (c == b' ' || c == b'\t' || c == b'\r') { + i += 1; + continue; + } + if line_start && c == b'/' && i + 1 < n && b[i + 1] == b'/' { + // Comment-style directive (`// #region` / `// #endregion`, + // the form the generator emits): parse it as a directive. + let mut j = i + 2; + while j < n && (b[j] == b' ' || b[j] == b'\t') { + j += 1; + } + if j < n && b[j] == b'#' { + i = j; + c = b'#'; + } + } + if line_start && c == b'#' { + // Preprocessor directive: parse the word, handle the + // foldable ones, then skip the whole line (no braces counted + // inside a directive line). + let mut j = i + 1; + while j < n && (b[j] == b' ' || b[j] == b'\t') { + j += 1; + } + let ws = j; + while j < n && b[j].is_ascii_alphabetic() { + j += 1; + } + let word = &text[ws..j]; + let mut rest = String::new(); + if word == "region" || word == "if" || word == "ifdef" || word == "ifndef" { + let eol = text[j..].find('\n').map(|r| j + r).unwrap_or(n); + rest = trim2(&text[j..eol]).to_string(); + if rest.len() > 48 { + rest.truncate(48); + } + } + if word == "region" { + region_stack.push(( + line, + if rest.is_empty() { + "#region".to_string() + } else { + format!("#region {}", rest) + }, + )); + } else if word == "endregion" { + if let Some(st) = region_stack.pop() { + if line > st.0 { + out.push(FoldRegion { + start_line: st.0, + end_line: line, + kind: "region", + depth: open_count(&brace_stack, ®ion_stack, &if_stack), + label: st.1, + }); + } + } + } else if word == "if" || word == "ifdef" || word == "ifndef" { + if_stack.push(line); + } else if word == "endif" { + if let Some(st) = if_stack.pop() { + if line > st { + out.push(FoldRegion { + start_line: st, + end_line: line, + kind: "preproc", + depth: open_count(&brace_stack, ®ion_stack, &if_stack), + label: format!("#{} {}", word, rest), + }); + } + } + } + // Skip to end of line. + while i < n && b[i] != b'\n' { + i += 1; + } + continue; + } + line_start = false; + if c == b'/' && i + 1 < n && b[i + 1] == b'/' { + in_line_comment = true; + i += 2; + continue; + } + if c == b'/' && i + 1 < n && b[i + 1] == b'*' { + in_block_comment = true; + comment_start = line; + i += 2; + continue; + } + if c == b'"' { + // Raw string? R"delim( ... )delim" — also u8R/uR/UR/LR. + let mut raw = false; + let mut delim = String::new(); + if i >= 1 + && b[i - 1] == b'R' + && (i < 2 + || !b[i - 2].is_ascii_alphanumeric() + || b[i - 2] == b'u' + || b[i - 2] == b'U' + || b[i - 2] == b'L') + { + let mut p = i + 1; + while p < n && b[p] != b'(' && b[p] != b'\n' && b[p] != b' ' && b[p] != b'\t' { + p += 1; + } + if p < n && b[p] == b'(' { + raw = true; + delim = text[i + 1..p].to_string(); + } + } + if raw { + let close = format!("){}\"", delim); + match text[i + 1..].find(&close) { + None => { + // unterminated raw string: rest is string + break; + } + Some(f) => { + let f_abs = i + 1 + f; + for &ch in &b[i..f_abs + close.len()] { + if ch == b'\n' { + line += 1; + } + } + i = f_abs + close.len(); + continue; + } + } + } + in_string = true; + i += 1; + continue; + } + if c == b'\'' { + // Digit separator (1'000) is not a character literal. + let sep = i > 0 && (b[i - 1].is_ascii_alphanumeric() || b[i - 1] == b'_'); + if !sep { + in_char = true; + } + i += 1; + continue; + } + if c == b'{' { + brace_stack.push(line); + i += 1; + continue; + } + if c == b'}' { + if let Some(st) = brace_stack.pop() { + if line > st { + let mut label = trim2(&lines[st as usize]).to_string(); + if label.len() > 48 { + label.truncate(48); + } + out.push(FoldRegion { + start_line: st, + end_line: line, + kind: "brace", + depth: open_count(&brace_stack, ®ion_stack, &if_stack), + label, + }); + } + } + // Unmatched '}': ignored — graceful, no fold, no crash. + i += 1; + continue; + } + i += 1; + } + // Unclosed '{', #region, #if, /* at EOF: dropped, no wrong fold. + // Depths: recompute properly — a region's depth is the number of + // other regions strictly containing it. + let count = out.len(); + for a in 0..count { + let mut d = 0; + for o in 0..count { + if o != a && out[o].start_line < out[a].start_line && out[o].end_line > out[a].end_line + { + d += 1; + } + } + out[a].depth = d; + } + out.sort_by(|a, b| { + if a.start_line != b.start_line { + a.start_line.cmp(&b.start_line) + } else { + b.end_line.cmp(&a.end_line) // outermost first at same start + } + }); + out +} + +/// True when 0-based `line` is strictly inside any region whose start +/// line is in `folded_starts` (start/end lines themselves stay visible). +pub fn codeview_line_hidden( + line: i32, + regions: &[FoldRegion], + folded_starts: &BTreeSet, +) -> bool { + regions + .iter() + .any(|r| folded_starts.contains(&r.start_line) && line > r.start_line && line < r.end_line) +} + +/// 0-based lines that stay visible given the folded start lines. +pub fn codeview_visible_lines(lines: &[String], folded_starts: &BTreeSet) -> Vec { + let regions = codeview_find_regions(lines); + (0..lines.len() as i32) + .filter(|l| !codeview_line_hidden(*l, ®ions, folded_starts)) + .collect() +} + +// ------------------------------------------------------------ widget + +/// Automatic variable inspection pane state (see codeview.h). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CodeViewInspectState { + NoTarget, + Running, + Stopped, + Exited, +} + +/// Breakpoint-toggle callback: (file, 1-based line) -> handled. +pub type BpCallback = Rc bool>; + +struct CodeViewState { + view: gtk::TextView, + gutter: gtk::DrawingArea, + scope_label: gtk::Label, + vars_store: gtk::ListStore, + file_path: String, + lines: Vec, + regions: Vec, + folded: BTreeSet, // 0-based region start lines + breakpoints: BTreeSet, // 1-based file lines + current_line: i32, // 1-based, 0 = none + paused_line: i32, // 1-based, 0 = none (debugger paused here) + theme: CodeTheme, + bp_cb: Option, + fold_tag: Option, + cur_tag: Option, + paused_tag: Option, + inspect_state: CodeViewInspectState, + inspect_scope: String, + inspect_vars: Vec, +} + +fn parse_hex(s: &str) -> Option<(f64, f64, f64)> { + let b = s.as_bytes(); + if b.len() != 7 || b[0] != b'#' { + return None; + } + let v = |k: usize| u8::from_str_radix(&s[k..k + 2], 16).ok(); + Some(( + v(1)? as f64 / 255.0, + v(3)? as f64 / 255.0, + v(5)? as f64 / 255.0, + )) +} + +fn is_dark_theme(t: &CodeTheme) -> bool { + match parse_hex(&t.background) { + Some((r, g, b)) => (0.299 * r + 0.587 * g + 0.114 * b) < 0.5, + None => false, + } +} + +/// A GtkBox (gutter + scrolled text view + inspection pane). +/// All line numbers in the widget API are 1-based file lines. +pub struct CodeView { + state: Rc>, + outer: gtk::Box, +} + +impl CodeView { + pub fn new() -> CodeView { + let outer = gtk::Box::new(gtk::Orientation::Vertical, 0); + let code_box = gtk::Box::new(gtk::Orientation::Horizontal, 0); + outer.pack_start(&code_box, true, true, 0); + + let gutter = gtk::DrawingArea::new(); + gutter.set_size_request(76, 100); + gutter.add_events(gdk::EventMask::BUTTON_PRESS_MASK); + + let view = gtk::TextView::new(); + view.set_editable(false); + view.set_cursor_visible(false); + view.set_monospace(true); + view.set_wrap_mode(gtk::WrapMode::None); + view.set_left_margin(8); + + let scroll = gtk::ScrolledWindow::new(None::<>k::Adjustment>, None::<>k::Adjustment>); + scroll.set_policy(gtk::PolicyType::Automatic, gtk::PolicyType::Automatic); + let inner = gtk::Box::new(gtk::Orientation::Horizontal, 0); + inner.pack_start(&gutter, false, false, 0); + inner.pack_start(&view, true, true, 0); + scroll.add(&inner); + code_box.pack_start(&scroll, true, true, 0); + + // Inspection pane: scope label + name/type/value list. + let inspect_frame = + gtk::Frame::new(Some("Variables in scope \u{2014} automatic inspection")); + let ivbox = gtk::Box::new(gtk::Orientation::Vertical, 4); + ivbox.set_margin_top(6); + ivbox.set_margin_bottom(6); + ivbox.set_margin_start(6); + ivbox.set_margin_end(6); + let scope_label = gtk::Label::new(Some( + "No target running \u{2014} start the debugger to inspect variables.", + )); + scope_label.set_xalign(0.0); + scope_label.set_ellipsize(pango::EllipsizeMode::End); + ivbox.pack_start(&scope_label, false, false, 0); + let vars_store = + gtk::ListStore::new(&[glib::Type::STRING, glib::Type::STRING, glib::Type::STRING]); + let vars_view = gtk::TreeView::with_model(&vars_store); + for (title, col, expand) in [("Name", 0, false), ("Type", 1, false), ("Value", 2, true)] { + let renderer = gtk::CellRendererText::new(); + let column = gtk::TreeViewColumn::new(); + column.set_title(title); + gtk::prelude::TreeViewColumnExt::pack_start(&column, &renderer, expand); + gtk::prelude::TreeViewColumnExt::add_attribute(&column, &renderer, "text", col); + column.set_expand(expand); + vars_view.append_column(&column); + } + let vscroll = gtk::ScrolledWindow::new(None::<>k::Adjustment>, None::<>k::Adjustment>); + vscroll.set_policy(gtk::PolicyType::Automatic, gtk::PolicyType::Automatic); + vscroll.set_size_request(-1, 140); + vscroll.add(&vars_view); + ivbox.pack_start(&vscroll, true, true, 0); + inspect_frame.add(&ivbox); + outer.pack_start(&inspect_frame, false, false, 0); + + let state = Rc::new(RefCell::new(CodeViewState { + view: view.clone(), + gutter: gutter.clone(), + scope_label: scope_label.clone(), + vars_store: vars_store.clone(), + file_path: String::new(), + lines: Vec::new(), + regions: Vec::new(), + folded: BTreeSet::new(), + breakpoints: BTreeSet::new(), + current_line: 0, + paused_line: 0, + theme: theme_current(), + bp_cb: None, + fold_tag: None, + cur_tag: None, + paused_tag: None, + inspect_state: CodeViewInspectState::NoTarget, + inspect_scope: String::new(), + inspect_vars: Vec::new(), + })); + + // Gutter drawing + clicks. + { + let st = Rc::clone(&state); + gutter.connect_draw(move |gutter, cr| { + on_gutter_draw(gutter, cr, &st); + glib::Propagation::Proceed + }); + } + { + let st = Rc::clone(&state); + gutter.connect_button_press_event(move |_, ev| { + if ev.button() != 1 { + return glib::Propagation::Proceed; + } + let (x, y) = ev.position(); + let ln = gutter_line_at_y(&st, y); + if ln < 0 { + return glib::Propagation::Proceed; + } + if x < 18.0 { + if region_starts_at(&st, ln) { + toggle_fold_line(&st, ln); + } + } else { + toggle_bp_line(&st, ln + 1); + } + glib::Propagation::Stop + }); + } + { + let g = gutter.clone(); + view.connect_size_allocate(move |_, alloc| { + g.set_size_request(76, alloc.height()); + }); + } + { + let g = gutter.clone(); + scroll + .vadjustment() + .connect_value_changed(move |_| g.queue_draw()); + } + + CodeView { state, outer } + } + + pub fn widget(&self) -> gtk::Box { + self.outer.clone() + } + + pub fn text_view(&self) -> gtk::TextView { + self.state.borrow().view.clone() + } + + pub fn set_text(&self, text: &str, file_path: &str) { + let theme = { + let mut st = self.state.borrow_mut(); + st.file_path = file_path.to_string(); + st.lines = codeview_split_lines(text); + st.regions = codeview_find_regions(&st.lines); + st.folded.clear(); + st.breakpoints.clear(); + st.current_line = 0; + st.paused_line = 0; // new file: no paused line until the next stop + st.theme.clone() + }; + let buf = self.state.borrow().view.buffer().expect("text buffer"); + buf.set_text(text); + let table = buf.tag_table().expect("tag table"); + { + let mut st = self.state.borrow_mut(); + st.fold_tag = Some(match table.lookup("theme-fold-hidden") { + Some(t) => t, + None => { + let tag = gtk::TextTag::new(Some("theme-fold-hidden")); + tag.set_property("invisible", true); + table.add(&tag); + tag + } + }); + st.cur_tag = Some(match table.lookup("theme-current-line") { + Some(t) => { + t.set_property("background", theme.current_line.as_str()); + t + } + None => { + let tag = gtk::TextTag::new(Some("theme-current-line")); + tag.set_property("background", theme.current_line.as_str()); + table.add(&tag); + tag + } + }); + ensure_paused_tag(&mut st, &buf); + } + theme_highlight_buffer(&buf, &theme); + theme_apply_to_view(self.state.borrow().view.upcast_ref(), &theme); + apply_folds(&self.state); + queue_redraw(&self.state); + } + + pub fn file_path(&self) -> String { + self.state.borrow().file_path.clone() + } + + pub fn line_count(&self) -> i32 { + // File lines, not the buffer count: a trailing newline makes the + // buffer report one extra empty line. + self.state.borrow().lines.len() as i32 + } + + pub fn set_theme(&self, theme: &CodeTheme) { + let buf = self.state.borrow().view.buffer().expect("text buffer"); + { + let mut st = self.state.borrow_mut(); + st.theme = theme.clone(); + if let Some(tag) = &st.cur_tag { + tag.set_property("background", &theme.current_line); + } + ensure_paused_tag(&mut st, &buf); + } + apply_line_marks(&self.state); + theme_highlight_buffer(&buf, theme); + theme_apply_to_view(self.state.borrow().view.upcast_ref(), theme); + queue_redraw(&self.state); + } + + pub fn theme(&self) -> CodeTheme { + self.state.borrow().theme.clone() + } + + pub fn set_current_line(&self, line_1based: i32) { + self.state.borrow_mut().current_line = line_1based; + apply_line_marks(&self.state); + queue_redraw(&self.state); + } + + pub fn current_line(&self) -> i32 { + self.state.borrow().current_line + } + + pub fn set_paused_line(&self, line_1based: i32) { + self.state.borrow_mut().paused_line = line_1based; + apply_line_marks(&self.state); + queue_redraw(&self.state); + if line_1based >= 1 { + let st = self.state.borrow(); + let buf = st.view.buffer().expect("text buffer"); + if line_1based <= buf.line_count() { + let mut it = buf.iter_at_line(line_1based - 1); + st.view.scroll_to_iter(&mut it, 0.0, true, 0.0, 0.5); + } + } + } + + pub fn paused_line(&self) -> i32 { + self.state.borrow().paused_line + } + + pub fn set_inspection( + &self, + state: CodeViewInspectState, + scope_label: &str, + vars: &[Variable], + ) { + { + let mut st = self.state.borrow_mut(); + st.inspect_state = state; + st.inspect_scope = scope_label.to_string(); + st.inspect_vars = vars.to_vec(); + } + refresh_inspection_ui(&self.state); + } + + pub fn inspection_state(&self) -> CodeViewInspectState { + self.state.borrow().inspect_state + } + + pub fn inspection_scope(&self) -> String { + self.state.borrow().inspect_scope.clone() + } + + pub fn inspection_vars(&self) -> Vec { + self.state.borrow().inspect_vars.clone() + } + + pub fn set_breakpoint_callback(&self, cb: BpCallback) { + self.state.borrow_mut().bp_cb = Some(cb); + } + + pub fn set_breakpoint_lines(&self, lines_1based: &BTreeSet) { + self.state.borrow_mut().breakpoints = lines_1based.clone(); + queue_redraw(&self.state); + } + + pub fn breakpoint_lines(&self) -> BTreeSet { + self.state.borrow().breakpoints.clone() + } + + pub fn regions(&self) -> Vec { + self.state.borrow().regions.clone() + } + + pub fn toggle_fold_at(&self, line_1based: i32) -> bool { + let line0 = line_1based - 1; + if !region_starts_at(&self.state, line0) { + return false; + } + toggle_fold_line(&self.state, line0); + true + } + + pub fn is_folded(&self, line_1based: i32) -> bool { + self.state.borrow().folded.contains(&(line_1based - 1)) + } + + /// Test helper: simulate a gutter click at a file line. `in_fold_zone` + /// mimics clicking the [-]/[+] marker column. + pub fn gutter_click(&self, line_1based: i32, in_fold_zone: bool) { + let line0 = line_1based - 1; + if in_fold_zone && region_starts_at(&self.state, line0) { + toggle_fold_line(&self.state, line0); + } else if !in_fold_zone { + toggle_bp_line(&self.state, line_1based); + } + } + + pub fn toggle_breakpoint_at(&self, line_1based: i32) { + toggle_bp_line(&self.state, line_1based); + } +} + +impl Default for CodeView { + fn default() -> Self { + Self::new() + } +} + +fn region_starts_at(state: &Rc>, line0: i32) -> bool { + state.borrow().regions.iter().any(|r| r.start_line == line0) +} + +/// Buffer line (0-based) at a gutter y in widget coordinates; -1 if none. +fn gutter_line_at_y(state: &Rc>, y: f64) -> i32 { + let st = state.borrow(); + let buf = match st.view.buffer() { + Some(b) => b, + None => return -1, + }; + let count = buf.line_count(); + for ln in 0..count { + let it = buf.iter_at_line(ln); + let (ly, lh) = st.view.line_yrange(&it); + if lh > 0 && (y as i32) >= ly && (y as i32) < ly + lh { + return ln; + } + } + -1 +} + +fn toggle_fold_line(state: &Rc>, line0: i32) { + if !region_starts_at(state, line0) { + return; + } + { + let mut st = state.borrow_mut(); + if st.folded.contains(&line0) { + st.folded.remove(&line0); + } else { + st.folded.insert(line0); + } + } + apply_folds(state); + queue_redraw(state); +} + +fn toggle_bp_line(state: &Rc>, line1: i32) { + let now_set = { + let st = state.borrow(); + match &st.bp_cb { + Some(cb) => cb(&st.file_path, line1), + None => !st.breakpoints.contains(&line1), + } + }; + { + let mut st = state.borrow_mut(); + if now_set { + st.breakpoints.insert(line1); + } else { + st.breakpoints.remove(&line1); + } + } + queue_redraw(state); +} + +fn queue_redraw(state: &Rc>) { + let st = state.borrow(); + st.gutter.queue_draw(); + st.view.queue_draw(); +} + +fn apply_folds(state: &Rc>) { + let st = state.borrow(); + let Some(buf) = st.view.buffer() else { return }; + let Some(fold_tag) = st.fold_tag.clone() else { + return; + }; + let (a, b) = buf.bounds(); + buf.remove_tag(&fold_tag, &a, &b); + for start in st.folded.iter() { + for r in st.regions.iter() { + if r.start_line != *start { + continue; + } + if r.end_line <= r.start_line + 1 { + continue; // nothing to hide + } + let sa = buf.iter_at_line(r.start_line + 1); + let sb = buf.iter_at_line(r.end_line); + buf.apply_tag(&fold_tag, &sa, &sb); + } + } +} + +// (Re)apply the current-line and paused-line tags. The paused tag has +// higher priority than the current-line tag, so when both mark the same +// line the red paused background wins. +fn apply_line_marks(state: &Rc>) { + let st = state.borrow(); + let Some(buf) = st.view.buffer() else { return }; + let (a, b) = buf.bounds(); + if let Some(tag) = &st.cur_tag { + buf.remove_tag(tag, &a, &b); + } + if let Some(tag) = &st.paused_tag { + buf.remove_tag(tag, &a, &b); + } + let apply_one = |tag: &Option, line1: i32| { + let Some(tag) = tag else { return }; + if line1 < 1 || line1 > buf.line_count() { + return; + } + let sa = buf.iter_at_line(line1 - 1); + let sb = if line1 < buf.line_count() { + buf.iter_at_line(line1) + } else { + buf.end_iter() + }; + buf.apply_tag(tag, &sa, &sb); + }; + apply_one(&st.cur_tag, st.current_line); + if let Some(tag) = &st.paused_tag { + if st.paused_line >= 1 { + let table = buf.tag_table().expect("tag table"); + tag.set_priority(table.size() - 1); + } + } + apply_one(&st.paused_tag, st.paused_line); +} + +/// The paused-line tag: solid red background, white text — readable on +/// any theme. Created (or re-pointed) whenever the buffer's tags are +/// (re)built. +fn ensure_paused_tag(st: &mut CodeViewState, buf: >k::TextBuffer) { + let table = buf.tag_table().expect("tag table"); + let tag = match table.lookup("theme-paused-line") { + Some(t) => { + t.set_property("background", "#c00000"); + t.set_property("foreground", "white"); + t + } + None => { + let tag = gtk::TextTag::new(Some("theme-paused-line")); + tag.set_property("background", "#c00000"); + tag.set_property("foreground", "white"); + table.add(&tag); + tag + } + }; + // Outrank every other tag on the line: top priority in the table is + // always valid. + tag.set_priority(table.size() - 1); + st.paused_tag = Some(tag); +} + +// Repaint the inspection pane from the stored snapshot. While the +// target runs the pane shows the running state and NO values, so stale +// locals are never presented as current. +fn refresh_inspection_ui(state: &Rc>) { + let st = state.borrow(); + let scope = match st.inspect_state { + CodeViewInspectState::NoTarget => { + "No target running \u{2014} start the debugger to inspect variables.".to_string() + } + CodeViewInspectState::Running => { + "Running \u{2014} variables will appear when the target stops.".to_string() + } + CodeViewInspectState::Stopped => { + if st.inspect_scope.is_empty() { + "Stopped.".to_string() + } else { + st.inspect_scope.clone() + } + } + CodeViewInspectState::Exited => { + if st.inspect_scope.is_empty() { + "Target exited.".to_string() + } else { + st.inspect_scope.clone() + } + } + }; + st.scope_label.set_text(&scope); + st.vars_store.clear(); + if st.inspect_state == CodeViewInspectState::Stopped { + if st.inspect_vars.is_empty() { + let it = st.vars_store.append(); + st.vars_store + .set_value(&it, 0, &glib::ToValue::to_value("(no locals in scope)")); + st.vars_store + .set_value(&it, 1, &glib::ToValue::to_value("")); + st.vars_store + .set_value(&it, 2, &glib::ToValue::to_value("")); + } else { + for v in st.inspect_vars.iter() { + let it = st.vars_store.append(); + st.vars_store + .set_value(&it, 0, &glib::ToValue::to_value(&v.name)); + st.vars_store + .set_value(&it, 1, &glib::ToValue::to_value(&v.typ)); + st.vars_store + .set_value(&it, 2, &glib::ToValue::to_value(&v.value)); + } + } + } +} + +fn on_gutter_draw( + gutter: >k::DrawingArea, + cr: &cairo::Context, + state: &Rc>, +) { + let st = state.borrow(); + let alloc = gutter.allocation(); + let dark = is_dark_theme(&st.theme); + if dark { + cr.set_source_rgb(0.17, 0.17, 0.17); + } else { + cr.set_source_rgb(0.93, 0.93, 0.93); + } + cr.rectangle(0.0, 0.0, alloc.width() as f64, alloc.height() as f64); + let _ = cr.fill(); + // Divider between gutter and code. + let dv = if dark { 0.35 } else { 0.75 }; + cr.set_source_rgb(dv, dv, dv); + cr.rectangle((alloc.width() - 1) as f64, 0.0, 1.0, alloc.height() as f64); + let _ = cr.fill(); + + let (fr, fg, fb) = parse_hex(&st.theme.foreground).unwrap_or((0.2, 0.2, 0.2)); + let (cr_, cg, cb) = parse_hex(&st.theme.current_line).unwrap_or((0.9, 0.9, 0.9)); + + let Some(buf) = st.view.buffer() else { return }; + let count = buf.line_count(); + cr.select_font_face( + "monospace", + cairo::FontSlant::Normal, + cairo::FontWeight::Normal, + ); + cr.set_font_size(11.0); + for ln in 0..count { + let it = buf.iter_at_line(ln); + let (y, h) = st.view.line_yrange(&it); + if h <= 0 { + continue; // folded away + } + let paused = st.paused_line == ln + 1; + if paused { + // Red gutter strip to match the red paused-line background. + cr.set_source_rgb(0.75, 0.0, 0.0); + cr.rectangle(0.0, y as f64, alloc.width() as f64, h as f64); + let _ = cr.fill(); + // White right-pointing execution arrow (Lazarus-style). + let yc = y as f64 + h as f64 / 2.0; + cr.set_source_rgb(1.0, 1.0, 1.0); + cr.move_to(14.0, yc - 5.0); + cr.line_to(14.0, yc + 5.0); + cr.line_to(22.0, yc); + cr.close_path(); + let _ = cr.fill(); + } else if st.current_line == ln + 1 { + cr.set_source_rgb(cr_, cg, cb); + cr.rectangle(0.0, y as f64, alloc.width() as f64, h as f64); + let _ = cr.fill(); + } + let is_start = st.regions.iter().any(|r| r.start_line == ln); + if is_start { + let folded = st.folded.contains(&ln); + let gv = if dark { 0.75 } else { 0.4 }; + cr.set_source_rgb(gv, gv, gv); + cr.rectangle(3.0, y as f64 + (h as f64 - 12.0) / 2.0, 12.0, 12.0); + let _ = cr.stroke(); + cr.move_to(6.0, y as f64 + (h as f64 - 12.0) / 2.0 + 9.0); + let _ = cr.show_text(if folded { "+" } else { "-" }); + } + if st.breakpoints.contains(&(ln + 1)) { + cr.set_source_rgb(0.88, 0.11, 0.14); + cr.arc( + 26.0, + y as f64 + h as f64 / 2.0, + 5.0, + 0.0, + 2.0 * std::f64::consts::PI, + ); + let _ = cr.fill(); + } + let num = format!("{}", ln + 1); + let ext = cr + .text_extents(&num) + .unwrap_or_else(|_| cairo::TextExtents::new(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)); + if paused { + cr.set_source_rgba(1.0, 1.0, 1.0, 1.0); + } else { + cr.set_source_rgba(fr, fg, fb, 0.65); + } + cr.move_to( + alloc.width() as f64 - 6.0 - ext.width(), + y as f64 + h as f64 - 4.0, + ); + let _ = cr.show_text(&num); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fold_lines() -> Vec { + 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(), + ] + } + + #[test] + fn split_lines_cases() { + assert_eq!(codeview_split_lines(""), Vec::::new()); + assert_eq!(codeview_split_lines("a\nb\n"), vec!["a", "b"]); + assert_eq!(codeview_split_lines("a\nb"), vec!["a", "b"]); + assert_eq!(codeview_split_lines("a\r\nb\r\n"), vec!["a", "b"]); + assert_eq!(codeview_split_lines("a\n"), vec!["a"]); + } + + #[test] + fn regions_sample() { + let flines = fold_lines(); + let regs = codeview_find_regions(&flines); + assert_eq!(regs.len(), 6, "regs: {:?}", regs); + let has_region = |st: i32, en: i32, kind: &str| { + regs.iter() + .any(|r| r.start_line == st && r.end_line == en && r.kind == kind) + }; + assert!(has_region(0, 10, "region")); + assert!(has_region(1, 9, "brace")); + assert!(has_region(2, 8, "brace")); + assert!(has_region(3, 5, "brace")); + assert!(has_region(6, 7, "comment")); + assert!(has_region(11, 13, "preproc")); + let mut depth_of = [-1i32; 17]; + for r in ®s { + depth_of[r.start_line as usize] = r.depth; + } + assert_eq!(depth_of[0], 0); + assert_eq!(depth_of[1], 1); + assert_eq!(depth_of[2], 2); + assert_eq!(depth_of[3], 3); + assert_eq!(depth_of[6], 3); + assert_eq!(depth_of[11], 0); + // No region starts at the extra close (14) or the unclosed brace (15). + assert!(!regs + .iter() + .any(|r| r.start_line == 14 || r.start_line == 15)); + // 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); + assert_eq!(tregs.len(), 1); + assert_eq!(tregs[0].start_line, 2); + assert_eq!(tregs[0].end_line, 4); + // Single-line block: nothing to fold. + assert!(codeview_find_regions(&["int f() { return 0; }".to_string()]).is_empty()); + // Comment-style region markers fold like bare #region. + 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); + assert_eq!(cregs.len(), 1); + assert_eq!(cregs[0].start_line, 0); + assert_eq!(cregs[0].end_line, 2); + assert_eq!(cregs[0].kind, "region"); + } + + #[test] + fn visible_lines_sample() { + let flines = fold_lines(); + let mut folded = BTreeSet::new(); + folded.insert(0); + let vis = codeview_visible_lines(&flines, &folded); + assert_eq!(vis.len(), 8); + assert_eq!(vis[0], 0); + assert_eq!(vis[1], 10); + let mut folded = BTreeSet::new(); + folded.insert(2); + assert_eq!(codeview_visible_lines(&flines, &folded).len(), 12); + let mut folded = BTreeSet::new(); + folded.insert(0); + folded.insert(2); + assert_eq!(codeview_visible_lines(&flines, &folded).len(), 8); + let mut folded = BTreeSet::new(); + folded.insert(3); + let vis = codeview_visible_lines(&flines, &folded); + assert_eq!(vis.len(), 16); + assert_eq!(vis[3], 3); + assert_eq!(vis[4], 5); + } +} diff --git a/crates/lightgui-support/src/lib.rs b/crates/lightgui-support/src/lib.rs new file mode 100644 index 0000000..906d233 --- /dev/null +++ b/crates/lightgui-support/src/lib.rs @@ -0,0 +1,34 @@ +//! LightGUI support modules — port of the non-debugger support sources +//! from lightgui (`eb0b5fc`): +//! +//! * `theme` — code-view color themes + C++ tokenizer (`src/theme.cpp`) +//! * `preferences` — global font settings (`src/preferences.cpp`) +//! * `codeview` — code view widget + fold scanner (`src/codeview.cpp`) +//! * `cmake` — CMakeLists.txt emitter + configure/build runner +//! (`src/cmake_build.cpp`) +//! +//! The GTK-dependent parts need `gtk::init()` (and a display, e.g. +//! under `xvfb-run`) before use; the pure parts (tokenizer, fold +//! scanner, settings parsing, CMakeLists text) do not. + +pub mod cmake; +pub mod codeview; +pub mod preferences; +pub mod theme; + +pub use cmake::{ + cmake_build_project, cmake_exe_path, cmake_lists_text, cmake_project_exists, cmake_shell_quote, + CMakeBuildResult, CMakeSettings, +}; +pub use codeview::{ + codeview_find_regions, codeview_line_hidden, codeview_split_lines, codeview_visible_lines, + CodeView, CodeViewInspectState, FoldRegion, +}; +pub use preferences::{ + preferences_applied_font, preferences_apply, preferences_apply_to_text_view, + preferences_current, preferences_open, FontSettings, +}; +pub use theme::{ + theme_current, theme_highlight_buffer, theme_picker_open, theme_set_current, theme_tokenize, + CodeTheme, HlSpan, +}; diff --git a/crates/lightgui-support/src/preferences.rs b/crates/lightgui-support/src/preferences.rs new file mode 100644 index 0000000..a585f47 --- /dev/null +++ b/crates/lightgui-support/src/preferences.rs @@ -0,0 +1,429 @@ +// LightGUI global font settings — port of src/preferences.cpp / +// src/preferences.h (Edit -> Preferences...). +// +// One interface font and one code/text-view font, chosen with +// GtkFontButton widgets. Persisted in ~/.config/lightgui/settings.conf +// (key=value, the same pattern as the debugger's debugger.conf); +// LIGHTGUI_SETTINGS_CONF overrides the path (used by tests). +// +// Application is live and visible: the interface font is installed as +// a screen-wide CSS provider ("* { font-family...; font-size... }") +// and the code font as a "textview" CSS rule. Sizes are clamped to +// 6-48 pt; an empty or unparseable description falls back to the +// default instead of breaking the UI. + +use std::cell::RefCell; +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); + } + } +} + +/// Escape a font family for a quoted CSS string value. +fn css_quote(family: &str) -> String { + let mut out = String::new(); + for c in family.chars() { + if c == '"' || c == '\\' { + out.push('\\'); + } + out.push(c); + } + format!("\"{}\"", out) +} + +#[derive(Debug, Clone, PartialEq)] +pub struct FontSettings { + /// Interface font (Pango description). + pub font: String, + /// Code / text-view font. + pub code_font: String, +} + +impl Default for FontSettings { + fn default() -> Self { + FontSettings { + font: "Sans 10".to_string(), + code_font: "Monospace 11".to_string(), + } + } +} + +impl FontSettings { + pub fn default_path() -> String { + match std::env::var("LIGHTGUI_SETTINGS_CONF") { + Ok(e) if !e.is_empty() => e, + _ => format!("{}/.config/lightgui/settings.conf", home_dir()), + } + } + + /// Parse desc as a Pango font description; fall back to `fallback` + /// when it is empty/unparseable, and clamp the size to 6-48 pt. + pub fn sanitized(desc: &str, fallback: &str) -> String { + let d = pango::FontDescription::from_string(desc); + let family = d.family(); + if family.is_none() || family.map(|f| f.is_empty()).unwrap_or(true) { + if desc == fallback { + return "Sans 10".to_string(); // fallback itself is bad + } + return Self::sanitized(fallback, fallback); + } + let mut d = d; + let size = d.size(); // Pango units, 0 = unset + let fallback_size = Self::size_of(fallback); + let size = if size <= 0 { + (if fallback_size > 0 { fallback_size } else { 10 }) * pango::SCALE + } else { + size.clamp(6 * pango::SCALE, 48 * pango::SCALE) + }; + d.set_size(size); + d.to_string() + } + + /// "" if none. + pub fn family_of(desc: &str) -> String { + let d = pango::FontDescription::from_string(desc); + d.family().map(|f| f.to_string()).unwrap_or_default() + } + + /// pt, 0 if none. + pub fn size_of(desc: &str) -> i32 { + let d = pango::FontDescription::from_string(desc); + let size = d.size(); + if size > 0 { + size / pango::SCALE + } else { + 0 + } + } + + /// "* { font-family...; font-size... }" + pub fn ui_css(&self) -> String { + format!( + "* {{ font-family: {}; font-size: {}pt; }}", + css_quote(&Self::family_of(&self.font)), + Self::size_of(&self.font) + ) + } + + /// "textview { font-family...; ... }" + pub fn code_css(&self) -> String { + format!( + "textview {{ font-family: {}; font-size: {}pt; }}", + css_quote(&Self::family_of(&self.code_font)), + Self::size_of(&self.code_font) + ) + } + + 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!( + "# LightGUI settings\nfont={}\ncode_font={}\n", + Self::sanitized(&self.font, "Sans 10"), + Self::sanitized(&self.code_font, "Monospace 11"), + ); + 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, + }; + for line in text.lines() { + let t = trim_s(line); + if t.is_empty() || t.starts_with('#') { + continue; + } + let Some(eq) = t.find('=') else { continue }; + let key = trim_s(&t[..eq]); + let value = trim_s(&t[eq + 1..]); + if key == "font" { + let cur = self.font.clone(); + self.font = Self::sanitized(value, &cur); + } else if key == "code_font" { + let cur = self.code_font.clone(); + self.code_font = Self::sanitized(value, &cur); + } + } + true + } +} + +struct CurrentFonts { + settings: FontSettings, + loaded: bool, +} + +static CURRENT: OnceLock> = OnceLock::new(); + +fn current_lock() -> &'static Mutex { + CURRENT.get_or_init(|| { + Mutex::new(CurrentFonts { + settings: FontSettings::default(), + loaded: false, + }) + }) +} + +/// Settings currently in effect (loaded from disk on first call). +pub fn preferences_current() -> FontSettings { + let mut g = current_lock().lock().unwrap(); + if !g.loaded { + g.settings.load(""); // keeps defaults when no file exists + g.loaded = true; + } + g.settings.clone() +} + +fn load_css(provider: >k::CssProvider, css: &str) { + if let Err(e) = provider.load_from_data(css.as_bytes()) { + eprintln!("lightgui: font CSS failed: {}", e); + } +} + +struct ScreenProviders { + ui: gtk::CssProvider, + code: gtk::CssProvider, + added: bool, +} + +thread_local! { + // GTK objects are not Send/Sync, so the screen-wide providers live + // in thread-local storage (the GUI is single-threaded anyway). + static SCREEN: RefCell = RefCell::new(ScreenProviders { + ui: gtk::CssProvider::new(), + code: gtk::CssProvider::new(), + added: false, + }); +} + +/// Install the fonts as screen-wide CSS providers (re-appliable). +pub fn preferences_apply(s: &FontSettings) { + SCREEN.with(|cell| { + let mut g = cell.borrow_mut(); + load_css(&g.ui, &s.ui_css()); + load_css(&g.code, &s.code_css()); + if !g.added { + if let Some(screen) = gdk::Screen::default() { + gtk::StyleContext::add_provider_for_screen( + &screen, + &g.ui, + gtk::STYLE_PROVIDER_PRIORITY_APPLICATION, + ); + gtk::StyleContext::add_provider_for_screen( + &screen, + &g.code, + gtk::STYLE_PROVIDER_PRIORITY_APPLICATION, + ); + g.added = true; + } + } + }); +} + +/// Apply the code font to one text view (e.g. a code display). +pub fn preferences_apply_to_text_view(view: >k::Widget, s: &FontSettings) { + let provider = gtk::CssProvider::new(); + load_css( + &provider, + &format!( + "* {{ font-family: {}; font-size: {}pt; }}", + css_quote(&FontSettings::family_of(&s.code_font)), + FontSettings::size_of(&s.code_font) + ), + ); + view.style_context() + .add_provider(&provider, gtk::STYLE_PROVIDER_PRIORITY_USER); + // Style context holds its own reference; the Rust wrapper drops here. +} + +/// Pango description of the font a widget is currently showing +/// ("" if it cannot be determined). Test helper. +pub fn preferences_applied_font(widget: >k::Widget) -> String { + let ctx = widget.pango_context(); + match ctx.font_description() { + Some(d) => d.to_string(), + None => String::new(), + } +} + +/// Open the Preferences dialog; on Accept saves the choice, applies it +/// live, and returns true. On Cancel returns false. +pub fn preferences_open(parent: Option<>k::Window>) -> bool { + const RESET_RESPONSE: gtk::ResponseType = gtk::ResponseType::Other(100); + let mut s = preferences_current(); + let dlg = gtk::Dialog::with_buttons( + Some("Preferences"), + parent, + gtk::DialogFlags::MODAL, + &[ + ("_Cancel", gtk::ResponseType::Cancel), + ("_Apply", gtk::ResponseType::Accept), + ], + ); + dlg.add_button("_Reset to Defaults", RESET_RESPONSE); + let content = dlg.content_area(); + let grid = gtk::Grid::new(); + grid.set_row_spacing(6); + grid.set_column_spacing(8); + grid.set_margin_top(10); + grid.set_margin_bottom(10); + grid.set_margin_start(10); + grid.set_margin_end(10); + content.add(&grid); + + let ui_btn = gtk::FontButton::with_font(&s.font); + ui_btn.set_use_font(true); + ui_btn.set_hexpand(true); + grid.attach(>k::Label::new(Some("Interface font:")), 0, 0, 1, 1); + grid.attach(&ui_btn, 1, 0, 1, 1); + + let code_btn = gtk::FontButton::with_font(&s.code_font); + code_btn.set_use_font(true); + code_btn.set_hexpand(true); + grid.attach(>k::Label::new(Some("Code / text-view font:")), 0, 1, 1, 1); + grid.attach(&code_btn, 1, 1, 1, 1); + + let note_text = format!( + "Fonts apply immediately to the designer interface and to\ncode / text views, and are saved to {}.", + FontSettings::default_path() + ); + let note = gtk::Label::new(Some(¬e_text)); + note.set_xalign(0.0); + grid.attach(¬e, 0, 2, 2, 1); + + dlg.show_all(); + let mut resp; + loop { + resp = dlg.run(); + if resp != RESET_RESPONSE { + break; + } + ui_btn.set_font("Sans 10"); + code_btn.set_font("Monospace 11"); + } + if resp == gtk::ResponseType::Accept { + let ui_font = ui_btn + .font() + .map(|f| f.as_str().to_owned()) + .unwrap_or_default(); + let code_font = code_btn + .font() + .map(|f| f.as_str().to_owned()) + .unwrap_or_default(); + let cur_font = s.font.clone(); + let cur_code = s.code_font.clone(); + s.font = FontSettings::sanitized(&ui_font, &cur_font); + s.code_font = FontSettings::sanitized(&code_font, &cur_code); + s.save(""); + { + let mut g = current_lock().lock().unwrap(); + g.settings = s.clone(); + g.loaded = true; + } + preferences_apply(&s); + dlg.close(); + return true; + } + dlg.close(); + false +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn defaults() { + let def = FontSettings::default(); + assert_eq!(def.font, "Sans 10"); + assert_eq!(def.code_font, "Monospace 11"); + } + + #[test] + fn save_load_roundtrip() { + let dir = std::env::temp_dir().join("lightgui_font_unit"); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("settings.conf"); + let fs = FontSettings { + font: "DejaVu Sans 14".to_string(), + code_font: "DejaVu Sans Mono 13".to_string(), + }; + assert!(fs.save(path.to_str().unwrap())); + let mut fs2 = FontSettings::default(); + assert!(fs2.load(path.to_str().unwrap())); + assert_eq!(fs2.font, "DejaVu Sans 14"); + assert_eq!(fs2.code_font, "DejaVu Sans Mono 13"); + // Missing file: load fails, defaults kept. + let mut fs3 = FontSettings::default(); + assert!(!fs3.load("/tmp/lightgui_font_no_such_unit.conf")); + assert_eq!(fs3.font, "Sans 10"); + // Garbage in the file does not break loading. + let g = dir.join("garbage.conf"); + std::fs::write(&g, "# comment\nnot-a-kv-line\nfont=\ncode_font=\n").unwrap(); + let mut fs4 = FontSettings::default(); + assert!(fs4.load(g.to_str().unwrap())); + assert_eq!(fs4.font, "Sans 10"); + assert_eq!(fs4.code_font, "Monospace 11"); + } + + #[test] + fn sanitize_rules() { + assert_eq!(FontSettings::sanitized("", "Sans 10"), "Sans 10"); + assert_eq!( + FontSettings::size_of(&FontSettings::sanitized("Sans 99", "Sans 10")), + 48 + ); + assert_eq!( + FontSettings::size_of(&FontSettings::sanitized("Sans 2", "Sans 10")), + 6 + ); + assert_eq!( + FontSettings::family_of(&FontSettings::sanitized("DejaVu Sans Mono 13", "Sans 10")), + "DejaVu Sans Mono" + ); + } + + #[test] + fn css_content() { + let fs = FontSettings { + font: "DejaVu Sans 14".to_string(), + code_font: "DejaVu Sans Mono 13".to_string(), + }; + assert!(fs.ui_css().contains("DejaVu Sans")); + assert!(fs.ui_css().contains("14pt")); + assert!(fs.code_css().contains("textview")); + assert!(fs.code_css().contains("DejaVu Sans Mono")); + assert!(fs.code_css().contains("13pt")); + } +} diff --git a/crates/lightgui-support/src/theme.rs b/crates/lightgui-support/src/theme.rs new file mode 100644 index 0000000..1fbf879 --- /dev/null +++ b/crates/lightgui-support/src/theme.rs @@ -0,0 +1,936 @@ +// 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 { + 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 = 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> = 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> = 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 { + let b = code.as_bytes(); + let n = b.len(); + let mut out: Vec = 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> = OnceLock::new(); + +fn current_lock() -> &'static Mutex { + 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: >k::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: >k::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: >k::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::("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: >k::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: >k::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; + +/// 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<>k::Window>, + on_apply: Option, +) -> bool { + use std::cell::RefCell; + use std::rc::Rc; + + struct PickerCtx { + edited: CodeTheme, + combo: gtk::ComboBoxText, + buttons: BTreeMap, + } + 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(¬e, 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 \n// hi\nint main() { const char* s = \"x\"; return 42; }\n"; + let spans = theme_tokenize(sample); + assert!(has_span( + &spans, + sample, + "preprocessor", + "#include " + )); + 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")); + } +} diff --git a/crates/lightgui-support/tests/cmake_tests.rs b/crates/lightgui-support/tests/cmake_tests.rs new file mode 100644 index 0000000..9baa439 --- /dev/null +++ b/crates/lightgui-support/tests/cmake_tests.rs @@ -0,0 +1,202 @@ +// CMake tests — Rust port of tests/cmake_probe.cpp, minus the parts +// that need the code generator (sections 1-2: generate_project lives +// in lightgui-gen, not this crate). Covers: CMakeLists.txt text, +// real configure+build of hand-written console and GTK projects, +// settings persistence, failure reporting, and dirs with spaces. +// Run with: cargo test -p lightgui-support --test cmake_tests +// (the GTK app runs are wrapped in their own `xvfb-run -a`, so no +// outer display is needed for those checks). + +use lightgui_support::cmake::{ + cmake_build_project, cmake_lists_text, cmake_project_exists, CMakeSettings, +}; +use std::path::{Path, PathBuf}; +use std::process::Command; + +fn base(name: &str) -> PathBuf { + let b = std::env::temp_dir().join(format!("lightgui_cmake_rust_{}", name)); + let _ = std::fs::remove_dir_all(&b); + std::fs::create_dir_all(&b).unwrap(); + b +} + +fn write_file(p: &PathBuf, content: &str) { + if let Some(parent) = p.parent() { + std::fs::create_dir_all(parent).unwrap(); + } + std::fs::write(p, content).unwrap(); +} + +fn read_file(p: &PathBuf) -> String { + std::fs::read_to_string(p).unwrap_or_default() +} + +fn run_status(cmd: &str) -> i32 { + // Runs via /bin/sh; returns the exit code (-1 on spawn failure). + match Command::new("sh").arg("-c").arg(cmd).status() { + Ok(s) => s.code().unwrap_or(-1), + Err(_) => -1, + } +} + +fn console_project(dir: &Path) { + write_file( + &dir.join("CMakeLists.txt"), + "cmake_minimum_required(VERSION 3.10)\nproject(console_demo CXX)\nadd_executable(app main.cpp)\n", + ); + write_file( + &dir.join("main.cpp"), + "#include \nint main() { std::printf(\"cmake-console-ok\\n\"); return 0; }\n", + ); +} + +#[test] +fn cmakelists_text() { + let sources = vec![ + "main.cpp".to_string(), + "MyWindow.cpp".to_string(), + "Button_001.cpp".to_string(), + "Label_001.cpp".to_string(), + "Entry_001.cpp".to_string(), + ]; + let cm = cmake_lists_text("MyWindow", &sources); + assert!(!cm.is_empty()); + assert!(cm.contains("cmake_minimum_required(VERSION 3.10)")); + assert!(cm.contains("project(MyWindow CXX)")); + assert!(cm.contains("find_package(PkgConfig REQUIRED)")); + assert!(cm.contains("pkg_check_modules(GTK3 REQUIRED gtk+-3.0)")); + assert!(cm.contains("add_executable(app")); + for s in &sources { + assert!(cm.contains(s.as_str()), "missing {}", s); + } + assert!(cm.contains("target_include_directories(app PRIVATE ${GTK3_INCLUDE_DIRS})")); + assert!(cm.contains("target_link_libraries(app PRIVATE ${GTK3_LIBRARIES})")); + assert!(cm.contains("CMAKE_CXX_STANDARD 17")); + // project detection follows the file, not the text. + let b = base("text"); + assert!(!cmake_project_exists(b.to_str().unwrap())); + write_file(&b.join("CMakeLists.txt"), &cm); + assert!(cmake_project_exists(b.to_str().unwrap())); +} + +#[test] +fn cmake_build_handwritten_console() { + let b = base("console"); + let dir = b.join("console"); + console_project(&dir); + let def = CMakeSettings::default(); + let cr = cmake_build_project(dir.to_str().unwrap(), &def); + assert!(cr.ok, "output:\n{}", cr.output); + assert!(cr.configured); + assert_eq!(cr.exe_path, format!("{}/build/app", dir.to_string_lossy())); + assert!(PathBuf::from(&cr.exe_path).is_file()); + let rc = run_status(&format!( + "'{}' > '{}' 2>&1", + cr.exe_path, + dir.join("run.log").to_string_lossy() + )); + assert_eq!(rc, 0); + assert_eq!(read_file(&dir.join("run.log")), "cmake-console-ok\n"); + // Rebuild is a no-op success (idempotent configure+build). + let br2 = cmake_build_project(dir.to_str().unwrap(), &def); + assert!(br2.ok, "output:\n{}", br2.output); +} + +#[test] +fn cmake_build_handwritten_gtk() { + let b = base("gtk"); + let dir = b.join("gtk"); + write_file( + &dir.join("CMakeLists.txt"), + "cmake_minimum_required(VERSION 3.10)\nproject(gtk_demo CXX)\nfind_package(PkgConfig REQUIRED)\npkg_check_modules(GTK3 REQUIRED gtk+-3.0)\nadd_executable(app main.cpp)\ntarget_include_directories(app PRIVATE ${GTK3_INCLUDE_DIRS})\ntarget_link_libraries(app PRIVATE ${GTK3_LIBRARIES})\n", + ); + write_file( + &dir.join("main.cpp"), + "#include \nint main(int argc, char** argv) {\n gtk_init(&argc, &argv);\n GtkWidget* w = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n gtk_widget_show_all(w);\n gtk_main();\n return 0;\n}\n", + ); + let def = CMakeSettings::default(); + let gr = cmake_build_project(dir.to_str().unwrap(), &def); + assert!(gr.ok, "output:\n{}", gr.output); + // The built GTK app runs (timeout kills it: exit 124). + let rc = run_status(&format!( + "timeout 3 xvfb-run -a '{}' > /dev/null 2>&1", + gr.exe_path + )); + assert_eq!(rc, 124, "expected timeout-kill 124, got {}", rc); +} + +#[test] +fn cmake_settings_roundtrip_and_custom_build_dir() { + let b = base("settings"); + let s = CMakeSettings { + cmake_path: "cmake".to_string(), + generator: "Unix Makefiles".to_string(), + build_type: "Debug".to_string(), + build_dir: "out".to_string(), + }; + let conf = b.join("cmake.conf"); + assert!(s.save(conf.to_str().unwrap())); + let mut s2 = CMakeSettings::default(); + assert!(s2.load(conf.to_str().unwrap())); + assert_eq!(s2.generator, "Unix Makefiles"); + assert_eq!(s2.build_type, "Debug"); + assert_eq!(s2.build_dir, "out"); + assert_eq!(s2.cmake_path, "cmake"); + // Custom build dir + build type are honoured by a real build. + let dir = b.join("console"); + console_project(&dir); + let dbg = cmake_build_project(dir.to_str().unwrap(), &s); + assert!(dbg.ok, "output:\n{}", dbg.output); + assert_eq!(dbg.build_dir, format!("{}/out", dir.to_string_lossy())); + assert!(dir.join("out/app").is_file()); + // Defaults load: unknown keys ignored, empty file loads as defaults. + let conf2 = b.join("cmake2.conf"); + write_file(&conf2, "# comment\nunknown_key=1\n"); + let mut s3 = CMakeSettings::default(); + assert!(s3.load(conf2.to_str().unwrap())); + assert_eq!(s3.build_type, "Release"); + assert_eq!(s3.build_dir, "build"); +} + +#[test] +fn cmake_failure_reporting() { + let b = base("failures"); + let def = CMakeSettings::default(); + // Missing CMakeLists.txt. + let nofile = cmake_build_project(b.to_str().unwrap(), &def); + assert!(!nofile.ok && !nofile.configured); + // Broken CMakeLists.txt. + let broken_dir = b.join("broken"); + write_file( + &broken_dir.join("CMakeLists.txt"), + "this is not valid cmake (\n", + ); + let bad = cmake_build_project(broken_dir.to_str().unwrap(), &def); + assert!(!bad.ok && !bad.configured, "output:\n{}", bad.output); + // Project whose sources fail to compile: configure ok, build fails. + let badsrc_dir = b.join("badsrc"); + write_file( + &badsrc_dir.join("CMakeLists.txt"), + "cmake_minimum_required(VERSION 3.10)\nproject(bad CXX)\nadd_executable(app main.cpp)\n", + ); + write_file(&badsrc_dir.join("main.cpp"), "int main( { syntax error\n"); + let badsrc = cmake_build_project(badsrc_dir.to_str().unwrap(), &def); + assert!( + !badsrc.ok && badsrc.configured, + "output:\n{}", + badsrc.output + ); +} + +#[test] +fn cmake_dir_with_space_builds() { + let b = base("spaced"); + let spaced = b.join("dir with space"); + write_file( + &spaced.join("CMakeLists.txt"), + "cmake_minimum_required(VERSION 3.10)\nproject(spaced CXX)\nadd_executable(app main.cpp)\n", + ); + write_file(&spaced.join("main.cpp"), "int main() { return 0; }\n"); + let sp = cmake_build_project(spaced.to_str().unwrap(), &CMakeSettings::default()); + assert!(sp.ok, "output:\n{}", sp.output); +} diff --git a/crates/lightgui-support/tests/font_tests.rs b/crates/lightgui-support/tests/font_tests.rs new file mode 100644 index 0000000..425e283 --- /dev/null +++ b/crates/lightgui-support/tests/font_tests.rs @@ -0,0 +1,180 @@ +// Font settings tests — Rust port of tests/font_tests.cpp. +// Run under Xvfb: +// xvfb-run -a cargo test -p lightgui-support --test font_tests +// The whole suite runs as one #[test] because preferences_current() +// and the screen-wide providers are process-wide globals, exactly +// like the C++ harness's single main(). + +use gtk::prelude::*; +use lightgui_support::preferences::{ + preferences_applied_font, preferences_apply, preferences_apply_to_text_view, FontSettings, +}; + +struct Checker { + pass: usize, + fail: usize, + failed: Vec, +} + +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!("FONT TESTS: {} pass, {} fail", self.pass, self.fail); + if !self.failed.is_empty() { + panic!("FAILED: {}", self.failed.join(" ")); + } + } +} + +#[test] +fn font_suite() { + gtk::init().expect("gtk::init"); + let mut ck = Checker { + pass: 0, + fail: 0, + failed: Vec::new(), + }; + + // 1. Defaults. + let def = FontSettings::default(); + ck.check(def.font == "Sans 10", "defaults-ui-font"); + ck.check(def.code_font == "Monospace 11", "defaults-code-font"); + + // 2. Save / load round-trip at an explicit path. + let fs = FontSettings { + font: "DejaVu Sans 14".to_string(), + code_font: "DejaVu Sans Mono 13".to_string(), + }; + let path = "/tmp/lightgui_font_harness_rust.conf"; + ck.check(fs.save(path), "save-roundtrip"); + let mut fs2 = FontSettings::default(); + ck.check(fs2.load(path), "load-roundtrip"); + ck.check( + fs2.font == "DejaVu Sans 14" && fs2.code_font == "DejaVu Sans Mono 13", + "roundtrip-values", + ); + + // 3. Missing file: load fails, defaults kept. + let mut fs3 = FontSettings::default(); + ck.check( + !fs3.load("/tmp/lightgui_font_no_such_file_rust.conf"), + "load-missing-fails", + ); + ck.check(fs3.font == "Sans 10", "load-missing-keeps-defaults"); + + // 4. Garbage in the file does not break loading. + std::fs::write( + "/tmp/lightgui_font_garbage_rust.conf", + "# comment\nnot-a-kv-line\nfont=\ncode_font=\n", + ) + .unwrap(); + let mut fs4 = FontSettings::default(); + ck.check( + fs4.load("/tmp/lightgui_font_garbage_rust.conf"), + "load-garbage-file", + ); + ck.check( + fs4.font == "Sans 10" && fs4.code_font == "Monospace 11", + "garbage-falls-back-to-defaults", + ); + + // 5. Sanitising: empty -> fallback, sizes clamped to 6-48 pt. + ck.check( + FontSettings::sanitized("", "Sans 10") == "Sans 10", + "sanitize-empty", + ); + ck.check( + FontSettings::size_of(&FontSettings::sanitized("Sans 99", "Sans 10")) == 48, + "sanitize-clamp-high", + ); + ck.check( + FontSettings::size_of(&FontSettings::sanitized("Sans 2", "Sans 10")) == 6, + "sanitize-clamp-low", + ); + ck.check( + FontSettings::family_of(&FontSettings::sanitized("DejaVu Sans Mono 13", "Sans 10")) + == "DejaVu Sans Mono", + "sanitize-keeps-family", + ); + + // 6. Env override for the default path (mirrors debugger.conf). + std::env::set_var("LIGHTGUI_SETTINGS_CONF", "/tmp/lightgui_font_env_rust.conf"); + ck.check( + FontSettings::default_path() == "/tmp/lightgui_font_env_rust.conf", + "env-override-path", + ); + std::env::remove_var("LIGHTGUI_SETTINGS_CONF"); + + // 7. CSS generation. + ck.check( + fs.ui_css().contains("DejaVu Sans") && fs.ui_css().contains("14pt"), + "ui-css-content", + ); + ck.check( + fs.code_css().contains("textview") + && fs.code_css().contains("DejaVu Sans Mono") + && fs.code_css().contains("13pt"), + "code-css-content", + ); + + // 8. Live apply to a text view: the widget really shows the font. + let tv = gtk::TextView::new(); + tv.show(); + preferences_apply_to_text_view(tv.upcast_ref(), &fs); + while gtk::events_pending() { + gtk::main_iteration(); + } + let applied = preferences_applied_font(tv.upcast_ref()); + ck.check( + FontSettings::family_of(&applied) == "DejaVu Sans Mono" + && FontSettings::size_of(&applied) == 13, + "apply-to-text-view", + ); + + // 9. Screen-wide apply: a fresh text view and a label pick it up. + preferences_apply(&fs); + let tv2 = gtk::TextView::new(); + let lbl = gtk::Label::new(Some("probe")); + tv2.show(); + lbl.show(); + while gtk::events_pending() { + gtk::main_iteration(); + } + let applied2 = preferences_applied_font(tv2.upcast_ref()); + ck.check( + FontSettings::family_of(&applied2) == "DejaVu Sans Mono" + && FontSettings::size_of(&applied2) == 13, + "screen-apply-text-view", + ); + let applied_lbl = preferences_applied_font(lbl.upcast_ref()); + ck.check( + FontSettings::family_of(&applied_lbl) == "DejaVu Sans" + && FontSettings::size_of(&applied_lbl) == 14, + "screen-apply-label", + ); + + // 10. Re-applying defaults restores the defaults (no crash, no leak + // of the old providers). + preferences_apply(&FontSettings::default()); + let tv3 = gtk::TextView::new(); + tv3.show(); + while gtk::events_pending() { + gtk::main_iteration(); + } + let applied3 = preferences_applied_font(tv3.upcast_ref()); + ck.check( + FontSettings::family_of(&applied3) == "Monospace" && FontSettings::size_of(&applied3) == 11, + "reapply-defaults", + ); + + ck.finish(); +} diff --git a/crates/lightgui-support/tests/theme_tests.rs b/crates/lightgui-support/tests/theme_tests.rs new file mode 100644 index 0000000..8f17baa --- /dev/null +++ b/crates/lightgui-support/tests/theme_tests.rs @@ -0,0 +1,396 @@ +// 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, +} + +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 { + 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 \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 "), + "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 ®s { + 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::(), + ); + } + } + 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(); +}