gtk/rt.rs
1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use crate::ffi;
4use glib::translate::*;
5use std::cell::Cell;
6use std::sync::atomic::{AtomicBool, Ordering};
7
8#[cfg(target_os = "macos")]
9extern "C" {
10 fn pthread_main_np() -> i32;
11}
12
13thread_local! {
14 static IS_MAIN_THREAD: Cell<bool> = const { Cell::new(false) }
15}
16
17static INITIALIZED: AtomicBool = AtomicBool::new(false);
18
19/// Asserts that this is the main thread and `gtk::init` has been called.
20macro_rules! assert_initialized_main_thread {
21 () => {
22 if !crate::rt::is_initialized_main_thread() {
23 if crate::rt::is_initialized() {
24 panic!("GTK may only be used from the main thread.");
25 } else {
26 panic!("GTK has not been initialized. Call `gtk::init` first.");
27 }
28 }
29 };
30}
31
32/// No-op.
33macro_rules! skip_assert_initialized {
34 () => {};
35}
36
37/// Asserts that `gtk::init` has not been called.
38#[allow(unused_macros)]
39macro_rules! assert_not_initialized {
40 () => {
41 if crate::rt::is_initialized() {
42 panic!("This function has to be called before `gtk::init`.");
43 }
44 };
45}
46
47/// Returns `true` if GTK has been initialized.
48#[inline]
49pub fn is_initialized() -> bool {
50 skip_assert_initialized!();
51 if cfg!(not(feature = "unsafe-assume-initialized")) {
52 INITIALIZED.load(Ordering::Acquire)
53 } else {
54 true
55 }
56}
57
58/// Returns `true` if GTK has been initialized and this is the main thread.
59#[inline]
60pub fn is_initialized_main_thread() -> bool {
61 skip_assert_initialized!();
62 if cfg!(not(feature = "unsafe-assume-initialized")) {
63 IS_MAIN_THREAD.with(|c| c.get())
64 } else {
65 true
66 }
67}
68
69/// Informs this crate that GTK has been initialized and the current thread is the main one.
70///
71/// # Panics
72///
73/// This function will panic if you attempt to initialise GTK from more than
74/// one thread.
75///
76/// # Safety
77///
78/// You must only call this if:
79///
80/// 1. You have initialised the underlying GTK library yourself.
81/// 2. You did 1 on the thread with which you are calling this function
82/// 3. You ensure that this thread is the main thread for the process.
83pub unsafe fn set_initialized() {
84 unsafe {
85 skip_assert_initialized!();
86 if is_initialized_main_thread() {
87 return;
88 } else if is_initialized() {
89 panic!("Attempted to initialize GTK from two different threads.");
90 }
91
92 // OS X has its own notion of the main thread and init must be called on that thread.
93 #[cfg(target_os = "macos")]
94 {
95 assert_eq!(
96 pthread_main_np(),
97 1,
98 "Attempted to initialize GTK on OSX from non-main thread"
99 );
100 }
101
102 gdk::set_initialized();
103 INITIALIZED.store(true, Ordering::Release);
104 IS_MAIN_THREAD.with(|c| c.set(true));
105 }
106}
107
108/// Tries to initialize GTK+.
109///
110/// Call either this function or [`Application::new`][new] before using any
111/// other GTK+ functions.
112///
113/// [new]: struct.Application.html#method.new
114///
115/// Note that this function calls `gtk_init_check()` rather than `gtk_init()`,
116/// so will not cause the program to terminate if GTK could not be initialized.
117/// Instead, an Ok is returned if the windowing system was successfully
118/// initialized otherwise an Err is returned.
119#[doc(alias = "gtk_init")]
120pub fn init() -> Result<(), glib::BoolError> {
121 skip_assert_initialized!();
122 if is_initialized_main_thread() {
123 return Ok(());
124 } else if is_initialized() {
125 panic!("Attempted to initialize GTK from two different threads.");
126 }
127 unsafe {
128 // We just want to keep the program's name since more arguments could lead to unwanted
129 // behaviors...
130 let argv = ::std::env::args().take(1).collect::<Vec<_>>();
131
132 if from_glib(ffi::gtk_init_check(&mut 1, &mut argv.to_glib_none().0)) {
133 // See https://github.com/gtk-rs/gtk-rs-core/issues/186 for reasoning behind
134 // acquiring and leaking the main context here.
135 let result: bool = from_glib(glib::ffi::g_main_context_acquire(
136 glib::ffi::g_main_context_default(),
137 ));
138 if !result {
139 return Err(glib::bool_error!("Failed to acquire default main context"));
140 }
141 set_initialized();
142 Ok(())
143 } else {
144 Err(glib::bool_error!("Failed to initialize GTK"))
145 }
146 }
147}
148
149#[doc(alias = "gtk_main_quit")]
150pub fn main_quit() {
151 assert_initialized_main_thread!();
152 unsafe {
153 if ffi::gtk_main_level() > 0 {
154 ffi::gtk_main_quit();
155 } else if cfg!(debug_assertions) {
156 panic!("Attempted to quit a GTK main loop when none is running.");
157 }
158 }
159}
160
161#[cfg(test)]
162mod tests {
163 use crate::TEST_THREAD_WORKER;
164
165 #[test]
166 fn init_should_acquire_default_main_context() {
167 TEST_THREAD_WORKER
168 .push(move || {
169 let context = glib::MainContext::ref_thread_default();
170 assert!(context.is_owner());
171 })
172 .expect("Failed to schedule a test call");
173 while TEST_THREAD_WORKER.unprocessed() > 0 {}
174 }
175}