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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
//! The OpenGL platform display selection and creation.
#![allow(unreachable_patterns)]

use std::collections::HashSet;
use std::ffi::{self, CStr};
use std::fmt;

use bitflags::bitflags;
use raw_window_handle::RawDisplayHandle;

use crate::config::{Config, ConfigTemplate, GlConfig};
use crate::context::{ContextAttributes, NotCurrentContext, NotCurrentGlContext};
use crate::error::Result;
use crate::private::{gl_api_dispatch, Sealed};
use crate::surface::{
    GlSurface, PbufferSurface, PixmapSurface, Surface, SurfaceAttributes, WindowSurface,
};

#[cfg(cgl_backend)]
use crate::api::cgl::display::Display as CglDisplay;
#[cfg(egl_backend)]
use crate::api::egl::display::Display as EglDisplay;
#[cfg(glx_backend)]
use crate::api::glx::display::Display as GlxDisplay;
#[cfg(glx_backend)]
use crate::api::glx::XlibErrorHookRegistrar;
#[cfg(wgl_backend)]
use crate::api::wgl::display::Display as WglDisplay;

/// A trait to group common display operations.
pub trait GlDisplay: Sealed {
    /// A window surface created by the display.
    type WindowSurface: GlSurface<WindowSurface>;
    /// A pixmap surface created by the display.
    type PixmapSurface: GlSurface<PixmapSurface>;
    /// A pbuffer surface created by the display.
    type PbufferSurface: GlSurface<PbufferSurface>;
    /// A config that is used by the display.
    type Config: GlConfig;
    /// A context that is being used by the display.
    type NotCurrentContext: NotCurrentGlContext;

    /// Find configurations matching the given `template`.
    ///
    /// # Safety
    ///
    /// Some platforms use [`RawWindowHandle`] to pick configs, so it
    /// must point to a valid object if it was passed on
    /// [`crate::config::ConfigTemplate`].
    ///
    /// [`RawWindowHandle`]: raw_window_handle::RawWindowHandle
    unsafe fn find_configs(
        &self,
        template: ConfigTemplate,
    ) -> Result<Box<dyn Iterator<Item = Self::Config> + '_>>;

    /// Create the graphics platform context.
    ///
    /// # Safety
    ///
    /// Some platforms use [`RawWindowHandle`] for context creation, so it must
    /// point to a valid object.
    ///
    /// # Platform-specific
    ///
    /// - **Wayland:** this call may latch the underlying back buffer of the
    ///   currently active context (will do with mesa drivers), meaning that all
    ///   resize operations will apply to it after the next
    ///   [`GlSurface::swap_buffers`]. To workaround this behavior the current
    ///   context should be made [`not current`].
    ///
    /// [`RawWindowHandle`]: raw_window_handle::RawWindowHandle
    /// [`not current`]: crate::context::PossiblyCurrentGlContext::make_not_current
    unsafe fn create_context(
        &self,
        config: &Self::Config,
        context_attributes: &ContextAttributes,
    ) -> Result<Self::NotCurrentContext>;

    /// Create the surface that can be used to render into native window.
    ///
    /// # Safety
    ///
    /// The [`RawWindowHandle`] must point to a valid object.
    ///
    /// [`RawWindowHandle`]: raw_window_handle::RawWindowHandle
    unsafe fn create_window_surface(
        &self,
        config: &Self::Config,
        surface_attributes: &SurfaceAttributes<WindowSurface>,
    ) -> Result<Self::WindowSurface>;

    /// Create the surface that can be used to render into pbuffer.
    ///
    /// # Safety
    ///
    /// The function is safe in general, but marked as not for compatibility
    /// reasons.
    unsafe fn create_pbuffer_surface(
        &self,
        config: &Self::Config,
        surface_attributes: &SurfaceAttributes<PbufferSurface>,
    ) -> Result<Self::PbufferSurface>;

    /// Create the surface that can be used to render into pixmap.
    ///
    /// # Safety
    ///
    /// The [`NativePixmap`] must represent a valid native pixmap.
    ///
    /// [`NativePixmap`]: crate::surface::NativePixmap
    unsafe fn create_pixmap_surface(
        &self,
        config: &Self::Config,
        surface_attributes: &SurfaceAttributes<PixmapSurface>,
    ) -> Result<Self::PixmapSurface>;

