### Rust Search Query Examples Source: https://docs.rs/iced/latest/iced/advanced/input_method/enum.Event.html?search= Provides examples of common search queries used within Rust development environments or documentation tools. These examples demonstrate how to search for specific types, function signatures, and generic type transformations. ```text std::vec u32 -> bool Option, (T -> U) -> Option ``` -------------------------------- ### Example Usage: Creating a Column Source: https://docs.rs/iced/latest/iced/widget/struct.Column.html?search= Demonstrates how to create a `Column` widget with text and button elements. This example shows basic usage within a `view` function. ```rust use iced::widget::{button, column); #[derive(Debug, Clone)] enum Message { // ... } fn view(state: &State) -> Element<'_, Message> { column![ "I am on top!", button("I am in the center!"), "I am below.", ].into() } ``` -------------------------------- ### Example Search Queries for Rust Documentation Source: https://docs.rs/iced/latest/iced/window/enum.RedrawRequest.html?search= This section provides examples of common search queries used within Rust documentation or search tools. These examples illustrate how to search for specific types, type signatures, and generic function patterns. ```text * std::vec * u32 -> bool * Option, (T -> U) -> Option ``` -------------------------------- ### Initialize and Configure Menu Source: https://docs.rs/iced/latest/iced/overlay/menu/struct.Menu.html?search=u32+-%3E+bool Example showing the constructor and configuration methods for the Menu struct, allowing customization of layout and text properties. ```rust pub fn new( state: &'a mut State, options: &'a [T], hovered_option: &'a mut Option, on_selected: impl FnMut(T) -> Message + 'a, on_option_hovered: Option<&'a dyn Fn(T) -> Message>, class: &'a ::Class<'b>, ) -> Menu<'a, 'b, T, Message, Theme, Renderer> // Configuration methods menu.width(200.0) .padding(10) .text_size(16) .font(Font::default()); ``` -------------------------------- ### Get Start Point of Curve Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/geom/cubic_bezier/struct.CubicBezierSegment.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves the starting point of the cubic Bezier segment. This is a fundamental operation for understanding the segment's geometry. ```rust pub fn from(&self) -> Point2D ``` -------------------------------- ### Get Start Point of Cubic Bézier Segment Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/geom/cubic_bezier/struct.CubicBezierSegment.html Retrieves the starting point of the cubic Bézier segment. This corresponds to the point on the curve at t=0. ```rust fn from(&self) -> Point2D ``` -------------------------------- ### IntoBoot API Source: https://docs.rs/iced/latest/iced/time/struct.Instant.html?search=std%3A%3Avec Handles the initialization logic for application states. ```APIDOC ## fn into_boot(self) -> (State, Task) ### Description Transforms a type into the initial state and startup task of an `Application`. ### Method Function Call ### Response - **(State, Task)** (Tuple) - The initial state and the associated startup task. ``` -------------------------------- ### Get Start and End Points of Bezier Segment in Rust Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/geom/quadratic_bezier/struct.QuadraticBezierSegment.html?search=std%3A%3Avec Retrieves the starting and ending points of the Bezier curve segment. These methods are fundamental for defining the segment's geometry. ```rust pub fn from(&self) -> Point2D Source ``` ```rust pub fn to(&self) -> Point2D Source ``` -------------------------------- ### Bootstrapping API Source: https://docs.rs/iced/latest/iced/widget/struct.Responsive.html?search=std%3A%3Avec Utility for initializing application states. ```APIDOC ## [METHOD] into_boot ### Description Turns a type into the initial state and task of an Application. ### Response - **(State, Task)** - The initial state and associated task. ``` -------------------------------- ### Create and configure Menu instance Source: https://docs.rs/iced/latest/iced/widget/overlay/menu/struct.Menu.html?search= Demonstrates the constructor for the Menu widget and common configuration methods for styling and layout. ```rust pub fn new( state: &'a mut State, options: &'a [T], hovered_option: &'a mut Option, on_selected: impl FnMut(T) -> Message + 'a, on_option_hovered: Option<&'a dyn Fn(T) -> Message>, class: &'a ::Class<'b>, ) -> Menu<'a, 'b, T, Message, Theme, Renderer> // Configuration methods pub fn width(self, width: f32) -> Menu<'a, 'b, T, Message, Theme, Renderer> pub fn padding

