slint/lib.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// cSpell: ignore buildrs
5
6#![cfg_attr(docsrs, feature(doc_cfg))]
7
8/*!
9# Slint
10
11This crate is the main entry point for embedding user interfaces designed with
12[Slint](https://slint.rs/) in Rust programs.
13*/
14#.")]
15/*! If you are already familiar with Slint, the following topics provide related information.
16
17## Topics
18
19*/
20#")]
21/*! - [Type mappings between .slint and Rust](docs::type_mappings)
22 - [Feature flags and backend selection](docs::cargo_features)
23 - [Slint on Microcontrollers](docs::mcu)
24
25## How to use this crate:
26
27Designs of user interfaces are described in the `.slint` design markup language. There are three ways
28of including them in Rust:
29
30 - The `.slint` code is [inline in a macro](#the-slint-code-in-a-macro).
31 - The `.slint` code in [external files compiled with `build.rs`](#the-slint-code-in-external-files-is-compiled-with-buildrs)
32*/
33#.")]
34/*!
35
36With the first two methods, the markup code is translated to Rust code and each component is turned into a Rust
37struct with functions. Use these functions to instantiate and show the component, and
38to access declared properties. Check out our [sample component](docs::generated_code::SampleComponent) for more
39information about the generation functions and how to use them.
40
41### The .slint code in a macro
42
43This method combines your Rust code with the `.slint` design markup in one file, using a macro:
44
45```rust,no_run
46slint::slint!{
47 #[slint_edition = "1.19"]
48 export component HelloWorld inherits Window {
49 Text {
50 text: "hello world";
51 color: green;
52 }
53 }
54}
55fn main() {
56 HelloWorld::new().unwrap().run().unwrap();
57}
58```
59
60### The .slint code in external files is compiled with `build.rs`
61
62When your design becomes bigger in terms of markup code, you may want move it to a dedicated
63`.slint` file. */
64#.")]
65/*!Use a [build script](https://doc.rust-lang.org/cargo/reference/build-scripts.html) to compile
66your main `.slint` file:
67
68*/
69# crate in `build-dependencies`:")]
70/*!
71
72```toml
73[package]
74...
75build = "build.rs"
76edition = "2021"
77
78[dependencies]
79slint = "1.16.0"
80...
81
82[build-dependencies]
83slint-build = "1.16.0"
84```
85
86Use the API of the slint-build crate in the `build.rs` file:
87
88```rust,no_run
89fn main() {
90 slint_build::compile("ui/hello.slint").unwrap();
91}
92```
93
94Finally, use the [`include_modules!`] macro in your `main.rs`:
95
96```ignore
97slint::include_modules!();
98fn main() {
99 HelloWorld::new().unwrap().run().unwrap();
100}
101```
102
103Use our [Template Repository](https://github.com/slint-ui/slint-rust-template) to create a skeleton file
104hierarchy that uses this method:
105
1061. Download and extract the [ZIP archive of the Rust Template](https://github.com/slint-ui/slint-rust-template/archive/refs/heads/main.zip).
1072. Rename the extracted directory and change into it:
108
109```bash
110mv slint-rust-template-main my-project
111cd my-project
112```
113
114## Generated components
115
116Exported component from the macro or the main file that inherit `Window` or `Dialog` is mapped to a Rust structure.
117
118The components are generated and re-exported to the location of the [`include_modules!`] or [`slint!`] macro.
119It is represented as a struct with the same name as the component.
120
121For example, if you have
122
123```slint,no-preview
124export component MyComponent inherits Window { /*...*/ }
125```
126
127in the .slint file, it will create a
128```rust
129struct MyComponent { /*...*/ }
130```
131
132See also our [sample component](docs::generated_code::SampleComponent) for more information about the API of the generated struct.
133
134A component is instantiated using the [`fn new() -> Self`](docs::generated_code::SampleComponent::new) function. The following
135convenience functions are available through the [`ComponentHandle`] implementation:
136
137 - [`fn clone_strong(&self) -> Self`](docs::generated_code::SampleComponent::clone_strong): creates a strongly referenced clone of the component instance.
138 - [`fn as_weak(&self) -> Weak`](docs::generated_code::SampleComponent::as_weak): to create a [weak](Weak) reference to the component instance.
139 - [`fn show(&self)`](docs::generated_code::SampleComponent::show): to show the window of the component.
140 - [`fn hide(&self)`](docs::generated_code::SampleComponent::hide): to hide the window of the component.
141 - [`fn run(&self)`](docs::generated_code::SampleComponent::run): a convenience function that first calls `show()`,
142 followed by spinning the event loop, and `hide()` when returning from the event loop.
143 - [`fn global<T: Global<Self>>(&self) -> T`](docs::generated_code::SampleComponent::global): an accessor to the global singletons,
144
145For each top-level property
146 - A setter [`fn set_<property_name>(&self, value: <PropertyType>)`](docs::generated_code::SampleComponent::set_counter)
147 - A getter [`fn get_<property_name>(&self) -> <PropertyType>`](docs::generated_code::SampleComponent::get_counter)
148
149For each top-level callback
150 - [`fn invoke_<callback_name>(&self)`](docs::generated_code::SampleComponent::invoke_hello): to invoke the callback
151 - [`fn on_<callback_name>(&self, callback: impl Fn(<CallbackArgs>) + 'static)`](docs::generated_code::SampleComponent::on_hello): to set the callback handler.
152
153In the names of types, struct fields, and functions, use underscores (`_`) in place of dashes (`-`).
154If a name is a Rust keyword, such as a struct field `type`,
155write it as a [raw identifier](https://doc.rust-lang.org/reference/identifiers.html#raw-identifiers): `r#type`.
156Rust doesn't accept `self`, `Self`, `super`, and `crate` as raw identifiers;
157add a trailing underscore to these instead, such as `self_`.
158
159After instantiating the component, call [`ComponentHandle::run()`] on show it on the screen and spin the event loop to
160react to input events. To show multiple components simultaneously, call [`ComponentHandle::show()`] on each instance.
161Call [`run_event_loop()`] when you're ready to enter the event loop.
162
163The generated component struct acts as a handle holding a strong reference (similar to an `Rc`). The `Clone` trait is
164not implemented. Instead you need to make explicit [`ComponentHandle::clone_strong`] and [`ComponentHandle::as_weak`]
165calls. A strong reference should not be captured by the closures given to a callback, as this would produce a reference
166loop and leak the component. Instead, the callback function should capture a weak component.
167
168## Threading and Event-loop
169
170For platform-specific reasons, the event loop must run in the main thread, in most backends, and all the components
171must be created in the same thread as the thread the event loop is running or is going to run.
172
173You should perform the minimum amount of work in the main thread and delegate the actual logic to another
174thread to avoid blocking animations. Use the [`invoke_from_event_loop`] function to communicate from your worker thread to the UI thread.
175
176To run a function with a delay or with an interval use a [`Timer`].
177
178To run an async function or a future, use [`spawn_local()`].
179
180## Exported Global singletons
181
182*/
183# from the main file,")]
184/*! it is also generated with the exported name. Like the main component, the generated struct have
185inherent method to access the properties and callback:
186
187For each property
188 - A setter: `fn set_<property_name>(&self, value: <PropertyType>)`
189 - A getter: `fn get_<property_name>(&self) -> <PropertyType>`
190
191For each callback
192 - `fn invoke_<callback_name>(&self, <CallbackArgs>) -> <ReturnValue>` to invoke the callback
193 - `fn on_<callback_name>(&self, callback: impl Fn(<CallbackArgs>) + 'static)` to set the callback handler.
194
195The global can be accessed with the [`ComponentHandle::global()`] function, or with [`Global::get()`]
196
197See our [sample global](docs::generated_code::SampleGlobal) for an example of the API of the generated global.
198See also the [documentation of the `Global` trait](Global).
199
200**Note**: Global singletons are instantiated once per component. When declaring multiple components for `export` to Rust,
201each instance will have their own instance of associated globals singletons.
202*/
203
204#![warn(missing_docs)]
205#![deny(unsafe_code)]
206#![doc(html_logo_url = "https://slint.dev/logo/slint-logo-square-light.svg")]
207#![no_std]
208#![allow(clippy::needless_doctest_main)] // We document how to write a main function
209
210extern crate alloc;
211#[cfg(feature = "std")]
212extern crate std;
213
214#[cfg(not(feature = "compat-1-18"))]
215compile_error!(
216 "The feature `compat-1-18` must be enabled to ensure \
217 forward compatibility with future version of this crate"
218);
219
220pub use slint_macros::slint;
221
222pub use i_slint_backend_selector::api::*;
223pub use i_slint_core::api::*;
224#[doc(hidden)]
225#[deprecated(note = "Experimental type was made public by mistake")]
226pub use i_slint_core::component_factory::ComponentFactory;
227pub use i_slint_core::graphics::{BorrowedOpenGLTextureBuilder, BorrowedOpenGLTextureOrigin};
228pub use i_slint_core::input::{Keys, KeysParseError};
229#[doc(hidden)]
230#[deprecated(note = "Use slint::language::StandardListViewItem instead")]
231pub use i_slint_core::items::StandardListViewItem;
232#[doc(hidden)]
233#[deprecated(note = "Use slint::language::TableColumn instead")]
234pub use i_slint_core::items::TableColumn;
235pub use i_slint_core::model::{
236 FilterModel, MapModel, Model, ModelError, ModelExt, ModelNotify, ModelPeer, ModelRc,
237 ModelTracker, ReverseModel, SortModel, VecModel,
238};
239pub use i_slint_core::styled_text::StyledText;
240#[cfg(feature = "std")]
241pub use i_slint_core::styled_text::StyledTextFromMarkdownError;
242pub use i_slint_core::timers::{Timer, TimerMode};
243pub use i_slint_core::translations::{SelectBundledTranslationError, select_bundled_translation};
244
245pub mod private_unstable_api;
246
247/// Enters the main event loop. This is necessary in order to receive
248/// events from the windowing system for rendering to the screen
249/// and reacting to user input.
250///
251/// This function will run until the last window is closed and the last
252/// visible system tray icon is hidden, or until [`quit_event_loop()`] is
253/// called. A visible `SystemTrayIcon` keeps the loop alive on its own, so a
254/// tray-only program can use this variant directly.
255///
256/// See also [`run_event_loop_until_quit()`] to keep the loop running even
257/// when nothing visible is left.
258pub fn run_event_loop() -> Result<(), PlatformError> {
259 i_slint_backend_selector::with_platform(|b| b.run_event_loop())
260}
261
262/// Similar to [`run_event_loop()`], but this function continues to run even
263/// when no windows or system tray icons are visible, until
264/// [`quit_event_loop()`] is called.
265///
266/// Use this for daemon-style programs that wait on callbacks without any
267/// visible UI. A program with at least one visible window or `SystemTrayIcon`
268/// can use [`run_event_loop()`] instead, since either keeps the loop alive.
269pub fn run_event_loop_until_quit() -> Result<(), PlatformError> {
270 i_slint_backend_selector::with_platform(|b| {
271 #[allow(deprecated)]
272 b.set_event_loop_quit_on_last_window_closed(false);
273 b.run_event_loop()
274 })
275}
276
277/// Spawns a [`Future`] to execute in the Slint event loop.
278///
279/// This function is intended to be invoked only from the main Slint thread that runs the event loop.
280///
281/// For spawning a `Send` future from a different thread, this function should be called from a closure
282/// passed to [`invoke_from_event_loop()`].
283///
284/// This function is typically called from a UI callback.
285///
286/// # Example
287///
288/// ```rust,no_run
289/// slint::spawn_local(async move {
290/// // your async code goes here
291/// }).unwrap();
292/// ```
293///
294/// # Compatibility with Tokio and other runtimes
295///
296/// The runtime used to execute the future on the main thread is platform-dependent,
297/// for instance, it could be the winit event loop. Therefore, futures that assume a specific runtime
298/// may not work. This may be an issue if you call `.await` on a future created by another
299/// runtime, or pass the future directly to `spawn_local`.
300///
301/// Futures from the [smol](https://docs.rs/smol/latest/smol/) runtime always hand off their work to
302/// separate I/O threads that run in parallel to the Slint event loop.
303///
304/// The [Tokio](https://docs.rs/tokio/latest/tokio/index.html) runtime is subject to the following constraints:
305///
306/// * Tokio futures require entering the context of a global Tokio runtime.
307/// * Tokio futures aren't guaranteed to hand off their work to separate threads and may therefore not complete, because
308/// the Slint runtime can't drive the Tokio runtime.
309/// * Tokio futures require regular yielding to the Tokio runtime for fairness, a constraint that also can't be met by Slint.
310/// * Tokio's [current-thread schedule](https://docs.rs/tokio/latest/tokio/runtime/index.html#current-thread-scheduler)
311/// cannot be used in Slint main thread, because Slint cannot yield to it.
312///
313/// To address these constraints, use [async_compat](https://docs.rs/async-compat/latest/async_compat/index.html)'s [Compat::new()](https://docs.rs/async-compat/latest/async_compat/struct.Compat.html#method.new)
314/// to implicitly allocate a shared, multi-threaded Tokio runtime that will be used for Tokio futures.
315///
316/// The following little example demonstrates the use of Tokio's [`TcpStream`](https://docs.rs/tokio/latest/tokio/net/struct.TcpStream.html) to
317/// read from a network socket. The entire future passed to `spawn_local()` is wrapped in `Compat::new()` to make it run:
318///
319/// ```rust
320/// // A dummy TCP server that once reports "Hello World"
321/// fn main() {
322/// # i_slint_backend_testing::init_integration_test_with_mock_time();
323/// use std::io::Write;
324///
325/// let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
326/// let local_addr = listener.local_addr().unwrap();
327/// let server = std::thread::spawn(move || {
328/// let mut stream = listener.incoming().next().unwrap().unwrap();
329/// stream.write("Hello World".as_bytes()).unwrap();
330/// });
331///
332/// let slint_future = async move {
333/// use tokio::io::AsyncReadExt;
334/// let mut stream = tokio::net::TcpStream::connect(local_addr).await.unwrap();
335/// let mut data = Vec::new();
336/// stream.read_to_end(&mut data).await.unwrap();
337/// assert_eq!(data, "Hello World".as_bytes());
338/// slint::quit_event_loop().unwrap();
339/// };
340///
341/// // Wrap the future that includes Tokio futures in async_compat's `Compat` to ensure
342/// // presence of a Tokio run-time.
343/// slint::spawn_local(async_compat::Compat::new(slint_future)).unwrap();
344///
345/// slint::run_event_loop_until_quit().unwrap();
346///
347/// server.join().unwrap();
348/// }
349/// ```
350///
351/// The use of `#[tokio::main]` is **not recommended**. If it's necessary to use though, wrap the call to enter the Slint
352/// event loop in a call to [`tokio::task::block_in_place`](https://docs.rs/tokio/latest/tokio/task/fn.block_in_place.html):
353///
354/// ```rust, no_run
355/// // Wrap the call to run_event_loop to ensure presence of a Tokio run-time.
356/// tokio::task::block_in_place(slint::run_event_loop).unwrap();
357/// ```
358#[cfg(target_has_atomic = "ptr")]
359pub fn spawn_local<F: core::future::Future + 'static>(
360 fut: F,
361) -> Result<JoinHandle<F::Output>, EventLoopError> {
362 i_slint_backend_selector::with_global_context(|ctx| ctx.spawn_local(fut))
363 .map_err(|_| EventLoopError::NoEventLoopProvider)?
364}
365
366#[i_slint_core_macros::slint_doc]
367/// Include the code generated with the slint-build crate from the build script. After calling `slint_build::compile`
368/// in your `build.rs` build script, the use of this macro includes the generated Rust code and makes the exported types
369/// available for you to instantiate.
370///
371/// Check the documentation of the [`slint-build`](slint:rust:slint_build) crate for more information.
372#[macro_export]
373macro_rules! include_modules {
374 () => {
375 include!(env!("SLINT_INCLUDE_GENERATED"));
376 };
377}
378
379#[i_slint_core_macros::slint_doc]
380/// Initialize translations when using the `gettext` feature.
381///
382/// Call this at the start of your main function, before starting other threads,
383/// with the path where translations are located.
384/// This macro internally calls the [`bindtextdomain`](https://man7.org/linux/man-pages/man3/bindtextdomain.3.html) function from gettext.
385/// It also sets the C library's `LC_MESSAGES` locale from the environment,
386/// which isn't thread-safe.
387///
388/// The first argument of the macro must be an expression that implements `Into<std::path::PathBuf>`.
389/// It specifies the directory in which gettext should search for translations.
390///
391/// Translations are expected to be found at `<dirname>/<locale>/LC_MESSAGES/<crate>.mo`,
392/// where `dirname` is the directory passed as an argument to this macro,
393/// `locale` is a locale name (e.g., `en`, `en_GB`, `fr`), and
394/// `crate` is the package name obtained from the `CARGO_PKG_NAME` environment variable.
395///
396/// See also the [Translation documentation](slint:translations).
397///
398/// ### Example
399/// ```rust
400/// fn main() {
401/// slint::init_translations!(concat!(env!("CARGO_MANIFEST_DIR"), "/translations/"));
402/// // ...
403/// }
404/// ```
405///
406/// For example, assuming this is in a crate called `example` and the default locale
407/// is configured to be French, it will load translations at runtime from
408/// `/path/to/example/translations/fr/LC_MESSAGES/example.mo`.
409///
410/// Another example of loading translations relative to the executable:
411/// ```rust
412/// slint::init_translations!(std::env::current_exe().unwrap().parent().unwrap().join("translations"));
413/// ```
414#[cfg(feature = "gettext")]
415#[macro_export]
416macro_rules! init_translations {
417 ($dirname:expr) => {
418 $crate::private_unstable_api::init_translations(env!("CARGO_PKG_NAME"), $dirname);
419 };
420}
421
422/// Forces all the strings that are translated with `@tr(...)` to be re-evaluated.
423/// Call this function after changing the language at run-time and when translating
424/// with either gettext or a custom translator. For bundled translations, there is no need
425/// to call this function.
426pub fn update_all_translations() {
427 i_slint_core::translations::mark_all_translations_dirty();
428}
429
430/// This module contains items that you need to use or implement if you want use Slint in an environment without
431/// one of the supplied platform backends such as qt or winit.
432///
433/// The primary interface is the [`platform::Platform`] trait. Pass your implementation of it to Slint by calling
434/// [`platform::set_platform()`] early on in your application, before creating any Slint components.
435///
436/// The [Slint on Microcontrollers](crate::docs::mcu) documentation has additional examples.
437pub mod platform {
438 pub use i_slint_core::platform::*;
439
440 /// Set the Slint platform abstraction.
441 ///
442 /// If the platform abstraction was already set this will return `Err`.
443 pub fn set_platform(
444 platform: alloc::boxed::Box<dyn Platform + 'static>,
445 ) -> Result<(), SetPlatformError> {
446 i_slint_core::platform::set_platform(platform)?;
447 // Custom platforms bypass the backend selector, so start the embedded testing/MCP
448 // backends here to match applications that go through it.
449 #[cfg(any(feature = "mcp", feature = "system-testing"))]
450 i_slint_backend_selector::init_testing_backends();
451 Ok(())
452 }
453
454 /// This module contains the [`femtovg_renderer::FemtoVGRenderer`] and related types.
455 ///
456 /// It is only enabled when the `renderer-femtovg` Slint feature is enabled.
457 #[cfg(all(
458 not(target_os = "android"),
459 any(feature = "renderer-femtovg", feature = "renderer-femtovg-wgpu")
460 ))]
461 pub mod femtovg_renderer {
462 #[cfg(feature = "renderer-femtovg")]
463 pub use i_slint_renderer_femtovg::FemtoVGOpenGLRenderer as FemtoVGRenderer;
464 /// Use this type to render to a WGPU texture using FemtoVG.
465 #[cfg(feature = "unstable-wgpu-30")]
466 pub use i_slint_renderer_femtovg::FemtoVGWGPURenderer;
467 #[cfg(feature = "renderer-femtovg")]
468 pub use i_slint_renderer_femtovg::opengl::OpenGLInterface;
469 }
470
471 /// This module contains the Skia WGPU renderers and related types.
472 ///
473 /// It is only enabled when the `renderer-skia` Slint feature is enabled.
474 #[cfg(all(
475 any(feature = "unstable-wgpu-29", feature = "unstable-wgpu-30"),
476 any(
477 feature = "renderer-skia",
478 feature = "renderer-skia-opengl",
479 feature = "renderer-skia-vulkan"
480 )
481 ))]
482 pub mod skia_renderer {
483 #[cfg(feature = "unstable-wgpu-29")]
484 pub use i_slint_renderer_skia::SkiaWGPU29Renderer;
485 #[cfg(feature = "unstable-wgpu-30")]
486 pub use i_slint_renderer_skia::SkiaWGPU30Renderer;
487 #[allow(deprecated)]
488 pub use i_slint_renderer_skia::SkiaWGPURenderer;
489 }
490
491 #[cfg(feature = "renderer-software")]
492 /// This module contains the [`software_renderer::SoftwareRenderer`] and related types.
493 ///
494 /// It is only enabled when the `renderer-software` Slint feature is enabled.
495 pub mod software_renderer {
496 pub use i_slint_renderer_software::api::*;
497 }
498}
499
500#[i_slint_core_macros::slint_doc]
501/// This module contains some of the enums and structs from the Slint language.
502///
503/// See also the list of [global structs and enums](slint:struct)
504pub mod language {
505 macro_rules! export_builtin_structs {
506 ($(
507 $(#[$attr:meta])*
508 $vis:vis struct $Name:ident {
509 $( $(#[$field_attr:meta])* $field:ident : $field_type:ty $(= $field_default:expr)?, )*
510 }
511 )*) => {
512 $( #[allow(unused_imports)] $vis use i_slint_core::items::$Name; )*
513 };
514 }
515
516 i_slint_common::for_each_builtin_structs!(export_builtin_structs);
517
518 // `$vis use …;` propagates the enum's declared visibility: `pub enum Foo` becomes a
519 // `pub use`, plain `enum Foo` becomes a private `use` (in-scope only, suppressed by
520 // `#[allow(unused_imports)]`).
521 macro_rules! export_builtin_enums {
522 ($(
523 $(#[$attr:meta])*
524 $vis:vis enum $Name:ident { $($_body:tt)* }
525 )*) => {
526 $( #[allow(unused_imports)] $vis use i_slint_core::items::$Name; )*
527 };
528 }
529
530 i_slint_common::for_each_enums!(export_builtin_enums);
531}
532
533#[cfg(any(
534 doc,
535 all(
536 target_os = "android",
537 any(feature = "backend-android-activity-05", feature = "backend-android-activity-06")
538 )
539))]
540pub mod android;
541
542/// Helper type that helps checking that the generated code is generated for the right version
543#[doc(hidden)]
544#[allow(non_camel_case_types)]
545pub struct VersionCheck_1_19_0;
546
547#[cfg(doctest)]
548mod compile_fail_tests;
549
550#[cfg(doc)]
551pub mod docs;
552
553#[cfg(feature = "unstable-wgpu-29")]
554pub mod wgpu_29 {
555 //! WGPU 29.x specific types and re-exports.
556 //!
557 //! *Note*: This module is behind a feature flag and may be removed or changed in future minor releases,
558 //! as new major WGPU releases become available.
559 //!
560 //! This module exists for interoperability with ecosystems that are still on WGPU 29.x, such as bevy 0.19.
561 //!
562 //! See the [`wgpu_30`](crate::wgpu_30) module documentation for usage; the only difference is the
563 //! WGPU major version (29 vs 30) and the corresponding feature/selector/API names (`unstable-wgpu-29`,
564 //! [`slint::BackendSelector::require_wgpu_29()`](i_slint_backend_selector::api::BackendSelector::require_wgpu_29()),
565 //! [`slint::GraphicsAPI::WGPU29`](i_slint_core::api::GraphicsAPI::WGPU29)).
566 //!
567 //! When rendering offscreen with the Skia renderer, use `slint::platform::skia_renderer::SkiaWGPU29Renderer`
568 //! to select the wgpu 29 API explicitly, even if `unstable-wgpu-30` also ends up enabled through
569 //! Cargo feature unification.
570 pub use i_slint_core::graphics::wgpu_29::api::*;
571}
572
573#[cfg(feature = "unstable-wgpu-30")]
574pub mod wgpu_30 {
575 //! WGPU 30.x specific types and re-exports.
576 //!
577 //! *Note*: This module is behind a feature flag and may be removed or changed in future minor releases,
578 //! as new major WGPU releases become available.
579 //!
580 //! Use the types in this module in combination with other APIs to integrate external, WGPU-based rendering engines
581 //! into a UI with Slint.
582 //!
583 //! First, ensure that WGPU is used for rendering with Slint by using [`slint::BackendSelector::require_wgpu_30()`](i_slint_backend_selector::api::BackendSelector::require_wgpu_30()).
584 //! This function accepts a pre-configured WGPU setup or configuration hints such as required features or memory limits.
585 //!
586 //! For rendering, it's crucial that you're using the same [`wgpu::Device`] and [`wgpu::Queue`] for allocating textures or submitting commands as Slint. Obtain the same queue
587 //! by either using [`WGPUConfiguration::Manual`] to make Slint use an existing WGPU configuration, or use [`slint::Window::set_rendering_notifier()`](i_slint_core::api::Window::set_rendering_notifier())
588 //! to let Slint invoke a callback that provides access device, queue, etc. in [`slint::GraphicsAPI::WGPU30`](i_slint_core::api::GraphicsAPI::WGPU30).
589 //!
590 //! To integrate rendering content into a scene shared with a Slint UI, use either [`slint::Window::set_rendering_notifier()`](i_slint_core::api::Window::set_rendering_notifier()) to render an underlay
591 //! or overlay, or integrate externally produced [`wgpu::Texture`]s using [`slint::Image::try_from<wgpu::Texture>()`](i_slint_core::graphics::Image::try_from).
592 //!
593 //! The following example allocates a [`wgpu::Texture`] and, for the sake of simplicity in this documentation, fills with green as color, and then proceeds to set it as a `slint::Image` in the scene.
594 //!
595 //! `Cargo.toml`:
596 //! ```toml
597 //! slint = { version = "~1.19", features = ["unstable-wgpu-30"] }
598 //! ```
599 //!
600 //! `main.rs`:
601 //!```rust,no_run
602 //!
603 //! use slint::wgpu_30::wgpu;
604 //! use wgpu::util::DeviceExt;
605 //!
606 //!slint::slint!{
607 //! #[slint_edition = "1.19"]
608 //! export component HelloWorld inherits Window {
609 //! preferred-width: 320px;
610 //! preferred-height: 300px;
611 //! in-out property <image> app-texture;
612 //! VerticalLayout {
613 //! Text {
614 //! text: "hello world";
615 //! color: green;
616 //! }
617 //! Image { source: root.app-texture; }
618 //! }
619 //! }
620 //!}
621 //!fn main() -> Result<(), Box<dyn std::error::Error>> {
622 //! slint::BackendSelector::new()
623 //! .require_wgpu_30(slint::wgpu_30::WGPUConfiguration::default())
624 //! .select()?;
625 //! let app = HelloWorld::new()?;
626 //!
627 //! let app_weak = app.as_weak();
628 //!
629 //! app.window().set_rendering_notifier(move |state, graphics_api| {
630 //! let (Some(app), slint::RenderingState::RenderingSetup, slint::GraphicsAPI::WGPU30{ device, queue, ..}) = (app_weak.upgrade(), state, graphics_api) else {
631 //! return;
632 //! };
633 //!
634 //! let mut pixels = slint::SharedPixelBuffer::<slint::Rgba8Pixel>::new(320, 200);
635 //! pixels.make_mut_slice().fill(slint::Rgba8Pixel {
636 //! r: 0,
637 //! g: 255,
638 //! b :0,
639 //! a: 255,
640 //! });
641 //!
642 //! let texture = device.create_texture_with_data(queue,
643 //! &wgpu::TextureDescriptor {
644 //! label: None,
645 //! size: wgpu::Extent3d { width: 320, height: 200, depth_or_array_layers: 1 },
646 //! mip_level_count: 1,
647 //! sample_count: 1,
648 //! dimension: wgpu::TextureDimension::D2,
649 //! format: wgpu::TextureFormat::Rgba8Unorm,
650 //! usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
651 //! view_formats: &[],
652 //! },
653 //! wgpu::util::TextureDataOrder::default(),
654 //! pixels.as_bytes(),
655 //! );
656 //!
657 //! let imported_image = slint::Image::try_from(texture).unwrap();
658 //!
659 //! app.set_app_texture(imported_image);
660 //! })?;
661 //!
662 //! app.run()?;
663 //!
664 //! Ok(())
665 //!}
666 //!```
667 //!
668 pub use i_slint_core::graphics::wgpu_30::api::*;
669}
670
671#[cfg(feature = "unstable-winit-030")]
672pub mod winit_030 {
673 //! Winit 0.30.x specific types and re-exports.
674 //!
675 //! *Note*: This module is behind a feature flag and may be removed or changed in future minor releases,
676 //! as new major Winit releases become available.
677 //!
678 //! Use the types and traits in this module in combination with other APIs to access additional window properties,
679 //! create custom windows, or hook into the winit event loop.
680 //!
681 //! For example, use the [`WinitWindowAccessor`] to obtain access to the underling [`winit::window::Window`]:
682 //!
683 //! `Cargo.toml`:
684 //! ```toml
685 //! slint = { version = "~1.19", features = ["unstable-winit-030"] }
686 //! ```
687 //!
688 //! `main.rs`:
689 //! ```rust,no_run
690 //! // Bring winit and accessor traits into scope.
691 //! use slint::winit_030::{WinitWindowAccessor, winit};
692 //!
693 //! slint::slint!{
694 //! #[slint_edition = "1.19"]
695 //! import { VerticalBox, Button } from "std-widgets.slint";
696 //! export component HelloWorld inherits Window {
697 //! callback clicked;
698 //! VerticalBox {
699 //! Text {
700 //! text: "hello world";
701 //! color: green;
702 //! }
703 //! Button {
704 //! text: "Click me";
705 //! clicked => { root.clicked(); }
706 //! }
707 //! }
708 //! }
709 //! }
710 //! fn main() -> Result<(), Box<dyn std::error::Error>> {
711 //! // Make sure the winit backed is selected:
712 //! slint::BackendSelector::new()
713 //! .backend_name("winit".into())
714 //! .select()?;
715 //!
716 //! let app = HelloWorld::new()?;
717 //! let app_weak = app.as_weak();
718 //! app.on_clicked(move || {
719 //! // access the winit window
720 //! let app = app_weak.unwrap();
721 //! app.window().with_winit_window(|winit_window: &winit::window::Window| {
722 //! eprintln!("window id = {:#?}", winit_window.id());
723 //! });
724 //! });
725 //! app.run()?;
726 //! Ok(())
727 //! }
728 //! ```
729 //! See also [`BackendSelector::with_winit_event_loop_builder()`](crate::BackendSelector::with_winit_event_loop_builder())
730 //! and [`BackendSelector::with_winit_window_attributes_hook()`](crate::BackendSelector::with_winit_window_attributes_hook()).
731
732 pub use i_slint_backend_winit::{
733 CustomApplicationHandler, EventLoopBuilder, EventResult, SlintEvent, WinitWindowAccessor,
734 invoke_from_active_event_loop, winit,
735 };
736
737 #[deprecated(note = "Renamed to `EventResult`")]
738 /// Deprecated alias to [`EventResult`]
739 pub type WinitWindowEventResult = EventResult;
740}
741
742#[cfg(feature = "unstable-fontique-012")]
743pub mod fontique_012 {
744 //! Fontique 0.12 specific types and re-exports.
745 //!
746 //! *Note*: This module is behind a feature flag and may be removed or changed in future minor releases,
747 //! as new major Fontique releases become available.
748 //!
749 //! Use the types, functions, and re-exports in this module to register custom fonts at run-time for use
750 //! by Slint's renderers.
751
752 pub use i_slint_common::sharedfontique::fontique;
753
754 #[i_slint_core_macros::slint_doc]
755 /// Returns a clone of the [`fontique::Collection`] used for text rendering in the current thread's context.
756 /// It uses shared storage, so Slint sees the fonts you register and the fallbacks you configure.
757 ///
758 /// Note: The recommended way of including custom fonts is at compile time of Slint files. For details,
759 /// see also the [Font Handling](slint:FontHandling) documentation.
760 ///
761 /// The example below sketches out the steps for registering a downloaded font to add additional glyph
762 /// coverage for Japanese text:
763 ///
764 /// `Cargo.toml`:
765 /// ```toml
766 /// slint = { version = "~1.19", features = ["unstable-fontique-012"] }
767 /// ```
768 ///
769 /// `main.rs`:
770 /// ```rust,no_run
771 /// use slint::fontique_012::fontique;
772 ///
773 /// fn main() {
774 /// // ...
775 /// let downloaded_font: Vec<u8> = todo!("Download https://somewebsite.com/font.ttf");
776 /// let blob = fontique::Blob::new(std::sync::Arc::new(downloaded_font));
777 /// let mut collection = slint::fontique_012::shared_collection();
778 /// let fonts = collection.register_fonts(blob, None);
779 /// collection
780 /// .append_fallbacks(fontique::FallbackKey::new(fontique::Script::from_bytes(*b"Hira"), None), fonts.iter().map(|x| x.0));
781 /// collection
782 /// .append_fallbacks(fontique::FallbackKey::new(fontique::Script::from_bytes(*b"Kana"), None), fonts.iter().map(|x| x.0));
783 /// collection
784 /// .append_fallbacks(fontique::FallbackKey::new(fontique::Script::from_bytes(*b"Hani"), None), fonts.iter().map(|x| x.0));
785 /// // ...
786 /// }
787 /// ```
788 pub fn shared_collection() -> fontique::Collection {
789 i_slint_backend_selector::with_global_context(|ctx| {
790 ctx.font_context().borrow().collection.clone()
791 })
792 .unwrap()
793 }
794
795 /// Sets the font collection used for text rendering in the current thread's context.
796 /// Slint uses your collection as is and adds the fonts that `.slint` files import.
797 /// To skip system font discovery, create the collection with `system_fonts: false`.
798 ///
799 /// Call this before Slint initializes the platform, for example by creating a component
800 /// or by calling [`set_platform()`](crate::platform::set_platform).
801 /// If the platform is already initialized, this returns an error.
802 ///
803 /// To register fonts after this call, use the collection returned by [`shared_collection()`].
804 ///
805 /// For example, to make a font bundled with your application the default font:
806 ///
807 /// ```rust,no_run
808 /// use slint::fontique_012::fontique;
809 ///
810 /// let mut collection = fontique::Collection::new(fontique::CollectionOptions {
811 /// system_fonts: false,
812 /// ..Default::default()
813 /// });
814 /// let font_data = std::fs::read("fonts/MyFont.ttf")?;
815 /// let fonts = collection.register_fonts(fontique::Blob::new(std::sync::Arc::new(font_data)), None);
816 /// // Text without a `font-family` uses the generic sans-serif family.
817 /// collection.set_generic_families(
818 /// fontique::GenericFamily::SansSerif,
819 /// fonts.iter().map(|(family_id, _)| *family_id),
820 /// );
821 /// slint::fontique_012::set_shared_collection(collection)?;
822 /// # Ok::<(), Box<dyn std::error::Error>>(())
823 /// ```
824 pub fn set_shared_collection(
825 collection: fontique::Collection,
826 ) -> Result<(), crate::PlatformError> {
827 i_slint_core::font_collection::supply(collection)
828 }
829}