fix(graphics-server): run minifb event loop on main thread

Fixes crashes on macOS.

Some operating systems and GUI frameworks, in particular Cocoa, don't
allow creating an event loop from a thread other than the main thread
(TID 1) and will abort a program on violation.
This commit is contained in:
yvt 2023-04-28 00:35:02 +09:00
parent 66db5767eb
commit c9fd805da2
3 changed files with 77 additions and 23 deletions

View file

@ -10,6 +10,16 @@ pub const FB_LINES: usize = LINES as usize;
pub const FB_SIZE: usize = FB_WIDTH_WORDS * FB_LINES; // 44 bytes by 536 lines pub const FB_SIZE: usize = FB_WIDTH_WORDS * FB_LINES; // 44 bytes by 536 lines
const CONFIG_CLOCK_FREQUENCY: u32 = 100_000_000; const CONFIG_CLOCK_FREQUENCY: u32 = 100_000_000;
pub struct MainThreadToken(());
pub enum Never {}
#[inline]
pub fn claim_main_thread(f: impl FnOnce(MainThreadToken) -> Never + Send + 'static) -> ! {
// Just call the closure - this backend will work on any thread
f(MainThreadToken(()))
}
pub struct XousDisplay { pub struct XousDisplay {
fb: MemoryRange, fb: MemoryRange,
hwfb: MemoryRange, hwfb: MemoryRange,
@ -19,7 +29,7 @@ pub struct XousDisplay {
} }
impl XousDisplay { impl XousDisplay {
pub fn new() -> XousDisplay { pub fn new(_main_thread_token: MainThreadToken) -> XousDisplay {
let fb = xous::syscall::map_memory( let fb = xous::syscall::map_memory(
None, None,
None, None,

View file

@ -3,7 +3,7 @@
use crate::api::Point; use crate::api::Point;
use minifb::{Key, Window, WindowOptions}; use minifb::{Key, Window, WindowOptions};
use crate::api::{LINES, WIDTH}; use crate::api::{LINES, WIDTH};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex, mpsc};
const HEIGHT: i16 = LINES; const HEIGHT: i16 = LINES;
@ -18,6 +18,48 @@ const MAX_FPS: u64 = 60;
const DARK_COLOUR: u32 = 0xB5B5AD; const DARK_COLOUR: u32 = 0xB5B5AD;
const LIGHT_COLOUR: u32 = 0x1B1B19; const LIGHT_COLOUR: u32 = 0x1B1B19;
/// The channel for the backend to communicate back to the main thread that it
/// has claimed.
pub struct MainThreadToken(mpsc::SyncSender<MinifbThread>);
/// A substitute for the native never type (`!`), which is still unstable on
/// `Fn` bounds.
pub enum Never {}
/// Claim the calling thread (which must be a main thread) for use by the
/// backend and call the specified closure on a new thread.
pub fn claim_main_thread(f: impl FnOnce(MainThreadToken) -> Never + Send + 'static) -> ! {
// Some operating systems and GUI frameworks, in particular Cocoa, don't
// allow creating an event loop from a thread other than the main thread
// (TID 1) and will abort a program on violation (see issue #373), hence we
// need to claim the main thread for use by the backend.
let (send, recv) = mpsc::sync_channel(0);
// Call the closure on a fake main thread
let fake_main_thread = std::thread::Builder::new()
.name("wrapped_main".into())
.spawn(move || f(MainThreadToken(send)))
.unwrap();
// Process up to one request (that's the maximum because
// `MainThreadToken: !Clone`)
match recv.recv() {
Ok(thread_params) => {
// Run a GUI event loop. Abort if the fake main thread panics
thread_params.run_while(|| !fake_main_thread.is_finished());
}
Err(mpsc::RecvError) => {}
}
// Join on the fake main thread
match fake_main_thread.join() {
Ok(x) => match x {},
// The default panic handler should have already outputted the panic
// message, so we can just call `abort` here
Err(_) => std::process::abort(),
}
}
pub struct XousDisplay { pub struct XousDisplay {
native_buffer: Arc<Mutex<Vec<u32>>>, //[u32; WIDTH * HEIGHT], native_buffer: Arc<Mutex<Vec<u32>>>, //[u32; WIDTH * HEIGHT],
emulated_buffer: [u32; FB_SIZE], emulated_buffer: [u32; FB_SIZE],
@ -38,18 +80,15 @@ struct XousKeyboardHandler {
} }
impl XousDisplay { impl XousDisplay {
pub fn new() -> XousDisplay { pub fn new(main_thread_token: MainThreadToken) -> XousDisplay {
let native_buffer = vec![DARK_COLOUR; WIDTH as usize * HEIGHT as usize]; let native_buffer = vec![DARK_COLOUR; WIDTH as usize * HEIGHT as usize];
let native_buffer = Arc::new(Mutex::new(native_buffer)); let native_buffer = Arc::new(Mutex::new(native_buffer));
// Spawn a GUI thread // Start a GUI event loop on the main thread
let thread_params = MinifbThread { let thread_params = MinifbThread {
native_buffer: Arc::clone(&native_buffer), native_buffer: Arc::clone(&native_buffer),
}; };
std::thread::Builder::new() main_thread_token.0.send(thread_params).unwrap();
.name("minifb".into())
.spawn(move || thread_params.run())
.unwrap();
XousDisplay { XousDisplay {
native_buffer, native_buffer,
@ -126,7 +165,7 @@ impl XousDisplay {
} }
impl MinifbThread { impl MinifbThread {
pub fn run(self) -> ! { pub fn run_while(self, mut predicate: impl FnMut() -> bool) {
let mut window = Window::new( let mut window = Window::new(
"Precursor", "Precursor",
WIDTH as usize, WIDTH as usize,
@ -159,7 +198,7 @@ impl MinifbThread {
let mut native_buffer = Vec::new(); let mut native_buffer = Vec::new();
loop { while predicate() {
// Copy the contents of `native_buffer`. Release the lock // Copy the contents of `native_buffer`. Release the lock
// immediately so as not to starve the server thread. // immediately so as not to starve the server thread.
native_buffer.clear(); native_buffer.clear();

View file

@ -93,25 +93,30 @@ fn map_fonts() -> MemoryRange {
fontregion fontregion
} }
fn main () -> ! { fn main () -> ! {
#[cfg(any(not(feature = "ditherpunk"), target_os = "macos"))] // Some operating systems and GUI frameworks don't allow creating an event
wrapped_main(); // loop from a thread other than TID 1. Let the backend claim this thread
// if this may be the case.
backend::claim_main_thread(move |main_thread_token| {
#[cfg(any(not(feature = "ditherpunk"), target_os = "macos"))]
wrapped_main(main_thread_token);
#[cfg(feature="ditherpunk")] #[cfg(feature="ditherpunk")]
let stack_size = 1024 * 1024; let stack_size = 1024 * 1024;
#[cfg(feature="ditherpunk")] #[cfg(feature="ditherpunk")]
std::thread::Builder::new() std::thread::Builder::new()
.stack_size(stack_size) .stack_size(stack_size)
.spawn(wrapped_main) .spawn(move || wrapped_main(main_thread_token))
.unwrap() .unwrap()
.join() .join()
.unwrap() .unwrap()
})
} }
fn wrapped_main() -> ! { fn wrapped_main(main_thread_token: backend::MainThreadToken) -> ! {
log_server::init_wait().unwrap(); log_server::init_wait().unwrap();
log::set_max_level(log::LevelFilter::Info); log::set_max_level(log::LevelFilter::Info);
log::info!("my PID is {}", xous::process::id()); log::info!("my PID is {}", xous::process::id());
let mut display = XousDisplay::new(); let mut display = XousDisplay::new(main_thread_token);
draw_boot_logo(&mut display); // bring this up as soon as possible draw_boot_logo(&mut display); // bring this up as soon as possible
let fontregion = map_fonts(); let fontregion = map_fonts();