i_slint_core/platform.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
4/*!
5The backend is the abstraction for crates that need to do the actual drawing and event loop
6*/
7
8#![warn(missing_docs)]
9
10pub use crate::api::PlatformError;
11use crate::api::{LogicalPosition, LogicalSize};
12pub use crate::renderer::Renderer;
13#[cfg(feature = "software-renderer")]
14pub use crate::software_renderer;
15#[cfg(all(not(feature = "std"), feature = "unsafe-single-threaded"))]
16use crate::unsafe_single_threaded::OnceCell;
17pub use crate::window::{LayoutConstraints, WindowAdapter, WindowProperties};
18use crate::SharedString;
19use alloc::boxed::Box;
20use alloc::rc::Rc;
21use alloc::string::String;
22#[cfg(all(feature = "std", not(target_os = "android")))]
23use once_cell::sync::OnceCell;
24#[cfg(all(feature = "std", not(target_arch = "wasm32")))]
25use std::time;
26#[cfg(target_arch = "wasm32")]
27use web_time as time;
28
29/// This trait defines the interface between Slint and platform APIs typically provided by operating and windowing systems.
30pub trait Platform {
31 /// Instantiate a window for a component.
32 fn create_window_adapter(&self) -> Result<Rc<dyn WindowAdapter>, PlatformError>;
33
34 /// Spins an event loop and renders the visible windows.
35 fn run_event_loop(&self) -> Result<(), PlatformError> {
36 Err(PlatformError::NoEventLoopProvider)
37 }
38
39 /// Spins an event loop for a specified period of time.
40 ///
41 /// This function is similar to `run_event_loop()` with two differences:
42 /// * The function is expected to return after the provided timeout, but
43 /// allow for subsequent invocations to resume the previous loop. The
44 /// function can return earlier if the loop was terminated otherwise,
45 /// for example by `quit_event_loop()` or a last-window-closed mechanism.
46 /// * If the timeout is zero, the implementation should merely peek and
47 /// process any pending events, but then return immediately.
48 ///
49 /// When the function returns `ControlFlow::Continue`, it is assumed that
50 /// the loop remains intact and that in the future the caller should call
51 /// `process_events()` again, to permit the user to continue to interact with
52 /// windows.
53 /// When the function returns `ControlFlow::Break`, it is assumed that the
54 /// event loop was terminated. Any subsequent calls to `process_events()`
55 /// will start the event loop afresh.
56 #[doc(hidden)]
57 fn process_events(
58 &self,
59 _timeout: core::time::Duration,
60 _: crate::InternalToken,
61 ) -> Result<core::ops::ControlFlow<()>, PlatformError> {
62 Err(PlatformError::NoEventLoopProvider)
63 }
64
65 #[doc(hidden)]
66 #[deprecated(
67 note = "i-slint-core takes care of closing behavior. Application should call run_event_loop_until_quit"
68 )]
69 /// This is being phased out, see #1499.
70 fn set_event_loop_quit_on_last_window_closed(&self, quit_on_last_window_closed: bool) {
71 assert!(!quit_on_last_window_closed);
72 crate::context::GLOBAL_CONTEXT
73 .with(|ctx| (*ctx.get().unwrap().0.window_count.borrow_mut()) += 1);
74 }
75
76 /// Return an [`EventLoopProxy`] that can be used to send event to the event loop
77 ///
78 /// If this function returns `None` (the default implementation), then it will
79 /// not be possible to send event to the event loop and the function
80 /// [`slint::invoke_from_event_loop()`](crate::api::invoke_from_event_loop) and
81 /// [`slint::quit_event_loop()`](crate::api::quit_event_loop) will panic
82 fn new_event_loop_proxy(&self) -> Option<Box<dyn EventLoopProxy>> {
83 None
84 }
85
86 /// Returns the current time as a monotonic duration since the start of the program
87 ///
88 /// This is used by the animations and timer to compute the elapsed time.
89 ///
90 /// When the `std` feature is enabled, this function is implemented in terms of
91 /// [`std::time::Instant::now()`], but on `#![no_std]` platform, this function must
92 /// be implemented.
93 fn duration_since_start(&self) -> core::time::Duration {
94 #[cfg(feature = "std")]
95 {
96 let the_beginning = *INITIAL_INSTANT.get_or_init(time::Instant::now);
97 time::Instant::now() - the_beginning
98 }
99 #[cfg(not(feature = "std"))]
100 unimplemented!("The platform abstraction must implement `duration_since_start`")
101 }
102
103 /// Returns the current interval to internal measure the duration to send a double click event.
104 ///
105 /// A double click event is a series of two pointer clicks.
106 fn click_interval(&self) -> core::time::Duration {
107 // 500ms is the default delay according to https://en.wikipedia.org/wiki/Double-click#Speed_and_timing
108 core::time::Duration::from_millis(500)
109 }
110
111 /// Sends the given text into the system clipboard.
112 ///
113 /// If the platform doesn't support the specified clipboard, this function should do nothing
114 fn set_clipboard_text(&self, _text: &str, _clipboard: Clipboard) {}
115
116 /// Returns a copy of text stored in the system clipboard, if any.
117 ///
118 /// If the platform doesn't support the specified clipboard, the function should return None
119 fn clipboard_text(&self, _clipboard: Clipboard) -> Option<String> {
120 None
121 }
122
123 /// This function is called when debug() is used in .slint files. The implementation
124 /// should direct the output to some developer visible terminal. The default implementation
125 /// uses stderr if available, or `console.log` when targeting wasm.
126 fn debug_log(&self, _arguments: core::fmt::Arguments) {
127 crate::tests::default_debug_log(_arguments);
128 }
129
130 #[cfg(target_os = "android")]
131 #[doc(hidden)]
132 /// The long press interval before showing a context menu
133 fn long_press_interval(&self, _: crate::InternalToken) -> core::time::Duration {
134 core::time::Duration::from_millis(500)
135 }
136}
137
138/// The clip board, used in [`Platform::clipboard_text`] and [Platform::set_clipboard_text`]
139#[repr(u8)]
140#[non_exhaustive]
141#[derive(PartialEq, Clone, Default)]
142pub enum Clipboard {
143 /// This is the default clipboard used for text action for Ctrl+V, Ctrl+C.
144 /// Corresponds to the secondary clipboard on X11.
145 #[default]
146 DefaultClipboard = 0,
147
148 /// This is the clipboard that is used when text is selected
149 /// Corresponds to the primary clipboard on X11.
150 /// The Platform implementation should do nothing if copy on select is not supported on that platform.
151 SelectionClipboard = 1,
152}
153
154/// Trait that is returned by the [`Platform::new_event_loop_proxy`]
155///
156/// This are the implementation details for the function that may need to
157/// communicate with the eventloop from different thread
158pub trait EventLoopProxy: Send + Sync {
159 /// Exits the event loop.
160 ///
161 /// This is what is called by [`slint::quit_event_loop()`](crate::api::quit_event_loop)
162 fn quit_event_loop(&self) -> Result<(), crate::api::EventLoopError>;
163
164 /// Invoke the function from the event loop.
165 ///
166 /// This is what is called by [`slint::invoke_from_event_loop()`](crate::api::invoke_from_event_loop)
167 fn invoke_from_event_loop(
168 &self,
169 event: Box<dyn FnOnce() + Send>,
170 ) -> Result<(), crate::api::EventLoopError>;
171}
172
173#[cfg(feature = "std")]
174static INITIAL_INSTANT: once_cell::sync::OnceCell<time::Instant> = once_cell::sync::OnceCell::new();
175
176#[cfg(feature = "std")]
177impl std::convert::From<crate::animations::Instant> for time::Instant {
178 fn from(our_instant: crate::animations::Instant) -> Self {
179 let the_beginning = *INITIAL_INSTANT.get_or_init(time::Instant::now);
180 the_beginning + core::time::Duration::from_millis(our_instant.0)
181 }
182}
183
184#[cfg(not(target_os = "android"))]
185static EVENTLOOP_PROXY: OnceCell<Box<dyn EventLoopProxy + 'static>> = OnceCell::new();
186
187// On android, we allow the platform to be reset and the global eventloop proxy to be replaced.
188#[cfg(target_os = "android")]
189static EVENTLOOP_PROXY: std::sync::Mutex<Option<Box<dyn EventLoopProxy + 'static>>> =
190 std::sync::Mutex::new(None);
191
192pub(crate) fn with_event_loop_proxy<R>(f: impl FnOnce(Option<&dyn EventLoopProxy>) -> R) -> R {
193 #[cfg(not(target_os = "android"))]
194 return f(EVENTLOOP_PROXY.get().map(core::ops::Deref::deref));
195 #[cfg(target_os = "android")]
196 return f(EVENTLOOP_PROXY.lock().unwrap().as_ref().map(core::ops::Deref::deref));
197}
198
199/// This enum describes the different error scenarios that may occur when [`set_platform`]
200/// fails.
201#[derive(Debug, Clone, PartialEq)]
202#[repr(C)]
203#[non_exhaustive]
204pub enum SetPlatformError {
205 /// The platform has already been initialized in an earlier call to [`set_platform`].
206 AlreadySet,
207}
208
209impl core::fmt::Display for SetPlatformError {
210 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
211 match self {
212 SetPlatformError::AlreadySet => {
213 f.write_str("The platform has already been initialized.")
214 }
215 }
216 }
217}
218
219#[cfg(feature = "std")]
220impl std::error::Error for SetPlatformError {}
221
222/// Set the Slint platform abstraction.
223///
224/// If the platform abstraction was already set this will return `Err`.
225pub fn set_platform(platform: Box<dyn Platform + 'static>) -> Result<(), SetPlatformError> {
226 crate::context::GLOBAL_CONTEXT.with(|instance| {
227 if instance.get().is_some() {
228 return Err(SetPlatformError::AlreadySet);
229 }
230 if let Some(proxy) = platform.new_event_loop_proxy() {
231 #[cfg(not(target_os = "android"))]
232 {
233 EVENTLOOP_PROXY.set(proxy).map_err(|_| SetPlatformError::AlreadySet)?;
234 }
235 #[cfg(target_os = "android")]
236 {
237 *EVENTLOOP_PROXY.lock().unwrap() = Some(proxy);
238 }
239 }
240 instance
241 .set(crate::SlintContext::new(platform))
242 .map_err(|_| SetPlatformError::AlreadySet)
243 .unwrap();
244 // Ensure a sane starting point for the animation tick.
245 update_timers_and_animations();
246 Ok(())
247 })
248}
249
250/// Call this function to update and potentially activate any pending timers, as well
251/// as advance the state of any active animations.
252///
253/// This function should be called before rendering or processing input event, at the
254/// beginning of each event loop iteration.
255pub fn update_timers_and_animations() {
256 crate::animations::update_animations();
257 crate::timers::TimerList::maybe_activate_timers(crate::animations::Instant::now());
258 crate::properties::ChangeTracker::run_change_handlers();
259}
260
261/// Returns the duration before the next timer is expected to be activated. This is the
262/// largest amount of time that you can wait before calling [`update_timers_and_animations()`].
263///
264/// `None` is returned if there is no active timer.
265///
266/// Call this in your own event loop implementation to know how long the current thread can
267/// go to sleep. Note that this does not take currently activate animations into account.
268/// Only go to sleep if [`Window::has_active_animations()`](crate::api::Window::has_active_animations())
269/// returns false.
270pub fn duration_until_next_timer_update() -> Option<core::time::Duration> {
271 crate::timers::TimerList::next_timeout().map(|timeout| {
272 let duration_since_start = crate::context::GLOBAL_CONTEXT
273 .with(|p| p.get().map(|p| p.platform().duration_since_start()))
274 .unwrap_or_default();
275 core::time::Duration::from_millis(
276 timeout.0.saturating_sub(duration_since_start.as_millis() as u64),
277 )
278 })
279}
280
281// reexport key enum to the public api
282pub use crate::input::key_codes::Key;
283pub use crate::input::PointerEventButton;
284
285/// A event that describes user input or windowing system events.
286///
287/// Slint backends typically receive events from the windowing system, translate them to this
288/// enum and deliver them to the scene of items via [`slint::Window::try_dispatch_event()`](`crate::api::Window::try_dispatch_event()`).
289///
290/// The pointer variants describe events originating from an input device such as a mouse
291/// or a contact point on a touch-enabled surface.
292///
293/// All position fields are in logical window coordinates.
294#[allow(missing_docs)]
295#[derive(Debug, Clone, PartialEq)]
296#[non_exhaustive]
297#[repr(u32)]
298pub enum WindowEvent {
299 /// A pointer was pressed.
300 PointerPressed {
301 position: LogicalPosition,
302 /// The button that was pressed.
303 button: PointerEventButton,
304 },
305 /// A pointer was released.
306 PointerReleased {
307 position: LogicalPosition,
308 /// The button that was released.
309 button: PointerEventButton,
310 },
311 /// The position of the pointer has changed.
312 PointerMoved { position: LogicalPosition },
313 /// The wheel button of a mouse was rotated to initiate scrolling.
314 PointerScrolled {
315 position: LogicalPosition,
316 /// The amount of logical pixels to scroll in the horizontal direction.
317 delta_x: f32,
318 /// The amount of logical pixels to scroll in the vertical direction.
319 delta_y: f32,
320 },
321 /// The pointer exited the window.
322 PointerExited,
323 /// A key was pressed.
324 KeyPressed {
325 /// The unicode representation of the key pressed.
326 ///
327 /// # Example
328 /// A specific key can be mapped to a unicode by using the [`Key`] enum
329 /// ```rust
330 /// let _ = slint::platform::WindowEvent::KeyPressed { text: slint::platform::Key::Shift.into() };
331 /// ```
332 text: SharedString,
333 },
334 /// A key press was auto-repeated.
335 KeyPressRepeated {
336 /// The unicode representation of the key pressed.
337 ///
338 /// # Example
339 /// A specific key can be mapped to a unicode by using the [`Key`] enum
340 /// ```rust
341 /// let _ = slint::platform::WindowEvent::KeyPressRepeated { text: slint::platform::Key::Shift.into() };
342 /// ```
343 text: SharedString,
344 },
345 /// A key was released.
346 KeyReleased {
347 /// The unicode representation of the key released.
348 ///
349 /// # Example
350 /// A specific key can be mapped to a unicode by using the [`Key`] enum
351 /// ```rust
352 /// let _ = slint::platform::WindowEvent::KeyReleased { text: slint::platform::Key::Shift.into() };
353 /// ```
354 text: SharedString,
355 },
356 /// The window's scale factor has changed. This can happen for example when the display's resolution
357 /// changes, the user selects a new scale factor in the system settings, or the window is moved to a
358 /// different screen.
359 /// Platform implementations should dispatch this event also right after the initial window creation,
360 /// to set the initial scale factor the windowing system provided for the window.
361 ScaleFactorChanged {
362 /// The window system provided scale factor to map logical pixels to physical pixels.
363 scale_factor: f32,
364 },
365 /// The window was resized.
366 ///
367 /// The backend must send this event to ensure that the `width` and `height` property of the root Window
368 /// element are properly set.
369 Resized {
370 /// The new logical size of the window
371 size: LogicalSize,
372 },
373 /// The user requested to close the window.
374 ///
375 /// The backend should send this event when the user tries to close the window,for example by pressing the close button.
376 ///
377 /// This will have the effect of invoking the callback set in [`Window::on_close_requested()`](`crate::api::Window::on_close_requested()`)
378 /// and then hiding the window depending on the return value of the callback.
379 CloseRequested,
380
381 /// The Window was activated or de-activated.
382 ///
383 /// The backend should dispatch this event with true when the window gains focus
384 /// and false when the window loses focus.
385 WindowActiveChanged(bool),
386}
387
388impl WindowEvent {
389 /// The position of the cursor for this event, if any
390 pub fn position(&self) -> Option<LogicalPosition> {
391 match self {
392 WindowEvent::PointerPressed { position, .. } => Some(*position),
393 WindowEvent::PointerReleased { position, .. } => Some(*position),
394 WindowEvent::PointerMoved { position } => Some(*position),
395 WindowEvent::PointerScrolled { position, .. } => Some(*position),
396 _ => None,
397 }
398 }
399}
400
401/**
402 * Test the animation tick is updated when a platform is set
403```rust
404use i_slint_core::platform::*;
405struct DummyBackend;
406impl Platform for DummyBackend {
407 fn create_window_adapter(
408 &self,
409 ) -> Result<std::rc::Rc<dyn WindowAdapter>, PlatformError> {
410 Err(PlatformError::Other("not implemented".into()))
411 }
412 fn duration_since_start(&self) -> core::time::Duration {
413 core::time::Duration::from_millis(100)
414 }
415}
416
417let start_time = i_slint_core::tests::slint_get_mocked_time();
418i_slint_core::platform::set_platform(Box::new(DummyBackend{}));
419let time_after_platform_init = i_slint_core::tests::slint_get_mocked_time();
420assert_ne!(time_after_platform_init, start_time);
421assert_eq!(time_after_platform_init, 100);
422```
423 */
424#[cfg(doctest)]
425const _ANIM_TICK_UPDATED_ON_PLATFORM_SET: () = ();