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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
//! A cross platform OpenGL surface representation.
#![allow(unreachable_patterns)]

use std::marker::PhantomData;
use std::num::NonZeroU32;

use raw_window_handle::RawWindowHandle;

use crate::context::{PossiblyCurrentContext, PossiblyCurrentGlContext};
use crate::display::{Display, GetGlDisplay};
use crate::error::Result;
use crate::private::{gl_api_dispatch, Sealed};

#[cfg(cgl_backend)]
use crate::api::cgl::surface::Surface as CglSurface;
#[cfg(egl_backend)]
use crate::api::egl::surface::Surface as EglSurface;
#[cfg(glx_backend)]
use crate::api::glx::surface::Surface as GlxSurface;
#[cfg(wgl_backend)]
use crate::api::wgl::surface::Surface as WglSurface;

/// A trait to group common operations on the surface.
pub trait GlSurface<T: SurfaceTypeTrait>: Sealed {
    /// The type of the surface.
    type SurfaceType: SurfaceTypeTrait;
    /// The context to access surface data.
    type Context: PossiblyCurrentGlContext;

    /// The age of the back buffer of that surface. The `0` indicates that the
    /// buffer is either a new one or we failed to get the information about
    /// its age. In both cases you must redraw the entire buffer.
    ///
    /// # Platform-specific
    ///
    /// - **Wayland:** this call will latch the underlying back buffer, meaning
    ///   that all resize operations will apply after the next
    ///   [`GlSurface::swap_buffers`].
    fn buffer_age(&self) -> u32;

    /// The **physical** width of the underlying surface.
    fn width(&self) -> Option<u32>;

    /// The **physical** height of the underlying surface.
    ///
    /// # Platform specific
    ///
    /// - **macOS: this will block if your main thread is blocked.**
    fn height(&self) -> Option<u32>;

    /// Check whether the surface is single buffered.
    ///
    /// # Platform specific
    ///
    /// - **macOS: this will block if your main thread is blocked.**
    fn is_single_buffered(&self) -> bool;

    /// Swaps the underlying back buffers when the surface is not single
    /// buffered.
    fn swap_buffers(&self, context: &Self::Context) -> Result<()>;

    /// Check whether the surface is current on to the current thread.
    fn is_current(&self, context: &Self::Context) -> bool;

    /// Check whether the surface is the current draw surface to the current
    /// thread.
    fn is_current_draw(&self, context: &Self::Context) -> bool;

    /// Check whether the surface is the current read surface to the current
    /// thread.
    fn is_current_read(&self, context: &Self::Context) -> bool;

    /// Set swap interval for the surface.
    ///
    /// See [`crate::surface::SwapInterval`] for details.
    fn set_swap_interval(&self, context: &Self::Context, interval: SwapInterval) -> Result<()>;

    /// Resize the surface to a new size.
    ///
    /// This call is for compatibility reasons, on most platforms it's a no-op.
    /// It's recommended to call this function before doing any rendering and
    /// performing [`PossiblyCurrentGlContext::make_current`], and
    /// [`GlSurface::buffer_age`].
    ///
    /// # Platform specific
    ///
    /// - **Wayland:** resizes the surface;
    /// - **macOS: this will block if your main thread is blocked;**
    /// - **Other:** no op.
    fn resize(&self, context: &Self::Context, width: NonZeroU32, height: NonZeroU32)
    where
        Self::SurfaceType: ResizeableSurface;
}

/// The marker trait to indicate the type of the surface.
pub trait SurfaceTypeTrait: Sealed {
    /// Get the type of the surface.
    fn surface_type() -> SurfaceType;
}

/// Marker indicating that the surface could be resized.
pub trait ResizeableSurface: Sealed {}

/// Trait for accessing the raw GL surface.
pub trait AsRawSurface {
    /// Get the raw handle to the surface.
    fn raw_surface(&self) -> RawSurface;
}

/// Builder to get the required set of attributes initialized before hand.
#[derive(Default, Debug, Clone)]
pub struct SurfaceAttributesBuilder<T: SurfaceTypeTrait + Default> {
    attributes: SurfaceAttributes<T>,
}

impl<T: SurfaceTypeTrait + Default> SurfaceAttributesBuilder<T> {
    /// Get new surface attributes.
    pub fn new() -> Self {
        Default::default()
    }

    /// Specify whether the surface should support srgb or not. Passing `None`
    /// means you don't care.
    ///
    /// # Api-specific.
    ///
    /// This only controls EGL surfaces, other platforms use the context for
    /// that.
    pub fn with_srgb(mut self, srgb: Option<bool>) -> Self {
        self.attributes.srgb = srgb;
        self
    }
}

