1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
|
use std::cell::RefCell;
use std::ffi::{c_int, CStr, CString};
use std::panic::catch_unwind;
use std::ptr::null_mut;
use crate::init::{initialize, Glfw};
use crate::{get_glfw_error, Error};
#[derive(Debug)]
pub struct Window
{
_init: Glfw,
handle: *mut crate::ffi::GLFWwindow,
}
impl Window
{
/// Makes the context of the window current for the calling thread.
///
/// # Errors
/// Will return `Err` if a GLFW platform error occurs or if no OpenGL context is
/// present.
pub fn make_context_current(&self) -> Result<(), Error>
{
unsafe { crate::ffi::glfwMakeContextCurrent(self.handle) };
get_glfw_error()?;
Ok(())
}
/// Returns the address of the specified OpenGL function, if it is supported by the
/// current context.
///
/// # Errors
/// Will return `Err` if a GLFW platform error occurs or if no current context has
/// been set.
pub fn get_proc_address(
&self,
proc_name: &CStr,
) -> Result<unsafe extern "C" fn(), Error>
{
let proc_addr = unsafe { crate::ffi::glfwGetProcAddress(proc_name.as_ptr()) };
get_glfw_error()?;
// SAFETY: Is only None when a error has occured and that case is handled above
Ok(unsafe { proc_addr.unwrap_unchecked() })
}
/// Processes all pending events.
///
/// # Errors
/// Will return `Err` if a GLFW platform error occurs.
pub fn poll_events(&self) -> Result<(), Error>
{
// SAFETY: The initialize function (called when the window is created) makes sure
// the current thread is the main thread
unsafe { crate::ffi::glfwPollEvents() };
get_glfw_error()?;
Ok(())
}
/// Swaps the front and back buffers of the window.
///
/// # Errors
/// Will return `Err` if a GLFW platform error occurs or if no OpenGL window context
/// is present.
pub fn swap_buffers(&self) -> Result<(), Error>
{
unsafe {
crate::ffi::glfwSwapBuffers(self.handle);
};
get_glfw_error()?;
Ok(())
}
/// Returns whether or not the window should close.
#[must_use]
pub fn should_close(&self) -> bool
{
let should_close = unsafe { crate::ffi::glfwWindowShouldClose(self.handle) };
should_close == crate::ffi::GLFW_TRUE
}
/// Retrieves the size of the window.
///
/// # Errors
/// Will return `Err` if a GLFW platform error occurs.
pub fn size(&self) -> Result<Size, Error>
{
let mut width = 0;
let mut height = 0;
// SAFETY: The initialize function (called when the window is created) makes sure
// the current thread is the main thread
unsafe { crate::ffi::glfwGetWindowSize(self.handle, &mut width, &mut height) };
get_glfw_error()?;
#[allow(clippy::cast_sign_loss)]
Ok(Size {
width: width as u32,
height: height as u32,
})
}
pub fn set_framebuffer_size_callback(&self, callback: impl Fn(Size) + 'static)
{
FRAMEBUFFER_SIZE_CB.with_borrow_mut(|framebuffer_size_cb| {
*framebuffer_size_cb = Some(Box::new(callback));
});
// SAFETY: The initialize function (called when the window is created) makes sure
// the current thread is the main thread
unsafe {
crate::ffi::glfwSetFramebufferSizeCallback(
self.handle,
Some(framebuffer_size_callback),
);
}
}
}
/// [`Window`] builder.
#[derive(Debug, Clone, Default)]
pub struct Builder
{
hints: Vec<(Hint, i32)>,
}
impl Builder
{
#[must_use]
pub fn new() -> Self
{
Self { hints: Vec::new() }
}
/// Adds a window creation hint to set.
#[must_use]
pub fn hint(mut self, hint: Hint, value: i32) -> Self
{
self.hints.push((hint, value));
self
}
/// Sets the window hints to set.
pub fn hints(mut self, hints: impl IntoIterator<Item = (Hint, i32)>)
{
self.hints = hints.into_iter().collect();
}
/// Creates a new window.
///
/// # Errors
/// Will return `Err` if
/// - The title contains an internal nul byte
/// - A GLFW error occurs
pub fn create(&self, size: &Size, title: &str) -> Result<Window, Error>
{
let c_title =
CString::new(title).map_err(|_| Error::InternalNulByteInWindowTitle)?;
let init = initialize()?;
for (hint, value) in &self.hints {
// SAFETY: The initialize function makes sure the current thread is the main
// thread
//
// Error is not checked for after since the two possible errors
// (GLFW_NOT_INITIALIZED and GLFW_INVALID_ENUM) cannot occur.
unsafe {
crate::ffi::glfwWindowHint(hint.to_glfw(), *value);
}
}
// SAFETY: The initialize function makes sure the current thread is the main
// thread
let handle = unsafe {
#[allow(clippy::cast_possible_wrap)]
crate::ffi::glfwCreateWindow(
size.width as i32,
size.height as i32,
c_title.as_ptr(),
null_mut(),
null_mut(),
)
};
get_glfw_error()?;
Ok(Window {
_init: init,
handle,
})
}
}
/// Window creation hint
#[derive(Debug, Clone, Copy)]
pub enum Hint
{
OpenGLDebugContext,
}
impl Hint
{
fn to_glfw(self) -> c_int
{
match self {
Self::OpenGLDebugContext => crate::ffi::GLFW_OPENGL_DEBUG_CONTEXT,
}
}
}
/// Window size.
pub struct Size
{
pub width: u32,
pub height: u32,
}
type FramebufferSizeCb = Box<dyn Fn(Size)>;
thread_local! {
static FRAMEBUFFER_SIZE_CB: RefCell<Option<FramebufferSizeCb>> = RefCell::new(None);
}
extern "C" fn framebuffer_size_callback(
_window: *mut crate::ffi::GLFWwindow,
c_width: c_int,
c_height: c_int,
)
{
// Width and height can't possibly have their sign bit set
let width = u32::from_le_bytes(c_width.to_le_bytes());
let height = u32::from_le_bytes(c_height.to_le_bytes());
// Unwinds are catched because unwinding from Rust code into foreign code is UB.
let res = catch_unwind(|| {
FRAMEBUFFER_SIZE_CB
.try_with(|framebuffer_size_cb| {
if let Some(cb) = framebuffer_size_cb.borrow().as_deref() {
cb(Size { width, height });
}
})
.ok();
});
if res.is_err() {
println!("ERROR: Panic in framebuffer size callback");
}
}
|