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.
This commit is contained in:
1 parent
5bafafa8b0
commit
3d53281388
23 files changed
+7481
-5
No files matched your search
@@ -1,2 +1,5 @@
|
|||||||
__pycache__/
|
__pycache__/
|
||||||
*.pyc
|
*.pyc
|
||||||
|
/target
|
||||||
|
/test-results
|
||||||
|
/screenshots
|
||||||
Generated
+166
-3
@@ -2,6 +2,35 @@
|
|||||||
# It is not intended for manual editing.
|
# It is not intended for manual editing.
|
||||||
version = 4
|
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]]
|
[[package]]
|
||||||
name = "bitflags"
|
name = "bitflags"
|
||||||
version = "2.13.2"
|
version = "2.13.2"
|
||||||
@@ -59,6 +88,16 @@ dependencies = [
|
|||||||
"windows-sys",
|
"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]]
|
[[package]]
|
||||||
name = "futures-channel"
|
name = "futures-channel"
|
||||||
version = "0.3.34"
|
version = "0.3.34"
|
||||||
@@ -251,7 +290,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc"
|
checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"heck 0.4.1",
|
"heck 0.4.1",
|
||||||
"proc-macro-crate",
|
"proc-macro-crate 2.0.2",
|
||||||
"proc-macro-error",
|
"proc-macro-error",
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
@@ -279,6 +318,58 @@ dependencies = [
|
|||||||
"system-deps",
|
"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]]
|
[[package]]
|
||||||
name = "hashbrown"
|
name = "hashbrown"
|
||||||
version = "0.17.2"
|
version = "0.17.2"
|
||||||
@@ -334,6 +425,21 @@ dependencies = [
|
|||||||
"libc",
|
"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]]
|
[[package]]
|
||||||
name = "lightgui-gen"
|
name = "lightgui-gen"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
@@ -341,6 +447,18 @@ dependencies = [
|
|||||||
"lightgui-core",
|
"lightgui-core",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "lightgui-support"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"cairo-rs",
|
||||||
|
"gdk",
|
||||||
|
"glib",
|
||||||
|
"gtk",
|
||||||
|
"lightgui-debug",
|
||||||
|
"pango",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "linux-raw-sys"
|
name = "linux-raw-sys"
|
||||||
version = "0.12.1"
|
version = "0.12.1"
|
||||||
@@ -353,6 +471,15 @@ version = "2.8.3"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "memoffset"
|
||||||
|
version = "0.9.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
|
||||||
|
dependencies = [
|
||||||
|
"autocfg",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "once_cell"
|
name = "once_cell"
|
||||||
version = "1.21.4"
|
version = "1.21.4"
|
||||||
@@ -396,6 +523,16 @@ version = "0.3.34"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
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]]
|
[[package]]
|
||||||
name = "proc-macro-crate"
|
name = "proc-macro-crate"
|
||||||
version = "2.0.2"
|
version = "2.0.2"
|
||||||
@@ -403,7 +540,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24"
|
checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"toml_datetime",
|
"toml_datetime",
|
||||||
"toml_edit",
|
"toml_edit 0.20.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -448,6 +585,15 @@ dependencies = [
|
|||||||
"proc-macro2",
|
"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]]
|
[[package]]
|
||||||
name = "rustix"
|
name = "rustix"
|
||||||
version = "1.1.6"
|
version = "1.1.6"
|
||||||
@@ -461,6 +607,12 @@ dependencies = [
|
|||||||
"windows-sys",
|
"windows-sys",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "semver"
|
||||||
|
version = "1.0.28"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde"
|
name = "serde"
|
||||||
version = "1.0.229"
|
version = "1.0.229"
|
||||||
@@ -605,7 +757,7 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
"serde_spanned",
|
"serde_spanned",
|
||||||
"toml_datetime",
|
"toml_datetime",
|
||||||
"toml_edit",
|
"toml_edit 0.20.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -617,6 +769,17 @@ dependencies = [
|
|||||||
"serde",
|
"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]]
|
[[package]]
|
||||||
name = "toml_edit"
|
name = "toml_edit"
|
||||||
version = "0.20.2"
|
version = "0.20.2"
|
||||||
|
|||||||
+2
-2
@@ -3,6 +3,7 @@ resolver = "2"
|
|||||||
members = [
|
members = [
|
||||||
"crates/lightgui-core",
|
"crates/lightgui-core",
|
||||||
"crates/lightgui-gen",
|
"crates/lightgui-gen",
|
||||||
|
"crates/lightgui-designer",
|
||||||
"crates/lightgui-debug",
|
"crates/lightgui-debug",
|
||||||
"crates/xframe-common",
|
"crates/xframe-common",
|
||||||
"crates/xframe-demo",
|
"crates/xframe-demo",
|
||||||
@@ -12,7 +13,7 @@ members = [
|
|||||||
"crates/xframe-core",
|
"crates/xframe-core",
|
||||||
"crates/xframe-indicators",
|
"crates/xframe-indicators",
|
||||||
"crates/xframe-widgets",
|
"crates/xframe-widgets",
|
||||||
# TEMP-xframe-apps: "crates/lightgui-support", # no targets yet, restore before commit
|
"crates/lightgui-support",
|
||||||
]
|
]
|
||||||
exclude = ["probe"]
|
exclude = ["probe"]
|
||||||
|
|
||||||
@@ -23,7 +24,6 @@ glib = "0.18"
|
|||||||
pango = "0.18"
|
pango = "0.18"
|
||||||
cairo-rs = "0.18"
|
cairo-rs = "0.18"
|
||||||
libc = "0.2"
|
libc = "0.2"
|
||||||
serde = { version = "1.0", features = ["derive"] }
|
|
||||||
serde_json = "1.0"
|
serde_json = "1.0"
|
||||||
|
|
||||||
[profile.dev]
|
[profile.dev]
|
||||||
|
|||||||
@@ -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]
|
||||||
@@ -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,
|
||||||
|
};
|
||||||
@@ -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<String, MiValue>,
|
||||||
|
pub list: Vec<MiValue>,
|
||||||
|
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<MiValue> {
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -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::<i64>() {
|
||||||
|
self.stop_timeout_ms = n;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"cmd_timeout_ms" => {
|
||||||
|
if let Ok(n) = v.parse::<i64>() {
|
||||||
|
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<BpKind> {
|
||||||
|
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<String>) -> bool {
|
||||||
|
fmt.clear();
|
||||||
|
args.clear();
|
||||||
|
let chars: Vec<char> = 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<char> = 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<String> {
|
||||||
|
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<int>",
|
||||||
|
&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");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<Targets> = 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> = 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(|| "<missing>".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()))
|
||||||
|
}
|
||||||
@@ -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());
|
||||||
|
}
|
||||||
@@ -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"));
|
||||||
|
}
|
||||||
@@ -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 <cstdio>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
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<int> 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;
|
||||||
|
}
|
||||||
@@ -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 <gtk/gtk.h>
|
||||||
|
#include <cstdio>
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -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 <cstdio>
|
||||||
|
int main() {
|
||||||
|
volatile long n = 0;
|
||||||
|
std::printf("SPINNING\n");
|
||||||
|
std::fflush(stdout);
|
||||||
|
while (1) {
|
||||||
|
n++;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
@@ -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" }
|
||||||
@@ -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 <name>, GTK 3
|
||||||
|
/// via PkgConfig, C++17, and add_executable(app <sources>). `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 <dir>/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,
|
||||||
|
/// <build_dir>/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 <dir>/<build_dir>/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);
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -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,
|
||||||
|
};
|
||||||
@@ -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<Mutex<CurrentFonts>> = OnceLock::new();
|
||||||
|
|
||||||
|
fn current_lock() -> &'static Mutex<CurrentFonts> {
|
||||||
|
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<ScreenProviders> = 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"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<String> {
|
||||||
|
vec![
|
||||||
|
"Light".to_string(),
|
||||||
|
"Dark".to_string(),
|
||||||
|
"Monokai".to_string(),
|
||||||
|
"Solarized Dark".to_string(),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn builtin(name: &str) -> CodeTheme {
|
||||||
|
match name {
|
||||||
|
"Dark" => CodeTheme {
|
||||||
|
name: "Dark".to_string(),
|
||||||
|
background: "#1e1e1e".to_string(),
|
||||||
|
foreground: "#d4d4d4".to_string(),
|
||||||
|
keyword: "#569cd6".to_string(),
|
||||||
|
typ: "#4ec9b0".to_string(),
|
||||||
|
string: "#ce9178".to_string(),
|
||||||
|
comment: "#6a9955".to_string(),
|
||||||
|
number: "#b5cea8".to_string(),
|
||||||
|
preprocessor: "#c586c0".to_string(),
|
||||||
|
current_line: "#2a2d2e".to_string(),
|
||||||
|
},
|
||||||
|
"Monokai" => CodeTheme {
|
||||||
|
name: "Monokai".to_string(),
|
||||||
|
background: "#272822".to_string(),
|
||||||
|
foreground: "#f8f8f2".to_string(),
|
||||||
|
keyword: "#f92672".to_string(),
|
||||||
|
typ: "#66d9ef".to_string(),
|
||||||
|
string: "#e6db74".to_string(),
|
||||||
|
comment: "#75715e".to_string(),
|
||||||
|
number: "#ae81ff".to_string(),
|
||||||
|
preprocessor: "#fd971f".to_string(),
|
||||||
|
current_line: "#3e3d32".to_string(),
|
||||||
|
},
|
||||||
|
"Solarized Dark" => CodeTheme {
|
||||||
|
name: "Solarized Dark".to_string(),
|
||||||
|
background: "#002b36".to_string(),
|
||||||
|
foreground: "#839496".to_string(),
|
||||||
|
keyword: "#859900".to_string(),
|
||||||
|
typ: "#2aa198".to_string(),
|
||||||
|
string: "#b58900".to_string(),
|
||||||
|
comment: "#586e75".to_string(),
|
||||||
|
number: "#d33682".to_string(),
|
||||||
|
preprocessor: "#cb4b16".to_string(),
|
||||||
|
current_line: "#073642".to_string(),
|
||||||
|
},
|
||||||
|
_ => CodeTheme::default(), // Light, incl. unknown names
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_builtin(name: &str) -> bool {
|
||||||
|
Self::builtin_names().iter().any(|n| n == name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Strict "#rrggbb" (case-insensitive hex).
|
||||||
|
pub fn valid_color(s: &str) -> bool {
|
||||||
|
let b = s.as_bytes();
|
||||||
|
if b.len() != 7 || b[0] != b'#' {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
b[1..].iter().all(|c| c.is_ascii_hexdigit())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn default_path() -> String {
|
||||||
|
match std::env::var("LIGHTGUI_THEME_CONF") {
|
||||||
|
Ok(e) if !e.is_empty() => e,
|
||||||
|
_ => format!("{}/.config/lightgui/theme.conf", home_dir()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save(&self, path: &str) -> bool {
|
||||||
|
let p = if path.is_empty() {
|
||||||
|
Self::default_path()
|
||||||
|
} else {
|
||||||
|
path.to_string()
|
||||||
|
};
|
||||||
|
ensure_parent_dir(&p);
|
||||||
|
let mut f = match std::fs::File::create(&p) {
|
||||||
|
Ok(f) => f,
|
||||||
|
Err(_) => return false,
|
||||||
|
};
|
||||||
|
let body = format!(
|
||||||
|
"theme={}\nbackground={}\nforeground={}\nkeyword={}\ntype={}\nstring={}\ncomment={}\nnumber={}\npreprocessor={}\ncurrent_line={}\n",
|
||||||
|
self.name,
|
||||||
|
self.background,
|
||||||
|
self.foreground,
|
||||||
|
self.keyword,
|
||||||
|
self.typ,
|
||||||
|
self.string,
|
||||||
|
self.comment,
|
||||||
|
self.number,
|
||||||
|
self.preprocessor,
|
||||||
|
self.current_line,
|
||||||
|
);
|
||||||
|
f.write_all(body.as_bytes()).is_ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load(&mut self, path: &str) -> bool {
|
||||||
|
let p = if path.is_empty() {
|
||||||
|
Self::default_path()
|
||||||
|
} else {
|
||||||
|
path.to_string()
|
||||||
|
};
|
||||||
|
let text = match std::fs::read_to_string(&p) {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(_) => return false,
|
||||||
|
};
|
||||||
|
let mut kv: BTreeMap<String, String> = BTreeMap::new();
|
||||||
|
for line in text.lines() {
|
||||||
|
let t = trim_s(line);
|
||||||
|
if t.is_empty() || t.starts_with('#') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(eq) = t.find('=') {
|
||||||
|
kv.insert(
|
||||||
|
trim_s(&t[..eq]).to_string(),
|
||||||
|
trim_s(&t[eq + 1..]).to_string(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let nm = kv
|
||||||
|
.get("theme")
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_else(|| "Light".to_string());
|
||||||
|
let mut base = if nm == "Custom" {
|
||||||
|
Self::builtin("Dark")
|
||||||
|
} else {
|
||||||
|
Self::builtin(&nm)
|
||||||
|
};
|
||||||
|
base.name = nm; // keep the stored name, even if customised
|
||||||
|
let take = |key: &str, field: &mut String| {
|
||||||
|
if let Some(v) = kv.get(key) {
|
||||||
|
if Self::valid_color(v) {
|
||||||
|
*field = v.clone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
take("background", &mut base.background);
|
||||||
|
take("foreground", &mut base.foreground);
|
||||||
|
take("keyword", &mut base.keyword);
|
||||||
|
take("type", &mut base.typ);
|
||||||
|
take("string", &mut base.string);
|
||||||
|
take("comment", &mut base.comment);
|
||||||
|
take("number", &mut base.number);
|
||||||
|
take("preprocessor", &mut base.preprocessor);
|
||||||
|
take("current_line", &mut base.current_line);
|
||||||
|
*self = base;
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// CSS for the view (sets both "textview" and "textview text": the
|
||||||
|
/// text area background lives on the "text" subnode).
|
||||||
|
pub fn css(&self) -> String {
|
||||||
|
format!(
|
||||||
|
"textview text {{ background-color: {}; color: {}; }} textview {{ background-color: {}; color: {}; }}",
|
||||||
|
self.background, self.foreground, self.background, self.foreground
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn type_words() -> &'static HashSet<&'static str> {
|
||||||
|
use std::sync::OnceLock;
|
||||||
|
static T: OnceLock<HashSet<&'static str>> = OnceLock::new();
|
||||||
|
T.get_or_init(|| {
|
||||||
|
[
|
||||||
|
"bool",
|
||||||
|
"char",
|
||||||
|
"char8_t",
|
||||||
|
"char16_t",
|
||||||
|
"char32_t",
|
||||||
|
"double",
|
||||||
|
"float",
|
||||||
|
"int",
|
||||||
|
"long",
|
||||||
|
"short",
|
||||||
|
"signed",
|
||||||
|
"unsigned",
|
||||||
|
"void",
|
||||||
|
"wchar_t",
|
||||||
|
"size_t",
|
||||||
|
"ssize_t",
|
||||||
|
"string",
|
||||||
|
"vector",
|
||||||
|
"map",
|
||||||
|
"set",
|
||||||
|
"list",
|
||||||
|
"array",
|
||||||
|
"pair",
|
||||||
|
"tuple",
|
||||||
|
"optional",
|
||||||
|
"uint8_t",
|
||||||
|
"uint16_t",
|
||||||
|
"uint32_t",
|
||||||
|
"uint64_t",
|
||||||
|
"int8_t",
|
||||||
|
"int16_t",
|
||||||
|
"int32_t",
|
||||||
|
"int64_t",
|
||||||
|
"nullptr_t",
|
||||||
|
"GtkWidget",
|
||||||
|
"GtkTextBuffer",
|
||||||
|
"GtkTextIter",
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keyword_words() -> &'static HashSet<&'static str> {
|
||||||
|
use std::sync::OnceLock;
|
||||||
|
static K: OnceLock<HashSet<&'static str>> = OnceLock::new();
|
||||||
|
K.get_or_init(|| {
|
||||||
|
[
|
||||||
|
"alignas",
|
||||||
|
"alignof",
|
||||||
|
"and",
|
||||||
|
"and_eq",
|
||||||
|
"asm",
|
||||||
|
"auto",
|
||||||
|
"break",
|
||||||
|
"case",
|
||||||
|
"catch",
|
||||||
|
"class",
|
||||||
|
"concept",
|
||||||
|
"const",
|
||||||
|
"consteval",
|
||||||
|
"constexpr",
|
||||||
|
"constinit",
|
||||||
|
"continue",
|
||||||
|
"decltype",
|
||||||
|
"default",
|
||||||
|
"delete",
|
||||||
|
"do",
|
||||||
|
"else",
|
||||||
|
"enum",
|
||||||
|
"explicit",
|
||||||
|
"export",
|
||||||
|
"extern",
|
||||||
|
"false",
|
||||||
|
"for",
|
||||||
|
"friend",
|
||||||
|
"goto",
|
||||||
|
"if",
|
||||||
|
"inline",
|
||||||
|
"mutable",
|
||||||
|
"namespace",
|
||||||
|
"new",
|
||||||
|
"noexcept",
|
||||||
|
"not",
|
||||||
|
"not_eq",
|
||||||
|
"operator",
|
||||||
|
"or",
|
||||||
|
"or_eq",
|
||||||
|
"private",
|
||||||
|
"protected",
|
||||||
|
"public",
|
||||||
|
"register",
|
||||||
|
"reinterpret_cast",
|
||||||
|
"requires",
|
||||||
|
"return",
|
||||||
|
"sizeof",
|
||||||
|
"static",
|
||||||
|
"static_assert",
|
||||||
|
"static_cast",
|
||||||
|
"struct",
|
||||||
|
"switch",
|
||||||
|
"template",
|
||||||
|
"this",
|
||||||
|
"thread_local",
|
||||||
|
"throw",
|
||||||
|
"true",
|
||||||
|
"try",
|
||||||
|
"typedef",
|
||||||
|
"typeid",
|
||||||
|
"typename",
|
||||||
|
"union",
|
||||||
|
"using",
|
||||||
|
"virtual",
|
||||||
|
"volatile",
|
||||||
|
"while",
|
||||||
|
"xor",
|
||||||
|
"xor_eq",
|
||||||
|
"override",
|
||||||
|
"final",
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ident_start(c: u8) -> bool {
|
||||||
|
c.is_ascii_alphabetic() || c == b'_'
|
||||||
|
}
|
||||||
|
fn ident_char(c: u8) -> bool {
|
||||||
|
c.is_ascii_alphanumeric() || c == b'_'
|
||||||
|
}
|
||||||
|
fn is_digit(c: u8) -> bool {
|
||||||
|
c.is_ascii_digit()
|
||||||
|
}
|
||||||
|
fn is_hex(c: u8) -> bool {
|
||||||
|
c.is_ascii_hexdigit()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One highlighted span of C++ source: [start, end) byte offsets, kind
|
||||||
|
/// is one of "keyword", "type", "string", "comment", "number",
|
||||||
|
/// "preprocessor". Pure function of the text (no GTK).
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct HlSpan {
|
||||||
|
pub start: usize,
|
||||||
|
pub end: usize,
|
||||||
|
pub kind: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn theme_tokenize(code: &str) -> Vec<HlSpan> {
|
||||||
|
let b = code.as_bytes();
|
||||||
|
let n = b.len();
|
||||||
|
let mut out: Vec<HlSpan> = Vec::new();
|
||||||
|
let mut i = 0usize;
|
||||||
|
let mut line_start = true; // only whitespace seen so far on this line
|
||||||
|
while i < n {
|
||||||
|
let c = b[i];
|
||||||
|
if c == b'\n' {
|
||||||
|
line_start = true;
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if line_start && (c == b' ' || c == b'\t' || c == b'\r') {
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if line_start && c == b'#' {
|
||||||
|
let s = i;
|
||||||
|
while i < n && b[i] != b'\n' {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
out.push(HlSpan {
|
||||||
|
start: s,
|
||||||
|
end: i,
|
||||||
|
kind: "preprocessor",
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
line_start = false;
|
||||||
|
if c == b'/' && i + 1 < n && b[i + 1] == b'/' {
|
||||||
|
let s = i;
|
||||||
|
while i < n && b[i] != b'\n' {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
out.push(HlSpan {
|
||||||
|
start: s,
|
||||||
|
end: i,
|
||||||
|
kind: "comment",
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if c == b'/' && i + 1 < n && b[i + 1] == b'*' {
|
||||||
|
let s = i;
|
||||||
|
i += 2;
|
||||||
|
while i + 1 < n && !(b[i] == b'*' && b[i + 1] == b'/') {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
if i + 1 < n {
|
||||||
|
i += 2;
|
||||||
|
} else {
|
||||||
|
i = n;
|
||||||
|
}
|
||||||
|
out.push(HlSpan {
|
||||||
|
start: s,
|
||||||
|
end: i,
|
||||||
|
kind: "comment",
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if c == b'"' {
|
||||||
|
let s = i;
|
||||||
|
i += 1;
|
||||||
|
while i < n && b[i] != b'"' && b[i] != b'\n' {
|
||||||
|
if b[i] == b'\\' && i + 1 < n {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
if i < n && b[i] == b'"' {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
out.push(HlSpan {
|
||||||
|
start: s,
|
||||||
|
end: i,
|
||||||
|
kind: "string",
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if c == b'\'' {
|
||||||
|
// A ' between identifier/digit chars is a C++14 digit
|
||||||
|
// separator (1'000), not a character literal.
|
||||||
|
let sep = i > 0 && ident_char(b[i - 1]);
|
||||||
|
if !sep {
|
||||||
|
let s = i;
|
||||||
|
i += 1;
|
||||||
|
while i < n && b[i] != b'\'' && b[i] != b'\n' {
|
||||||
|
if b[i] == b'\\' && i + 1 < n {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
if i < n && b[i] == b'\'' {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
out.push(HlSpan {
|
||||||
|
start: s,
|
||||||
|
end: i,
|
||||||
|
kind: "string",
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if is_digit(c) || (c == b'.' && i + 1 < n && is_digit(b[i + 1])) {
|
||||||
|
let s = i;
|
||||||
|
if c == b'0' && i + 1 < n && (b[i + 1] == b'x' || b[i + 1] == b'X') {
|
||||||
|
i += 2;
|
||||||
|
while i < n && (is_hex(b[i]) || b[i] == b'\'') {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
while i < n
|
||||||
|
&& (is_digit(b[i])
|
||||||
|
|| b[i] == b'.'
|
||||||
|
|| b[i] == b'_'
|
||||||
|
|| b[i] == b'\''
|
||||||
|
|| b[i] == b'e'
|
||||||
|
|| b[i] == b'E'
|
||||||
|
|| ((b[i] == b'+' || b[i] == b'-')
|
||||||
|
&& i > s
|
||||||
|
&& (b[i - 1] == b'e' || b[i - 1] == b'E')))
|
||||||
|
{
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
while i < n && b[i].is_ascii_alphabetic() {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push(HlSpan {
|
||||||
|
start: s,
|
||||||
|
end: i,
|
||||||
|
kind: "number",
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ident_start(c) {
|
||||||
|
let s = i;
|
||||||
|
while i < n && ident_char(b[i]) {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
let w = &code[s..i];
|
||||||
|
if type_words().contains(w) {
|
||||||
|
out.push(HlSpan {
|
||||||
|
start: s,
|
||||||
|
end: i,
|
||||||
|
kind: "type",
|
||||||
|
});
|
||||||
|
} else if keyword_words().contains(w) {
|
||||||
|
out.push(HlSpan {
|
||||||
|
start: s,
|
||||||
|
end: i,
|
||||||
|
kind: "keyword",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ current theme
|
||||||
|
|
||||||
|
struct CurrentTheme {
|
||||||
|
theme: CodeTheme,
|
||||||
|
loaded: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
static CURRENT: OnceLock<Mutex<CurrentTheme>> = OnceLock::new();
|
||||||
|
|
||||||
|
fn current_lock() -> &'static Mutex<CurrentTheme> {
|
||||||
|
CURRENT.get_or_init(|| {
|
||||||
|
Mutex::new(CurrentTheme {
|
||||||
|
theme: CodeTheme::default(),
|
||||||
|
loaded: false,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Theme currently in effect (loaded from disk on first call).
|
||||||
|
pub fn theme_current() -> CodeTheme {
|
||||||
|
let mut g = current_lock().lock().unwrap();
|
||||||
|
if !g.loaded {
|
||||||
|
let mut t = CodeTheme::default();
|
||||||
|
t.load(""); // missing file: defaults stand
|
||||||
|
g.theme = t;
|
||||||
|
g.loaded = true;
|
||||||
|
}
|
||||||
|
g.theme.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Make `t` current and persist it.
|
||||||
|
pub fn theme_set_current(t: &CodeTheme) {
|
||||||
|
let mut g = current_lock().lock().unwrap();
|
||||||
|
g.theme = t.clone();
|
||||||
|
g.loaded = true;
|
||||||
|
g.theme.save("");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ GTK apply
|
||||||
|
|
||||||
|
fn ensure_tag(buf: >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::<gtk::CssProvider>("theme-css-provider") {
|
||||||
|
Some(ptr) => ptr.as_ref().clone(),
|
||||||
|
None => {
|
||||||
|
let p = gtk::CssProvider::new();
|
||||||
|
view.style_context()
|
||||||
|
.add_provider(&p, gtk::STYLE_PROVIDER_PRIORITY_USER);
|
||||||
|
view.set_data("theme-css-provider", p.clone());
|
||||||
|
p
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Err(e) = provider.load_from_data(theme.css().as_bytes()) {
|
||||||
|
eprintln!("lightgui: theme CSS failed: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ picker dialog
|
||||||
|
fn color_of_button(btn: >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<dyn Fn(&CodeTheme)>;
|
||||||
|
|
||||||
|
/// Open the theme picker dialog (theme combo + per-role colour buttons).
|
||||||
|
/// On Apply/OK the choice is saved, made current, and on_apply (if set)
|
||||||
|
/// is called so the caller can repaint open code views. Returns true on
|
||||||
|
/// Apply/OK, false on Cancel.
|
||||||
|
pub fn theme_picker_open(
|
||||||
|
parent: Option<>k::Window>,
|
||||||
|
on_apply: Option<ThemeApplyCallback>,
|
||||||
|
) -> bool {
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
|
struct PickerCtx {
|
||||||
|
edited: CodeTheme,
|
||||||
|
combo: gtk::ComboBoxText,
|
||||||
|
buttons: BTreeMap<String, gtk::ColorButton>,
|
||||||
|
}
|
||||||
|
let ctx = Rc::new(RefCell::new(PickerCtx {
|
||||||
|
edited: theme_current(),
|
||||||
|
combo: gtk::ComboBoxText::new(),
|
||||||
|
buttons: BTreeMap::new(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
let dlg = gtk::Dialog::with_buttons(
|
||||||
|
Some("Color Theme"),
|
||||||
|
parent,
|
||||||
|
gtk::DialogFlags::MODAL,
|
||||||
|
&[
|
||||||
|
("_Cancel", gtk::ResponseType::Cancel),
|
||||||
|
("_Apply", gtk::ResponseType::Apply),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
dlg.set_default_size(420, 480);
|
||||||
|
let content = dlg.content_area();
|
||||||
|
let grid = gtk::Grid::new();
|
||||||
|
grid.set_row_spacing(6);
|
||||||
|
grid.set_column_spacing(12);
|
||||||
|
grid.set_margin_top(12);
|
||||||
|
grid.set_margin_bottom(12);
|
||||||
|
grid.set_margin_start(12);
|
||||||
|
grid.set_margin_end(12);
|
||||||
|
content.add(&grid);
|
||||||
|
|
||||||
|
let name_lbl = gtk::Label::new(Some("Theme"));
|
||||||
|
name_lbl.set_halign(gtk::Align::Start);
|
||||||
|
grid.attach(&name_lbl, 0, 0, 1, 1);
|
||||||
|
{
|
||||||
|
let c = ctx.borrow();
|
||||||
|
for n in CodeTheme::builtin_names() {
|
||||||
|
c.combo.append_text(&n);
|
||||||
|
}
|
||||||
|
let active = CodeTheme::builtin_names()
|
||||||
|
.iter()
|
||||||
|
.position(|n| *n == c.edited.name)
|
||||||
|
.unwrap_or(0) as u32;
|
||||||
|
c.combo.set_active(Some(active));
|
||||||
|
grid.attach(&c.combo, 1, 0, 1, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
let roles: [(&str, &str); 9] = [
|
||||||
|
("background", "Background"),
|
||||||
|
("foreground", "Foreground"),
|
||||||
|
("keyword", "Keyword"),
|
||||||
|
("type", "Type"),
|
||||||
|
("string", "String"),
|
||||||
|
("comment", "Comment"),
|
||||||
|
("number", "Number"),
|
||||||
|
("preprocessor", "Preprocessor"),
|
||||||
|
("current_line", "Current line"),
|
||||||
|
];
|
||||||
|
for (row, (role, label)) in roles.iter().enumerate() {
|
||||||
|
let lbl = gtk::Label::new(Some(label));
|
||||||
|
lbl.set_halign(gtk::Align::Start);
|
||||||
|
grid.attach(&lbl, 0, (row + 1) as i32, 1, 1);
|
||||||
|
let btn = gtk::ColorButton::new();
|
||||||
|
btn.set_title(label);
|
||||||
|
{
|
||||||
|
let c = ctx.borrow();
|
||||||
|
let field: &str = match *role {
|
||||||
|
"background" => &c.edited.background,
|
||||||
|
"foreground" => &c.edited.foreground,
|
||||||
|
"keyword" => &c.edited.keyword,
|
||||||
|
"type" => &c.edited.typ,
|
||||||
|
"string" => &c.edited.string,
|
||||||
|
"comment" => &c.edited.comment,
|
||||||
|
"number" => &c.edited.number,
|
||||||
|
"preprocessor" => &c.edited.preprocessor,
|
||||||
|
_ => &c.edited.current_line,
|
||||||
|
};
|
||||||
|
set_button_color(&btn, field);
|
||||||
|
}
|
||||||
|
grid.attach(&btn, 1, (row + 1) as i32, 1, 1);
|
||||||
|
ctx.borrow_mut().buttons.insert(role.to_string(), btn);
|
||||||
|
}
|
||||||
|
let note = gtk::Label::new(Some(
|
||||||
|
"Pick a built-in theme, then tweak any colour.\nApply saves to ~/.config/lightgui/theme.conf.",
|
||||||
|
));
|
||||||
|
note.set_line_wrap(true);
|
||||||
|
note.set_halign(gtk::Align::Start);
|
||||||
|
grid.attach(¬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 <gtk/gtk.h>\n// hi\nint main() { const char* s = \"x\"; return 42; }\n";
|
||||||
|
let spans = theme_tokenize(sample);
|
||||||
|
assert!(has_span(
|
||||||
|
&spans,
|
||||||
|
sample,
|
||||||
|
"preprocessor",
|
||||||
|
"#include <gtk/gtk.h>"
|
||||||
|
));
|
||||||
|
assert!(has_span(&spans, sample, "comment", "// hi"));
|
||||||
|
assert!(has_span(&spans, sample, "type", "int"));
|
||||||
|
assert!(has_span(&spans, sample, "keyword", "return"));
|
||||||
|
assert!(has_span(&spans, sample, "string", "\"x\""));
|
||||||
|
assert!(has_span(&spans, sample, "number", "42"));
|
||||||
|
let sample2 =
|
||||||
|
"/* { not a fold */\nchar c = 'x';\nint n = 1'000;\nconst char* s = \"a{b\";\nfloat f = 1.5e-3;\n";
|
||||||
|
let spans2 = theme_tokenize(sample2);
|
||||||
|
assert!(has_span(&spans2, sample2, "comment", "/* { not a fold */"));
|
||||||
|
assert!(has_span(&spans2, sample2, "string", "'x'"));
|
||||||
|
assert!(has_span(&spans2, sample2, "number", "1'000"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 <cstdio>\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 <gtk/gtk.h>\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);
|
||||||
|
}
|
||||||
@@ -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<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Checker {
|
||||||
|
fn check(&mut self, cond: bool, name: &str) {
|
||||||
|
if cond {
|
||||||
|
self.pass += 1;
|
||||||
|
println!("PASS {}", name);
|
||||||
|
} else {
|
||||||
|
self.fail += 1;
|
||||||
|
self.failed.push(name.to_string());
|
||||||
|
println!("FAIL {}", name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn finish(&self) {
|
||||||
|
println!("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();
|
||||||
|
}
|
||||||
@@ -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<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Checker {
|
||||||
|
fn check(&mut self, cond: bool, name: &str) {
|
||||||
|
if cond {
|
||||||
|
self.pass += 1;
|
||||||
|
println!("PASS {}", name);
|
||||||
|
} else {
|
||||||
|
self.fail += 1;
|
||||||
|
self.failed.push(name.to_string());
|
||||||
|
println!("FAIL {}", name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn finish(&self) {
|
||||||
|
println!("THEME TESTS: {} pass, {} fail", self.pass, self.fail);
|
||||||
|
if !self.failed.is_empty() {
|
||||||
|
panic!("FAILED: {}", self.failed.join(" "));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn file_contains(path: &str, needle: &str) -> bool {
|
||||||
|
std::fs::read_to_string(path)
|
||||||
|
.map(|s| s.contains(needle))
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The fold sample used by both the pure-logic and widget checks.
|
||||||
|
fn fold_lines() -> Vec<String> {
|
||||||
|
vec![
|
||||||
|
"#region Outer".to_string(),
|
||||||
|
"class Foo {".to_string(),
|
||||||
|
" void bar() {".to_string(),
|
||||||
|
" if (x) {".to_string(),
|
||||||
|
" work();".to_string(),
|
||||||
|
" }".to_string(),
|
||||||
|
" /* multi".to_string(),
|
||||||
|
" line */".to_string(),
|
||||||
|
" }".to_string(),
|
||||||
|
"};".to_string(),
|
||||||
|
"#endregion".to_string(),
|
||||||
|
"#if DEBUG".to_string(),
|
||||||
|
"int d = 1;".to_string(),
|
||||||
|
"#endif".to_string(),
|
||||||
|
"}".to_string(),
|
||||||
|
"int leftover() {".to_string(),
|
||||||
|
" return 1;".to_string(),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn join_lines(lines: &[String]) -> String {
|
||||||
|
lines.iter().map(|l| format!("{}\n", l)).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn theme_suite() {
|
||||||
|
// Isolate all HOME-based config (theme file).
|
||||||
|
std::env::set_var("HOME", "/tmp/lightgui_theme_home_rust");
|
||||||
|
std::env::set_var("LIGHTGUI_THEME_CONF", "");
|
||||||
|
gtk::init().expect("gtk::init");
|
||||||
|
let mut ck = Checker {
|
||||||
|
pass: 0,
|
||||||
|
fail: 0,
|
||||||
|
failed: Vec::new(),
|
||||||
|
};
|
||||||
|
|
||||||
|
// 1. Built-in themes.
|
||||||
|
let names = CodeTheme::builtin_names();
|
||||||
|
ck.check(names.len() == 4, "builtins-count-4");
|
||||||
|
ck.check(
|
||||||
|
names[0] == "Light"
|
||||||
|
&& names[1] == "Dark"
|
||||||
|
&& names[2] == "Monokai"
|
||||||
|
&& names[3] == "Solarized Dark",
|
||||||
|
"builtins-names",
|
||||||
|
);
|
||||||
|
let light = CodeTheme::builtin("Light");
|
||||||
|
let dark = CodeTheme::builtin("Dark");
|
||||||
|
let mono = CodeTheme::builtin("Monokai");
|
||||||
|
let solar = CodeTheme::builtin("Solarized Dark");
|
||||||
|
ck.check(
|
||||||
|
light.keyword != dark.keyword
|
||||||
|
&& dark.keyword != mono.keyword
|
||||||
|
&& mono.keyword != solar.keyword,
|
||||||
|
"builtins-distinct-keywords",
|
||||||
|
);
|
||||||
|
ck.check(
|
||||||
|
light.background != dark.background && dark.background != mono.background,
|
||||||
|
"builtins-distinct-backgrounds",
|
||||||
|
);
|
||||||
|
ck.check(
|
||||||
|
CodeTheme::builtin("Nope").name == "Light",
|
||||||
|
"builtin-unknown-light",
|
||||||
|
);
|
||||||
|
ck.check(
|
||||||
|
CodeTheme::is_builtin("Dark") && !CodeTheme::is_builtin("Custom"),
|
||||||
|
"is-builtin",
|
||||||
|
);
|
||||||
|
|
||||||
|
// 2. Colour validation.
|
||||||
|
ck.check(
|
||||||
|
CodeTheme::valid_color("#1a2b3c")
|
||||||
|
&& CodeTheme::valid_color("#FFFFFF")
|
||||||
|
&& !CodeTheme::valid_color("red")
|
||||||
|
&& !CodeTheme::valid_color("#12345")
|
||||||
|
&& !CodeTheme::valid_color("#gggggg")
|
||||||
|
&& !CodeTheme::valid_color(""),
|
||||||
|
"valid-color",
|
||||||
|
);
|
||||||
|
|
||||||
|
// 3. Save / load round-trip at an explicit path, incl. custom colour.
|
||||||
|
let mut custom = dark.clone();
|
||||||
|
custom.keyword = "#ff0000".to_string();
|
||||||
|
let tpath = "/tmp/lightgui_theme_harness_rust.conf";
|
||||||
|
ck.check(custom.save(tpath), "save-roundtrip");
|
||||||
|
let mut reloaded = CodeTheme::default();
|
||||||
|
ck.check(reloaded.load(tpath), "load-roundtrip");
|
||||||
|
ck.check(
|
||||||
|
reloaded.name == "Dark"
|
||||||
|
&& reloaded.keyword == "#ff0000"
|
||||||
|
&& reloaded.background == dark.background,
|
||||||
|
"roundtrip-values",
|
||||||
|
);
|
||||||
|
// Missing file: load fails, defaults kept.
|
||||||
|
let mut miss = CodeTheme::default();
|
||||||
|
ck.check(
|
||||||
|
!miss.load("/tmp/lightgui_theme_no_such_rust.conf"),
|
||||||
|
"load-missing-fails",
|
||||||
|
);
|
||||||
|
ck.check(miss.name == "Light", "load-missing-keeps-defaults");
|
||||||
|
// Garbage in the file does not break loading; bad colours ignored.
|
||||||
|
std::fs::write(
|
||||||
|
"/tmp/lightgui_theme_garbage_rust.conf",
|
||||||
|
"# comment\nnot-a-kv-line\ntheme=Dark\nkeyword=red\nbackground=#1e1e1e\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let mut garb = CodeTheme::default();
|
||||||
|
ck.check(
|
||||||
|
garb.load("/tmp/lightgui_theme_garbage_rust.conf"),
|
||||||
|
"load-garbage-file",
|
||||||
|
);
|
||||||
|
ck.check(
|
||||||
|
garb.name == "Dark" && garb.keyword == dark.keyword && garb.background == "#1e1e1e",
|
||||||
|
"garbage-bad-colour-ignored",
|
||||||
|
);
|
||||||
|
|
||||||
|
// 4. Default-path persistence (HOME is redirected above).
|
||||||
|
let dp = CodeTheme::builtin("Monokai");
|
||||||
|
theme_set_current(&dp);
|
||||||
|
ck.check(
|
||||||
|
file_contains(
|
||||||
|
"/tmp/lightgui_theme_home_rust/.config/lightgui/theme.conf",
|
||||||
|
"theme=Monokai",
|
||||||
|
),
|
||||||
|
"default-path-persists",
|
||||||
|
);
|
||||||
|
let cur = theme_current();
|
||||||
|
ck.check(
|
||||||
|
cur.name == "Monokai" && cur.keyword == mono.keyword,
|
||||||
|
"theme-current-roundtrip",
|
||||||
|
);
|
||||||
|
|
||||||
|
// 5. Tokeniser spans.
|
||||||
|
let sample = "#include <gtk/gtk.h>\n// hi\nint main() { const char* s = \"x\"; return 42; }\n";
|
||||||
|
let spans = theme_tokenize(sample);
|
||||||
|
let has_span = |kind: &str, word: &str| {
|
||||||
|
spans
|
||||||
|
.iter()
|
||||||
|
.any(|sp| sp.kind == kind && &sample[sp.start..sp.end] == word)
|
||||||
|
};
|
||||||
|
ck.check(
|
||||||
|
has_span("preprocessor", "#include <gtk/gtk.h>"),
|
||||||
|
"token-preprocessor",
|
||||||
|
);
|
||||||
|
ck.check(has_span("comment", "// hi"), "token-line-comment");
|
||||||
|
ck.check(has_span("type", "int"), "token-type");
|
||||||
|
ck.check(has_span("keyword", "return"), "token-keyword");
|
||||||
|
ck.check(has_span("string", "\"x\""), "token-string");
|
||||||
|
ck.check(has_span("number", "42"), "token-number");
|
||||||
|
// Block comment, char literal, digit separator, string with brace.
|
||||||
|
let sample2 =
|
||||||
|
"/* { not a fold */\nchar c = 'x';\nint n = 1'000;\nconst char* s = \"a{b\";\nfloat f = 1.5e-3;\n";
|
||||||
|
let spans2 = theme_tokenize(sample2);
|
||||||
|
let (mut block_ok, mut char_ok, mut num_ok) = (false, false, false);
|
||||||
|
for sp in &spans2 {
|
||||||
|
let w = &sample2[sp.start..sp.end];
|
||||||
|
if sp.kind == "comment" && w == "/* { not a fold */" {
|
||||||
|
block_ok = true;
|
||||||
|
}
|
||||||
|
if sp.kind == "string" && w == "'x'" {
|
||||||
|
char_ok = true;
|
||||||
|
}
|
||||||
|
if sp.kind == "number" && w == "1'000" {
|
||||||
|
num_ok = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ck.check(block_ok, "token-block-comment");
|
||||||
|
ck.check(char_ok, "token-char-literal");
|
||||||
|
ck.check(num_ok, "token-digit-separator");
|
||||||
|
|
||||||
|
// 6. Fold regions: braces, region, comment, #if, nesting, unbalanced.
|
||||||
|
let flines = fold_lines();
|
||||||
|
let regs = codeview_find_regions(&flines);
|
||||||
|
ck.check(regs.len() == 6, "regions-count-6");
|
||||||
|
let has_region = |st: i32, en: i32, kind: &str| {
|
||||||
|
regs.iter()
|
||||||
|
.any(|r| r.start_line == st && r.end_line == en && r.kind == kind)
|
||||||
|
};
|
||||||
|
ck.check(has_region(0, 10, "region"), "region-outer");
|
||||||
|
ck.check(has_region(1, 9, "brace"), "brace-class");
|
||||||
|
ck.check(has_region(2, 8, "brace"), "brace-method");
|
||||||
|
ck.check(has_region(3, 5, "brace"), "brace-if");
|
||||||
|
ck.check(has_region(6, 7, "comment"), "region-comment");
|
||||||
|
ck.check(has_region(11, 13, "preproc"), "region-if");
|
||||||
|
let mut depth_of = [-1i32; 17];
|
||||||
|
for r in ®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::<std::ffi::c_void>(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let col = if col_ptr.is_null() {
|
||||||
|
gdk::Color {
|
||||||
|
pixel: 0,
|
||||||
|
red: 0,
|
||||||
|
green: 0,
|
||||||
|
blue: 0,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let c = unsafe { *col_ptr };
|
||||||
|
unsafe { gdk::ffi::gdk_color_free(col_ptr) };
|
||||||
|
c
|
||||||
|
};
|
||||||
|
ck.check(
|
||||||
|
kw.is_some() && col.red / 257 == 0x56 && col.green / 257 == 0x9c && col.blue / 257 == 0xd6,
|
||||||
|
"widget-theme-switch-changes-tag",
|
||||||
|
);
|
||||||
|
// Real collapse: fold bar() (lines 3..8, 1-based) and check the
|
||||||
|
// hidden buffer lines report zero height.
|
||||||
|
cv.toggle_fold_at(3);
|
||||||
|
while gtk::events_pending() {
|
||||||
|
gtk::main_iteration();
|
||||||
|
}
|
||||||
|
{
|
||||||
|
let tv = cv.text_view();
|
||||||
|
let it4 = cbuf.iter_at_line(3); // file line 4
|
||||||
|
let (_, h4) = tv.line_yrange(&it4);
|
||||||
|
let it7 = cbuf.iter_at_line(6); // file line 7
|
||||||
|
let (_, h7) = tv.line_yrange(&it7);
|
||||||
|
ck.check(h4 == 0 && h7 == 0, "widget-fold-collapses-lines");
|
||||||
|
}
|
||||||
|
win.close();
|
||||||
|
|
||||||
|
ck.finish();
|
||||||
|
}
|
||||||
Reference in new issue
Block a user