-
Notifications
You must be signed in to change notification settings - Fork 123
/
lib.rs
3851 lines (3504 loc) · 128 KB
/
lib.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
// Copyright 2013-2016 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![crate_type = "lib"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![crate_name = "glfw"]
#![deny(
rust_2018_compatibility,
rust_2018_idioms,
nonstandard_style,
unused,
future_incompatible,
missing_copy_implementations,
missing_debug_implementations,
missing_abi,
clippy::doc_markdown
)]
#![allow(non_upper_case_globals)]
//! An idiomatic wrapper for the GLFW library.
//!
//! # Example
//!
//! ~~~no_run
//! extern crate glfw;
//!
//! use glfw::{Action, Context, Key};
//!
//! fn main() {
//! use glfw::fail_on_errors;
//! let mut glfw = glfw::init(fail_on_errors!()).unwrap();
//!
//! // Create a windowed mode window and its OpenGL context
//! let (mut window, events) = glfw.create_window(300, 300, "Hello this is window", glfw::WindowMode::Windowed)
//! .expect("Failed to create GLFW window.");
//!
//! // Make the window's context current
//! window.make_current();
//! window.set_key_polling(true);
//!
//! // Loop until the user closes the window
//! while !window.should_close() {
//! // Swap front and back buffers
//! window.swap_buffers();
//!
//! // Poll for and process events
//! glfw.poll_events();
//! for (_, event) in glfw::flush_messages(&events) {
//! println!("{:?}", event);
//! match event {
//! glfw::WindowEvent::Key(Key::Escape, _, Action::Press, _) => {
//! window.set_should_close(true)
//! },
//! _ => {},
//! }
//! }
//! }
//! }
//! ~~~
//!
//! # Cargo Features
//!
//! Use the `vulkan` feature flag to enable all Vulkan functions and types.
//!
//! Use the `image` feature flag to enable use of the [`image`](https://github.com/PistonDevelopers/image) library for cursors and icons.
//!
//! Use the `all` feature flag to enable both at the same time.
//!
// TODO: Document differences between GLFW and glfw-rs
macro_rules! make_user_callback_functions {
(
doc -> $doc:literal,
set -> $set:ident,
unset -> $unset:ident,
poll -> $poll:ident,
callback_field -> $callback_field:ident,
poll_field -> $poll_field:ident,
glfw -> $glfw:ident,
args -> ($($args:ty),*),
secret -> $secret:ident
) => {
#[doc = $doc]
pub fn $set<T>(&mut self, callback: T)
where T: FnMut(&mut Window, $($args),*) + 'static {
unsafe {
let callbacks = WindowCallbacks::get_callbacks(self.ptr);
callbacks.$callback_field = Some(Box::new(callback));
ffi::$glfw(self.ptr, Some(Self::$secret));
}
}
#[doc = $doc]
pub fn $unset(&mut self) {
unsafe {
let callbacks = WindowCallbacks::get_callbacks(self.ptr);
callbacks.$callback_field = None;
// We're removing the callback, if theres no polling either, set to null
if !callbacks.$poll_field {
ffi::$glfw(self.ptr, None);
}
}
}
#[doc = $doc]
pub fn $poll(&mut self, should_poll: bool) {
unsafe {
let callbacks = WindowCallbacks::get_callbacks(self.ptr);
callbacks.$poll_field = should_poll;
// If no polling and not custom callback, set glfw callback to null
if should_poll {
ffi::$glfw(self.ptr, Some(Self::$secret));
} else if callbacks.$callback_field.is_none() {
ffi::$glfw(self.ptr, None);
}
}
}
}
}
macro_rules! new_callback {
(
doc -> $doc:literal,
set -> $set:ident,
unset -> $unset:ident,
poll -> $poll:ident,
callback_field -> $callback_field:ident,
poll_field -> $poll_field:ident,
window_event -> $window_event:ident ($($args:ty),+),
glfw -> $glfw:ident ($($glfw_arg_names:ident: $glfw_args:ty),*),
convert_args -> ($($convert_args:expr),*),
secret -> $secret:ident
) => {
#[allow(unused_unsafe)]
extern "C" fn $secret(glfw_window: *mut GLFWwindow, $($glfw_arg_names: $glfw_args),*) {
unsafe {
let callbacks = WindowCallbacks::get_callbacks(glfw_window);
let window = &mut *callbacks.window_ptr;
if let Some(func) = &mut callbacks.$callback_field {
func(window, $($convert_args),*);
}
if callbacks.$poll_field {
let event = (ffi::glfwGetTime() as f64, WindowEvent::$window_event($($convert_args),*));
if let Some(event) = callbacks::unbuffered::handle(glfw_window as WindowId, event) {
callbacks.sender.send(event);
}
}
}
}
make_user_callback_functions!(
doc -> $doc,
set -> $set,
unset -> $unset,
poll -> $poll,
callback_field -> $callback_field,
poll_field -> $poll_field,
glfw -> $glfw,
args -> ($($args),*),
secret -> $secret
);
};
(
doc -> $doc:literal,
set -> $set:ident,
unset -> $unset:ident,
poll -> $poll:ident,
callback_field -> $callback_field:ident,
poll_field -> $poll_field:ident,
window_event -> $window_event:ident,
glfw -> $glfw:ident ($($glfw_arg_names:ident: $glfw_args:ty),*),
convert_args -> ($($convert_args:expr),*),
secret -> $secret:ident
) => {
#[allow(unused_unsafe)]
extern "C" fn $secret(glfw_window: *mut GLFWwindow, $($glfw_arg_names: $glfw_args),*) {
unsafe {
let callbacks = WindowCallbacks::get_callbacks(glfw_window);
let window = &mut *callbacks.window_ptr;
if let Some(func) = &mut callbacks.$callback_field {
func(window);
}
if callbacks.$poll_field {
let event = (ffi::glfwGetTime() as f64, WindowEvent::$window_event);
if let Some(event) = callbacks::unbuffered::handle(glfw_window as WindowId, event) {
callbacks.sender.send(event);
}
}
}
}
make_user_callback_functions!(
doc -> $doc,
set -> $set,
unset -> $unset,
poll -> $poll,
callback_field -> $callback_field,
poll_field -> $poll_field,
glfw -> $glfw,
args -> (),
secret -> $secret
);
}
}
#[cfg(feature = "log")]
#[macro_use]
extern crate log;
#[macro_use]
extern crate bitflags;
#[cfg(feature = "image")]
extern crate image;
#[cfg(all(target_os = "macos"))]
#[macro_use]
extern crate objc;
use std::collections::VecDeque;
use raw_window_handle::{HasRawWindowHandle, RawWindowHandle, HasRawDisplayHandle, RawDisplayHandle};
use std::error;
use std::ffi::{CStr, CString};
use std::fmt;
use std::marker::Send;
use std::mem;
#[cfg(feature = "vulkan")]
use std::os::raw::c_uint;
use std::os::raw::{c_char, c_double, c_float, c_int};
use std::os::raw::{c_uchar, c_ushort};
#[cfg(not(target_os = "emscripten"))]
use std::os::raw::c_void;
use std::path::PathBuf;
use std::ptr;
use std::ptr::{null, null_mut};
use std::slice;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{channel, Receiver, Sender};
#[allow(unused)]
use std::ffi::*;
use std::ops::{Deref, DerefMut};
use std::sync::{Arc, Mutex};
#[cfg(feature = "vulkan")]
use ash::vk;
use crate::ffi::GLFWwindow;
/// Alias to `MouseButton1`, supplied for improved clarity.
pub use self::MouseButton::Button1 as MouseButtonLeft;
/// Alias to `MouseButton2`, supplied for improved clarity.
pub use self::MouseButton::Button2 as MouseButtonRight;
/// Alias to `MouseButton3`, supplied for improved clarity.
pub use self::MouseButton::Button3 as MouseButtonMiddle;
mod callbacks;
pub mod ffi;
#[derive(Debug)]
#[repr(transparent)]
pub struct PWindow(Box<Window>);
impl PWindow {
fn raw_ptr(&mut self) -> *mut Window {
self.0.deref_mut()
}
}
impl Deref for PWindow {
type Target = Window;
fn deref(&self) -> &Self::Target {
self.0.deref()
}
}
impl DerefMut for PWindow {
fn deref_mut(&mut self) -> &mut Self::Target {
self.0.deref_mut()
}
}
/// Unique identifier for a `Window`.
pub type WindowId = usize;
#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Version {
pub major: u64,
pub minor: u64,
pub patch: u64,
}
/// Input actions.
#[repr(i32)]
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub enum Action {
Release = ffi::RELEASE,
Press = ffi::PRESS,
Repeat = ffi::REPEAT,
}
/// Input keys.
#[repr(i32)]
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub enum Key {
Space = ffi::KEY_SPACE,
Apostrophe = ffi::KEY_APOSTROPHE,
Comma = ffi::KEY_COMMA,
Minus = ffi::KEY_MINUS,
Period = ffi::KEY_PERIOD,
Slash = ffi::KEY_SLASH,
Num0 = ffi::KEY_0,
Num1 = ffi::KEY_1,
Num2 = ffi::KEY_2,
Num3 = ffi::KEY_3,
Num4 = ffi::KEY_4,
Num5 = ffi::KEY_5,
Num6 = ffi::KEY_6,
Num7 = ffi::KEY_7,
Num8 = ffi::KEY_8,
Num9 = ffi::KEY_9,
Semicolon = ffi::KEY_SEMICOLON,
Equal = ffi::KEY_EQUAL,
A = ffi::KEY_A,
B = ffi::KEY_B,
C = ffi::KEY_C,
D = ffi::KEY_D,
E = ffi::KEY_E,
F = ffi::KEY_F,
G = ffi::KEY_G,
H = ffi::KEY_H,
I = ffi::KEY_I,
J = ffi::KEY_J,
K = ffi::KEY_K,
L = ffi::KEY_L,
M = ffi::KEY_M,
N = ffi::KEY_N,
O = ffi::KEY_O,
P = ffi::KEY_P,
Q = ffi::KEY_Q,
R = ffi::KEY_R,
S = ffi::KEY_S,
T = ffi::KEY_T,
U = ffi::KEY_U,
V = ffi::KEY_V,
W = ffi::KEY_W,
X = ffi::KEY_X,
Y = ffi::KEY_Y,
Z = ffi::KEY_Z,
LeftBracket = ffi::KEY_LEFT_BRACKET,
Backslash = ffi::KEY_BACKSLASH,
RightBracket = ffi::KEY_RIGHT_BRACKET,
GraveAccent = ffi::KEY_GRAVE_ACCENT,
World1 = ffi::KEY_WORLD_1,
World2 = ffi::KEY_WORLD_2,
Escape = ffi::KEY_ESCAPE,
Enter = ffi::KEY_ENTER,
Tab = ffi::KEY_TAB,
Backspace = ffi::KEY_BACKSPACE,
Insert = ffi::KEY_INSERT,
Delete = ffi::KEY_DELETE,
Right = ffi::KEY_RIGHT,
Left = ffi::KEY_LEFT,
Down = ffi::KEY_DOWN,
Up = ffi::KEY_UP,
PageUp = ffi::KEY_PAGE_UP,
PageDown = ffi::KEY_PAGE_DOWN,
Home = ffi::KEY_HOME,
End = ffi::KEY_END,
CapsLock = ffi::KEY_CAPS_LOCK,
ScrollLock = ffi::KEY_SCROLL_LOCK,
NumLock = ffi::KEY_NUM_LOCK,
PrintScreen = ffi::KEY_PRINT_SCREEN,
Pause = ffi::KEY_PAUSE,
F1 = ffi::KEY_F1,
F2 = ffi::KEY_F2,
F3 = ffi::KEY_F3,
F4 = ffi::KEY_F4,
F5 = ffi::KEY_F5,
F6 = ffi::KEY_F6,
F7 = ffi::KEY_F7,
F8 = ffi::KEY_F8,
F9 = ffi::KEY_F9,
F10 = ffi::KEY_F10,
F11 = ffi::KEY_F11,
F12 = ffi::KEY_F12,
F13 = ffi::KEY_F13,
F14 = ffi::KEY_F14,
F15 = ffi::KEY_F15,
F16 = ffi::KEY_F16,
F17 = ffi::KEY_F17,
F18 = ffi::KEY_F18,
F19 = ffi::KEY_F19,
F20 = ffi::KEY_F20,
F21 = ffi::KEY_F21,
F22 = ffi::KEY_F22,
F23 = ffi::KEY_F23,
F24 = ffi::KEY_F24,
F25 = ffi::KEY_F25,
Kp0 = ffi::KEY_KP_0,
Kp1 = ffi::KEY_KP_1,
Kp2 = ffi::KEY_KP_2,
Kp3 = ffi::KEY_KP_3,
Kp4 = ffi::KEY_KP_4,
Kp5 = ffi::KEY_KP_5,
Kp6 = ffi::KEY_KP_6,
Kp7 = ffi::KEY_KP_7,
Kp8 = ffi::KEY_KP_8,
Kp9 = ffi::KEY_KP_9,
KpDecimal = ffi::KEY_KP_DECIMAL,
KpDivide = ffi::KEY_KP_DIVIDE,
KpMultiply = ffi::KEY_KP_MULTIPLY,
KpSubtract = ffi::KEY_KP_SUBTRACT,
KpAdd = ffi::KEY_KP_ADD,
KpEnter = ffi::KEY_KP_ENTER,
KpEqual = ffi::KEY_KP_EQUAL,
LeftShift = ffi::KEY_LEFT_SHIFT,
LeftControl = ffi::KEY_LEFT_CONTROL,
LeftAlt = ffi::KEY_LEFT_ALT,
LeftSuper = ffi::KEY_LEFT_SUPER,
RightShift = ffi::KEY_RIGHT_SHIFT,
RightControl = ffi::KEY_RIGHT_CONTROL,
RightAlt = ffi::KEY_RIGHT_ALT,
RightSuper = ffi::KEY_RIGHT_SUPER,
Menu = ffi::KEY_MENU,
Unknown = ffi::KEY_UNKNOWN,
}
/// Wrapper around `glfwGetKeyName`
pub fn get_key_name(key: Option<Key>, scancode: Option<Scancode>) -> Option<String> {
unsafe {
string_from_nullable_c_str(ffi::glfwGetKeyName(
match key {
Some(k) => k as c_int,
None => ffi::KEY_UNKNOWN,
},
scancode.unwrap_or(ffi::KEY_UNKNOWN),
))
}
}
/// Wrapper around `glfwGetKeyName`
#[deprecated(
since = "0.16.0",
note = "'key_name' can cause a segfault, use 'get_key_name' instead"
)]
pub fn key_name(key: Option<Key>, scancode: Option<Scancode>) -> String {
unsafe {
string_from_c_str(ffi::glfwGetKeyName(
match key {
Some(k) => k as c_int,
None => ffi::KEY_UNKNOWN,
},
scancode.unwrap_or(ffi::KEY_UNKNOWN),
))
}
}
/// Wrapper around `glfwGetKeyScancode`.
pub fn get_key_scancode(key: Option<Key>) -> Option<Scancode> {
unsafe {
match ffi::glfwGetKeyScancode(match key {
Some(key) => key as c_int,
None => ffi::KEY_UNKNOWN,
}) {
ffi::KEY_UNKNOWN => None,
scancode => Some(scancode as Scancode),
}
}
}
impl Key {
/// Wrapper around `glfwGetKeyName` without scancode
#[deprecated(
since = "0.16.0",
note = "Key method 'name' can cause a segfault, use 'get_name' instead"
)]
pub fn name(&self) -> String {
#[allow(deprecated)]
key_name(Some(*self), None)
}
/// Wrapper around `glfwGetKeyName` without scancode
pub fn get_name(&self) -> Option<String> {
get_key_name(Some(*self), None)
}
/// Wrapper around `glfwGetKeyScancode`.
pub fn get_scancode(&self) -> Option<Scancode> {
get_key_scancode(Some(*self))
}
}
/// Mouse buttons. The `MouseButtonLeft`, `MouseButtonRight`, and
/// `MouseButtonMiddle` aliases are supplied for convenience.
#[repr(i32)]
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub enum MouseButton {
/// The left mouse button. A `MouseButtonLeft` alias is provided to improve clarity.
Button1 = ffi::MOUSE_BUTTON_1,
/// The right mouse button. A `MouseButtonRight` alias is provided to improve clarity.
Button2 = ffi::MOUSE_BUTTON_2,
/// The middle mouse button. A `MouseButtonMiddle` alias is provided to improve clarity.
Button3 = ffi::MOUSE_BUTTON_3,
Button4 = ffi::MOUSE_BUTTON_4,
Button5 = ffi::MOUSE_BUTTON_5,
Button6 = ffi::MOUSE_BUTTON_6,
Button7 = ffi::MOUSE_BUTTON_7,
Button8 = ffi::MOUSE_BUTTON_8,
}
impl MouseButton {
/// Converts from `i32`.
pub fn from_i32(n: i32) -> Option<MouseButton> {
if (0..=ffi::MOUSE_BUTTON_LAST).contains(&n) {
Some(unsafe { mem::transmute(n) })
} else {
None
}
}
}
/// Formats the type using aliases rather than the default variant names.
///
/// # Example
///
/// ~~~ignore
/// assert_eq(format!("{}", glfw::MouseButtonLeft), "MouseButton1");
/// assert_eq(format!("{}", glfw::DebugAliases(glfw::MouseButtonLeft)), "MouseButtonLeft");
/// ~~~
pub struct DebugAliases<T>(pub T);
impl fmt::Debug for DebugAliases<MouseButton> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let DebugAliases(button) = *self;
match button {
MouseButtonLeft => write!(f, "MouseButtonLeft"),
MouseButtonRight => write!(f, "MouseButtonRight"),
MouseButtonMiddle => write!(f, "MouseButtonMiddle"),
button => button.fmt(f),
}
}
}
/// Tokens corresponding to various error types.
#[repr(i32)]
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub enum Error {
NoError = ffi::NO_ERROR,
NotInitialized = ffi::NOT_INITIALIZED,
NoCurrentContext = ffi::NO_CURRENT_CONTEXT,
InvalidEnum = ffi::INVALID_ENUM,
InvalidValue = ffi::INVALID_VALUE,
OutOfMemory = ffi::OUT_OF_MEMORY,
ApiUnavailable = ffi::API_UNAVAILABLE,
VersionUnavailable = ffi::VERSION_UNAVAILABLE,
PlatformError = ffi::PLATFORM_ERROR,
FormatUnavailable = ffi::FORMAT_UNAVAILABLE,
NoWindowContext = ffi::NO_WINDOW_CONTEXT,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let description = match *self {
Error::NoError => "NoError",
Error::NotInitialized => "NotInitialized",
Error::NoCurrentContext => "NoCurrentContext",
Error::InvalidEnum => "InvalidEnum",
Error::InvalidValue => "InvalidValue",
Error::OutOfMemory => "OutOfMemory",
Error::ApiUnavailable => "ApiUnavailable",
Error::VersionUnavailable => "VersionUnavailable",
Error::PlatformError => "PlatformError",
Error::FormatUnavailable => "FormatUnavailable",
Error::NoWindowContext => "NoWindowContext",
};
f.write_str(description)
}
}
impl error::Error for Error {}
/// The function to be used with the `fail_on_errors!()` callback.
pub fn fail_on_errors(_: Error, description: String) {
panic!("GLFW Error: {}", description);
}
/// A callback that triggers a task failure when an error is encountered.
#[macro_export]
macro_rules! fail_on_errors {
() => {{
|error, description| {
fail_on_errors(error, description);
}
}}
}
#[cfg(feature = "log")]
/// The function to be used with the `LOG_ERRORS` callback.
pub fn log_errors(_: Error, description: String) {
error!("GLFW Error: {}", description);
}
#[cfg(not(feature = "log"))]
/// The function to be used with the `LOG_ERRORS` callback.
pub fn log_errors(_: Error, description: String) {
eprintln!("GLFW Error: {}", description);
}
/// A callback that logs each error as it is encountered without triggering a
/// task failure
#[macro_export]
macro_rules! log_errors {
() => {{
|error, description| {
log_errors(error, description);
}
}}
}
/// When not using the `image` library, or if you just want to,
/// you can specify an image from its raw pixel data using this structure.
#[derive(Debug)]
pub struct PixelImage {
/// Width of the image in pixels
pub width: u32,
/// Height of the image in pixels
pub height: u32,
/// Pixels are 4 bytes each, one byte for each RGBA subpixel.
pub pixels: Vec<u32>,
}
/// Cursor modes.
#[repr(i32)]
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub enum CursorMode {
Normal = ffi::CURSOR_NORMAL,
Hidden = ffi::CURSOR_HIDDEN,
Disabled = ffi::CURSOR_DISABLED,
}
/// Standard cursors provided by GLFW
#[repr(i32)]
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub enum StandardCursor {
/// The regular arrow cursor shape.
Arrow = ffi::ARROW_CURSOR,
/// The text input I-beam cursor shape.
IBeam = ffi::IBEAM_CURSOR,
/// The crosshair shape.
Crosshair = ffi::CROSSHAIR_CURSOR,
/// The hand shape.
Hand = ffi::HAND_CURSOR,
/// The horizontal resize arrow shape.
HResize = ffi::HRESIZE_CURSOR,
/// The vertical resize arrow shape.
VResize = ffi::VRESIZE_CURSOR,
}
/// Represents a window cursor that can be used to display any
/// of the standard cursors or load a custom cursor from an image.
///
/// Note that the cursor object has a lifetime and will not display
/// correctly after it has been dropped.
#[derive(Debug)]
pub struct Cursor {
ptr: *mut ffi::GLFWcursor,
}
impl Drop for Cursor {
fn drop(&mut self) {
unsafe { ffi::glfwDestroyCursor(self.ptr) }
}
}
impl Cursor {
/// Create a new cursor using `glfwCreateStandardCursor`
pub fn standard(cursor: StandardCursor) -> Cursor {
Cursor {
ptr: unsafe { ffi::glfwCreateStandardCursor(cursor as c_int) },
}
}
/// Creates a new cursor from the image provided via `glfwCreateCursor`
///
/// Note that the cursor image will be the same size as the image provided,
/// so scaling it beforehand may be required.
///
/// The cursor hotspot is specified in pixels, relative to the upper-left
/// corner of the cursor image. Like all other coordinate systems in GLFW,
/// the X-axis points to the right and the Y-axis points down.
#[cfg(feature = "image")]
pub fn create(image: image::RgbaImage, x_hotspot: u32, y_hotspot: u32) -> Cursor {
let (width, height) = image.dimensions();
let image_data = image.into_vec();
let glfw_image = ffi::GLFWimage {
width: width as c_int,
height: height as c_int,
pixels: image_data.as_ptr() as *const c_uchar,
};
Cursor {
ptr: unsafe {
ffi::glfwCreateCursor(
&glfw_image as *const ffi::GLFWimage,
x_hotspot as c_int,
y_hotspot as c_int,
)
},
}
}
/// Creates a new cursor from the `PixelImage` provided via `glfwCreateCursor`
///
/// Note that the cursor image will be the same size as the image provided,
/// so scaling it beforehand may be required.
///
/// The cursor hotspot is specified in pixels, relative to the upper-left
/// corner of the cursor image. Like all other coordinate systems in GLFW,
/// the X-axis points to the right and the Y-axis points down.
pub fn create_from_pixels(image: PixelImage, x_hotspot: u32, y_hotspot: u32) -> Cursor {
let glfw_image = ffi::GLFWimage {
width: image.width as c_int,
height: image.height as c_int,
pixels: image.pixels.as_ptr() as *const c_uchar,
};
Cursor {
ptr: unsafe {
ffi::glfwCreateCursor(
&glfw_image as *const ffi::GLFWimage,
x_hotspot as c_int,
y_hotspot as c_int,
)
},
}
}
}
/// Describes a single video mode.
#[derive(Copy, Clone)]
pub struct VidMode {
pub width: u32,
pub height: u32,
pub red_bits: u32,
pub green_bits: u32,
pub blue_bits: u32,
pub refresh_rate: u32,
}
/// Describes the gamma ramp of a monitor.
#[derive(Debug)]
pub struct GammaRamp {
pub red: Vec<c_ushort>,
pub green: Vec<c_ushort>,
pub blue: Vec<c_ushort>,
}
/// `ContextReleaseBehavior` specifies the release behavior to be used by the context.
#[repr(i32)]
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub enum ContextReleaseBehavior {
Any = ffi::ANY_RELEASE_BEHAVIOR,
/// `Flush` tells the context to flush the pipeline whenever the context is released from being the current one.
Flush = ffi::RELEASE_BEHAVIOR_FLUSH,
/// `None` tells the context to NOT flush the pipeline on release
None = ffi::RELEASE_BEHAVIOR_NONE,
}
/// Specifies the API to use to create the context
#[repr(i32)]
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub enum ContextCreationApi {
Native = ffi::NATIVE_CONTEXT_API,
Egl = ffi::EGL_CONTEXT_API,
OsMesa = ffi::OSMESA_CONTEXT_API,
}
/// Specifies how the context should handle swapping the buffers.
///
/// i.e. the number of screen updates to wait from the time
/// `glfwSwapBuffers`/`context.swap_buffers`
/// was called before swapping the buffers and returning.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub enum SwapInterval {
/// Specifies no waits
None,
/// If either of the `WGL_EXT_swap_control_tear` and `GLX_EXT_swap_control_tear` extensions
/// are enabled, allows the adaptively swap the frame. Sometimes called Adaptive V-sync
Adaptive,
/// Synchronizes the buffers every N frames. Set to 1 for V-sync
Sync(u32),
}
/// An OpenGL process address.
pub type GLProc = ffi::GLFWglproc;
/// A Vulkan process address
#[cfg(feature = "vulkan")]
pub type VkProc = ffi::GLFWvkproc;
/// Counts for (Calling glfwInit) - (Calling glfwTerminate)
/// It uses for "global" refference counting for Glfw.
static REF_COUNT_FOR_GLFW: AtomicUsize = AtomicUsize::new(0);
/// A struct that represents a thread safe handle to a `Glfw`
#[derive(Debug)]
pub struct ThreadSafeGlfw {
glfw: Glfw
}
impl ThreadSafeGlfw {
/// Creates a new `Glfw` wrapper that can be shared between threads
pub fn from(glfw: &mut Glfw) -> Self {
Self {
glfw: glfw.clone()
}
}
/// Wrapper function, please refer to [`Glfw::set_swap_interval`]
pub fn set_swap_interval(&mut self, interval: SwapInterval) {
self.glfw.set_swap_interval(interval);
}
/// Wrapper function, please refer to [`Glfw::extension_supported`]
pub fn extension_supported(&self, extension: &str) -> bool {
self.glfw.extension_supported(extension)
}
/// Wrapper function, please refer to [`Glfw::get_time`]
pub fn get_time(&self) -> f64 {
self.glfw.get_time()
}
/// Wrapper function, please refer to [`Glfw::set_time`]
pub fn set_time(&mut self, time: f64) {
self.glfw.set_time(time);
}
/// Wrapper function, please refer to [`Glfw::vulkan_supported`]
#[cfg(feature = "vulkan")]
pub fn vulkan_supported(&self) -> bool {
self.glfw.vulkan_supported()
}
/// Wrapper function, please refer to [`Glfw::get_required_instance_extensions`]
#[cfg(feature = "vulkan")]
pub fn get_required_instance_extensions(&self) -> Option<Vec<String>> {
self.glfw.get_required_instance_extensions()
}
/// Wrapper function, please refer to [`Glfw::get_instance_proc_address_raw`]
#[cfg(feature = "vulkan")]
pub fn get_instance_proc_address_raw(&self, instance: vk::Instance, procname: &str) -> VkProc {
self.glfw.get_instance_proc_address_raw(instance, procname)
}
/// Wrapper function, please refer to [`Glfw::get_physical_device_presentation_support_raw`]
#[cfg(feature = "vulkan")]
pub fn get_physical_device_presentation_support_raw(
&self,
instance: vk::Instance,
device: vk::PhysicalDevice,
queue_family: u32,
) -> bool {
self.glfw.get_physical_device_presentation_support_raw(instance, device, queue_family)
}
/// Wrapper function, please refer to [`Glfw::get_timer_value`]
pub fn get_timer_value(&self) -> u64 {
self.glfw.get_timer_value()
}
/// Wrapper function, please refer to [`Glfw::get_timer_frequency`]
pub fn get_timer_frequency(&self) -> u64 {
self.glfw.get_timer_frequency()
}
/// Wrapper function, please refer to [`Glfw::post_empty_event`]
pub fn post_empty_event(&self) {
self.glfw.post_empty_event()
}
}
unsafe impl Send for ThreadSafeGlfw {}
/// A token from which to call various GLFW functions. It can be obtained by
/// calling the `init` function. This cannot be sent to other tasks, and should
/// only be initialized on the main platform thread. Whilst this might make
/// performing some operations harder, this is to ensure thread safety is enforced
/// statically.
#[non_exhaustive]
#[derive(Debug)]
pub struct Glfw {
phantom: std::marker::PhantomData<*const ()>,
}
/// An error that might be returned when `glfw::init` is called.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub enum InitError {
/// Deprecated. Does not occur.
AlreadyInitialized,
/// An internal error occurred when trying to initialize the library.
Internal,
}
impl fmt::Display for InitError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let description = match *self {
InitError::AlreadyInitialized => "Already Initialized",
InitError::Internal => "Internal Initialization Error",
};
f.write_str(description)
}
}
impl error::Error for InitError {}
/// Initialization hints that can be set using the `init_hint` function.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub enum InitHint {
/// Specifies whether to also expose joystick hats as buttons, for compatibility with earlier
/// versions of GLFW that did not have `glfwGetJoystickHats`.
JoystickHatButtons(bool),
/// Specifies whether to set the current directory to the application to the `Contents/Resources`
/// subdirectory of the application's bundle, if present.
///
/// This is ignored on platforms besides macOS.
CocoaChdirResources(bool),
/// Specifies whether to create a basic menu bar, either from a nib or manually, when the first
/// window is created, which is when AppKit is initialized.
///
/// This is ignored on platforms besides macOS.
CocoaMenubar(bool),
}
/// Sets hints for the next initialization of GLFW.
///
/// The values you set hints to are never reset by GLFW, but they only take effect during
/// initialization. Once GLFW has been initialized, any values you set will be ignored until the
/// library is terminated and initialized again.
///
/// Wrapper for `glfwInitHint`.
pub fn init_hint(hint: InitHint) {
match hint {
InitHint::JoystickHatButtons(joystick_hat_buttons) => unsafe {
ffi::glfwInitHint(ffi::JOYSTICK_HAT_BUTTONS, joystick_hat_buttons as c_int)
},
InitHint::CocoaChdirResources(chdir) => unsafe {
ffi::glfwInitHint(ffi::COCOA_CHDIR_RESOURCES, chdir as c_int)
},
InitHint::CocoaMenubar(menubar) => unsafe {
ffi::glfwInitHint(ffi::COCOA_MENUBAR, menubar as c_int)
},
}
}
/// Initializes the GLFW library. This must be called on the main platform
/// thread.
///
/// Wrapper for `glfwInit`.
///
/// # Example
///
/// ~~~no_run
/// extern crate glfw;
///
/// fn main() {
/// let glfw = glfw::init_no_callbacks().unwrap();
/// }
/// ~~~
///
/// # Error callback
///
/// An error callback can be set if desired. This allows for the handling of any
/// errors that occur during initialization. This can subsequently be changed
/// using the `glfw::init` function.
///
/// ~~~no_run