i_slint_core/
context.rs

1// Copyright © SixtyFPS GmbH <info@slint.dev>
2// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
3
4use crate::api::PlatformError;
5use crate::platform::{EventLoopProxy, Platform};
6use crate::Property;
7use alloc::boxed::Box;
8use alloc::rc::Rc;
9
10crate::thread_local! {
11    pub(crate) static GLOBAL_CONTEXT : once_cell::unsync::OnceCell<SlintContext>
12        = const { once_cell::unsync::OnceCell::new() }
13}
14
15pub(crate) struct SlintContextInner {
16    platform: Box<dyn Platform>,
17    pub(crate) window_count: core::cell::RefCell<isize>,
18    /// This property is read by all translations, and marked dirty when the language changes,
19    /// so that every translated string gets re-translated. The property's value is the current selected
20    /// language when bundling translations.
21    pub(crate) translations_dirty: core::pin::Pin<Box<Property<usize>>>,
22    pub(crate) translations_bundle_languages:
23        core::cell::RefCell<Option<alloc::vec::Vec<&'static str>>>,
24    pub(crate) window_shown_hook:
25        core::cell::RefCell<Option<Box<dyn FnMut(&Rc<dyn crate::platform::WindowAdapter>)>>>,
26    #[cfg(all(unix, not(target_os = "macos")))]
27    xdg_app_id: core::cell::RefCell<Option<crate::SharedString>>,
28    #[cfg(feature = "tr")]
29    external_translator: core::cell::RefCell<Option<Box<dyn tr::Translator>>>,
30}
31
32/// This context is meant to hold the state and the backend.
33/// Currently it is not possible to have several platform at the same time in one process, but in the future it might be.
34/// See issue #4294
35#[derive(Clone)]
36pub struct SlintContext(pub(crate) Rc<SlintContextInner>);
37
38impl SlintContext {
39    /// Create a new context with a given platform
40    pub fn new(platform: Box<dyn Platform + 'static>) -> Self {
41        Self(Rc::new(SlintContextInner {
42            platform,
43            window_count: 0.into(),
44            translations_dirty: Box::pin(Property::new_named(0, "SlintContext::translations")),
45            translations_bundle_languages: Default::default(),
46            window_shown_hook: Default::default(),
47            #[cfg(all(unix, not(target_os = "macos")))]
48            xdg_app_id: Default::default(),
49            #[cfg(feature = "tr")]
50            external_translator: Default::default(),
51        }))
52    }
53
54    /// Return a reference to the platform abstraction
55    pub fn platform(&self) -> &dyn Platform {
56        &*self.0.platform
57    }
58
59    /// Return an event proxy
60    // FIXME: Make EvenLoopProxy cloneable, and maybe wrap in a struct
61    pub fn event_loop_proxy(&self) -> Option<Box<dyn EventLoopProxy>> {
62        self.0.platform.new_event_loop_proxy()
63    }
64
65    #[cfg(target_has_atomic = "ptr")]
66    /// Context specific version of `slint::spawn_local`
67    pub fn spawn_local<F: core::future::Future + 'static>(
68        &self,
69        fut: F,
70    ) -> Result<crate::future::JoinHandle<F::Output>, crate::api::EventLoopError> {
71        crate::future::spawn_local_with_ctx(self, fut)
72    }
73
74    pub fn run_event_loop(&self) -> Result<(), PlatformError> {
75        self.0.platform.run_event_loop()
76    }
77
78    pub fn set_xdg_app_id(&self, _app_id: crate::SharedString) {
79        #[cfg(all(unix, not(target_os = "macos")))]
80        {
81            self.0.xdg_app_id.replace(Some(_app_id));
82        }
83    }
84
85    #[cfg(all(unix, not(target_os = "macos")))]
86    pub fn xdg_app_id(&self) -> Option<crate::SharedString> {
87        self.0.xdg_app_id.borrow().clone()
88    }
89
90    #[cfg(not(all(unix, not(target_os = "macos"))))]
91    pub fn xdg_app_id(&self) -> Option<crate::SharedString> {
92        None
93    }
94
95    #[cfg(feature = "tr")]
96    pub fn set_external_translator(&self, translator: Option<Box<dyn tr::Translator>>) {
97        *self.0.external_translator.borrow_mut() = translator;
98    }
99
100    #[cfg(feature = "tr")]
101    pub fn external_translator(&self) -> Option<core::cell::Ref<'_, Box<dyn tr::Translator>>> {
102        core::cell::Ref::filter_map(self.0.external_translator.borrow(), |maybe_translator| {
103            maybe_translator.as_ref()
104        })
105        .ok()
106    }
107}
108
109/// Internal function to access the context.
110/// The factory function is called if the platform abstraction is not yet
111/// initialized, and should be given by the platform_selector
112pub fn with_global_context<R>(
113    factory: impl FnOnce() -> Result<Box<dyn Platform + 'static>, PlatformError>,
114    f: impl FnOnce(&SlintContext) -> R,
115) -> Result<R, PlatformError> {
116    GLOBAL_CONTEXT.with(|p| match p.get() {
117        Some(ctx) => Ok(f(ctx)),
118        None => {
119            crate::platform::set_platform(factory()?).map_err(PlatformError::SetPlatformError)?;
120            Ok(f(p.get().unwrap()))
121        }
122    })
123}
124
125/// Internal function to set a hook that's invoked whenever a slint::Window is shown. This
126/// is used by the system testing module. Returns a previously set hook, if any.
127pub fn set_window_shown_hook(
128    hook: Option<Box<dyn FnMut(&Rc<dyn crate::platform::WindowAdapter>)>>,
129) -> Result<Option<Box<dyn FnMut(&Rc<dyn crate::platform::WindowAdapter>)>>, PlatformError> {
130    GLOBAL_CONTEXT.with(|p| match p.get() {
131        Some(ctx) => Ok(ctx.0.window_shown_hook.replace(hook)),
132        None => Err(PlatformError::NoPlatform),
133    })
134}