(self, padding: P) -> Menu<'a, 'b, T, Message, Theme, Renderer> pub fn text_size( self, text_size: impl Into, ) -> Menu<'a, 'b, T, Message, Theme, Renderer> ``` -------------------------------- ### Get X11 Server Setup Information (Rust) Source: https://docs.rs/iced/latest/iced/widget/float/type.StyleFn.html Retrieves the setup information provided by the X11 server upon connection. This includes details about the server's capabilities and configuration. ```rust fn setup(&self) -> &Setup ``` -------------------------------- ### Get Segment Endpoints Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/geom/quadratic_bezier/struct.QuadraticBezierSegment.html?search=u32+-%3E+bool Retrieves the starting and ending points of the curve segment. ```rust pub fn from(&self) -> Point2D ``` ```rust pub fn to(&self) -> Point2D ``` -------------------------------- ### IntoBoot Trait Source: https://docs.rs/iced/latest/iced/widget/theme/struct.Palette.html?search= Documentation for the `into_boot` method, which initializes an application's state and task. ```APIDOC ## fn into_boot(self) -> (State, Task) ### Description Turns some type into the initial state of some `Application`. ### Method `fn` ### Endpoint N/A (Trait method) ### Parameters None ### Request Example None ### Response #### Success Response (200) - **(State, Task)** - A tuple containing the initial state and a task for the application. #### Response Example None ``` -------------------------------- ### Get Curve Segment Endpoints Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/geom/quadratic_bezier/struct.QuadraticBezierSegment.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves the starting and ending points of the curve segment. ```rust pub fn from(&self) -> Point2D pub fn to(&self) -> Point2D ``` -------------------------------- ### Initialize and configure Menu Source: https://docs.rs/iced/latest/iced/widget/overlay/menu/struct.Menu.html?search=std%3A%3Avec Demonstrates the constructor for creating a new Menu instance and the builder methods used to configure its visual properties like dimensions and text styling. ```rust pub fn new( state: &'a mut State, options: &'a [T], hovered_option: &'a mut Option, on_selected: impl FnMut(T) -> Message + 'a, on_option_hovered: Option<&'a dyn Fn(T) -> Message>, class: &'a ::Class<'b>, ) -> Menu<'a, 'b, T, Message, Theme, Renderer> pub fn width(self, width: f32) -> Menu<'a, 'b, T, Message, Theme, Renderer> pub fn padding

