native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
Documentation
use std::fmt::{Display, Formatter};

#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GuiError {
    WidgetNotFound(u64),
    InvalidParentChild {
        parent: u64,
        child: u64,
    },
    UnsupportedWidget(&'static str),
    /// The backend does not implement the requested capability yet (for
    /// example a native accessibility bridge). The payload names the
    /// capability; callers should degrade gracefully rather than treat this
    /// as a programming error.
    UnsupportedCapability(String),
    Backend(String),
    /// The OS or backend refused an allocation due to resource pressure
    /// (e.g. GDI handles, window limits, canvas size limits).
    ResourceExhausted {
        operation: &'static str,
        code: Option<u32>,
    },
    /// Invalid numeric input encountered in layout calculations or constraints (NaN, infinite).
    InvalidNumericInput,
    /// Invalid layout geometry (negative dimensions where forbidden, etc.).
    InvalidLayoutGeometry,
    /// Unsupported layout mode or feature.
    UnsupportedLayoutMode(&'static str),
    /// A property model rejected an operation (unknown node, read-only
    /// property, incompatible value, stale change token, ...).
    Property(crate::properties::PropertyError),
    /// A styled text document rejected an operation (range outside the
    /// text, unknown line, read-only document, ...).
    #[cfg(feature = "styled-text")]
    StyledText(crate::styled_text::StyledTextError),
    /// A WebView operation failed (engine missing, invalid URL, ...).
    #[cfg(feature = "webview")]
    WebView(crate::webview::WebViewError),
}

impl From<crate::properties::PropertyError> for GuiError {
    fn from(error: crate::properties::PropertyError) -> Self {
        GuiError::Property(error)
    }
}

impl GuiError {
    /// Returns true if this error represents a resource exhaustion failure,
    /// either via the typed `ResourceExhausted` variant or a fallback
    /// `Backend` string containing "OS resources exhausted".
    pub fn is_resource_exhaustion(&self) -> bool {
        match self {
            GuiError::ResourceExhausted { .. } => true,
            GuiError::Backend(msg) => msg.contains("OS resources exhausted"),
            _ => false,
        }
    }
}

impl Display for GuiError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            GuiError::WidgetNotFound(id) => write!(f, "Widget not found: {id}"),
            GuiError::InvalidParentChild { parent, child } => {
                write!(
                    f,
                    "Invalid parent-child relationship: parent={parent}, child={child}"
                )
            }
            GuiError::UnsupportedWidget(kind) => write!(f, "Unsupported widget type: {kind}"),
            GuiError::UnsupportedCapability(capability) => {
                write!(f, "Unsupported capability: {capability}")
            }
            GuiError::Backend(msg) => write!(f, "Backend error: {msg}"),
            GuiError::ResourceExhausted { operation, code } => {
                if let Some(c) = code {
                    write!(f, "OS resources exhausted during {operation}: code {c}")
                } else {
                    write!(f, "OS resources exhausted during {operation}")
                }
            }
            GuiError::InvalidNumericInput => write!(f, "Invalid numeric input in layout"),
            GuiError::InvalidLayoutGeometry => write!(f, "Invalid layout geometry constraints"),
            GuiError::UnsupportedLayoutMode(mode) => write!(f, "Unsupported layout mode: {mode}"),
            GuiError::Property(error) => write!(f, "Property error: {error}"),
            #[cfg(feature = "styled-text")]
            GuiError::StyledText(error) => write!(f, "Styled text error: {error}"),
            #[cfg(feature = "webview")]
            GuiError::WebView(error) => write!(f, "WebView error: {error}"),
        }
    }
}

impl std::error::Error for GuiError {}

pub type GuiResult<T> = Result<T, GuiError>;

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

    #[test]
    fn is_resource_exhaustion_matches_typed_and_fallback() {
        assert!(GuiError::ResourceExhausted {
            operation: "test",
            code: None
        }
        .is_resource_exhaustion());
        assert!(
            GuiError::Backend("OS resources exhausted: GDI limit".into()).is_resource_exhaustion()
        );
        assert!(!GuiError::Backend("other error".into()).is_resource_exhaustion());
    }
}