native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
Documentation
//! Portable display and monitor metrics.
//!
//! The vocabulary a backend reports through [`crate::Backend::displays`]:
//! stable display identifiers, physical-pixel bounds and work areas, scale
//! factors, and the primary flag — enough for a display inspector and for
//! correct multi-monitor placement without any platform types leaking into
//! the shared model.
//!
//! Capability reporting follows the theming pattern: [`DisplayCapabilities`]
//! is a plain query (`none()` default) while enumeration itself returns the
//! typed [`crate::GuiError::UnsupportedCapability`] on lanes that cannot
//! report metrics, so a lane never fabricates monitor geometry.
//!
//! DPI/monitor transitions surface as [`crate::UiEvent::DisplayChanged`]; the
//! event payload is a fresh [`DisplayInfo`] for the window's current display.

#[cfg(feature = "displays")]
use std::fmt;

/// Physical-pixel rectangle in virtual-desktop coordinates.
///
/// `x`/`y` are the rectangle's top-left corner; `width`/`height` are always
/// non-negative for real displays (the constructor does not enforce it so
/// tests and fixtures can model hostile data).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg(feature = "displays")]
pub struct DisplayRect {
    /// Left edge in virtual-desktop pixels.
    pub x: i32,
    /// Top edge in virtual-desktop pixels.
    pub y: i32,
    /// Width in pixels.
    pub width: i32,
    /// Height in pixels.
    pub height: i32,
}

#[cfg(feature = "displays")]
impl DisplayRect {
    /// Creates a rectangle from its top-left corner and size.
    pub const fn new(x: i32, y: i32, width: i32, height: i32) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }

    /// Exclusive right edge (`x + width`).
    pub fn right(&self) -> i32 {
        self.x + self.width
    }

    /// Exclusive bottom edge (`y + height`).
    pub fn bottom(&self) -> i32 {
        self.y + self.height
    }

    /// Returns `true` when `(x, y)` lies inside the half-open rectangle.
    pub fn contains(&self, x: i32, y: i32) -> bool {
        x >= self.x && x < self.right() && y >= self.y && y < self.bottom()
    }

    /// Returns `true` when `other` lies entirely inside `self`.
    pub fn contains_rect(&self, other: &DisplayRect) -> bool {
        other.x >= self.x
            && other.y >= self.y
            && other.right() <= self.right()
            && other.bottom() <= self.bottom()
    }
}

#[cfg(feature = "displays")]
impl fmt::Display for DisplayRect {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}x{}+{}+{}", self.width, self.height, self.x, self.y)
    }
}

/// One display's portable metrics.
#[derive(Debug, Clone, PartialEq)]
#[cfg(feature = "displays")]
pub struct DisplayInfo {
    /// Stable identifier for the display within this backend session
    /// (Win32 derives it from the device name so it survives re-enumeration).
    pub id: u32,
    /// Human-readable device name (Win32: `\\.\DISPLAY1` style).
    pub name: String,
    /// Full display bounds in physical pixels.
    pub bounds: DisplayRect,
    /// Work area (bounds minus taskbar/dock reserved space).
    pub work_area: DisplayRect,
    /// Scale factor relative to 96 DPI (`1.0`, `1.25`, `1.5`, …).
    pub scale_factor: f64,
    /// Whether this is the primary display.
    pub primary: bool,
}

#[cfg(feature = "displays")]
impl DisplayInfo {
    /// Creates display metrics.
    pub fn new(
        id: u32,
        name: &str,
        bounds: DisplayRect,
        work_area: DisplayRect,
        scale_factor: f64,
        primary: bool,
    ) -> Self {
        Self {
            id,
            name: name.to_owned(),
            bounds,
            work_area,
            scale_factor,
            primary,
        }
    }

    /// Effective DPI derived from [`DisplayInfo::scale_factor`].
    pub fn dpi(&self) -> u32 {
        (self.scale_factor * 96.0).round() as u32
    }
}

/// Which display-metric features a backend supports.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct DisplayCapabilities {
    /// The backend can enumerate connected displays through
    /// [`crate::Backend::displays`].
    pub enumeration: bool,
    /// The backend reports DPI/monitor transitions through
    /// [`crate::UiEvent::DisplayChanged`].
    pub dpi_change_events: bool,
}

impl DisplayCapabilities {
    /// No enumeration and no change events.
    pub const fn none() -> Self {
        Self {
            enumeration: false,
            dpi_change_events: false,
        }
    }

    /// Enumeration and change events.
    pub const fn all() -> Self {
        Self {
            enumeration: true,
            dpi_change_events: true,
        }
    }

    /// `true` when any display feature is supported.
    pub const fn is_supported(&self) -> bool {
        self.enumeration || self.dpi_change_events
    }
}

