Files
ghostty-rs/crates/ghostty-config/src/metric_modifier.rs
T
ddidderr 79a7fd4f76 fix(config): match Zig's numeric grammar, NUL handling and diagnostics
Resolves the 6 differential gap groups in docs/rewrite/notes/review-
rv9-codex.md (details in final-Z11.md):
- ghostty_os::zig_fmt ports std.fmt.parseInt/parseUnsigned/parseFloat
  (underscores, 0x/0o/0b prefixes, hex floats, inf/nan) with the Zig std
  tests and replaces every int/float parse in config, keybind
  parameters, ssh-cache and desktop detection.
- Interior NUL no longer panics in font names and ends C strings like
  Zig's backing bytes (fontconfig, C config getters, title actions,
  clipboard callback, relative paths, config-file, shaders, background
  image, GTK CSS).
- GTK new-window arguments are trimmed of ASCII whitespace only.
- Command tokenization uses a port of std.process.ArgIteratorGeneral
  (incl. CR/LF separators) with its std tests.
- UTF-8 validation happens where Zig's field parsers do it, so error
  kinds match (metric modifiers, quick-terminal size, link, ...).

A scripted differential run of 202 fields x ~220 hostile/valid values
against /usr/bin/ghostty (+validate-config and +show-config: exit code,
stdout, stderr) now has zero mismatches besides build-specific defaults
(theme resources path, auto-update-channel, gtk-opengl-debug); it also
surfaced and fixed background-blur failure state, NaN formatting and
NaN/-0 finalize clamps. Regression tests: ghostty-config/tests/
zig_parity.rs.

Test Plan:
- cargo test --workspace --no-fail-fast (3456 passed, exit 0)
- just check-macos (both), just check-windows, just check-wasm
2026-10-12 12:35:37 +02:00

191 lines
5.8 KiB
Rust

