gdk/rt.rs
1// Take a look at the license at the top of the repository in the LICENSE file.
2
3//! General — Library initialization and miscellaneous functions
4
5use std::cell::Cell;
6use std::ptr;
7use std::sync::atomic::{AtomicBool, Ordering};
8
9thread_local! {
10 static IS_MAIN_THREAD: Cell<bool> = Cell::new(false)
11}
12
13static INITIALIZED: AtomicBool = AtomicBool::new(false);
14
15/// Asserts that this is the main thread and either `gdk::init` or `gtk::init` has been called.
16macro_rules! assert_initialized_main_thread {
17 () => {
18 if !crate::rt::is_initialized_main_thread() {
19 if crate::rt::is_initialized() {
20 panic!("GDK may only be used from the main thread.");
21 } else {
22 panic!("GDK has not been initialized. Call `gdk::init` or `gtk::init` first.");
23 }
24 }
25 };
26}
27
28/// No-op.
29macro_rules! skip_assert_initialized {
30 () => {};
31}
32
33/// Asserts that neither `gdk::init` nor `gtk::init` has been called.
34macro_rules! assert_not_initialized {
35 () => {
36 if crate::rt::is_initialized() {
37 panic!("This function has to be called before `gdk::init` or `gtk::init`.");
38 }
39 };
40}
41
42/// Returns `true` if GDK has been initialized.
43#[inline]
44pub fn is_initialized() -> bool {
45 skip_assert_initialized!();
46 if cfg!(not(feature = "unsafe-assume-initialized")) {
47 INITIALIZED.load(Ordering::Acquire)
48 } else {
49 true
50 }
51}
52
53/// Returns `true` if GDK has been initialized and this is the main thread.
54#[inline]
55pub fn is_initialized_main_thread() -> bool {
56 skip_assert_initialized!();
57 if cfg!(not(feature = "unsafe-assume-initialized")) {
58 IS_MAIN_THREAD.with(|c| c.get())
59 } else {
60 true
61 }
62}
63
64/// Informs this crate that GDK has been initialized and the current thread is the main one.
65pub unsafe fn set_initialized() {
66 skip_assert_initialized!();
67 if is_initialized_main_thread() {
68 return;
69 } else if is_initialized() {
70 panic!("Attempted to initialize GDK from two different threads.");
71 }
72 INITIALIZED.store(true, Ordering::Release);
73 IS_MAIN_THREAD.with(|c| c.set(true));
74}
75
76#[doc(alias = "gdk_init")]
77pub fn init() {
78 assert_not_initialized!();
79 unsafe {
80 ffi::gdk_init(ptr::null_mut(), ptr::null_mut());
81 set_initialized();
82 }
83}