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
#![cfg(target_os = "windows")]

use crate::{
    Api, ContextError, CreationError, GlAttributes, GlRequest, PixelFormat,
    PixelFormatRequirements,
};

use crate::api::egl::{Context as EglContext, NativeDisplay, EGL};
use crate::api::wgl::Context as WglContext;
use crate::os::windows::WindowExt;

use glutin_egl_sys as ffi;
use winapi::shared::windef::{HGLRC, HWND};
use winit;
use winit::dpi;

use std::os::raw;

/// Context handles available on Windows.
#[derive(Clone, Debug)]
pub enum RawHandle {
    Egl(ffi::EGLContext),
    Wgl(HGLRC),
}

pub enum Context {
    /// A regular window
    Egl(EglContext),
    Wgl(WglContext),
    /// A regular window, but invisible.
    HiddenWindowEgl(winit::Window, EglContext),
    HiddenWindowWgl(winit::Window, WglContext),
    /// An EGL pbuffer.
    EglPbuffer(EglContext),
}

unsafe impl Send for Context {}
unsafe impl Sync for Context {}

impl Context {
    /// See the docs in the crate root file.
    #[inline]
    pub fn new_windowed(
        wb: winit::WindowBuilder,
        el: &winit::EventsLoop,
        pf_reqs: &PixelFormatRequirements,
        gl_attr: &GlAttributes<&Self>,
    ) -> Result<(winit::Window, Self), CreationError> {
        let win = wb.build(el)?;
        let hwnd = win.get_hwnd() as HWND;
        let ctx = Self::new_raw_context(hwnd, pf_reqs, gl_attr)?;

        Ok((win, ctx))
    }

    #[inline]
    pub fn new_raw_context(
        hwnd: HWND,
        pf_reqs: &PixelFormatRequirements,
        gl_attr: &GlAttributes<&Self>,
    ) -> Result<Self, CreationError> {
        match gl_attr.version {
            GlRequest::Specific(Api::OpenGlEs, (_major, _minor)) => {
                match (gl_attr.sharing, &*EGL) {
                    // We must use WGL.
                    (Some(&Context::HiddenWindowWgl(_, _)), _)
                    | (Some(&Context::Wgl(_)), _)
                    | (None, None) => {
                        let gl_attr_wgl =
                            gl_attr.clone().map_sharing(|ctx| match *ctx {
                                Context::HiddenWindowWgl(_, ref c)
                                | Context::Wgl(ref c) => c.get_hglrc(),
                                _ => unreachable!(),
                            });
                        unsafe {
                            WglContext::new(&pf_reqs, &gl_attr_wgl, hwnd)
                                .map(Context::Wgl)
                        }
                    }
                    // We must use EGL.
                    (Some(_), Some(_)) => {
                        let gl_attr_egl =
                            gl_attr.clone().map_sharing(|ctx| match *ctx {
                                Context::Egl(ref c)
                                | Context::EglPbuffer(ref c)
                                | Context::HiddenWindowEgl(_, ref c) => c,
                                _ => unreachable!(),
                            });

                        EglContext::new(
                            &pf_reqs,
                            &gl_attr_egl,
                            NativeDisplay::Other(Some(std::ptr::null())),
                        )
                        .and_then(|p| p.finish(hwnd))
                        .map(|c| Context::Egl(c))
                    }
                    // Try EGL, fallback to WGL.
                    (None, Some(_)) => {
                        let gl_attr_egl =
                            gl_attr.clone().map_sharing(|_| unreachable!());
                        let gl_attr_wgl =
                            gl_attr.clone().map_sharing(|_| unreachable!());

                        if let Ok(c) = EglContext::new(
                            &pf_reqs,
                            &gl_attr_egl,
                            NativeDisplay::Other(Some(std::ptr::null())),
                        )
                        .and_then(|p| p.finish(hwnd))
                        {
                            Ok(Context::Egl(c))
                        } else {
                            unsafe {
                                WglContext::new(&pf_reqs, &gl_attr_wgl, hwnd)
                                    .map(Context::Wgl)
                            }
                        }
                    }
                    _ => panic!(),
                }
            }
            _ => {
                let gl_attr_wgl =
                    gl_attr.clone().map_sharing(|ctx| match *ctx {
                        Context::HiddenWindowWgl(_, ref c)
                        | Context::Wgl(ref c) => c.get_hglrc(),
                        _ => panic!(),
                    });
                unsafe {
                    WglContext::new(&pf_reqs, &gl_attr_wgl, hwnd).map(Context::Wgl)
                }
            }
        }
    }