(self, padding: P) -> Menu<'a, 'b, T, Message, Theme, Renderer> pub fn text_size(self, text_size: impl Into) -> Menu<'a, 'b, T, Message, Theme, Renderer> ``` -------------------------------- ### Configure and run an iced Daemon Source: https://docs.rs/iced/latest/iced/daemon/struct.Daemon.html Demonstrates how to initialize a Daemon and chain configuration methods such as setting the title, theme, and running the application. ```rust let daemon = iced::daemon(my_program) .title(|state| format!("App: {}", state.name)) .theme(|state| state.theme) .antialiasing(true); daemon.run().expect("Failed to run daemon"); ``` -------------------------------- ### GET /rchunks_exact Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/geom/arrayvec/struct.ArrayVec.html?search=u32+-%3E+bool Returns an iterator over chunks of exactly chunk_size elements starting from the end. ```APIDOC ## GET /rchunks_exact ### Description Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice. Chunks are exactly `chunk_size` elements; remainder elements are handled separately. ### Method GET ### Endpoint /rchunks_exact ### Parameters #### Query Parameters - **chunk_size** (usize) - Required - The exact size of each chunk. ``` -------------------------------- ### Application Bootstrapping Source: https://docs.rs/iced/latest/iced/advanced/struct.Shell.html Utilities for initializing application states. ```APIDOC ## [METHOD] into_boot ### Description Transforms a type into the initial state and task stream for an Application. ### Method Function ### Response - **result** ((State, Task)) - A tuple containing the initial state and the startup task. ``` -------------------------------- ### GET /rchunks Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/geom/arrayvec/struct.ArrayVec.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns an iterator over chunk_size elements of the slice at a time, starting at the end of the slice. ```APIDOC ## GET /rchunks ### Description Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice. The chunks are slices and do not overlap. ### Method GET ### Endpoint /rchunks ### Parameters #### Query Parameters - **chunk_size** (usize) - Required - The size of each chunk. ### Request Example { "slice": ['l', 'o', 'r', 'e', 'm'], "chunk_size": 2 } ### Response #### Success Response (200) - **iterator** (RChunks) - An iterator over chunks starting from the end. #### Response Example { "chunks": [['e', 'm'], ['o', 'r'], ['l']] } ``` -------------------------------- ### Bootstrapping API Source: https://docs.rs/iced/latest/iced/advanced/struct.Shell.html?search= Utility for initializing application states. ```APIDOC ## [METHOD] into_boot ### Description Turns a type into the initial state of an Application. ### Method Function ### Response #### Success Response (200) - **state** (State) - The initial application state. - **task** (Task) - The startup task. ``` -------------------------------- ### GET /array_windows Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/geom/arrayvec/struct.ArrayVec.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns an iterator over overlapping windows of N elements of a slice, starting at the beginning. ```APIDOC ## GET /array_windows ### Description Returns an iterator over overlapping windows of `N` elements of a slice, starting at the beginning of the slice. This is the const generic equivalent of `windows`. ### Method GET ### Endpoint /array_windows ### Parameters #### Query Parameters - **N** (usize) - Required - The size of the window. ### Request Example { "slice": [0, 1, 2, 3], "N": 2 } ### Response #### Success Response (200) - **iterator** (ArrayWindows) - An iterator over overlapping windows. #### Response Example { "windows": [[0, 1], [1, 2], [2, 3]] } ``` -------------------------------- ### Application Bootstrapping Source: https://docs.rs/iced/latest/iced/widget/theme/enum.Theme.html?search=std%3A%3Avec Conversion utilities for initializing application states. ```APIDOC ## fn into_boot(self) ### Description Turns a type into the initial state and task for an Iced Application. ### Response - **(State, Task)** - A tuple containing the initial state and the startup task. ``` -------------------------------- ### GET /array_windows Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/geom/arrayvec/struct.ArrayVec.html Returns an iterator over overlapping windows of N elements of a slice, starting at the beginning of the slice. ```APIDOC ## GET /array_windows ### Description Returns an iterator over overlapping windows of N elements of a slice. This is the const generic equivalent of windows. ### Method GET ### Endpoint /array_windows ### Parameters #### Query Parameters - **N** (usize) - Required - The size of the windows to create. ### Request Example { "N": 2 } ### Response #### Success Response (200) - **iterator** (ArrayWindows) - An iterator over overlapping windows of size N. #### Response Example { "result": [[0, 1], [1, 2], [2, 3]] } ``` -------------------------------- ### GET /rchunks_exact Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/geom/arrayvec/struct.ArrayVec.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns an iterator over chunk_size elements starting from the end, omitting the remainder if the slice length is not divisible by chunk_size. ```APIDOC ## GET /rchunks_exact ### Description Returns an iterator over `chunk_size` elements of the slice at a time, starting at the end of the slice. If the slice length is not divisible by `chunk_size`, the remainder is omitted. ### Method GET ### Endpoint /rchunks_exact ### Parameters #### Query Parameters - **chunk_size** (usize) - Required - The size of each chunk. ### Request Example { "slice": ['l', 'o', 'r', 'e', 'm'], "chunk_size": 2 } ### Response #### Success Response (200) - **iterator** (RChunksExact) - An iterator over exact chunks. - **remainder** (Array) - The remaining elements not included in chunks. #### Response Example { "chunks": [['e', 'm'], ['o', 'r']], "remainder": ['l'] } ``` -------------------------------- ### IntoBoot Trait Methods Source: https://docs.rs/iced/latest/iced/window/raw_window_handle/struct.WindowHandle.html?search= Interface for initializing application states. ```APIDOC ## [METHOD] into_boot ### Description Transforms a type into the initial state and task for an application. ### Method Function ### Response #### Success Response (200) - **(State, Task)** - A tuple containing the initial state and the boot task. ``` -------------------------------- ### IntoBoot Methods Source: https://docs.rs/iced/latest/iced/widget/pane_grid/state/struct.State.html?search= Provides functionality for initializing an application's state and task. ```APIDOC ## POST /into_boot ### Description Turns some type into the initial state of some `Application`. ### Method POST ### Endpoint /into_boot ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **self** (State) - The initial state. ### Request Example ```json { "self": "initial_state" } ``` ### Response #### Success Response (200) - **(State, Task)** (Tuple) - A tuple containing the initial state and the initial task. #### Response Example ```json { "example": ["initial_state", "initial_task"] } ``` ``` -------------------------------- ### Get Cursor Selection - Rust Source: https://docs.rs/iced/latest/iced/widget/text_input/cursor/struct.Cursor.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the current selection range of the cursor for a given text input `Value`. The returned tuple `(usize, usize)` represents the start and end indices of the selection, with `start` always less than or equal to `end`. ```rust pub fn selection(&self, value: &Value) -> Option<(usize, usize)> ``` -------------------------------- ### POST /into_boot Source: https://docs.rs/iced/latest/iced/time/struct.Duration.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes the application state from a given type. ```APIDOC ## POST /into_boot ### Description Turns a specific type into the initial state of an Application. ### Method POST ### Endpoint /into_boot ### Parameters #### Request Body - **self** (State) - Required - The initial state object. ### Response #### Success Response (200) - **state** (State) - The initialized application state. - **task** (Task) - The initial task to be executed. ### Response Example { "state": "InitialState", "task": "Task::none()" } ``` -------------------------------- ### Implement Path Event Properties in Rust Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/enum.Event.html?search=u32+-%3E+bool Implements utility methods for the `Event` enum, including `is_edge` to check if an event represents an edge, `from` to get the starting endpoint, and `to` to get the ending endpoint. These methods require the endpoint type to be `Clone`. ```rust impl Event where Ep: Clone, { pub fn is_edge(&self) -> bool pub fn from(&self) -> Ep pub fn to(&self) -> Ep } ``` -------------------------------- ### Initialize and manage Iced Preset Source: https://docs.rs/iced/latest/iced/struct.Preset.html Demonstrates how to create a new Preset with a specific name and boot strategy, and how to access its properties. The boot strategy returns the initial state and a Task for concurrent execution. ```rust use iced::{Task, Preset}; use std::borrow::Cow; // Creating a new Preset let preset = Preset::new("my_preset", || { let state = MyState::default(); let task = Task::none(); (state, task) }); // Accessing properties let name = preset.name(); let (state, task) = preset.boot(); ``` -------------------------------- ### VerticalSlider Structure and Example Usage (Rust) Source: https://docs.rs/iced/latest/iced/widget/struct.VerticalSlider.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Defines the `VerticalSlider` struct and provides a practical example of its integration within an iced application. This includes setting up the state, handling value changes via messages, and rendering the slider in the UI. It demonstrates the basic setup for using a `VerticalSlider`. ```rust pub struct VerticalSlider<'a, T, Message, Theme = Theme> where Theme: Catalog, { /* private fields */ } use iced::widget::vertical_slider; struct State { value: f32, } #[derive(Debug, Clone)] enum Message { ValueChanged(f32), } fn view(state: &State) -> Element<'_, Message> { vertical_slider(0.0..=100.0, state.value, Message::ValueChanged).into() } fn update(state: &mut State, message: Message) { match message { Message::ValueChanged(value) => { state.value = value; } } } ``` -------------------------------- ### IntoBoot Trait Source: https://docs.rs/iced/latest/iced/window/raw_window_handle/struct.DrmWindowHandle.html?search=u32+-%3E+bool Handles the initialization logic for application state. ```APIDOC ## [METHOD] into_boot ### Description Converts a state type into the initial state of an `Application` along with its startup task. ### Method Rust Trait Method ### Response - **(State, Task)** (Tuple) - The initial state and the associated startup task. ``` -------------------------------- ### Example: Get NSView from WindowHandle (Rust) Source: https://docs.rs/iced/latest/iced/window/raw_window_handle/struct.AppKitWindowHandle.html?search=u32+-%3E+bool Demonstrates how to safely extract an NSView from a WindowHandle on macOS. It includes checks for the main thread and proper unsafe casting. ```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"), } ``` -------------------------------- ### Create and Configure Responsive Widget in Rust Source: https://docs.rs/iced/latest/iced/widget/struct.Responsive.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to instantiate a new Responsive widget using a closure that receives the current size, and how to set its width and height constraints. ```Rust use iced::widget::Responsive; use iced::{Size, Element}; let responsive_widget = Responsive::new(|size: Size| { if size.width > 400.0 { // Render wide layout Element::from(iced::widget::text("Wide")) } else { // Render narrow layout Element::from(iced::widget::text("Narrow")) } }) .width(iced::Length::Fill) .height(iced::Length::Fixed(200.0)); ``` -------------------------------- ### Get Flattened Curve Iterator (Rust) Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/geom/quadratic_bezier/struct.QuadraticBezierSegment.html Returns an iterator that yields the flattened representation of the curve. This iterator starts after the current point and provides segments based on a specified tolerance. ```rust pub fn flattened(&self, tolerance: S) -> Flattened ``` -------------------------------- ### Application Bootstrapping Source: https://docs.rs/iced/latest/iced/widget/image/viewer/struct.Viewer.html?search=u32+-%3E+bool Converts a state into an initial application state and task. ```APIDOC ## Convert State to Application Bootstrapping ### Description Turns a state into the initial state of an `Application`, along with an associated `Task` for handling messages. ### Method `into_boot` ### Endpoint N/A (Method on `State`) ### Parameters - `self` (State): The state to convert. ### Request Example ```rust struct MyState; struct MyMessage; impl IntoBoot for MyState { fn into_boot(self) -> (MyState, Task) { // Implementation details (self, Task::none()) } } let initial_state = MyState; let (state, task) = initial_state.into_boot(); ``` ### Response #### Success Response (200) - `(State, Task)`: A tuple containing the initial state and the task. #### Response Example ```json // No direct JSON response, returns a tuple ``` ``` -------------------------------- ### Get Current Position in Boxed Stream Source: https://docs.rs/iced/latest/iced/advanced/widget/text/type.StyleFn.html?search=u32+-%3E+bool Returns the current byte offset from the start of a boxed stream. This function is part of the `Seek` trait. ```rust fn stream_position(&mut self) -> Result ``` -------------------------------- ### Getting the Current Instant in Rust Source: https://docs.rs/iced/latest/iced/time/struct.Instant.html This example shows the basic usage of `Instant::now()` to capture the current point in time. It's a fundamental operation for any time-related measurement. ```rust use std::time::Instant; let now = Instant::now(); ``` -------------------------------- ### Iced Application Example Source: https://docs.rs/iced/latest/iced/fn.application.html?search= A complete, runnable example demonstrating how to use the `iced::application` function to create a basic GUI application. It includes the main function, message enum, update logic, and view definition for a simple counter. ```rust use iced::widget::{button, column, text, Column}; pub fn main() -> iced::Result { iced::application(u64::default, update, view).run() } #[derive(Debug, Clone)] enum Message { Increment, } fn update(value: &mut u64, message: Message) { match message { Message::Increment => *value += 1, } } fn view(value: &u64) -> Column { column![ text(value), button("+").on_press(Message::Increment), ] } ``` -------------------------------- ### Create and Configure Responsive Widget in Rust Source: https://docs.rs/iced/latest/iced/widget/struct.Responsive.html?search= Demonstrates how to instantiate a new Responsive widget using a closure that receives the available size, and how to set its dimensions. ```Rust use iced::widget::Responsive; use iced::{Size, Element}; // Creating a new Responsive widget let responsive = Responsive::new(|size: Size| { // Conditionally build content based on size if size.width > 500.0 { // Return wide layout } else { // Return narrow layout } }); // Configuring dimensions let responsive = responsive.width(Length::Fill).height(Length::Fixed(200.0)); ``` -------------------------------- ### Get Current System Time and Calculate Elapsed Time in Rust Source: https://docs.rs/iced/latest/iced/time/struct.SystemTime.html?search=u32+-%3E+bool Demonstrates how to get the current system time using `SystemTime::now()` and calculate the elapsed time since then using `elapsed()`. It includes error handling for cases where the system clock might have moved backward. This example requires the `std::time` and `std::thread` modules. ```rust use std::time::{Duration, SystemTime}; use std::thread::sleep; fn main() { let now = SystemTime::now(); // we sleep for 2 seconds sleep(Duration::new(2, 0)); match now.elapsed() { Ok(elapsed) => { // it prints '2' println!("{}", elapsed.as_secs()); } Err(e) => { // the system clock went backwards! println!("Great Scott! {:?}", e); } } } ``` -------------------------------- ### Get indices of string pattern matches in Rust Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/geom/arrayvec/struct.ArrayString.html?search=std%3A%3Avec Methods to retrieve both the starting byte index and the matched string slice for all occurrences. Use match_indices for forward order and rmatch_indices for reverse order. ```rust let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect(); assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]); ``` -------------------------------- ### Create and Configure Responsive Widget in Rust Source: https://docs.rs/iced/latest/iced/widget/struct.Responsive.html?search=u32+-%3E+bool Demonstrates how to instantiate a new Responsive widget using a closure that receives the current size, and how to set its width and height dimensions. ```Rust use iced::widget::Responsive; use iced::{Size, Element}; // Creating a new Responsive widget let responsive = Responsive::new(|size: Size| { // Conditionally build content based on size if size.width > 500.0 { // Return wide layout Element::from(iced::widget::text("Wide")) } else { // Return narrow layout Element::from(iced::widget::text("Narrow")) } }) .width(iced::Length::Fill) .height(iced::Length::Shrink); ``` -------------------------------- ### Initialize and Configure Grid Widget Source: https://docs.rs/iced/latest/iced/widget/struct.Grid.html?search=u32+-%3E+bool Demonstrates how to instantiate a Grid widget and apply configuration methods such as setting spacing, dimensions, and adding children. ```Rust use iced::widget::Grid; use iced::Pixels; let grid = Grid::new() .spacing(10) .width(Pixels::from(500)) .columns(3) .push(element1) .push_maybe(Some(element2)); ``` -------------------------------- ### Get Indices of Elements Satisfying a Predicate Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/commands/struct.Events.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns an iterator adaptor that yields the indices of all elements satisfying a predicate, counted from the start of the iterator. Requires the iterator to be `Sized`. ```Rust fn positions

