### Installing Gettext Translations Source: https://docs.slint.dev/latest/docs/python/api/functions/init_translations Example of how to load and install gettext translations for a Slint application. Ensure the 'lang' directory exists and contains the necessary translation files. ```python import gettext import slint translations_dir = os.path.join(os.path.dirname(__file__), "lang") try: translations = gettext.translation("my_app", translations_dir, ["de"]) slint.install_translations(translations) except OSError: pass ``` -------------------------------- ### Node.js Project Setup Source: https://docs.slint.dev/latest/docs/slint/tutorial/getting_started Commands to download, extract, and install dependencies for the Slint Node.js template project. ```sh mv slint-nodejs-template-main memory cd memory ``` ```sh npm install ``` -------------------------------- ### Custom WindowAdapter Implementation Example Source: https://docs.slint.dev/latest/docs/cpp/api/slint/platform/windowadapter Provides an example of how to subclass WindowAdapter, implementing methods to interact with a native window handle for rendering and visibility. ```cpp class MyWindowAdapter : public slint::platform::WindowAdapter { slint::platform::SoftwareRenderer m_renderer; NativeHandle m_native_window; // a handle to the native window public: void request_redraw() override { m_native_window.refresh(); } slint::PhysicalSize size() const override { return slint::PhysicalSize({m_native_window.width, m_native_window.height}); } slint::platform::AbstractRenderer &renderer() override { return m_renderer; } void set_visible(bool v) override { if (v) { m_native_window.show(); } else { m_native_window.hide(); } } // ... void repaint_callback(); } ``` -------------------------------- ### Minimal Platform Implementation for MCUs Source: https://docs.slint.dev/latest/docs/rust/slint/docs/mcu A basic implementation of the `slint::platform::Platform` trait for bare metal environments using `MinimalSoftwareWindow`. This example demonstrates how to provide window creation and time duration functionalities, essential for Slint's operation on MCUs. It also shows the setup within the `main` function, including initializing the window and setting the platform. ```rust #![no_std] extern crate alloc; use alloc::{rc::Rc, boxed::Box}; use slint::platform::{Platform, software_renderer::MinimalSoftwareWindow}; slint::include_modules!(); struct MyPlatform { window: Rc, // optional: some timer device from your device's HAL crate timer: hal::Timer, // ... maybe more devices } impl Platform for MyPlatform { fn create_window_adapter(&self) -> Result, slint::PlatformError> { // Since on MCUs, there can be only one window, just return a clone of self.window. // We'll also use the same window in the event loop. Ok(self.window.clone()) } fn duration_since_start(&self) -> core::time::Duration { core::time::Duration::from_micros(self.timer.get_time()) } // optional: You can put the event loop there, or in the main function, see later fn run_event_loop(&self) -> Result<(), slint::PlatformError> { todo!(); } } // #[hal::entry] fn main() { // Initialize the heap allocator, peripheral devices and other things. // ... // Initialize a window (we'll need it later). let window = MinimalSoftwareWindow::new(Default::default()); slint::platform::set_platform(Box::new(MyPlatform { window: window.clone(), timer: hal::Timer(/*...*/), //... })) .unwrap(); // Setup the UI. let ui = MyUI::new(); // ... setup callback and properties on `ui` \ // Make sure the window covers our entire screen. window.set_size(slint::PhysicalSize::new(320, 240)); // ... start event loop (see later) ... } ``` -------------------------------- ### Basic CheckBox Example Source: https://docs.slint.dev/latest/docs/slint/reference/std-widgets/basic-widgets/checkbox A simple example demonstrating how to use the CheckBox widget with text. ```slint import { CheckBox } from "std-widgets.slint"; export component Example inherits Window { width: 200px; height: 25px; background: transparent; CheckBox { x: 5px; width: parent.width; height: parent.height; text: "Hello World"; } } ``` -------------------------------- ### Basic Switch Example Source: https://docs.slint.dev/latest/docs/slint/reference/std-widgets/basic-widgets/switch A simple example demonstrating the basic structure of a Switch component in Slint. ```slint import { Switch } from "std-widgets.slint"; export component Example inherits Window { width: 200px; height: 40px; Switch { text: "Hello World"; } } ``` -------------------------------- ### Run Setup Code Source: https://docs.slint.dev/latest/docs/rust/src/slint_interpreter/dynamic_item_tree.rs Executes the setup code for the component box, utilizing a guard for managing lifetimes. ```rust pub fn run_setup_code(&self) { generativity::make_guard!(guard); let compo_box = self.unerase(guard); ``` -------------------------------- ### StandardListView Example Source: https://docs.slint.dev/latest/docs/slint/reference/std-widgets/views/standardlistview A basic example demonstrating the StandardListView with a simple model containing text items. ```slint import { StandardListView, VerticalBox } from "std-widgets.slint"; export component Example inherits Window { width: 200px; height: 200px; VerticalBox { StandardListView { model: [ { text: "Blue"}, { text: "Red" }, { text: "Green" }, { text: "Yellow" }, { text: "Black"}, { text: "White"}, { text: "Magenta" }, { text: "Cyan" }, ]; } } } ``` -------------------------------- ### Set Component Callback Handler Example Source: https://docs.slint.dev/latest/docs/cpp/api/slint/interpreter/componentinstance Example of setting a callback handler for 'foo' that prints its arguments. ```cpp instance->set_callback("foo", [](auto args) { std::cout << "foo(" << *args[0].to_string() << ", " << *args[1].to_number() << ")\n"; }); ``` -------------------------------- ### 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 options and enabled backends. Panics if no backend feature for the active target platform is enabled. ```APIDOC ## fn new(desc: &InstanceDescriptor) -> Instance ### Description Create a new instance of wgpu using the given options and enabled backends. ### Parameters * `desc` - InstanceDescriptor: Configuration options for the new instance. ### Panics * If no backend feature for the active target platform is enabled, this method will panic; see `Instance::enabled_backend_features()`. ``` -------------------------------- ### Get Component Property Example Source: https://docs.slint.dev/latest/docs/rust/src/slint_interpreter/api.rs.html Demonstrates how to retrieve the value of a public property from a component instance. This example shows the setup required, including compiling source code and creating an instance. ```rust /// ## Examples /// /// ``` /// # i_slint_backend_testing::init_no_event_loop(); /// use slint_interpreter::{ComponentDefinition, Compiler, Value, SharedString}; /// let code = r#"# /// export component MyWin inherits Window { /// in-out property my_property: 42; /// } /// "#; /// let mut compiler = Compiler::default(); /// let result = spin_on::spin_on( /// compiler.build_from_source(code.into(), Default::default())); /// assert_eq!(result.diagnostics().count(), 0, "{:?}", result.diagnostics().collect::>()); /// let instance = result.component("MyWin").unwrap().create().unwrap(); /// assert_eq!(instance.get_property("my_property").unwrap(), Value::from(42)); /// ``` pub fn get_property(&self, name: &str) -> Result { generativity::make_guard!(guard); let comp = self.inner.unerase(guard); let name = normalize_identifier(name); if comp .description() .original .root_element .borrow() .property_declarations .get(&name) .is_none_or(|d| !d.expose_in_public_api) { return Err(GetPropertyError::NoSuchProperty); } comp.description() .get_property(comp.borrow(), &name) .map_err(|()| GetPropertyError::NoSuchProperty) } ``` -------------------------------- ### Get Duration Since Start Source: https://docs.slint.dev/latest/docs/cpp/api/slint/platform/platform Pure virtual function to get the duration in milliseconds since the application started. Intended for freestanding runtimes. ```cpp std::chrono::milliseconds slint::platform::Platform::duration_since_start()=0 ``` -------------------------------- ### Instance::new Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgc/instance/struct.Instance.html Creates a new Instance. This is the entry point to wgpu. ```APIDOC ## pub fn new( name: &str, instance_desc: &InstanceDescriptor, telemetry: Option, ) -> Instance ### Description Creates a new Instance. This is the entry point to wgpu. ### Parameters #### Path Parameters - **name** (str) - Required - The name of the instance. - **instance_desc** (InstanceDescriptor) - Required - The descriptor for the instance. - **telemetry** (Option) - Optional - Telemetry options for the instance. ### Returns - **Instance** - A new Instance object. ``` -------------------------------- ### Get X11 Server Setup Information Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_29/wgpu/wgc/error/type.ContextErrorSource Retrieves the setup information provided by the X11 server. This method is part of the Connection trait. ```rust fn setup(&self) -> &Setup ``` -------------------------------- ### Initial JavaScript Application Setup Source: https://docs.slint.dev/latest/docs/slint/tutorial/getting_started Sets up the main JavaScript file to load and run a Slint UI component. Ensure the UI file is in the correct relative path. ```js import * as slint from "slint-ui"; const ui = slint.loadFile(new URL("./ui/app-window.slint", import.meta.url)); const mainWindow = new ui.MainWindow(); await mainWindow.run(); ``` -------------------------------- ### Batching Barriers with transition_resources Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_29/wgpu/struct.CommandEncoder.html This example demonstrates how to use `transition_resources` to manually transition resources, reducing the need for wgpu to insert automatic barriers between command buffers. It shows transitioning resources from a general usage state to a color target state before rendering, and back to a general state afterwards. ```rust use wgpu::util::BufferTransition; use wgpu::util::TextureTransition; // Assume 'encoder' is a mutable CommandEncoder instance // Assume 'resource_x' and 'resource_y' are Texture or Buffer instances // Transition resources X and Y from TextureUses::RESOURCE to TextureUses::COLOR_TARGET let buffer_transitions = [BufferTransition::new(&resource_x, wgpu::BufferUses::RESOURCE, wgpu::BufferUses::COLOR_TARGET)]; let texture_transitions = [TextureTransition::new(&resource_y, wgpu::TextureUses::RESOURCE, wgpu::TextureUses::COLOR_TARGET)]; encoder.transition_resources(buffer_transitions.into_iter(), texture_transitions.into_iter()); // ... record commands that use resource_x as a render pass attachment ... // Transition resources X and Y from TextureUses::COLOR_TARGET to TextureUses::RESOURCE let buffer_transitions_back = [BufferTransition::new(&resource_x, wgpu::BufferUses::COLOR_TARGET, wgpu::BufferUses::RESOURCE)]; let texture_transitions_back = [TextureTransition::new(&resource_y, wgpu::TextureUses::COLOR_TARGET, wgpu::TextureUses::RESOURCE)]; encoder.transition_resources(buffer_transitions_back.into_iter(), texture_transitions_back.into_iter()); // ... record commands that use resources X and Y in a bind group ... ``` -------------------------------- ### Initialize WGSL Frontend with Custom 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. Requires the 'wgpu-28' crate feature. ```rust pub const fn new_with_options(options: Options) -> Frontend ``` -------------------------------- ### Option::iter_mut Example Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgc/type.Label Demonstrates getting a mutable iterator over the contained value of an Option. ```rust let mut x = Some(4); match x.iter_mut().next() { Some(v) => *v = 42, None => {}, } assert_eq!(x, Some(42)); ``` -------------------------------- ### Get Match Indices with match_indices Source: https://docs.slint.dev/latest/docs/rust/slint/struct.SharedString.html Use `match_indices` to get an iterator over the starting indices and the matched string slices for all disjoint matches of a pattern. Overlapping matches are handled by returning only the first. ```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")]); ``` -------------------------------- ### Instance::new Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgc/instance/struct.Instance.html Creates a new wgpu Instance. This is the primary entry point for initializing wgpu. ```rust pub fn new( name: &str, instance_desc: &InstanceDescriptor, telemetry: Option, ) -> Instance ``` -------------------------------- ### Initialize WGSL Frontend with Default 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 default options. Requires the 'wgpu-28' crate feature. ```rust pub const fn new() -> Frontend ``` -------------------------------- ### Basic ScaleRotateGestureHandler Example Source: https://docs.slint.dev/latest/docs/slint/reference/gestures/scalerotategesturehandler This example demonstrates how to use ScaleRotateGestureHandler to scale and rotate a Rectangle. The `started` callback captures the initial scale and rotation, while the `updated` callback applies the gesture's transformations. ```slint export component Example inherits Window { width: 400px; height: 400px; property start-scale; property start-rotation; gesture := ScaleRotateGestureHandler { started => { start-scale = rect.current-scale; start-rotation = rect.current-rotation; } updated => { rect.current-scale = start-scale * self.scale; rect.current-rotation = start-rotation + self.rotation; } rect := Rectangle { background: @radial-gradient(circle, #4488ff, #224488); border-radius: 8px; property current-scale: 1.0; property current-rotation: 0deg; width: 200px * self.current-scale; height: 200px * self.current-scale; x: (parent.width - self.width) / 2; y: (parent.height - self.height) / 2; Text { text: "Pinch & rotate"; color: white; } } } } ``` -------------------------------- ### Import Library Example in .slint Source: https://docs.slint.dev/latest/docs/rust/slint_build/struct.CompilerConfiguration Demonstrates how to import a library using the '@' prefix in a .slint file, corresponding to the configured library paths. ```slint import { Example } from "@example"; ``` -------------------------------- ### Setting and Getting Instance Properties Source: https://docs.slint.dev/latest/docs/rust/src/slint_interpreter/api.rs.html Shows how to set and get properties directly on a Slint component instance. This example demonstrates error handling when attempting to access or modify properties that do not exist on the instance. ```rust assert_eq!( instance.set_property("the-property", Value::Void), Err(SetPropertyError::NoSuchProperty) ); assert_eq!(instance.get_property("the-property"), Err(GetPropertyError::NoSuchProperty)); ``` -------------------------------- ### Get Timer Interval Source: https://docs.slint.dev/latest/docs/cpp/api/slint/timer Returns the interval of the timer in milliseconds. Returns 0 if the timer was never started. ```cpp std::chrono::milliseconds slint::Timer::interval() const ``` -------------------------------- ### initialize_adapter_from_env_or_default Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_29/wgpu/util Initialize the adapter obeying the `WGPU_ADAPTER_NAME` environment variable and if it doesn’t exist fall back on a default adapter. ```APIDOC ## Function: initialize_adapter_from_env_or_default ### Description Initialize the adapter obeying the `WGPU_ADAPTER_NAME` environment variable and if it doesn’t exist fall back on a default adapter. ### Parameters (No specific parameters documented in the source text) ### Returns (type) - Description ``` -------------------------------- ### Basic ContextMenuArea Example Source: https://docs.slint.dev/latest/docs/slint/reference/window/contextmenuarea Demonstrates how to set up a ContextMenuArea with a nested Menu, including menu items, sub-menus, and separators. This example shows the structure for defining a context menu that appears on right-click or keyboard activation. ```slint export component Example { ContextMenuArea { Menu { MenuItem { title: @tr("Cut"); activated => { debug("Cut"); } } MenuItem { title: @tr("Copy"); activated => { debug("Copy"); } } MenuItem { title: @tr("Paste"); activated => { debug("Paste"); } } MenuSeparator {} Menu { title: @tr("Find"); MenuItem { title: @tr("Find Next"); } MenuItem { title: @tr("Find Previous"); } } } } } ``` -------------------------------- ### Basic PopupWindow Example Source: https://docs.slint.dev/latest/docs/slint/reference/window/popupwindow Demonstrates how to create and show a PopupWindow. The popup is displayed when the parent window is clicked. ```slint export component Example inherits Window { width: 100px; height: 100px; popup := PopupWindow { Rectangle { height:100%; width: 100%; background: yellow; } x: 20px; y: 20px; height: 50px; width: 50px; } TouchArea { height:100%; width: 100%; clicked => { popup.show(); } } } ``` -------------------------------- ### Example Usage of Slice Iteration Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgc/naga/ir/struct.Block.html Demonstrates the output of iterating over a slice, showing the start and end points of ranges. ```rust assert_eq!(iter.next(), Some(Range { start: 0, end: 0 })); assert_eq!(iter.next(), Some(Range { start: 1, end: 3 })); assert_eq!(iter.next(), Some(Range { start: 4, end: 4 })); assert_eq!(iter.next(), Some(Range { start: 5, end: 6 })); ``` -------------------------------- ### Iterate Mutably Over Slice Elements Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/struct.BufferViewMut.html Get an iterator that yields mutable references to each element, allowing modification. Iterates from start to end. ```rust let x = &mut [1, 2, 4]; for elem in x.iter_mut() { *elem += 2; } assert_eq!(x, &[3, 4, 6]); ``` -------------------------------- ### Example: Configure winit window attributes hook Source: https://docs.slint.dev/latest/docs/rust/slint/struct.BackendSelector.html Demonstrates how to use `with_winit_window_attributes_hook` to set window content protection. This example selects the backend after applying the hook. ```rust let mut backend = slint::BackendSelector::new() .with_winit_window_attributes_hook(|attributes| attributes.with_content_protected(true)) .select() .unwrap(); ``` -------------------------------- ### Create Empty PipelineLayoutFlags Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/hal/struct.PipelineLayoutFlags.html Get a flags value with all bits unset. Use this as a starting point for building custom flag combinations. ```rust pub const fn empty() -> PipelineLayoutFlags ``` -------------------------------- ### Instance and Adapter Information Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/hal/noop/struct.Context.html Methods for initializing the instance and enumerating available adapters. ```APIDOC ## init ### Description Initializes the WGPU instance with the given descriptor. ### Method `unsafe fn init(desc: &InstanceDescriptor<'_>) -> Result` ## enumerate_adapters ### Description Enumerates the available hardware adapters for the instance. ### Method `unsafe fn enumerate_adapters(&self, _surface_hint: Option<&Context>) -> Vec>` ### Notes `surface_hint` is only used by the GLES backend targeting WebGL2. ``` -------------------------------- ### Get length of WriteOnly slice Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_29/wgpu/struct.WriteOnly.html Returns the number of elements that can be written to in a WriteOnly slice. This is useful for bounds checking or iteration setup. ```rust let example_slice: &mut [u8] = &mut [0; 10]; assert_eq!(wgpu::WriteOnly::from_mut(example_slice).len(), example_slice.len()); ``` -------------------------------- ### Instance::default 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`. This method will panic if no backend feature for the active target platform is enabled. ```APIDOC ## 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()`. ``` -------------------------------- ### Rust HashSet Get Hasher Example Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgc/naga/back/type.NeedBakeExpressions.html Shows how to retrieve a reference to the `BuildHasher` used by a `HashSet`. This can be useful for introspection or if the hasher needs to be reused. ```rust use hashbrown::HashSet; use hashbrown::DefaultHashBuilder; let hasher = DefaultHashBuilder::default(); let set: HashSet = HashSet::with_hasher(hasher); let hasher: &DefaultHashBuilder = set.hasher(); ``` -------------------------------- ### Basic ListView Example Source: https://docs.slint.dev/latest/docs/slint/reference/std-widgets/views/listview Demonstrates how to use ListView to display a list of items with dynamic text and background colors. Elements are instantiated only when visible. ```slint import { ListView, VerticalBox } from "std-widgets.slint"; export component Example inherits Window { width: 150px; height: 150px; VerticalBox { ListView { for data in [ { text: "Blue", color: #0000ff, bg: #eeeeee}, { text: "Red", color: #ff0000, bg: #eeeeee}, { text: "Green", color: #00ff00, bg: #eeeeee}, { text: "Yellow", color: #ffff00, bg: #222222 }, { text: "Black", color: #000000, bg: #eeeeee }, { text: "White", color: #ffffff, bg: #222222 }, { text: "Magenta", color: #ff00ff, bg: #eeeeee }, { text: "Cyan", color: #00ffff, bg: #222222 }, ] : Rectangle { height: 30px; background: data.bg; width: parent.width; Text { x: 0; text: data.text; color: data.color; } } } } } ``` -------------------------------- ### Project Setup Commands Source: https://docs.slint.dev/latest/docs/rust/slint Commands to set up a new Slint project using the Rust template repository. ```bash mv slint-rust-template-main my-project cd my-project ``` -------------------------------- ### Begin Compute Pass Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_29/wgpu/hal/gles/struct.CommandEncoder.html Starts a new compute pass. All active bindings are cleared upon entry. Ensure proper setup of ComputePassDescriptor. ```rust unsafe fn begin_compute_pass(&mut self, desc: &ComputePassDescriptor<'_, QuerySet>) ``` -------------------------------- ### 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 ## Function initialize_adapter_from_env_or_default ### Summary ```rust pub async fn initialize_adapter_from_env_or_default( instance: &Instance, compatible_surface: Option<&Surface<'_>>, ) -> Result ``` ### Availability Available on **crate feature `unstable-wgpu-28`** only. ### Description Initialize the adapter obeying the `WGPU_ADAPTER_NAME` environment variable and if it doesn’t exist fall back on a default adapter. ``` -------------------------------- ### Get Bounding Box Origin of PhysicalRegion Source: https://docs.slint.dev/latest/docs/rust/slint/platform/software_renderer/struct.PhysicalRegion.html Retrieves the origin (top-left corner) of the bounding box for the PhysicalRegion. This indicates the starting position of the overall area. ```rust pub fn bounding_box_origin(&self) -> PhysicalPosition ``` -------------------------------- ### Get Element Index by Reference Source: https://docs.slint.dev/latest/docs/rust/slint/struct.SharedVector.html Use `element_offset` to find the index of an element given a reference to it. Returns `None` if the reference is not aligned to an element's start. ```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 ``` -------------------------------- ### FeaturesWebGPU Initialization Methods Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_29/wgpu/wgt/struct.FeaturesWebGPU.html Methods for creating and initializing FeaturesWebGPU instances. ```APIDOC ## pub const fn empty() -> FeaturesWebGPU Available on **crate feature`wgpu-29`** only. Get a flags value with all bits unset. ``` ```APIDOC ## pub const fn all() -> FeaturesWebGPU Available on **crate feature`wgpu-29`** only. Get a flags value with all known bits set. ``` ```APIDOC ## pub const fn from_bits(bits: u64) -> Option Available on **crate feature`wgpu-29`** only. Convert from a bits value. This method will return `None` if any unknown bits are set. ``` ```APIDOC ## pub const fn from_bits_truncate(bits: u64) -> FeaturesWebGPU Available on **crate feature`wgpu-29`** only. Convert from a bits value, unsetting any unknown bits. ``` ```APIDOC ## pub const fn from_bits_retain(bits: u64) -> FeaturesWebGPU Available on **crate feature`wgpu-29`** only. Convert from a bits value exactly. ``` ```APIDOC ## pub fn from_name(name: &str) -> Option Available on **crate feature`wgpu-29`** only. Get a flags value with the bits of a flag with the given name set. This method will return `None` if `name` is empty or doesn’t correspond to any named flag. ``` -------------------------------- ### Get Component Property Example Source: https://docs.slint.dev/latest/docs/rust/src/slint_interpreter/api.rs Demonstrates how to retrieve the value of a public property from a Slint component instance. Ensure the 'display-diagnostics' feature is enabled and the component is built successfully. ```rust use slint_interpreter::{ComponentDefinition, Compiler, Value, SharedString}; // Assume `spin_on` and `i_slint_backend_testing` are available and configured. // The following code is a simplified representation of the example in the documentation. let code = r#"\ export component MyWin inherits Window {\ in-out property my_property: 42;\ } "#; let mut compiler = Compiler::default(); // In a real scenario, `build_from_source` would be called within a runtime context. // For this example, we simulate a successful build. // let result = spin_on::spin_on(compiler.build_from_source(code.into(), Default::default())); // assert_eq!(result.diagnostics().count(), 0, "{:?}", result.diagnostics().collect::>()); // Placeholder for a successfully built component instance. // In a real test, `result.component("MyWin").unwrap().create().unwrap()` would be used. struct MockComponentInstance; impl MockComponentInstance { fn get_property(&self, name: &str) -> Result { // Simplified error type if name == "my_property" { Ok(Value::from(42)) } else { Err(()) } } } let instance = MockComponentInstance; assert_eq!(instance.get_property("my_property").unwrap(), Value::from(42)); ``` -------------------------------- ### Create a new wgpu Instance Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/struct.Instance.html Creates a new wgpu Instance with specified options. Panics if no backend feature for the active target platform is enabled. ```rust pub fn new(desc: &InstanceDescriptor) -> Instance ``` -------------------------------- ### Struct Field Manipulation in Slint Source: https://docs.slint.dev/latest/docs/rust/src/slint_interpreter/api.rs.html Provides examples of getting and setting struct fields using the `get_field` and `set_field` methods. These methods normalize identifiers before performing operations. ```rust /// Get the value for a given struct field pub fn get_field(&self, name: &str) -> Option<&Value> { self.0.get(&*normalize_identifier(name)) } /// Set the value of a given struct field pub fn set_field(&mut self, name: String, value: Value) { self.0.insert(normalize_identifier(&name), value); } ``` -------------------------------- ### Shell Commands for Python Project Setup Source: https://docs.slint.dev/latest/docs/slint/tutorial/getting_started Provides commands to download, extract, rename, and navigate into the Slint Python template project directory. Also includes dependency installation. ```sh mv slint-python-template-main memory cd memory uv sync ``` -------------------------------- ### Loading a Slint File and Instantiating a Component Source: https://docs.slint.dev/latest/docs/node/api/functions/loadfile This example demonstrates how to load a 'main.slint' file using loadFile and then create an instance of the exported 'Main' component. It also shows how to modify a property ('greeting') of the instantiated component. ```slint export component Main inherits Window { in-out property greeting <=> label.text; label := Text { text: "Hello World"; } } ``` ```javascript import * as slint from "slint-ui"; let ui = slint.loadFile("main.slint"); let main = new ui.Main(); main.greeting = "Hello friends"; ``` -------------------------------- ### Example Usage of WinitWindowAccessor Source: https://docs.slint.dev/latest/docs/rust/slint/winit_030/trait.WinitWindowAccessor.html Demonstrates how to use the WinitWindowAccessor trait to retrieve and print the ID of the winit window. Ensures the winit backend is selected and spawns a future to asynchronously get the window. ```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(()) } ``` -------------------------------- ### FeaturesWebGPU Initialization Methods Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_29/wgpu/struct.FeaturesWebGPU.html Methods for creating new FeaturesWebGPU instances, either empty, with all known features, or from raw bit values. ```APIDOC ## Initialization Methods ### `empty()` Available on **crate feature`wgpu-29`** only. Get a flags value with all bits unset. ### `all()` Available on **crate feature`wgpu-29`** only. Get a flags value with all known bits set. ### `from_bits(bits: u64) -> Option` Available on **crate feature`wgpu-29`** only. Convert from a bits value. This method will return `None` if any unknown bits are set. ### `from_bits_truncate(bits: u64) -> FeaturesWebGPU` Available on **crate feature`wgpu-29`** only. Convert from a bits value, unsetting any unknown bits. ### `from_bits_retain(bits: u64) -> FeaturesWebGPU` Available on **crate feature`wgpu-29`** only. Convert from a bits value exactly. ### `from_name(name: &str) -> Option` Available on **crate feature`wgpu-29`** only. Get a flags value with the bits of a flag with the given name set. This method will return `None` if `name` is empty or doesn’t correspond to any named flag. ``` -------------------------------- ### Get Multiple Mutable Key-Value Pairs (Safe Example) Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgc/naga/back/type.PipelineConstants.html Illustrates the safe usage of `get_disjoint_key_value_mut` to retrieve mutable references to values from a HashMap. Shows handling of both existing and missing keys. ```rust use hashbrown::HashMap; let mut libraries = HashMap::new(); libraries.insert("Bodleian Library".to_string(), 1602); libraries.insert("Athenæum".to_string(), 1807); libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691); libraries.insert("Library of Congress".to_string(), 1800); let got = libraries.get_disjoint_key_value_mut([ "Bodleian Library", "Herzogin-Anna-Amalia-Bibliothek", ]); assert_eq!( got, [ Some((&"Bodleian Library".to_string(), &mut 1602)), Some((&"Herzogin-Anna-Amalia-Bibliothek".to_string(), &mut 1691)), ], ); // Missing keys result in None let got = libraries.get_disjoint_key_value_mut([ "Bodleian Library", "Gewandhaus", ]); assert_eq!( got, [ Some((&"Bodleian Library".to_string(), &mut 1602)), None, ], ); ``` -------------------------------- ### Instantiate Slint MainWindow with Properties and Callbacks Source: https://docs.slint.dev/latest/docs/node This JavaScript code demonstrates how to load a Slint UI file and instantiate the 'MainWindow' component, initializing its properties and setting up a callback. ```js import * as slint from "slint-ui"; // In this example, the main.slint file exports a module which // has a counter property and a clicked callback let ui = slint.loadFile(new URL("ui/main.slint", import.meta.url)); let component = new ui.MainWindow({ counter: 42, clicked: function() { console.log("hello"); } }); ``` -------------------------------- ### Example: Getting UIView from WindowHandle on UIKit Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/rwh/struct.UiKitWindowHandle.html Demonstrates how to safely access the UIView from a WindowHandle on UIKit platforms. Asserts that the operation is performed on the main thread and uses unsafe blocks for pointer casting. ```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"), } ``` -------------------------------- ### Create ESP-IDF Project Source: https://docs.slint.dev/latest/docs/cpp/mcu/esp-idf Initializes a new ESP-IDF project and navigates into its directory. ```bash idf.py create-project slint-hello-world cd slint-hello-world ``` -------------------------------- ### InstanceDescriptor Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgt/instance/struct.InstanceDescriptor.html Configuration for creating a WGPU instance. ```APIDOC ## struct InstanceDescriptor Configuration for creating a WGPU instance. ### Fields * `backends`: A bitmask of backends to use. If 0, all available backends will be used. * `dx12_shader_compiler`: Specifies the DX12 shader compiler to use. Defaults to `Auto`. * `gles_minor_version`: The minor version for GLES. Only relevant if GLES is enabled. * `flags`: Flags to control instance behavior. ### Example ```rust let descriptor = wgpu::InstanceDescriptor { backends: wgpu::Backends::PRIMARY | wgpu::Backends::VULKAN, dx12_shader_compiler: Default::default(), gles_minor_version: Default::default(), flags: wgpu::InstanceFlags::default(), }; let instance = wgpu::Instance::new(descriptor); ``` ``` -------------------------------- ### Setting and Getting Global Properties Source: https://docs.slint.dev/latest/docs/rust/src/slint_interpreter/api.rs.html Illustrates how to set and retrieve values for global properties of a Slint component instance. It includes examples of successful operations and error handling for non-existent properties or incorrect value types. ```rust let instance = definition.create().unwrap(); assert_eq!( instance.set_global_property("My_Super-Global", "the_property", Value::Number(44.)), Ok(()) ); assert_eq!( instance.set_global_property("AliasedGlobal", "the_property", Value::Number(44.)), Ok(()) ); assert_eq!( instance.set_global_property("DontExist", "the-property", Value::Number(88.)), Err(SetPropertyError::NoSuchProperty) ); assert_eq!( instance.set_global_property("My_Super-Global", "theproperty", Value::Number(88.)), Err(SetPropertyError::NoSuchProperty) ); assert_eq!( instance.set_global_property("AliasedGlobal", "theproperty", Value::Number(88.)), Err(SetPropertyError::NoSuchProperty) ); assert_eq!( instance.set_global_property("My_Super-Global", "the_property", Value::String("88".into())), Err(SetPropertyError::WrongType) ); assert_eq!( instance.get_global_property("My-Super_Global", "yoyo"), Err(GetPropertyError::NoSuchProperty) ); assert_eq!( instance.get_global_property("My-Super_Global", "the-property"), Ok(Value::Number(44.)) ); ``` -------------------------------- ### Get Raw Mutable Pointer from Box (Aliasing Guarantee) Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgc/device/queue/type.SubmittedWorkDoneClosure.html Returns a raw mutable pointer to the Box's contents. This method provides an aliasing guarantee, meaning it can be safely used alongside other pointer access methods without invalidating them, as demonstrated in the example. ```rust unsafe { let mut b = Box::new(0); let ptr1 = Box::as_mut_ptr(&mut b); ptr1.write(1); let ptr2 = Box::as_mut_ptr(&mut b); ptr2.write(2); // Notably, the write to `ptr2` did *not* invalidate `ptr1`: ptr1.write(3); } ``` -------------------------------- ### Initialize BackendOptions from Environment or Default Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/struct.BackendOptions.html Chooses backend options by calling `from_env` on each field. This method is available only with the 'wgpu-28' crate feature. ```rust pub fn from_env_or_default() -> BackendOptions ``` -------------------------------- ### Slint Application Fails to Start on Windows (Missing Runtime) Source: https://docs.slint.dev/latest/docs/slint/guide/backends-and-renderers/backends_and_renderers Addresses an issue where a Slint application on Windows builds successfully but terminates immediately upon execution without errors. This is often due to missing MSVC runtime libraries. Install the Microsoft Visual C++ Redistributable package. ```text The build succeeds, but running the .exe on Windows terminates immediately without error messages. This might be caused by missing MSVC runtime libraries. To solve this install, install the [Microsoft Visual C++ Redistributable package](https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist) ``` -------------------------------- ### Basic Dialog Example Source: https://docs.slint.dev/latest/docs/slint/reference/window/dialog This example demonstrates how to create a basic dialog with text and standard buttons like OK and Cancel, along with a custom action button. The buttons are automatically arranged based on the target platform. ```slint import { StandardButton, Button } from "std-widgets.slint"; export component Example inherits Dialog { Text { text: "This is a dialog box"; } StandardButton { kind: ok; } StandardButton { kind: cancel; } Button { text: "More Info"; dialog-button-role: action; } } ``` -------------------------------- ### Instantiate Window and Tray Icon, Handle Click Event (Rust) Source: https://docs.slint.dev/latest/docs/slint/reference/window/systemtrayicon This Rust snippet shows how to create a main window and a system tray icon. It wires the tray icon's click event to bring the window back if hidden. The event loop is then started. ```rust fn main() -> Result<(), slint::PlatformError> { let window = MainWindow::new()?; let tray = ExampleTray::new()?; let window_weak = window.as_weak(); tray.on_clicked(move || { if let Some(w) = window_weak.upgrade() { let _ = w.show(); } }); window.show()?; tray.show()?; slint::run_event_loop() } ``` -------------------------------- ### initialize_adapter_from_env_or_default Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_29/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. This function is only available when the `unstable-wgpu-29` crate feature is enabled. ```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. ### Availability Available on `crate feature 'unstable-wgpu-29'` only. ### 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` object for compatibility checks. ``` -------------------------------- ### Install slint-viewer with Cargo Source: https://docs.slint.dev/latest/docs/slint/guide/tooling/slint-viewer Install the slint-viewer binary using Cargo, the Rust package manager. This requires a Rust toolchain to be installed. ```sh cargo install slint-viewer ``` -------------------------------- ### Load and Run .slint from String with Properties Source: https://docs.slint.dev/latest/docs/rust/slint_interpreter This example demonstrates loading .slint UI code directly from a string. It shows how to set properties on the instantiated component before running it. ```rust use slint_interpreter::{ComponentDefinition, Compiler, Value, SharedString, ComponentHandle}; let code = r#"# export component MyWin inherits Window { in property my_name; Text { text: "Hello, " + my_name; } } "#; let mut compiler = Compiler::default(); let result = spin_on::spin_on(compiler.build_from_source(code.into(), Default::default())); assert_eq!(result.diagnostics().count(), 0); let definition = result.component("MyWin"); let instance = definition.unwrap().create().unwrap(); instance.set_property("my_name", Value::from(SharedString::from("World"))).unwrap(); instance.run().unwrap(); ``` -------------------------------- ### Install Slint Skill using npx skills Source: https://docs.slint.dev/latest/docs/slint/guide/tooling/ai-coding-assistants Install the Slint skill into the current project using the 'skills' CLI. Pass -g to install globally. ```sh npx skills add slint-ui/ai-plugins --skill slint ``` -------------------------------- ### Stop Timer Source: https://docs.slint.dev/latest/docs/cpp/api/slint/timer Stops a previously started timer. If the timer was never started, this function does nothing. A stopped timer cannot be restarted with restart(); use start() instead. ```cpp void slint::Timer::stop() ``` -------------------------------- ### from_env_or_default() Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_29/wgpu/struct.BackendOptions.html Initializes BackendOptions by choosing options from environment variables or using defaults for each backend. ```APIDOC ## impl BackendOptions ### pub fn from_env_or_default() -> BackendOptions Available on **crate feature`wgpu-29`** only. Choose backend options by calling `from_env` on every field. See those methods for more information. ``` -------------------------------- ### Example: Conditionally Pop from FastIndexMap Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/wgc/naga/type.FastIndexMap.html An example demonstrating the usage of `pop_if` to remove the last element from an IndexMap based on a condition. This example requires the `indexmap` crate. ```rust use indexmap::IndexMap; let init = [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]; let mut map = IndexMap::from(init); let pred = |key: &i32, _value: &mut char| *key % 2 == 0; assert_eq!(map.pop_if(pred), Some((4, 'd'))); assert_eq!(map.as_slice(), &init[..3]); assert_eq!(map.pop_if(pred), None); ``` -------------------------------- ### Create wgpu instance with WebGPU detection Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_29/wgpu/util/fn.new_instance_with_webgpu_detection.html Use this function to create a wgpu instance. It checks for WebGPU support and falls back to WebGL if necessary, especially when `Backends::BROWSER_WEBGPU` is enabled in the instance descriptor. This is crucial because WebGPU support must be determined at instance creation. ```rust pub async fn new_instance_with_webgpu_detection( instance_desc: InstanceDescriptor, ) -> Instance ``` -------------------------------- ### Get Associated Window Source: https://docs.slint.dev/latest/docs/cpp/api/slint/platform/windowadapter Overload for getting the associated `slint::Window`. ```cpp Window & slint::platform::WindowAdapter::window() ``` -------------------------------- ### 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. ### Method Signature ```rust pub async fn initialize_adapter_from_env( instance: &Instance, compatible_surface: Option<&Surface<'_>>, ) -> Result ``` ### Parameters * `instance` (&Instance): The wgpu instance. * `compatible_surface` (Option<&Surface<'_>>): An optional compatible surface. ### Returns * `Result`: A Result containing the initialized Adapter or a RequestAdapterError. ### Availability Available on `wgpu_core` and crate feature `unstable-wgpu-28` only. ``` -------------------------------- ### Create New XcbDisplayHandle Source: https://docs.slint.dev/latest/docs/rust/slint/wgpu_28/wgpu/rwh/struct.XcbDisplayHandle.html Example of creating a new XcbDisplayHandle with a connection and screen. ```rust let connection: NonNull; let screen; let handle = XcbDisplayHandle::new(Some(connection), screen); ```