impl SurfaceAttributesBuilder<WindowSurface> {
    /// Specify whether the single buffer should be used instead of double
    /// buffering. This doesn't guarantee that the resulted buffer will have
    /// only single buffer, to know that the single buffer is actually used
    /// query the created surface with [`Surface::is_single_buffered`].
    ///
    /// The surface is requested as double buffered by default.
    ///
    /// # Api-specific.
    ///
    /// This is EGL specific, other platforms use the context for that.
    pub fn with_single_buffer(mut self, single_buffer: bool) -> Self {
        self.attributes.single_buffer = single_buffer;
        self
    }

    /// Build the surface attributes suitable to create a window surface.
    pub fn build(
        mut self,
        raw_window_handle: RawWindowHandle,
        width: NonZeroU32,
        height: NonZeroU32,
    ) -> SurfaceAttributes<WindowSurface> {
        self.attributes.raw_window_handle = Some(raw_window_handle);
        self.attributes.width = Some(width);
        self.attributes.height = Some(height);
        self.attributes
    }
}

impl SurfaceAttributesBuilder<PbufferSurface> {
    /// Request the largest pbuffer.
    pub fn with_largest_pbuffer(mut self, largest_pbuffer: bool) -> Self {
        self.attributes.largest_pbuffer = largest_pbuffer;
        self
    }

    /// The same as in
    /// [`SurfaceAttributesBuilder::<WindowSurface>::with_single_buffer`].
    pub fn with_single_buffer(mut self, single_buffer: bool) -> Self {
        self.attributes.single_buffer = single_buffer;
        self
    }

    /// Build the surface attributes suitable to create a pbuffer surface.
    pub fn build(
        mut self,
        width: NonZeroU32,
        height: NonZeroU32,
    ) -> SurfaceAttributes<PbufferSurface> {
        self.attributes.width = Some(width);
        self.attributes.height = Some(height);
        self.attributes
    }
}

impl SurfaceAttributesBuilder<PixmapSurface> {
    /// Build the surface attributes suitable to create a pixmap surface.
    pub fn build(mut self, native_pixmap: NativePixmap) -> SurfaceAttributes<PixmapSurface> {
        self.attributes.native_pixmap = Some(native_pixmap);
        self.attributes
    }
}

/// Attributes which are used for creating a particular surface.
#[derive(Default, Debug, Clone)]
pub struct SurfaceAttributes<T: SurfaceTypeTrait> {
    pub(crate) srgb: Option<bool>,
    pub(crate) single_buffer: bool,
    pub(crate) width: Option<NonZeroU32>,
    pub(crate) height: Option<NonZeroU32>,
    pub(crate) largest_pbuffer: bool,
    pub(crate) raw_window_handle: Option<RawWindowHandle>,
    pub(crate) native_pixmap: Option<NativePixmap>,
    _ty: PhantomData<T>,
}

/// Marker that used to type-gate methods for window.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
pub struct WindowSurface;

impl SurfaceTypeTrait for WindowSurface {
    fn surface_type() -> SurfaceType {
        SurfaceType::Window
    }
}

impl ResizeableSurface for WindowSurface {}

impl Sealed for WindowSurface {}

/// Marker that used to type-gate methods for pbuffer.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
pub struct PbufferSurface;

impl SurfaceTypeTrait for PbufferSurface {
    fn surface_type() -> SurfaceType {
        SurfaceType::Pbuffer
    }
}

impl Sealed for PbufferSurface {}

/// Marker that used to type-gate methods for pixmap.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
pub struct PixmapSurface;

impl SurfaceTypeTrait for PixmapSurface {
    fn surface_type() -> SurfaceType {
        SurfaceType::Pixmap
    }
}

impl Sealed for PixmapSurface {}

/// The underlying type of the surface.
#[derive(Debug, Clone, Copy)]
pub enum SurfaceType {
    /// The window surface.
    Window,

    /// Pixmap surface.
    Pixmap,

    /// Pbuffer surface.
    Pbuffer,
}

/// The GL surface that is used for rendering.
///
/// The GL surface is not thread safe, it can neither be [`Send`] nor [`Sync`],
/// so it should be created on the thread it'll be used to render.
///
/// ```compile_fail
/// fn test_send<T: Send>() {}
/// test_send::<glutin::surface::Surface<glutin::surface::WindowSurface>>();
/// ```
/// ```compile_fail
/// fn test_sync<T: Sync>() {}
/// test_sync::<glutin::surface::Surface<glutin::surface::WindowSurface>>();
/// ```
#[derive(Debug)]
pub enum Surface<T: SurfaceTypeTrait> {
    /// The EGL surface.
    #[cfg(egl_backend)]
    Egl(EglSurface<T>),