    /// Return the address of an OpenGL function.
    ///
    /// # Api-specific
    ///
    /// - **WGL:** to load all the functions you must have a current context on
    ///   the calling thread, otherwise only a limited set of functions will be
    ///   loaded.
    fn get_proc_address(&self, addr: &CStr) -> *const ffi::c_void;

    /// Helper to obtain the information about the underlying display.
    ///
    /// This function is intended to be used for logging purposes to help with
    /// troubleshooting issues.
    fn version_string(&self) -> String;

    /// Get the features supported by the display.
    ///
    /// These features could be used to check that something is supported
    /// beforehand instead of doing fallback.
    fn supported_features(&self) -> DisplayFeatures;
}

/// Get the [`Display`].
pub trait GetGlDisplay: Sealed {
    /// The display used by the object.
    type Target: GlDisplay;

    /// Obtain the GL display used to create a particular GL object.
    fn display(&self) -> Self::Target;
}

/// Obtain the underlying api extensions.
pub trait GetDisplayExtensions: Sealed {
    /// Supported extensions by the display.
    ///
    /// # Api-specific
    ///
    /// - **WGL:** to have extensions loaded, `raw_window_handle` must be used
    ///   when creating the display.
    fn extensions(&self) -> &HashSet<&'static str>;
}

/// Get the raw handle to the [`Display`].
pub trait AsRawDisplay {
    /// A raw handle to the underlying Api display.
    fn raw_display(&self) -> RawDisplay;
}

/// The graphics display to handle underlying graphics platform in a
/// cross-platform way.
///
/// The display can be accessed from any thread.
///
/// ```no_run
/// fn test_send<T: Send>() {}
/// fn test_sync<T: Sync>() {}
/// test_send::<glutin::display::Display>();
/// test_sync::<glutin::display::Display>();
/// ```
#[derive(Debug, Clone)]
pub enum Display {
    /// The EGL display.
    #[cfg(egl_backend)]
    Egl(EglDisplay),

    /// The GLX display.
    #[cfg(glx_backend)]
    Glx(GlxDisplay),

    /// The WGL display.
    #[cfg(wgl_backend)]
    Wgl(WglDisplay),

    /// The CGL display.
    #[cfg(cgl_backend)]
    Cgl(CglDisplay),
}

impl Display {
    /// Create a graphics platform display from the given raw display handle.
    ///
    /// The display mixing isn't supported, so if you created EGL display you
    /// can't use it with the GLX display objects. Interaction between those
    /// will result in a runtime panic.
    ///
    /// # Safety
    ///
    /// The `display` must point to the valid platform display and be valid for
    /// the entire lifetime of all Objects created with that display.
    ///
    /// The `preference` must contain pointers to the valid values if GLX or WGL
    /// specific options were used.
    pub unsafe fn new(display: RawDisplayHandle, preference: DisplayApiPreference) -> Result<Self> {
        match preference {
            #[cfg(egl_backend)]
            DisplayApiPreference::Egl => unsafe { Ok(Self::Egl(EglDisplay::new(display)?)) },
            #[cfg(glx_backend)]
            DisplayApiPreference::Glx(registrar) => unsafe {
                Ok(Self::Glx(GlxDisplay::new(display, registrar)?))
            },
            #[cfg(all(egl_backend, glx_backend))]
            DisplayApiPreference::GlxThenEgl(registrar) => unsafe {
                if let Ok(display) = GlxDisplay::new(display, registrar) {
                    Ok(Self::Glx(display))
                } else {
                    Ok(Self::Egl(EglDisplay::new(display)?))
                }
            },
            #[cfg(all(egl_backend, glx_backend))]
            DisplayApiPreference::EglThenGlx(registrar) => unsafe {
                if let Ok(display) = EglDisplay::new(display) {
                    Ok(Self::Egl(display))
                } else {
                    Ok(Self::Glx(GlxDisplay::new(display, registrar)?))
                }
            },
            #[cfg(wgl_backend)]
            DisplayApiPreference::Wgl(window_handle) => unsafe {
                Ok(Self::Wgl(WglDisplay::new(display, window_handle)?))
            },
            #[cfg(all(egl_backend, wgl_backend))]
            DisplayApiPreference::EglThenWgl(window_handle) => unsafe {
                if let Ok(display) = EglDisplay::new(display) {
                    Ok(Self::Egl(display))
                } else {
                    Ok(Self::Wgl(WglDisplay::new(display, window_handle)?))
                }
            },
            #[cfg(all(egl_backend, wgl_backend))]
            DisplayApiPreference::WglThenEgl(window_handle) => unsafe {
                if let Ok(display) = WglDisplay::new(display, window_handle) {
                    Ok(Self::Wgl(display))
                } else {
                    Ok(Self::Egl(EglDisplay::new(display)?))
                }
            },
            #[cfg(cgl_backend)]
            DisplayApiPreference::Cgl => unsafe { Ok(Self::Cgl(CglDisplay::new(display)?)) },
        }
    }
}

