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