    /// The GLX surface.
    #[cfg(glx_backend)]
    Glx(GlxSurface<T>),

    /// The WGL surface.
    #[cfg(wgl_backend)]
    Wgl(WglSurface<T>),

    /// The CGL surface.
    #[cfg(cgl_backend)]
    Cgl(CglSurface<T>),
}

impl<T: SurfaceTypeTrait> GlSurface<T> for Surface<T> {
    type Context = PossiblyCurrentContext;
    type SurfaceType = T;

    fn buffer_age(&self) -> u32 {
        gl_api_dispatch!(self; Self(surface) => surface.buffer_age())
    }

    fn width(&self) -> Option<u32> {
        gl_api_dispatch!(self; Self(surface) => surface.width())
    }

    fn height(&self) -> Option<u32> {
        gl_api_dispatch!(self; Self(surface) => surface.height())
    }

    fn is_single_buffered(&self) -> bool {
        gl_api_dispatch!(self; Self(surface) => surface.is_single_buffered())
    }

    fn swap_buffers(&self, context: &Self::Context) -> Result<()> {
        match (self, context) {
            #[cfg(egl_backend)]
            (Self::Egl(surface), PossiblyCurrentContext::Egl(context)) => {
                surface.swap_buffers(context)
            },
            #[cfg(glx_backend)]
            (Self::Glx(surface), PossiblyCurrentContext::Glx(context)) => {
                surface.swap_buffers(context)
            },
            #[cfg(cgl_backend)]
            (Self::Cgl(surface), PossiblyCurrentContext::Cgl(context)) => {
                surface.swap_buffers(context)
            },
            #[cfg(wgl_backend)]
            (Self::Wgl(surface), PossiblyCurrentContext::Wgl(context)) => {
                surface.swap_buffers(context)
            },
            _ => unreachable!(),
        }
    }

    fn set_swap_interval(&self, context: &Self::Context, interval: SwapInterval) -> Result<()> {
        match (self, context) {
            #[cfg(egl_backend)]
            (Self::Egl(surface), PossiblyCurrentContext::Egl(context)) => {
                surface.set_swap_interval(context, interval)
            },
            #[cfg(glx_backend)]
            (Self::Glx(surface), PossiblyCurrentContext::Glx(context)) => {
                surface.set_swap_interval(context, interval)
            },
            #[cfg(cgl_backend)]
            (Self::Cgl(surface), PossiblyCurrentContext::Cgl(context)) => {
                surface.set_swap_interval(context, interval)
            },
            #[cfg(wgl_backend)]
            (Self::Wgl(surface), PossiblyCurrentContext::Wgl(context)) => {
                surface.set_swap_interval(context, interval)
            },
            _ => unreachable!(),
        }
    }

    fn is_current(&self, context: &Self::Context) -> bool {
        match (self, context) {
            #[cfg(egl_backend)]
            (Self::Egl(surface), PossiblyCurrentContext::Egl(context)) => {
                surface.is_current(context)
            },
            #[cfg(glx_backend)]
            (Self::Glx(surface), PossiblyCurrentContext::Glx(context)) => {
                surface.is_current(context)
            },
            #[cfg(cgl_backend)]
            (Self::Cgl(surface), PossiblyCurrentContext::Cgl(context)) => {
                surface.is_current(context)
            },
            #[cfg(wgl_backend)]
            (Self::Wgl(surface), PossiblyCurrentContext::Wgl(context)) => {
                surface.is_current(context)
            },
            _ => unreachable!(),
        }
    }

    fn is_current_draw(&self, context: &Self::Context) -> bool {
        match (self, context) {
            #[cfg(egl_backend)]
            (Self::Egl(surface), PossiblyCurrentContext::Egl(context)) => {
                surface.is_current_draw(context)
            },
            #[cfg(glx_backend)]
            (Self::Glx(surface), PossiblyCurrentContext::Glx(context)) => {
                surface.is_current_draw(context)
            },
            #[cfg(cgl_backend)]
            (Self::Cgl(surface), PossiblyCurrentContext::Cgl(context)) => {
                surface.is_current_draw(context)
            },
            #[cfg(wgl_backend)]
            (Self::Wgl(surface), PossiblyCurrentContext::Wgl(context)) => {
                surface.is_current_draw(context)
            },
            _ => unreachable!(),
        }
    }