impl GlDisplay for Display {
    type Config = Config;
    type NotCurrentContext = NotCurrentContext;
    type PbufferSurface = Surface<PbufferSurface>;
    type PixmapSurface = Surface<PixmapSurface>;
    type WindowSurface = Surface<WindowSurface>;

    unsafe fn find_configs(
        &self,
        template: ConfigTemplate,
    ) -> Result<Box<dyn Iterator<Item = Self::Config> + '_>> {
        match self {
            #[cfg(egl_backend)]
            Self::Egl(display) => unsafe {
                Ok(Box::new(display.find_configs(template)?.map(Config::Egl)))
            },
            #[cfg(glx_backend)]
            Self::Glx(display) => unsafe {
                Ok(Box::new(display.find_configs(template)?.map(Config::Glx)))
            },
            #[cfg(wgl_backend)]
            Self::Wgl(display) => unsafe {
                Ok(Box::new(display.find_configs(template)?.map(Config::Wgl)))
            },
            #[cfg(cgl_backend)]
            Self::Cgl(display) => unsafe {
                Ok(Box::new(display.find_configs(template)?.map(Config::Cgl)))
            },
        }
    }

    unsafe fn create_context(
        &self,
        config: &Self::Config,
        context_attributes: &ContextAttributes,
    ) -> Result<Self::NotCurrentContext> {
        match (self, config) {
            #[cfg(egl_backend)]
            (Self::Egl(display), Config::Egl(config)) => unsafe {
                Ok(NotCurrentContext::Egl(display.create_context(config, context_attributes)?))
            },
            #[cfg(glx_backend)]
            (Self::Glx(display), Config::Glx(config)) => unsafe {
                Ok(NotCurrentContext::Glx(display.create_context(config, context_attributes)?))
            },
            #[cfg(wgl_backend)]
            (Self::Wgl(display), Config::Wgl(config)) => unsafe {
                Ok(NotCurrentContext::Wgl(display.create_context(config, context_attributes)?))
            },
            #[cfg(cgl_backend)]
            (Self::Cgl(display), Config::Cgl(config)) => unsafe {
                Ok(NotCurrentContext::Cgl(display.create_context(config, context_attributes)?))
            },
            _ => unreachable!(),
        }
    }

    unsafe fn create_window_surface(
        &self,
        config: &Self::Config,
        surface_attributes: &SurfaceAttributes<WindowSurface>,
    ) -> Result<Self::WindowSurface> {
        match (self, config) {
            #[cfg(egl_backend)]
            (Self::Egl(display), Config::Egl(config)) => unsafe {
                Ok(Surface::Egl(display.create_window_surface(config, surface_attributes)?))
            },
            #[cfg(glx_backend)]
            (Self::Glx(display), Config::Glx(config)) => unsafe {
                Ok(Surface::Glx(display.create_window_surface(config, surface_attributes)?))
            },
            #[cfg(wgl_backend)]
            (Self::Wgl(display), Config::Wgl(config)) => unsafe {
                Ok(Surface::Wgl(display.create_window_surface(config, surface_attributes)?))
            },
            #[cfg(cgl_backend)]
            (Self::Cgl(display), Config::Cgl(config)) => unsafe {
                Ok(Surface::Cgl(display.create_window_surface(config, surface_attributes)?))
            },
            _ => unreachable!(),
        }
    }

    unsafe fn create_pbuffer_surface(
        &self,
        config: &Self::Config,
        surface_attributes: &SurfaceAttributes<PbufferSurface>,
    ) -> Result<Self::PbufferSurface> {
        match (self, config) {
            #[cfg(egl_backend)]
            (Self::Egl(display), Config::Egl(config)) => unsafe {
                Ok(Surface::Egl(display.create_pbuffer_surface(config, surface_attributes)?))
            },
            #[cfg(glx_backend)]
            (Self::Glx(display), Config::Glx(config)) => unsafe {
                Ok(Surface::Glx(display.create_pbuffer_surface(config, surface_attributes)?))
            },
            #[cfg(wgl_backend)]
            (Self::Wgl(display), Config::Wgl(config)) => unsafe {
                Ok(Surface::Wgl(display.create_pbuffer_surface(config, surface_attributes)?))
            },
            #[cfg(cgl_backend)]
            (Self::Cgl(display), Config::Cgl(config)) => unsafe {
                Ok(Surface::Cgl(display.create_pbuffer_surface(config, surface_attributes)?))
            },
            _ => unreachable!(),
        }
    }

    unsafe fn create_pixmap_surface(
        &self,
        config: &Self::Config,
        surface_attributes: &SurfaceAttributes<PixmapSurface>,
    ) -> Result<Self::PixmapSurface> {
        match (self, config) {
            #[cfg(egl_backend)]
            (Self::Egl(display), Config::Egl(config)) => unsafe {
                Ok(Surface::Egl(display.create_pixmap_surface(config, surface_attributes)?))
            },
            #[cfg(glx_backend)]
            (Self::Glx(display), Config::Glx(config)) => unsafe {
                Ok(Surface::Glx(display.create_pixmap_surface(config, surface_attributes)?))
            },
            #[cfg(wgl_backend)]
            (Self::Wgl(display), Config::Wgl(config)) => unsafe {
                Ok(Surface::Wgl(display.create_pixmap_surface(config, surface_attributes)?))
            },
            #[cfg(cgl_backend)]
            (Self::Cgl(display), Config::Cgl(config)) => unsafe {
                Ok(Surface::Cgl(display.create_pixmap_surface(config, surface_attributes)?))
            },
            _ => unreachable!(),
        }
    }

    fn get_proc_address(&self, addr: &CStr) -> *const ffi::c_void {
        gl_api_dispatch!(self; Self(display) => display.get_proc_address(addr))
    }

    fn version_string(&self) -> String {
        gl_api_dispatch!(self; Self(display) => display.version_string())
    }

    fn supported_features(&self) -> DisplayFeatures {
        gl_api_dispatch!(self; Self(display) => display.supported_features())
    }
}

