Skip to main content

nadir_platform/
error.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The error type for `nadir-platform`.
16
17use std::fmt;
18
19/// Errors produced by `nadir-platform`.
20///
21/// New kinds of error can join it in a minor version (ADR-0047), so a
22/// `match` on it needs a `_` arm.
23#[non_exhaustive]
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub enum PlatformError {
26    /// This operating system has no backend yet.
27    Unsupported,
28    /// There is no display server to connect to.
29    NoDisplay {
30        /// Whether a Wayland session is running. If so, it runs without
31        /// XWayland.
32        wayland: bool,
33    },
34    /// A system library could not be loaded.
35    LibraryNotFound {
36        /// The file name of the library, such as `libX11.so.6`.
37        library: &'static str,
38        /// What the system's loader said.
39        reason: String,
40    },
41    /// A system library lacks functions that the engine calls.
42    MissingSymbols {
43        /// The file name of the library.
44        library: &'static str,
45        /// The name of every missing function.
46        symbols: Vec<&'static str>,
47    },
48    /// The display server did not accept the connection.
49    ConnectionFailed {
50        /// The display that was tried, as `DISPLAY` names it.
51        display: String,
52    },
53    /// A call to the operating system failed.
54    CallFailed {
55        /// The function that failed.
56        call: &'static str,
57    },
58    /// A studio or game name cannot be a folder name on every system. See
59    /// [`user_dirs`](crate::user_dirs).
60    InvalidName {
61        /// The name as given.
62        name: String,
63    },
64    /// The user's home directory is unknown, and the folders for settings
65    /// and data are inside it.
66    NoHomeDirectory,
67    /// The window was to be opened on a thread other than the main one,
68    /// which macOS does not allow.
69    NotMainThread,
70    /// A call to EGL or OpenGL failed.
71    GpuCallFailed {
72        /// The function that failed.
73        call: &'static str,
74        /// What went wrong: the error that the call reported, such as
75        /// `EGL_BAD_MATCH`, or what was wrong with what it returned.
76        error: String,
77    },
78    /// The graphics driver has no OpenGL frame buffer format with 8 bits
79    /// each of red, green and blue that suits the window, or offscreen
80    /// drawing.
81    NoGlConfig,
82    /// The graphics driver does not offer OpenGL 3.3 with the core profile.
83    GlTooOld {
84        /// The version that the driver did give, as its `GL_VERSION`
85        /// string, if a context could be made at all.
86        found: Option<String>,
87    },
88    /// This thread already has an OpenGL context: the window's, or one from
89    /// [`create_headless_gl`](crate::create_headless_gl). A thread can have
90    /// one at a time.
91    GlContextExists,
92    /// A field of an [`AudioOutputConfig`](crate::AudioOutputConfig) is out
93    /// of its range.
94    InvalidAudioConfig {
95        /// The field, such as `channels`.
96        field: &'static str,
97        /// Its range, such as `1 to 8`.
98        expected: &'static str,
99    },
100    /// A call to set up the audio output failed. See
101    /// [`open_audio`](crate::open_audio).
102    AudioCallFailed {
103        /// The function that failed, such as `snd_pcm_set_params`.
104        call: &'static str,
105        /// What went wrong, as the system said it, and which device.
106        error: String,
107    },
108}
109
110impl fmt::Display for PlatformError {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        match self {
113            Self::Unsupported => f.write_str("this operating system has no backend yet"),
114            Self::NoDisplay { wayland: false } => {
115                f.write_str("no X server to connect to: `DISPLAY` is not set")
116            }
117            Self::NoDisplay { wayland: true } => f.write_str(
118                "no X server to connect to: `DISPLAY` is not set. This is a Wayland session, \
119                 and the game needs XWayland in it. Turn XWayland on in the compositor's \
120                 settings, then start the game again",
121            ),
122            Self::LibraryNotFound { library, reason } => {
123                write!(f, "could not load {library}: {reason}")
124            }
125            Self::MissingSymbols { library, symbols } => write!(
126                f,
127                "{library} lacks functions that the engine calls: {}",
128                symbols.join(", ")
129            ),
130            Self::ConnectionFailed { display } => {
131                write!(f, "could not connect to the X server `{display}`")
132            }
133            Self::CallFailed { call } => write!(f, "{call} failed"),
134            Self::InvalidName { name } => write!(
135                f,
136                "`{name}` cannot be a folder name on Windows, macOS and Linux"
137            ),
138            Self::NoHomeDirectory => {
139                f.write_str("could not find the home directory: set `HOME` to an absolute path")
140            }
141            Self::NotMainThread => f.write_str("the window can only be opened on the main thread"),
142            Self::GpuCallFailed { call, error } => write!(f, "{call} failed: {error}"),
143            Self::NoGlConfig => f.write_str(
144                "the graphics driver has no OpenGL frame buffer format with 8-bit red, green and \
145                 blue",
146            ),
147            Self::GlTooOld { found: None } => {
148                f.write_str("the graphics driver does not offer OpenGL 3.3 (core profile)")
149            }
150            Self::GlTooOld { found: Some(found) } => write!(
151                f,
152                "the graphics driver does not offer OpenGL 3.3 (core profile): it gave `{found}`"
153            ),
154            Self::GlContextExists => f.write_str("this thread already has an OpenGL context"),
155            Self::InvalidAudioConfig { field, expected } => {
156                write!(f, "the audio output's `{field}` must be from {expected}")
157            }
158            Self::AudioCallFailed { call, error } => write!(f, "{call} failed: {error}"),
159        }
160    }
161}
162
163impl std::error::Error for PlatformError {}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    #[test]
170    fn each_message_says_what_went_wrong() {
171        let cases = [
172            (
173                PlatformError::Unsupported,
174                "this operating system has no backend yet",
175            ),
176            (
177                PlatformError::NoDisplay { wayland: false },
178                "no X server to connect to: `DISPLAY` is not set",
179            ),
180            (
181                PlatformError::LibraryNotFound {
182                    library: "libX11.so.6",
183                    reason: "cannot open shared object file".to_string(),
184                },
185                "could not load libX11.so.6: cannot open shared object file",
186            ),
187            (
188                PlatformError::MissingSymbols {
189                    library: "libX11.so.6",
190                    symbols: vec!["XPending", "XNextEvent"],
191                },
192                "libX11.so.6 lacks functions that the engine calls: XPending, XNextEvent",
193            ),
194            (
195                PlatformError::ConnectionFailed {
196                    display: ":7".to_string(),
197                },
198                "could not connect to the X server `:7`",
199            ),
200            (
201                PlatformError::CallFailed {
202                    call: "XSetWMProtocols",
203                },
204                "XSetWMProtocols failed",
205            ),
206            (
207                PlatformError::InvalidName {
208                    name: "a/b".to_string(),
209                },
210                "`a/b` cannot be a folder name on Windows, macOS and Linux",
211            ),
212            (
213                PlatformError::NoHomeDirectory,
214                "could not find the home directory: set `HOME` to an absolute path",
215            ),
216            (
217                PlatformError::NotMainThread,
218                "the window can only be opened on the main thread",
219            ),
220            (
221                PlatformError::GpuCallFailed {
222                    call: "eglCreateWindowSurface",
223                    error: "EGL_BAD_MATCH".to_string(),
224                },
225                "eglCreateWindowSurface failed: EGL_BAD_MATCH",
226            ),
227            (
228                PlatformError::NoGlConfig,
229                "the graphics driver has no OpenGL frame buffer format with 8-bit red, green and \
230                 blue",
231            ),
232            (
233                PlatformError::GlTooOld { found: None },
234                "the graphics driver does not offer OpenGL 3.3 (core profile)",
235            ),
236            (
237                PlatformError::GlTooOld {
238                    found: Some("3.1 Mesa 24.0.5".to_string()),
239                },
240                "the graphics driver does not offer OpenGL 3.3 (core profile): it gave `3.1 Mesa \
241                 24.0.5`",
242            ),
243            (
244                PlatformError::GlContextExists,
245                "this thread already has an OpenGL context",
246            ),
247            (
248                PlatformError::InvalidAudioConfig {
249                    field: "channels",
250                    expected: "1 to 8",
251                },
252                "the audio output's `channels` must be from 1 to 8",
253            ),
254            (
255                PlatformError::AudioCallFailed {
256                    call: "snd_pcm_set_params",
257                    error: "Invalid argument (the ALSA device `default`)".to_string(),
258                },
259                "snd_pcm_set_params failed: Invalid argument (the ALSA device `default`)",
260            ),
261        ];
262        for (error, message) in cases {
263            assert_eq!(error.to_string(), message);
264        }
265    }
266
267    #[test]
268    fn a_wayland_session_without_xwayland_is_told_what_to_do() {
269        let message = PlatformError::NoDisplay { wayland: true }.to_string();
270        assert!(
271            message.starts_with("no X server to connect to"),
272            "{message}"
273        );
274        assert!(message.contains("Wayland session"), "{message}");
275        assert!(message.contains("Turn XWayland on"), "{message}");
276    }
277
278    #[test]
279    fn it_is_an_error() {
280        let error: Box<dyn std::error::Error> = Box::new(PlatformError::Unsupported);
281        assert!(error.source().is_none());
282    }
283}