Skip to main content

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