(self, predicate: P) -> Positions where Self: Sized, P: FnMut(Self::Item) -> bool ``` -------------------------------- ### POST /iced/menu/new Source: https://docs.rs/iced/latest/iced/overlay/menu/struct.Menu.html Initializes a new Menu instance with a state, a list of options, and event handlers for selection and hovering. ```APIDOC ## POST /iced/menu/new ### Description Creates a new `Menu` component with the provided state, options, and selection callbacks. ### Method POST ### Endpoint /iced/menu/new ### Parameters #### Request Body - **state** (State) - Required - The mutable state of the menu. - **options** (Vec) - Required - The list of selectable items. - **hovered_option** (Option) - Required - Mutable reference to the currently hovered index. - **on_selected** (FnMut) - Required - Callback triggered when an option is selected. - **on_option_hovered** (Option) - Optional - Callback triggered when an option is hovered. - **class** (Catalog::Class) - Required - The styling class for the menu. ### Response #### Success Response (200) - **menu** (Menu) - The initialized Menu instance. ``` -------------------------------- ### Example: Point3D clamp Usage (Rust) Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/geom/euclid/default/type.Point3D.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates the `clamp` method for Point3D, which constrains each component within a specified range defined by start and end points. This ensures the point stays within a bounding box. ```rust where T: Copy, Returns the point each component of which clamped by corresponding components of `start` and `end`. Shortcut for `self.max(start).min(end)`. ``` -------------------------------- ### Get Whole Seconds from Duration in Rust Source: https://docs.rs/iced/latest/iced/time/struct.Duration.html?search= Demonstrates the `as_secs` method, which returns the number of whole seconds in a `Duration`. It does not include the fractional nanosecond part. An example shows retrieving seconds from a duration with nanoseconds. ```rust use std::time::Duration; let duration = Duration::new(5, 730_023_852); assert_eq!(duration.as_secs(), 5); ``` -------------------------------- ### Path Construction Methods Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/path/type.Builder.html Examples of core methods used to manipulate the path builder, such as starting a sub-path, adding lines, and closing the path. These methods require a sub-path to be in progress or not, depending on the specific operation. ```rust pub fn begin(&mut self, at: Point2D) -> EndpointId; pub fn line_to(&mut self, to: Point2D) -> EndpointId; pub fn close(&mut self); pub fn end(&mut self, close: bool); ``` -------------------------------- ### Application Bootstrapping Source: https://docs.rs/iced/latest/iced/widget/theme/struct.Palette.html Converts a state into the initial state and task for an application. ```APIDOC ## fn into_boot(self) -> (State, Task) ### Description Turns some type into the initial state of some `Application`. ### Method `into_boot` ### Parameters None ### Response - `(State, Task)`: A tuple containing the initial state and a task for the application. ``` -------------------------------- ### Get Shared Reference using Box AsRef Trait (Rust) Source: https://docs.rs/iced/latest/iced/advanced/widget/text/type.StyleFn.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Example of obtaining a shared reference to the contained data of a `Box` using the `as_ref` method from the `AsRef` trait. This provides immutable access to the boxed value. ```rust fn as_ref(&self) -> &T ``` -------------------------------- ### IntoBoot Trait API Source: https://docs.rs/iced/latest/iced/theme/struct.Palette.html?search=u32+-%3E+bool Handles the initialization of application states. ```APIDOC ## IntoBoot Trait ### Description Converts a type into the initial state and task set for an application. ### Method - **into_boot() -> (State, Task)** ### Response Example { "state": "InitialState", "task": "Task" } ``` -------------------------------- ### Application Bootstrapping Source: https://docs.rs/iced/latest/iced/widget/checkbox/struct.Checkbox.html?search=std%3A%3Avec The `into_boot` function is used to initialize an application's state and any associated asynchronous tasks. It returns a tuple containing the initial state and a `Task` that will be executed. ```rust fn into_boot(self) -> (State, Task) { // Implementation details for into_boot unimplemented!() } ``` -------------------------------- ### Rust: Safely Get Duration Since Another Instant Source: https://docs.rs/iced/latest/iced/time/struct.Instant.html?search=std%3A%3Avec Provides an example of using `checked_duration_since()` to safely calculate the duration between two `Instant`s, returning `None` if the earlier instant is later than the current one or due to monotonicity bugs. ```rust use std::time::{Instant, Duration}; let now = Instant::now(); let earlier = Instant::now(); // In a real scenario, this would be a past instant let duration_option = now.checked_duration_since(earlier); match duration_option { Some(duration) => println!("Duration: {:?}", duration), None => println!("Could not calculate duration."), } ``` -------------------------------- ### POST /into_boot Source: https://docs.rs/iced/latest/iced/advanced/input_method/struct.Preedit.html Initializes an application state from a given type, returning the initial state and a task message. ```APIDOC ## POST /into_boot ### Description Turns a type into the initial state of an Application, returning the state and a task queue. ### Method POST ### Endpoint /into_boot ### Request Body - **state** (Object) - Required - The initial state object to be transformed. ### Response #### Success Response (200) - **state** (Object) - The initialized application state. - **task** (Task) - The task message associated with the application startup. ### Response Example { "state": { "id": 1 }, "task": "initialize_app" } ``` -------------------------------- ### Measuring Elapsed Time with Instant in Rust Source: https://docs.rs/iced/latest/iced/time/struct.Instant.html This example demonstrates how to get the current `Instant`, sleep for a duration, and then measure the elapsed time in seconds. It requires importing `Duration` and `Instant` from `std::time`, and `sleep` from `std::thread`. ```rust use std::time::{Duration, Instant}; use std::thread::sleep; fn main() { let now = Instant::now(); // we sleep for 2 seconds sleep(Duration::new(2, 0)); // it prints '2' println!("{}", now.elapsed().as_secs()); } ``` -------------------------------- ### Point2D Clamping Example (Rust) Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/geom/euclid/struct.Point2D.html Shows how to use the clamp method on a Point2D. This method ensures that each component of the point lies within the bounds defined by the corresponding components of the start and end points. ```rust use euclid::point2; use euclid::default::Point2D; let point: Point2D = point2(5, 15); let start: Point2D = point2(0, 10); let end: Point2D = point2(10, 20); let clamped_point = point.clamp(start, end); assert_eq!(clamped_point, point2(5, 15)); let out_of_bounds_point: Point2D = point2(-5, 25); let clamped_out_of_bounds = out_of_bounds_point.clamp(start, end); assert_eq!(clamped_out_of_bounds, point2(0, 20)); ``` -------------------------------- ### Initialize and configure Menu in Rust Source: https://docs.rs/iced/latest/iced/widget/overlay/menu/struct.Menu.html?search=u32+-%3E+bool Methods to instantiate a new Menu and configure its visual properties like width, padding, and text styling. ```rust pub fn new( state: &'a mut State, options: &'a [T], hovered_option: &'a mut Option, on_selected: impl FnMut(T) -> Message + 'a, on_option_hovered: Option<&'a dyn Fn(T) -> Message>, class: &'a ::Class<'b>, ) -> Menu<'a, 'b, T, Message, Theme, Renderer> pub fn width(self, width: f32) -> Menu<'a, 'b, T, Message, Theme, Renderer> pub fn padding

