### Example Usage Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/rwh/struct.UiKitWindowHandle.html Demonstrates how to get and use the `UiKitWindowHandle` from a `WindowHandle`. ```APIDOC ## §Example Getting the view from a `WindowHandle`. ```rust #![cfg(any(target_os = "ios", target_os = "tvos", target_os = "watchos", target_os = "xros"))] use objc2_foundation::is_main_thread; use objc2::rc::Id; use objc2_ui_kit::UIView; use raw_window_handle::{WindowHandle, RawWindowHandle}; let handle: WindowHandle<'_>; // Get the window handle from somewhere else match handle.as_raw() { RawWindowHandle::UIKit(handle) => { assert!(is_main_thread(), "can only access UIKit handles on the main thread"); let ui_view = handle.ui_view.as_ptr(); // SAFETY: The pointer came from `WindowHandle`, which ensures // that the `UiKitWindowHandle` contains a valid pointer to an // `UIView`. // Unwrap is fine, since the pointer came from `NonNull`. let ui_view: Id = unsafe { Id::retain(ui_view.cast()) }.unwrap(); // Do something with the UIView here. } handle => unreachable!("unknown handle {handle:?} for platform"), } ``` ``` -------------------------------- ### Example Usage Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/rwh/struct.AppKitWindowHandle.html Demonstrates how to get the NSView from a WindowHandle on macOS. ```APIDOC ## §Example Getting the view from a `WindowHandle`. ```rust #![cfg(target_os = "macos")] use objc2_app_kit::NSView; use objc2_foundation::is_main_thread; use objc2::rc::Id; use raw_window_handle::{WindowHandle, RawWindowHandle}; let handle: WindowHandle<'_>; // Get the window handle from somewhere else match handle.as_raw() { RawWindowHandle::AppKit(handle) => { assert!(is_main_thread(), "can only access AppKit handles on the main thread"); let ns_view = handle.ns_view.as_ptr(); // SAFETY: The pointer came from `WindowHandle`, which ensures // that the `AppKitWindowHandle` contains a valid pointer to an // `NSView`. // Unwrap is fine, since the pointer came from `NonNull`. let ns_view: Id = unsafe { Id::retain(ns_view.cast()) }.unwrap(); // Do something with the NSView here, like getting the `NSWindow` let ns_window = ns_view.window().expect("view was not installed in a window"); } handle => unreachable!("unknown handle {handle:?} for platform"), } ``` ``` -------------------------------- ### Example Usage Source: https://docs.slint.dev/latest/docs/rust/slint/winit_030/trait.WinitWindowAccessor.html Demonstrates how to use the WinitWindowAccessor trait to get the winit window and print its ID. ```APIDOC ```rust // Bring winit and accessor traits into scope. use slint::winit_030::{WinitWindowAccessor, winit}; slint::slint!{ import { VerticalBox, Button } from "std-widgets.slint"; export component HelloWorld inherits Window { callback clicked; VerticalBox { Text { text: "hello world"; color: green; } Button { text: "Click me"; clicked => { root.clicked(); } } } } } fn main() -> Result<(), Box> { // Make sure the winit backed is selected: slint::BackendSelector::new() .backend_name("winit".into()) .select()?; let app = HelloWorld::new()?; let app_weak = app.as_weak(); slint::spawn_local(async move { let app = app_weak.unwrap(); let winit_window = app.window().winit_window().await.unwrap(); eprintln!("window id = {:#?}", winit_window.id()); }).unwrap(); app.run()?; Ok(()) } ``` ``` -------------------------------- ### Example LineBufferProvider Implementation Source: https://docs.slint.dev/latest/docs/rust/slint/platform/software_renderer/struct.SoftwareRenderer.html An example implementation of `LineBufferProvider` for rendering into a plain frame buffer using `render_by_line`. This demonstrates how to provide a buffer for each line and process it. ```rust struct FrameBuffer<'a>{ frame_buffer: &'a mut [Rgb565Pixel], stride: usize } impl<'a> LineBufferProvider for FrameBuffer<'a> { type TargetPixel = Rgb565Pixel; fn process_line( &mut self, line: usize, range: core::ops::Range, render_fn: impl FnOnce(&mut [Self::TargetPixel]), ) { let line_begin = line * self.stride; render_fn(&mut self.frame_buffer[line_begin..][range]); // The line has been rendered and there could be code here to // send the pixel to the display } } renderer.render_by_line(FrameBuffer{ frame_buffer: the_frame_buffer, stride: display_width }); ``` -------------------------------- ### Color Examples Source: https://docs.slint.dev/latest/docs/rust/slint_interpreter/struct.Color.html Examples demonstrating the usage of the Color struct, including mixing colors and creating colors from RGB values. ```APIDOC ## Examples Mix red with black half-and-half: ```rust let red = Color::from_rgb_f32(1.0, 0.0, 0.0); let black = Color::from_rgb_f32(0.0, 0.0, 0.0); assert_eq!(red.mix(&black, 0.5), Color::from_rgb_f32(0.5, 0.0, 0.0)); ``` Mix Purple with OrangeRed, with `75%` purpe and `25%` orange red ratio: ```rust let purple = Color::from_rgb_u8(128, 0, 128); let orange_red = Color::from_rgb_u8(255, 69, 0); assert_eq!(purple.mix(&orange_red, 0.75), Color::from_rgb_f32(0.6264706, 0.06764706, 0.37647063)); ``` ``` -------------------------------- ### Instance::new Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgc/instance/struct.Instance Creates a new Instance with the given name, descriptor, and telemetry options. This is the primary way to initialize wgpu. ```APIDOC ## Instance::new ### Description Creates a new Instance with the given name, descriptor, and telemetry options. ### Method `pub fn new( name: &str, instance_desc: &InstanceDescriptor, telemetry: Option, ) -> Instance` ### Parameters - `name`: `&str` - A name for the instance. - `instance_desc`: `&InstanceDescriptor` - The descriptor for the instance. - `telemetry`: `Option` - Optional telemetry settings. ### Available On `crate feature`wgpu-28` only. ``` -------------------------------- ### Instance::new Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/struct.Instance.html Creates a new wgpu instance with the given descriptor. This is the first step in using wgpu. ```APIDOC ## Instance::new ### Description Creates a new instance of wgpu using the given options and enabled backends. ### Method `pub fn new(desc: &InstanceDescriptor) -> Instance` ### Parameters * `desc` - `&InstanceDescriptor` - The descriptor for the instance configuration. ### Panics * If no backend feature for the active target platform is enabled, this method will panic; see `Instance::enabled_backend_features()`. ``` -------------------------------- ### Project Setup with Template Repository Source: https://docs.slint.dev/latest/docs/rust/slint/index.html Instructions for setting up a new Rust project using the Slint template repository, including downloading, extracting, and renaming the project. ```bash mv slint-rust-template-main my-project cd my-project ``` -------------------------------- ### Get Empty Flags Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/type.AccelerationStructureGeometryFlags.html Obtain a flags value with all bits unset. Use this as a starting point when building custom flag combinations. ```rust pub const fn empty() -> AccelerationStructureGeometryFlags ``` -------------------------------- ### Integrate winit 0.30.x with Slint Application Source: https://docs.slint.dev/latest/docs/rust/slint/winit_030 This example demonstrates how to set up a Slint application using the winit backend and access the underlying winit window. It shows how to import necessary traits and use `WinitWindowAccessor` to retrieve window information. ```rust // Bring winit and accessor traits into scope. use slint::winit_030::{WinitWindowAccessor, winit}; slint::slint!{ import { VerticalBox, Button } from "std-widgets.slint"; export component HelloWorld inherits Window { callback clicked; VerticalBox { Text { text: "hello world"; color: green; } Button { text: "Click me"; clicked => { root.clicked(); } } } } } fn main() -> Result<(), Box> { // Make sure the winit backed is selected: slint::BackendSelector::new () .backend_name ("winit".into ()) .select ()?; let app = HelloWorld::new ()?; let app_weak = app.as_weak (); app.on_clicked (move || { // access the winit window let app = app_weak.unwrap (); app.window().with_winit_window(|winit_window: &winit::window::Window| { eprintln!("window id = {:#?}", winit_window.id ()); }); }); app.run ()?; Ok () } ``` -------------------------------- ### Create Empty FormatAspects Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/hal/struct.FormatAspects.html Use `empty()` to get a `FormatAspects` value with no bits set. This is useful for starting with a clean set of flags. ```rust pub const fn empty() -> FormatAspects ``` -------------------------------- ### Example: Load Image and Get Path Source: https://docs.slint.dev/latest/docs/rust/slint/struct.Image.html Demonstrates loading an image from a file path and then retrieving its path using the `path()` method. Asserts that the retrieved path matches the original path. ```rust let path_buf = Path::new(env!("CARGO_MANIFEST_DIR")) .join("../../demos/printerdemo/ui/images/cat.jpg"); let image = Image::load_from_path(&path_buf).unwrap(); assert_eq!(image.path(), Some(path_buf.as_path())); ``` -------------------------------- ### Iterate Over Characters and Their Byte Positions Source: https://docs.slint.dev/latest/docs/rust/slint_interpreter/struct.SharedString.html Use `char_indices` to get an iterator over the Unicode characters and their starting byte positions within a string slice. This is useful for correctly handling multi-byte UTF-8 characters. ```rust let word = "goodbye"; let count = word.char_indices().count(); assert_eq!(7, count); let mut char_indices = word.char_indices(); assert_eq!(Some((0, 'g')), char_indices.next()); assert_eq!(Some((1, 'o')), char_indices.next()); assert_eq!(Some((2, 'o')), char_indices.next()); assert_eq!(Some((3, 'd')), char_indices.next()); assert_eq!(Some((4, 'b')), char_indices.next()); assert_eq!(Some((5, 'y')), char_indices.next()); assert_eq!(Some((6, 'e')), char_indices.next()); assert_eq!(None, char_indices.next()); ``` ```rust let yes = "y̆es"; let mut char_indices = yes.char_indices(); assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆') assert_eq!(Some((1, '\u{0306}')), char_indices.next()); // note the 3 here - the previous character took up two bytes assert_eq!(Some((3, 'e')), char_indices.next()); assert_eq!(Some((4, 's')), char_indices.next()); assert_eq!(None, char_indices.next()); ``` -------------------------------- ### Create a new wgpu Instance Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/struct.Instance.html Creates a new instance of wgpu with the given options and enabled backends. Panics if no backend feature for the active target platform is enabled. ```rust let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::default()); ``` -------------------------------- ### Basic Slint UI with WGPU Texture Integration Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/index.html This example demonstrates how to set up a Slint window with WGPU rendering, create a green texture, and display it within the UI. It requires the `unstable-wgpu-28` feature. ```rust use slint::wgpu_28::wgpu; use wgpu::util::DeviceExt; slint::slint!{ export component HelloWorld inherits Window { preferred-width: 320px; preferred-height: 300px; in-out property app-texture; VerticalLayout { Text { text: "hello world"; color: green; } Image { source: root.app-texture; } } } } fn main() -> Result<(), Box> { slint::BackendSelector::new() .require_wgpu_28(slint::wgpu_28::WGPUConfiguration::default()) .select()?; let app = HelloWorld::new()?; let app_weak = app.as_weak(); app.window().set_rendering_notifier(move |state, graphics_api| { let (Some(app), slint::RenderingState::RenderingSetup, slint::GraphicsAPI::WGPU28{ device, queue, ..}) = (app_weak.upgrade(), state, graphics_api) else { return; }; let mut pixels = slint::SharedPixelBuffer::::new(320, 200); pixels.make_mut_slice().fill(slint::Rgba8Pixel { r: 0, g: 255, b :0, a: 255, }); let texture = device.create_texture_with_data(queue, &wgpu::TextureDescriptor { label: None, size: wgpu::Extent3d { width: 320, height: 200, depth_or_array_layers: 1 }, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Rgba8Unorm, usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, view_formats: &[], }, wgpu::util::TextureDataOrder::default(), pixels.as_bytes(), ); let imported_image = slint::Image::try_from(texture).unwrap(); app.set_app_texture(imported_image); })?; app.run()?; Ok(()) } ``` -------------------------------- ### Get Element Offset in SharedVector Source: https://docs.slint.dev/latest/docs/rust/slint_interpreter/struct.SharedVector.html Returns the index of an element reference within the slice. Returns `None` if the element reference does not point to the start of an element. This method uses pointer arithmetic and does not compare elements. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### Find String Indices with `match_indices` Source: https://docs.slint.dev/latest/docs/rust/slint_interpreter/struct.SharedString.html Use `match_indices` to find all non-overlapping occurrences of a pattern within a string and get their starting indices. The pattern can be a string slice, a character, or a closure. Overlapping matches are ignored, and only the first occurrence's index is returned. ```rust let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect(); assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]); ``` ```rust let v: Vec<_> = "1abcabc2".match_indices("abc").collect(); assert_eq!(v, [(1, "abc"), (4, "abc")]); ``` ```rust let v: Vec<_> = "ababa".match_indices("aba").collect(); assert_eq!(v, [(0, "aba")]); // only the first `aba` ``` -------------------------------- ### Frontend::new_with_options() Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgc/naga/front/wgsl/struct.Frontend.html Creates a new instance of the Frontend with specified options. This function is available only on the `wgpu-28` crate feature. ```APIDOC ### pub const fn new_with_options(options: Options) -> Frontend Available on **crate feature`wgpu-28`** only. ``` -------------------------------- ### get Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/struct.Tlas.html Get a reference to all instances within the TLAS. ```APIDOC ### pub fn get(&self) -> &[Option] **Available on:** crate feature`wgpu-28` only. Get a reference to all instances. ``` -------------------------------- ### Instance::init_with_callback Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/hal/vulkan/struct.Instance.html Initializes an Instance with a callback for customization. Available on crate feature `wgpu-28` only. Safety requires the callback not to alter unsupported features. ```APIDOC ## pub unsafe fn init_with_callback( desc: &InstanceDescriptor<'_>, callback: Option FnOnce(CreateInstanceCallbackArgs<'arg, 'pnext, '_>) + '_>>, ) -> Result Available on **crate feature`wgpu-28`** only. `Instance::init` but with a callback. If you want to add extensions, add the to the `Vec<'static CStr>` not the create info, otherwise it will be overwritten ##### §Safety: Same as `init` but additionally * Callback must not remove features. * Callback must not change anything to what the instance does not support. ``` -------------------------------- ### initialize_adapter_from_env_or_default Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/util/fn.initialize_adapter_from_env_or_default.html Initializes the adapter obeying the `WGPU_ADAPTER_NAME` environment variable and if it doesn’t exist fall back on a default adapter. Available on crate feature `unstable-wgpu-28` only. ```APIDOC ## initialize_adapter_from_env_or_default ### Description Initializes the adapter obeying the `WGPU_ADAPTER_NAME` environment variable and if it doesn’t exist fall back on a default adapter. ### Available on `crate feature "unstable-wgpu-28"` ### Signature ```rust pub async fn initialize_adapter_from_env_or_default( instance: &Instance, compatible_surface: Option<&Surface<'_>>, ) -> Result ``` ### Parameters * `instance`: A reference to the `Instance` object. * `compatible_surface`: An optional reference to a `Surface` that the adapter should be compatible with. ### Returns A `Result` containing the `Adapter` if successful, or a `RequestAdapterError` if initialization fails. ``` -------------------------------- ### Setup Information Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgc/error/type.ContextErrorSource Retrieves the setup information sent by the X11 server. ```APIDOC ## fn setup ### Description Get the setup information sent by the X11 server. ### Signature `fn setup(&self) -> &Setup` ### Returns - `&Setup`: A reference to the `Setup` information. ``` -------------------------------- ### Example of Keys Formatting on Linux Source: https://docs.slint.dev/latest/docs/rust/slint_interpreter/struct.Keys.html Demonstrates how a Slint `@keys(Meta + Control + A)` shortcut is formatted for Linux using the `Display` trait. ```text Linux : Super+Ctrl+A ``` -------------------------------- ### Getting a Subslice Safely Source: https://docs.slint.dev/latest/docs/rust/slint/struct.SharedString.html Illustrates how to safely get a subslice of a string using the `get` method. This method returns `None` if the indexing would panic, providing a non-panicking alternative to direct indexing. ```rust let s = "Hello"; let sub = s.get(1..4); assert_eq!(sub, Some("ell")); let sub = s.get(1..10); assert_eq!(sub, None); ``` -------------------------------- ### Default Instance Creation Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/struct.Instance.html Creates a new wgpu Instance with default options. Backends are set to `Backends::all()`, and FXC is chosen as the `dx12_shader_compiler`. ```APIDOC ### impl Default for Instance #### fn default() -> Instance Creates a new instance of wgpu with default options. Backends are set to `Backends::all()`, and FXC is chosen as the `dx12_shader_compiler`. ### Panics If no backend feature for the active target platform is enabled, this method will panic, see `Instance::enabled_backend_features()`. ``` -------------------------------- ### Timer::stop Source: https://docs.slint.dev/latest/docs/rust/slint/struct.Timer.html Stops a previously started timer. This method has no effect if the timer has never been started. ```APIDOC ## Timer::stop ### Description Stops the previously started timer. Does nothing if the timer has never been started. ### Signature ```rust pub fn stop(&self) ``` ``` -------------------------------- ### Install cargo-apk Source: https://docs.slint.dev/latest/docs/rust/slint/android Install the `cargo-apk` tool, which simplifies building, signing, and deploying Rust-based Android applications. ```bash cargo install cargo-apk ``` -------------------------------- ### Example of Keys Formatting on Windows Source: https://docs.slint.dev/latest/docs/rust/slint_interpreter/struct.Keys.html Demonstrates how a Slint `@keys(Meta + Control + A)` shortcut is formatted for Windows using the `Display` trait. ```text Windows : Win+Ctrl+A ``` -------------------------------- ### Timer::start Source: https://docs.slint.dev/latest/docs/rust/slint/struct.Timer.html Starts a timer that repeatedly triggers a callback after a specified interval. The timer will restart if already started. ```APIDOC ## Timer::start ### Description Starts the timer with the given mode and interval, in order for the callback to called when the timer fires. If the timer has been started previously, then it will be restarted, no matter if it has already been fired or not. ### Arguments * `mode`: The timer mode to apply, i.e. whether to repeatedly fire the timer or just once. * `interval`: The duration from now until when the timer should fire the first time, and subsequently for repeated `Repeated` timers. * `callback`: The function to call when the time has been reached or exceeded. ### Signature ```rust pub fn start(&self, mode: TimerMode, interval: Duration, callback: impl FnMut() + 'static) ``` ``` -------------------------------- ### Surface::configure Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/struct.Surface.html Initializes Surface for presentation. If the surface is already configured, this will wait for the GPU to come idle before recreating the swapchain to prevent race conditions. ```APIDOC ## Surface::configure ### Description Initializes `Surface` for presentation. If the surface is already configured, this will wait for the GPU to come idle before recreating the swapchain to prevent race conditions. ### Method `configure(&self, device: &Device, config: &SurfaceConfiguration>)` ### Parameters * `device` (&Device): The device to use for configuration. * `config` (&SurfaceConfiguration>): The configuration for the surface. ### Validation Errors * Submissions that happen _during_ the configure may cause the internal wait-for-idle to fail, raising a validation error. ### Panics * A old `SurfaceTexture` is still alive referencing an old surface. * Texture format requested is unsupported on the surface. * `config.width` or `config.height` is zero. ``` -------------------------------- ### InstanceDescriptor Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/hal/struct.InstanceDescriptor.html Configuration for creating a wgpu instance. ```APIDOC struct InstanceDescriptor { pub backends: Backends, pub extensions: InstanceExtensions, } ``` -------------------------------- ### mip_level_size Example Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgc/resource/type.TextureDescriptor.html Example demonstrating the usage of the `mip_level_size` method to calculate texture extents at different mip levels. ```APIDOC ```rust let desc = TextureDescriptor { label: None, size: wgpu::Extent3d { width: 100, height: 60, depth_or_array_layers: 1 }, mip_level_count: 7, sample_count: 1, dimension: wgpu::TextureDimension::D3, format: wgpu::TextureFormat::Rgba8Sint, usage: wgpu::TextureUsages::empty(), view_formats: &[], }; assert_eq!(desc.mip_level_size(0), Some(wgpu::Extent3d { width: 100, height: 60, depth_or_array_layers: 1 })); assert_eq!(desc.mip_level_size(1), Some(wgpu::Extent3d { width: 50, height: 30, depth_or_array_layers: 1 })); assert_eq!(desc.mip_level_size(2), Some(wgpu::Extent3d { width: 25, height: 15, depth_or_array_layers: 1 })); assert_eq!(desc.mip_level_size(3), Some(wgpu::Extent3d { width: 12, height: 7, depth_or_array_layers: 1 })); assert_eq!(desc.mip_level_size(4), Some(wgpu::Extent3d { width: 6, height: 3, depth_or_array_layers: 1 })); assert_eq!(desc.mip_level_size(5), Some(wgpu::Extent3d { width: 3, height: 1, depth_or_array_layers: 1 })); assert_eq!(desc.mip_level_size(6), Some(wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 })); assert_eq!(desc.mip_level_size(7), None); ``` ``` -------------------------------- ### SampleComponent Creation Source: https://docs.slint.dev/latest/docs/rust/slint/docs/generated_code/struct.SampleComponent.html Demonstrates how to create a new instance of SampleComponent. ```APIDOC ## `SampleComponent::new()` ### Description Creates a new instance that is reference counted and pinned in memory. ### Method `pub fn new() -> Result` ### Returns A `Result` containing a new `SampleComponent` instance or a `PlatformError`. ``` -------------------------------- ### Get Bytes of NonZero Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/type.BufferSize.html Gets a slice of bytes representing the NonZero value. Requires the type to be Immutable. ```rust fn as_bytes(&self) -> &[u8] where Self: Immutable ``` -------------------------------- ### Get Mutable Bytes of NonZero Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/type.BufferSize.html Gets a mutable slice of bytes representing the NonZero value. Requires the type to be FromBytes. ```rust fn as_mut_bytes(&mut self) -> &mut [u8] where Self: FromBytes ``` -------------------------------- ### Instance Initialization and Surface Creation Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/hal/noop/struct.Context.html Methods for initializing the instance and creating surfaces. ```APIDOC ## unsafe fn init(desc: &InstanceDescriptor<'_>) -> Result ### Description Initializes a new instance of the graphics API. ### Method `unsafe fn init` ### Parameters - `desc` (`&InstanceDescriptor<'_>`) - Descriptor for instance initialization. ### Returns `Result` - The initialized Context or an InstanceError. ``` ```APIDOC ## unsafe fn create_surface(&self, _display_handle: RawDisplayHandle, _window_handle: RawWindowHandle) -> Result ### Description Creates a surface for rendering. ### Method `unsafe fn create_surface` ### Parameters - `_display_handle` (`RawDisplayHandle`) - Handle to the display. - `_window_handle` (`RawWindowHandle`) - Handle to the window. ### Returns `Result` - The created surface context or an InstanceError. ``` -------------------------------- ### initialize_adapter_from_env Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/util/fn.initialize_adapter_from_env.html Initializes the adapter obeying the `WGPU_ADAPTER_NAME` environment variable. ```APIDOC ## initialize_adapter_from_env ### Description Initializes the adapter obeying the `WGPU_ADAPTER_NAME` environment variable. ### Signature ```rust pub async fn initialize_adapter_from_env( instance: &Instance, compatible_surface: Option<&Surface<'_>>, ) -> Result ``` ### Availability Available on crate feature `unstable-wgpu-28` and `wgpu_core` only. ``` -------------------------------- ### Get pointer from slice of Rgb565Pixels Source: https://docs.slint.dev/latest/docs/rust/slint/platform/software_renderer/struct.Rgb565Pixel.html Gets a raw pointer to the buffer contents from a slice of Rgb565Pixels. This is an unsafe operation and part of the `BufferContents` trait. ```rust unsafe fn ptr_from_slice(slice: NonNull<[u8]>) -> *mut T ``` -------------------------------- ### Integrating WGPU rendering with Slint Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28 This example demonstrates how to set up Slint to use WGPU 28.x for rendering and integrate a WGPU-generated texture into the Slint UI. It requires a shared WGPU device and queue. ```rust use slint::wgpu_28::wgpu; use wgpu::util::DeviceExt; slint::slint!{ export component HelloWorld inherits Window { preferred-width: 320px; preferred-height: 300px; in-out property app-texture; VerticalLayout { Text { text: "hello world"; color: green; } Image { source: root.app-texture; } } } } fn main() -> Result<(), Box> { slint::BackendSelector::new() .require_wgpu_28(slint::wgpu_28::WGPUConfiguration::default()) .select()?; let app = HelloWorld::new()?; let app_weak = app.as_weak(); app.window().set_rendering_notifier(move |state, graphics_api| { let (Some(app), slint::RenderingState::RenderingSetup, slint::GraphicsAPI::WGPU28{ device, queue, ..}) = (app_weak.upgrade(), state, graphics_api) else { return; }; let mut pixels = slint::SharedPixelBuffer::::new(320, 200); pixels.make_mut_slice().fill(slint::Rgba8Pixel { r: 0, g: 255, b :0, a: 255, }); let texture = device.create_texture_with_data(queue, &wgpu::TextureDescriptor { label: None, size: wgpu::Extent3d { width: 320, height: 200, depth_or_array_layers: 1 }, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Rgba8Unorm, usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, view_formats: &[], }, wgpu::util::TextureDataOrder::default(), pixels.as_bytes(), ); let imported_image = slint::Image::try_from(texture).unwrap(); app.set_app_texture(imported_image); })?; app.run()?; Ok(()) } ``` -------------------------------- ### Get Underlying Array Reference Source: https://docs.slint.dev/latest/docs/rust/slint_interpreter/struct.SharedVector.html Attempts to get a reference to the underlying array if its length exactly matches N. Returns None otherwise. ```rust let arr = [1, 2, 3]; let slice = &arr[..]; // This will succeed because N is 3, matching the slice length let array_ref: Option<&[i32; 3]> = slice.as_array(); // This will fail because N is 2, not matching the slice length let array_ref_fail: Option<&[i32; 2]> = slice.as_array(); assert!(array_ref.is_some()); assert!(array_ref_fail.is_none()); ``` -------------------------------- ### Frontend::new() Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgc/naga/front/wgsl/struct.Frontend.html Creates a new instance of the Frontend with default options. This function is available only on the `wgpu-28` crate feature. ```APIDOC ### pub const fn new() -> Frontend Available on **crate feature`wgpu-28`** only. ``` -------------------------------- ### Try to get raw Buffer resource Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgc/resource/struct.Buffer.html Attempts to get access to the raw `DynBuffer` resource, returning an error if the buffer has been destroyed. Available on `wgpu-28` feature. ```rust fn try_raw<'a>( &'a self, guard: &'a SnatchGuard<'_>, ) -> Result<&'a Self::DynResource, DestroyedResourceError> ``` -------------------------------- ### Safe String Slicing with `get` Source: https://docs.slint.dev/latest/docs/rust/slint_interpreter/struct.SharedString.html Safely get a subslice of a string using byte indices. Returns `None` if indices are out of bounds or not on UTF-8 sequence boundaries. ```rust let v = String::from("🗻∈🌏"); assert_eq!(Some("🗻"), v.get(0..4)); // indices not on UTF-8 sequence boundaries assert!(v.get(1..).is_none()); assert!(v.get(..8).is_none()); // out of bounds assert!(v.get(..42).is_none()); ``` -------------------------------- ### Example Usage Source: https://docs.slint.dev/latest/docs/rust/slint/platform/enum.Key.html Demonstrates how to send a tab key press event to a window using the Key enum and WindowEvent. ```APIDOC ## Example: Sending a Tab Key Press Event This example shows how to dispatch a `WindowEvent::KeyPressed` event for the Tab key. ### Code ```rust use slint::platform::{WindowEvent, Key}; fn send_tab_pressed(window: &slint::Window) { window.dispatch_event(WindowEvent::KeyPressed { text: Key::Tab.into() }); } ``` ``` -------------------------------- ### Initialize ComponentCompiler with Default Style Source: https://docs.slint.dev/latest/docs/rust/slint_interpreter/struct.ComponentCompiler.html Demonstrates how to create a new ComponentCompiler, set the 'material' style, and then compile a .slint file using `build_from_path`. ```rust use slint_interpreter::{ComponentDefinition, ComponentCompiler, ComponentHandle}; let mut compiler = ComponentCompiler::default(); compiler.set_style("material".into()); let definition = spin_on::spin_on(compiler.build_from_path("hello.slint")); ``` -------------------------------- ### Start Graphics Debugger Capture Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/struct.Device.html Starts a capture in the attached graphics debugger. The behavior varies depending on the debugger (e.g., RenderDoc, Xcode). This is an unsafe operation. ```rust pub unsafe fn start_graphics_debugger_capture(&self) ``` -------------------------------- ### Example usage of format macro Source: https://docs.slint.dev/latest/docs/rust/slint_interpreter/macro.format.html Demonstrates how to use the format macro to create a SharedString. ```rust let s : slint::SharedString = slint::format!("Hello {}", "world"); assert_eq!(s, slint::SharedString::from("Hello world")); ``` -------------------------------- ### Runtime Downcast Failure Example Source: https://docs.slint.dev/latest/docs/rust/slint/trait.Model.html This example demonstrates a common runtime failure when downcasting a model due to a type mismatch. It shows the incorrect usage that leads to the failure. ```rust let model = VecModel::from_slice(&[3i32, 2, 1]) .filter(Box::new(|v: &i32| *v >= 2) as Box bool>); let model_rc = ModelRc::new(model); assert!(model_rc.as_any() .downcast_ref::, Box bool>>>() .is_none()); ``` -------------------------------- ### Get Slice as Array Reference Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/struct.BufferViewMut.html Attempt to get a reference to the underlying array if the requested size `N` exactly matches the slice's length. Returns `None` otherwise. ```rust let slice: &[i32] = &[1, 2, 3]; let arr: Option<&[i32; 3]> = slice.as_array(); assert!(arr.is_some()); let arr_short: Option<&[i32; 2]> = slice.as_array(); assert!(arr_short.is_none()); ``` -------------------------------- ### Instance Struct Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgc/instance The Instance struct is the entry point for creating resources and interacting with the GPU. It is available only when the `unstable-wgpu-28` crate feature is enabled. ```APIDOC ## Struct Instance Available on **crate feature`unstable-wgpu-28`** only. Represents a handle to the Vulkan/Metal/DX12/etc. instance. This is the entry point for creating resources and interacting with the GPU. ``` -------------------------------- ### Safely get a subslice of SharedString Source: https://docs.slint.dev/latest/docs/rust/slint_interpreter/struct.SharedString.html Provides a non-panicking way to get a subslice of the string using various index types. Returns `None` if the index would cause a panic. ```rust pub fn get(&self, i: I) -> Option<&>::Output> where I: SliceIndex, ``` -------------------------------- ### Instance Creation from Core Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/struct.Instance.html Creates a new wgpu Instance from a wgpu-core instance. This is useful for interoperation between wgpu and wgpu-core. ```APIDOC ## pub unsafe fn from_core(core_instance: Instance) -> Instance ### Description Create a new instance of wgpu from a wgpu-core instance. ### Arguments - `core_instance` - wgpu-core instance. ### Safety Refer to the creation of wgpu-core Instance. ``` -------------------------------- ### Getting Underlying Array Reference Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgc/naga/struct.Block.html Demonstrates using `as_array` to get a reference to the underlying array if the requested size `N` matches the slice's length. Returns `None` otherwise. ```rust let slice: &[i32] = &[1, 2, 3]; let array_ref: Option<&[i32; 3]> = slice.as_array(); let none_ref: Option<&[i32; 4]> = slice.as_array(); assert!(array_ref.is_some()); assert!(none_ref.is_none()); ``` -------------------------------- ### Adapter::create_device_and_queue Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgc/instance/struct.Adapter.html Asynchronously creates a logical device and its associated command queue from the adapter. This is the primary method for obtaining resources to interact with the GPU. Requires the `wgpu-28` crate feature. ```rust pub fn create_device_and_queue( self: &Arc, desc: &DeviceDescriptor>>, instance_flags: InstanceFlags, ) -> Result<(Arc, Arc), RequestDeviceError> ``` -------------------------------- ### Hello Callback Invocation and Connection Source: https://docs.slint.dev/latest/docs/rust/slint/docs/generated_code/struct.SampleComponent.html Details on how to invoke the `hello` callback and how to connect a function to it. ```APIDOC ## `SampleComponent::invoke_hello()` ### Description For each callback declared at the root of the component, a function to synchronously call that callback is generated. This function calls the `hello` callback. ### Method `pub fn invoke_hello(&self)` ## `SampleComponent::on_hello()` ### Description For each callback declared at the root of the component, a function to connect to that callback is generated. This function registers a closure `f` to be called when the `hello` callback is emitted. ### Method `pub fn on_hello(&self, f: impl Fn() + 'static)` ### Parameters - **f** (impl Fn() + 'static) - The closure to execute when the `hello` callback is emitted. It's recommended to capture a weak reference to the component within the closure. ``` -------------------------------- ### Get Mutable Slice as Mutable Array Reference Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/struct.BufferViewMut.html Attempt to get a mutable reference to the underlying array if the requested size `N` exactly matches the slice's length. Returns `None` otherwise. ```rust let mut slice: &mut [i32] = &mut [1, 2, 3]; let arr: Option<&mut [i32; 3]> = slice.as_mut_array(); assert!(arr.is_some()); let arr_short: Option<&mut [i32; 2]> = slice.as_mut_array(); assert!(arr_short.is_none()); ``` -------------------------------- ### Any::type_id Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgt/struct.TextureUses Gets the `TypeId` of the object. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. Read more ### Method type_id ### Returns - TypeId - The unique identifier for the type of `self`. ``` -------------------------------- ### Instance::from_raw Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/hal/vulkan/struct.Instance.html Initializes an Instance from raw Vulkan components. Available on crate feature `wgpu-28` only. Requires careful handling of raw Vulkan handles and extensions. ```APIDOC ## pub unsafe fn from_raw( entry: Entry, raw_instance: Instance, instance_api_version: u32, android_sdk_version: u32, debug_utils_create_info: Option, extensions: Vec<&'static CStr>, flags: InstanceFlags, memory_budget_thresholds: MemoryBudgetThresholds, has_nv_optimus: bool, drop_callback: Option>, ) -> Result Available on **crate feature`wgpu-28`** only. ##### §Safety * `raw_instance` must be created from `entry` * `raw_instance` must be created respecting `instance_api_version`, `extensions` and `flags` * `extensions` must be a superset of `desired_extensions()` and must be created from the same entry, `instance_api_version`` and flags. * `android_sdk_version` is ignored and can be `0` for all platforms besides Android * If `drop_callback` is `None`, wgpu-hal will take ownership of `raw_instance`. If `drop_callback` is `Some`, `raw_instance` must be valid until the callback is called. If `debug_utils_user_data` is `Some`, then the validation layer is available, so create a [`vk::DebugUtilsMessengerEXT`]. ``` -------------------------------- ### Example of Keys Formatting on macOS Source: https://docs.slint.dev/latest/docs/rust/slint_interpreter/struct.Keys.html Demonstrates how a Slint `@keys(Meta + Control + A)` shortcut is formatted for macOS using the `Display` trait. ```text macOS : ⌃⌘A ``` -------------------------------- ### Get Property Source: https://docs.slint.dev/latest/docs/rust/slint_interpreter/live_preview/struct.LiveReloadingComponent Forward to get_property. ```rust pub fn get_property(&self, name: &str) -> Value ``` -------------------------------- ### Get a reference to a value by key in BTreeMap Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgc/naga/back/hlsl/type.DynamicStorageBufferOffsetsTargets Use `get` to retrieve an immutable reference to the value associated with a given key. The key can be a borrowed form of the map's key type, provided their ordering matches. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); ``` -------------------------------- ### ComputePipeline Creation Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/struct.ComputePipeline.html Demonstrates how to create a ComputePipeline using a builder pattern. ```APIDOC ## ComputePipeline::new ### Description Creates a new `ComputePipelineBuilder` to configure and build a `ComputePipeline`. ### Method `new()` ### Example ```rust let pipeline = ComputePipeline::new(device, &desc)?; ``` ``` -------------------------------- ### create_buffer_init Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/util/trait.DeviceExt.html Creates a Buffer with data to initialize it. This method is available only with the `unstable-wgpu-28` crate feature. ```APIDOC ## fn create_buffer_init(&self, desc: &BufferInitDescriptor<'_>) -> Buffer ### Description Creates a Buffer with data to initialize it. ### Method `create_buffer_init` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Buffer**: The created buffer. #### Response Example None ``` -------------------------------- ### Duration Since Start Source: https://docs.slint.dev/latest/docs/rust/slint/platform/trait.Platform.html Returns the current time as a monotonic duration since the program's start. Used for animations and timers. The default implementation uses `std::time::Instant::now()` when the `std` feature is enabled. ```rust fn duration_since_start(&self) -> Duration { ... } ``` -------------------------------- ### bits Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgt/instance/struct.InstanceFlags Get the underlying bits value. ```APIDOC ## bits() ### Description Get the underlying bits value. The returned value is exactly the bits set in this flags value. ### Availability Available on **crate feature`wgpu-28`** only. ### Returns - `u32`: The underlying bits value. ``` -------------------------------- ### Initialize Instance with Callback Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/hal/vulkan/struct.Instance.html Initializes the Instance with a callback function, allowing for custom configuration like adding extensions. This function is available on the 'wgpu-28' crate feature and requires adherence to safety guidelines regarding the callback. ```rust pub unsafe fn init_with_callback( desc: &InstanceDescriptor<'_>, callback: Option FnOnce(CreateInstanceCallbackArgs<'arg, 'pnext, '_>) + '_>>, ) -> Result ``` -------------------------------- ### SampleComponent Methods Source: https://docs.slint.dev/latest/docs/rust/slint/docs/generated_code/struct.SampleComponent.html Provides details on how to interact with SampleComponent instances. ```APIDOC ## fn get(component: &'a SampleComponent) -> Self ### Description Returns a reference to the global. ### Method fn get ### Parameters #### Path Parameters - **component** (&'a SampleComponent) - Required - A reference to the SampleComponent. ### Response #### Success Response (Self) - Returns a reference to the global component. ``` ```APIDOC ## fn as_weak(&self) -> Weak ### Description Convert this Global reference into a weak reference. ### Method fn as_weak ### Parameters This method takes no parameters. ### Response #### Success Response (Weak) - Returns a weak reference to the component. ``` -------------------------------- ### type_id Source: https://docs.slint.dev/latest/docs/rust/slint_interpreter/struct.Compiler.html Gets the TypeId of the compiler instance. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `type_id` ``` -------------------------------- ### Get Global Property Source: https://docs.slint.dev/latest/docs/rust/slint_interpreter/live_preview/struct.LiveReloadingComponent Forward to get_global_property. ```rust pub fn get_global_property(&self, global_name: &str, name: &str) -> Value ``` -------------------------------- ### Instance Implementations Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/hal/gles/struct.Instance.html Core implementations for the Instance struct, including initialization and surface/adapter creation. ```APIDOC ## unsafe fn init(desc: &InstanceDescriptor<'_>) -> Result ## unsafe fn create_surface( &self, display_handle: RawDisplayHandle, window_handle: RawWindowHandle, ) -> Result ## unsafe fn enumerate_adapters( &self, _surface_hint: Option<&Surface>, ) -> Vec> `surface_hint` is only used by the GLES backend targeting WebGL2 ``` -------------------------------- ### RayFlag::empty Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgc/naga/back/struct.RayFlag Gets a RayFlag with all bits unset. ```APIDOC ## RayFlag::empty ### Description Get a flags value with all bits unset. ### Method `fn empty() -> Self` ``` -------------------------------- ### init Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgc/naga/valid/enum.ValidationError.html Initializes a with the given initializer. ```APIDOC ## unsafe fn init(init: ::Init) -> usize ### Description Initializes a with the given initializer. ### Parameters - `init` (::Init): The initializer value. ### Returns `usize`: The pointer to the initialized memory. ``` -------------------------------- ### all Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/type.AccelerationStructureFlags.html Get a flags value with all known bits set. ```APIDOC ### pub const fn all() -> AccelerationStructureFlags Available on **crate feature`wgpu-28`** only. Get a flags value with all known bits set. ```