Skip to main content

native_gui_core/
error.rs

1use std::fmt::{Display, Formatter};
2
3#[non_exhaustive]
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub enum GuiError {
6    WidgetNotFound(u64),
7    InvalidParentChild {
8        parent: u64,
9        child: u64,
10    },
11    UnsupportedWidget(&'static str),
12    /// The backend does not implement the requested capability yet (for
13    /// example a native accessibility bridge). The payload names the
14    /// capability; callers should degrade gracefully rather than treat this
15    /// as a programming error.
16    UnsupportedCapability(String),
17    Backend(String),
18    /// The OS or backend refused an allocation due to resource pressure
19    /// (e.g. GDI handles, window limits, canvas size limits).
20    ResourceExhausted {
21        operation: &'static str,
22        code: Option<u32>,
23    },
24    /// Invalid numeric input encountered in layout calculations or constraints (NaN, infinite).
25    InvalidNumericInput,
26    /// Invalid layout geometry (negative dimensions where forbidden, etc.).
27    InvalidLayoutGeometry,
28    /// Unsupported layout mode or feature.
29    UnsupportedLayoutMode(&'static str),
30    /// A property model rejected an operation (unknown node, read-only
31    /// property, incompatible value, stale change token, ...).
32    Property(crate::properties::PropertyError),
33    /// A styled text document rejected an operation (range outside the
34    /// text, unknown line, read-only document, ...).
35    #[cfg(feature = "styled-text")]
36    StyledText(crate::styled_text::StyledTextError),
37    /// A WebView operation failed (engine missing, invalid URL, ...).
38    #[cfg(feature = "webview")]
39    WebView(crate::webview::WebViewError),
40}
41
42impl From<crate::properties::PropertyError> for GuiError {
43    fn from(error: crate::properties::PropertyError) -> Self {
44        GuiError::Property(error)
45    }
46}
47
48impl GuiError {
49    /// Returns true if this error represents a resource exhaustion failure,
50    /// either via the typed `ResourceExhausted` variant or a fallback
51    /// `Backend` string containing "OS resources exhausted".
52    pub fn is_resource_exhaustion(&self) -> bool {
53        match self {
54            GuiError::ResourceExhausted { .. } => true,
55            GuiError::Backend(msg) => msg.contains("OS resources exhausted"),
56            _ => false,
57        }
58    }
59}
60
61impl Display for GuiError {
62    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
63        match self {
64            GuiError::WidgetNotFound(id) => write!(f, "Widget not found: {id}"),
65            GuiError::InvalidParentChild { parent, child } => {
66                write!(
67                    f,
68                    "Invalid parent-child relationship: parent={parent}, child={child}"
69                )
70            }
71            GuiError::UnsupportedWidget(kind) => write!(f, "Unsupported widget type: {kind}"),
72            GuiError::UnsupportedCapability(capability) => {
73                write!(f, "Unsupported capability: {capability}")
74            }
75            GuiError::Backend(msg) => write!(f, "Backend error: {msg}"),
76            GuiError::ResourceExhausted { operation, code } => {
77                if let Some(c) = code {
78                    write!(f, "OS resources exhausted during {operation}: code {c}")
79                } else {
80                    write!(f, "OS resources exhausted during {operation}")
81                }
82            }
83            GuiError::InvalidNumericInput => write!(f, "Invalid numeric input in layout"),
84            GuiError::InvalidLayoutGeometry => write!(f, "Invalid layout geometry constraints"),
85            GuiError::UnsupportedLayoutMode(mode) => write!(f, "Unsupported layout mode: {mode}"),
86            GuiError::Property(error) => write!(f, "Property error: {error}"),
87            #[cfg(feature = "styled-text")]
88            GuiError::StyledText(error) => write!(f, "Styled text error: {error}"),
89            #[cfg(feature = "webview")]
90            GuiError::WebView(error) => write!(f, "WebView error: {error}"),
91        }
92    }
93}
94
95impl std::error::Error for GuiError {}
96
97pub type GuiResult<T> = Result<T, GuiError>;
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102
103    #[test]
104    fn is_resource_exhaustion_matches_typed_and_fallback() {
105        assert!(GuiError::ResourceExhausted {
106            operation: "test",
107            code: None
108        }
109        .is_resource_exhaustion());
110        assert!(
111            GuiError::Backend("OS resources exhausted: GDI limit".into()).is_resource_exhaustion()
112        );
113        assert!(!GuiError::Backend("other error".into()).is_resource_exhaustion());
114    }
115}