nadir-platform 0.4.0

OS layer of the Nadir engine: windows, the event loop, input devices, GL surfaces, audio output and paths.
Documentation
// Copyright 2026 Joseph Anthony Abbott III
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! The error type for `nadir-platform`.

use std::fmt;

/// Errors produced by `nadir-platform`.
///
/// New kinds of error can join it in a minor version (ADR-0047), so a
/// `match` on it needs a `_` arm.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PlatformError {
    /// This operating system has no backend yet.
    Unsupported,
    /// There is no display server to connect to.
    NoDisplay {
        /// Whether a Wayland session is running. If so, it runs without
        /// XWayland.
        wayland: bool,
    },
    /// A system library could not be loaded.
    LibraryNotFound {
        /// The file name of the library, such as `libX11.so.6`.
        library: &'static str,
        /// What the system's loader said.
        reason: String,
    },
    /// A system library lacks functions that the engine calls.
    MissingSymbols {
        /// The file name of the library.
        library: &'static str,
        /// The name of every missing function.
        symbols: Vec<&'static str>,
    },
    /// The display server did not accept the connection.
    ConnectionFailed {
        /// The display that was tried, as `DISPLAY` names it.
        display: String,
    },
    /// A call to the operating system failed.
    CallFailed {
        /// The function that failed.
        call: &'static str,
    },
    /// A studio or game name cannot be a folder name on every system. See
    /// [`user_dirs`](crate::user_dirs).
    InvalidName {
        /// The name as given.
        name: String,
    },
    /// The user's home directory is unknown, and the folders for settings
    /// and data are inside it.
    NoHomeDirectory,
    /// The window was to be opened on a thread other than the main one,
    /// which macOS does not allow.
    NotMainThread,
    /// A call to EGL or OpenGL failed.
    GpuCallFailed {
        /// The function that failed.
        call: &'static str,
        /// What went wrong: the error that the call reported, such as
        /// `EGL_BAD_MATCH`, or what was wrong with what it returned.
        error: String,
    },
    /// The graphics driver has no OpenGL frame buffer format with 8 bits
    /// each of red, green and blue that suits the window, or offscreen
    /// drawing.
    NoGlConfig,
    /// The graphics driver does not offer OpenGL 3.3 with the core profile.
    GlTooOld {
        /// The version that the driver did give, as its `GL_VERSION`
        /// string, if a context could be made at all.
        found: Option<String>,
    },
    /// This thread already has an OpenGL context: the window's, or one from
    /// [`create_headless_gl`](crate::create_headless_gl). A thread can have
    /// one at a time.
    GlContextExists,
    /// A field of an [`AudioOutputConfig`](crate::AudioOutputConfig) is out
    /// of its range.
    InvalidAudioConfig {
        /// The field, such as `channels`.
        field: &'static str,
        /// Its range, such as `1 to 8`.
        expected: &'static str,
    },
    /// A call to set up the audio output failed. See
    /// [`open_audio`](crate::open_audio).
    AudioCallFailed {
        /// The function that failed, such as `snd_pcm_set_params`.
        call: &'static str,
        /// What went wrong, as the system said it, and which device.
        error: String,
    },
}

