Skip to main content

hao_runtime/
console.rs

1//! Give an injected mod somewhere to see its logs.
2//!
3//! A game is usually a windowed process with no console, so `stdout`/`stderr`
4//! (and a `tracing` subscriber writing to them) go nowhere. [`alloc_console`]
5//! fixes that on Windows by allocating a console and pointing the standard
6//! handles at it. On other platforms the process already has a `stderr`, so it
7//! is a no-op; run the game from a terminal to see the output.
8
9/// Allocates a console and attaches the standard output/error handles to it.
10/// Returns whether a console was allocated (always `false` off Windows).
11pub fn alloc_console() -> bool {
12    imp::alloc_console()
13}
14
15#[cfg(windows)]
16mod imp {
17    use windows_sys::Win32::System::Console::AllocConsole;
18
19    pub fn alloc_console() -> bool {
20        // AllocConsole points the process's standard handles at the new console.
21        // Rust reads those handles lazily, so as long as this runs before the
22        // first stdout/stderr use (it does, at mod load) the output reaches it.
23        unsafe { AllocConsole() != 0 }
24    }
25}
26
27#[cfg(not(windows))]
28mod imp {
29    pub fn alloc_console() -> bool {
30        false
31    }
32}