i_slint_core/api.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/*!
5This module contains types that are public and re-exported in the slint-rs as well as the slint-interpreter crate as public API.
6*/
7
8#![warn(missing_docs)]
9
10#[cfg(target_has_atomic = "ptr")]
11pub use crate::future::*;
12use crate::graphics::{Rgba8Pixel, SharedPixelBuffer};
13use crate::input::{KeyEventType, MouseEvent};
14use crate::item_tree::ItemTreeVTable;
15use crate::window::{WindowAdapter, WindowInner};
16use alloc::boxed::Box;
17use alloc::string::String;
18
19/// A position represented in the coordinate space of logical pixels. That is the space before applying
20/// a display device specific scale factor.
21#[derive(Debug, Default, Copy, Clone, PartialEq)]
22#[repr(C)]
23#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
24pub struct LogicalPosition {
25 /// The x coordinate.
26 pub x: f32,
27 /// The y coordinate.
28 pub y: f32,
29}
30
31impl LogicalPosition {
32 /// Construct a new logical position from the given x and y coordinates, that are assumed to be
33 /// in the logical coordinate space.
34 pub const fn new(x: f32, y: f32) -> Self {
35 Self { x, y }
36 }
37
38 /// Convert a given physical position to a logical position by dividing the coordinates with the
39 /// specified scale factor.
40 pub fn from_physical(physical_pos: PhysicalPosition, scale_factor: f32) -> Self {
41 Self::new(physical_pos.x as f32 / scale_factor, physical_pos.y as f32 / scale_factor)
42 }
43
44 /// Convert this logical position to a physical position by multiplying the coordinates with the
45 /// specified scale factor.
46 pub fn to_physical(&self, scale_factor: f32) -> PhysicalPosition {
47 PhysicalPosition::from_logical(*self, scale_factor)
48 }
49
50 pub(crate) fn to_euclid(self) -> crate::lengths::LogicalPoint {
51 [self.x as _, self.y as _].into()
52 }
53 pub(crate) fn from_euclid(p: crate::lengths::LogicalPoint) -> Self {
54 Self::new(p.x as _, p.y as _)
55 }
56}
57
58/// A position represented in the coordinate space of physical device pixels. That is the space after applying
59/// a display device specific scale factor to pixels from the logical coordinate space.
60#[derive(Debug, Default, Copy, Clone, Eq, PartialEq)]
61#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
62pub struct PhysicalPosition {
63 /// The x coordinate.
64 pub x: i32,
65 /// The y coordinate.
66 pub y: i32,
67}
68
69impl PhysicalPosition {
70 /// Construct a new physical position from the given x and y coordinates, that are assumed to be
71 /// in the physical coordinate space.
72 pub const fn new(x: i32, y: i32) -> Self {
73 Self { x, y }
74 }
75
76 /// Convert a given logical position to a physical position by multiplying the coordinates with the
77 /// specified scale factor.
78 pub fn from_logical(logical_pos: LogicalPosition, scale_factor: f32) -> Self {
79 Self::new((logical_pos.x * scale_factor) as i32, (logical_pos.y * scale_factor) as i32)
80 }
81
82 /// Convert this physical position to a logical position by dividing the coordinates with the
83 /// specified scale factor.
84 pub fn to_logical(&self, scale_factor: f32) -> LogicalPosition {
85 LogicalPosition::from_physical(*self, scale_factor)
86 }
87
88 #[cfg(feature = "ffi")]
89 pub(crate) fn to_euclid(&self) -> crate::graphics::euclid::default::Point2D<i32> {
90 [self.x, self.y].into()
91 }
92
93 #[cfg(feature = "ffi")]
94 pub(crate) fn from_euclid(p: crate::graphics::euclid::default::Point2D<i32>) -> Self {
95 Self::new(p.x as _, p.y as _)
96 }
97}
98
99/// The position of the window in either physical or logical pixels. This is used
100/// with [`Window::set_position`].
101#[derive(Clone, Debug, derive_more::From, PartialEq)]
102pub enum WindowPosition {
103 /// The position in physical pixels.
104 Physical(PhysicalPosition),
105 /// The position in logical pixels.
106 Logical(LogicalPosition),
107}
108
109impl WindowPosition {
110 /// Turn the `WindowPosition` into a `PhysicalPosition`.
111 pub fn to_physical(&self, scale_factor: f32) -> PhysicalPosition {
112 match self {
113 WindowPosition::Physical(pos) => *pos,
114 WindowPosition::Logical(pos) => pos.to_physical(scale_factor),
115 }
116 }
117}
118
119/// A size represented in the coordinate space of logical pixels. That is the space before applying
120/// a display device specific scale factor.
121#[repr(C)]
122#[derive(Debug, Default, Copy, Clone, PartialEq)]
123#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
124pub struct LogicalSize {
125 /// The width in logical pixels.
126 pub width: f32,
127 /// The height in logical.
128 pub height: f32,
129}
130
131impl LogicalSize {
132 /// Construct a new logical size from the given width and height values, that are assumed to be
133 /// in the logical coordinate space.
134 pub const fn new(width: f32, height: f32) -> Self {
135 Self { width, height }
136 }
137
138 /// Convert a given physical size to a logical size by dividing width and height by the
139 /// specified scale factor.
140 pub fn from_physical(physical_size: PhysicalSize, scale_factor: f32) -> Self {
141 Self::new(
142 physical_size.width as f32 / scale_factor,
143 physical_size.height as f32 / scale_factor,
144 )
145 }
146
147 /// Convert this logical size to a physical size by multiplying width and height with the
148 /// specified scale factor.
149 pub fn to_physical(&self, scale_factor: f32) -> PhysicalSize {
150 PhysicalSize::from_logical(*self, scale_factor)
151 }
152
153 pub(crate) fn to_euclid(self) -> crate::lengths::LogicalSize {
154 [self.width as _, self.height as _].into()
155 }
156
157 pub(crate) fn from_euclid(p: crate::lengths::LogicalSize) -> Self {
158 Self::new(p.width as _, p.height as _)
159 }
160}
161
162/// A size represented in the coordinate space of physical device pixels. That is the space after applying
163/// a display device specific scale factor to pixels from the logical coordinate space.
164#[derive(Debug, Default, Copy, Clone, Eq, PartialEq)]
165#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
166pub struct PhysicalSize {
167 /// The width in physical pixels.
168 pub width: u32,
169 /// The height in physical pixels;
170 pub height: u32,
171}
172
173impl PhysicalSize {
174 /// Construct a new physical size from the width and height values, that are assumed to be
175 /// in the physical coordinate space.
176 pub const fn new(width: u32, height: u32) -> Self {
177 Self { width, height }
178 }
179
180 /// Convert a given logical size to a physical size by multiplying width and height with the
181 /// specified scale factor.
182 pub fn from_logical(logical_size: LogicalSize, scale_factor: f32) -> Self {
183 Self::new(
184 (logical_size.width * scale_factor) as u32,
185 (logical_size.height * scale_factor) as u32,
186 )
187 }
188
189 /// Convert this physical size to a logical size by dividing width and height by the
190 /// specified scale factor.
191 pub fn to_logical(&self, scale_factor: f32) -> LogicalSize {
192 LogicalSize::from_physical(*self, scale_factor)
193 }
194
195 #[cfg(feature = "ffi")]
196 pub(crate) fn to_euclid(&self) -> crate::graphics::euclid::default::Size2D<u32> {
197 [self.width, self.height].into()
198 }
199}
200
201/// The size of a window represented in either physical or logical pixels. This is used
202/// with [`Window::set_size`].
203#[derive(Clone, Debug, derive_more::From, PartialEq)]
204pub enum WindowSize {
205 /// The size in physical pixels.
206 Physical(PhysicalSize),
207 /// The size in logical screen pixels.
208 Logical(LogicalSize),
209}
210
211impl WindowSize {
212 /// Turn the `WindowSize` into a `PhysicalSize`.
213 pub fn to_physical(&self, scale_factor: f32) -> PhysicalSize {
214 match self {
215 WindowSize::Physical(size) => *size,
216 WindowSize::Logical(size) => size.to_physical(scale_factor),
217 }
218 }
219
220 /// Turn the `WindowSize` into a `LogicalSize`.
221 pub fn to_logical(&self, scale_factor: f32) -> LogicalSize {
222 match self {
223 WindowSize::Physical(size) => size.to_logical(scale_factor),
224 WindowSize::Logical(size) => *size,
225 }
226 }
227}
228
229#[test]
230fn logical_physical_pos() {
231 use crate::graphics::euclid::approxeq::ApproxEq;
232
233 let phys = PhysicalPosition::new(100, 50);
234 let logical = phys.to_logical(2.);
235 assert!(logical.x.approx_eq(&50.));
236 assert!(logical.y.approx_eq(&25.));
237
238 assert_eq!(logical.to_physical(2.), phys);
239}
240
241#[test]
242fn logical_physical_size() {
243 use crate::graphics::euclid::approxeq::ApproxEq;
244
245 let phys = PhysicalSize::new(100, 50);
246 let logical = phys.to_logical(2.);
247 assert!(logical.width.approx_eq(&50.));
248 assert!(logical.height.approx_eq(&25.));
249
250 assert_eq!(logical.to_physical(2.), phys);
251}
252
253/// This enum describes a low-level access to specific graphics APIs used
254/// by the renderer.
255#[derive(Clone)]
256#[non_exhaustive]
257pub enum GraphicsAPI<'a> {
258 /// The rendering is done using OpenGL.
259 NativeOpenGL {
260 /// Use this function pointer to obtain access to the OpenGL implementation - similar to `eglGetProcAddress`.
261 get_proc_address: &'a dyn Fn(&core::ffi::CStr) -> *const core::ffi::c_void,
262 },
263 /// The rendering is done on a HTML Canvas element using WebGL.
264 WebGL {
265 /// The DOM element id of the HTML Canvas element used for rendering.
266 canvas_element_id: &'a str,
267 /// The drawing context type used on the HTML Canvas element for rendering. This is the argument to the
268 /// `getContext` function on the HTML Canvas element.
269 context_type: &'a str,
270 },
271}
272
273impl core::fmt::Debug for GraphicsAPI<'_> {
274 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
275 match self {
276 GraphicsAPI::NativeOpenGL { .. } => write!(f, "GraphicsAPI::NativeOpenGL"),
277 GraphicsAPI::WebGL { context_type, .. } => {
278 write!(f, "GraphicsAPI::WebGL(context_type = {context_type})")
279 }
280 }
281 }
282}
283
284/// This enum describes the different rendering states, that will be provided
285/// to the parameter of the callback for `set_rendering_notifier` on the `slint::Window`.
286#[derive(Debug, Clone)]
287#[repr(u8)]
288#[non_exhaustive]
289pub enum RenderingState {
290 /// The window has been created and the graphics adapter/context initialized. When OpenGL
291 /// is used for rendering, the context will be current.
292 RenderingSetup,
293 /// The scene of items is about to be rendered. When OpenGL
294 /// is used for rendering, the context will be current.
295 BeforeRendering,
296 /// The scene of items was rendered, but the back buffer was not sent for display presentation
297 /// yet (for example GL swap buffers). When OpenGL is used for rendering, the context will be current.
298 AfterRendering,
299 /// The window will be destroyed and/or graphics resources need to be released due to other
300 /// constraints.
301 RenderingTeardown,
302}
303
304/// Internal trait that's used to map rendering state callbacks to either a Rust-API provided
305/// impl FnMut or a struct that invokes a C callback and implements Drop to release the closure
306/// on the C++ side.
307#[doc(hidden)]
308pub trait RenderingNotifier {
309 /// Called to notify that rendering has reached a certain state.
310 fn notify(&mut self, state: RenderingState, graphics_api: &GraphicsAPI);
311}
312
313impl<F: FnMut(RenderingState, &GraphicsAPI)> RenderingNotifier for F {
314 fn notify(&mut self, state: RenderingState, graphics_api: &GraphicsAPI) {
315 self(state, graphics_api)
316 }
317}
318
319/// This enum describes the different error scenarios that may occur when the application
320/// registers a rendering notifier on a `slint::Window`.
321#[derive(Debug, Clone)]
322#[repr(u8)]
323#[non_exhaustive]
324pub enum SetRenderingNotifierError {
325 /// The rendering backend does not support rendering notifiers.
326 Unsupported,
327 /// There is already a rendering notifier set, multiple notifiers are not supported.
328 AlreadySet,
329}
330
331impl core::fmt::Display for SetRenderingNotifierError {
332 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
333 match self {
334 Self::Unsupported => {
335 f.write_str("The rendering backend does not support rendering notifiers.")
336 }
337 Self::AlreadySet => f.write_str(
338 "There is already a rendering notifier set, multiple notifiers are not supported.",
339 ),
340 }
341 }
342}
343
344#[cfg(feature = "std")]
345impl std::error::Error for SetRenderingNotifierError {}
346
347#[cfg(feature = "raw-window-handle-06")]
348#[derive(Clone)]
349enum WindowHandleInner {
350 HandleByAdapter(alloc::rc::Rc<dyn WindowAdapter>),
351 HandleByRcRWH {
352 window_handle_provider: alloc::rc::Rc<dyn raw_window_handle_06::HasWindowHandle>,
353 display_handle_provider: alloc::rc::Rc<dyn raw_window_handle_06::HasDisplayHandle>,
354 },
355}
356
357/// This struct represents a persistent handle to a window and implements the
358/// [`raw_window_handle_06::HasWindowHandle`] and [`raw_window_handle_06::HasDisplayHandle`]
359/// traits for accessing exposing raw window and display handles.
360/// Obtain an instance of this by calling [`Window::window_handle()`].
361#[cfg(feature = "raw-window-handle-06")]
362#[derive(Clone)]
363pub struct WindowHandle {
364 inner: WindowHandleInner,
365}
366
367#[cfg(feature = "raw-window-handle-06")]
368impl raw_window_handle_06::HasWindowHandle for WindowHandle {
369 fn window_handle(
370 &self,
371 ) -> Result<raw_window_handle_06::WindowHandle<'_>, raw_window_handle_06::HandleError> {
372 match &self.inner {
373 WindowHandleInner::HandleByAdapter(adapter) => adapter.window_handle_06(),
374 WindowHandleInner::HandleByRcRWH { window_handle_provider, .. } => {
375 window_handle_provider.window_handle()
376 }
377 }
378 }
379}
380
381#[cfg(feature = "raw-window-handle-06")]
382impl raw_window_handle_06::HasDisplayHandle for WindowHandle {
383 fn display_handle(
384 &self,
385 ) -> Result<raw_window_handle_06::DisplayHandle<'_>, raw_window_handle_06::HandleError> {
386 match &self.inner {
387 WindowHandleInner::HandleByAdapter(adapter) => adapter.display_handle_06(),
388 WindowHandleInner::HandleByRcRWH { display_handle_provider, .. } => {
389 display_handle_provider.display_handle()
390 }
391 }
392 }
393}
394
395/// This type represents a window towards the windowing system, that's used to render the
396/// scene of a component. It provides API to control windowing system specific aspects such
397/// as the position on the screen.
398#[repr(transparent)]
399pub struct Window(pub(crate) WindowInner);
400
401/// This enum describes whether a Window is allowed to be hidden when the user tries to close the window.
402/// It is the return type of the callback provided to [Window::on_close_requested].
403#[derive(Copy, Clone, Debug, PartialEq, Default)]
404#[repr(u8)]
405pub enum CloseRequestResponse {
406 /// The Window will be hidden (default action)
407 #[default]
408 HideWindow = 0,
409 /// The close request is rejected and the window will be kept shown.
410 KeepWindowShown = 1,
411}
412
413impl Window {
414 /// Create a new window from a window adapter
415 ///
416 /// You only need to create the window yourself when you create a [`WindowAdapter`] from
417 /// [`Platform::create_window_adapter`](crate::platform::Platform::create_window_adapter)
418 ///
419 /// Since the window adapter must own the Window, this function is meant to be used with
420 /// [`Rc::new_cyclic`](alloc::rc::Rc::new_cyclic)
421 ///
422 /// # Example
423 /// ```rust
424 /// use std::rc::Rc;
425 /// use slint::platform::{WindowAdapter, Renderer};
426 /// use slint::{Window, PhysicalSize};
427 /// struct MyWindowAdapter {
428 /// window: Window,
429 /// //...
430 /// }
431 /// impl WindowAdapter for MyWindowAdapter {
432 /// fn window(&self) -> &Window { &self.window }
433 /// fn size(&self) -> PhysicalSize { unimplemented!() }
434 /// fn renderer(&self) -> &dyn Renderer { unimplemented!() }
435 /// }
436 ///
437 /// fn create_window_adapter() -> Rc<dyn WindowAdapter> {
438 /// Rc::<MyWindowAdapter>::new_cyclic(|weak| {
439 /// MyWindowAdapter {
440 /// window: Window::new(weak.clone()),
441 /// //...
442 /// }
443 /// })
444 /// }
445 /// ```
446 pub fn new(window_adapter_weak: alloc::rc::Weak<dyn WindowAdapter>) -> Self {
447 Self(WindowInner::new(window_adapter_weak))
448 }
449
450 /// Shows the window on the screen. An additional strong reference on the
451 /// associated component is maintained while the window is visible.
452 ///
453 /// Call [`Self::hide()`] to make the window invisible again, and drop the additional
454 /// strong reference.
455 pub fn show(&self) -> Result<(), PlatformError> {
456 self.0.show()
457 }
458
459 /// Hides the window, so that it is not visible anymore. The additional strong
460 /// reference on the associated component, that was created when [`Self::show()`] was called, is
461 /// dropped.
462 pub fn hide(&self) -> Result<(), PlatformError> {
463 self.0.hide()
464 }
465
466 /// This function allows registering a callback that's invoked during the different phases of
467 /// rendering. This allows custom rendering on top or below of the scene.
468 pub fn set_rendering_notifier(
469 &self,
470 callback: impl FnMut(RenderingState, &GraphicsAPI) + 'static,
471 ) -> Result<(), SetRenderingNotifierError> {
472 self.0.window_adapter().renderer().set_rendering_notifier(Box::new(callback))
473 }
474
475 /// This function allows registering a callback that's invoked when the user tries to close a window.
476 /// The callback has to return a [CloseRequestResponse].
477 pub fn on_close_requested(&self, callback: impl FnMut() -> CloseRequestResponse + 'static) {
478 self.0.on_close_requested(callback);
479 }
480
481 /// This function issues a request to the windowing system to redraw the contents of the window.
482 pub fn request_redraw(&self) {
483 self.0.window_adapter().request_redraw()
484 }
485
486 /// This function returns the scale factor that allows converting between logical and
487 /// physical pixels.
488 pub fn scale_factor(&self) -> f32 {
489 self.0.scale_factor()
490 }
491
492 /// Returns the position of the window on the screen, in physical screen coordinates and including
493 /// a window frame (if present).
494 pub fn position(&self) -> PhysicalPosition {
495 self.0.window_adapter().position().unwrap_or_default()
496 }
497
498 /// Sets the position of the window on the screen, in physical screen coordinates and including
499 /// a window frame (if present).
500 /// Note that on some windowing systems, such as Wayland, this functionality is not available.
501 pub fn set_position(&self, position: impl Into<WindowPosition>) {
502 let position = position.into();
503 self.0.window_adapter().set_position(position)
504 }
505
506 /// Returns the size of the window on the screen, in physical screen coordinates and excluding
507 /// a window frame (if present).
508 pub fn size(&self) -> PhysicalSize {
509 self.0.window_adapter().size()
510 }
511
512 /// Resizes the window to the specified size on the screen, in physical pixels and excluding
513 /// a window frame (if present).
514 pub fn set_size(&self, size: impl Into<WindowSize>) {
515 let size = size.into();
516 crate::window::WindowAdapter::set_size(&*self.0.window_adapter(), size);
517 }
518
519 /// Returns if the window is currently fullscreen
520 pub fn is_fullscreen(&self) -> bool {
521 self.0.is_fullscreen()
522 }
523
524 /// Set or unset the window to display fullscreen.
525 pub fn set_fullscreen(&self, fullscreen: bool) {
526 self.0.set_fullscreen(fullscreen);
527 }
528
529 /// Returns if the window is currently maximized
530 pub fn is_maximized(&self) -> bool {
531 self.0.is_maximized()
532 }
533
534 /// Maximize or unmaximize the window.
535 pub fn set_maximized(&self, maximized: bool) {
536 self.0.set_maximized(maximized);
537 }
538
539 /// Returns if the window is currently minimized
540 pub fn is_minimized(&self) -> bool {
541 self.0.is_minimized()
542 }
543
544 /// Minimize or unminimze the window.
545 pub fn set_minimized(&self, minimized: bool) {
546 self.0.set_minimized(minimized);
547 }
548
549 /// Dispatch a window event to the scene.
550 ///
551 /// Use this when you're implementing your own backend and want to forward user input events.
552 ///
553 /// Any position fields in the event must be in the logical pixel coordinate system relative to
554 /// the top left corner of the window.
555 ///
556 /// This function panics if there is an error processing the event.
557 /// Use [`Self::try_dispatch_event()`] to handle the error.
558 #[track_caller]
559 pub fn dispatch_event(&self, event: crate::platform::WindowEvent) {
560 self.try_dispatch_event(event).unwrap()
561 }
562
563 /// Dispatch a window event to the scene.
564 ///
565 /// Use this when you're implementing your own backend and want to forward user input events.
566 ///
567 /// Any position fields in the event must be in the logical pixel coordinate system relative to
568 /// the top left corner of the window.
569 pub fn try_dispatch_event(
570 &self,
571 event: crate::platform::WindowEvent,
572 ) -> Result<(), PlatformError> {
573 match event {
574 crate::platform::WindowEvent::PointerPressed { position, button } => {
575 self.0.process_mouse_input(MouseEvent::Pressed {
576 position: position.to_euclid().cast(),
577 button,
578 click_count: 0,
579 });
580 }
581 crate::platform::WindowEvent::PointerReleased { position, button } => {
582 self.0.process_mouse_input(MouseEvent::Released {
583 position: position.to_euclid().cast(),
584 button,
585 click_count: 0,
586 });
587 }
588 crate::platform::WindowEvent::PointerMoved { position } => {
589 self.0.process_mouse_input(MouseEvent::Moved {
590 position: position.to_euclid().cast(),
591 });
592 }
593 crate::platform::WindowEvent::PointerScrolled { position, delta_x, delta_y } => {
594 self.0.process_mouse_input(MouseEvent::Wheel {
595 position: position.to_euclid().cast(),
596 delta_x: delta_x as _,
597 delta_y: delta_y as _,
598 });
599 }
600 crate::platform::WindowEvent::PointerExited => {
601 self.0.process_mouse_input(MouseEvent::Exit)
602 }
603
604 crate::platform::WindowEvent::KeyPressed { text } => {
605 self.0.process_key_input(crate::input::KeyEvent {
606 text,
607 repeat: false,
608 event_type: KeyEventType::KeyPressed,
609 ..Default::default()
610 })
611 }
612 crate::platform::WindowEvent::KeyPressRepeated { text } => {
613 self.0.process_key_input(crate::input::KeyEvent {
614 text,
615 repeat: true,
616 event_type: KeyEventType::KeyPressed,
617 ..Default::default()
618 })
619 }
620 crate::platform::WindowEvent::KeyReleased { text } => {
621 self.0.process_key_input(crate::input::KeyEvent {
622 text,
623 event_type: KeyEventType::KeyReleased,
624 ..Default::default()
625 })
626 }
627 crate::platform::WindowEvent::ScaleFactorChanged { scale_factor } => {
628 self.0.set_scale_factor(scale_factor);
629 }
630 crate::platform::WindowEvent::Resized { size } => {
631 self.0.set_window_item_geometry(size.to_euclid());
632 self.0.window_adapter().renderer().resize(size.to_physical(self.scale_factor()))?;
633 }
634 crate::platform::WindowEvent::CloseRequested => {
635 if self.0.request_close() {
636 self.hide()?;
637 }
638 }
639 crate::platform::WindowEvent::WindowActiveChanged(bool) => self.0.set_active(bool),
640 };
641 Ok(())
642 }
643
644 /// Returns true if there is an animation currently active on any property in the Window; false otherwise.
645 pub fn has_active_animations(&self) -> bool {
646 // TODO make it really per window.
647 crate::animations::CURRENT_ANIMATION_DRIVER.with(|driver| driver.has_active_animations())
648 }
649
650 /// Returns the visibility state of the window. This function can return false even if you previously called show()
651 /// on it, for example if the user minimized the window.
652 pub fn is_visible(&self) -> bool {
653 self.0.is_visible()
654 }
655
656 /// Returns a struct that implements the raw window handle traits to access the windowing system specific window
657 /// and display handles. This function is only accessible if you enable the `raw-window-handle-06` crate feature.
658 #[cfg(feature = "raw-window-handle-06")]
659 pub fn window_handle(&self) -> WindowHandle {
660 let adapter = self.0.window_adapter();
661 if let Some((window_handle_provider, display_handle_provider)) =
662 adapter.internal(crate::InternalToken).and_then(|internal| {
663 internal.window_handle_06_rc().ok().zip(internal.display_handle_06_rc().ok())
664 })
665 {
666 WindowHandle {
667 inner: WindowHandleInner::HandleByRcRWH {
668 window_handle_provider,
669 display_handle_provider,
670 },
671 }
672 } else {
673 WindowHandle { inner: WindowHandleInner::HandleByAdapter(adapter) }
674 }
675 }
676
677 /// Takes a snapshot of the window contents and returns it as RGBA8 encoded pixel buffer.
678 ///
679 /// Note that this function may be slow to call as it may need to re-render the scene.
680 pub fn take_snapshot(&self) -> Result<SharedPixelBuffer<Rgba8Pixel>, PlatformError> {
681 self.0.window_adapter().renderer().take_snapshot()
682 }
683}
684
685pub use crate::SharedString;
686
687#[i_slint_core_macros::slint_doc]
688/// This trait is used to obtain references to global singletons exported in `.slint`
689/// markup. Alternatively, you can use [`ComponentHandle::global`] to obtain access.
690///
691/// This trait is implemented by the compiler for each global singleton that's exported.
692///
693/// # Example
694/// The following example of `.slint` markup defines a global singleton called `Palette`, exports
695/// it and modifies it from Rust code:
696/// ```rust
697/// # i_slint_backend_testing::init_no_event_loop();
698/// slint::slint!{
699/// export global Palette {
700/// in property<color> foreground-color;
701/// in property<color> background-color;
702/// }
703///
704/// export component App inherits Window {
705/// background: Palette.background-color;
706/// Text {
707/// text: "Hello";
708/// color: Palette.foreground-color;
709/// }
710/// // ...
711/// }
712/// }
713/// let app = App::new().unwrap();
714/// app.global::<Palette>().set_background_color(slint::Color::from_rgb_u8(0, 0, 0));
715///
716/// // alternate way to access the global singleton:
717/// Palette::get(&app).set_foreground_color(slint::Color::from_rgb_u8(255, 255, 255));
718/// ```
719///
720/// See also the [language documentation for global singletons](slint:globals) for more information.
721///
722/// **Note:** Only globals that are exported or re-exported from the main .slint file will
723/// be exposed in the API
724pub trait Global<'a, Component> {
725 /// Returns a reference that's tied to the life time of the provided component.
726 fn get(component: &'a Component) -> Self;
727}
728
729/// This trait describes the common public API of a strongly referenced Slint component.
730/// It allows creating strongly-referenced clones, a conversion into/ a weak pointer as well
731/// as other convenience functions.
732///
733/// This trait is implemented by the [generated component](index.html#generated-components)
734pub trait ComponentHandle {
735 /// The type of the generated component.
736 #[doc(hidden)]
737 type Inner;
738 /// Returns a new weak pointer.
739 fn as_weak(&self) -> Weak<Self>
740 where
741 Self: Sized;
742
743 /// Returns a clone of this handle that's a strong reference.
744 #[must_use]
745 fn clone_strong(&self) -> Self;
746
747 /// Internal function used when upgrading a weak reference to a strong one.
748 #[doc(hidden)]
749 fn from_inner(_: vtable::VRc<ItemTreeVTable, Self::Inner>) -> Self;
750
751 /// Convenience function for [`crate::Window::show()`](struct.Window.html#method.show).
752 /// This shows the window on the screen and maintains an extra strong reference while
753 /// the window is visible. To react to events from the windowing system, such as draw
754 /// requests or mouse/touch input, it is still necessary to spin the event loop,
755 /// using [`crate::run_event_loop`](fn.run_event_loop.html).
756 fn show(&self) -> Result<(), PlatformError>;
757
758 /// Convenience function for [`crate::Window::hide()`](struct.Window.html#method.hide).
759 /// Hides the window, so that it is not visible anymore. The additional strong reference
760 /// on the associated component, that was created when show() was called, is dropped.
761 fn hide(&self) -> Result<(), PlatformError>;
762
763 /// Returns the Window associated with this component. The window API can be used
764 /// to control different aspects of the integration into the windowing system,
765 /// such as the position on the screen.
766 fn window(&self) -> &Window;
767
768 /// This is a convenience function that first calls [`Self::show`], followed by [`crate::run_event_loop()`](fn.run_event_loop.html)
769 /// and [`Self::hide`].
770 fn run(&self) -> Result<(), PlatformError>;
771
772 /// This function provides access to instances of global singletons exported in `.slint`.
773 /// See [`Global`] for an example how to export and access globals from `.slint` markup.
774 fn global<'a, T: Global<'a, Self>>(&'a self) -> T
775 where
776 Self: Sized;
777}
778
779mod weak_handle {
780
781 use super::*;
782
783 /// Struct that's used to hold weak references of a [Slint component](index.html#generated-components)
784 ///
785 /// In order to create a Weak, you should use [`ComponentHandle::as_weak`].
786 ///
787 /// Strong references should not be captured by the functions given to a lambda,
788 /// as this would produce a reference loop and leak the component.
789 /// Instead, the callback function should capture a weak component.
790 ///
791 /// The Weak component also implement `Send` and can be send to another thread.
792 /// but the upgrade function will only return a valid component from the same thread
793 /// as the one it has been created from.
794 /// This is useful to use with [`invoke_from_event_loop()`] or [`Self::upgrade_in_event_loop()`].
795 pub struct Weak<T: ComponentHandle> {
796 inner: vtable::VWeak<ItemTreeVTable, T::Inner>,
797 #[cfg(feature = "std")]
798 thread: std::thread::ThreadId,
799 }
800
801 impl<T: ComponentHandle> Default for Weak<T> {
802 fn default() -> Self {
803 Self {
804 inner: vtable::VWeak::default(),
805 #[cfg(feature = "std")]
806 thread: std::thread::current().id(),
807 }
808 }
809 }
810
811 impl<T: ComponentHandle> Clone for Weak<T> {
812 fn clone(&self) -> Self {
813 Self {
814 inner: self.inner.clone(),
815 #[cfg(feature = "std")]
816 thread: self.thread,
817 }
818 }
819 }
820
821 impl<T: ComponentHandle> Weak<T> {
822 #[doc(hidden)]
823 pub fn new(rc: &vtable::VRc<ItemTreeVTable, T::Inner>) -> Self {
824 Self {
825 inner: vtable::VRc::downgrade(rc),
826 #[cfg(feature = "std")]
827 thread: std::thread::current().id(),
828 }
829 }
830
831 /// Returns a new strongly referenced component if some other instance still
832 /// holds a strong reference. Otherwise, returns None.
833 ///
834 /// This also returns None if the current thread is not the thread that created
835 /// the component
836 pub fn upgrade(&self) -> Option<T>
837 where
838 T: ComponentHandle,
839 {
840 #[cfg(feature = "std")]
841 if std::thread::current().id() != self.thread {
842 return None;
843 }
844 self.inner.upgrade().map(T::from_inner)
845 }
846
847 /// Convenience function that returns a new strongly referenced component if
848 /// some other instance still holds a strong reference and the current thread
849 /// is the thread that created this component.
850 /// Otherwise, this function panics.
851 #[track_caller]
852 pub fn unwrap(&self) -> T {
853 #[cfg(feature = "std")]
854 if std::thread::current().id() != self.thread {
855 panic!(
856 "Trying to upgrade a Weak from a different thread than the one it belongs to"
857 );
858 }
859 T::from_inner(self.inner.upgrade().expect("The Weak doesn't hold a valid component"))
860 }
861
862 /// A helper function to allow creation on `component_factory::Component` from
863 /// a `ComponentHandle`
864 pub(crate) fn inner(&self) -> vtable::VWeak<ItemTreeVTable, T::Inner> {
865 self.inner.clone()
866 }
867
868 /// Convenience function that combines [`invoke_from_event_loop()`] with [`Self::upgrade()`]
869 ///
870 /// The given functor will be added to an internal queue and will wake the event loop.
871 /// On the next iteration of the event loop, the functor will be executed with a `T` as an argument.
872 ///
873 /// If the component was dropped because there are no more strong reference to the component,
874 /// the functor will not be called.
875 ///
876 /// # Example
877 /// ```rust
878 /// # i_slint_backend_testing::init_no_event_loop();
879 /// slint::slint! { export component MyApp inherits Window { in property <int> foo; /* ... */ } }
880 /// let handle = MyApp::new().unwrap();
881 /// let handle_weak = handle.as_weak();
882 /// let thread = std::thread::spawn(move || {
883 /// // ... Do some computation in the thread
884 /// let foo = 42;
885 /// # assert!(handle_weak.upgrade().is_none()); // note that upgrade fails in a thread
886 /// # return; // don't upgrade_in_event_loop in our examples
887 /// // now forward the data to the main thread using upgrade_in_event_loop
888 /// handle_weak.upgrade_in_event_loop(move |handle| handle.set_foo(foo));
889 /// });
890 /// # thread.join().unwrap(); return; // don't run the event loop in examples
891 /// handle.run().unwrap();
892 /// ```
893 #[cfg(any(feature = "std", feature = "unsafe-single-threaded"))]
894 pub fn upgrade_in_event_loop(
895 &self,
896 func: impl FnOnce(T) + Send + 'static,
897 ) -> Result<(), EventLoopError>
898 where
899 T: 'static,
900 {
901 let weak_handle = self.clone();
902 super::invoke_from_event_loop(move || {
903 if let Some(h) = weak_handle.upgrade() {
904 func(h);
905 }
906 })
907 }
908 }
909
910 // Safety: we make sure in upgrade that the thread is the proper one,
911 // and the VWeak only use atomic pointer so it is safe to clone and drop in another thread
912 #[allow(unsafe_code)]
913 #[cfg(any(feature = "std", feature = "unsafe-single-threaded"))]
914 unsafe impl<T: ComponentHandle> Send for Weak<T> {}
915 #[allow(unsafe_code)]
916 #[cfg(any(feature = "std", feature = "unsafe-single-threaded"))]
917 unsafe impl<T: ComponentHandle> Sync for Weak<T> {}
918}
919
920pub use weak_handle::*;
921
922/// Adds the specified function to an internal queue, notifies the event loop to wake up.
923/// Once woken up, any queued up functors will be invoked.
924///
925/// This function is thread-safe and can be called from any thread, including the one
926/// running the event loop. The provided functors will only be invoked from the thread
927/// that started the event loop.
928///
929/// You can use this to set properties or use any other Slint APIs from other threads,
930/// by collecting the code in a functor and queuing it up for invocation within the event loop.
931///
932/// If you want to capture non-Send types to run in the next event loop iteration,
933/// you can use the `slint::spawn_local` function instead.
934///
935/// See also [`Weak::upgrade_in_event_loop`].
936///
937/// # Example
938/// ```rust
939/// slint::slint! { export component MyApp inherits Window { in property <int> foo; /* ... */ } }
940/// # i_slint_backend_testing::init_no_event_loop();
941/// let handle = MyApp::new().unwrap();
942/// let handle_weak = handle.as_weak();
943/// # return; // don't run the event loop in examples
944/// let thread = std::thread::spawn(move || {
945/// // ... Do some computation in the thread
946/// let foo = 42;
947/// // now forward the data to the main thread using invoke_from_event_loop
948/// let handle_copy = handle_weak.clone();
949/// slint::invoke_from_event_loop(move || handle_copy.unwrap().set_foo(foo));
950/// });
951/// handle.run().unwrap();
952/// ```
953pub fn invoke_from_event_loop(func: impl FnOnce() + Send + 'static) -> Result<(), EventLoopError> {
954 crate::platform::with_event_loop_proxy(|proxy| {
955 proxy
956 .ok_or(EventLoopError::NoEventLoopProvider)?
957 .invoke_from_event_loop(alloc::boxed::Box::new(func))
958 })
959}
960
961/// Schedules the main event loop for termination. This function is meant
962/// to be called from callbacks triggered by the UI. After calling the function,
963/// it will return immediately and once control is passed back to the event loop,
964/// the initial call to `slint::run_event_loop()` will return.
965///
966/// This function can be called from any thread
967pub fn quit_event_loop() -> Result<(), EventLoopError> {
968 crate::platform::with_event_loop_proxy(|proxy| {
969 proxy.ok_or(EventLoopError::NoEventLoopProvider)?.quit_event_loop()
970 })
971}
972
973#[derive(Debug, Clone, Eq, PartialEq)]
974#[non_exhaustive]
975/// Error returned from the [`invoke_from_event_loop()`] and [`quit_event_loop()`] function
976pub enum EventLoopError {
977 /// The event could not be sent because the event loop was terminated already
978 EventLoopTerminated,
979 /// The event could not be sent because the Slint platform abstraction was not yet initialized,
980 /// or the platform does not support event loop.
981 NoEventLoopProvider,
982}
983
984impl core::fmt::Display for EventLoopError {
985 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
986 match self {
987 EventLoopError::EventLoopTerminated => {
988 f.write_str("The event loop was already terminated")
989 }
990 EventLoopError::NoEventLoopProvider => {
991 f.write_str("The Slint platform does not provide an event loop")
992 }
993 }
994 }
995}
996
997#[cfg(feature = "std")]
998impl std::error::Error for EventLoopError {}
999
1000/// The platform encountered a fatal error.
1001///
1002/// This error typically indicates an issue with initialization or connecting to the windowing system.
1003///
1004/// This can be constructed from a `String`:
1005/// ```rust
1006/// use slint::platform::PlatformError;
1007/// PlatformError::from(format!("Could not load resource {}", 1234));
1008/// ```
1009#[derive(Debug)]
1010#[non_exhaustive]
1011pub enum PlatformError {
1012 /// No default platform was selected, or no platform could be initialized.
1013 ///
1014 /// If you encounter this error, make sure to either selected trough the `backend-*` cargo features flags,
1015 /// or call [`platform::set_platform()`](crate::platform::set_platform)
1016 /// before running the event loop
1017 NoPlatform,
1018 /// The Slint Platform does not provide an event loop.
1019 ///
1020 /// The [`Platform::run_event_loop`](crate::platform::Platform::run_event_loop)
1021 /// is not implemented for the current platform.
1022 NoEventLoopProvider,
1023
1024 /// There is already a platform set from another thread.
1025 SetPlatformError(crate::platform::SetPlatformError),
1026
1027 /// Another platform-specific error occurred
1028 Other(String),
1029 /// Another platform-specific error occurred.
1030 #[cfg(feature = "std")]
1031 OtherError(Box<dyn std::error::Error + Send + Sync>),
1032}
1033
1034impl core::fmt::Display for PlatformError {
1035 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1036 match self {
1037 PlatformError::NoPlatform => f.write_str(
1038 "No default Slint platform was selected, and no Slint platform was initialized",
1039 ),
1040 PlatformError::NoEventLoopProvider => {
1041 f.write_str("The Slint platform does not provide an event loop")
1042 }
1043 PlatformError::SetPlatformError(_) => {
1044 f.write_str("The Slint platform was initialized in another thread")
1045 }
1046 PlatformError::Other(str) => f.write_str(str),
1047 #[cfg(feature = "std")]
1048 PlatformError::OtherError(error) => error.fmt(f),
1049 }
1050 }
1051}
1052
1053impl From<String> for PlatformError {
1054 fn from(value: String) -> Self {
1055 Self::Other(value)
1056 }
1057}
1058impl From<&str> for PlatformError {
1059 fn from(value: &str) -> Self {
1060 Self::Other(value.into())
1061 }
1062}
1063
1064#[cfg(feature = "std")]
1065impl From<Box<dyn std::error::Error + Send + Sync>> for PlatformError {
1066 fn from(error: Box<dyn std::error::Error + Send + Sync>) -> Self {
1067 Self::OtherError(error)
1068 }
1069}
1070
1071#[cfg(feature = "std")]
1072impl std::error::Error for PlatformError {
1073 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1074 match self {
1075 PlatformError::OtherError(err) => Some(err.as_ref()),
1076 _ => None,
1077 }
1078 }
1079}
1080
1081#[test]
1082#[cfg(feature = "std")]
1083fn error_is_send() {
1084 let _: Box<dyn std::error::Error + Send + Sync + 'static> = PlatformError::NoPlatform.into();
1085}
1086
1087/// Sets the application id for use on Wayland or X11 with [xdg](https://specifications.freedesktop.org/desktop-entry-spec/latest/)
1088/// compliant window managers. This must be set before the window is shown, and has only an effect on Wayland or X11.
1089pub fn set_xdg_app_id(app_id: impl Into<SharedString>) -> Result<(), PlatformError> {
1090 crate::context::with_global_context(
1091 || Err(crate::platform::PlatformError::NoPlatform),
1092 |ctx| ctx.set_xdg_app_id(app_id.into()),
1093 )
1094}