/// Projects a pointer position from the display's native pixel space into
/// logical (96-DPI) coordinates by dividing by `scale`.
///
/// `scale` is the display's scale factor relative to 96 DPI (`1.0` = 100 %,
/// `1.25` = 125 %, …). Lanes that emit pointer coordinates in physical
/// pixels (Win32 under Per-Monitor v2) divide by the scale to recover the
/// logical position the layout engine lays out against; lanes that already emit logical
/// coordinates (GTK4 gestures, the Mock backend) report a scale of `1.0`,
/// making this the identity. A scale at or below `1.0` is clamped to `1.0`
/// so a hostile or unreported scale can never amplify a coordinate.
///
/// This is the shared half of the physical-to-logical input isomorphism:
/// the backend reports the scale through
/// [`crate::Backend::widget_scale_factor`] and [`crate::Ui`] applies this to
/// every pointer event it dispatches, so app code always receives logical
/// coordinates. Call it directly for a raw position that did not come through
/// [`crate::UiEvent::PointerMove`].
pub fn logical_pointer_projection(x: f32, y: f32, scale: f64) -> (f32, f32) {
    let scale = scale.max(1.0) as f32;
    (x / scale, y / scale)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rect_math_and_containment_are_half_open() {
        let rect = DisplayRect::new(10, 20, 100, 50);
        assert_eq!(rect.right(), 110);
        assert_eq!(rect.bottom(), 70);
        assert!(rect.contains(10, 20));
        assert!(rect.contains(109, 69));
        // Right/bottom edges are exclusive.
        assert!(!rect.contains(110, 69));
        assert!(!rect.contains(109, 70));
        assert!(!rect.contains(9, 20));
        assert!(rect.contains_rect(&DisplayRect::new(10, 20, 100, 50)));
        assert!(rect.contains_rect(&DisplayRect::new(60, 40, 10, 10)));
        assert!(!rect.contains_rect(&DisplayRect::new(60, 40, 60, 10)));
        assert_eq!(rect.to_string(), "100x50+10+20");
    }

    #[test]
    fn display_info_derives_dpi_from_scale() {
        let display = DisplayInfo::new(
            7,
            "mock-primary",
            DisplayRect::new(0, 0, 1920, 1080),
            DisplayRect::new(0, 0, 1920, 1040),
            1.25,
            true,
        );
        assert_eq!(display.dpi(), 120);
        assert!(display.primary);
        assert_eq!(
            display.work_area,
            DisplayRect::new(0, 0, 1920, 1040),
            "work area keeps its own rectangle"
        );
        let secondary = DisplayInfo::new(
            8,
            "mock-secondary",
            DisplayRect::new(1920, 0, 1280, 1024),
            DisplayRect::new(1920, 0, 1280, 984),
            1.0,
            false,
        );
        assert_eq!(secondary.dpi(), 96);
        assert_ne!(display, secondary);
    }

    #[test]
    fn capabilities_default_to_none_and_expose_all() {
        assert_eq!(DisplayCapabilities::default(), DisplayCapabilities::none());
        assert!(!DisplayCapabilities::default().is_supported());
        assert!(DisplayCapabilities::all().enumeration);
        assert!(DisplayCapabilities::all().dpi_change_events);
        assert!(DisplayCapabilities::all().is_supported());
        let enumeration_only = DisplayCapabilities {
            enumeration: true,
            dpi_change_events: false,
        };
        assert!(enumeration_only.is_supported());
        assert!(!DisplayCapabilities::none().is_supported());
    }

    #[test]
    fn logical_pointer_projection_divides_by_scale() {
        // 125 % display: 125 physical px -> 100 logical px.
        assert_eq!(
            logical_pointer_projection(125.0, 250.0, 1.25),
            (100.0, 200.0)
        );
        // 150 % display: 300 physical px -> 200 logical px.
        assert_eq!(
            logical_pointer_projection(300.0, 150.0, 1.5),
            (200.0, 100.0)
        );
        // 200 % display: 400 physical px -> 200 logical px.
        assert_eq!(
            logical_pointer_projection(400.0, 400.0, 2.0),
            (200.0, 200.0)
        );
    }

    #[test]
    fn logical_pointer_projection_is_identity_at_100_percent() {
        assert_eq!(logical_pointer_projection(10.0, 20.0, 1.0), (10.0, 20.0));
        // Sub-100 % scales clamp to 1.0 (identity) so a hostile scale never
        // amplifies a coordinate.
        assert_eq!(logical_pointer_projection(10.0, 20.0, 0.5), (10.0, 20.0));
        assert_eq!(logical_pointer_projection(10.0, 20.0, 0.0), (10.0, 20.0));
        assert_eq!(logical_pointer_projection(10.0, 20.0, -3.0), (10.0, 20.0));
    }

    #[test]
    fn logical_pointer_projection_preserves_negative_and_zero() {
        assert_eq!(logical_pointer_projection(-125.0, 0.0, 1.25), (-100.0, 0.0));
        assert_eq!(logical_pointer_projection(0.0, -250.0, 1.25), (0.0, -200.0));
    }
}