From 70ed800481594e5797da23c64459663f299b2f63 Mon Sep 17 00:00:00 2001 From: AzureMarker Date: Sat, 1 Jan 2022 13:04:29 -0500 Subject: [PATCH] Implement Drop for Console so printing doesn't crash after dropping --- ctru-rs/src/console.rs | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/ctru-rs/src/console.rs b/ctru-rs/src/console.rs index 9e533d5..276509f 100644 --- a/ctru-rs/src/console.rs +++ b/ctru-rs/src/console.rs @@ -13,12 +13,11 @@ impl Console { /// previously (including other consoles). The new console is automatically selected for /// printing. pub fn init(screen: Screen) -> Self { - unsafe { - let mut context = Box::new(PrintConsole::default()); - consoleInit(screen.into(), context.as_mut()); + let mut context = Box::new(PrintConsole::default()); - Console { context } - } + unsafe { consoleInit(screen.into(), context.as_mut()) }; + + Console { context } } /// Select this console as the current target for stdout @@ -45,6 +44,26 @@ impl Console { } } +impl Drop for Console { + fn drop(&mut self) { + // Get the current console by replacing it with the default. + let default_console = unsafe { libctru::consoleGetDefault() }; + let current_console = unsafe { libctru::consoleSelect(default_console) }; + + if std::ptr::eq(current_console, &*self.context) { + // Console dropped while selected. We just replaced it with the + // default so make sure it's initialized. + if unsafe { !(*default_console).consoleInitialised } { + unsafe { libctru::consoleInit(Screen::Top.into(), default_console) }; + } + } else { + // Console dropped while a different console was selected. Put back + // the console that was selected. + unsafe { libctru::consoleSelect(current_console) }; + } + } +} + impl Default for Console { fn default() -> Self { Console::init(Screen::Top)