impl AsRawDisplay for Display {
    fn raw_display(&self) -> RawDisplay {
        gl_api_dispatch!(self; Self(display) => display.raw_display())
    }
}

impl Sealed for Display {}

/// Preference of the display that should be used.
pub enum DisplayApiPreference {
    /// Use only EGL.
    ///
    /// The EGL is a cross platform recent OpenGL platform. That being said
    /// it's usually lacking on Windows and not present at all on macOS
    /// natively.
    ///
    /// Be also aware that some features may not be present with it, like window
    /// transparency on X11 with mesa.
    ///
    /// But despite this issues it should be preferred on at least Linux over
    /// GLX, given that GLX is phasing away.
    ///
    /// # Platform-specific
    ///
    /// **Windows:** ANGLE can be used if `libEGL.dll` and `libGLESv2.dll` are
    ///              in the library search path.
    #[cfg(egl_backend)]
    Egl,

    /// Use only GLX.
    ///
    /// The native GLX platform, it's not very optimal since it's usually tied
    /// to Xlib. It's know to work fine, but be aware that you must register
    /// glutin with your X11  error handling callback, since it's a
    /// per-process global state.
    ///
    /// The hook to register glutin error handler in the X11 error handling
    /// function.
    #[cfg(glx_backend)]
    Glx(XlibErrorHookRegistrar),

    /// Use only WGL.
    ///
    /// The most spread platform on Windows and what should be used on it by
    /// default. EGL usually not present there so you'd have to account for that
    /// and create the window beforehand.
    ///
    /// When raw window handle isn't provided the display will lack extensions
    /// support and most features will be lacking.
    #[cfg(wgl_backend)]
    Wgl(Option<raw_window_handle::RawWindowHandle>),

    /// Use only CGL.
    ///
    /// The only option on macOS for now.
    #[cfg(cgl_backend)]
    Cgl,

    /// Prefer EGL and fallback to GLX.
    ///
    /// See [`Egl`] and [`Glx`] to decide what you want.
    ///
    /// [`Egl`]: Self::Egl
    /// [`Glx`]: Self::Glx
    #[cfg(all(egl_backend, glx_backend))]
    EglThenGlx(XlibErrorHookRegistrar),

