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
593
594
595
596
597
598
599
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
#![allow(deprecated)]

#[cfg(feature = "v4_6")]
#[cfg_attr(docsrs, doc(cfg(feature = "v4_6")))]
use crate::GLAPI;
use crate::{Display, DrawContext, Surface};
#[cfg(feature = "v4_6")]
#[cfg_attr(docsrs, doc(cfg(feature = "v4_6")))]
use glib::signal::{connect_raw, SignalHandlerId};
use glib::{prelude::*, translate::*};
#[cfg(feature = "v4_6")]
#[cfg_attr(docsrs, doc(cfg(feature = "v4_6")))]
use std::boxed::Box as Box_;

glib::wrapper! {
    /// [`GLContext`][crate::GLContext] is an object representing a platform-specific
    /// OpenGL draw context.
    ///
    /// [`GLContext`][crate::GLContext]s are created for a surface using
    /// [`SurfaceExt::create_gl_context()`][crate::prelude::SurfaceExt::create_gl_context()], and the context will match
    /// the characteristics of the surface.
    ///
    /// A [`GLContext`][crate::GLContext] is not tied to any particular normal framebuffer.
    /// For instance, it cannot draw to the surface back buffer. The GDK
    /// repaint system is in full control of the painting to that. Instead,
    /// you can create render buffers or textures and use [`draw_from_gl()`][crate::draw_from_gl()]
    /// in the draw function of your widget to draw them. Then GDK will handle
    /// the integration of your rendering with that of other widgets.
    ///
    /// Support for [`GLContext`][crate::GLContext] is platform-specific and context creation
    /// can fail, returning [`None`] context.
    ///
    /// A [`GLContext`][crate::GLContext] has to be made "current" in order to start using
    /// it, otherwise any OpenGL call will be ignored.
    ///
    /// ## Creating a new OpenGL context
    ///
    /// In order to create a new [`GLContext`][crate::GLContext] instance you need a [`Surface`][crate::Surface],
    /// which you typically get during the realize call of a widget.
    ///
    /// A [`GLContext`][crate::GLContext] is not realized until either [`GLContextExt::make_current()`][crate::prelude::GLContextExt::make_current()]
    /// or [`GLContextExt::realize()`][crate::prelude::GLContextExt::realize()] is called. It is possible to specify
    /// details of the GL context like the OpenGL version to be used, or whether
    /// the GL context should have extra state validation enabled after calling
    /// [`SurfaceExt::create_gl_context()`][crate::prelude::SurfaceExt::create_gl_context()] by calling [`GLContextExt::realize()`][crate::prelude::GLContextExt::realize()].
    /// If the realization fails you have the option to change the settings of
    /// the [`GLContext`][crate::GLContext] and try again.
    ///
    /// ## Using a GdkGLContext
    ///
    /// You will need to make the [`GLContext`][crate::GLContext] the current context before issuing
    /// OpenGL calls; the system sends OpenGL commands to whichever context is current.
    /// It is possible to have multiple contexts, so you always need to ensure that
    /// the one which you want to draw with is the current one before issuing commands:
    ///
    /// **⚠️ The following code is in c ⚠️**
    ///
    /// ```c
    /// gdk_gl_context_make_current (context);
    /// ```
    ///
    /// You can now perform your drawing using OpenGL commands.
    ///
    /// You can check which [`GLContext`][crate::GLContext] is the current one by using
    /// [`current()`][Self::current()]; you can also unset any [`GLContext`][crate::GLContext]
    /// that is currently set by calling [`clear_current()`][Self::clear_current()].
    ///
    /// This is an Abstract Base Class, you cannot instantiate it.
    ///
    /// ## Properties
    ///
    ///
    /// #### `allowed-apis`
    ///  The allowed APIs.
    ///
    /// Readable | Writeable
    ///
    ///
    /// #### `api`
    ///  The API currently in use.
    ///
    /// Readable
    ///
    ///
    /// #### `shared-context`
    ///  Always [`None`]
    ///
    /// As many contexts can share data now and no single shared context exists
    /// anymore, this function has been deprecated and now always returns [`None`].
    ///
    /// Readable | Writeable | Construct Only
    /// <details><summary><h4>DrawContext</h4></summary>
    ///
    ///
    /// #### `display`
    ///  The [`Display`][crate::Display] used to create the [`DrawContext`][crate::DrawContext].
    ///
    /// Readable | Writeable | Construct Only
    ///
    ///
    /// #### `surface`
    ///  The [`Surface`][crate::Surface] the context is bound to.
    ///
    /// Readable | Writeable | Construct Only
    /// </details>
    ///
    /// # Implements
    ///
    /// [`GLContextExt`][trait@crate::prelude::GLContextExt], [`DrawContextExt`][trait@crate::prelude::DrawContextExt], [`DrawContextExtManual`][trait@crate::prelude::DrawContextExtManual]
    #[doc(alias = "GdkGLContext")]
    pub struct GLContext(Object<ffi::GdkGLContext>) @extends DrawContext;

    match fn {
        type_ => || ffi::gdk_gl_context_get_type(),
    }
}

