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
use glib::translate::*;
use std::cell::Cell;
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(target_os = "macos")]
extern "C" {
fn pthread_main_np() -> i32;
}
thread_local! {
static IS_MAIN_THREAD: Cell<bool> = Cell::new(false)
}
static INITIALIZED: AtomicBool = AtomicBool::new(false);
macro_rules! assert_initialized_main_thread {
() => {
if !crate::rt::is_initialized_main_thread() {
if crate::rt::is_initialized() {
panic!("GTK may only be used from the main thread.");
} else {
panic!("GTK has not been initialized. Call `gtk::init` first.");
}
}
};
}
macro_rules! skip_assert_initialized {
() => {};
}
#[allow(unused_macros)]
macro_rules! assert_not_initialized {
() => {
if crate::rt::is_initialized() {
panic!("This function has to be called before `gtk::init`.");
}
};
}
#[inline]
pub fn is_initialized() -> bool {
skip_assert_initialized!();
INITIALIZED.load(Ordering::Acquire)
}
#[inline]
pub fn is_initialized_main_thread() -> bool {
skip_assert_initialized!();
IS_MAIN_THREAD.with(|c| c.get())
}
pub unsafe fn set_initialized() {
skip_assert_initialized!();
if is_initialized_main_thread() {
return;
} else if is_initialized() {
panic!("Attempted to initialize GTK from two different threads.");
}
#[cfg(target_os = "macos")]
{
if pthread_main_np() == 0 {
panic!("Attempted to initialize GTK on OSX from non-main thread");
}
}
gdk::set_initialized();
INITIALIZED.store(true, Ordering::Release);
IS_MAIN_THREAD.with(|c| c.set(true));
}
#[doc(alias = "gtk_init")]
pub fn init() -> Result<(), glib::BoolError> {
skip_assert_initialized!();
if is_initialized_main_thread() {
return Ok(());
} else if is_initialized() {
panic!("Attempted to initialize GTK from two different threads.");
}
unsafe {
let argv = ::std::env::args().take(1).collect::<Vec<_>>();
if from_glib(ffi::gtk_init_check(&mut 1, &mut argv.to_glib_none().0)) {
set_initialized();
Ok(())
} else {
Err(glib::bool_error!("Failed to initialize GTK"))
}
}
}
#[doc(alias = "gtk_main_quit")]
pub fn main_quit() {
assert_initialized_main_thread!();
unsafe {
if ffi::gtk_main_level() > 0 {
ffi::gtk_main_quit();
} else if cfg!(debug_assertions) {
panic!("Attempted to quit a GTK main loop when none is running.");
}
}
}