//! Port of `Metrics.Modifier` from `font/Metrics.zig`.
//!
//! The font crate depends on this crate (not the other way around), so the
//! modifier type used by the `adjust-*` config options lives here.
use std::fmt;
use crate::{
cli_args::{ArgError, ConfigField},
formatter::EntryFormatter,
};
/// A modifier to apply to a metrics value. The modifier value represents
/// a delta, so percent is a percentage to change, not a percentage of.
/// For example, "20%" is 20% larger, not 20% of the value. Likewise,
/// an absolute value of "20" is 20 larger, not literally 20.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MetricModifier {
Percent(f64),
Absolute(i32),
}
impl Default for MetricModifier {
fn default() -> Self {
MetricModifier::Absolute(0)
}
}
impl MetricModifier {
/// Parses the modifier value. If the value ends in "%" it is assumed
/// to be a percent, otherwise the value is parsed as an integer.
pub fn parse(input: &str) -> Result<MetricModifier, ArgError> {
Self::parse_bytes(input.as_bytes())
}
/// [`MetricModifier::parse`] over the original bytes (Zig never
/// validates UTF-8; every failure is `InvalidFormat`).
pub fn parse_bytes(input: &[u8]) -> Result<MetricModifier, ArgError> {
if input.is_empty() {
return Err(ArgError::other("InvalidFormat"));
}
if let Some(num) = input.strip_suffix(b"%") {
let mut percent = ghostty_os::zig_fmt::parse_float::<f64>(num)
.map_err(|_| ArgError::other("InvalidFormat"))?;
percent /= 100.0;
if percent <= -1.0 {
return Ok(MetricModifier::Percent(0.0));
}
return Ok(MetricModifier::Percent(1.0 + percent));
}
ghostty_os::zig_fmt::parse_int::<i32>(input, 10)
.map(MetricModifier::Absolute)
.map_err(|_| ArgError::other("InvalidFormat"))
}
/// So it works with the config framework.
pub fn parse_cli_value(input: Option<&[u8]>) -> Result<MetricModifier, ArgError> {
Self::parse_bytes(input.ok_or(ArgError::ValueRequired)?)
}
/// Apply a modifier to an integer value (saturating, clamped at zero for
/// unsigned results, like the Zig implementation for unsigned types).
#[must_use]
pub fn apply_i64(&self, v: i64, unsigned: bool) -> i64 {
match *self {
MetricModifier::Percent(p) => {
let p = p.max(0.0);
(v as f64 * p).round() as i64
}
MetricModifier::Absolute(abs) => {
let applied = v.saturating_add(i64::from(abs));
if unsigned { applied.max(0) } else { applied }
}
}
}
/// Apply to a `u32`.
#[must_use]
pub fn apply_u32(&self, v: u32) -> u32 {
let r = self.apply_i64(i64::from(v), true);
u32::try_from(r).unwrap_or(u32::MAX)
}
/// Apply to an `i32`.
#[must_use]
pub fn apply_i32(&self, v: i32) -> i32 {
let r = self.apply_i64(i64::from(v), false);
// Mirrors Zig: out-of-range yields maxInt * sign.
i32::try_from(r).unwrap_or(if r < 0 { -i32::MAX } else { i32::MAX })
}
/// Apply to a float value.
#[must_use]
pub fn apply_f64(&self, v: f64) -> f64 {
match *self {
MetricModifier::Percent(p) => v * p.max(0.0),
MetricModifier::Absolute(abs) => v + f64::from(abs),
}
}
}
impl ConfigField for MetricModifier {
fn parse_bytes(&mut self, value: Option<&[u8]>) -> Result<(), ArgError> {
*self = Self::parse_cli_value(value)?;
Ok(())
}
fn format_entry(&self, f: &mut EntryFormatter<'_>) -> fmt::Result {
let s = match self {
MetricModifier::Percent(v) => format!(
"{}%",
ghostty_os::zig_fmt::format_float_d((v - 1.0) * 100.0)
),
MetricModifier::Absolute(v) => format!("{v}"),
};
f.format_entry(&s)
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
fn fmt1(m: MetricModifier) -> String {
let mut s = String::new();
crate::formatter::format_entry("a", &m, &mut s).unwrap();
s
}
#[test]
fn modifier_parse_absolute() {
assert_eq!(
MetricModifier::parse("100").unwrap(),
MetricModifier::Absolute(100)
);
assert_eq!(
MetricModifier::parse("-100").unwrap(),
MetricModifier::Absolute(-100)
);
}
#[test]
fn modifier_parse_percent() {
assert_eq!(
MetricModifier::parse("20%").unwrap(),
MetricModifier::Percent(1.2)
);
assert_eq!(
MetricModifier::parse("-20%").unwrap(),
MetricModifier::Percent(0.8)
);
assert_eq!(
MetricModifier::parse("0%").unwrap(),
MetricModifier::Percent(1.0)
);
}
#[test]
fn modifier_percent() {
assert_eq!(MetricModifier::Percent(0.8).apply_u32(100), 80);
assert_eq!(MetricModifier::Percent(1.8).apply_u32(100), 180);
}
#[test]
fn modifier_absolute() {
assert_eq!(MetricModifier::Absolute(-100).apply_u32(100), 0);
assert_eq!(MetricModifier::Absolute(-120).apply_u32(100), 0);
assert_eq!(MetricModifier::Absolute(100).apply_u32(100), 200);
assert_eq!(MetricModifier::Absolute(-100).apply_i32(100), 0);
assert_eq!(MetricModifier::Absolute(-120).apply_i32(100), -20);
}
#[test]
fn format_config_percent() {
let mut m = MetricModifier::default();
m.parse_cli(Some("24%")).unwrap();
assert_eq!(fmt1(m), "a = 24%\n");
}
#[test]
fn format_config_absolute() {
let mut m = MetricModifier::default();
m.parse_cli(Some("-30")).unwrap();
assert_eq!(fmt1(m), "a = -30\n");
}
}