impl GLContext {
    pub const NONE: Option<&'static GLContext> = None;

    /// Clears the current [`GLContext`][crate::GLContext].
    ///
    /// Any OpenGL call after this function returns will be ignored
    /// until [`GLContextExt::make_current()`][crate::prelude::GLContextExt::make_current()] is called.
    #[doc(alias = "gdk_gl_context_clear_current")]
    pub fn clear_current() {
        assert_initialized_main_thread!();
        unsafe {
            ffi::gdk_gl_context_clear_current();
        }
    }

    /// Retrieves the current [`GLContext`][crate::GLContext].
    ///
    /// # Returns
    ///
    /// the current [`GLContext`][crate::GLContext]
    #[doc(alias = "gdk_gl_context_get_current")]
    #[doc(alias = "get_current")]
    pub fn current() -> Option<GLContext> {
        assert_initialized_main_thread!();
        unsafe { from_glib_none(ffi::gdk_gl_context_get_current()) }
    }
}

mod sealed {
    pub trait Sealed {}
    impl<T: super::IsA<super::GLContext>> Sealed for T {}
}

/// Trait containing all [`struct@GLContext`] methods.
///
/// # Implementors
///
/// [`GLContext`][struct@crate::GLContext]
pub trait GLContextExt: IsA<GLContext> + sealed::Sealed + 'static {
    /// Gets the allowed APIs set via gdk_gl_context_set_allowed_apis().
    ///
    /// # Returns
    ///
    /// the allowed APIs
    #[cfg(feature = "v4_6")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v4_6")))]
    #[doc(alias = "gdk_gl_context_get_allowed_apis")]
    #[doc(alias = "get_allowed_apis")]
    fn allowed_apis(&self) -> GLAPI {
        unsafe {
            from_glib(ffi::gdk_gl_context_get_allowed_apis(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    /// Gets the API currently in use.
    ///
    /// If the renderer has not been realized yet, 0 is returned.
    ///
    /// # Returns
    ///
    /// the currently used API
    #[cfg(feature = "v4_6")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v4_6")))]
    #[doc(alias = "gdk_gl_context_get_api")]
    #[doc(alias = "get_api")]
    fn api(&self) -> GLAPI {
        unsafe { from_glib(ffi::gdk_gl_context_get_api(self.as_ref().to_glib_none().0)) }
    }

    /// Retrieves whether the context is doing extra validations and runtime checking.
    ///
    /// See [`set_debug_enabled()`][Self::set_debug_enabled()].
    ///
    /// # Returns
    ///
    /// [`true`] if debugging is enabled
    #[doc(alias = "gdk_gl_context_get_debug_enabled")]
    #[doc(alias = "get_debug_enabled")]
    fn is_debug_enabled(&self) -> bool {
        unsafe {
            from_glib(ffi::gdk_gl_context_get_debug_enabled(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    /// Retrieves the display the @self is created for
    ///
    /// # Returns
    ///
    /// a [`Display`][crate::Display]
    #[doc(alias = "gdk_gl_context_get_display")]
    #[doc(alias = "get_display")]
    fn display(&self) -> Option<Display> {
        unsafe {
            from_glib_none(ffi::gdk_gl_context_get_display(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    /// Retrieves whether the context is forward-compatible.
    ///
    /// See [`set_forward_compatible()`][Self::set_forward_compatible()].
    ///
    /// # Returns
    ///
    /// [`true`] if the context should be forward-compatible
    #[doc(alias = "gdk_gl_context_get_forward_compatible")]
    #[doc(alias = "get_forward_compatible")]
    fn is_forward_compatible(&self) -> bool {
        unsafe {
            from_glib(ffi::gdk_gl_context_get_forward_compatible(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    /// Retrieves required OpenGL version set as a requirement for the @self
    /// realization. It will not change even if a greater OpenGL version is supported
    /// and used after the @self is realized. See
    /// [`version()`][Self::version()] for the real version in use.
    ///
    /// See [`set_required_version()`][Self::set_required_version()].
    ///
    /// # Returns
    ///
    ///
    /// ## `major`
    /// return location for the major version to request
    ///
    /// ## `minor`
    /// return location for the minor version to request
    #[doc(alias = "gdk_gl_context_get_required_version")]
    #[doc(alias = "get_required_version")]
    fn required_version(&self) -> (i32, i32) {
        unsafe {
            let mut major = std::mem::MaybeUninit::uninit();
            let mut minor = std::mem::MaybeUninit::uninit();
            ffi::gdk_gl_context_get_required_version(
                self.as_ref().to_glib_none().0,
                major.as_mut_ptr(),
                minor.as_mut_ptr(),
            );
            (major.assume_init(), minor.assume_init())
        }
    }

    /// Used to retrieves the [`GLContext`][crate::GLContext] that this @self share data with.
    ///
    /// As many contexts can share data now and no single shared context exists
    /// anymore, this function has been deprecated and now always returns [`None`].
    ///
    /// # Deprecated since 4.4
    ///
    /// Use [`is_shared()`][Self::is_shared()] to check if contexts
    ///   can be shared.
    ///
    /// # Returns
    ///
    /// [`None`]
    #[cfg_attr(feature = "v4_4", deprecated = "Since 4.4")]
    #[allow(deprecated)]
    #[doc(alias = "gdk_gl_context_get_shared_context")]
    #[doc(alias = "get_shared_context")]
    #[must_use]
    fn shared_context(&self) -> Option<GLContext> {
        unsafe {
            from_glib_none(ffi::gdk_gl_context_get_shared_context(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    /// Retrieves the surface used by the @self.
    ///
    /// # Returns
    ///
    /// a [`Surface`][crate::Surface]
    #[doc(alias = "gdk_gl_context_get_surface")]
    #[doc(alias = "get_surface")]
    fn surface(&self) -> Option<Surface> {
        unsafe {
            from_glib_none(ffi::gdk_gl_context_get_surface(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    /// Checks whether the @self is using an OpenGL or OpenGL ES profile.
    ///
    /// # Returns
    ///
    /// [`true`] if the [`GLContext`][crate::GLContext] is using an OpenGL ES profile;
    /// [`false`] if other profile is in use of if the @self has not yet
    /// been realized.
    #[doc(alias = "gdk_gl_context_get_use_es")]
    #[doc(alias = "get_use_es")]
    fn uses_es(&self) -> bool {
        unsafe {
            from_glib(ffi::gdk_gl_context_get_use_es(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    /// Retrieves the OpenGL version of the @self.
    ///
    /// The @self must be realized prior to calling this function.
    ///
    /// # Returns
    ///
    ///
    /// ## `major`
    /// return location for the major version
    ///
    /// ## `minor`
    /// return location for the minor version
    #[doc(alias = "gdk_gl_context_get_version")]
    #[doc(alias = "get_version")]
    fn version(&self) -> (i32, i32) {
        unsafe {
            let mut major = std::mem::MaybeUninit::uninit();
            let mut minor = std::mem::MaybeUninit::uninit();
            ffi::gdk_gl_context_get_version(
                self.as_ref().to_glib_none().0,
                major.as_mut_ptr(),
                minor.as_mut_ptr(),
            );
            (major.assume_init(), minor.assume_init())
        }
    }

    /// Whether the [`GLContext`][crate::GLContext] is in legacy mode or not.
    ///
    /// The [`GLContext`][crate::GLContext] must be realized before calling this function.
    ///
    /// When realizing a GL context, GDK will try to use the OpenGL 3.2 core
    /// profile; this profile removes all the OpenGL API that was deprecated
    /// prior to the 3.2 version of the specification. If the realization is
    /// successful, this function will return [`false`].
    ///
    /// If the underlying OpenGL implementation does not support core profiles,
    /// GDK will fall back to a pre-3.2 compatibility profile, and this function
    /// will return [`true`].
    ///
    /// You can use the value returned by this function to decide which kind
    /// of OpenGL API to use, or whether to do extension discovery, or what
    /// kind of shader programs to load.
    ///
    /// # Returns
    ///
    /// [`true`] if the GL context is in legacy mode
    #[doc(alias = "gdk_gl_context_is_legacy")]
    fn is_legacy(&self) -> bool {
        unsafe {
            from_glib(ffi::gdk_gl_context_is_legacy(
                self.as_ref().to_glib_none().0,
            ))
        }
    }

    /// Checks if the two GL contexts can share resources.
    ///
    /// When they can, the texture IDs from @other can be used in @self. This
    /// is particularly useful when passing [`GLTexture`][crate::GLTexture] objects between
    /// different contexts.
    ///
    /// Contexts created for the same display with the same properties will
    /// always be compatible, even if they are created for different surfaces.
    /// For other contexts it depends on the GL backend.
    ///
    /// Both contexts must be realized for this check to succeed. If either one
    /// is not, this function will return [`false`].
    /// ## `other`
    /// the [`GLContext`][crate::GLContext] that should be compatible with @self
    ///
    /// # Returns
    ///
    /// [`true`] if the two GL contexts are compatible.
    #[cfg(feature = "v4_4")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v4_4")))]
    #[doc(alias = "gdk_gl_context_is_shared")]
    fn is_shared(&self, other: &impl IsA<GLContext>) -> bool {
        unsafe {
            from_glib(ffi::gdk_gl_context_is_shared(
                self.as_ref().to_glib_none().0,
                other.as_ref().to_glib_none().0,
            ))
        }
    }

    /// Makes the @self the current one.
    #[doc(alias = "gdk_gl_context_make_current")]
    fn make_current(&self) {
        unsafe {
            ffi::gdk_gl_context_make_current(self.as_ref().to_glib_none().0);
        }
    }

    /// Realizes the given [`GLContext`][crate::GLContext].
    ///
    /// It is safe to call this function on a realized [`GLContext`][crate::GLContext].
    ///
    /// # Returns
    ///
    /// [`true`] if the context is realized
    #[doc(alias = "gdk_gl_context_realize")]
    fn realize(&self) -> Result<(), glib::Error> {
        unsafe {
            let mut error = std::ptr::null_mut();
            let is_ok = ffi::gdk_gl_context_realize(self.as_ref().to_glib_none().0, &mut error);
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Sets the allowed APIs. When gdk_gl_context_realize() is called, only the
    /// allowed APIs will be tried. If you set this to 0, realizing will always fail.
    ///
    /// If you set it on a realized context, the property will not have any effect.
    /// It is only relevant during gdk_gl_context_realize().
    ///
    /// By default, all APIs are allowed.
    /// ## `apis`
    /// the allowed APIs
    #[cfg(feature = "v4_6")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v4_6")))]
    #[doc(alias = "gdk_gl_context_set_allowed_apis")]
    fn set_allowed_apis(&self, apis: GLAPI) {
        unsafe {
            ffi::gdk_gl_context_set_allowed_apis(self.as_ref().to_glib_none().0, apis.into_glib());
        }
    }

    /// Sets whether the [`GLContext`][crate::GLContext] should perform extra validations and
    /// runtime checking.
    ///
    /// This is useful during development, but has additional overhead.
    ///
    /// The [`GLContext`][crate::GLContext] must not be realized or made current prior to
    /// calling this function.
    /// ## `enabled`
    /// whether to enable debugging in the context
    #[doc(alias = "gdk_gl_context_set_debug_enabled")]
    fn set_debug_enabled(&self, enabled: bool) {
        unsafe {
            ffi::gdk_gl_context_set_debug_enabled(
                self.as_ref().to_glib_none().0,
                enabled.into_glib(),
            );
        }
    }

    /// Sets whether the [`GLContext`][crate::GLContext] should be forward-compatible.
    ///
    /// Forward-compatible contexts must not support OpenGL functionality that
    /// has been marked as deprecated in the requested version; non-forward
    /// compatible contexts, on the other hand, must support both deprecated and
    /// non deprecated functionality.
    ///
    /// The [`GLContext`][crate::GLContext] must not be realized or made current prior to calling
    /// this function.
    /// ## `compatible`
    /// whether the context should be forward-compatible
    #[doc(alias = "gdk_gl_context_set_forward_compatible")]
    fn set_forward_compatible(&self, compatible: bool) {
        unsafe {
            ffi::gdk_gl_context_set_forward_compatible(
                self.as_ref().to_glib_none().0,
                compatible.into_glib(),
            );
        }
    }

    /// Sets the major and minor version of OpenGL to request.
    ///
    /// Setting @major and @minor to zero will use the default values.
    ///
    /// Setting @major and @minor lower than the minimum versions required
    /// by GTK will result in the context choosing the minimum version.
    ///
    /// The @self must not be realized or made current prior to calling
    /// this function.
    /// ## `major`
    /// the major version to request
    /// ## `minor`
    /// the minor version to request
    #[doc(alias = "gdk_gl_context_set_required_version")]
    fn set_required_version(&self, major: i32, minor: i32) {
        unsafe {
            ffi::gdk_gl_context_set_required_version(self.as_ref().to_glib_none().0, major, minor);
        }
    }

    /// Requests that GDK create an OpenGL ES context instead of an OpenGL one.
    ///
    /// Not all platforms support OpenGL ES.
    ///
    /// The @self must not have been realized.
    ///
    /// By default, GDK will attempt to automatically detect whether the
    /// underlying GL implementation is OpenGL or OpenGL ES once the @self
    /// is realized.
    ///
    /// You should check the return value of [`uses_es()`][Self::uses_es()]
    /// after calling [`realize()`][Self::realize()] to decide whether to use
    /// the OpenGL or OpenGL ES API, extensions, or shaders.
    /// ## `use_es`
    /// whether the context should use OpenGL ES instead of OpenGL,
    ///   or -1 to allow auto-detection
    #[doc(alias = "gdk_gl_context_set_use_es")]
    fn set_use_es(&self, use_es: i32) {
        unsafe {
            ffi::gdk_gl_context_set_use_es(self.as_ref().to_glib_none().0, use_es);
        }
    }

    #[cfg(feature = "v4_6")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v4_6")))]
    #[doc(alias = "allowed-apis")]
    fn connect_allowed_apis_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_allowed_apis_trampoline<
            P: IsA<GLContext>,
            F: Fn(&P) + 'static,
        >(
            this: *mut ffi::GdkGLContext,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(GLContext::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::allowed-apis\0".as_ptr() as *const _,
                Some(std::mem::transmute::<_, unsafe extern "C" fn()>(
                    notify_allowed_apis_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }

    #[cfg(feature = "v4_6")]
    #[cfg_attr(docsrs, doc(cfg(feature = "v4_6")))]
    #[doc(alias = "api")]
    fn connect_api_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe extern "C" fn notify_api_trampoline<P: IsA<GLContext>, F: Fn(&P) + 'static>(
            this: *mut ffi::GdkGLContext,
            _param_spec: glib::ffi::gpointer,
            f: glib::ffi::gpointer,
        ) {
            let f: &F = &*(f as *const F);
            f(GLContext::from_glib_borrow(this).unsafe_cast_ref())
        }
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(
                self.as_ptr() as *mut _,
                b"notify::api\0".as_ptr() as *const _,
                Some(std::mem::transmute::<_, unsafe extern "C" fn()>(
                    notify_api_trampoline::<Self, F> as *const (),
                )),
                Box_::into_raw(f),
            )
        }
    }
}

impl<O: IsA<GLContext>> GLContextExt for O {}