impl fmt::Display for PlatformError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unsupported => f.write_str("this operating system has no backend yet"),
            Self::NoDisplay { wayland: false } => {
                f.write_str("no X server to connect to: `DISPLAY` is not set")
            }
            Self::NoDisplay { wayland: true } => f.write_str(
                "no X server to connect to: `DISPLAY` is not set. This is a Wayland session, \
                 and the game needs XWayland in it. Turn XWayland on in the compositor's \
                 settings, then start the game again",
            ),
            Self::LibraryNotFound { library, reason } => {
                write!(f, "could not load {library}: {reason}")
            }
            Self::MissingSymbols { library, symbols } => write!(
                f,
                "{library} lacks functions that the engine calls: {}",
                symbols.join(", ")
            ),
            Self::ConnectionFailed { display } => {
                write!(f, "could not connect to the X server `{display}`")
            }
            Self::CallFailed { call } => write!(f, "{call} failed"),
            Self::InvalidName { name } => write!(
                f,
                "`{name}` cannot be a folder name on Windows, macOS and Linux"
            ),
            Self::NoHomeDirectory => {
                f.write_str("could not find the home directory: set `HOME` to an absolute path")
            }
            Self::NotMainThread => f.write_str("the window can only be opened on the main thread"),
            Self::GpuCallFailed { call, error } => write!(f, "{call} failed: {error}"),
            Self::NoGlConfig => f.write_str(
                "the graphics driver has no OpenGL frame buffer format with 8-bit red, green and \
                 blue",
            ),
            Self::GlTooOld { found: None } => {
                f.write_str("the graphics driver does not offer OpenGL 3.3 (core profile)")
            }
            Self::GlTooOld { found: Some(found) } => write!(
                f,
                "the graphics driver does not offer OpenGL 3.3 (core profile): it gave `{found}`"
            ),
            Self::GlContextExists => f.write_str("this thread already has an OpenGL context"),
            Self::InvalidAudioConfig { field, expected } => {
                write!(f, "the audio output's `{field}` must be from {expected}")
            }
            Self::AudioCallFailed { call, error } => write!(f, "{call} failed: {error}"),
        }
    }
}

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

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

    #[test]
    fn each_message_says_what_went_wrong() {
        let cases = [
            (
                PlatformError::Unsupported,
                "this operating system has no backend yet",
            ),
            (
                PlatformError::NoDisplay { wayland: false },
                "no X server to connect to: `DISPLAY` is not set",
            ),
            (
                PlatformError::LibraryNotFound {
                    library: "libX11.so.6",
                    reason: "cannot open shared object file".to_string(),
                },
                "could not load libX11.so.6: cannot open shared object file",
            ),
            (
                PlatformError::MissingSymbols {
                    library: "libX11.so.6",
                    symbols: vec!["XPending", "XNextEvent"],
                },
                "libX11.so.6 lacks functions that the engine calls: XPending, XNextEvent",
            ),
            (
                PlatformError::ConnectionFailed {
                    display: ":7".to_string(),
                },
                "could not connect to the X server `:7`",
            ),
            (
                PlatformError::CallFailed {
                    call: "XSetWMProtocols",
                },
                "XSetWMProtocols failed",
            ),
            (
                PlatformError::InvalidName {
                    name: "a/b".to_string(),
                },
                "`a/b` cannot be a folder name on Windows, macOS and Linux",
            ),
            (
                PlatformError::NoHomeDirectory,
                "could not find the home directory: set `HOME` to an absolute path",
            ),
            (
                PlatformError::NotMainThread,
                "the window can only be opened on the main thread",
            ),
            (
                PlatformError::GpuCallFailed {
                    call: "eglCreateWindowSurface",
                    error: "EGL_BAD_MATCH".to_string(),
                },
                "eglCreateWindowSurface failed: EGL_BAD_MATCH",
            ),
            (
                PlatformError::NoGlConfig,
                "the graphics driver has no OpenGL frame buffer format with 8-bit red, green and \
                 blue",
            ),
            (
                PlatformError::GlTooOld { found: None },
                "the graphics driver does not offer OpenGL 3.3 (core profile)",
            ),
            (
                PlatformError::GlTooOld {
                    found: Some("3.1 Mesa 24.0.5".to_string()),
                },
                "the graphics driver does not offer OpenGL 3.3 (core profile): it gave `3.1 Mesa \
                 24.0.5`",
            ),
            (
                PlatformError::GlContextExists,
                "this thread already has an OpenGL context",
            ),
            (
                PlatformError::InvalidAudioConfig {
                    field: "channels",
                    expected: "1 to 8",
                },
                "the audio output's `channels` must be from 1 to 8",
            ),
            (
                PlatformError::AudioCallFailed {
                    call: "snd_pcm_set_params",
                    error: "Invalid argument (the ALSA device `default`)".to_string(),
                },
                "snd_pcm_set_params failed: Invalid argument (the ALSA device `default`)",
            ),
        ];
        for (error, message) in cases {
            assert_eq!(error.to_string(), message);
        }
    }

    #[test]
    fn a_wayland_session_without_xwayland_is_told_what_to_do() {
        let message = PlatformError::NoDisplay { wayland: true }.to_string();
        assert!(
            message.starts_with("no X server to connect to"),
            "{message}"
        );
        assert!(message.contains("Wayland session"), "{message}");
        assert!(message.contains("Turn XWayland on"), "{message}");
    }

    #[test]
    fn it_is_an_error() {
        let error: Box<dyn std::error::Error> = Box::new(PlatformError::Unsupported);
        assert!(error.source().is_none());
    }
}