-
Notifications
You must be signed in to change notification settings - Fork 464
/
Copy pathvideo.rs
2140 lines (1886 loc) · 68.9 KB
/
video.rs
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use libc::{c_char, c_float, c_int, c_uint};
use std::convert::TryFrom;
use std::error::Error;
use std::ffi::{CStr, CString, NulError};
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use std::{fmt, mem, ptr};
use crate::common::{validate_int, IntegerOrSdlError};
use crate::pixels::PixelFormatEnum;
use crate::rect::Rect;
use crate::render::CanvasBuilder;
use crate::surface::SurfaceRef;
use crate::EventPump;
use crate::VideoSubsystem;
use crate::get_error;
use crate::sys;
pub use crate::sys::{VkInstance, VkSurfaceKHR};
pub struct WindowSurfaceRef<'a>(&'a mut SurfaceRef, &'a Window);
impl<'a> Deref for WindowSurfaceRef<'a> {
type Target = SurfaceRef;
#[inline]
fn deref(&self) -> &SurfaceRef {
self.0
}
}
impl<'a> DerefMut for WindowSurfaceRef<'a> {
#[inline]
fn deref_mut(&mut self) -> &mut SurfaceRef {
self.0
}
}
impl<'a> WindowSurfaceRef<'a> {
/// Updates the change made to the inner Surface to the Window it was created from.
///
/// This would effectively be the theoretical equivalent of `present` from a Canvas.
#[doc(alias = "SDL_UpdateWindowSurface")]
pub fn update_window(&self) -> Result<(), String> {
unsafe {
if sys::SDL_UpdateWindowSurface(self.1.context.raw) == 0 {
Ok(())
} else {
Err(get_error())
}
}
}
/// Same as `update_window`, but only update the parts included in `rects` to the Window it was
/// created from.
#[doc(alias = "SDL_UpdateWindowSurfaceRects")]
pub fn update_window_rects(&self, rects: &[Rect]) -> Result<(), String> {
unsafe {
if sys::SDL_UpdateWindowSurfaceRects(
self.1.context.raw,
Rect::raw_slice(rects),
rects.len() as c_int,
) == 0
{
Ok(())
} else {
Err(get_error())
}
}
}
/// Gives up this WindowSurfaceRef, allowing to use the window freely again. Before being
/// destroyed, calls `update_window` one last time.
///
/// If you don't want to `update_window` one last time, simply Drop this struct. However
/// beware, since the Surface will still be in the state you left it the next time you will
/// call `window.surface()` again.
pub fn finish(self) -> Result<(), String> {
self.update_window()
}
}
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub enum GLProfile {
/// OpenGL core profile - deprecated functions are disabled
Core,
/// OpenGL compatibility profile - deprecated functions are allowed
Compatibility,
/// OpenGL ES profile - only a subset of the base OpenGL functionality is available
GLES,
/// Unknown profile - SDL will tend to return 0 if you ask when no particular profile
/// has been defined or requested.
Unknown(i32),
}
trait GLAttrTypeUtil {
fn to_gl_value(self) -> i32;
fn from_gl_value(value: i32) -> Self;
}
impl GLAttrTypeUtil for u8 {
fn to_gl_value(self) -> i32 {
self as i32
}
fn from_gl_value(value: i32) -> u8 {
value as u8
}
}
impl GLAttrTypeUtil for bool {
fn to_gl_value(self) -> i32 {
if self {
1
} else {
0
}
}
fn from_gl_value(value: i32) -> bool {
value != 0
}
}
impl GLAttrTypeUtil for GLProfile {
fn to_gl_value(self) -> i32 {
use self::GLProfile::*;
match self {
Unknown(i) => i,
Core => 1,
Compatibility => 2,
GLES => 4,
}
}
fn from_gl_value(value: i32) -> GLProfile {
use self::GLProfile::*;
match value {
1 => Core,
2 => Compatibility,
4 => GLES,
i => Unknown(i),
}
}
}
macro_rules! attrs {
(
$(($attr_name:ident, $set_property:ident, $get_property:ident, $t:ty, $doc:expr)),*
) => (
$(
#[doc = "**Sets** the attribute: "]
#[doc = $doc]
#[inline]
pub fn $set_property(&self, value: $t) {
gl_set_attribute!($attr_name, value.to_gl_value());
}
#[doc = "**Gets** the attribute: "]
#[doc = $doc]
#[inline]
pub fn $get_property(&self) -> $t {
let value = gl_get_attribute!($attr_name);
GLAttrTypeUtil::from_gl_value(value)
}
)*
);
}
/// OpenGL context getters and setters
///
/// # Example
/// ```no_run
/// use sdl2::video::GLProfile;
///
/// let sdl_context = sdl2::init().unwrap();
/// let video_subsystem = sdl_context.video().unwrap();
/// let gl_attr = video_subsystem.gl_attr();
///
/// // Don't use deprecated OpenGL functions
/// gl_attr.set_context_profile(GLProfile::Core);
///
/// // Set the context into debug mode
/// gl_attr.set_context_flags().debug().set();
///
/// // Set the OpenGL context version (OpenGL 3.2)
/// gl_attr.set_context_version(3, 2);
///
/// // Enable anti-aliasing
/// gl_attr.set_multisample_buffers(1);
/// gl_attr.set_multisample_samples(4);
///
/// let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 600).opengl().build().unwrap();
///
/// // Yes, we're still using the Core profile
/// assert_eq!(gl_attr.context_profile(), GLProfile::Core);
/// // ... and we're still using OpenGL 3.2
/// assert_eq!(gl_attr.context_version(), (3, 2));
/// ```
pub mod gl_attr {
use super::{GLAttrTypeUtil, GLProfile};
use crate::get_error;
use crate::sys;
use std::marker::PhantomData;
/// OpenGL context getters and setters. Obtain with `VideoSubsystem::gl_attr()`.
pub struct GLAttr<'a> {
_marker: PhantomData<&'a crate::VideoSubsystem>,
}
impl crate::VideoSubsystem {
/// Obtains access to the OpenGL window attributes.
pub fn gl_attr(&self) -> GLAttr {
GLAttr {
_marker: PhantomData,
}
}
}
macro_rules! gl_set_attribute {
($attr:ident, $value:expr) => {{
let result = unsafe { sys::SDL_GL_SetAttribute(sys::SDL_GLattr::$attr, $value) };
if result != 0 {
// Panic and print the attribute that failed.
panic!(
"couldn't set attribute {}: {}",
stringify!($attr),
get_error()
);
}
}};
}
macro_rules! gl_get_attribute {
($attr:ident) => {{
let mut value = 0;
let result = unsafe { sys::SDL_GL_GetAttribute(sys::SDL_GLattr::$attr, &mut value) };
if result != 0 {
// Panic and print the attribute that failed.
panic!(
"couldn't get attribute {}: {}",
stringify!($attr),
get_error()
);
}
value
}};
}
impl<'a> GLAttr<'a> {
// Note: Wish I could avoid the redundancy of set_property and property (without namespacing into new modules),
// but Rust's `concat_idents!` macro isn't stable.
attrs! {
(SDL_GL_RED_SIZE, set_red_size, red_size, u8,
"the minimum number of bits for the red channel of the color buffer; defaults to 3"),
(SDL_GL_GREEN_SIZE, set_green_size, green_size, u8,
"the minimum number of bits for the green channel of the color buffer; defaults to 3"),
(SDL_GL_BLUE_SIZE, set_blue_size, blue_size, u8,
"the minimum number of bits for the blue channel of the color buffer; defaults to 2"),
(SDL_GL_ALPHA_SIZE, set_alpha_size, alpha_size, u8,
"the minimum number of bits for the alpha channel of the color buffer; defaults to 0"),
(SDL_GL_BUFFER_SIZE, set_buffer_size, buffer_size, u8,
"the minimum number of bits for frame buffer size; defaults to 0"),
(SDL_GL_DOUBLEBUFFER, set_double_buffer, double_buffer, bool,
"whether the output is single or double buffered; defaults to double buffering on"),
(SDL_GL_DEPTH_SIZE, set_depth_size, depth_size, u8,
"the minimum number of bits in the depth buffer; defaults to 16"),
(SDL_GL_STENCIL_SIZE, set_stencil_size, stencil_size, u8,
"the minimum number of bits in the stencil buffer; defaults to 0"),
(SDL_GL_ACCUM_RED_SIZE, set_accum_red_size, accum_red_size, u8,
"the minimum number of bits for the red channel of the accumulation buffer; defaults to 0"),
(SDL_GL_ACCUM_GREEN_SIZE, set_accum_green_size, accum_green_size, u8,
"the minimum number of bits for the green channel of the accumulation buffer; defaults to 0"),
(SDL_GL_ACCUM_BLUE_SIZE, set_accum_blue_size, accum_blue_size, u8,
"the minimum number of bits for the blue channel of the accumulation buffer; defaults to 0"),
(SDL_GL_ACCUM_ALPHA_SIZE, set_accum_alpha_size, accum_alpha_size, u8,
"the minimum number of bits for the alpha channel of the accumulation buffer; defaults to 0"),
(SDL_GL_STEREO, set_stereo, stereo, bool,
"whether the output is stereo 3D; defaults to off"),
(SDL_GL_MULTISAMPLEBUFFERS, set_multisample_buffers, multisample_buffers, u8,
"the number of buffers used for multisample anti-aliasing; defaults to 0"),
(SDL_GL_MULTISAMPLESAMPLES, set_multisample_samples, multisample_samples, u8,
"the number of samples used around the current pixel used for multisample anti-aliasing; defaults to 0"),
(SDL_GL_ACCELERATED_VISUAL, set_accelerated_visual, accelerated_visual, bool,
"whether to require hardware acceleration; false to force software rendering; defaults to allow either"),
(SDL_GL_CONTEXT_MAJOR_VERSION, set_context_major_version, context_major_version, u8,
"OpenGL context major version"),
(SDL_GL_CONTEXT_MINOR_VERSION, set_context_minor_version, context_minor_version, u8,
"OpenGL context minor version"),
(SDL_GL_CONTEXT_PROFILE_MASK, set_context_profile, context_profile, GLProfile,
"type of GL context (Core, Compatibility, ES)"),
(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, set_share_with_current_context, share_with_current_context, bool,
"OpenGL context sharing; defaults to false"),
(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, set_framebuffer_srgb_compatible, framebuffer_srgb_compatible, bool,
"requests sRGB capable visual; defaults to false (>= SDL 2.0.1)"),
(SDL_GL_CONTEXT_NO_ERROR, set_context_no_error, context_no_error, bool,
"disables OpenGL error checking; defaults to false (>= SDL 2.0.6)")
}
/// **Sets** the OpenGL context major and minor versions.
#[inline]
pub fn set_context_version(&self, major: u8, minor: u8) {
self.set_context_major_version(major);
self.set_context_minor_version(minor);
}
/// **Gets** the OpenGL context major and minor versions as a tuple.
#[inline]
pub fn context_version(&self) -> (u8, u8) {
(self.context_major_version(), self.context_minor_version())
}
}
/// The type that allows you to build a OpenGL context configuration.
pub struct ContextFlagsBuilder<'a> {
flags: i32,
_marker: PhantomData<&'a crate::VideoSubsystem>,
}
impl<'a> ContextFlagsBuilder<'a> {
/// Finishes the builder and applies the GL context flags to the GL context.
#[inline]
pub fn set(&self) {
gl_set_attribute!(SDL_GL_CONTEXT_FLAGS, self.flags);
}
/// Sets the context into "debug" mode.
#[inline]
pub fn debug(&mut self) -> &mut ContextFlagsBuilder<'a> {
self.flags |= 0x0001;
self
}
/// Sets the context into "forward compatible" mode.
#[inline]
pub fn forward_compatible(&mut self) -> &mut ContextFlagsBuilder<'a> {
self.flags |= 0x0002;
self
}
#[inline]
pub fn robust_access(&mut self) -> &mut ContextFlagsBuilder<'a> {
self.flags |= 0x0004;
self
}
#[inline]
pub fn reset_isolation(&mut self) -> &mut ContextFlagsBuilder<'a> {
self.flags |= 0x0008;
self
}
}
pub struct ContextFlags {
flags: i32,
}
impl ContextFlags {
#[inline]
pub const fn has_debug(&self) -> bool {
self.flags & 0x0001 != 0
}
#[inline]
pub const fn has_forward_compatible(&self) -> bool {
self.flags & 0x0002 != 0
}
#[inline]
pub const fn has_robust_access(&self) -> bool {
self.flags & 0x0004 != 0
}
#[inline]
pub const fn has_reset_isolation(&self) -> bool {
self.flags & 0x0008 != 0
}
}
impl<'a> GLAttr<'a> {
/// **Sets** any combination of OpenGL context configuration flags.
///
/// Note that calling this will reset any existing context flags.
///
/// # Example
/// ```no_run
/// let sdl_context = sdl2::init().unwrap();
/// let video_subsystem = sdl_context.video().unwrap();
/// let gl_attr = video_subsystem.gl_attr();
///
/// // Sets the GL context into debug mode.
/// gl_attr.set_context_flags().debug().set();
/// ```
pub fn set_context_flags(&self) -> ContextFlagsBuilder {
ContextFlagsBuilder {
flags: 0,
_marker: PhantomData,
}
}
/// **Gets** the applied OpenGL context configuration flags.
///
/// # Example
/// ```no_run
/// let sdl_context = sdl2::init().unwrap();
/// let video_subsystem = sdl_context.video().unwrap();
/// let gl_attr = video_subsystem.gl_attr();
///
/// // Is the GL context in debug mode?
/// if gl_attr.context_flags().has_debug() {
/// println!("Debug mode");
/// }
/// ```
pub fn context_flags(&self) -> ContextFlags {
let flags = gl_get_attribute!(SDL_GL_CONTEXT_FLAGS);
ContextFlags { flags }
}
}
}
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct DisplayMode {
pub format: PixelFormatEnum,
pub w: i32,
pub h: i32,
pub refresh_rate: i32,
}
impl DisplayMode {
pub fn new(format: PixelFormatEnum, w: i32, h: i32, refresh_rate: i32) -> DisplayMode {
DisplayMode {
format,
w,
h,
refresh_rate,
}
}
pub fn from_ll(raw: &sys::SDL_DisplayMode) -> DisplayMode {
DisplayMode::new(
PixelFormatEnum::try_from(raw.format).unwrap_or(PixelFormatEnum::Unknown),
raw.w,
raw.h,
raw.refresh_rate,
)
}
pub fn to_ll(&self) -> sys::SDL_DisplayMode {
sys::SDL_DisplayMode {
format: self.format as u32,
w: self.w as c_int,
h: self.h as c_int,
refresh_rate: self.refresh_rate as c_int,
driverdata: ptr::null_mut(),
}
}
}
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub enum FullscreenType {
Off = 0,
True = 0x00_00_00_01,
Desktop = 0x00_00_10_01,
}
impl FullscreenType {
pub fn from_window_flags(window_flags: u32) -> FullscreenType {
if window_flags & FullscreenType::Desktop as u32 == FullscreenType::Desktop as u32 {
FullscreenType::Desktop
} else if window_flags & FullscreenType::True as u32 == FullscreenType::True as u32 {
FullscreenType::True
} else {
FullscreenType::Off
}
}
}
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub enum WindowPos {
Undefined,
Centered,
Positioned(i32),
}
impl From<i32> for WindowPos {
fn from(pos: i32) -> Self {
WindowPos::Positioned(pos)
}
}
fn to_ll_windowpos(pos: WindowPos) -> c_int {
match pos {
WindowPos::Undefined => sys::SDL_WINDOWPOS_UNDEFINED_MASK as c_int,
WindowPos::Centered => sys::SDL_WINDOWPOS_CENTERED_MASK as c_int,
WindowPos::Positioned(x) => x as c_int,
}
}
pub struct GLContext {
raw: sys::SDL_GLContext,
}
impl Drop for GLContext {
#[doc(alias = "SDL_GL_DeleteContext")]
fn drop(&mut self) {
unsafe { sys::SDL_GL_DeleteContext(self.raw) }
}
}
impl GLContext {
/// Returns true if the OpenGL context is the current one in the thread.
#[doc(alias = "SDL_GL_GetCurrentContext")]
pub fn is_current(&self) -> bool {
let current_raw = unsafe { sys::SDL_GL_GetCurrentContext() };
self.raw == current_raw
}
}
/// Holds a `SDL_Window`
///
/// When the `WindowContext` is dropped, it destroys the `SDL_Window`
pub struct WindowContext {
subsystem: VideoSubsystem,
raw: *mut sys::SDL_Window,
#[allow(dead_code)]
pub(crate) metal_view: sys::SDL_MetalView,
}
impl Drop for WindowContext {
#[inline]
#[doc(alias = "SDL_DestroyWindow")]
fn drop(&mut self) {
unsafe {
#[cfg(target_os = "macos")]
if !self.metal_view.is_null() {
sys::SDL_Metal_DestroyView(self.metal_view);
}
sys::SDL_DestroyWindow(self.raw)
};
}
}
impl WindowContext {
#[inline]
/// # Safety
///
/// Unsound if the `*mut SDL_Window` is used after the `WindowContext` is dropped
pub unsafe fn from_ll(
subsystem: VideoSubsystem,
raw: *mut sys::SDL_Window,
metal_view: sys::SDL_MetalView,
) -> WindowContext {
WindowContext {
subsystem: subsystem.clone(),
raw,
metal_view,
}
}
}
/// Represents a setting for vsync/swap interval.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
#[repr(i32)]
pub enum SwapInterval {
Immediate = 0,
VSync = 1,
LateSwapTearing = -1,
}
impl From<i32> for SwapInterval {
fn from(i: i32) -> Self {
match i {
-1 => SwapInterval::LateSwapTearing,
0 => SwapInterval::Immediate,
1 => SwapInterval::VSync,
other => panic!(
"Invalid value for SwapInterval: {}; valid values are -1, 0, 1",
other
),
}
}
}
/// Represents orientation of a display.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
#[repr(i32)]
pub enum Orientation {
/// The display orientation can’t be determined
Unknown = sys::SDL_DisplayOrientation::SDL_ORIENTATION_UNKNOWN as i32,
/// The display is in landscape mode, with the right side up, relative to portrait mode
Landscape = sys::SDL_DisplayOrientation::SDL_ORIENTATION_LANDSCAPE as i32,
/// The display is in landscape mode, with the left side up, relative to portrait mode
LandscapeFlipped = sys::SDL_DisplayOrientation::SDL_ORIENTATION_LANDSCAPE_FLIPPED as i32,
/// The display is in portrait mode
Portrait = sys::SDL_DisplayOrientation::SDL_ORIENTATION_PORTRAIT as i32,
/// The display is in portrait mode, upside down
PortraitFlipped = sys::SDL_DisplayOrientation::SDL_ORIENTATION_PORTRAIT_FLIPPED as i32,
}
impl Orientation {
pub fn from_ll(orientation: sys::SDL_DisplayOrientation) -> Orientation {
match orientation {
sys::SDL_DisplayOrientation::SDL_ORIENTATION_UNKNOWN => Orientation::Unknown,
sys::SDL_DisplayOrientation::SDL_ORIENTATION_LANDSCAPE => Orientation::Landscape,
sys::SDL_DisplayOrientation::SDL_ORIENTATION_LANDSCAPE_FLIPPED => {
Orientation::LandscapeFlipped
}
sys::SDL_DisplayOrientation::SDL_ORIENTATION_PORTRAIT => Orientation::Portrait,
sys::SDL_DisplayOrientation::SDL_ORIENTATION_PORTRAIT_FLIPPED => {
Orientation::PortraitFlipped
}
}
}
pub fn to_ll(self) -> sys::SDL_DisplayOrientation {
match self {
Orientation::Unknown => sys::SDL_DisplayOrientation::SDL_ORIENTATION_UNKNOWN,
Orientation::Landscape => sys::SDL_DisplayOrientation::SDL_ORIENTATION_LANDSCAPE,
Orientation::LandscapeFlipped => {
sys::SDL_DisplayOrientation::SDL_ORIENTATION_LANDSCAPE_FLIPPED
}
Orientation::Portrait => sys::SDL_DisplayOrientation::SDL_ORIENTATION_PORTRAIT,
Orientation::PortraitFlipped => {
sys::SDL_DisplayOrientation::SDL_ORIENTATION_PORTRAIT_FLIPPED
}
}
}
}
/// Represents a setting for a window flash operation.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
#[repr(i32)]
pub enum FlashOperation {
/// Cancel any window flash state
Cancel = sys::SDL_FlashOperation::SDL_FLASH_CANCEL as i32,
/// Flash the window briefly to get attention
Briefly = sys::SDL_FlashOperation::SDL_FLASH_BRIEFLY as i32,
/// Flash the window until it gets focus
UntilFocused = sys::SDL_FlashOperation::SDL_FLASH_UNTIL_FOCUSED as i32,
}
impl FlashOperation {
pub fn from_ll(flash_operation: sys::SDL_FlashOperation) -> FlashOperation {
match flash_operation {
sys::SDL_FlashOperation::SDL_FLASH_CANCEL => FlashOperation::Cancel,
sys::SDL_FlashOperation::SDL_FLASH_BRIEFLY => FlashOperation::Briefly,
sys::SDL_FlashOperation::SDL_FLASH_UNTIL_FOCUSED => FlashOperation::UntilFocused,
}
}
pub fn to_ll(self) -> sys::SDL_FlashOperation {
match self {
FlashOperation::Cancel => sys::SDL_FlashOperation::SDL_FLASH_CANCEL,
FlashOperation::Briefly => sys::SDL_FlashOperation::SDL_FLASH_BRIEFLY,
FlashOperation::UntilFocused => sys::SDL_FlashOperation::SDL_FLASH_UNTIL_FOCUSED,
}
}
}
/// Represents the "shell" of a `Window`.
///
/// You can set get and set many of the `SDL_Window` properties (i.e., border, size, `PixelFormat`, etc)
///
/// However, you cannot directly access the pixels of the `Window`.
/// It needs to be converted to a `Canvas` to access the rendering functions.
///
/// Note: If a `Window` goes out of scope but it cloned its context,
/// then the `SDL_Window` will not be destroyed until there are no more references to the `WindowContext`.
/// This may happen when a `TextureCreator<Window>` outlives the `Canvas<Window>`
#[derive(Clone)]
pub struct Window {
context: Rc<WindowContext>,
}
impl From<WindowContext> for Window {
fn from(context: WindowContext) -> Window {
Window {
context: Rc::new(context),
}
}
}
impl_raw_accessors!((GLContext, sys::SDL_GLContext));
impl VideoSubsystem {
/// Initializes a new `WindowBuilder`; a convenience method that calls `WindowBuilder::new()`.
pub fn window(&self, title: &str, width: u32, height: u32) -> WindowBuilder {
WindowBuilder::new(self, title, width, height)
}
#[doc(alias = "SDL_GetCurrentVideoDriver")]
pub fn current_video_driver(&self) -> &'static str {
use std::str;
unsafe {
let buf = sys::SDL_GetCurrentVideoDriver();
assert!(!buf.is_null());
str::from_utf8(CStr::from_ptr(buf as *const _).to_bytes()).unwrap()
}
}
#[doc(alias = "SDL_GetNumVideoDisplays")]
pub fn num_video_displays(&self) -> Result<i32, String> {
let result = unsafe { sys::SDL_GetNumVideoDisplays() };
if result < 0 {
Err(get_error())
} else {
Ok(result as i32)
}
}
/// Get the name of the display at the index `display_name`.
///
/// Will return an error if the index is out of bounds or if SDL experienced a failure; inspect
/// the returned string for further info.
#[doc(alias = "SDL_GetDisplayName")]
pub fn display_name(&self, display_index: i32) -> Result<String, String> {
unsafe {
let display = sys::SDL_GetDisplayName(display_index as c_int);
if display.is_null() {
Err(get_error())
} else {
Ok(CStr::from_ptr(display as *const _)
.to_str()
.unwrap()
.to_owned())
}
}
}
#[doc(alias = "SDL_GetDisplayBounds")]
pub fn display_bounds(&self, display_index: i32) -> Result<Rect, String> {
let mut out = mem::MaybeUninit::uninit();
let result =
unsafe { sys::SDL_GetDisplayBounds(display_index as c_int, out.as_mut_ptr()) == 0 };
if result {
let out = unsafe { out.assume_init() };
Ok(Rect::from_ll(out))
} else {
Err(get_error())
}
}
#[doc(alias = "SDL_GetDisplayUsableBounds")]
pub fn display_usable_bounds(&self, display_index: i32) -> Result<Rect, String> {
let mut out = mem::MaybeUninit::uninit();
let result =
unsafe { sys::SDL_GetDisplayUsableBounds(display_index as c_int, out.as_mut_ptr()) };
if result == 0 {
let out = unsafe { out.assume_init() };
Ok(Rect::from_ll(out))
} else {
Err(get_error())
}
}
#[doc(alias = "SDL_GetNumDisplayModes")]
pub fn num_display_modes(&self, display_index: i32) -> Result<i32, String> {
let result = unsafe { sys::SDL_GetNumDisplayModes(display_index as c_int) };
if result < 0 {
Err(get_error())
} else {
Ok(result as i32)
}
}
#[doc(alias = "SDL_GetDisplayMode")]
pub fn display_mode(&self, display_index: i32, mode_index: i32) -> Result<DisplayMode, String> {
let mut dm = mem::MaybeUninit::uninit();
let result = unsafe {
sys::SDL_GetDisplayMode(display_index as c_int, mode_index as c_int, dm.as_mut_ptr())
== 0
};
if result {
let dm = unsafe { dm.assume_init() };
Ok(DisplayMode::from_ll(&dm))
} else {
Err(get_error())
}
}
#[doc(alias = "SDL_GetDesktopDisplayMode")]
pub fn desktop_display_mode(&self, display_index: i32) -> Result<DisplayMode, String> {
let mut dm = mem::MaybeUninit::uninit();
let result =
unsafe { sys::SDL_GetDesktopDisplayMode(display_index as c_int, dm.as_mut_ptr()) == 0 };
if result {
let dm = unsafe { dm.assume_init() };
Ok(DisplayMode::from_ll(&dm))
} else {
Err(get_error())
}
}
#[doc(alias = "SDL_GetCurrentDisplayMode")]
pub fn current_display_mode(&self, display_index: i32) -> Result<DisplayMode, String> {
let mut dm = mem::MaybeUninit::uninit();
let result =
unsafe { sys::SDL_GetCurrentDisplayMode(display_index as c_int, dm.as_mut_ptr()) == 0 };
if result {
let dm = unsafe { dm.assume_init() };
Ok(DisplayMode::from_ll(&dm))
} else {
Err(get_error())
}
}
#[doc(alias = "SDL_GetClosestDisplayMode")]
pub fn closest_display_mode(
&self,
display_index: i32,
mode: &DisplayMode,
) -> Result<DisplayMode, String> {
let input = mode.to_ll();
let mut dm = mem::MaybeUninit::uninit();
let result = unsafe {
sys::SDL_GetClosestDisplayMode(display_index as c_int, &input, dm.as_mut_ptr())
};
if result.is_null() {
Err(get_error())
} else {
let dm = unsafe { dm.assume_init() };
Ok(DisplayMode::from_ll(&dm))
}
}
/// Return a triplet `(ddpi, hdpi, vdpi)` containing the diagonal, horizontal and vertical
/// dots/pixels-per-inch of a display
#[doc(alias = "SDL_GetDisplayDPI")]
pub fn display_dpi(&self, display_index: i32) -> Result<(f32, f32, f32), String> {
let mut ddpi = 0.0;
let mut hdpi = 0.0;
let mut vdpi = 0.0;
let result = unsafe {
sys::SDL_GetDisplayDPI(display_index as c_int, &mut ddpi, &mut hdpi, &mut vdpi)
};
if result < 0 {
Err(get_error())
} else {
Ok((ddpi, hdpi, vdpi))
}
}
/// Return orientation of a display or Unknown if orientation could not be determined.
#[doc(alias = "SDL_GetDisplayOrientation")]
pub fn display_orientation(&self, display_index: i32) -> Orientation {
Orientation::from_ll(unsafe { sys::SDL_GetDisplayOrientation(display_index as c_int) })
}
#[doc(alias = "SDL_IsScreenSaverEnabled")]
pub fn is_screen_saver_enabled(&self) -> bool {
unsafe { sys::SDL_IsScreenSaverEnabled() == sys::SDL_bool::SDL_TRUE }
}
#[doc(alias = "SDL_EnableScreenSaver")]
pub fn enable_screen_saver(&self) {
unsafe { sys::SDL_EnableScreenSaver() }
}
#[doc(alias = "SDL_DisableScreenSaver")]
pub fn disable_screen_saver(&self) {
unsafe { sys::SDL_DisableScreenSaver() }
}
/// Loads the default OpenGL library.
///
/// This should be done after initializing the video driver, but before creating any OpenGL windows.
/// If no OpenGL library is loaded, the default library will be loaded upon creation of the first OpenGL window.
///
/// If a different library is already loaded, this function will return an error.
#[doc(alias = "SDL_GL_LoadLibrary")]
pub fn gl_load_library_default(&self) -> Result<(), String> {
unsafe {
if sys::SDL_GL_LoadLibrary(ptr::null()) == 0 {
Ok(())
} else {
Err(get_error())
}
}
}
/// Loads the OpenGL library using a platform-dependent OpenGL library name (usually a file path).
///
/// This should be done after initializing the video driver, but before creating any OpenGL windows.
/// If no OpenGL library is loaded, the default library will be loaded upon creation of the first OpenGL window.
///
/// If a different library is already loaded, this function will return an error.
#[doc(alias = "SDL_GL_LoadLibrary")]
pub fn gl_load_library<P: AsRef<::std::path::Path>>(&self, path: P) -> Result<(), String> {
unsafe {
// TODO: use OsStr::to_cstring() once it's stable
let path = CString::new(path.as_ref().to_str().unwrap()).unwrap();
if sys::SDL_GL_LoadLibrary(path.as_ptr() as *const c_char) == 0 {
Ok(())
} else {
Err(get_error())
}
}
}
/// Unloads the current OpenGL library.
///
/// To completely unload the library, this should be called for every successful load of the
/// OpenGL library.
#[doc(alias = "SDL_GL_UnloadLibrary")]
pub fn gl_unload_library(&self) {
unsafe {
sys::SDL_GL_UnloadLibrary();
}
}
/// Gets the pointer to the named OpenGL function.
///
/// This is useful for OpenGL wrappers such as [`gl-rs`](https://github.com/bjz/gl-rs).
#[doc(alias = "SDL_GL_GetProcAddress")]
pub fn gl_get_proc_address(&self, procname: &str) -> *const () {
match CString::new(procname) {
Ok(procname) => unsafe {
sys::SDL_GL_GetProcAddress(procname.as_ptr() as *const c_char) as *const ()
},
// string contains a nul byte - it won't match anything.
Err(_) => ptr::null(),
}
}
#[doc(alias = "SDL_GL_ExtensionSupported")]
pub fn gl_extension_supported(&self, extension: &str) -> bool {
match CString::new(extension) {
Ok(extension) => unsafe {
sys::SDL_GL_ExtensionSupported(extension.as_ptr() as *const c_char)
!= sys::SDL_bool::SDL_FALSE
},
// string contains a nul byte - it won't match anything.
Err(_) => false,
}
}
#[doc(alias = "SDL_GL_GetCurrentWindow")]
pub fn gl_get_current_window_id(&self) -> Result<u32, String> {
let raw = unsafe { sys::SDL_GL_GetCurrentWindow() };
if raw.is_null() {
Err(get_error())
} else {
let id = unsafe { sys::SDL_GetWindowID(raw) };
Ok(id)
}
}
/// Releases the thread's current OpenGL context, i.e. sets the current OpenGL context to nothing.
#[doc(alias = "SDL_GL_MakeCurrent")]
pub fn gl_release_current_context(&self) -> Result<(), String> {
let result = unsafe { sys::SDL_GL_MakeCurrent(ptr::null_mut(), ptr::null_mut()) };
if result == 0 {
Ok(())
} else {
Err(get_error())
}
}
#[doc(alias = "SDL_GL_SetSwapInterval")]
pub fn gl_set_swap_interval<S: Into<SwapInterval>>(&self, interval: S) -> Result<(), String> {
let result = unsafe { sys::SDL_GL_SetSwapInterval(interval.into() as c_int) };
if result == 0 {
Ok(())
} else {
Err(get_error())
}