Skip to main content

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::Property;
5use crate::api::PlatformError;
6use crate::input::InternalKeyboardModifierState;
7use crate::platform::{EventLoopProxy, Platform};
8use alloc::boxed::Box;
9use alloc::rc::Rc;
10use core::cell::Cell;
11
12crate::thread_local! {
13    pub(crate) static GLOBAL_CONTEXT : once_cell::unsync::OnceCell<SlintContext>
14        = const { once_cell::unsync::OnceCell::new() }
15}
16
17pub(crate) struct SlintContextInner {
18    platform: Box<dyn Platform>,
19    pub(crate) window_count: core::cell::RefCell<isize>,
20    /// This property is read by all translations, and marked dirty when the language changes,
21    /// so that every translated string gets re-translated. The property's value is the current selected
22    /// language when bundling translations.
23    pub(crate) translations_dirty: core::pin::Pin<Box<Property<usize>>>,
24    pub(crate) translations_bundle_languages:
25        core::cell::RefCell<Option<alloc::vec::Vec<&'static str>>>,
26    pub(crate) window_shown_hook:
27        core::cell::RefCell<Option<Box<dyn FnMut(&Rc<dyn crate::platform::WindowAdapter>)>>>,
28    #[cfg(all(unix, not(target_os = "macos")))]
29    xdg_app_id: core::cell::RefCell<Option<crate::SharedString>>,
30    #[cfg(feature = "tr")]
31    external_translator: core::cell::RefCell<Option<Box<dyn tr::Translator>>>,
32    #[cfg(feature = "shared-parley")]
33    pub(crate) font_context: core::cell::RefCell<parley::FontContext>,
34    #[cfg(feature = "shared-swash")]
35    pub(crate) swash_scale_context: core::cell::RefCell<swash::scale::ScaleContext>,
36    pub(crate) modifiers: Cell<InternalKeyboardModifierState>,
37}
38
39/// This context is meant to hold the state and the backend.
40/// Currently it is not possible to have several platform at the same time in one process, but in the future it might be.
41/// See issue #4294
42#[derive(Clone)]
43pub struct SlintContext(pub(crate) Rc<SlintContextInner>);
44
45impl SlintContext {
46    /// Create a new context with a given platform
47    pub fn new(platform: Box<dyn Platform + 'static>) -> Self {
48        #[cfg(feature = "shared-parley")]
49        let collection = i_slint_common::sharedfontique::create_collection(true);
50
51        Self(Rc::new(SlintContextInner {
52            platform,
53            window_count: 0.into(),
54            translations_dirty: Box::pin(Property::new_named(0, "SlintContext::translations")),
55            translations_bundle_languages: Default::default(),
56            window_shown_hook: Default::default(),
57            #[cfg(all(unix, not(target_os = "macos")))]
58            xdg_app_id: Default::default(),
59            #[cfg(feature = "tr")]
60            external_translator: Default::default(),
61            #[cfg(feature = "shared-parley")]
62            font_context: {
63                let font_context = parley::FontContext {
64                    collection: collection.inner,
65                    source_cache: collection.source_cache,
66                };
67                core::cell::RefCell::new(font_context)
68            },
69            #[cfg(feature = "shared-swash")]
70            swash_scale_context: core::cell::RefCell::new(swash::scale::ScaleContext::new()),
71            modifiers: Cell::new(Default::default()),
72        }))
73    }
74
75    /// Return a reference to the platform abstraction
76    pub fn platform(&self) -> &dyn Platform {
77        &*self.0.platform
78    }
79
80    /// Return a reference to the font context
81    #[cfg(feature = "shared-parley")]
82    pub fn font_context(&self) -> &core::cell::RefCell<parley::FontContext> {
83        &self.0.font_context
84    }
85
86    /// Return a reference to the swash scale context
87    #[cfg(feature = "shared-swash")]
88    pub fn swash_scale_context(&self) -> &core::cell::RefCell<swash::scale::ScaleContext> {
89        &self.0.swash_scale_context
90    }
91
92    /// Return an event proxy
93    // FIXME: Make EvenLoopProxy cloneable, and maybe wrap in a struct
94    pub fn event_loop_proxy(&self) -> Option<Box<dyn EventLoopProxy>> {
95        self.0.platform.new_event_loop_proxy()
96    }
97
98    #[cfg(target_has_atomic = "ptr")]
99    /// Context specific version of `slint::spawn_local`
100    pub fn spawn_local<F: core::future::Future + 'static>(
101        &self,
102        fut: F,
103    ) -> Result<crate::future::JoinHandle<F::Output>, crate::api::EventLoopError> {
104        crate::future::spawn_local_with_ctx(self, fut)
105    }
106
107    pub fn run_event_loop(&self) -> Result<(), PlatformError> {
108        self.0.platform.run_event_loop()
109    }
110
111    pub fn set_xdg_app_id(&self, _app_id: crate::SharedString) {
112        #[cfg(all(unix, not(target_os = "macos")))]
113        {
114            self.0.xdg_app_id.replace(Some(_app_id));
115        }
116    }
117
118    #[cfg(all(unix, not(target_os = "macos")))]
119    pub fn xdg_app_id(&self) -> Option<crate::SharedString> {
120        self.0.xdg_app_id.borrow().clone()
121    }
122
123    #[cfg(not(all(unix, not(target_os = "macos"))))]
124    pub fn xdg_app_id(&self) -> Option<crate::SharedString> {
125        None
126    }
127
128    #[cfg(feature = "tr")]
129    pub fn set_external_translator(&self, translator: Option<Box<dyn tr::Translator>>) {
130        *self.0.external_translator.borrow_mut() = translator;
131        self.0.translations_dirty.mark_dirty();
132    }
133
134    #[cfg(feature = "tr")]
135    pub fn external_translator(&self) -> Option<core::cell::Ref<'_, Box<dyn tr::Translator>>> {
136        core::cell::Ref::filter_map(self.0.external_translator.borrow(), |maybe_translator| {
137            maybe_translator.as_ref()
138        })
139        .ok()
140    }
141}
142
143/// Internal function to access the context.
144/// The factory function is called if the platform abstraction is not yet
145/// initialized, and should be given by the platform_selector
146pub fn with_global_context<R>(
147    factory: impl FnOnce() -> Result<Box<dyn Platform + 'static>, PlatformError>,
148    f: impl FnOnce(&SlintContext) -> R,
149) -> Result<R, PlatformError> {
150    GLOBAL_CONTEXT.with(|p| match p.get() {
151        Some(ctx) => Ok(f(ctx)),
152        None => {
153            if crate::platform::with_event_loop_proxy(|proxy| proxy.is_some()) {
154                return Err(PlatformError::SetPlatformError(
155                    crate::platform::SetPlatformError::AlreadySet,
156                ));
157            }
158            crate::platform::set_platform(factory()?).map_err(PlatformError::SetPlatformError)?;
159            Ok(f(p.get().unwrap()))
160        }
161    })
162}
163
164/// Internal function to set a hook that's invoked whenever a slint::Window is shown. This
165/// is used by the system testing module. Returns a previously set hook, if any.
166pub fn set_window_shown_hook(
167    hook: Option<Box<dyn FnMut(&Rc<dyn crate::platform::WindowAdapter>)>>,
168) -> Result<Option<Box<dyn FnMut(&Rc<dyn crate::platform::WindowAdapter>)>>, PlatformError> {
169    GLOBAL_CONTEXT.with(|p| match p.get() {
170        Some(ctx) => Ok(ctx.0.window_shown_hook.replace(hook)),
171        None => Err(PlatformError::NoPlatform),
172    })
173}