(self, padding: P) -> Menu<'a, 'b, T, Message, Theme, Renderer> where P: Into pub fn text_size( self, text_size: impl Into, ) -> Menu<'a, 'b, T, Message, Theme, Renderer> ``` -------------------------------- ### Get Mutable Chunk (Rust) Source: https://docs.rs/iced/latest/iced/widget/checkbox/type.StyleFn.html Returns a mutable slice starting at the current `BufMut` position. The length of the slice is between 0 and `BufMut::remaining_mut()`, and it may be shorter than the total remaining space to allow for non-contiguous buffer implementations. ```rust fn chunk_mut(&mut self) -> &mut UninitSlice ``` -------------------------------- ### Application Bootstrapping Source: https://docs.rs/iced/latest/iced/window/raw_window_handle/struct.WebDisplayHandle.html Provides functionality to convert a state into the initial state and task for an application. ```APIDOC ## Application Bootstrapping ### `impl IntoBoot for State` #### `fn into_boot(self) -> (State, Task)` Turns some type into the initial state of some `Application`. ``` -------------------------------- ### Measure Elapsed Time Since an Instant Source: https://docs.rs/iced/latest/iced/time/struct.Instant.html Shows how to use the `elapsed()` method on an `Instant` to get the `Duration` that has passed since that instant was created. This is useful for timing operations. The example asserts that the elapsed duration is greater than or equal to a specified duration. ```rust use std::thread::sleep; use std::time::{Duration, Instant}; let instant = Instant::now(); let three_secs = Duration::from_secs(3); sleep(three_secs); assert!(instant.elapsed() >= three_secs); ``` -------------------------------- ### Application Bootstrapping Source: https://docs.rs/iced/latest/iced/struct.Animation.html?search= Utility for initializing application state and tasks. ```APIDOC ## [METHOD] into_boot ### Description Transitions a type into the initial state and task set for an Application. ### Method N/A (Trait Method) ### Response #### Success Response (200) - **(State, Task)** - The initial state and associated task. ``` -------------------------------- ### Create Iced Application Source: https://docs.rs/iced/latest/iced/fn.application.html?search=u32+-%3E+bool Creates an iced `Application` given its boot, update, and view logic. This is the main entry point for building an Iced GUI application. ```APIDOC ## POST /application ### Description Creates an iced `Application` given its boot, update, and view logic. ### Method POST ### Endpoint /application ### Parameters #### Request Body - **boot** (impl BootFn) - Required - The function to initialize the application's state. - **update** (impl UpdateFn) - Required - The function to handle incoming messages and update the application's state. - **view** (impl for<'a> ViewFn<'a, State, Message, Theme, Renderer>) - Required - The function to render the application's UI based on its current state. ### Request Example ```json { "boot": "u64::default", "update": "update", "view": "view" } ``` ### Response #### Success Response (200) - **Application** (Application>) - The created Iced application instance. #### Response Example ```json { "application_instance": "..." } ``` ``` -------------------------------- ### Example: Get UIView from WindowHandle (Rust) Source: https://docs.rs/iced/latest/iced/window/raw_window_handle/struct.UiKitWindowHandle.html?search=std%3A%3Avec Demonstrates how to safely retrieve a UIKit UIView from a generic WindowHandle. It uses pattern matching to identify a RawWindowHandle::UIKit and asserts that the operation is performed on the main thread before casting the raw pointer to an Id. ```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"), } ``` -------------------------------- ### Initialize and use Iced Shell Source: https://docs.rs/iced/latest/iced/advanced/struct.Shell.html?search=u32+-%3E+bool Demonstrates how to instantiate a new Shell with a message buffer and use it to publish messages or manage application state. ```Rust use iced::advanced::Shell; // Create a new shell with a message buffer let mut messages = Vec::new(); let mut shell = Shell::new(&mut messages); // Publish a message shell.publish(MyMessage::Clicked); // Capture an event to prevent bubbling shell.capture_event(); // Invalidate layout if necessary shell.invalidate_layout(); ``` -------------------------------- ### Get Word Boundary Positions in Rust Source: https://docs.rs/iced/latest/iced/widget/text_input/struct.Value.html?search=u32+-%3E+bool Illustrates how to find the positions of the previous start of a word and the next end of a word relative to a given index within the text input's Value. This is useful for implementing word-based navigation or selection. ```Rust use iced::widget::text_input::Value; let value = Value::new("Hello, world!"); let index = 7; // Position within "world" // Get the position of the previous start of a word let prev_word_start = value.previous_start_of_word(index); println!("Previous word start: {}", prev_word_start); // 7 (start of 'w') // Get the position of the next end of a word let next_word_end = value.next_end_of_word(index); println!("Next word end: {}", next_word_end); // 12 (end of 'd') ``` -------------------------------- ### POST /window/open Source: https://docs.rs/iced/latest/iced/window/index.html?search=u32+-%3E+bool Opens a new application window using the provided settings and returns a unique window identifier. ```APIDOC ## POST /window/open ### Description Opens a new window with the given settings. Returns the `Id` of the new window upon successful creation. ### Method POST ### Endpoint /window/open ### Request Body - **settings** (Settings) - Required - Configuration object for the new window (dimensions, title, etc.) ### Request Example { "settings": { "size": [800, 600], "resizable": true } } ### Response #### Success Response (200) - **id** (Id) - The unique identifier for the newly created window. #### Response Example { "id": "window_01" } ``` -------------------------------- ### Get Mutable Raw Pointer from Box (Rust) Source: https://docs.rs/iced/latest/iced/widget/svg/type.StyleFn.html?search= This example shows how to obtain a mutable raw pointer to the contents of a Box using `as_mut_ptr`. It's crucial to ensure the Box outlives the pointer to avoid dangling pointers and undefined behavior. ```rust #![feature(allocator_api, box_as_ptr)] use std::alloc::System; let mut x = Box::new_in(5, System); let ptr = Box::as_mut_ptr(&mut x); // Use ptr here, ensuring x lives long enough. ``` -------------------------------- ### Get Mutable Raw Pointer Range of Slice (Rust) Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/geom/arrayvec/struct.ArrayVec.html Returns a half-open range of two mutable raw pointers representing the start and one-past-the-end of the slice's buffer. Useful for foreign function interfaces. The end pointer requires extra caution. ```rust let mut a = [1, 2, 3]; let start_ptr = a.as_mut_ptr(); let end_ptr = unsafe { start_ptr.add(a.len()) }; let range = start_ptr..end_ptr; // Example usage: iterating through the range unsafe { for ptr in range { // Do something with the mutable pointer } } ``` -------------------------------- ### Initialize Custom Theme in Iced Source: https://docs.rs/iced/latest/iced/theme/struct.Custom.html Demonstrates how to instantiate a Custom theme using the new constructor or the with_fn method for advanced palette generation. ```Rust use iced::theme::Custom; use iced::theme::palette::Palette; // Basic initialization let theme = Custom::new("my_theme".to_string(), Palette::default()); // Advanced initialization with custom generator let theme_advanced = Custom::with_fn( "advanced_theme", Palette::default(), |palette| { // Logic to generate Extended palette todo!() } ); ``` -------------------------------- ### Implement Zero for Size2D in Rust Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/geom/euclid/struct.Size2D.html?search= This Rust code shows the implementation of the `Zero` trait for `Size2D`. It provides a way to get the zero value for `Size2D`, which is useful for initialization or as a starting point for accumulations. This requires the inner type `T` to implement `Zero`. ```rust impl Zero for Size2D where T: Zero, { fn zero() -> Size2D { // Implementation details for returning the zero value of Size2D } } ``` -------------------------------- ### Application Bootstrapping Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/polygon/struct.PolygonIter.html Utility for initializing application state and tasks. ```APIDOC ## IntoBoot Trait ### Description Converts a type into the initial state and associated tasks for an application. ### Method `into_boot(self) -> (State, Task)` ### Response - **State** (Object) - The initial application state. - **Task** (Task) - The initial command or task to execute. ``` -------------------------------- ### Get Element Offset in Slice (Rust - Nightly) Source: https://docs.rs/iced/latest/iced/widget/canvas/path/lyon_path/geom/arrayvec/struct.ArrayVec.html?search=std%3A%3Avec An experimental nightly-only API that returns the byte offset of an element within a slice. It uses pointer arithmetic and does not compare elements. Returns `None` if the element reference is not aligned to the start of an element. Panics for zero-sized types. ```rust #![feature(substr_range)] let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust #![feature(substr_range)] 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 ``` -------------------------------- ### Into Bootstrapping Source: https://docs.rs/iced/latest/iced/window/raw_window_handle/struct.GbmDisplayHandle.html?search= Converts a type into the initial state and task for an application. ```APIDOC ## fn into_boot(self) -> (State, Task) ### Description Turns some type into the initial state of some `Application`. ### Method POST (Conceptual) ### Endpoint N/A (Method within a trait) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **self** (State) - The type to convert into initial state and task. ### Request Example ```json { "example": "initial_state_object" } ``` ### Response #### Success Response (200) - **(State, Task)** (Tuple) - A tuple containing the initial state and a task. #### Response Example ```json { "example": [ "initial_state", "task_object" ] } ``` ``` -------------------------------- ### Getting a Mutable Reference to Pinned Data - Rust Source: https://docs.rs/iced/latest/iced/advanced/subscription/type.EventStream.html?search=std%3A%3Avec Illustrates the `as_mut` method on `Pin`, which safely provides a mutable reference (`Pin<&mut T>`) to the pinned data. This is crucial for APIs that consume the pinning pointer multiple times, like the `method` example. ```rust pub fn as_mut(&mut self) -> Pin<&mut ::Target> where Ptr: DerefMut, { // ... implementation details ... } // Example usage: impl Type { fn method(self: Pin<&mut Self>) { // do something } fn call_method_twice(mut self: Pin<&mut Self>) { // `method` consumes `self`, so reborrow the `Pin<&mut Self>` via `as_mut`. self.as_mut().method(); self.as_mut().method(); } } ``` -------------------------------- ### Application Bootstrapping Source: https://docs.rs/iced/latest/iced/window/struct.Settings.html Converts a state type into the initial state and task for an application. ```APIDOC ## `into_boot` ### Description Turns some type into the initial state of some `Application`. ### Method `impl IntoBoot for State` ### Endpoint N/A (Method Implementation) ### Parameters - `self` (State): The state to be converted. ### Request Example None ### Response #### Success Response (N/A) - `(State, Task)`: A tuple containing the initial state and the associated task. ### Response Example None ``` -------------------------------- ### Iced Application Example: Counter Source: https://docs.rs/iced/latest/iced/fn.application.html?search=u32+-%3E+bool A complete, runnable example of an Iced application. It demonstrates a simple counter that increments when a button is pressed. This example includes the main function, message enum, update logic, and view. ```rust use iced::widget::{button, column, text, Column}; pub fn main() -> iced::Result { iced::application(u64::default, update, view).run() } #[derive(Debug, Clone)] enum Message { Increment, } fn update(value: &mut u64, message: Message) { match message { Message::Increment => *value += 1, } } fn view(value: &u64) -> Column { column![ text(value), button("+").on_press(Message::Increment), ] ```