    fn is_current_read(&self, context: &Self::Context) -> bool {
        match (self, context) {
            #[cfg(egl_backend)]
            (Self::Egl(surface), PossiblyCurrentContext::Egl(context)) => {
                surface.is_current_read(context)
            },
            #[cfg(glx_backend)]
            (Self::Glx(surface), PossiblyCurrentContext::Glx(context)) => {
                surface.is_current_read(context)
            },
            #[cfg(cgl_backend)]
            (Self::Cgl(surface), PossiblyCurrentContext::Cgl(context)) => {
                surface.is_current_read(context)
            },
            #[cfg(wgl_backend)]
            (Self::Wgl(surface), PossiblyCurrentContext::Wgl(context)) => {
                surface.is_current_read(context)
            },
            _ => unreachable!(),
        }
    }

    fn resize(&self, context: &Self::Context, width: NonZeroU32, height: NonZeroU32)
    where
        Self::SurfaceType: ResizeableSurface,
    {
        match (self, context) {
            #[cfg(egl_backend)]
            (Self::Egl(surface), PossiblyCurrentContext::Egl(context)) => {
                surface.resize(context, width, height)
            },
            #[cfg(glx_backend)]
            (Self::Glx(surface), PossiblyCurrentContext::Glx(context)) => {
                surface.resize(context, width, height)
            },
            #[cfg(cgl_backend)]
            (Self::Cgl(surface), PossiblyCurrentContext::Cgl(context)) => {
                surface.resize(context, width, height)
            },
            #[cfg(wgl_backend)]
            (Self::Wgl(surface), PossiblyCurrentContext::Wgl(context)) => {
                surface.resize(context, width, height)
            },
            _ => unreachable!(),
        }
    }
}

impl<T: SurfaceTypeTrait> GetGlDisplay for Surface<T> {
    type Target = Display;

    fn display(&self) -> Self::Target {
        gl_api_dispatch!(self; Self(surface) => surface.display(); as Display)
    }
}

impl<T: SurfaceTypeTrait> AsRawSurface for Surface<T> {
    fn raw_surface(&self) -> RawSurface {
        gl_api_dispatch!(self; Self(surface) => surface.raw_surface())
    }
}

impl<T: SurfaceTypeTrait> Sealed for Surface<T> {}

/// A swap interval.
///
/// The default swap interval for your [`Surface`] is platform-dependent. For
/// example, on EGL it is `1` by default, but on GLX it is `0` by default.
///
/// Please note that your application's desired swap interval may be overridden
/// by external, driver-specific configuration, which means that you can't know
/// in advance whether [`crate::surface::GlSurface::swap_buffers`] will block
/// or not.
///
/// # Platform specific
///
/// - **Wayland:** when the window is hidden and [`SwapInterval::Wait`] is used
///   [`GlSurface::swap_buffers`] and any functions based on it may block until
///   the window is visible again. Using this variant is not recommended on
///   Wayland and instead the throttling should be performed by [`frame
///   callbacks`].
///
/// [`frame callbacks`]: https://wayland.freedesktop.org/docs/html/apa.html#protocol-spec-wl_surface-request-frame
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SwapInterval {
    /// When this variant is used calling
    /// `[crate::surface::GlSurface::swap_buffers]` will not block.
    DontWait,

    /// The swap is synchronized to the `n`'th video frame. This is typically
    /// set to `1` to enable vsync and prevent screen tearing.
    Wait(NonZeroU32),
}

/// A platform native pixmap.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NativePixmap {
    /// XID of X11 pixmap.
    XlibPixmap(std::os::raw::c_ulong),

    /// XID of X11 pixmap from xcb.
    XcbPixmap(u32),

    /// HBITMAP handle for windows bitmap.
    WindowsPixmap(isize),
}

/// Handle to the raw OpenGL surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RawSurface {
    /// A pointer to EGLSurface.
    #[cfg(egl_backend)]
    Egl(*const std::ffi::c_void),

    /// GLXDrawable.
    #[cfg(glx_backend)]
    Glx(u64),

    /// HWND
    #[cfg(wgl_backend)]
    Wgl(*const std::ffi::c_void),

    /// Pointer to `NSView`.
    #[cfg(cgl_backend)]
    Cgl(*const std::ffi::c_void),
}

/// The rect that is being used in various surface operations.
///
/// The origin is in the bottom left of the surface.
#[repr(C)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Rect {
    /// `X` of the origin.
    pub x: i32,
    /// `Y` of the origin.
    pub y: i32,
    /// Rect width.
    pub width: i32,
    /// Rect height.
    pub height: i32,
}

impl Rect {
    /// Helper to simplify rectangle creation.
    pub fn new(x: i32, y: i32, width: i32, height: i32) -> Self {
        Self { x, y, width, height }
    }
}