use std::ffi::{c_void, CStr};
use std::fmt;
use std::panic::{self, AssertUnwindSafe};
use std::ptr;
use std::rc::Rc;
use crate::context::{GlContext, GlInner};
use crate::error::{GlError, Result};
use crate::sys;
use crate::types::{DebugSeverity, DebugSource, DebugType};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DebugMessage {
pub source: DebugSource,
pub message_type: DebugType,
pub id: u32,
pub severity: DebugSeverity,
pub message: String,
}
type BoxedCallback = Box<dyn FnMut(DebugMessage) + 'static>;
pub struct DebugGuard {
ctx: Rc<GlInner>,
user_data: *mut BoxedCallback,
}
impl fmt::Debug for DebugGuard {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DebugGuard")
.field("active", &(!self.user_data.is_null()))
.finish()
}
}
impl Drop for DebugGuard {
fn drop(&mut self) {
if let Some(set_cb) = self.ctx.fns.debug_message_callback {
unsafe {
set_cb(None, ptr::null());
(self.ctx.fns.disable)(sys::GL_DEBUG_OUTPUT);
}
}
if !self.user_data.is_null() {
let _ = unsafe { Box::from_raw(self.user_data) };
self.user_data = ptr::null_mut();
}
}
}
impl DebugGuard {
pub fn new<F>(ctx: &GlContext, synchronous: bool, callback: F) -> Result<Self>
where
F: FnMut(DebugMessage) + 'static,
{
let Some(set_cb) = ctx.inner.fns.debug_message_callback else {
return Err(GlError::MissingFunction {
name: "glDebugMessageCallback",
});
};
let boxed: Box<BoxedCallback> = Box::new(Box::new(callback));
let user_data = Box::into_raw(boxed);
unsafe {
(ctx.inner.fns.enable)(sys::GL_DEBUG_OUTPUT);
if synchronous {
(ctx.inner.fns.enable)(sys::GL_DEBUG_OUTPUT_SYNCHRONOUS);
} else {
(ctx.inner.fns.disable)(sys::GL_DEBUG_OUTPUT_SYNCHRONOUS);
}
set_cb(Some(debug_trampoline), user_data.cast::<c_void>());
if let Some(control) = ctx.inner.fns.debug_message_control {
control(
sys::GL_DONT_CARE,
sys::GL_DONT_CARE,
sys::GL_DONT_CARE,
0,
ptr::null(),
sys::GL_TRUE,
);
}
}
Ok(Self {
ctx: Rc::clone(&ctx.inner),
user_data,
})
}
}
unsafe extern "system" fn debug_trampoline(
source: sys::GLenum,
gltype: sys::GLenum,
id: sys::GLuint,
severity: sys::GLenum,
length: sys::GLsizei,
message: *const sys::GLchar,
user_param: *mut c_void,
) {
if user_param.is_null() {
return;
}
let text = if message.is_null() {
String::new()
} else if length > 0 {
let bytes = unsafe { std::slice::from_raw_parts(message.cast::<u8>(), length as usize) };
String::from_utf8_lossy(bytes).into_owned()
} else {
let cstr = unsafe { CStr::from_ptr(message) };
cstr.to_string_lossy().into_owned()
};
let msg = DebugMessage {
source: DebugSource::from_raw(source),
message_type: DebugType::from_raw(gltype),
id,
severity: DebugSeverity::from_raw(severity),
message: text,
};
let cb = unsafe { &mut *user_param.cast::<BoxedCallback>() };
let _ = panic::catch_unwind(AssertUnwindSafe(|| {
cb(msg);
}));
}