    /// Prefer GLX and fallback to EGL.
    ///
    /// See [`Egl`] and [`Glx`] to decide what you want.
    ///
    /// [`Egl`]: Self::Egl
    /// [`Glx`]: Self::Glx
    #[cfg(all(egl_backend, glx_backend))]
    GlxThenEgl(XlibErrorHookRegistrar),

    /// Prefer EGL and fallback to WGL.
    ///
    /// See [`Egl`] and [`Wgl`] to decide what you want.
    ///
    /// [`Egl`]: Self::Egl
    /// [`Wgl`]: Self::Wgl
    #[cfg(all(egl_backend, wgl_backend))]
    EglThenWgl(Option<raw_window_handle::RawWindowHandle>),

    /// Prefer WGL and fallback to EGL.
    ///
    /// See [`Egl`] and [`Wgl`] to decide what you want.
    ///
    /// [`Egl`]: Self::Egl
    /// [`Wgl`]: Self::Wgl
    #[cfg(all(egl_backend, wgl_backend))]
    WglThenEgl(Option<raw_window_handle::RawWindowHandle>),
}

impl fmt::Debug for DisplayApiPreference {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let api = match self {
            #[cfg(egl_backend)]
            DisplayApiPreference::Egl => "Egl",
            #[cfg(glx_backend)]
            DisplayApiPreference::Glx(_) => "Glx",
            #[cfg(all(egl_backend, glx_backend))]
            DisplayApiPreference::GlxThenEgl(_) => "GlxThenEgl",
            #[cfg(all(egl_backend, glx_backend))]
            DisplayApiPreference::EglThenGlx(_) => "EglThenGlx",
            #[cfg(wgl_backend)]
            DisplayApiPreference::Wgl(_) => "Wgl",
            #[cfg(all(egl_backend, wgl_backend))]
            DisplayApiPreference::EglThenWgl(_) => "EglThenWgl",
            #[cfg(all(egl_backend, wgl_backend))]
            DisplayApiPreference::WglThenEgl(_) => "WglThenEgl",
            #[cfg(cgl_backend)]
            DisplayApiPreference::Cgl => "Cgl",
        };

        f.write_fmt(format_args!("DisplayApiPreference::{api}"))
    }
}

bitflags! {
    /// The features and extensions supported by the [`Display`].
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct DisplayFeatures: u32 {
        /// The display supports creating [`robust`] context.
        ///
        /// [`robust`]: crate::context::Robustness
        const CONTEXT_ROBUSTNESS          = 0b0000_0001;

        /// The display supports creating [`no error`] context.
        ///
        /// [`no error`]: crate::context::Robustness::NoError
        const CONTEXT_NO_ERROR            = 0b0000_0010;

        /// The display supports [`floating`] pixel formats.
        ///
        /// [`floating`]: crate::config::ConfigTemplateBuilder::with_float_pixels
        const FLOAT_PIXEL_FORMAT          = 0b0000_0100;

        /// The display supports changing the [`swap interval`] on surfaces.
        ///
        /// [`swap interval`]: crate::surface::GlSurface::set_swap_interval
        const SWAP_CONTROL                = 0b0000_1000;

        /// The display supports creating context with explicit [`release behavior`].
        ///
        /// [`release behavior`]: crate::context::ReleaseBehavior
        const CONTEXT_RELEASE_BEHAVIOR   = 0b0001_0000;

        /// The display supports creating OpenGL ES [`context`].
        ///
        /// [`context`]: crate::context::ContextApi::Gles
        const CREATE_ES_CONTEXT           = 0b0010_0000;

        /// The display supports pixel formats with [`multisampling`].
        ///
        /// [`multisampling`]: crate::config::ConfigTemplateBuilder::with_multisampling
        const MULTISAMPLING_PIXEL_FORMATS = 0b0100_0000;

        /// The display supports creating surfaces backed by [`SRGB`] framebuffers.
        ///
        /// [`SRGB`]: crate::surface::SurfaceAttributesBuilder::with_srgb
        const SRGB_FRAMEBUFFERS           = 0b1000_0000;
    }
}

/// Raw GL platform display.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RawDisplay {
    /// Raw EGL display.
    #[cfg(egl_backend)]
    Egl(*const std::ffi::c_void),

    /// Raw GLX display.
    #[cfg(glx_backend)]
    Glx(*const std::ffi::c_void),

    /// Raw display is WGL.
    #[cfg(wgl_backend)]
    Wgl,

    /// Raw display is CGL.
    #[cfg(cgl_backend)]
    Cgl,
}