    #[inline]
    pub fn new_headless(
        el: &winit::EventsLoop,
        pf_reqs: &PixelFormatRequirements,
        gl_attr: &GlAttributes<&Context>,
        dims: dpi::PhysicalSize,
    ) -> Result<Self, CreationError> {
        // if EGL is available, we try using EGL first
        // if EGL returns an error, we try the hidden window method
        match (gl_attr.sharing, &*EGL) {
            (None, Some(_))
            | (Some(&Context::Egl(_)), Some(_))
            | (Some(&Context::HiddenWindowEgl(_, _)), Some(_))
            | (Some(&Context::EglPbuffer(_)), Some(_)) => {
                let gl_attr_egl =
                    gl_attr.clone().map_sharing(|ctx| match *ctx {
                        Context::Egl(ref c)
                        | Context::EglPbuffer(ref c)
                        | Context::HiddenWindowEgl(_, ref c) => c,
                        _ => unreachable!(),
                    });

                let native_display = NativeDisplay::Other(None);
                let context =
                    EglContext::new(pf_reqs, &gl_attr_egl, native_display)
                        .and_then(|prototype| prototype.finish_pbuffer(dims))
                        .map(|ctx| Context::EglPbuffer(ctx));

                if let Ok(context) = context {
                    return Ok(context);
                }
            }
            _ => (),
        }

        let wb = winit::WindowBuilder::new()
            .with_visibility(false)
            .with_dimensions(dims.to_logical(1.));
        Self::new_windowed(wb, &el, pf_reqs, gl_attr).map(|(win, context)| {
            match context {
                Context::Egl(context) => Context::HiddenWindowEgl(win, context),
                Context::Wgl(context) => Context::HiddenWindowWgl(win, context),
                _ => unreachable!(),
            }
        })
    }

    #[inline]
    pub fn resize(&self, _width: u32, _height: u32) {
        // Method is for API consistency.
    }

    #[inline]
    pub unsafe fn make_current(&self) -> Result<(), ContextError> {
        match *self {
            Context::Wgl(ref c) | Context::HiddenWindowWgl(_, ref c) => {
                c.make_current()
            }
            Context::Egl(ref c)
            | Context::HiddenWindowEgl(_, ref c)
            | Context::EglPbuffer(ref c) => c.make_current(),
        }
    }

    #[inline]
    pub fn is_current(&self) -> bool {
        match *self {
            Context::Wgl(ref c) | Context::HiddenWindowWgl(_, ref c) => {
                c.is_current()
            }
            Context::Egl(ref c)
            | Context::HiddenWindowEgl(_, ref c)
            | Context::EglPbuffer(ref c) => c.is_current(),
        }
    }

    #[inline]
    pub fn get_proc_address(&self, addr: &str) -> *const () {
        match *self {
            Context::Wgl(ref c) | Context::HiddenWindowWgl(_, ref c) => {
                c.get_proc_address(addr)
            }
            Context::Egl(ref c)
            | Context::HiddenWindowEgl(_, ref c)
            | Context::EglPbuffer(ref c) => c.get_proc_address(addr),
        }
    }

    #[inline]
    pub fn swap_buffers(&self) -> Result<(), ContextError> {
        match *self {
            Context::Wgl(ref c) => c.swap_buffers(),
            Context::Egl(ref c) => c.swap_buffers(),
            _ => unreachable!(),
        }
    }

    #[inline]
    pub fn get_api(&self) -> Api {
        match *self {
            Context::Wgl(ref c) | Context::HiddenWindowWgl(_, ref c) => {
                c.get_api()
            }
            Context::Egl(ref c)
            | Context::HiddenWindowEgl(_, ref c)
            | Context::EglPbuffer(ref c) => c.get_api(),
        }
    }

    #[inline]
    pub fn get_pixel_format(&self) -> PixelFormat {
        match *self {
            Context::Wgl(ref c) => c.get_pixel_format(),
            Context::Egl(ref c) => c.get_pixel_format(),
            _ => unreachable!(),
        }
    }

    #[inline]
    pub unsafe fn raw_handle(&self) -> RawHandle {
        match *self {
            Context::Wgl(ref c) | Context::HiddenWindowWgl(_, ref c) => {
                RawHandle::Wgl(c.get_hglrc())
            }
            Context::Egl(ref c)
            | Context::HiddenWindowEgl(_, ref c)
            | Context::EglPbuffer(ref c) => RawHandle::Egl(c.raw_handle()),
        }
    }

    #[inline]
    pub unsafe fn get_egl_display(&self) -> Option<*const raw::c_void> {
        match *self {
            Context::Egl(ref c)
            | Context::HiddenWindowEgl(_, ref c)
            | Context::EglPbuffer(ref c) => Some(c.get_egl_display()),
            _ => None,
        }
    }
}

pub trait RawContextExt {
    /// Creates a raw context on the provided window.
    ///
    /// Unsafe behaviour might happen if you:
    ///   - Provide us with invalid parameters.
    ///   - The window is destroyed before the context
    unsafe fn new_raw_context(
        hwnd: *mut raw::c_void,
        cb: crate::ContextBuilder,
    ) -> Result<crate::RawContext, CreationError>
    where
        Self: Sized;
}

impl RawContextExt for crate::Context {
    #[inline]
    unsafe fn new_raw_context(
        hwnd: *mut raw::c_void,
        cb: crate::ContextBuilder,
    ) -> Result<crate::RawContext, CreationError>
    where
        Self: Sized,
    {
        let crate::ContextBuilder { pf_reqs, gl_attr } = cb;
        let gl_attr = gl_attr.map_sharing(|ctx| &ctx.context);
        Context::new_raw_context(hwnd as *mut _, &pf_reqs, &gl_attr)
            .map(|context| crate::Context { context })
            .map(|context| crate::RawContext { context })
    }
}